test.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import {
  2. Connection,
  3. Keypair,
  4. LAMPORTS_PER_SOL,
  5. PublicKey,
  6. sendAndConfirmTransaction,
  7. SystemProgram,
  8. Transaction,
  9. TransactionInstruction,
  10. } from '@solana/web3.js';
  11. import * as buffer_layout from "buffer-layout";
  12. function createKeypairFromFile(path: string): Keypair {
  13. return Keypair.fromSecretKey(
  14. Buffer.from(JSON.parse(require('fs').readFileSync(path, "utf-8")))
  15. )
  16. };
  17. describe("transfer-sol", () => {
  18. async function getBalances(payerPubkey: PublicKey, recipientPubkey: PublicKey, timeframe: string) {
  19. let payerBalance = await connection.getBalance(payerPubkey);
  20. let recipientBalance = await connection.getBalance(recipientPubkey);
  21. console.log(`${timeframe} balances:`);
  22. console.log(` Payer: ${payerBalance}`);
  23. console.log(` Recipient: ${recipientBalance}`);
  24. };
  25. const connection = new Connection(`http://localhost:8899`, 'confirmed');
  26. const payer = createKeypairFromFile(require('os').homedir() + '/.config/solana/id.json');
  27. const program = createKeypairFromFile('./program/target/so/program-keypair.json');
  28. it("Transfer some SOL", async () => {
  29. let recipientKeypair = Keypair.generate();
  30. let transferAmount = 1 * LAMPORTS_PER_SOL;
  31. await getBalances(payer.publicKey, recipientKeypair.publicKey, "Beginning");
  32. let data = Buffer.alloc(8) // 8 bytes
  33. buffer_layout.ns64("value").encode(transferAmount, data);
  34. let ix = new TransactionInstruction({
  35. keys: [
  36. {pubkey: payer.publicKey, isSigner: true, isWritable: true},
  37. {pubkey: recipientKeypair.publicKey, isSigner: false, isWritable: true},
  38. {pubkey: SystemProgram.programId, isSigner: false, isWritable: false}
  39. ],
  40. programId: program.publicKey,
  41. data: data,
  42. });
  43. await sendAndConfirmTransaction(
  44. connection,
  45. new Transaction().add(ix),
  46. [payer]
  47. );
  48. await getBalances(payer.publicKey, recipientKeypair.publicKey, "Resulting");
  49. });
  50. });