rpc.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { TransactionSignature } from "@solana/web3.js";
  2. import Provider from "../../provider.js";
  3. import { Idl } from "../../idl.js";
  4. import { splitArgsAndCtx } from "../context.js";
  5. import { TransactionFn } from "./transaction.js";
  6. import { ProgramError } from "../../error.js";
  7. import * as features from "../../utils/features.js";
  8. import {
  9. AllInstructions,
  10. InstructionContextFn,
  11. MakeInstructionsNamespace,
  12. } from "./types.js";
  13. export default class RpcFactory {
  14. public static build<IDL extends Idl, I extends AllInstructions<IDL>>(
  15. idlIx: I,
  16. txFn: TransactionFn<IDL, I>,
  17. idlErrors: Map<number, string>,
  18. provider: Provider
  19. ): RpcFn {
  20. const rpc: RpcFn<IDL, I> = async (...args) => {
  21. const tx = txFn(...args);
  22. const [, ctx] = splitArgsAndCtx(idlIx, [...args]);
  23. try {
  24. const txSig = await provider.send(tx, ctx.signers, ctx.options);
  25. return txSig;
  26. } catch (err) {
  27. if (features.isSet("debug-logs")) {
  28. console.log("Translating error:", err);
  29. }
  30. let translatedErr = ProgramError.parse(err, idlErrors);
  31. if (translatedErr === null) {
  32. throw err;
  33. }
  34. throw translatedErr;
  35. }
  36. };
  37. return rpc;
  38. }
  39. }
  40. /**
  41. * The namespace provides async methods to send signed transactions for each
  42. * *non*-state method on Anchor program.
  43. *
  44. * Keys are method names, values are RPC functions returning a
  45. * [[TransactionInstruction]].
  46. *
  47. * ## Usage
  48. *
  49. * ```javascript
  50. * rpc.<method>(...args, ctx);
  51. * ```
  52. *
  53. * ## Parameters
  54. *
  55. * 1. `args` - The positional arguments for the program. The type and number
  56. * of these arguments depend on the program being used.
  57. * 2. `ctx` - [[Context]] non-argument parameters to pass to the method.
  58. * Always the last parameter in the method call.
  59. * ```
  60. *
  61. * ## Example
  62. *
  63. * To send a transaction invoking the `increment` method above,
  64. *
  65. * ```javascript
  66. * const txSignature = await program.rpc.increment({
  67. * accounts: {
  68. * counter,
  69. * authority,
  70. * },
  71. * });
  72. * ```
  73. */
  74. export type RpcNamespace<
  75. IDL extends Idl = Idl,
  76. I extends AllInstructions<IDL> = AllInstructions<IDL>
  77. > = MakeInstructionsNamespace<IDL, I, Promise<TransactionSignature>>;
  78. /**
  79. * RpcFn is a single RPC method generated from an IDL, sending a transaction
  80. * paid for and signed by the configured provider.
  81. */
  82. export type RpcFn<
  83. IDL extends Idl = Idl,
  84. I extends AllInstructions<IDL> = AllInstructions<IDL>
  85. > = InstructionContextFn<IDL, I, Promise<TransactionSignature>>;