account.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. import camelCase from "camelcase";
  2. import EventEmitter from "eventemitter3";
  3. import * as bs58 from "bs58";
  4. import {
  5. Signer,
  6. PublicKey,
  7. SystemProgram,
  8. TransactionInstruction,
  9. Commitment,
  10. } from "@solana/web3.js";
  11. import Provider from "../../provider";
  12. import { Idl, IdlTypeDef } from "../../idl";
  13. import Coder, {
  14. ACCOUNT_DISCRIMINATOR_SIZE,
  15. accountDiscriminator,
  16. accountSize,
  17. } from "../../coder";
  18. import { Subscription, Address, translateAddress } from "../common";
  19. import { getProvider } from "../../";
  20. import { AllAccountsMap, IdlTypes, TypeDef } from "./types";
  21. import * as pubkeyUtil from "../../utils/pubkey";
  22. export default class AccountFactory {
  23. public static build<IDL extends Idl>(
  24. idl: IDL,
  25. coder: Coder,
  26. programId: PublicKey,
  27. provider: Provider
  28. ): AccountNamespace<IDL> {
  29. const accountFns: AccountNamespace = {};
  30. idl.accounts.forEach((idlAccount) => {
  31. const name = camelCase(idlAccount.name);
  32. accountFns[name] = new AccountClient<IDL>(
  33. idl,
  34. idlAccount,
  35. programId,
  36. provider,
  37. coder
  38. );
  39. });
  40. return accountFns as AccountNamespace<IDL>;
  41. }
  42. }
  43. /**
  44. * The namespace provides handles to an [[AccountClient]] object for each
  45. * account in a program.
  46. *
  47. * ## Usage
  48. *
  49. * ```javascript
  50. * account.<account-client>
  51. * ```
  52. *
  53. * ## Example
  54. *
  55. * To fetch a `Counter` account from the above example,
  56. *
  57. * ```javascript
  58. * const counter = await program.account.counter.fetch(address);
  59. * ```
  60. *
  61. * For the full API, see the [[AccountClient]] reference.
  62. */
  63. export type AccountNamespace<IDL extends Idl = Idl> = {
  64. [M in keyof AllAccountsMap<IDL>]: AccountClient<IDL>
  65. }
  66. export class AccountClient<
  67. IDL extends Idl = Idl,
  68. A extends IDL["accounts"][number] = IDL["accounts"][number],
  69. T = TypeDef<A, IdlTypes<IDL>>
  70. > {
  71. /**
  72. * Returns the number of bytes in this account.
  73. */
  74. get size(): number {
  75. return this._size;
  76. }
  77. private _size: number;
  78. /**
  79. * Returns the program ID owning all accounts.
  80. */
  81. get programId(): PublicKey {
  82. return this._programId;
  83. }
  84. private _programId: PublicKey;
  85. /**
  86. * Returns the client's wallet and network provider.
  87. */
  88. get provider(): Provider {
  89. return this._provider;
  90. }
  91. private _provider: Provider;
  92. /**
  93. * Returns the coder.
  94. */
  95. get coder(): Coder {
  96. return this._coder;
  97. }
  98. private _coder: Coder;
  99. private _idlAccount: A;
  100. constructor(
  101. idl: IDL,
  102. idlAccount: A,
  103. programId: PublicKey,
  104. provider?: Provider,
  105. coder?: Coder
  106. ) {
  107. this._idlAccount = idlAccount;
  108. this._programId = programId;
  109. this._provider = provider ?? getProvider();
  110. this._coder = coder ?? new Coder(idl);
  111. this._size = ACCOUNT_DISCRIMINATOR_SIZE + accountSize(idl, idlAccount);
  112. }
  113. /**
  114. * Returns a deserialized account.
  115. *
  116. * @param address The address of the account to fetch.
  117. */
  118. async fetch(address: Address): Promise<T> {
  119. const accountInfo = await this._provider.connection.getAccountInfo(
  120. translateAddress(address)
  121. );
  122. if (accountInfo === null) {
  123. throw new Error(`Account does not exist ${address.toString()}`);
  124. }
  125. // Assert the account discriminator is correct.
  126. const discriminator = await accountDiscriminator(this._idlAccount.name);
  127. if (discriminator.compare(accountInfo.data.slice(0, 8))) {
  128. throw new Error("Invalid account discriminator");
  129. }
  130. return this._coder.accounts.decode<T>(
  131. this._idlAccount.name,
  132. accountInfo.data
  133. );
  134. }
  135. /**
  136. * Returns all instances of this account type for the program.
  137. */
  138. async all(filter?: Buffer): Promise<ProgramAccount<T>[]> {
  139. let bytes = await accountDiscriminator(this._idlAccount.name);
  140. if (filter !== undefined) {
  141. bytes = Buffer.concat([bytes, filter]);
  142. }
  143. let resp = await this._provider.connection.getProgramAccounts(
  144. this._programId,
  145. {
  146. commitment: this._provider.connection.commitment,
  147. filters: [
  148. {
  149. memcmp: {
  150. offset: 0,
  151. bytes: bs58.encode(bytes),
  152. },
  153. },
  154. ],
  155. }
  156. );
  157. return resp.map(({ pubkey, account }) => {
  158. return {
  159. publicKey: pubkey,
  160. account: this._coder.accounts.decode(
  161. this._idlAccount.name,
  162. account.data
  163. ),
  164. };
  165. });
  166. }
  167. /**
  168. * Returns an `EventEmitter` emitting a "change" event whenever the account
  169. * changes.
  170. */
  171. subscribe(address: Address, commitment?: Commitment): EventEmitter {
  172. if (subscriptions.get(address.toString())) {
  173. return subscriptions.get(address.toString()).ee;
  174. }
  175. const ee = new EventEmitter();
  176. address = translateAddress(address);
  177. const listener = this._provider.connection.onAccountChange(
  178. address,
  179. (acc) => {
  180. const account = this._coder.accounts.decode(
  181. this._idlAccount.name,
  182. acc.data
  183. );
  184. ee.emit("change", account);
  185. },
  186. commitment
  187. );
  188. subscriptions.set(address.toString(), {
  189. ee,
  190. listener,
  191. });
  192. return ee;
  193. }
  194. /**
  195. * Unsubscribes from the account at the given address.
  196. */
  197. unsubscribe(address: Address) {
  198. let sub = subscriptions.get(address.toString());
  199. if (!sub) {
  200. console.warn("Address is not subscribed");
  201. return;
  202. }
  203. if (subscriptions) {
  204. this._provider.connection
  205. .removeAccountChangeListener(sub.listener)
  206. .then(() => {
  207. subscriptions.delete(address.toString());
  208. })
  209. .catch(console.error);
  210. }
  211. }
  212. /**
  213. * Returns an instruction for creating this account.
  214. */
  215. async createInstruction(
  216. signer: Signer,
  217. sizeOverride?: number
  218. ): Promise<TransactionInstruction> {
  219. const size = this.size;
  220. return SystemProgram.createAccount({
  221. fromPubkey: this._provider.wallet.publicKey,
  222. newAccountPubkey: signer.publicKey,
  223. space: sizeOverride ?? size,
  224. lamports: await this._provider.connection.getMinimumBalanceForRentExemption(
  225. sizeOverride ?? size
  226. ),
  227. programId: this._programId,
  228. });
  229. }
  230. /**
  231. * Function returning the associated account. Args are keys to associate.
  232. * Order matters.
  233. */
  234. async associated(...args: Array<PublicKey | Buffer>): Promise<T> {
  235. const addr = await this.associatedAddress(...args);
  236. return await this.fetch(addr);
  237. }
  238. /**
  239. * Function returning the associated address. Args are keys to associate.
  240. * Order matters.
  241. */
  242. async associatedAddress(
  243. ...args: Array<PublicKey | Buffer>
  244. ): Promise<PublicKey> {
  245. return await pubkeyUtil.associated(this._programId, ...args);
  246. }
  247. }
  248. /**
  249. * @hidden
  250. *
  251. * Deserialized account owned by a program.
  252. */
  253. export type ProgramAccount<T = any> = {
  254. publicKey: PublicKey;
  255. account: T;
  256. };
  257. // Tracks all subscriptions.
  258. const subscriptions: Map<string, Subscription> = new Map();