Token Account
- create a token account
- manually do it
- use helper to do it
How to Create a Token Account
https://beta.solpg.io/660ce716cffcf4b13384d010
Starter Code
- open solana playground
- starter code
client.ts
import {
ACCOUNT_SIZE,
TOKEN_2022_PROGRAM_ID,
createInitializeAccountInstruction,
getMinimumBalanceForRentExemptAccount,
createMint,
} from "@solana/spl-token";
import {
Connection,
Keypair,
SystemProgram,
Transaction,
clusterApiUrl,
sendAndConfirmTransaction,
} from "@solana/web3.js";
const wallet = pg.wallet;
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
// Create new mint account
const mint = await createMint(
connection,
wallet.keypair, // payer
wallet.publicKey, // mint authority
wallet.publicKey, // freeze authority
2, // decimals
new Keypair(), // keypair for mint account
null, // confirmOptions
TOKEN_2022_PROGRAM_ID,
);
Generate Keypair
client.ts
// Generate keypair to use as address of token account
const token = Keypair.generate();
// Calculate minimum lamports for space required by token account
const rentLamports = await getMinimumBalanceForRentExemptAccount(connection);
Build Create Account Instruction
client.ts
// Instruction to create new account with space for new token account
const createAccountInstruction = SystemProgram.createAccount({
fromPubkey: wallet.publicKey,
newAccountPubkey: token.publicKey,
space: ACCOUNT_SIZE,
lamports: rentLamports,
programId: TOKEN_2022_PROGRAM_ID,
});
Build Initialize Account Instruction
client.ts
// Instruction to initialize token account
const initializeAccountInstruction = createInitializeAccountInstruction(
token.publicKey, // token account address
mint, // mint address
wallet.publicKey, // token account owner
TOKEN_2022_PROGRAM_ID,
);
Add Instructions to Transaction
client.ts
const transaction = new Transaction().add(
createAccountInstruction,
initializeAccountInstruction,
);
Send Transaction
client.ts
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[
wallet.keypair, // payer
token, // token address keypair
],
);
client.ts
console.log(
"\nTransaction Signature:",
`https://explorer.solana.com/tx/${transactionSignature}?cluster=devnet`,
);
console.log(
"\nToken Account: ",
`https://explorer.solana.com/address/${token.publicKey}?cluster=devnet`,
);
Run script
Terminal
run
Output
Running client...
client.ts:
Transaction Signature: https://explorer.solana.com/tx/KrXyevdmKCNcscZru52dwgHRTQnMeMcWiiHrJXL3QUkaGpLF4cVfSMA4JruwVtfrBg2pjVBvTqJVofN8ceyEUFm?cluster=devnet
Token Account: https://explorer.solana.com/address/6MWnReiGWboKJaVroawnw7vRJC53t5UB5Uts4XJ9nXUf?cluster=devnet