rpc.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. import camelCase from "camelcase";
  2. import EventEmitter from "eventemitter3";
  3. import * as bs58 from "bs58";
  4. import {
  5. Account,
  6. AccountMeta,
  7. PublicKey,
  8. ConfirmOptions,
  9. SystemProgram,
  10. Transaction,
  11. TransactionSignature,
  12. TransactionInstruction,
  13. SYSVAR_RENT_PUBKEY,
  14. Commitment,
  15. } from "@solana/web3.js";
  16. import Provider from "./provider";
  17. import {
  18. Idl,
  19. IdlAccount,
  20. IdlInstruction,
  21. IdlAccountItem,
  22. IdlStateMethod,
  23. } from "./idl";
  24. import { IdlError, ProgramError } from "./error";
  25. import Coder, {
  26. ACCOUNT_DISCRIMINATOR_SIZE,
  27. accountDiscriminator,
  28. stateDiscriminator,
  29. accountSize,
  30. } from "./coder";
  31. /**
  32. * Dynamically generated rpc namespace.
  33. */
  34. export interface Rpcs {
  35. [key: string]: RpcFn;
  36. }
  37. /**
  38. * Dynamically generated instruction namespace.
  39. */
  40. export interface Ixs {
  41. [key: string]: IxFn;
  42. }
  43. /**
  44. * Dynamically generated transaction namespace.
  45. */
  46. export interface Txs {
  47. [key: string]: TxFn;
  48. }
  49. /**
  50. * Accounts is a dynamically generated object to fetch any given account
  51. * of a program.
  52. */
  53. export interface Accounts {
  54. [key: string]: AccountFn;
  55. }
  56. /**
  57. * RpcFn is a single rpc method generated from an IDL.
  58. */
  59. export type RpcFn = (...args: any[]) => Promise<TransactionSignature>;
  60. /**
  61. * Ix is a function to create a `TransactionInstruction` generated from an IDL.
  62. */
  63. export type IxFn = IxProps & ((...args: any[]) => any);
  64. type IxProps = {
  65. accounts: (ctx: RpcAccounts) => any;
  66. };
  67. /**
  68. * Tx is a function to create a `Transaction` generate from an IDL.
  69. */
  70. export type TxFn = (...args: any[]) => Transaction;
  71. /**
  72. * Account is a function returning a deserialized account, given an address.
  73. */
  74. export type AccountFn<T = any> = AccountProps & ((address: PublicKey) => T);
  75. /**
  76. * Deserialized account owned by a program.
  77. */
  78. export type ProgramAccount<T = any> = {
  79. publicKey: PublicKey;
  80. account: T;
  81. };
  82. /**
  83. * Non function properties on the acccount namespace.
  84. */
  85. type AccountProps = {
  86. size: number;
  87. all: (filter?: Buffer) => Promise<ProgramAccount<any>[]>;
  88. subscribe: (address: PublicKey, commitment?: Commitment) => EventEmitter;
  89. unsubscribe: (address: PublicKey) => void;
  90. createInstruction: (account: Account) => Promise<TransactionInstruction>;
  91. associated: (...args: PublicKey[]) => Promise<any>;
  92. associatedAddress: (...args: PublicKey[]) => Promise<PublicKey>;
  93. };
  94. /**
  95. * Options for an RPC invocation.
  96. */
  97. export type RpcOptions = ConfirmOptions;
  98. /**
  99. * RpcContext provides all arguments for an RPC/IX invocation that are not
  100. * covered by the instruction enum.
  101. */
  102. type RpcContext = {
  103. // Accounts the instruction will use.
  104. accounts?: RpcAccounts;
  105. remainingAccounts?: AccountMeta[];
  106. // Instructions to run *before* the specified rpc instruction.
  107. instructions?: TransactionInstruction[];
  108. // Accounts that must sign the transaction.
  109. signers?: Array<Account>;
  110. // RpcOptions.
  111. options?: RpcOptions;
  112. __private?: { logAccounts: boolean };
  113. };
  114. /**
  115. * Dynamic object representing a set of accounts given to an rpc/ix invocation.
  116. * The name of each key should match the name for that account in the IDL.
  117. */
  118. type RpcAccounts = {
  119. [key: string]: PublicKey | RpcAccounts;
  120. };
  121. export type State = () =>
  122. | Promise<any>
  123. | {
  124. address: () => Promise<PublicKey>;
  125. rpc: Rpcs;
  126. instruction: Ixs;
  127. subscribe: (address: PublicKey, commitment?: Commitment) => EventEmitter;
  128. unsubscribe: (address: PublicKey) => void;
  129. };
  130. // Tracks all subscriptions.
  131. const subscriptions: Map<string, Subscription> = new Map();
  132. /**
  133. * RpcFactory builds an Rpcs object for a given IDL.
  134. */
  135. export class RpcFactory {
  136. /**
  137. * build dynamically generates RPC methods.
  138. *
  139. * @returns an object with all the RPC methods attached.
  140. */
  141. public static build(
  142. idl: Idl,
  143. coder: Coder,
  144. programId: PublicKey,
  145. provider: Provider
  146. ): [Rpcs, Ixs, Txs, Accounts, State] {
  147. const idlErrors = parseIdlErrors(idl);
  148. const rpcs: Rpcs = {};
  149. const ixFns: Ixs = {};
  150. const txFns: Txs = {};
  151. const state = RpcFactory.buildState(
  152. idl,
  153. coder,
  154. programId,
  155. idlErrors,
  156. provider
  157. );
  158. idl.instructions.forEach((idlIx) => {
  159. const name = camelCase(idlIx.name);
  160. // Function to create a raw `TransactionInstruction`.
  161. const ix = RpcFactory.buildIx(idlIx, coder, programId);
  162. // Ffnction to create a `Transaction`.
  163. const tx = RpcFactory.buildTx(idlIx, ix);
  164. // Function to invoke an RPC against a cluster.
  165. const rpc = RpcFactory.buildRpc(idlIx, tx, idlErrors, provider);
  166. rpcs[name] = rpc;
  167. ixFns[name] = ix;
  168. txFns[name] = tx;
  169. });
  170. const accountFns = idl.accounts
  171. ? RpcFactory.buildAccounts(idl, coder, programId, provider)
  172. : {};
  173. return [rpcs, ixFns, txFns, accountFns, state];
  174. }
  175. // Builds the state namespace.
  176. private static buildState(
  177. idl: Idl,
  178. coder: Coder,
  179. programId: PublicKey,
  180. idlErrors: Map<number, string>,
  181. provider: Provider
  182. ): State | undefined {
  183. if (idl.state === undefined) {
  184. return undefined;
  185. }
  186. // Fetches the state object from the blockchain.
  187. const state = async (): Promise<any> => {
  188. const addr = await programStateAddress(programId);
  189. const accountInfo = await provider.connection.getAccountInfo(addr);
  190. if (accountInfo === null) {
  191. throw new Error(`Account does not exist ${addr.toString()}`);
  192. }
  193. // Assert the account discriminator is correct.
  194. const expectedDiscriminator = await stateDiscriminator(
  195. idl.state.struct.name
  196. );
  197. if (expectedDiscriminator.compare(accountInfo.data.slice(0, 8))) {
  198. throw new Error("Invalid account discriminator");
  199. }
  200. return coder.state.decode(accountInfo.data);
  201. };
  202. // Namespace with all rpc functions.
  203. const rpc: Rpcs = {};
  204. const ix: Ixs = {};
  205. idl.state.methods.forEach((m: IdlStateMethod) => {
  206. const accounts = async (accounts: RpcAccounts): Promise<any> => {
  207. const keys = await stateInstructionKeys(
  208. programId,
  209. provider,
  210. m,
  211. accounts
  212. );
  213. return keys.concat(RpcFactory.accountsArray(accounts, m.accounts));
  214. };
  215. const ixFn = async (...args: any[]): Promise<TransactionInstruction> => {
  216. const [ixArgs, ctx] = splitArgsAndCtx(m, [...args]);
  217. return new TransactionInstruction({
  218. keys: await accounts(ctx.accounts),
  219. programId,
  220. data: coder.instruction.encodeState(
  221. m.name,
  222. toInstruction(m, ...ixArgs)
  223. ),
  224. });
  225. };
  226. ixFn["accounts"] = accounts;
  227. ix[m.name] = ixFn;
  228. rpc[m.name] = async (...args: any[]): Promise<TransactionSignature> => {
  229. const [_, ctx] = splitArgsAndCtx(m, [...args]);
  230. const tx = new Transaction();
  231. if (ctx.instructions !== undefined) {
  232. tx.add(...ctx.instructions);
  233. }
  234. tx.add(await ix[m.name](...args));
  235. try {
  236. const txSig = await provider.send(tx, ctx.signers, ctx.options);
  237. return txSig;
  238. } catch (err) {
  239. let translatedErr = translateError(idlErrors, err);
  240. if (translatedErr === null) {
  241. throw err;
  242. }
  243. throw translatedErr;
  244. }
  245. };
  246. });
  247. state["rpc"] = rpc;
  248. state["instruction"] = ix;
  249. // Calculates the address of the program's global state object account.
  250. state["address"] = async (): Promise<PublicKey> =>
  251. programStateAddress(programId);
  252. // Subscription singleton.
  253. let sub: null | Subscription = null;
  254. // Subscribe to account changes.
  255. state["subscribe"] = (commitment?: Commitment): EventEmitter => {
  256. if (sub !== null) {
  257. return sub.ee;
  258. }
  259. const ee = new EventEmitter();
  260. state["address"]().then((address) => {
  261. const listener = provider.connection.onAccountChange(
  262. address,
  263. (acc) => {
  264. const account = coder.state.decode(acc.data);
  265. ee.emit("change", account);
  266. },
  267. commitment
  268. );
  269. sub = {
  270. ee,
  271. listener,
  272. };
  273. });
  274. return ee;
  275. };
  276. // Unsubscribe from account changes.
  277. state["unsubscribe"] = () => {
  278. if (sub !== null) {
  279. provider.connection
  280. .removeAccountChangeListener(sub.listener)
  281. .then(async () => {
  282. sub = null;
  283. })
  284. .catch(console.error);
  285. }
  286. };
  287. return state;
  288. }
  289. // Builds the instuction namespace.
  290. private static buildIx(
  291. idlIx: IdlInstruction,
  292. coder: Coder,
  293. programId: PublicKey
  294. ): IxFn {
  295. if (idlIx.name === "_inner") {
  296. throw new IdlError("the _inner name is reserved");
  297. }
  298. const ix = (...args: any[]): TransactionInstruction => {
  299. const [ixArgs, ctx] = splitArgsAndCtx(idlIx, [...args]);
  300. validateAccounts(idlIx.accounts, ctx.accounts);
  301. validateInstruction(idlIx, ...args);
  302. const keys = RpcFactory.accountsArray(ctx.accounts, idlIx.accounts);
  303. if (ctx.remainingAccounts !== undefined) {
  304. keys.push(...ctx.remainingAccounts);
  305. }
  306. if (ctx.__private && ctx.__private.logAccounts) {
  307. console.log("Outgoing account metas:", keys);
  308. }
  309. return new TransactionInstruction({
  310. keys,
  311. programId,
  312. data: coder.instruction.encode(
  313. idlIx.name,
  314. toInstruction(idlIx, ...ixArgs)
  315. ),
  316. });
  317. };
  318. // Utility fn for ordering the accounts for this instruction.
  319. ix["accounts"] = (accs: RpcAccounts) => {
  320. return RpcFactory.accountsArray(accs, idlIx.accounts);
  321. };
  322. return ix;
  323. }
  324. private static accountsArray(
  325. ctx: RpcAccounts,
  326. accounts: IdlAccountItem[]
  327. ): any {
  328. return accounts
  329. .map((acc: IdlAccountItem) => {
  330. // Nested accounts.
  331. // @ts-ignore
  332. const nestedAccounts: IdlAccountItem[] | undefined = acc.accounts;
  333. if (nestedAccounts !== undefined) {
  334. const rpcAccs = ctx[acc.name] as RpcAccounts;
  335. return RpcFactory.accountsArray(rpcAccs, nestedAccounts).flat();
  336. } else {
  337. const account: IdlAccount = acc as IdlAccount;
  338. return {
  339. pubkey: ctx[acc.name],
  340. isWritable: account.isMut,
  341. isSigner: account.isSigner,
  342. };
  343. }
  344. })
  345. .flat();
  346. }
  347. // Builds the rpc namespace.
  348. private static buildRpc(
  349. idlIx: IdlInstruction,
  350. txFn: TxFn,
  351. idlErrors: Map<number, string>,
  352. provider: Provider
  353. ): RpcFn {
  354. const rpc = async (...args: any[]): Promise<TransactionSignature> => {
  355. const tx = txFn(...args);
  356. const [_, ctx] = splitArgsAndCtx(idlIx, [...args]);
  357. try {
  358. const txSig = await provider.send(tx, ctx.signers, ctx.options);
  359. return txSig;
  360. } catch (err) {
  361. console.log("Translating error", err);
  362. let translatedErr = translateError(idlErrors, err);
  363. if (translatedErr === null) {
  364. throw err;
  365. }
  366. throw translatedErr;
  367. }
  368. };
  369. return rpc;
  370. }
  371. // Builds the transaction namespace.
  372. private static buildTx(idlIx: IdlInstruction, ixFn: IxFn): TxFn {
  373. const txFn = (...args: any[]): Transaction => {
  374. const [_, ctx] = splitArgsAndCtx(idlIx, [...args]);
  375. const tx = new Transaction();
  376. if (ctx.instructions !== undefined) {
  377. tx.add(...ctx.instructions);
  378. }
  379. tx.add(ixFn(...args));
  380. return tx;
  381. };
  382. return txFn;
  383. }
  384. // Returns the generated accounts namespace.
  385. private static buildAccounts(
  386. idl: Idl,
  387. coder: Coder,
  388. programId: PublicKey,
  389. provider: Provider
  390. ): Accounts {
  391. const accountFns: Accounts = {};
  392. idl.accounts.forEach((idlAccount) => {
  393. const name = camelCase(idlAccount.name);
  394. // Fetches the decoded account from the network.
  395. const accountsNamespace = async (address: PublicKey): Promise<any> => {
  396. const accountInfo = await provider.connection.getAccountInfo(address);
  397. if (accountInfo === null) {
  398. throw new Error(`Account does not exist ${address.toString()}`);
  399. }
  400. // Assert the account discriminator is correct.
  401. const discriminator = await accountDiscriminator(idlAccount.name);
  402. if (discriminator.compare(accountInfo.data.slice(0, 8))) {
  403. throw new Error("Invalid account discriminator");
  404. }
  405. return coder.accounts.decode(idlAccount.name, accountInfo.data);
  406. };
  407. // Returns the size of the account.
  408. // @ts-ignore
  409. accountsNamespace["size"] =
  410. ACCOUNT_DISCRIMINATOR_SIZE + accountSize(idl, idlAccount);
  411. // Returns an instruction for creating this account.
  412. // @ts-ignore
  413. accountsNamespace["createInstruction"] = async (
  414. account: Account,
  415. sizeOverride?: number
  416. ): Promise<TransactionInstruction> => {
  417. // @ts-ignore
  418. const size = accountsNamespace["size"];
  419. return SystemProgram.createAccount({
  420. fromPubkey: provider.wallet.publicKey,
  421. newAccountPubkey: account.publicKey,
  422. space: sizeOverride ?? size,
  423. lamports: await provider.connection.getMinimumBalanceForRentExemption(
  424. sizeOverride ?? size
  425. ),
  426. programId,
  427. });
  428. };
  429. // Subscribes to all changes to this account.
  430. // @ts-ignore
  431. accountsNamespace["subscribe"] = (
  432. address: PublicKey,
  433. commitment?: Commitment
  434. ): EventEmitter => {
  435. if (subscriptions.get(address.toString())) {
  436. return subscriptions.get(address.toString()).ee;
  437. }
  438. const ee = new EventEmitter();
  439. const listener = provider.connection.onAccountChange(
  440. address,
  441. (acc) => {
  442. const account = coder.accounts.decode(idlAccount.name, acc.data);
  443. ee.emit("change", account);
  444. },
  445. commitment
  446. );
  447. subscriptions.set(address.toString(), {
  448. ee,
  449. listener,
  450. });
  451. return ee;
  452. };
  453. // Unsubscribes to account changes.
  454. // @ts-ignore
  455. accountsNamespace["unsubscribe"] = (address: PublicKey) => {
  456. let sub = subscriptions.get(address.toString());
  457. if (!sub) {
  458. console.warn("Address is not subscribed");
  459. return;
  460. }
  461. if (subscriptions) {
  462. provider.connection
  463. .removeAccountChangeListener(sub.listener)
  464. .then(() => {
  465. subscriptions.delete(address.toString());
  466. })
  467. .catch(console.error);
  468. }
  469. };
  470. // Returns all instances of this account type for the program.
  471. // @ts-ignore
  472. accountsNamespace["all"] = async (
  473. filter?: Buffer
  474. ): Promise<ProgramAccount<any>[]> => {
  475. let bytes = await accountDiscriminator(idlAccount.name);
  476. if (filter !== undefined) {
  477. bytes = Buffer.concat([bytes, filter]);
  478. }
  479. // @ts-ignore
  480. let resp = await provider.connection._rpcRequest("getProgramAccounts", [
  481. programId.toBase58(),
  482. {
  483. commitment: provider.connection.commitment,
  484. filters: [
  485. {
  486. memcmp: {
  487. offset: 0,
  488. bytes: bs58.encode(bytes),
  489. },
  490. },
  491. ],
  492. },
  493. ]);
  494. if (resp.error) {
  495. console.error(resp);
  496. throw new Error("Failed to get accounts");
  497. }
  498. return (
  499. resp.result
  500. // @ts-ignore
  501. .map(({ pubkey, account: { data } }) => {
  502. data = bs58.decode(data);
  503. return {
  504. publicKey: new PublicKey(pubkey),
  505. account: coder.accounts.decode(idlAccount.name, data),
  506. };
  507. })
  508. );
  509. };
  510. // Function returning the associated address. Args are keys to associate.
  511. // Order matters.
  512. accountsNamespace["associatedAddress"] = async (
  513. ...args: PublicKey[]
  514. ): Promise<PublicKey> => {
  515. let seeds = [Buffer.from([97, 110, 99, 104, 111, 114])]; // b"anchor".
  516. args.forEach((arg) => {
  517. seeds.push(arg.toBuffer());
  518. });
  519. const [assoc] = await PublicKey.findProgramAddress(seeds, programId);
  520. return assoc;
  521. };
  522. // Function returning the associated account. Args are keys to associate.
  523. // Order matters.
  524. accountsNamespace["associated"] = async (
  525. ...args: PublicKey[]
  526. ): Promise<any> => {
  527. const addr = await accountsNamespace["associatedAddress"](...args);
  528. return await accountsNamespace(addr);
  529. };
  530. accountFns[name] = accountsNamespace;
  531. });
  532. return accountFns;
  533. }
  534. }
  535. type Subscription = {
  536. listener: number;
  537. ee: EventEmitter;
  538. };
  539. function translateError(
  540. idlErrors: Map<number, string>,
  541. err: any
  542. ): Error | null {
  543. // TODO: don't rely on the error string. web3.js should preserve the error
  544. // code information instead of giving us an untyped string.
  545. let components = err.toString().split("custom program error: ");
  546. if (components.length === 2) {
  547. try {
  548. const errorCode = parseInt(components[1]);
  549. let errorMsg = idlErrors.get(errorCode);
  550. if (errorMsg === undefined) {
  551. // Unexpected error code so just throw the untranslated error.
  552. return null;
  553. }
  554. return new ProgramError(errorCode, errorMsg);
  555. } catch (parseErr) {
  556. // Unable to parse the error. Just return the untranslated error.
  557. return null;
  558. }
  559. }
  560. }
  561. function parseIdlErrors(idl: Idl): Map<number, string> {
  562. const errors = new Map();
  563. if (idl.errors) {
  564. idl.errors.forEach((e) => {
  565. let msg = e.msg ?? e.name;
  566. errors.set(e.code, msg);
  567. });
  568. }
  569. return errors;
  570. }
  571. function splitArgsAndCtx(
  572. idlIx: IdlInstruction,
  573. args: any[]
  574. ): [any[], RpcContext] {
  575. let options = {};
  576. const inputLen = idlIx.args ? idlIx.args.length : 0;
  577. if (args.length > inputLen) {
  578. if (args.length !== inputLen + 1) {
  579. throw new Error("provided too many arguments ${args}");
  580. }
  581. options = args.pop();
  582. }
  583. return [args, options];
  584. }
  585. // Allow either IdLInstruction or IdlStateMethod since the types share fields.
  586. function toInstruction(idlIx: IdlInstruction | IdlStateMethod, ...args: any[]) {
  587. if (idlIx.args.length != args.length) {
  588. throw new Error("Invalid argument length");
  589. }
  590. const ix: { [key: string]: any } = {};
  591. let idx = 0;
  592. idlIx.args.forEach((ixArg) => {
  593. ix[ixArg.name] = args[idx];
  594. idx += 1;
  595. });
  596. return ix;
  597. }
  598. // Throws error if any account required for the `ix` is not given.
  599. function validateAccounts(ixAccounts: IdlAccountItem[], accounts: RpcAccounts) {
  600. ixAccounts.forEach((acc) => {
  601. // @ts-ignore
  602. if (acc.accounts !== undefined) {
  603. // @ts-ignore
  604. validateAccounts(acc.accounts, accounts[acc.name]);
  605. } else {
  606. if (accounts[acc.name] === undefined) {
  607. throw new Error(`Invalid arguments: ${acc.name} not provided.`);
  608. }
  609. }
  610. });
  611. }
  612. // Throws error if any argument required for the `ix` is not given.
  613. function validateInstruction(ix: IdlInstruction, ...args: any[]) {
  614. // todo
  615. }
  616. // Calculates the deterministic address of the program's "state" account.
  617. async function programStateAddress(programId: PublicKey): Promise<PublicKey> {
  618. let [registrySigner, _nonce] = await PublicKey.findProgramAddress(
  619. [],
  620. programId
  621. );
  622. return PublicKey.createWithSeed(registrySigner, "unversioned", programId);
  623. }
  624. // Returns the common keys that are prepended to all instructions targeting
  625. // the "state" of a program.
  626. async function stateInstructionKeys(
  627. programId: PublicKey,
  628. provider: Provider,
  629. m: IdlStateMethod,
  630. accounts: RpcAccounts
  631. ) {
  632. if (m.name === "new") {
  633. // Ctor `new` method.
  634. const [programSigner, _nonce] = await PublicKey.findProgramAddress(
  635. [],
  636. programId
  637. );
  638. return [
  639. {
  640. pubkey: provider.wallet.publicKey,
  641. isWritable: false,
  642. isSigner: true,
  643. },
  644. {
  645. pubkey: await programStateAddress(programId),
  646. isWritable: true,
  647. isSigner: false,
  648. },
  649. { pubkey: programSigner, isWritable: false, isSigner: false },
  650. {
  651. pubkey: SystemProgram.programId,
  652. isWritable: false,
  653. isSigner: false,
  654. },
  655. { pubkey: programId, isWritable: false, isSigner: false },
  656. {
  657. pubkey: SYSVAR_RENT_PUBKEY,
  658. isWritable: false,
  659. isSigner: false,
  660. },
  661. ];
  662. } else {
  663. validateAccounts(m.accounts, accounts);
  664. return [
  665. {
  666. pubkey: await programStateAddress(programId),
  667. isWritable: true,
  668. isSigner: false,
  669. },
  670. ];
  671. }
  672. }