utils.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import * as bs58 from "bs58";
  2. import { sha256 } from "crypto-hash";
  3. import assert from "assert";
  4. import { PublicKey, AccountInfo, Connection } from "@solana/web3.js";
  5. import { idlAddress } from "./idl";
  6. export const TOKEN_PROGRAM_ID = new PublicKey(
  7. "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
  8. );
  9. async function getMultipleAccounts(
  10. connection: Connection,
  11. publicKeys: PublicKey[]
  12. ): Promise<
  13. Array<null | { publicKey: PublicKey; account: AccountInfo<Buffer> }>
  14. > {
  15. const args = [publicKeys.map((k) => k.toBase58()), { commitment: "recent" }];
  16. // @ts-ignore
  17. const res = await connection._rpcRequest("getMultipleAccounts", args);
  18. if (res.error) {
  19. throw new Error(
  20. "failed to get info about accounts " +
  21. publicKeys.map((k) => k.toBase58()).join(", ") +
  22. ": " +
  23. res.error.message
  24. );
  25. }
  26. assert(typeof res.result !== "undefined");
  27. const accounts: Array<null | {
  28. executable: any;
  29. owner: PublicKey;
  30. lamports: any;
  31. data: Buffer;
  32. }> = [];
  33. for (const account of res.result.value) {
  34. let value: {
  35. executable: any;
  36. owner: PublicKey;
  37. lamports: any;
  38. data: Buffer;
  39. } | null = null;
  40. if (account === null) {
  41. accounts.push(null);
  42. continue;
  43. }
  44. if (res.result.value) {
  45. const { executable, owner, lamports, data } = account;
  46. assert(data[1] === "base64");
  47. value = {
  48. executable,
  49. owner: new PublicKey(owner),
  50. lamports,
  51. data: Buffer.from(data[0], "base64"),
  52. };
  53. }
  54. if (value === null) {
  55. throw new Error("Invalid response");
  56. }
  57. accounts.push(value);
  58. }
  59. return accounts.map((account, idx) => {
  60. if (account === null) {
  61. return null;
  62. }
  63. return {
  64. publicKey: publicKeys[idx],
  65. account,
  66. };
  67. });
  68. }
  69. const utils = {
  70. bs58,
  71. sha256,
  72. getMultipleAccounts,
  73. idlAddress,
  74. };
  75. export default utils;