├── .eslintrc.js ├── .gitignore ├── LICENSE ├── README.md ├── docs ├── .nojekyll ├── assets │ ├── highlight.css │ ├── icons.css │ ├── icons.png │ ├── icons@2x.png │ ├── main.js │ ├── search.js │ ├── style.css │ ├── widgets.png │ └── widgets@2x.png ├── classes │ ├── Mint.html │ ├── SimpleWallet.html │ └── Wallet.html ├── index.html ├── modules.html └── modules │ ├── account.html │ ├── associatedTokenAccount.html │ ├── mint.html │ ├── sol.html │ ├── token.html │ ├── tokenAccount.html │ └── util.html ├── jest.config.js ├── package.json ├── src ├── index.ts ├── mint.ts ├── tx │ ├── account.ts │ ├── associated-token-account.ts │ ├── mint.ts │ ├── sol.ts │ ├── token-account.ts │ ├── token-instructions.ts │ └── token.ts ├── types.ts ├── util.ts └── wallet │ ├── connected.ts │ ├── index.ts │ ├── internal.ts │ └── simple.ts ├── tests ├── connected-wallet.test.ts └── transactions.test.ts ├── tsconfig.json ├── typedoc.json └── yarn.lock /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es2021: true, 5 | node: true 6 | }, 7 | extends: [ 8 | "eslint:recommended", 9 | "plugin:@typescript-eslint/recommended" 10 | ], 11 | parser: "@typescript-eslint/parser", 12 | parserOptions: { 13 | ecmaVersion: 13, 14 | sourceType: "module" 15 | }, 16 | plugins: [ 17 | "@typescript-eslint" 18 | ], 19 | rules: { 20 | "@typescript-eslint/member-delimiter-style": ["error", { 21 | "multiline": { 22 | "delimiter": "none", 23 | "requireLast": false 24 | }, 25 | }], 26 | "@typescript-eslint/no-use-before-define": ["off"], 27 | "@typescript-eslint/semi": ["error", "never"], 28 | "@typescript-eslint/quotes": ["error", "single", { 29 | allowTemplateLiterals: true 30 | }] 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | node_modules/ 3 | .tool-versions 4 | yarn-error.log 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Easy SPL 2 | [![NPM](https://img.shields.io/npm/v/easy-spl)](https://www.npmjs.com/package/easy-spl) 3 | 4 | _Making tokens on Solana easy!_ 5 | 6 | ## Motivation 7 | SPL tokens are difficult to get started with. They function differently from other common blockchain-based tokens. There is no single stateful contract (as in ERC-20 tokens). Tokens aren't even held in a user's root account! Instead a user creates a new account (that their root account has authority over) for each token they want to interact with. Each token contract stores the number of decimals for a mint, but tokens are sent around without reference to the number of decimals. So to send 1 token of a mint with 4 decimals, you need to send 1000 tokens. 8 | 9 | All of this is prone to developer error and diffiult to keep straight when getting started! 10 | 11 | We wanted to develop a library that papers over all of these difficulties. Using Easy SPL, you don't have to think about associated token accounts or decimals! We also include some stateful classes for repeated interactions with a mint or given user wallet. 12 | 13 | ## Use 14 | See the [Documentation](https://solstar-tech.github.io/easy-spl/) for full details 15 | ```ts 16 | import * as spl from 'easy-spl' 17 | const connection = new web3.Connection('https://api.devnet.solana.com', 'confirmed') 18 | 19 | // create accounts and wallets 20 | const keypairAlice = web3.Keypair.generate() 21 | const alice = spl.Wallet.fromKeypair(connection, keypairAlice) 22 | const keypairBob = web3.Keypair.generate() 23 | const bob = spl.Wallet.fromKeypair(connection, keypairBob) 24 | 25 | // create a new mint controlled by alice with 6 decimals 26 | const mint = await spl.Mint.create(connection, 6, alice.publicKey, alice) 27 | 28 | // mint 10 tokens to bob 29 | await mint.mintTo(bob.publicKey, alice, 10) 30 | 31 | // send 5 tokens to alice 32 | await bob.transferToken(mint.key, alice.publicKey, 5) 33 | 34 | // check bob's balance 35 | const balance = await mint.getBalance(bob.publicKey) 36 | // OR 37 | const balance = await bob.getBalance(mint.key) 38 | 39 | // get mint decimals 40 | const decimals = await mint.getDecimals() 41 | 42 | // get mint supply (total tokens in circulation 43 | const supply = await mint.getSupply() 44 | ``` 45 | 46 | ## Connected wallets 47 | Connected wallets can also be instantiated from any wallet that uses the common Solana wallet interface. For instance, from the solana labs browser [wallet-adapter](https://github.com/solana-labs/wallet-adapter/) package. Or signers in [anchor](https://project-serum.github.io/anchor/getting-started/introduction.html) 48 | ```ts 49 | import * as spl from 'easy-spl' 50 | import { useConnection, useWallet } from "@solana/wallet-adapter-react" 51 | 52 | export default function OurComponent () { 53 | const wallet = useWallet() 54 | const { connection } = useConnection() 55 | 56 | const user = spl.Wallet.fromWallet(connection, wallet) 57 | 58 | ... 59 | } 60 | 61 | ``` 62 | 63 | ## Txs & Instructions 64 | Sometimes you need to just format the instructions for something, without sending. In that case you can use the txs & instructions api. 65 | 66 | _Note: any function that has the word "raw" in it, refers to addresses in terms of **associated token accounts** and amounts in terms of **integer amounts** (multiplied out by the token decimals)._ 67 | 68 | Each method includes 4-5 variations: 69 | - `instructions`: get just the instruction for the operation 70 | - `rawInstructions`: get just the instruction, but parameters are given as **associated token accounts** and **integer amounts** 71 | - `tx`: get the tx for the operation, with `recentBlockhash` & `feePayer` filled out 72 | - `signed`: get the formatted tx for the operation & sign with the given wallet 73 | - `send`: get the signed tx for the operation, send to the network, and wait for confirmation 74 | 75 | See the [Documentation](https://solstar-tech.github.io/easy-spl/) for more details. 76 | 77 | 78 | ## Development 79 | ```bash 80 | # install dependencies 81 | yarn 82 | 83 | # build 84 | yarn build 85 | 86 | # compiler with reloading 87 | yarn dev 88 | 89 | # test 90 | yarn test 91 | 92 | # test with reloading 93 | yarn test:watch 94 | 95 | # docs 96 | yarn docs 97 | 98 | # lint 99 | yarn lint 100 | ``` 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /docs/.nojekyll: -------------------------------------------------------------------------------- 1 | TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. -------------------------------------------------------------------------------- /docs/assets/highlight.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --light-hl-0: #AF00DB; 3 | --dark-hl-0: #C586C0; 4 | --light-hl-1: #000000; 5 | --dark-hl-1: #D4D4D4; 6 | --light-hl-2: #0000FF; 7 | --dark-hl-2: #569CD6; 8 | --light-hl-3: #001080; 9 | --dark-hl-3: #9CDCFE; 10 | --light-hl-4: #A31515; 11 | --dark-hl-4: #CE9178; 12 | --light-hl-5: #0070C1; 13 | --dark-hl-5: #4FC1FF; 14 | --light-hl-6: #795E26; 15 | --dark-hl-6: #DCDCAA; 16 | --light-hl-7: #008000; 17 | --dark-hl-7: #6A9955; 18 | --light-hl-8: #098658; 19 | --dark-hl-8: #B5CEA8; 20 | --light-code-background: #FFFFFF; 21 | --dark-code-background: #1E1E1E; 22 | } 23 | 24 | @media (prefers-color-scheme: light) { :root { 25 | --hl-0: var(--light-hl-0); 26 | --hl-1: var(--light-hl-1); 27 | --hl-2: var(--light-hl-2); 28 | --hl-3: var(--light-hl-3); 29 | --hl-4: var(--light-hl-4); 30 | --hl-5: var(--light-hl-5); 31 | --hl-6: var(--light-hl-6); 32 | --hl-7: var(--light-hl-7); 33 | --hl-8: var(--light-hl-8); 34 | --code-background: var(--light-code-background); 35 | } } 36 | 37 | @media (prefers-color-scheme: dark) { :root { 38 | --hl-0: var(--dark-hl-0); 39 | --hl-1: var(--dark-hl-1); 40 | --hl-2: var(--dark-hl-2); 41 | --hl-3: var(--dark-hl-3); 42 | --hl-4: var(--dark-hl-4); 43 | --hl-5: var(--dark-hl-5); 44 | --hl-6: var(--dark-hl-6); 45 | --hl-7: var(--dark-hl-7); 46 | --hl-8: var(--dark-hl-8); 47 | --code-background: var(--dark-code-background); 48 | } } 49 | 50 | body.light { 51 | --hl-0: var(--light-hl-0); 52 | --hl-1: var(--light-hl-1); 53 | --hl-2: var(--light-hl-2); 54 | --hl-3: var(--light-hl-3); 55 | --hl-4: var(--light-hl-4); 56 | --hl-5: var(--light-hl-5); 57 | --hl-6: var(--light-hl-6); 58 | --hl-7: var(--light-hl-7); 59 | --hl-8: var(--light-hl-8); 60 | --code-background: var(--light-code-background); 61 | } 62 | 63 | body.dark { 64 | --hl-0: var(--dark-hl-0); 65 | --hl-1: var(--dark-hl-1); 66 | --hl-2: var(--dark-hl-2); 67 | --hl-3: var(--dark-hl-3); 68 | --hl-4: var(--dark-hl-4); 69 | --hl-5: var(--dark-hl-5); 70 | --hl-6: var(--dark-hl-6); 71 | --hl-7: var(--dark-hl-7); 72 | --hl-8: var(--dark-hl-8); 73 | --code-background: var(--dark-code-background); 74 | } 75 | 76 | .hl-0 { color: var(--hl-0); } 77 | .hl-1 { color: var(--hl-1); } 78 | .hl-2 { color: var(--hl-2); } 79 | .hl-3 { color: var(--hl-3); } 80 | .hl-4 { color: var(--hl-4); } 81 | .hl-5 { color: var(--hl-5); } 82 | .hl-6 { color: var(--hl-6); } 83 | .hl-7 { color: var(--hl-7); } 84 | .hl-8 { color: var(--hl-8); } 85 | pre, code { background: var(--code-background); } 86 | -------------------------------------------------------------------------------- /docs/assets/icons.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/solstar-tech/easy-spl/a33a5d98a22224ed5fb30cf3480b44505538e273/docs/assets/icons.png -------------------------------------------------------------------------------- /docs/assets/icons@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/solstar-tech/easy-spl/a33a5d98a22224ed5fb30cf3480b44505538e273/docs/assets/icons@2x.png -------------------------------------------------------------------------------- /docs/assets/widgets.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/solstar-tech/easy-spl/a33a5d98a22224ed5fb30cf3480b44505538e273/docs/assets/widgets.png -------------------------------------------------------------------------------- /docs/assets/widgets@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/solstar-tech/easy-spl/a33a5d98a22224ed5fb30cf3480b44505538e273/docs/assets/widgets@2x.png -------------------------------------------------------------------------------- /docs/classes/Mint.html: -------------------------------------------------------------------------------- 1 | Mint | Easy SPL
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Mint

Hierarchy

  • Mint

Index

Constructors

constructor

  • new Mint(conn: Connection, key: PublicKey): Mint
  • Parameters

    • conn: Connection
    • key: PublicKey

    Returns Mint

Properties

conn

conn: Connection

key

key: PublicKey

Methods

getBalance

  • getBalance(user: PublicKey): Promise<number>
  • Parameters

    • user: PublicKey

    Returns Promise<number>

getDecimals

  • getDecimals(): Promise<number>

getInfo

  • getInfo(): Promise<MintInfo>

getSupply

  • getSupply(): Promise<number>

mintTo

  • mintTo(user: PublicKey, sender: WalletI, amount: number): Promise<string>
  • Parameters

    • user: PublicKey
    • sender: WalletI
    • amount: number

    Returns Promise<string>

Static create

  • create(conn: Connection, decimals: number, owner: PublicKey, sender: WalletI): Promise<Mint>
  • Parameters

    • conn: Connection
    • decimals: number
    • owner: PublicKey
    • sender: WalletI

    Returns Promise<Mint>

Static get

  • get(conn: Connection, key: PublicKey): Mint
  • Parameters

    • conn: Connection
    • key: PublicKey

    Returns Mint

Generated using TypeDoc

-------------------------------------------------------------------------------- /docs/classes/SimpleWallet.html: -------------------------------------------------------------------------------- 1 | SimpleWallet | Easy SPL
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class SimpleWallet

Hierarchy

  • InternalWallet
    • SimpleWallet

Index

Constructors

constructor

Properties

publicKey

publicKey: PublicKey

Methods

connect

  • connect(conn: Connection): Wallet

signAllTransactions

  • signAllTransactions(txs: Transaction[]): Promise<Transaction[]>
  • Parameters

    • txs: Transaction[]

    Returns Promise<Transaction[]>

signTransaction

  • signTransaction(tx: Transaction): Promise<Transaction>
  • Parameters

    • tx: Transaction

    Returns Promise<Transaction>

Static fromKeypair

Static fromSecretKey

Generated using TypeDoc

-------------------------------------------------------------------------------- /docs/classes/Wallet.html: -------------------------------------------------------------------------------- 1 | Wallet | Easy SPL
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Wallet

Hierarchy

  • Wallet

Implements

  • WalletI

Index

Constructors

constructor

  • new Wallet(conn: Connection, signer: WalletI): Wallet

Properties

conn

conn: Connection

publicKey

publicKey: PublicKey

signer

signer: WalletI

Methods

createAssociatedTokenAccount

  • createAssociatedTokenAccount(mintKey: PublicKey): Promise<PublicKey>

existsAssociatedTokenAccount

  • existsAssociatedTokenAccount(mintKey: PublicKey): Promise<boolean>

getAssociatedTokenAccount

  • getAssociatedTokenAccount(mintKey: PublicKey): Promise<PublicKey>

getBalance

  • getBalance(mintKey: PublicKey): Promise<number>

getSolBalance

  • getSolBalance(): Promise<number>

signAllTransactions

  • signAllTransactions(txs: Transaction[]): Promise<Transaction[]>
  • Parameters

    • txs: Transaction[]

    Returns Promise<Transaction[]>

signTransaction

  • signTransaction(tx: Transaction): Promise<Transaction>
  • Parameters

    • tx: Transaction

    Returns Promise<Transaction>

transferSol

  • transferSol(to: PublicKey, amount: number): Promise<string>

transferToken

  • transferToken(mintKey: PublicKey, to: PublicKey, amount: number): Promise<string>
  • Parameters

    • mintKey: PublicKey
    • to: PublicKey
    • amount: number

    Returns Promise<string>

Static fromKeypair

  • fromKeypair(conn: Connection, keypair: Keypair): Wallet

Static fromSecretKey

  • fromSecretKey(conn: Connection, key: Uint8Array): Wallet

Static fromWallet

  • fromWallet(conn: Connection, signer: WalletI): Wallet

Generated using TypeDoc

-------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | Easy SPL
Options
All
  • Public
  • Public/Protected
  • All
Menu

Easy SPL

2 | 3 |

Easy SPL

4 |
5 |

NPM

6 |

Making tokens on Solana easy!

7 | 8 | 9 |

Motivation

10 |
11 |

SPL tokens are difficult to get started with. They function differently from other common blockchain-based tokens. There is no single stateful contract (as in ERC-20 tokens). Tokens aren't even held in a user's root account! Instead a user creates a new account (that their root account has authority over) for each token they want to interact with. Each token contract stores the number of decimals for a mint, but tokens are sent around without reference to the number of decimals. So to send 1 token of a mint with 4 decimals, you need to send 1000 tokens.

12 |

All of this is prone to developer error and diffiult to keep straight when getting started!

13 |

We wanted to develop a library that papers over all of these difficulties. Using Easy SPL, you don't have to think about associated token accounts or decimals! We also include some stateful classes for repeated interactions with a mint or given user wallet.

14 | 15 | 16 |

Use

17 |
18 |

See the Documentation for full details

19 |
import * as spl from 'easy-spl'
const connection = new web3.Connection('https://api.devnet.solana.com', 'confirmed')

// create accounts and wallets
const keypairAlice = web3.Keypair.generate()
const alice = spl.Wallet.fromKeypair(connection, keypairAlice)
const keypairBob = web3.Keypair.generate()
const bob = spl.Wallet.fromKeypair(connection, keypairBob)

// create a new mint controlled by alice with 6 decimals
const mint = await spl.Mint.create(connection, 6, alice.publicKey, alice)

// mint 10 tokens to bob
await mint.mintTo(bob.publicKey, alice, 10)

// send 5 tokens to alice
await bob.transferToken(mint.key, alice.publicKey, 5)

// check bob's balance
const balance = await mint.getBalance(bob.publicKey)
// OR
const balance = await bob.getBalance(mint.key)

// get mint decimals
const decimals = await mint.getDecimals()

// get mint supply (total tokens in circulation
const supply = await mint.getSupply() 20 |
21 | 22 | 23 |

Connected wallets

24 |
25 |

Connected wallets can also be instantiated from any wallet that uses the common Solana wallet interface. For instance, from the solana labs browser wallet-adapter package. Or signers in anchor

26 |
import * as spl from 'easy-spl'
import { useConnection, useWallet } from "@solana/wallet-adapter-react"

export default function OurComponent () {
const wallet = useWallet()
const { connection } = useConnection()

const user = spl.Wallet.fromWallet(connection, wallet)

...
}
27 |
28 | 29 | 30 |

Txs & Instructions

31 |
32 |

Sometimes you need to just format the instructions for something, without sending. In that case you can use the txs & instructions api.

33 |

Note: any function that has the word "raw" in it, refers to addresses in terms of associated token accounts and amounts in terms of integer amounts (multiplied out by the token decimals).

34 |

Each method includes 4-5 variations:

35 |
    36 |
  • instructions: get just the instruction for the operation
  • 37 |
  • rawInstructions: get just the instruction, but parameters are given as associated token accounts and integer amounts
  • 38 |
  • tx: get the tx for the operation, with recentBlockhash & feePayer filled out
  • 39 |
  • signed: get the formatted tx for the operation & sign with the given wallet
  • 40 |
  • send: get the signed tx for the operation, send to the network, and wait for confirmation
  • 41 |
42 |

See the Documentation for more details.

43 | 44 | 45 |

Development

46 |
47 |
# install dependencies
yarn

# build
yarn build

# compiler with reloading
yarn dev

# test
yarn test

# test with reloading
yarn test:watch

# docs
yarn docs

# lint
yarn lint 48 |
49 |

Generated using TypeDoc

-------------------------------------------------------------------------------- /docs/modules.html: -------------------------------------------------------------------------------- 1 | Easy SPL
Options
All
  • Public
  • Public/Protected
  • All
Menu

Easy SPL

Generated using TypeDoc

-------------------------------------------------------------------------------- /docs/modules/account.html: -------------------------------------------------------------------------------- 1 | account | Easy SPL
Options
All
  • Public
  • Public/Protected
  • All
Menu

Namespace account

Index

Functions

Functions

Const exists

  • exists(conn: Connection, account: PublicKey): Promise<boolean>
  • Parameters

    • conn: Connection
    • account: PublicKey

    Returns Promise<boolean>

Generated using TypeDoc

-------------------------------------------------------------------------------- /docs/modules/sol.html: -------------------------------------------------------------------------------- 1 | sol | Easy SPL
Options
All
  • Public
  • Public/Protected
  • All
Menu

Namespace sol

Index

Variables

get

get: { balance: (conn: Connection, user: PublicKey) => Promise<number> } = ...

Type declaration

  • balance: (conn: Connection, user: PublicKey) => Promise<number>
      • (conn: Connection, user: PublicKey): Promise<number>
      • Parameters

        • conn: Connection
        • user: PublicKey

        Returns Promise<number>

transfer

transfer: { instructions: (from: PublicKey, to: PublicKey, amount: number) => TransactionInstruction[]; rawInstructions: (from: PublicKey, to: PublicKey, amount: number) => TransactionInstruction[]; send: (conn: Connection, to: PublicKey, amount: number, wallet: WalletI) => Promise<string>; signed: (conn: Connection, to: PublicKey, amount: number, wallet: WalletI) => Promise<Transaction>; tx: (conn: Connection, from: PublicKey, to: PublicKey, amount: number) => Promise<Transaction> } = ...

Type declaration

  • instructions: (from: PublicKey, to: PublicKey, amount: number) => TransactionInstruction[]
      • (from: PublicKey, to: PublicKey, amount: number): TransactionInstruction[]
      • Parameters

        • from: PublicKey
        • to: PublicKey
        • amount: number

        Returns TransactionInstruction[]

  • rawInstructions: (from: PublicKey, to: PublicKey, amount: number) => TransactionInstruction[]
      • (from: PublicKey, to: PublicKey, amount: number): TransactionInstruction[]
      • Parameters

        • from: PublicKey
        • to: PublicKey
        • amount: number

        Returns TransactionInstruction[]

  • send: (conn: Connection, to: PublicKey, amount: number, wallet: WalletI) => Promise<string>
      • (conn: Connection, to: PublicKey, amount: number, wallet: WalletI): Promise<string>
      • Parameters

        • conn: Connection
        • to: PublicKey
        • amount: number
        • wallet: WalletI

        Returns Promise<string>

  • signed: (conn: Connection, to: PublicKey, amount: number, wallet: WalletI) => Promise<Transaction>
      • (conn: Connection, to: PublicKey, amount: number, wallet: WalletI): Promise<Transaction>
      • Parameters

        • conn: Connection
        • to: PublicKey
        • amount: number
        • wallet: WalletI

        Returns Promise<Transaction>

  • tx: (conn: Connection, from: PublicKey, to: PublicKey, amount: number) => Promise<Transaction>
      • (conn: Connection, from: PublicKey, to: PublicKey, amount: number): Promise<Transaction>
      • Parameters

        • conn: Connection
        • from: PublicKey
        • to: PublicKey
        • amount: number

        Returns Promise<Transaction>

Functions

Const getBalance

  • getBalance(conn: Connection, user: PublicKey): Promise<number>
  • Parameters

    • conn: Connection
    • user: PublicKey

    Returns Promise<number>

Const transferInstructions

  • transferInstructions(from: PublicKey, to: PublicKey, amount: number): TransactionInstruction[]
  • Parameters

    • from: PublicKey
    • to: PublicKey
    • amount: number

    Returns TransactionInstruction[]

Const transferRawInstructions

  • transferRawInstructions(from: PublicKey, to: PublicKey, amount: number): TransactionInstruction[]
  • Parameters

    • from: PublicKey
    • to: PublicKey
    • amount: number

    Returns TransactionInstruction[]

Const transferSend

  • transferSend(conn: Connection, to: PublicKey, amount: number, wallet: WalletI): Promise<string>
  • Parameters

    • conn: Connection
    • to: PublicKey
    • amount: number
    • wallet: WalletI

    Returns Promise<string>

Const transferSigned

  • transferSigned(conn: Connection, to: PublicKey, amount: number, wallet: WalletI): Promise<Transaction>
  • Parameters

    • conn: Connection
    • to: PublicKey
    • amount: number
    • wallet: WalletI

    Returns Promise<Transaction>

Const transferTx

  • transferTx(conn: Connection, from: PublicKey, to: PublicKey, amount: number): Promise<Transaction>
  • Parameters

    • conn: Connection
    • from: PublicKey
    • to: PublicKey
    • amount: number

    Returns Promise<Transaction>

Generated using TypeDoc

-------------------------------------------------------------------------------- /docs/modules/tokenAccount.html: -------------------------------------------------------------------------------- 1 | tokenAccount | Easy SPL
Options
All
  • Public
  • Public/Protected
  • All
Menu

Namespace tokenAccount

Index

Variables

create

create: { instructions: (conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, sender: PublicKey) => Promise<TransactionInstruction[]>; send: (conn: Connection, mint: PublicKey, owner: PublicKey, wallet: WalletI) => Promise<PublicKey>; signed: (conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, wallet: WalletI) => Promise<Transaction>; tx: (conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, sender: PublicKey) => Promise<Transaction> } = ...

Type declaration

  • instructions: (conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, sender: PublicKey) => Promise<TransactionInstruction[]>
      • (conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, sender: PublicKey): Promise<TransactionInstruction[]>
      • Parameters

        • conn: Connection
        • mint: PublicKey
        • address: PublicKey
        • owner: PublicKey
        • sender: PublicKey

        Returns Promise<TransactionInstruction[]>

  • send: (conn: Connection, mint: PublicKey, owner: PublicKey, wallet: WalletI) => Promise<PublicKey>
      • (conn: Connection, mint: PublicKey, owner: PublicKey, wallet: WalletI): Promise<PublicKey>
      • Parameters

        • conn: Connection
        • mint: PublicKey
        • owner: PublicKey
        • wallet: WalletI

        Returns Promise<PublicKey>

  • signed: (conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, wallet: WalletI) => Promise<Transaction>
      • (conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, wallet: WalletI): Promise<Transaction>
      • Parameters

        • conn: Connection
        • mint: PublicKey
        • address: PublicKey
        • owner: PublicKey
        • wallet: WalletI

        Returns Promise<Transaction>

  • tx: (conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, sender: PublicKey) => Promise<Transaction>
      • (conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, sender: PublicKey): Promise<Transaction>
      • Parameters

        • conn: Connection
        • mint: PublicKey
        • address: PublicKey
        • owner: PublicKey
        • sender: PublicKey

        Returns Promise<Transaction>

Functions

Const createTokenAccountInstructions

  • createTokenAccountInstructions(conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, sender: PublicKey): Promise<TransactionInstruction[]>
  • Parameters

    • conn: Connection
    • mint: PublicKey
    • address: PublicKey
    • owner: PublicKey
    • sender: PublicKey

    Returns Promise<TransactionInstruction[]>

Const createTokenAccountSend

  • createTokenAccountSend(conn: Connection, mint: PublicKey, owner: PublicKey, wallet: WalletI): Promise<PublicKey>
  • Parameters

    • conn: Connection
    • mint: PublicKey
    • owner: PublicKey
    • wallet: WalletI

    Returns Promise<PublicKey>

Const createTokenAccountSigned

  • createTokenAccountSigned(conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, wallet: WalletI): Promise<Transaction>
  • Parameters

    • conn: Connection
    • mint: PublicKey
    • address: PublicKey
    • owner: PublicKey
    • wallet: WalletI

    Returns Promise<Transaction>

Const createTokenAccountTx

  • createTokenAccountTx(conn: Connection, mint: PublicKey, address: PublicKey, owner: PublicKey, sender: PublicKey): Promise<Transaction>
  • Parameters

    • conn: Connection
    • mint: PublicKey
    • address: PublicKey
    • owner: PublicKey
    • sender: PublicKey

    Returns Promise<Transaction>

Generated using TypeDoc

-------------------------------------------------------------------------------- /docs/modules/util.html: -------------------------------------------------------------------------------- 1 | util | Easy SPL
Options
All
  • Public
  • Public/Protected
  • All
Menu

Namespace util

Index

Functions

Const makeDecimal

  • makeDecimal(bn: BN, decimals: number): number
  • Parameters

    • bn: BN
    • decimals: number

    Returns number

Const makeInteger

  • makeInteger(num: number, decimals: number): BN
  • Parameters

    • num: number
    • decimals: number

    Returns BN

Const partialSignAndSend

  • partialSignAndSend(conn: Connection, tx: Transaction, signers?: Keypair[]): Promise<string>
  • Parameters

    • conn: Connection
    • tx: Transaction
    • signers: Keypair[] = []

    Returns Promise<string>

Const sendAndConfirm

  • sendAndConfirm(conn: Connection, tx: Transaction): Promise<string>
  • Parameters

    • conn: Connection
    • tx: Transaction

    Returns Promise<string>

Const wrapInstructions

  • wrapInstructions(conn: Connection, instructions: TransactionInstruction[], signer: PublicKey): Promise<Transaction>
  • Parameters

    • conn: Connection
    • instructions: TransactionInstruction[]
    • signer: PublicKey

    Returns Promise<Transaction>

Generated using TypeDoc

-------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { // eslint-disable-line 2 | transform: { 3 | ".(ts|tsx)": "ts-jest" 4 | }, 5 | testEnvironment: "node", 6 | testRegex: "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", 7 | moduleFileExtensions: [ 8 | "ts", 9 | "tsx", 10 | "js" 11 | ], 12 | } 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "easy-spl", 3 | "version": "0.5.0", 4 | "main": "dist/index.js", 5 | "browser": "dist/index.js", 6 | "typings": "dist/index.d.ts", 7 | "license": "Apache-2.0", 8 | "scripts": { 9 | "docs": "typedoc", 10 | "prebuild": "rimraf dist", 11 | "build": "tsc", 12 | "dev": "tsc -w", 13 | "test": "jest", 14 | "test:watch": "jest --watch", 15 | "lint": "eslint src/**/*" 16 | }, 17 | "dependencies": { 18 | "@solana/spl-token": "^0.1.8", 19 | "@solana/web3.js": "^1.29.2", 20 | "bn.js": "^5.2.0", 21 | "buffer-layout": "^1.2.2" 22 | }, 23 | "devDependencies": { 24 | "@types/jest": "^27.0.2", 25 | "@typescript-eslint/eslint-plugin": "^5.0.0", 26 | "@typescript-eslint/parser": "^5.0.0", 27 | "eslint": "^8.0.0", 28 | "jest": "^27.2.5", 29 | "rimraf": "^3.0.2", 30 | "ts-jest": "^27.0.5", 31 | "typedoc": "^0.22.5", 32 | "typescript": "^4.4.3" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * as mint from './tx/mint' 2 | export * as sol from './tx/sol' 3 | export * as token from './tx/token' 4 | export * as account from './tx/account' 5 | export * as tokenAccount from './tx/token-account' 6 | export * as associatedTokenAccount from './tx/associated-token-account' 7 | export * as util from './util' 8 | export * from './wallet' 9 | export * from './mint' 10 | export * from './types' 11 | -------------------------------------------------------------------------------- /src/mint.ts: -------------------------------------------------------------------------------- 1 | import { MintInfo } from '@solana/spl-token' 2 | 3 | import * as web3 from '@solana/web3.js' 4 | import * as mint from './tx/mint' 5 | import { WalletI } from './types' 6 | export class Mint { 7 | 8 | conn: web3.Connection 9 | key: web3.PublicKey 10 | 11 | constructor(conn: web3.Connection, key: web3.PublicKey) { 12 | this.conn = conn 13 | this.key = key 14 | } 15 | 16 | static async create(conn: web3.Connection, decimals: number, owner: web3.PublicKey, sender: WalletI): Promise { 17 | const key = await mint.create.send(conn, decimals, owner, sender) 18 | return new Mint(conn, key) 19 | } 20 | 21 | static get(conn: web3.Connection, key: web3.PublicKey): Mint { 22 | return new Mint(conn, key) 23 | } 24 | 25 | async mintTo(user: web3.PublicKey, sender: WalletI, amount: number): Promise { 26 | return mint.mintTo.send(this.conn, this.key, user, sender, amount) 27 | } 28 | 29 | async getInfo(): Promise { 30 | return mint.get.info(this.conn, this.key) 31 | } 32 | 33 | async getDecimals(): Promise { 34 | return mint.get.decimals(this.conn, this.key) 35 | } 36 | 37 | async getSupply(): Promise { 38 | return mint.get.supply(this.conn, this.key) 39 | } 40 | 41 | async getBalance(user: web3.PublicKey): Promise { 42 | return mint.get.balance(this.conn, this.key, user) 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/tx/account.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | 3 | export const exists = async ( 4 | conn: web3.Connection, 5 | account: web3.PublicKey, 6 | ): Promise => { 7 | const info = await conn.getParsedAccountInfo(account) 8 | return info.value !== null 9 | } 10 | 11 | -------------------------------------------------------------------------------- /src/tx/associated-token-account.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | import { ASSOCIATED_TOKEN_PROGRAM_ID, Token, TOKEN_PROGRAM_ID } from '@solana/spl-token' 3 | import * as util from '../util' 4 | import * as account from './account' 5 | import { WalletI } from '../types' 6 | 7 | export const createAssociatedTokenAccountRawInstructions = ( 8 | mint: web3.PublicKey, 9 | address: web3.PublicKey, 10 | owner: web3.PublicKey, 11 | sender: web3.PublicKey, 12 | ): web3.TransactionInstruction[] => { 13 | return [Token.createAssociatedTokenAccountInstruction( 14 | ASSOCIATED_TOKEN_PROGRAM_ID, 15 | TOKEN_PROGRAM_ID, 16 | mint, 17 | address, 18 | owner, 19 | sender 20 | )] 21 | } 22 | 23 | export const createAssociatedTokenAccountInstructions = async ( 24 | mint: web3.PublicKey, 25 | owner: web3.PublicKey, 26 | sender: web3.PublicKey, 27 | ): Promise => { 28 | const toMake = await getAssociatedTokenAddress(mint, owner) 29 | return createAssociatedTokenAccountRawInstructions(mint, toMake, owner, sender) 30 | } 31 | 32 | export const maybeCreateAssociatedTokenAccountInstructions = async ( 33 | conn: web3.Connection, 34 | mint: web3.PublicKey, 35 | owner: web3.PublicKey, 36 | sender: web3.PublicKey, 37 | ): Promise => { 38 | const doesExist = await exists(conn, mint, owner) 39 | if (doesExist) return [] 40 | return createAssociatedTokenAccountInstructions(mint, owner, sender) 41 | } 42 | 43 | export const createAssociatedTokenAccountTx = async ( 44 | conn: web3.Connection, 45 | mint: web3.PublicKey, 46 | owner: web3.PublicKey, 47 | sender: web3.PublicKey, 48 | ): Promise => { 49 | const instructions = await createAssociatedTokenAccountInstructions(mint, owner, sender) 50 | return util.wrapInstructions(conn, instructions, sender) 51 | } 52 | 53 | export const createAssociatedTokenAccountSigned = async ( 54 | conn: web3.Connection, 55 | mint: web3.PublicKey, 56 | owner: web3.PublicKey, 57 | wallet: WalletI, 58 | ): Promise => { 59 | const tx = await createAssociatedTokenAccountTx(conn, mint, owner, wallet.publicKey) 60 | return await wallet.signTransaction(tx) 61 | } 62 | 63 | export const createAssociatedTokenAccountSend = async ( 64 | conn: web3.Connection, 65 | mint: web3.PublicKey, 66 | owner: web3.PublicKey, 67 | wallet: WalletI, 68 | ): Promise => { 69 | const address = await getAssociatedTokenAddress(mint, owner) 70 | if (await account.exists(conn, address)) { 71 | return address 72 | } 73 | const tx = await createAssociatedTokenAccountSigned(conn, mint, owner, wallet) 74 | await util.sendAndConfirm(conn, tx) 75 | return address 76 | } 77 | 78 | export const getAssociatedTokenAddress = async ( 79 | mint: web3.PublicKey, 80 | user: web3.PublicKey 81 | ): Promise => { 82 | return Token.getAssociatedTokenAddress(ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID, mint, user) 83 | } 84 | 85 | export const exists = async( 86 | conn: web3.Connection, 87 | mint: web3.PublicKey, 88 | user: web3.PublicKey 89 | ): Promise => { 90 | const address = await getAssociatedTokenAddress(mint, user) 91 | return account.exists(conn, address) 92 | } 93 | 94 | 95 | export const get = { 96 | address: getAssociatedTokenAddress, 97 | } 98 | 99 | export const create = { 100 | rawInstructions: createAssociatedTokenAccountRawInstructions, 101 | instructions: createAssociatedTokenAccountInstructions, 102 | maybeInstructions: maybeCreateAssociatedTokenAccountInstructions, 103 | tx: createAssociatedTokenAccountTx, 104 | signed: createAssociatedTokenAccountSigned, 105 | send: createAssociatedTokenAccountSend 106 | } 107 | -------------------------------------------------------------------------------- /src/tx/mint.ts: -------------------------------------------------------------------------------- 1 | import BN from 'bn.js' 2 | import * as web3 from '@solana/web3.js' 3 | import * as TokenInstructions from './token-instructions' 4 | import { TOKEN_PROGRAM_ID, Token, MintInfo } from '@solana/spl-token' 5 | import * as util from '../util' 6 | import { WalletI } from '../types' 7 | import * as associatedTokenAccount from './associated-token-account' 8 | 9 | export const createMintInstructions = async ( 10 | conn: web3.Connection, 11 | decimals: number, 12 | mint: web3.PublicKey, 13 | authority: web3.PublicKey, 14 | signer: web3.PublicKey, 15 | ): Promise => { 16 | return [ 17 | web3.SystemProgram.createAccount({ 18 | fromPubkey: signer, 19 | newAccountPubkey: mint, 20 | space: 82, 21 | lamports: await conn.getMinimumBalanceForRentExemption(82), 22 | programId: TOKEN_PROGRAM_ID, 23 | }), 24 | TokenInstructions.initializeMint({ 25 | mint: mint, 26 | decimals: decimals, 27 | mintAuthority: authority, 28 | }), 29 | ] 30 | } 31 | 32 | export const createMintTx = async ( 33 | conn: web3.Connection, 34 | decimals: number, 35 | mint: web3.PublicKey, 36 | authority: web3.PublicKey, 37 | signer: web3.PublicKey 38 | ): Promise => { 39 | const instructions = await createMintInstructions(conn, decimals, mint, authority, signer) 40 | return util.wrapInstructions(conn, instructions, signer) 41 | } 42 | 43 | export const createMintSigned = async ( 44 | conn: web3.Connection, 45 | decimals: number, 46 | mint: web3.PublicKey, 47 | authority: web3.PublicKey, 48 | wallet: WalletI 49 | ): Promise => { 50 | const tx = await createMintTx(conn, decimals, mint, authority, wallet.publicKey) 51 | return await wallet.signTransaction(tx) 52 | } 53 | 54 | export const createMintSend = async ( 55 | conn: web3.Connection, 56 | decimals: number, 57 | authority: web3.PublicKey, 58 | wallet: WalletI 59 | ): Promise => { 60 | const mint = web3.Keypair.generate() 61 | const tx = await createMintSigned(conn, decimals, mint.publicKey, authority, wallet) 62 | await util.partialSignAndSend(conn, tx, [mint]) 63 | return mint.publicKey 64 | } 65 | 66 | export const mintToRawInstructions = ( 67 | mint: web3.PublicKey, 68 | dest: web3.PublicKey, 69 | authority: web3.PublicKey, 70 | amount: number 71 | ): web3.TransactionInstruction[] => { 72 | return [Token.createMintToInstruction( 73 | TOKEN_PROGRAM_ID, 74 | mint, 75 | dest, 76 | authority, 77 | [], 78 | amount 79 | )] 80 | } 81 | 82 | export const mintToInstructions = async ( 83 | conn: web3.Connection, 84 | mint: web3.PublicKey, 85 | dest: web3.PublicKey, 86 | authority: web3.PublicKey, 87 | amount: number 88 | ): Promise => { 89 | const associated = await associatedTokenAccount.get.address(mint, dest) 90 | const mintDecimals = await getMintDecimals(conn, mint) 91 | const amountRaw = util.makeInteger(amount, mintDecimals).toNumber() 92 | const instructions = [ 93 | ...await associatedTokenAccount.create.maybeInstructions(conn, mint, dest, authority), 94 | ...mintToRawInstructions(mint, associated, authority, amountRaw) 95 | ] 96 | return instructions 97 | } 98 | 99 | export const mintToTx = async ( 100 | conn: web3.Connection, 101 | mint: web3.PublicKey, 102 | dest: web3.PublicKey, 103 | authority: web3.PublicKey, 104 | amount: number 105 | ): Promise => { 106 | const instructions = await mintToInstructions(conn, mint, dest, authority, amount) 107 | return util.wrapInstructions(conn, instructions, authority) 108 | } 109 | 110 | export const mintToSigned = async ( 111 | conn: web3.Connection, 112 | mint: web3.PublicKey, 113 | dest: web3.PublicKey, 114 | authority: WalletI, 115 | amount: number 116 | ): Promise => { 117 | const tx = await mintToTx(conn, mint, dest, authority.publicKey, amount) 118 | return await authority.signTransaction(tx) 119 | } 120 | 121 | export const mintToSend = async ( 122 | conn: web3.Connection, 123 | mint: web3.PublicKey, 124 | dest: web3.PublicKey, 125 | authority: WalletI, 126 | amount: number 127 | ): Promise => { 128 | const tx = await mintToSigned(conn, mint, dest, authority, amount) 129 | return util.sendAndConfirm(conn, tx) 130 | } 131 | 132 | export const getMintInfo = async ( 133 | conn: web3.Connection, 134 | mint: web3.PublicKey 135 | ): Promise => { 136 | const token = new Token(conn, mint, TOKEN_PROGRAM_ID, {} as any) 137 | return token.getMintInfo() 138 | } 139 | 140 | export const getMintDecimals = async ( 141 | conn: web3.Connection, 142 | mint: web3.PublicKey 143 | ): Promise => { 144 | const info = await getMintInfo(conn, mint) 145 | return info.decimals 146 | } 147 | 148 | export const getMintSupplyRaw = async ( 149 | conn: web3.Connection, 150 | mint: web3.PublicKey 151 | ): Promise => { 152 | const info = await getMintInfo(conn, mint) 153 | return info.supply 154 | } 155 | 156 | export const getMintSupply = async ( 157 | conn: web3.Connection, 158 | mint: web3.PublicKey 159 | ): Promise => { 160 | const info = await getMintInfo(conn, mint) 161 | return util.makeDecimal(info.supply, info.decimals) 162 | } 163 | 164 | export const getBalanceRaw = async ( 165 | conn: web3.Connection, 166 | mint: web3.PublicKey, 167 | tokenAccnt: web3.PublicKey 168 | ): Promise => { 169 | const token = new Token(conn, mint, TOKEN_PROGRAM_ID, {} as any) 170 | try { 171 | const info = await token.getAccountInfo(tokenAccnt) 172 | return info.amount 173 | } catch(err) { 174 | return new BN(0) 175 | 176 | } 177 | } 178 | 179 | export const getBalance = async ( 180 | conn: web3.Connection, 181 | mint: web3.PublicKey, 182 | user: web3.PublicKey 183 | ): Promise => { 184 | const tokenAccnt = await associatedTokenAccount.get.address(mint, user) 185 | const rawBalance = await getBalanceRaw(conn, mint, tokenAccnt) 186 | const decimals = await getMintDecimals(conn, mint) 187 | return util.makeDecimal(rawBalance, decimals) 188 | } 189 | 190 | 191 | export const create = { 192 | instructions: createMintInstructions, 193 | tx: createMintTx, 194 | signed: createMintSigned, 195 | send: createMintSend 196 | } 197 | 198 | export const get = { 199 | info: getMintInfo, 200 | decimals: getMintDecimals, 201 | supply: getMintSupply, 202 | supplyRaw: getMintSupplyRaw, 203 | balanceRaw: getBalanceRaw, 204 | balance: getBalance, 205 | } 206 | 207 | export const mintTo = { 208 | rawInstructions: mintToRawInstructions, 209 | instructions: mintToInstructions, 210 | tx: mintToTx, 211 | signed: mintToSigned, 212 | send: mintToSend 213 | } 214 | -------------------------------------------------------------------------------- /src/tx/sol.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | import { WalletI } from '../types' 3 | import * as util from '../util' 4 | 5 | export const transferRawInstructions = ( 6 | from: web3.PublicKey, 7 | to: web3.PublicKey, 8 | amount: number 9 | ): web3.TransactionInstruction[] => { 10 | return [web3.SystemProgram.transfer({ 11 | fromPubkey: from, 12 | toPubkey: to, 13 | lamports: amount 14 | })] 15 | } 16 | 17 | export const transferInstructions = ( 18 | from: web3.PublicKey, 19 | to: web3.PublicKey, 20 | amount: number 21 | ): web3.TransactionInstruction[] => { 22 | return transferRawInstructions(from, to, web3.LAMPORTS_PER_SOL * amount) 23 | } 24 | 25 | export const transferTx = async ( 26 | conn: web3.Connection, 27 | from: web3.PublicKey, 28 | to: web3.PublicKey, 29 | amount: number 30 | ): Promise => { 31 | const instructions = transferInstructions(from, to, amount) 32 | return util.wrapInstructions(conn, instructions, from) 33 | } 34 | 35 | export const transferSigned = async ( 36 | conn: web3.Connection, 37 | to: web3.PublicKey, 38 | amount: number, 39 | wallet: WalletI 40 | ): Promise => { 41 | const tx = await transferTx(conn, wallet.publicKey, to, amount) 42 | return await wallet.signTransaction(tx) 43 | } 44 | 45 | export const transferSend = async ( 46 | conn: web3.Connection, 47 | to: web3.PublicKey, 48 | amount: number, 49 | wallet: WalletI 50 | ): Promise => { 51 | const tx = await transferSigned(conn, to, amount, wallet) 52 | return await util.sendAndConfirm(conn, tx) 53 | } 54 | 55 | export const getBalance = async( 56 | conn: web3.Connection, 57 | user: web3.PublicKey 58 | ): Promise => { 59 | const balance = await conn.getBalance(user) 60 | return balance / web3.LAMPORTS_PER_SOL 61 | } 62 | 63 | export const transfer = { 64 | rawInstructions: transferRawInstructions, 65 | instructions: transferInstructions, 66 | tx: transferTx, 67 | signed: transferSigned, 68 | send: transferSend 69 | } 70 | 71 | export const get = { 72 | balance: getBalance 73 | } 74 | -------------------------------------------------------------------------------- /src/tx/token-account.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | import * as TokenInstructions from './token-instructions' 3 | import { TOKEN_PROGRAM_ID } from '@solana/spl-token' 4 | import * as util from '../util' 5 | import { WalletI } from '../types' 6 | 7 | export const createTokenAccountInstructions = async ( 8 | conn: web3.Connection, 9 | mint: web3.PublicKey, 10 | address: web3.PublicKey, 11 | owner: web3.PublicKey, 12 | sender: web3.PublicKey 13 | ): Promise => { 14 | return [ 15 | web3.SystemProgram.createAccount({ 16 | fromPubkey: sender, 17 | newAccountPubkey: address, 18 | space: 165, 19 | lamports: await conn.getMinimumBalanceForRentExemption(165), 20 | programId: TOKEN_PROGRAM_ID, 21 | }), 22 | TokenInstructions.initializeAccount({ 23 | account: address, 24 | mint, 25 | owner, 26 | }), 27 | ] 28 | } 29 | 30 | export const createTokenAccountTx = async ( 31 | conn: web3.Connection, 32 | mint: web3.PublicKey, 33 | address: web3.PublicKey, 34 | owner: web3.PublicKey, 35 | sender: web3.PublicKey 36 | ): Promise => { 37 | const instructions = await createTokenAccountInstructions(conn, mint, address, owner, sender) 38 | return util.wrapInstructions(conn, instructions, sender) 39 | } 40 | 41 | export const createTokenAccountSigned = async ( 42 | conn: web3.Connection, 43 | mint: web3.PublicKey, 44 | address: web3.PublicKey, 45 | owner: web3.PublicKey, 46 | wallet: WalletI 47 | ): Promise => { 48 | const tx = await createTokenAccountTx(conn, mint, address, owner, wallet.publicKey) 49 | return await wallet.signTransaction(tx) 50 | } 51 | 52 | export const createTokenAccountSend = async ( 53 | conn: web3.Connection, 54 | mint: web3.PublicKey, 55 | owner: web3.PublicKey, 56 | wallet: WalletI 57 | ): Promise => { 58 | const vault = web3.Keypair.generate() 59 | const tx = await createTokenAccountSigned(conn, mint, vault.publicKey, owner, wallet) 60 | await util.partialSignAndSend(conn, tx, [vault]) 61 | return vault.publicKey 62 | } 63 | 64 | export const create = { 65 | instructions: createTokenAccountInstructions, 66 | tx: createTokenAccountTx, 67 | signed: createTokenAccountSigned, 68 | send: createTokenAccountSend 69 | } 70 | -------------------------------------------------------------------------------- /src/tx/token-instructions.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | // @ts-nocheck 3 | // shamelessly ripped from @project-serum/serum to avoid dependency 4 | // https://github.com/project-serum/serum-ts/blob/master/packages/serum/src/token-instructions.js 5 | 6 | import * as BufferLayout from 'buffer-layout'; 7 | import { 8 | PublicKey, 9 | SYSVAR_RENT_PUBKEY, 10 | TransactionInstruction, 11 | } from '@solana/web3.js'; 12 | 13 | // NOTE: Update these if the position of arguments for the initializeAccount instruction changes 14 | export const INITIALIZE_ACCOUNT_ACCOUNT_INDEX = 0; 15 | export const INITIALIZE_ACCOUNT_MINT_INDEX = 1; 16 | export const INITIALIZE_ACCOUNT_OWNER_INDEX = 2; 17 | 18 | // NOTE: Update these if the position of arguments for the transfer instruction changes 19 | export const TRANSFER_SOURCE_INDEX = 0; 20 | export const TRANSFER_DESTINATION_INDEX = 1; 21 | export const TRANSFER_OWNER_INDEX = 2; 22 | 23 | // NOTE: Update these if the position of arguments for the closeAccount instruction changes 24 | export const CLOSE_ACCOUNT_SOURCE_INDEX = 0; 25 | export const CLOSE_ACCOUNT_DESTINATION_INDEX = 1; 26 | export const CLOSE_ACCOUNT_OWNER_INDEX = 2; 27 | 28 | export const TOKEN_PROGRAM_ID = new PublicKey( 29 | 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', 30 | ); 31 | 32 | export const WRAPPED_SOL_MINT = new PublicKey( 33 | 'So11111111111111111111111111111111111111112', 34 | ); 35 | 36 | 37 | class PublicKeyLayout extends BufferLayout.Blob { 38 | constructor(property) { 39 | super(32, property); 40 | } 41 | 42 | decode(b, offset) { 43 | return new PublicKey(super.decode(b, offset)); 44 | } 45 | 46 | encode(src, b, offset) { 47 | return super.encode(src.toBuffer(), b, offset); 48 | } 49 | } 50 | 51 | export function publicKeyLayout(property) { 52 | return new PublicKeyLayout(property); 53 | } 54 | 55 | const LAYOUT = BufferLayout.union(BufferLayout.u8('instruction')); 56 | LAYOUT.addVariant( 57 | 0, 58 | BufferLayout.struct([ 59 | BufferLayout.u8('decimals'), 60 | publicKeyLayout('mintAuthority'), 61 | BufferLayout.u8('freezeAuthorityOption'), 62 | publicKeyLayout('freezeAuthority'), 63 | ]), 64 | 'initializeMint', 65 | ); 66 | LAYOUT.addVariant(1, BufferLayout.struct([]), 'initializeAccount'); 67 | LAYOUT.addVariant( 68 | 3, 69 | BufferLayout.struct([BufferLayout.nu64('amount')]), 70 | 'transfer', 71 | ); 72 | LAYOUT.addVariant( 73 | 4, 74 | BufferLayout.struct([BufferLayout.nu64('amount')]), 75 | 'approve', 76 | ); 77 | LAYOUT.addVariant(5, BufferLayout.struct([]), 'revoke'); 78 | LAYOUT.addVariant( 79 | 6, 80 | BufferLayout.struct([ 81 | BufferLayout.u8('authorityType'), 82 | BufferLayout.u8('newAuthorityOption'), 83 | publicKeyLayout('newAuthority'), 84 | ]), 85 | 'setAuthority', 86 | ); 87 | LAYOUT.addVariant( 88 | 7, 89 | BufferLayout.struct([BufferLayout.nu64('amount')]), 90 | 'mintTo', 91 | ); 92 | LAYOUT.addVariant( 93 | 8, 94 | BufferLayout.struct([BufferLayout.nu64('amount')]), 95 | 'burn', 96 | ); 97 | LAYOUT.addVariant(9, BufferLayout.struct([]), 'closeAccount'); 98 | 99 | const instructionMaxSpan = Math.max( 100 | ...Object.values(LAYOUT.registry).map((r) => r.span), 101 | ); 102 | 103 | function encodeTokenInstructionData(instruction) { 104 | const b = Buffer.alloc(instructionMaxSpan); 105 | const span = LAYOUT.encode(instruction, b); 106 | return b.slice(0, span); 107 | } 108 | 109 | export function decodeTokenInstructionData(instruction) { 110 | return LAYOUT.decode(instruction); 111 | } 112 | 113 | export function initializeMint({ 114 | mint, 115 | decimals, 116 | mintAuthority, 117 | freezeAuthority = null, 118 | }) { 119 | const keys = [ 120 | { pubkey: mint, isSigner: false, isWritable: true }, 121 | { pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false }, 122 | ]; 123 | return new TransactionInstruction({ 124 | keys, 125 | data: encodeTokenInstructionData({ 126 | initializeMint: { 127 | decimals, 128 | mintAuthority, 129 | freezeAuthorityOption: !!freezeAuthority, 130 | freezeAuthority: freezeAuthority || new PublicKey(0), 131 | }, 132 | }), 133 | programId: TOKEN_PROGRAM_ID, 134 | }); 135 | } 136 | 137 | export function initializeAccount({ account, mint, owner }) { 138 | const keys = [ 139 | { pubkey: account, isSigner: false, isWritable: true }, 140 | { pubkey: mint, isSigner: false, isWritable: false }, 141 | { pubkey: owner, isSigner: false, isWritable: false }, 142 | { pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false }, 143 | ]; 144 | return new TransactionInstruction({ 145 | keys, 146 | data: encodeTokenInstructionData({ 147 | initializeAccount: {}, 148 | }), 149 | programId: TOKEN_PROGRAM_ID, 150 | }); 151 | } 152 | 153 | export function transfer({ source, destination, amount, owner }) { 154 | const keys = [ 155 | { pubkey: source, isSigner: false, isWritable: true }, 156 | { pubkey: destination, isSigner: false, isWritable: true }, 157 | { pubkey: owner, isSigner: true, isWritable: false }, 158 | ]; 159 | return new TransactionInstruction({ 160 | keys, 161 | data: encodeTokenInstructionData({ 162 | transfer: { amount }, 163 | }), 164 | programId: TOKEN_PROGRAM_ID, 165 | }); 166 | } 167 | 168 | export function approve({ source, delegate, amount, owner }) { 169 | const keys = [ 170 | { pubkey: source, isSigner: false, isWritable: true }, 171 | { pubkey: delegate, isSigner: false, isWritable: false }, 172 | { pubkey: owner, isSigner: true, isWritable: false }, 173 | ]; 174 | return new TransactionInstruction({ 175 | keys, 176 | data: encodeTokenInstructionData({ 177 | approve: { amount }, 178 | }), 179 | programId: TOKEN_PROGRAM_ID, 180 | }); 181 | } 182 | 183 | export function revoke({ source, owner }) { 184 | const keys = [ 185 | { pubkey: source, isSigner: false, isWritable: true }, 186 | { pubkey: owner, isSigner: true, isWritable: false }, 187 | ]; 188 | return new TransactionInstruction({ 189 | keys, 190 | data: encodeTokenInstructionData({ 191 | revoke: {}, 192 | }), 193 | programId: TOKEN_PROGRAM_ID, 194 | }); 195 | } 196 | 197 | export function setAuthority({ 198 | target, 199 | currentAuthority, 200 | newAuthority, 201 | authorityType, 202 | }) { 203 | const keys = [ 204 | { pubkey: target, isSigner: false, isWritable: true }, 205 | { pubkey: currentAuthority, isSigner: true, isWritable: false }, 206 | ]; 207 | return new TransactionInstruction({ 208 | keys, 209 | data: encodeTokenInstructionData({ 210 | setAuthority: { 211 | authorityType, 212 | newAuthorityOption: !!newAuthority, 213 | newAuthority, 214 | }, 215 | }), 216 | programId: TOKEN_PROGRAM_ID, 217 | }); 218 | } 219 | 220 | export function mintTo({ mint, destination, amount, mintAuthority }) { 221 | const keys = [ 222 | { pubkey: mint, isSigner: false, isWritable: true }, 223 | { pubkey: destination, isSigner: false, isWritable: true }, 224 | { pubkey: mintAuthority, isSigner: true, isWritable: false }, 225 | ]; 226 | return new TransactionInstruction({ 227 | keys, 228 | data: encodeTokenInstructionData({ 229 | mintTo: { amount }, 230 | }), 231 | programId: TOKEN_PROGRAM_ID, 232 | }); 233 | } 234 | 235 | export function closeAccount({ source, destination, owner }) { 236 | const keys = [ 237 | { pubkey: source, isSigner: false, isWritable: true }, 238 | { pubkey: destination, isSigner: false, isWritable: true }, 239 | { pubkey: owner, isSigner: true, isWritable: false }, 240 | ]; 241 | return new TransactionInstruction({ 242 | keys, 243 | data: encodeTokenInstructionData({ 244 | closeAccount: {}, 245 | }), 246 | programId: TOKEN_PROGRAM_ID, 247 | }); 248 | } 249 | -------------------------------------------------------------------------------- /src/tx/token.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | import { TOKEN_PROGRAM_ID, Token } from '@solana/spl-token' 3 | import * as util from '../util' 4 | import * as associatedTokenAccount from './associated-token-account' 5 | import * as mintTx from './mint' 6 | import { WalletI } from '../types' 7 | 8 | export const transferTokenRawInstructions = ( 9 | mint: web3.PublicKey, 10 | from: web3.PublicKey, 11 | to: web3.PublicKey, 12 | owner: web3.PublicKey, 13 | amount: number, 14 | decimals: number, 15 | ): web3.TransactionInstruction[] => { 16 | return [ 17 | Token.createTransferCheckedInstruction(TOKEN_PROGRAM_ID, from, mint, to, owner, [], amount, decimals) 18 | ] 19 | } 20 | 21 | export const transferTokenInstructions = async ( 22 | conn: web3.Connection, 23 | mint: web3.PublicKey, 24 | from: web3.PublicKey, 25 | to: web3.PublicKey, 26 | amount: number, 27 | ): Promise => { 28 | const [fromAssociated, toAssociated] = await Promise.all([ 29 | associatedTokenAccount.get.address(mint, from), 30 | associatedTokenAccount.get.address(mint, to) 31 | ]) 32 | 33 | const mintDecimals = await mintTx.get.decimals(conn, mint) 34 | const amountRaw = util.makeInteger(amount, mintDecimals).toNumber() 35 | const instructions = [ 36 | ...await associatedTokenAccount.create.maybeInstructions(conn, mint, to, from), 37 | ...transferTokenRawInstructions(mint, fromAssociated, toAssociated, from, amountRaw, mintDecimals) 38 | ] 39 | 40 | return instructions 41 | } 42 | 43 | export const transferTokenTx = async ( 44 | conn: web3.Connection, 45 | mint: web3.PublicKey, 46 | from: web3.PublicKey, 47 | to: web3.PublicKey, 48 | amount: number 49 | ): Promise => { 50 | const instructions = await transferTokenInstructions(conn, mint, from, to, amount) 51 | return util.wrapInstructions(conn, instructions, from) 52 | } 53 | 54 | export const transferTokenSigned = async ( 55 | conn: web3.Connection, 56 | mint: web3.PublicKey, 57 | to: web3.PublicKey, 58 | amount: number, 59 | wallet: WalletI 60 | ): Promise => { 61 | const tx = await transferTokenTx(conn, mint, wallet.publicKey, to, amount) 62 | return await wallet.signTransaction(tx) 63 | } 64 | 65 | export const transferTokenSend = async ( 66 | conn: web3.Connection, 67 | mint: web3.PublicKey, 68 | to: web3.PublicKey, 69 | amount: number, 70 | wallet: WalletI 71 | ): Promise => { 72 | const tx = await transferTokenSigned(conn, mint, to, amount, wallet) 73 | return await util.sendAndConfirm(conn, tx) 74 | } 75 | 76 | 77 | export const transfer = { 78 | rawInstructions: transferTokenRawInstructions, 79 | instructions: transferTokenInstructions, 80 | tx: transferTokenTx, 81 | signed: transferTokenSigned, 82 | send: transferTokenSend 83 | } 84 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | 3 | export interface WalletI { 4 | publicKey: web3.PublicKey 5 | signTransaction: (tx: web3.Transaction) => Promise 6 | signAllTransactions: (txs: web3.Transaction[]) => Promise 7 | } 8 | -------------------------------------------------------------------------------- /src/util.ts: -------------------------------------------------------------------------------- 1 | import BN from 'bn.js' 2 | import * as web3 from '@solana/web3.js' 3 | 4 | export const wrapInstructions = async (conn: web3.Connection, instructions: web3.TransactionInstruction[], signer: web3.PublicKey): Promise => { 5 | const tx = new web3.Transaction(); 6 | tx.add(...instructions); 7 | const { blockhash } = await conn.getRecentBlockhash() 8 | tx.recentBlockhash = blockhash 9 | tx.feePayer = signer 10 | return tx 11 | } 12 | 13 | export const partialSignAndSend = async (conn: web3.Connection, tx: web3.Transaction, signers: web3.Keypair[] = []): Promise => { 14 | if(signers.length > 0) { 15 | await tx.partialSign(...signers) 16 | } 17 | return sendAndConfirm(conn, tx) 18 | } 19 | 20 | export const sendAndConfirm = async (conn: web3.Connection, tx: web3.Transaction): Promise => { 21 | return web3.sendAndConfirmRawTransaction(conn, tx.serialize(), { commitment: 'confirmed' }) 22 | } 23 | 24 | export const makeDecimal = (bn: BN, decimals: number): number => { 25 | return bn.toNumber() / Math.pow(10, decimals) 26 | } 27 | 28 | export const makeInteger = (num: number, decimals: number): BN => { 29 | const mul = Math.pow(10, decimals) 30 | return new BN(num * mul) 31 | } 32 | -------------------------------------------------------------------------------- /src/wallet/connected.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | import * as mint from '../tx/mint' 3 | import * as token from '../tx/token' 4 | import * as sol from '../tx/sol' 5 | import * as associatedTokenAccount from '../tx/associated-token-account' 6 | import InternalWallet from './simple' 7 | import { WalletI } from '../types' 8 | 9 | export class Wallet implements WalletI { 10 | 11 | conn: web3.Connection 12 | signer: WalletI 13 | publicKey: web3.PublicKey 14 | 15 | constructor(conn: web3.Connection, signer: WalletI) { 16 | this.conn = conn 17 | this.signer = signer 18 | this.publicKey = signer.publicKey 19 | } 20 | 21 | static fromWallet(conn: web3.Connection, signer: WalletI) { 22 | return new Wallet(conn, signer) 23 | } 24 | 25 | // from web3 keypair 26 | static fromKeypair(conn: web3.Connection, keypair: web3.Keypair): Wallet { 27 | const signer = new InternalWallet(keypair) 28 | return Wallet.fromWallet(conn, signer) 29 | } 30 | 31 | // from base58 secretKey 32 | static fromSecretKey(conn: web3.Connection, key: Uint8Array): Wallet { 33 | const keypair = web3.Keypair.fromSecretKey(key) 34 | return Wallet.fromKeypair(conn, keypair) 35 | } 36 | 37 | async getBalance(mintKey: web3.PublicKey): Promise { 38 | return mint.getBalance(this.conn, mintKey, this.publicKey) 39 | } 40 | 41 | async transferToken(mintKey: web3.PublicKey, to: web3.PublicKey, amount: number): Promise { 42 | return token.transfer.send(this.conn, mintKey, to, amount, this) 43 | } 44 | 45 | async getSolBalance(): Promise { 46 | return sol.get.balance(this.conn, this.publicKey) 47 | } 48 | 49 | async transferSol(to: web3.PublicKey, amount: number): Promise { 50 | return sol.transfer.send(this.conn, to, amount, this) 51 | } 52 | 53 | async getAssociatedTokenAccount(mintKey: web3.PublicKey): Promise { 54 | return associatedTokenAccount.get.address(mintKey, this.publicKey) 55 | } 56 | 57 | async existsAssociatedTokenAccount(mintKey: web3.PublicKey): Promise { 58 | return associatedTokenAccount.exists(this.conn, mintKey, this.publicKey) 59 | } 60 | 61 | // idempotent, can call as many times as you like 62 | async createAssociatedTokenAccount(mintKey: web3.PublicKey): Promise { 63 | return associatedTokenAccount.create.send(this.conn, mintKey, this.publicKey, this) 64 | } 65 | 66 | async signTransaction(tx: web3.Transaction): Promise { 67 | return this.signer.signTransaction(tx) 68 | } 69 | 70 | async signAllTransactions(txs: web3.Transaction[]): Promise { 71 | return this.signer.signAllTransactions(txs) 72 | } 73 | 74 | } 75 | 76 | export default Wallet 77 | -------------------------------------------------------------------------------- /src/wallet/index.ts: -------------------------------------------------------------------------------- 1 | export * from './connected' 2 | export * from './simple' 3 | -------------------------------------------------------------------------------- /src/wallet/internal.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | import { WalletI } from '../types' 3 | 4 | // internal wallet to prevent circular dependencies 5 | export class InternalWallet implements WalletI { 6 | 7 | private keypair: web3.Keypair 8 | publicKey: web3.PublicKey 9 | 10 | constructor(keypair: web3.Keypair) { 11 | this.keypair = keypair 12 | this.publicKey = keypair.publicKey 13 | } 14 | 15 | async signTransaction(tx: web3.Transaction): Promise { 16 | await tx.sign(this.keypair) 17 | return tx 18 | } 19 | 20 | async signAllTransactions(txs: web3.Transaction[]): Promise { 21 | return Promise.all( 22 | txs.map(tx => this.signTransaction(tx)) 23 | ) 24 | } 25 | 26 | } 27 | 28 | export default InternalWallet 29 | -------------------------------------------------------------------------------- /src/wallet/simple.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | import InternalWallet from './internal' 3 | import ConnectedWallet from './connected' 4 | 5 | // simple wrapper around keypairs so interfaces line up 6 | export class SimpleWallet extends InternalWallet { 7 | 8 | // from web3 keypair 9 | static fromKeypair(keypair: web3.Keypair): SimpleWallet { 10 | return new SimpleWallet(keypair) 11 | } 12 | 13 | // from base58 secretKey 14 | static fromSecretKey(key: Uint8Array): SimpleWallet { 15 | const keypair = web3.Keypair.fromSecretKey(key) 16 | return new SimpleWallet(keypair) 17 | } 18 | 19 | connect(conn: web3.Connection): ConnectedWallet { 20 | return ConnectedWallet.fromWallet(conn, this) 21 | } 22 | 23 | } 24 | 25 | export default SimpleWallet 26 | -------------------------------------------------------------------------------- /tests/connected-wallet.test.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | import * as spl from '../src' 3 | 4 | jest.setTimeout(100000) 5 | 6 | describe('connected wallet', () => { 7 | 8 | const connection = new web3.Connection('http://localhost:8899', 'confirmed') 9 | 10 | const keypairA = web3.Keypair.generate() 11 | const walletA = spl.Wallet.fromKeypair(connection, keypairA) 12 | const keypairB = web3.Keypair.generate() 13 | const walletB = spl.Wallet.fromKeypair(connection, keypairB) 14 | 15 | const ONE_SOL = web3.LAMPORTS_PER_SOL 16 | const MINT_AMOUNT = 15 17 | const TRANSFER_AMOUNT = 5 18 | 19 | let mint: spl.Mint 20 | 21 | it('sets up accounts', async () => { 22 | const [sigA, sigB] = await Promise.all([ 23 | connection.requestAirdrop(walletA.publicKey, ONE_SOL), 24 | connection.requestAirdrop(walletB.publicKey, ONE_SOL) 25 | ]) 26 | await Promise.all([ 27 | connection.confirmTransaction(sigA), 28 | connection.confirmTransaction(sigB) 29 | ]) 30 | }) 31 | 32 | it('creates mint', async () => { 33 | mint = await spl.Mint.create(connection, 6, walletA.publicKey, walletA) 34 | }) 35 | 36 | it('mints to user with no account', async () => { 37 | await mint.mintTo(walletB.publicKey, walletA, MINT_AMOUNT) 38 | }) 39 | 40 | it('accurately retrieves their balance', async () => { 41 | const balance = await walletB.getBalance(mint.key) 42 | expect(balance).toEqual(MINT_AMOUNT) 43 | }) 44 | 45 | it('transfers to user with no account', async () => { 46 | await walletB.transferToken(mint.key, walletA.publicKey, TRANSFER_AMOUNT) 47 | }) 48 | 49 | it('accurately retrieves both balances', async () => { 50 | const [balanceA, balanceB] = await Promise.all([ 51 | walletA.getBalance(mint.key), 52 | walletB.getBalance(mint.key) 53 | ]) 54 | expect(balanceA).toEqual(TRANSFER_AMOUNT) 55 | expect(balanceB).toEqual(MINT_AMOUNT - TRANSFER_AMOUNT) 56 | }) 57 | 58 | 59 | }) 60 | -------------------------------------------------------------------------------- /tests/transactions.test.ts: -------------------------------------------------------------------------------- 1 | import * as web3 from '@solana/web3.js' 2 | import * as spl from '../src' 3 | 4 | jest.setTimeout(100000) 5 | 6 | describe('transactions', () => { 7 | 8 | const keypairA = web3.Keypair.generate() 9 | const walletA = spl.SimpleWallet.fromKeypair(keypairA) 10 | const keypairB = web3.Keypair.generate() 11 | const walletB = spl.SimpleWallet.fromKeypair(keypairB) 12 | 13 | const connection = new web3.Connection('http://localhost:8899', 'confirmed') 14 | 15 | const ONE_SOL = web3.LAMPORTS_PER_SOL 16 | const MINT_AMOUNT = 15 17 | const TRANSFER_AMOUNT = 5 18 | 19 | let mint: web3.PublicKey 20 | 21 | it('sets up accounts', async () => { 22 | const [sigA, sigB] = await Promise.all([ 23 | connection.requestAirdrop(walletA.publicKey, ONE_SOL), 24 | connection.requestAirdrop(walletB.publicKey, ONE_SOL) 25 | ]) 26 | await Promise.all([ 27 | connection.confirmTransaction(sigA), 28 | connection.confirmTransaction(sigB) 29 | ]) 30 | }) 31 | 32 | it('creates mint', async () => { 33 | mint = await spl.mint.create.send(connection, 6, walletA.publicKey, walletA) 34 | }) 35 | 36 | it('mints to user with no account', async () => { 37 | await spl.mint.mintTo.send(connection, mint, walletB.publicKey, walletA, MINT_AMOUNT) 38 | }) 39 | 40 | it('accurately retrieves their balance', async () => { 41 | const balance = await spl.mint.getBalance(connection, mint, walletB.publicKey) 42 | expect(balance).toEqual(MINT_AMOUNT) 43 | }) 44 | 45 | it('transfers to user with no account', async () => { 46 | await spl.token.transfer.send(connection, mint, walletA.publicKey, TRANSFER_AMOUNT, walletB) 47 | }) 48 | 49 | it('accurately retrieves both balances', async () => { 50 | const [balanceA, balanceB] = await Promise.all([ 51 | spl.mint.getBalance(connection, mint, walletA.publicKey), 52 | spl.mint.getBalance(connection, mint, walletB.publicKey) 53 | ]) 54 | expect(balanceA).toEqual(TRANSFER_AMOUNT) 55 | expect(balanceB).toEqual(MINT_AMOUNT - TRANSFER_AMOUNT) 56 | }) 57 | 58 | 59 | }) 60 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "lib": ["es2015"], 4 | "module": "commonjs", 5 | "target": "es6", 6 | "esModuleInterop": true, 7 | "declaration": true, 8 | "outDir": "dist", 9 | "declarationDir": "dist", 10 | "resolveJsonModule": true 11 | }, 12 | "include": [ 13 | "src" 14 | ], 15 | "exclude": [ 16 | "lib/**/*.test.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /typedoc.json: -------------------------------------------------------------------------------- 1 | { 2 | "entryPoints": [ "./src/" ], 3 | "exclude": "**/*.test.ts", 4 | "excludeExternals": true, 5 | "excludeInternal": true, 6 | "excludePrivate": true, 7 | "excludeProtected": true, 8 | "name": "Easy SPL", 9 | "out": "docs", 10 | "readme": "./README.md" 11 | } 12 | --------------------------------------------------------------------------------