test.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. function createKeypairFromFile(path: string): Keypair {
  12. return Keypair.fromSecretKey(
  13. Buffer.from(JSON.parse(require('fs').readFileSync(path, "utf-8")))
  14. )
  15. };
  16. describe("Create a system account", async () => {
  17. const connection = new Connection(`http://localhost:8899`, 'confirmed');
  18. const payer = createKeypairFromFile(require('os').homedir() + '/.config/solana/id.json');
  19. const program = createKeypairFromFile('./program/target/so/program-keypair.json')
  20. const PROGRAM_ID: PublicKey = program.publicKey;
  21. it("Create the account via a cross program invocation", async () => {
  22. const newKeypair = Keypair.generate();
  23. let ix = new TransactionInstruction({
  24. keys: [
  25. {pubkey: payer.publicKey, isSigner: true, isWritable: true},
  26. {pubkey: newKeypair.publicKey, isSigner: true, isWritable: true},
  27. {pubkey: SystemProgram.programId, isSigner: false, isWritable: false}
  28. ],
  29. programId: PROGRAM_ID,
  30. data: Buffer.alloc(0),
  31. });
  32. await sendAndConfirmTransaction(
  33. connection,
  34. new Transaction().add(ix),
  35. [payer, newKeypair]
  36. );
  37. });
  38. it("Create the account via direct call to system program", async () => {
  39. const newKeypair = Keypair.generate();
  40. const ix = SystemProgram.createAccount({
  41. fromPubkey: payer.publicKey,
  42. newAccountPubkey: newKeypair.publicKey,
  43. lamports: LAMPORTS_PER_SOL,
  44. space: 0,
  45. programId: SystemProgram.programId
  46. })
  47. await sendAndConfirmTransaction(connection,
  48. new Transaction().add(ix),
  49. [payer, newKeypair]);
  50. console.log(`Account with public key ${newKeypair.publicKey} successfully created`);
  51. });
  52. });