Browse Source

ts: Add fetchMultiple to compliment rpc getMultiple (#761)

Dana Hanna 4 years ago
parent
commit
d40400fff2
1 changed files with 29 additions and 0 deletions
  1. 29 0
      ts/src/program/namespace/account.ts

+ 29 - 0
ts/src/program/namespace/account.ts

@@ -18,6 +18,7 @@ import Coder, {
 import { Subscription, Address, translateAddress } from "../common";
 import { getProvider } from "../../";
 import * as pubkeyUtil from "../../utils/pubkey";
+import * as rpcUtil from "../../utils/rpc";
 
 export default class AccountFactory {
   public static build(
@@ -152,6 +153,34 @@ export class AccountClient<T = any> {
     return data;
   }
 
+  /**
+   * Returns multiple deserialized accounts.
+   * Accounts not found or with wrong discriminator are returned as null.
+   *
+   * @param addresses The addresses of the accounts to fetch.
+   */
+  async fetchMultiple(addresses: Address[]): Promise<(Object | null)[]> {
+    const accounts = await rpcUtil.getMultipleAccounts(
+      this._provider.connection,
+      addresses.map((address) => translateAddress(address))
+    );
+
+    const discriminator = await accountDiscriminator(this._idlAccount.name);
+    // Decode accounts where discriminator is correct, null otherwise
+    return accounts.map((account) => {
+      if (account == null) {
+        return null;
+      }
+      if (discriminator.compare(account?.account.data.slice(0, 8))) {
+        return null;
+      }
+      return this._coder.accounts.decode(
+        this._idlAccount.name,
+        account?.account.data
+      );
+    });
+  }
+
   /**
    * Returns all instances of this account type for the program.
    */