transaction.spec.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. layoutVersion: "0.1.0",
  18. version: "0.0.0",
  19. name: "basic_0",
  20. instructions: [
  21. {
  22. name: "initialize",
  23. accounts: [],
  24. args: [],
  25. },
  26. ],
  27. };
  28. it("should add pre instructions before method ix", async () => {
  29. const coder = new BorshCoder(idl);
  30. const programId = PublicKey.default;
  31. const ixItem = InstructionFactory.build(
  32. idl.instructions[0],
  33. (ixName, ix) => coder.instruction.encode(ixName, ix),
  34. programId
  35. );
  36. const txItem = TransactionFactory.build(idl.instructions[0], ixItem);
  37. const tx = txItem({ accounts: {}, preInstructions: [preIx] });
  38. expect(tx.instructions.length).toBe(2);
  39. expect(tx.instructions[0]).toMatchObject(preIx);
  40. });
  41. it("should add post instructions after method ix", async () => {
  42. const coder = new BorshCoder(idl);
  43. const programId = PublicKey.default;
  44. const ixItem = InstructionFactory.build(
  45. idl.instructions[0],
  46. (ixName, ix) => coder.instruction.encode(ixName, ix),
  47. programId
  48. );
  49. const txItem = TransactionFactory.build(idl.instructions[0], ixItem);
  50. const tx = txItem({ accounts: {}, postInstructions: [postIx] });
  51. expect(tx.instructions.length).toBe(2);
  52. expect(tx.instructions[1]).toMatchObject(postIx);
  53. });
  54. it("should throw error if both preInstructions and instructions are used", async () => {
  55. const coder = new BorshCoder(idl);
  56. const programId = PublicKey.default;
  57. const ixItem = InstructionFactory.build(
  58. idl.instructions[0],
  59. (ixName, ix) => coder.instruction.encode(ixName, ix),
  60. programId
  61. );
  62. const txItem = TransactionFactory.build(idl.instructions[0], ixItem);
  63. expect(() =>
  64. txItem({ accounts: {}, preInstructions: [preIx], instructions: [preIx] })
  65. ).toThrow(new Error("instructions is deprecated, use preInstructions"));
  66. });
  67. });