test.ts 2.0 KB

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