test.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Buffer } from 'node:buffer';
  2. import { describe, test } from 'node:test';
  3. import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js';
  4. import * as borsh from 'borsh';
  5. import { start } from 'solana-bankrun';
  6. describe('Create a system account', async () => {
  7. const PROGRAM_ID = PublicKey.unique();
  8. const context = await start([{ name: 'program', programId: PROGRAM_ID }], []);
  9. const client = context.banksClient;
  10. const payer = context.payer;
  11. class Assignable {
  12. constructor(properties) {
  13. for (const [key, value] of Object.entries(properties)) {
  14. this[key] = value;
  15. }
  16. }
  17. }
  18. class AddressData extends Assignable {
  19. toBuffer() {
  20. return Buffer.from(borsh.serialize(AddressDataSchema, this));
  21. }
  22. }
  23. const AddressDataSchema = new Map([
  24. [
  25. AddressData,
  26. {
  27. kind: 'struct',
  28. fields: [
  29. ['name', 'string'],
  30. ['address', 'string'],
  31. ],
  32. },
  33. ],
  34. ]);
  35. test('Create the account', async () => {
  36. const newKeypair = Keypair.generate();
  37. const addressData = new AddressData({
  38. name: 'Marcus',
  39. address: '123 Main St. San Francisco, CA',
  40. });
  41. // We're just going to serialize our object here so we can check
  42. // the size on the client side against the program logs
  43. const addressDataBuffer = addressData.toBuffer();
  44. console.log(`Address data buffer length: ${addressDataBuffer.length}`);
  45. const ix = new TransactionInstruction({
  46. keys: [
  47. { pubkey: payer.publicKey, isSigner: true, isWritable: true },
  48. { pubkey: newKeypair.publicKey, isSigner: true, isWritable: true },
  49. { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
  50. ],
  51. programId: PROGRAM_ID,
  52. data: addressDataBuffer,
  53. });
  54. const tx = new Transaction();
  55. const blockhash = context.lastBlockhash;
  56. tx.recentBlockhash = blockhash;
  57. tx.add(ix).sign(payer, newKeypair);
  58. await client.processTransaction(tx);
  59. });
  60. });