initializeAccount.test.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { getCreateAccountInstruction } from '@solana-program/system';
  2. import {
  3. Account,
  4. appendTransactionMessageInstructions,
  5. generateKeyPairSigner,
  6. none,
  7. pipe,
  8. } from '@solana/web3.js';
  9. import test from 'ava';
  10. import {
  11. AccountState,
  12. TOKEN_PROGRAM_ADDRESS,
  13. Token,
  14. fetchToken,
  15. getInitializeAccountInstruction,
  16. getTokenSize,
  17. } from '../src/index.js';
  18. import {
  19. createDefaultSolanaClient,
  20. createDefaultTransaction,
  21. createMint,
  22. generateKeyPairSignerWithSol,
  23. signAndSendTransaction,
  24. } from './_setup.js';
  25. test('it creates and initializes a new token account', async (t) => {
  26. // Given a mint account, its mint authority and two generated keypairs
  27. // for the token to be created and its owner.
  28. const client = createDefaultSolanaClient();
  29. const [mintAuthority, token, owner] = await Promise.all([
  30. generateKeyPairSignerWithSol(client),
  31. generateKeyPairSigner(),
  32. generateKeyPairSigner(),
  33. ]);
  34. const mint = await createMint(client, mintAuthority);
  35. // When we create and initialize a token account at this address.
  36. const space = BigInt(getTokenSize());
  37. const rent = await client.rpc.getMinimumBalanceForRentExemption(space).send();
  38. const instructions = [
  39. getCreateAccountInstruction({
  40. payer: mintAuthority,
  41. newAccount: token,
  42. lamports: rent,
  43. space,
  44. programAddress: TOKEN_PROGRAM_ADDRESS,
  45. }),
  46. getInitializeAccountInstruction({
  47. account: token.address,
  48. mint,
  49. owner: owner.address,
  50. }),
  51. ];
  52. await pipe(
  53. await createDefaultTransaction(client, mintAuthority),
  54. (tx) => appendTransactionMessageInstructions(instructions, tx),
  55. (tx) => signAndSendTransaction(client, tx)
  56. );
  57. // Then we expect the token account to exist and have the following data.
  58. const tokenAccount = await fetchToken(client.rpc, token.address);
  59. t.like(tokenAccount, <Account<Token>>{
  60. address: token.address,
  61. data: {
  62. mint,
  63. owner: owner.address,
  64. amount: 0n,
  65. delegate: none(),
  66. state: AccountState.Initialized,
  67. isNative: none(),
  68. delegatedAmount: 0n,
  69. closeAuthority: none(),
  70. },
  71. });
  72. });