workspace.ts 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import camelCase from "camelcase";
  2. import * as toml from "toml";
  3. import { PublicKey } from "@solana/web3.js";
  4. import { Program } from "./program/index.js";
  5. import { Idl } from "./idl.js";
  6. import { isBrowser } from "./utils/common.js";
  7. let _populatedWorkspace = false;
  8. /**
  9. * The `workspace` namespace provides a convenience API to automatically
  10. * search for and deserialize [[Program]] objects defined by compiled IDLs
  11. * in an Anchor workspace.
  12. *
  13. * This API is for Node only.
  14. */
  15. const workspace = new Proxy({} as any, {
  16. get(workspaceCache: { [key: string]: Program }, programName: string) {
  17. if (isBrowser) {
  18. throw new Error("Workspaces aren't available in the browser");
  19. }
  20. const fs = require("fs");
  21. const process = require("process");
  22. if (!_populatedWorkspace) {
  23. const path = require("path");
  24. let projectRoot = process.cwd();
  25. while (!fs.existsSync(path.join(projectRoot, "Anchor.toml"))) {
  26. const parentDir = path.dirname(projectRoot);
  27. if (parentDir === projectRoot) {
  28. projectRoot = undefined;
  29. }
  30. projectRoot = parentDir;
  31. }
  32. if (projectRoot === undefined) {
  33. throw new Error("Could not find workspace root.");
  34. }
  35. const idlFolder = `${projectRoot}/target/idl`;
  36. if (!fs.existsSync(idlFolder)) {
  37. throw new Error(
  38. `${idlFolder} doesn't exist. Did you use "anchor build"?`
  39. );
  40. }
  41. const idlMap = new Map<string, Idl>();
  42. fs.readdirSync(idlFolder)
  43. .filter((file) => file.endsWith(".json"))
  44. .forEach((file) => {
  45. const filePath = `${idlFolder}/${file}`;
  46. const idlStr = fs.readFileSync(filePath);
  47. const idl = JSON.parse(idlStr);
  48. idlMap.set(idl.name, idl);
  49. const name = camelCase(idl.name, { pascalCase: true });
  50. if (idl.metadata && idl.metadata.address) {
  51. workspaceCache[name] = new Program(
  52. idl,
  53. new PublicKey(idl.metadata.address)
  54. );
  55. }
  56. });
  57. // Override the workspace programs if the user put them in the config.
  58. const anchorToml = toml.parse(
  59. fs.readFileSync(path.join(projectRoot, "Anchor.toml"), "utf-8")
  60. );
  61. const clusterId = anchorToml.provider.cluster;
  62. if (anchorToml.programs && anchorToml.programs[clusterId]) {
  63. attachWorkspaceOverride(
  64. workspaceCache,
  65. anchorToml.programs[clusterId],
  66. idlMap
  67. );
  68. }
  69. _populatedWorkspace = true;
  70. }
  71. return workspaceCache[programName];
  72. },
  73. });
  74. function attachWorkspaceOverride(
  75. workspaceCache: { [key: string]: Program },
  76. overrideConfig: { [key: string]: string | { address: string; idl?: string } },
  77. idlMap: Map<string, Idl>
  78. ) {
  79. Object.keys(overrideConfig).forEach((programName) => {
  80. const wsProgramName = camelCase(programName, { pascalCase: true });
  81. const entry = overrideConfig[programName];
  82. const overrideAddress = new PublicKey(
  83. typeof entry === "string" ? entry : entry.address
  84. );
  85. let idl = idlMap.get(programName);
  86. if (typeof entry !== "string" && entry.idl) {
  87. idl = JSON.parse(require("fs").readFileSync(entry.idl, "utf-8"));
  88. }
  89. if (!idl) {
  90. throw new Error(`Error loading workspace IDL for ${programName}`);
  91. }
  92. workspaceCache[wsProgramName] = new Program(idl, overrideAddress);
  93. });
  94. }
  95. export default workspace;