test.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Buffer } from 'node:buffer';
  2. import { describe, test } from 'node:test';
  3. import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js';
  4. import * as borsh from 'borsh';
  5. import { start } from 'solana-bankrun';
  6. describe('custom-instruction-data', async () => {
  7. const PROGRAM_ID = PublicKey.unique();
  8. const context = await start([{ name: 'processing_instructions_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 InstructionData extends Assignable {
  19. toBuffer() {
  20. return Buffer.from(borsh.serialize(InstructionDataSchema, this));
  21. }
  22. }
  23. const InstructionDataSchema = new Map([
  24. [
  25. InstructionData,
  26. {
  27. kind: 'struct',
  28. fields: [
  29. ['name', 'string'],
  30. ['height', 'u32'],
  31. ],
  32. },
  33. ],
  34. ]);
  35. test('Go to the park!', async () => {
  36. const blockhash = context.lastBlockhash;
  37. const jimmy = new InstructionData({
  38. name: 'Jimmy',
  39. height: 3,
  40. });
  41. const mary = new InstructionData({
  42. name: 'Mary',
  43. height: 10,
  44. });
  45. const ix1 = new TransactionInstruction({
  46. keys: [{ pubkey: payer.publicKey, isSigner: true, isWritable: true }],
  47. programId: PROGRAM_ID,
  48. data: jimmy.toBuffer(),
  49. });
  50. const ix2 = new TransactionInstruction({
  51. ...ix1,
  52. data: mary.toBuffer(),
  53. });
  54. const tx = new Transaction();
  55. tx.recentBlockhash = blockhash;
  56. tx.add(ix1).add(ix2).sign(payer);
  57. await client.processTransaction(tx);
  58. });
  59. });