1
0

initializeAccount.test.ts 2.1 KB

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