Skip to content

Instantly share code, notes, and snippets.

@keitaj
Created April 29, 2022 08:26
Show Gist options
  • Save keitaj/c5e79a62062aabd42582d05fb1243319 to your computer and use it in GitHub Desktop.
Save keitaj/c5e79a62062aabd42582d05fb1243319 to your computer and use it in GitHub Desktop.
import { Connection, PublicKey, clusterApiUrl, LAMPORTS_PER_SOL, RpcResponseAndContext, AccountInfo } from "@solana/web3.js";
import { AccountLayout, TOKEN_PROGRAM_ID } from "@solana/spl-token";


// ... 省略 ...

            const getOwnedTokenAccount = async () : Promise<RpcResponseAndContext<{
                pubkey: PublicKey;
                account: AccountInfo<Buffer>;
            }[]>> => {
                return new Promise((resolve) => {
                    try {
                        const connection = new Connection(clusterApiUrl("devnet"),"confirmed");
                        const tokenAccounts = connection.getTokenAccountsByOwner(
                                publicKey,
                            {
                                programId: TOKEN_PROGRAM_ID,
                            }
                          );
                        console.log(tokenAccounts);
                        resolve(tokenAccounts)
                    } catch(err) {
                        console.log(err);
                    }
                });
            }
            getOwnedTokenAccount().then((tokenAccounts: RpcResponseAndContext<{
                pubkey: PublicKey;
                account: AccountInfo<Buffer>;
            }[]>) => {
                console.log("Token Balance");
                console.log("------------------------------------------------------------");
                tokenAccounts.value.forEach((e) => {
                    const accountInfo = AccountLayout.decode(e.account.data);
                    console.log(`${new PublicKey(accountInfo.mint)}   ${accountInfo.amount}`);
                })
              });

https://spl.solana.com/token を参考に、以上のようなコードを書くと、

Uncaught (in promise) ReferenceError: Buffer is not defined

というエラーが起こる。

頭に、global.Bufferの定義をすることで解決。

global.Buffer = global.Buffer || require('buffer').Buffer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment