anchor/ts/src/workspace.ts

56 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-01-02 22:40:17 -08:00
import camelCase from "camelcase";
2021-01-04 23:59:52 -08:00
import { PublicKey } from "@solana/web3.js";
import { Program } from "./program";
2021-01-02 22:40:17 -08:00
let _populatedWorkspace = false;
// Workspace program discovery only works for node environments.
export default new Proxy({} as any, {
2021-01-04 23:59:52 -08:00
get(workspaceCache: { [key: string]: Program }, programName: string) {
const find = require("find");
const fs = require("fs");
const process = require("process");
if (typeof window !== "undefined") {
// Workspaces aren't available in the browser, yet.
return undefined;
2021-01-04 23:59:52 -08:00
}
if (!_populatedWorkspace) {
const path = require("path");
let projectRoot = process.cwd();
while (!fs.existsSync(path.join(projectRoot, "Anchor.toml"))) {
const parentDir = path.dirname(projectRoot);
if (parentDir === projectRoot) {
projectRoot = undefined;
}
projectRoot = parentDir;
}
if (projectRoot === undefined) {
2021-01-02 22:40:17 -08:00
throw new Error(
2021-01-04 23:59:52 -08:00
"Could not find workspace root. Perhaps set the `OASIS_WORKSPACE` env var?"
2021-01-02 22:40:17 -08:00
);
}
2021-01-04 23:59:52 -08:00
find
.fileSync(/target\/idl\/.*\.json/, projectRoot)
.reduce((programs: any, path: string) => {
const idlStr = fs.readFileSync(path);
const idl = JSON.parse(idlStr);
const name = camelCase(idl.name, { pascalCase: true });
programs[name] = new Program(
idl,
new PublicKey(idl.metadata.address)
2021-01-02 22:40:17 -08:00
);
2021-01-04 23:59:52 -08:00
return programs;
}, workspaceCache);
2021-01-02 22:40:17 -08:00
2021-01-04 23:59:52 -08:00
_populatedWorkspace = true;
}
2021-01-02 22:40:17 -08:00
2021-01-04 23:59:52 -08:00
return workspaceCache[programName];
},
});