transaction.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Transaction } from "@solana/web3.js";
  2. import { Idl, IdlInstruction } from "../../idl";
  3. import { splitArgsAndCtx } from "../context";
  4. import { InstructionFn } from "./instruction";
  5. import {
  6. AllInstructions,
  7. InstructionContextFn,
  8. MakeInstructionsNamespace,
  9. } from "./types";
  10. export default class TransactionFactory {
  11. public static build<IDL extends Idl, I extends AllInstructions<IDL>>(
  12. idlIx: I,
  13. ixFn: InstructionFn<IDL, I>
  14. ): TransactionFn<IDL, I> {
  15. const txFn: TransactionFn<IDL, I> = (...args): Transaction => {
  16. const [, ctx] = splitArgsAndCtx(idlIx, [...args]);
  17. const tx = new Transaction();
  18. if (ctx.instructions !== undefined) {
  19. tx.add(...ctx.instructions);
  20. }
  21. tx.add(ixFn(...args));
  22. return tx;
  23. };
  24. return txFn;
  25. }
  26. }
  27. /**
  28. * The namespace provides functions to build [[Transaction]] objects for each
  29. * method of a program.
  30. *
  31. * ## Usage
  32. *
  33. * ```javascript
  34. * program.transaction.<method>(...args, ctx);
  35. * ```
  36. *
  37. * ## Parameters
  38. *
  39. * 1. `args` - The positional arguments for the program. The type and number
  40. * of these arguments depend on the program being used.
  41. * 2. `ctx` - [[Context]] non-argument parameters to pass to the method.
  42. * Always the last parameter in the method call.
  43. *
  44. * ## Example
  45. *
  46. * To create an instruction for the `increment` method above,
  47. *
  48. * ```javascript
  49. * const tx = await program.transaction.increment({
  50. * accounts: {
  51. * counter,
  52. * },
  53. * });
  54. * ```
  55. */
  56. export type TransactionNamespace<
  57. IDL extends Idl = Idl,
  58. I extends AllInstructions<IDL> = AllInstructions<IDL>
  59. > = MakeInstructionsNamespace<IDL, I, Transaction>;
  60. /**
  61. * Tx is a function to create a `Transaction` for a given program instruction.
  62. */
  63. export type TransactionFn<
  64. IDL extends Idl = Idl,
  65. I extends AllInstructions<IDL> = AllInstructions<IDL>
  66. > = InstructionContextFn<IDL, I, Transaction>;