transferSol.test.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import {
  2. AccountRole,
  3. Address,
  4. appendTransactionMessageInstruction,
  5. generateKeyPairSigner,
  6. lamports,
  7. pipe,
  8. } from '@solana/kit';
  9. import test from 'ava';
  10. import { getTransferSolInstruction, parseTransferSolInstruction } from '../src';
  11. import {
  12. createDefaultSolanaClient,
  13. createDefaultTransaction,
  14. generateKeyPairSignerWithSol,
  15. getBalance,
  16. signAndSendTransaction,
  17. } from './_setup';
  18. test('it transfers SOL from one account to another', async (t) => {
  19. // Given a source account with 3 SOL and a destination account with no SOL.
  20. const client = createDefaultSolanaClient();
  21. const source = await generateKeyPairSignerWithSol(client, 3_000_000_000n);
  22. const destination = (await generateKeyPairSigner()).address;
  23. // When the source account transfers 1 SOL to the destination account.
  24. const transferSol = getTransferSolInstruction({
  25. source,
  26. destination,
  27. amount: 1_000_000_000,
  28. });
  29. await pipe(
  30. await createDefaultTransaction(client, source),
  31. (tx) => appendTransactionMessageInstruction(transferSol, tx),
  32. (tx) => signAndSendTransaction(client, tx)
  33. );
  34. // Then the source account now has roughly 2 SOL (minus the transaction fee).
  35. const sourceBalance = await getBalance(client, source.address);
  36. t.true(sourceBalance < 2_000_000_000n);
  37. t.true(sourceBalance > 1_999_000_000n);
  38. // And the destination account has exactly 1 SOL.
  39. t.is(await getBalance(client, destination), lamports(1_000_000_000n));
  40. });
  41. test('it parses the accounts and the data of an existing transfer SOL instruction', async (t) => {
  42. // Given a transfer SOL instruction with the following accounts and data.
  43. const source = await generateKeyPairSigner();
  44. const destination = (await generateKeyPairSigner()).address;
  45. const transferSol = getTransferSolInstruction({
  46. source,
  47. destination,
  48. amount: 1_000_000_000,
  49. });
  50. // When we parse this instruction.
  51. const parsedTransferSol = parseTransferSolInstruction(transferSol);
  52. // Then we expect the following accounts and data.
  53. t.is(parsedTransferSol.accounts.source.address, source.address);
  54. t.is(parsedTransferSol.accounts.source.role, AccountRole.WRITABLE_SIGNER);
  55. t.is(parsedTransferSol.accounts.source.signer, source);
  56. t.is(parsedTransferSol.accounts.destination.address, destination);
  57. t.is(parsedTransferSol.accounts.destination.role, AccountRole.WRITABLE);
  58. t.is(parsedTransferSol.data.amount, 1_000_000_000n);
  59. t.is(
  60. parsedTransferSol.programAddress,
  61. '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>
  62. );
  63. });