transfer.test.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import {
  2. appendTransactionMessageInstruction,
  3. generateKeyPairSigner,
  4. pipe,
  5. } from '@solana/web3.js';
  6. import test from 'ava';
  7. import {
  8. Mint,
  9. Token,
  10. fetchMint,
  11. fetchToken,
  12. getTransferInstruction,
  13. } from '../src/index.js';
  14. import {
  15. createDefaultSolanaClient,
  16. createDefaultTransaction,
  17. createMint,
  18. createToken,
  19. createTokenWithAmount,
  20. generateKeyPairSignerWithSol,
  21. signAndSendTransaction,
  22. } from './_setup.js';
  23. test('it transfers tokens from one account to another', async (t) => {
  24. // Given a mint account and two token accounts.
  25. // One with 100 tokens and the other with 0 tokens.
  26. const client = createDefaultSolanaClient();
  27. const [payer, mintAuthority, ownerA, ownerB] = await Promise.all([
  28. generateKeyPairSignerWithSol(client),
  29. generateKeyPairSigner(),
  30. generateKeyPairSigner(),
  31. generateKeyPairSigner(),
  32. ]);
  33. const mint = await createMint(client, payer, mintAuthority.address);
  34. const [tokenA, tokenB] = await Promise.all([
  35. createTokenWithAmount(
  36. client,
  37. payer,
  38. mintAuthority,
  39. mint,
  40. ownerA.address,
  41. 100n
  42. ),
  43. createToken(client, payer, mint, ownerB.address),
  44. ]);
  45. // When owner A transfers 50 tokens to owner B.
  46. const transfer = getTransferInstruction({
  47. source: tokenA,
  48. destination: tokenB,
  49. authority: ownerA,
  50. amount: 50n,
  51. });
  52. await pipe(
  53. await createDefaultTransaction(client, payer),
  54. (tx) => appendTransactionMessageInstruction(transfer, tx),
  55. (tx) => signAndSendTransaction(client, tx)
  56. );
  57. // Then we expect the mint and token accounts to have the following updated data.
  58. const [{ data: mintData }, { data: tokenDataA }, { data: tokenDataB }] =
  59. await Promise.all([
  60. fetchMint(client.rpc, mint),
  61. fetchToken(client.rpc, tokenA),
  62. fetchToken(client.rpc, tokenB),
  63. ]);
  64. t.like(mintData, <Mint>{ supply: 100n });
  65. t.like(tokenDataA, <Token>{ amount: 50n });
  66. t.like(tokenDataB, <Token>{ amount: 50n });
  67. });