transaction.spec.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import TransactionFactory from "../src/program/namespace/transaction";
  2. import InstructionFactory from "../src/program/namespace/instruction";
  3. import { BorshCoder } from "../src";
  4. import { PublicKey, TransactionInstruction } from "@solana/web3.js";
  5. describe("Transaction", () => {
  6. const preIx = new TransactionInstruction({
  7. keys: [],
  8. programId: PublicKey.default,
  9. data: Buffer.from("pre"),
  10. });
  11. const postIx = new TransactionInstruction({
  12. keys: [],
  13. programId: PublicKey.default,
  14. data: Buffer.from("post"),
  15. });
  16. const idl = {
  17. version: "0.0.0",
  18. name: "basic_0",
  19. instructions: [
  20. {
  21. name: "initialize",
  22. accounts: [],
  23. args: [],
  24. },
  25. ],
  26. };
  27. it("should add pre instructions before method ix", async () => {
  28. const coder = new BorshCoder(idl);
  29. const programId = PublicKey.default;
  30. const ixItem = InstructionFactory.build(
  31. idl.instructions[0],
  32. (ixName, ix) => coder.instruction.encode(ixName, ix),
  33. programId
  34. );
  35. const txItem = TransactionFactory.build(idl.instructions[0], ixItem);
  36. const tx = txItem({ accounts: {}, preInstructions: [preIx] });
  37. expect(tx.instructions.length).toBe(2);
  38. expect(tx.instructions[0]).toMatchObject(preIx);
  39. });
  40. it("should add post instructions after method ix", async () => {
  41. const coder = new BorshCoder(idl);
  42. const programId = PublicKey.default;
  43. const ixItem = InstructionFactory.build(
  44. idl.instructions[0],
  45. (ixName, ix) => coder.instruction.encode(ixName, ix),
  46. programId
  47. );
  48. const txItem = TransactionFactory.build(idl.instructions[0], ixItem);
  49. const tx = txItem({ accounts: {}, postInstructions: [postIx] });
  50. expect(tx.instructions.length).toBe(2);
  51. expect(tx.instructions[1]).toMatchObject(postIx);
  52. });
  53. it("should throw error if both preInstructions and instructions are used", async () => {
  54. const coder = new BorshCoder(idl);
  55. const programId = PublicKey.default;
  56. const ixItem = InstructionFactory.build(
  57. idl.instructions[0],
  58. (ixName, ix) => coder.instruction.encode(ixName, ix),
  59. programId
  60. );
  61. const txItem = TransactionFactory.build(idl.instructions[0], ixItem);
  62. expect(() =>
  63. txItem({ accounts: {}, preInstructions: [preIx], instructions: [preIx] })
  64. ).toThrow(new Error("instructions is deprecated, use preInstructions"));
  65. });
  66. });