test.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import {
  2. Connection,
  3. Keypair,
  4. sendAndConfirmTransaction,
  5. Transaction,
  6. TransactionInstruction,
  7. } from '@solana/web3.js';
  8. import * as borsh from "borsh";
  9. import { Buffer } from "buffer";
  10. function createKeypairFromFile(path: string): Keypair {
  11. return Keypair.fromSecretKey(
  12. Buffer.from(JSON.parse(require('fs').readFileSync(path, "utf-8")))
  13. )
  14. };
  15. describe("custom-instruction-data", () => {
  16. const connection = new Connection(`http://localhost:8899`, 'confirmed');
  17. const payer = createKeypairFromFile(require('os').homedir() + '/.config/solana/id.json');
  18. const program = createKeypairFromFile('./program/target/so/program-keypair.json');
  19. class Assignable {
  20. constructor(properties) {
  21. Object.keys(properties).map((key) => {
  22. return (this[key] = properties[key]);
  23. });
  24. };
  25. };
  26. class InstructionData extends Assignable {};
  27. const InstructionDataSchema = new Map([
  28. [
  29. InstructionData, {
  30. kind: 'struct',
  31. fields: [
  32. ['name', 'string'],
  33. ['height', 'u32'],
  34. ]
  35. }
  36. ]
  37. ]);
  38. it("Go to the park!", async () => {
  39. const jimmy = new InstructionData({
  40. name: "Jimmy",
  41. height: 3
  42. });
  43. const mary = new InstructionData({
  44. name: "Mary",
  45. height: 10
  46. });
  47. function toBuffer(obj: InstructionData): Buffer {
  48. return Buffer.from(borsh.serialize(InstructionDataSchema, obj));
  49. }
  50. let ix1 = new TransactionInstruction({
  51. keys: [
  52. {pubkey: payer.publicKey, isSigner: true, isWritable: true}
  53. ],
  54. programId: program.publicKey,
  55. data: toBuffer(jimmy),
  56. });
  57. let ix2 = new TransactionInstruction({
  58. ...ix1,
  59. data: toBuffer(mary),
  60. });
  61. await sendAndConfirmTransaction(
  62. connection,
  63. new Transaction().add(ix1).add(ix2),
  64. [payer]
  65. );
  66. });
  67. });