test.ts 1.9 KB

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