index.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import { inflate } from "pako";
  2. import { PublicKey } from "@solana/web3.js";
  3. import Provider, { getProvider } from "../provider.js";
  4. import { Idl, idlAddress, decodeIdlAccount } from "../idl.js";
  5. import { Coder, BorshCoder } from "../coder/index.js";
  6. import NamespaceFactory, {
  7. RpcNamespace,
  8. InstructionNamespace,
  9. TransactionNamespace,
  10. AccountNamespace,
  11. StateClient,
  12. SimulateNamespace,
  13. MethodsNamespace,
  14. ViewNamespace,
  15. } from "./namespace/index.js";
  16. import { utf8 } from "../utils/bytes/index.js";
  17. import { EventManager } from "./event.js";
  18. import { Address, translateAddress } from "./common.js";
  19. export * from "./common.js";
  20. export * from "./context.js";
  21. export * from "./event.js";
  22. export * from "./namespace/index.js";
  23. /**
  24. * ## Program
  25. *
  26. * Program provides the IDL deserialized client representation of an Anchor
  27. * program.
  28. *
  29. * This API is the one stop shop for all things related to communicating with
  30. * on-chain programs. Among other things, one can send transactions, fetch
  31. * deserialized accounts, decode instruction data, subscribe to account
  32. * changes, and listen to events.
  33. *
  34. * In addition to field accessors and methods, the object provides a set of
  35. * dynamically generated properties, also known as namespaces, that
  36. * map one-to-one to program methods and accounts. These namespaces generally
  37. * can be used as follows:
  38. *
  39. * ## Usage
  40. *
  41. * ```javascript
  42. * program.<namespace>.<program-specific-method>
  43. * ```
  44. *
  45. * API specifics are namespace dependent. The examples used in the documentation
  46. * below will refer to the two counter examples found
  47. * [here](https://github.com/project-serum/anchor#examples).
  48. */
  49. export class Program<IDL extends Idl = Idl> {
  50. /**
  51. * Async methods to send signed transactions to *non*-state methods on the
  52. * program, returning a [[TransactionSignature]].
  53. *
  54. * ## Usage
  55. *
  56. * ```javascript
  57. * rpc.<method>(...args, ctx);
  58. * ```
  59. *
  60. * ## Parameters
  61. *
  62. * 1. `args` - The positional arguments for the program. The type and number
  63. * of these arguments depend on the program being used.
  64. * 2. `ctx` - [[Context]] non-argument parameters to pass to the method.
  65. * Always the last parameter in the method call.
  66. *
  67. * ## Example
  68. *
  69. * To send a transaction invoking the `increment` method above,
  70. *
  71. * ```javascript
  72. * const txSignature = await program.rpc.increment({
  73. * accounts: {
  74. * counter,
  75. * authority,
  76. * },
  77. * });
  78. * ```
  79. * @deprecated
  80. */
  81. readonly rpc: RpcNamespace<IDL>;
  82. /**
  83. * The namespace provides handles to an [[AccountClient]] object for each
  84. * account in the program.
  85. *
  86. * ## Usage
  87. *
  88. * ```javascript
  89. * program.account.<account-client>
  90. * ```
  91. *
  92. * ## Example
  93. *
  94. * To fetch a `Counter` account from the above example,
  95. *
  96. * ```javascript
  97. * const counter = await program.account.counter.fetch(address);
  98. * ```
  99. *
  100. * For the full API, see the [[AccountClient]] reference.
  101. */
  102. readonly account: AccountNamespace<IDL>;
  103. /**
  104. * The namespace provides functions to build [[TransactionInstruction]]
  105. * objects for each method of a program.
  106. *
  107. * ## Usage
  108. *
  109. * ```javascript
  110. * program.instruction.<method>(...args, ctx);
  111. * ```
  112. *
  113. * ## Parameters
  114. *
  115. * 1. `args` - The positional arguments for the program. The type and number
  116. * of these arguments depend on the program being used.
  117. * 2. `ctx` - [[Context]] non-argument parameters to pass to the method.
  118. * Always the last parameter in the method call.
  119. *
  120. * ## Example
  121. *
  122. * To create an instruction for the `increment` method above,
  123. *
  124. * ```javascript
  125. * const tx = await program.instruction.increment({
  126. * accounts: {
  127. * counter,
  128. * },
  129. * });
  130. * ```
  131. * @deprecated
  132. */
  133. readonly instruction: InstructionNamespace<IDL>;
  134. /**
  135. * The namespace provides functions to build [[Transaction]] objects for each
  136. * method of a program.
  137. *
  138. * ## Usage
  139. *
  140. * ```javascript
  141. * program.transaction.<method>(...args, ctx);
  142. * ```
  143. *
  144. * ## Parameters
  145. *
  146. * 1. `args` - The positional arguments for the program. The type and number
  147. * of these arguments depend on the program being used.
  148. * 2. `ctx` - [[Context]] non-argument parameters to pass to the method.
  149. * Always the last parameter in the method call.
  150. *
  151. * ## Example
  152. *
  153. * To create an instruction for the `increment` method above,
  154. *
  155. * ```javascript
  156. * const tx = await program.transaction.increment({
  157. * accounts: {
  158. * counter,
  159. * },
  160. * });
  161. * ```
  162. * @deprecated
  163. */
  164. readonly transaction: TransactionNamespace<IDL>;
  165. /**
  166. * The namespace provides functions to simulate transactions for each method
  167. * of a program, returning a list of deserialized events *and* raw program
  168. * logs.
  169. *
  170. * One can use this to read data calculated from a program on chain, by
  171. * emitting an event in the program and reading the emitted event client side
  172. * via the `simulate` namespace.
  173. *
  174. * ## simulate
  175. *
  176. * ```javascript
  177. * program.simulate.<method>(...args, ctx);
  178. * ```
  179. *
  180. * ## Parameters
  181. *
  182. * 1. `args` - The positional arguments for the program. The type and number
  183. * of these arguments depend on the program being used.
  184. * 2. `ctx` - [[Context]] non-argument parameters to pass to the method.
  185. * Always the last parameter in the method call.
  186. *
  187. * ## Example
  188. *
  189. * To simulate the `increment` method above,
  190. *
  191. * ```javascript
  192. * const events = await program.simulate.increment({
  193. * accounts: {
  194. * counter,
  195. * },
  196. * });
  197. * ```
  198. * @deprecated
  199. */
  200. readonly simulate: SimulateNamespace<IDL>;
  201. /**
  202. * A client for the program state. Similar to the base [[Program]] client,
  203. * one can use this to send transactions and read accounts for the state
  204. * abstraction.
  205. */
  206. readonly state?: StateClient<IDL>;
  207. /**
  208. * The namespace provides a builder API for all APIs on the program.
  209. * This is an alternative to using namespace the other namespaces..
  210. */
  211. readonly methods: MethodsNamespace<IDL>;
  212. readonly views?: ViewNamespace<IDL>;
  213. /**
  214. * Address of the program.
  215. */
  216. public get programId(): PublicKey {
  217. return this._programId;
  218. }
  219. private _programId: PublicKey;
  220. /**
  221. * IDL defining the program's interface.
  222. */
  223. public get idl(): IDL {
  224. return this._idl;
  225. }
  226. private _idl: IDL;
  227. /**
  228. * Coder for serializing requests.
  229. */
  230. public get coder(): Coder {
  231. return this._coder;
  232. }
  233. private _coder: Coder;
  234. /**
  235. * Wallet and network provider.
  236. */
  237. public get provider(): Provider {
  238. return this._provider;
  239. }
  240. private _provider: Provider;
  241. /**
  242. * Handles event subscriptions.
  243. */
  244. private _events: EventManager;
  245. /**
  246. * @param idl The interface definition.
  247. * @param programId The on-chain address of the program.
  248. * @param provider The network and wallet context to use. If not provided
  249. * then uses [[getProvider]].
  250. */
  251. public constructor(
  252. idl: IDL,
  253. programId: Address,
  254. provider?: Provider,
  255. coder?: Coder
  256. ) {
  257. programId = translateAddress(programId);
  258. if (!provider) {
  259. provider = getProvider();
  260. }
  261. // Fields.
  262. this._idl = idl;
  263. this._provider = provider;
  264. this._programId = programId;
  265. this._coder = coder ?? new BorshCoder(idl);
  266. this._events = new EventManager(this._programId, provider, this._coder);
  267. // Dynamic namespaces.
  268. const [
  269. rpc,
  270. instruction,
  271. transaction,
  272. account,
  273. simulate,
  274. methods,
  275. state,
  276. views,
  277. ] = NamespaceFactory.build(idl, this._coder, programId, provider);
  278. this.rpc = rpc;
  279. this.instruction = instruction;
  280. this.transaction = transaction;
  281. this.account = account;
  282. this.simulate = simulate;
  283. this.methods = methods;
  284. this.state = state;
  285. this.views = views;
  286. }
  287. /**
  288. * Generates a Program client by fetching the IDL from the network.
  289. *
  290. * In order to use this method, an IDL must have been previously initialized
  291. * via the anchor CLI's `anchor idl init` command.
  292. *
  293. * @param programId The on-chain address of the program.
  294. * @param provider The network and wallet context.
  295. */
  296. public static async at<IDL extends Idl = Idl>(
  297. address: Address,
  298. provider?: Provider
  299. ): Promise<Program<IDL>> {
  300. const programId = translateAddress(address);
  301. const idl = await Program.fetchIdl<IDL>(programId, provider);
  302. if (!idl) {
  303. throw new Error(`IDL not found for program: ${address.toString()}`);
  304. }
  305. return new Program(idl, programId, provider);
  306. }
  307. /**
  308. * Fetches an idl from the blockchain.
  309. *
  310. * In order to use this method, an IDL must have been previously initialized
  311. * via the anchor CLI's `anchor idl init` command.
  312. *
  313. * @param programId The on-chain address of the program.
  314. * @param provider The network and wallet context.
  315. */
  316. public static async fetchIdl<IDL extends Idl = Idl>(
  317. address: Address,
  318. provider?: Provider
  319. ): Promise<IDL | null> {
  320. provider = provider ?? getProvider();
  321. const programId = translateAddress(address);
  322. const idlAddr = await idlAddress(programId);
  323. const accountInfo = await provider.connection.getAccountInfo(idlAddr);
  324. if (!accountInfo) {
  325. return null;
  326. }
  327. // Chop off account discriminator.
  328. let idlAccount = decodeIdlAccount(accountInfo.data.slice(8));
  329. const inflatedIdl = inflate(idlAccount.data);
  330. return JSON.parse(utf8.decode(inflatedIdl));
  331. }
  332. /**
  333. * Invokes the given callback every time the given event is emitted.
  334. *
  335. * @param eventName The PascalCase name of the event, provided by the IDL.
  336. * @param callback The function to invoke whenever the event is emitted from
  337. * program logs.
  338. */
  339. public addEventListener(
  340. eventName: string,
  341. callback: (event: any, slot: number) => void
  342. ): number {
  343. return this._events.addEventListener(eventName, callback);
  344. }
  345. /**
  346. * Unsubscribes from the given eventName.
  347. */
  348. public async removeEventListener(listener: number): Promise<void> {
  349. return await this._events.removeEventListener(listener);
  350. }
  351. }