transaction.ts 1.5 KB

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