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. toBuffer() {
  28. return Buffer.from(borsh.serialize(InstructionDataSchema, this));
  29. }
  30. };
  31. const InstructionDataSchema = new Map([
  32. [
  33. InstructionData, {
  34. kind: 'struct',
  35. fields: [
  36. ['name', 'string'],
  37. ['height', 'u32'],
  38. ]
  39. }
  40. ]
  41. ]);
  42. it("Go to the park!", async () => {
  43. const jimmy = new InstructionData({
  44. name: "Jimmy",
  45. height: 3
  46. });
  47. const mary = new InstructionData({
  48. name: "Mary",
  49. height: 10
  50. });
  51. let ix1 = new TransactionInstruction({
  52. keys: [
  53. {pubkey: payer.publicKey, isSigner: true, isWritable: true}
  54. ],
  55. programId: program.publicKey,
  56. data: jimmy.toBuffer(),
  57. });
  58. let ix2 = new TransactionInstruction({
  59. ...ix1,
  60. data: mary.toBuffer(),
  61. });
  62. await sendAndConfirmTransaction(
  63. connection,
  64. new Transaction().add(ix1).add(ix2),
  65. [payer]
  66. );
  67. });
  68. });