@simbachain/web3-suites
Version:
common code for web3 suite plugins. Code in this repo can be used for truffle or hardhat, but is designed to be applicable to future web3 suite plugins as well.
826 lines • 34.4 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimbaConfig = exports.simbaEnvFilesArray = exports.EnvVariableKeys = exports.AllDirs = void 0;
const fs = __importStar(require("fs"));
const logger_1 = require("./logger");
const tslog_1 = require("tslog");
const process_1 = require("process");
const dotenv = __importStar(require("dotenv"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const configstore_1 = __importDefault(require("configstore"));
const authentication_1 = require("./authentication");
const lib_1 = require("../lib");
const simbainfo_1 = require("./simbainfo");
const chalk_1 = __importDefault(require("chalk"));
const axios_1 = __importDefault(require("axios"));
// const fsPromises = require("fs").promises;
var WebThreeSuites;
(function (WebThreeSuites) {
WebThreeSuites["TRUFFLE"] = "truffle";
WebThreeSuites["HARDHAT"] = "hardhat";
})(WebThreeSuites || (WebThreeSuites = {}));
var CompiledDirs;
(function (CompiledDirs) {
CompiledDirs["ARTIFACTS"] = "artifacts";
CompiledDirs["BUILD"] = "build";
})(CompiledDirs || (CompiledDirs = {}));
var AllDirs;
(function (AllDirs) {
AllDirs["BUILDDIRECTORY"] = "buildDirectory";
AllDirs["ARTIFACTDIRECTORY"] = "artifactDirectory";
AllDirs["CONTRACTDIRECTORY"] = "contractDirectory";
})(AllDirs || (exports.AllDirs = AllDirs = {}));
var EnvVariableKeys;
(function (EnvVariableKeys) {
EnvVariableKeys["ID"] = "ID";
EnvVariableKeys["SECRET"] = "SECRET";
EnvVariableKeys["AUTHENDPOINT"] = "ENDPOINT";
EnvVariableKeys["BASE_URL"] = "BASE_URL";
})(EnvVariableKeys || (exports.EnvVariableKeys = EnvVariableKeys = {}));
var SimbaEnvFiles;
(function (SimbaEnvFiles) {
SimbaEnvFiles["DOT_SIMBACHAIN_DOT_ENV"] = ".simbachain.env";
SimbaEnvFiles["SIMBACHAIN_DOT_ENV"] = "simbachain.env";
SimbaEnvFiles["DOT_ENV"] = ".env";
})(SimbaEnvFiles || (SimbaEnvFiles = {}));
// for ordered iteration purposes
exports.simbaEnvFilesArray = [
SimbaEnvFiles.DOT_SIMBACHAIN_DOT_ENV,
SimbaEnvFiles.SIMBACHAIN_DOT_ENV,
SimbaEnvFiles.DOT_ENV,
];
const SIMBA_HOME = process.env.SIMBA_HOME || os.homedir();
/**
* appends /auth onto end of baseurl for authinfo for AuthProviders.KEYCLOAKOAUTH2
* @param authInfo
* @returns
*/
function handleAlternativeAuthJSON(authInfo) {
SimbaConfig.log.debug(`:: ENTER : ${JSON.stringify(authInfo)}`);
const type = authInfo.type;
let newAuthInfo = {};
switch (type) {
case authentication_1.AuthProviders.KEYCLOAKOAUTH2: {
if (authInfo.config) {
newAuthInfo.type = type;
newAuthInfo.realm = authInfo.config.realm;
newAuthInfo.client_id = authInfo.config.key;
const baseurl = authInfo.config.host.endsWith("/auth") ?
authInfo.config.host :
`${authInfo.config.host}/auth`;
newAuthInfo.baseurl = baseurl;
}
break;
}
default: {
newAuthInfo = authInfo;
break;
}
}
SimbaConfig.log.debug(`:: EXIT :`);
return newAuthInfo;
}
/**
* this class handles our configstore operations (eg reading simba.json)
* http operations are handled by our authStore property.
*
* the two main files SimbaConfig manipulates and reads from are simba.json and authconfig.json
*
* If you notice throughout this class, many methods are defined in static
* and instance methods. This was so that some older code that was integrated,
* that uses instance methods, would still be supported.
*/
class SimbaConfig {
/**
* many of these instance properties are not actually uses
* they're just defined here for debugging/logging purposes
*/
constructor() {
const confstore = this.ConfigStore;
const projconfstore = this.ProjectConfigStore;
const app = this.application;
const org = this.organisation;
const authStr = this.authStore;
const buildDir = this.buildDirectory;
const logLevel = this.logLevel;
const log = new tslog_1.Logger({ minLevel: logLevel });
const constructorParams = {
confstore,
projconfstore,
app,
org,
authStr,
buildDir,
logLevel,
};
SimbaConfig.log.debug(`:: ENTER : SimbaConfig constructor params : ${JSON.stringify(constructorParams)}`);
}
/**
* handles our auth / access token info - currently authconfig.json
*/
static get ConfigStore() {
if (!this._configStore) {
this._configStore = new configstore_1.default(`@simbachain/${this._web3Suite}`, null, {
configPath: path.join((0, process_1.cwd)(), 'authconfig.json'),
});
}
return this._configStore;
}
get ConfigStore() {
return SimbaConfig.ConfigStore;
}
/**
* handles project info, contained in simba.json
*/
static get ProjectConfigStore() {
if (!this._projectConfigStore) {
this._projectConfigStore = new configstore_1.default(`@simbachain/${this._web3Suite}`, null, {
configPath: path.join((0, process_1.cwd)(), 'simba.json'),
});
}
return this._projectConfigStore;
}
get ProjectConfigStore() {
return SimbaConfig.ProjectConfigStore;
}
/**
* looks for baseURL in simba.json
* @returns {string | void}
*/
static retrieveBaseAPIURLFromConfigStore() {
SimbaConfig.log.debug(":: ENTER :");
const fullKey = "SIMBA_API_BASE_URL";
let val = SimbaConfig.ProjectConfigStore.get("baseURL") ||
SimbaConfig.ProjectConfigStore.get("baseUrl") ||
SimbaConfig.ProjectConfigStore.get("baseurl") ||
SimbaConfig.ProjectConfigStore.get(fullKey);
if (val) {
SimbaConfig.log.debug(`:: EXIT : ${val}`);
return val;
}
SimbaConfig.log.debug(":: EXIT :");
}
/**
* looks for SIMBA_API_BASE_URL in env vars
* first looks in local project (.simbachain.env, simbachain.env, .env)
* then looks in SIMBA_HOME location, iterating through those same file names
* @returns {string | void}
*/
static retrieveBaseAPIURLFromEnvVars() {
// first check local project
SimbaConfig.log.debug(":: ENTER :");
const fullKey = "SIMBA_API_BASE_URL";
for (let i = 0; i < exports.simbaEnvFilesArray.length; i++) {
const fileName = exports.simbaEnvFilesArray[i];
dotenv.config({
override: true,
path: path.resolve((0, process_1.cwd)(), fileName),
});
const val = process.env[fullKey];
if (val) {
SimbaConfig.log.debug(`:: EXIT : ${val}`);
return val;
}
}
// now we check SIMBA_HOME directory
for (let i = 0; i < exports.simbaEnvFilesArray.length; i++) {
const fileName = exports.simbaEnvFilesArray[i];
dotenv.config({
override: true,
path: path.resolve(SIMBA_HOME, fileName),
});
const val = process.env[fullKey];
if (val) {
SimbaConfig.log.debug(`:: EXIT : ${val}`);
return val;
}
}
SimbaConfig.log.debug(":: EXIT :");
}
/**
* checks simba.json first, then looks for env vars
* @returns {string}
*/
static retrieveBaseAPIURL() {
SimbaConfig.log.debug(":: ENTER :");
let baseURL = this.retrieveBaseAPIURLFromConfigStore();
if (baseURL) {
SimbaConfig.log.debug(`:: EXIT : ${baseURL}`);
return baseURL;
}
baseURL = this.retrieveBaseAPIURLFromEnvVars();
if (baseURL) {
SimbaConfig.log.debug(`:: EXIT : ${baseURL}`);
return baseURL;
}
const message = `Unable to locate a value for either SIMBA_API_BASE_URL or baseURL. We check in the following places:\n1. simba.json for either SIMBA_API_BASE_URL or baseURL\n2. local project root for SIMBA_API_BASE_URL in: .simbachain.env, simbachain.env, or .env\n3. SIMBA_HOME for SIMBA_API_BASE_URL in .simbachain.env, simbachain.env, or .env. If you want to use SIMBA_HOME, then set a desired directory as SIMBA_HOME in your system's environment variables. Then within that specified directory, create one of .simbachain.env, simbachain.env, or .env, and then set SIMBA_API_BASE_URL=<YOUR BASE URL>\n`;
SimbaConfig.log.error(`:: EXIT : ${chalk_1.default.redBright(`${message}`)}`);
throw new Error(message);
}
/**
* this method only gets called once, when a process first tries to retrieve an env var
* if SimbaConfig.envVars's values is zero length, then we call this method
*
* The code is a bit convoluted, so here's the process:
* 1. iterate through file names of (.simbachain.env, simbachain.env, .env) in our project root
* 2. we then loop through each of our simba keys:"ID", "SECRET", "ENDPOINT", and "BASE_URL"
* 3. for each one of those keys, we search for `SIMBA_AUTH_CLIENT_${key}`
* 4. once we have found a value for "ID", "SECRET", "ENDPOINT", and "BASE_URL", based on the above keys that users can actually set (in 3), we return them and set them as SimbaConfig.envVars
* 5. we then run through 1-4 again, but we use SIMBA_HOME instead of project root
* @returns {Promise<Record<any, any>>}
*/
static setEnvVars() {
SimbaConfig.log.debug(`:: ENTER :`);
const foundKeys = [];
// the following shouldn't need to be changed
// has to do with whether authendpoint should be configured, but
// for now this is fine
foundKeys.push("SIMBA_AUTH_CLIENT_ENDPOINT");
SimbaConfig.envVars["SIMBA_AUTH_CLIENT_ENDPOINT"] = "/o/";
// first iterate through local project
// through each file name
// if we have found all our keys, return our object
for (let i = 0; i < exports.simbaEnvFilesArray.length; i++) {
if (foundKeys.length === Object.values(EnvVariableKeys).length) {
SimbaConfig.log.debug(`:: EXIT : ${JSON.stringify(SimbaConfig.envVars)}`);
return SimbaConfig.envVars;
}
const fileName = exports.simbaEnvFilesArray[i];
dotenv.config({
override: true,
path: path.resolve((0, process_1.cwd)(), fileName),
});
for (let j = 0; j < Object.values(EnvVariableKeys).length; j++) {
const envVarKey = Object.values(EnvVariableKeys)[j];
if (envVarKey in foundKeys) {
continue;
}
const simbaKey = `SIMBA_AUTH_CLIENT_${envVarKey}`;
const val = process.env[simbaKey];
if (val) {
SimbaConfig.envVars[simbaKey] = val;
foundKeys.push(envVarKey);
}
}
}
// now same thing in SIMBA_HOME
for (let i = 0; i < exports.simbaEnvFilesArray.length; i++) {
if (foundKeys.length === Object.values(EnvVariableKeys).length) {
SimbaConfig.log.debug(`:: EXIT : ${JSON.stringify(SimbaConfig.envVars)}`);
return SimbaConfig.envVars;
}
const fileName = exports.simbaEnvFilesArray[i];
dotenv.config({
override: true,
path: path.resolve(SIMBA_HOME, fileName),
});
for (let j = 0; j < Object.values(EnvVariableKeys).length; j++) {
const envVarKey = Object.values(EnvVariableKeys)[j];
if (envVarKey in foundKeys) {
continue;
}
const simbaKey = `SIMBA_AUTH_CLIENT_${envVarKey}`;
const val = process.env[simbaKey];
if (val) {
SimbaConfig.envVars[simbaKey] = val;
foundKeys.push(envVarKey);
}
}
}
SimbaConfig.log.debug(`:: EXIT : ${JSON.stringify(SimbaConfig.envVars)}`);
return SimbaConfig.envVars;
}
/**
* retrieves value for env var key. looks for:
* `SIMBA_AUTH_CLIENT_${envVarKey}`
*
* if SimbaConfig.envVars values has zero length, we first call SimbaConfig.setEnvVars
* @param envVarKey
* @returns
*/
static retrieveEnvVar(envVarKey) {
let envVars;
if (!Object.values(SimbaConfig.envVars).length) {
envVars = SimbaConfig.setEnvVars();
}
else {
envVars = SimbaConfig.envVars;
}
const simbaKey = `SIMBA_AUTH_CLIENT_${envVarKey}`;
const val = envVars[simbaKey];
if (val) {
SimbaConfig.log.debug(`:: EXIT : ${envVarKey} : ${val}`);
return val;
}
const message = `Unable to find value for ${simbaKey}. You can set this in one of the following file names: .simbachain.env, simbachain.env, or .env; and these files can live in your local project root (best option) or in the directory that SIMBA_HOME points to in your system env vars.`;
SimbaConfig.log.error(`${chalk_1.default.redBright(`:: EXIT : ${message}`)}`);
throw new Error(message);
}
async retrieveEnvVar(envVarKey) {
SimbaConfig.log.debug(`:: ENTER : envVarKey : ${envVarKey}`);
const val = SimbaConfig.retrieveEnvVar(envVarKey);
SimbaConfig.log.debug(`:: EXIT : `);
return val;
}
/**
* this method is used in the plugins to reset simba.json, but with more control over what exactly gets reset
* @param previousSimbaJson
* @param newOrg
* @param forceReset - basically wipes all of simba.json if true, dependent on value of keepOrgAndApp
* @param keepOrgAndApp
* @returns
*/
static resetSimbaJson(previousSimbaJson, newOrg, forceReset = false, keepOrgAndApp = true) {
const entryParams = {
previousSimbaJson,
newOrg,
forceReset,
keepOrgAndApp,
};
SimbaConfig.log.debug(`:: ENTER : entryParams : ${JSON.stringify(entryParams)}`);
if (forceReset) {
SimbaConfig.log.debug(`:: forcing reset`);
const newSimbaJson = {
baseURL: previousSimbaJson.baseURL,
web3Suite: previousSimbaJson.web3Suite,
logLevel: previousSimbaJson.logLevel ? previousSimbaJson.logLevel : "info",
contracts_info: {},
};
if (previousSimbaJson.authProviderInfo) {
newSimbaJson["authProviderInfo"] = previousSimbaJson.authProviderInfo;
}
if (keepOrgAndApp) {
if (previousSimbaJson.organisation) {
newSimbaJson["organisation"] = previousSimbaJson.organisation;
}
if (previousSimbaJson.application) {
newSimbaJson["application"] = previousSimbaJson.application;
}
}
SimbaConfig.ProjectConfigStore.clear();
SimbaConfig.ProjectConfigStore.set(newSimbaJson);
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
const previousOrg = previousSimbaJson.organisation;
if (!newOrg) {
SimbaConfig.log.debug(`:: EXIT : no new org name specified; no action required`);
return;
}
const previousOrgName = previousSimbaJson.organisation ? previousSimbaJson.organisation.name : null;
const newOrgName = (typeof newOrg === "string") ?
newOrg :
newOrg.name;
if (!previousOrg) {
SimbaConfig.log.debug(`:: EXIT : organisation was not previously set; no action required`);
return;
}
if (previousOrgName !== newOrgName) {
SimbaConfig.log.info(`\nsimba: ${previousOrgName} !== ${newOrgName}; switching orgs, deleting contracts_info`);
SimbaConfig.ProjectConfigStore.set("contracts_info", {});
if (!keepOrgAndApp) {
SimbaConfig.ProjectConfigStore.delete("organisation");
SimbaConfig.ProjectConfigStore.delete("application");
}
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
else {
SimbaConfig.log.debug(`\nsimba: ${previousOrgName} === ${newOrgName}; not switching orgs, no action needed`);
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
}
/**
* used to delete field in simba.json
* @param key
*/
static deleteSimbaJsonField(key) {
SimbaConfig.log.debug(`:: ENTER : key : ${key}`);
if (this.ProjectConfigStore.get(key)) {
this.ProjectConfigStore.delete(key);
SimbaConfig.log.debug(`${chalk_1.default.cyanBright(`key ${key} removed from simba.json`)}`);
}
else {
SimbaConfig.log.debug(`${chalk_1.default.cyanBright(`key ${key} not present in simba.json`)}`);
}
SimbaConfig.log.debug(`:: EXIT :`);
}
deleteSimbaJsonField(key) {
SimbaConfig.deleteSimbaJsonField(key);
}
/**
* deletes authProviderInfo in simba.json
*/
static deleteAuthProviderInfo() {
SimbaConfig.log.debug(`:: ENTER :`);
const key = "authProviderInfo";
SimbaConfig.deleteSimbaJsonField(key);
}
deleteAuthProviderInfo() {
SimbaConfig.deleteAuthProviderInfo();
}
/**
* retrieves and sets authProviderInfo in simba.json, based on our baseAPI (or SIMBA)AUTH_CLIENT_ID or other iteration of key)
* @returns {Promise<any>}
*/
static async setAndGetAuthProviderInfo() {
SimbaConfig.log.debug(`:: ENTER :`);
if (!SimbaConfig.ProjectConfigStore.get("authProviderInfo")) {
const baseURL = SimbaConfig.retrieveBaseAPIURL();
if (!baseURL) {
SimbaConfig.log.error(`${chalk_1.default.redBright(`${authentication_1.authErrors.noBaseURLError}`)}`);
throw new Error(authentication_1.authErrors.noBaseURLError);
}
const authInfoURL = (0, lib_1.buildURL)(baseURL, "/authinfo");
SimbaConfig.log.debug(`:: authInfoURL: ${authInfoURL}`);
try {
const res = await axios_1.default.get(authInfoURL);
let _authProviderInfo = res.data;
_authProviderInfo = handleAlternativeAuthJSON(_authProviderInfo);
SimbaConfig.log.debug(`${chalk_1.default.cyanBright(`\n_authProviderInfo: ${JSON.stringify(_authProviderInfo)}`)}`);
SimbaConfig.ProjectConfigStore.set("authProviderInfo", _authProviderInfo);
return _authProviderInfo;
}
catch (error) {
if (axios_1.default.isAxiosError(error) && error.response) {
if (error.response.status == 404) {
SimbaConfig.log.error(`${chalk_1.default.redBright(`\n:: EXIT : received 404 response for url ${authInfoURL}.`)}`);
}
else {
SimbaConfig.log.error(`${chalk_1.default.redBright(`\nsimba: EXIT : messsage: ${JSON.stringify(error.response.data)}`)}`);
}
}
else {
SimbaConfig.log.error(`${chalk_1.default.redBright(`\nsimba: EXIT : ${JSON.stringify(error)}`)}`);
}
return;
}
}
return SimbaConfig.ProjectConfigStore.get("authProviderInfo");
}
/**
* currently only returns KeycloakHandler, since we no longer use AzureHandler
* @returns {Promise<KeycloakHandler | null>}
*/
static async authStore() {
SimbaConfig.log.debug(`:: ENTER :`);
if (!this._authStore) {
SimbaConfig.log.debug(`${chalk_1.default.cyanBright(`\nsimba: instantiating new authStore`)}`);
const _authProviderInfo = await SimbaConfig.setAndGetAuthProviderInfo();
if (!_authProviderInfo) {
SimbaConfig.log.error(`${chalk_1.default.redBright(authentication_1.authErrors.badAuthProviderInfo)}`);
return null;
}
SimbaConfig.log.debug(`${chalk_1.default.cyanBright(`\nsimba: _authProviderInfo: ${JSON.stringify(_authProviderInfo)}`)}`);
if (!_authProviderInfo) {
SimbaConfig.log.error(`${chalk_1.default.redBright(`\nsimba: no auth provider info detected.`)}`);
}
let authProviderType = _authProviderInfo.type;
switch (authProviderType) {
case authentication_1.AuthProviders.KEYCLOAK: {
this._authStore = new authentication_1.KeycloakHandler(this._configStore, this._projectConfigStore);
break;
}
case authentication_1.AuthProviders.KEYCLOAKOAUTH2: {
this._authStore = new authentication_1.KeycloakHandler(this._configStore, this._projectConfigStore);
break;
}
default: {
SimbaConfig.log.error(`${chalk_1.default.redBright(`\nsimba: a valid auth provider was not found. Deleting authProviderInfo from simba.json. Please make sure your SIMBA_API_BASE_URL is properly configured.`)}`);
SimbaConfig.deleteAuthProviderInfo();
break;
}
}
}
SimbaConfig.log.debug(`:: EXIT :`);
return this._authStore;
}
async authStore() {
return await SimbaConfig.authStore();
}
/**
* if user has modified build, contract, artifact directory for their project,
* then it grabs these and returns them from simba.json
* @returns {Record<any, any>}
*/
static allDirs() {
SimbaConfig.log.debug(`:: ENTER :`);
const dirs = {
buildDirectory: SimbaConfig.buildDirectory,
contractDirectory: SimbaConfig.contractDirectory,
artifactDirectory: SimbaConfig.artifactDirectory,
};
SimbaConfig.log.debug(`:: EXIT : dirs : ${JSON.stringify(dirs)}`);
return dirs;
}
allDirs() {
SimbaConfig.log.debug(`:: ENTER :`);
SimbaConfig.log.debug(`:: EXIT :`);
return SimbaConfig.allDirs();
}
/**
* prints chalked directories
*/
static printChalkedDirs() {
SimbaConfig.log.debug(`:: ENTER :`);
simbainfo_1.SimbaInfo.printChalkedObject(SimbaConfig.allDirs(), "simba directories");
SimbaConfig.log.debug(`:: EXIT :`);
}
printChalkedDirs() {
SimbaConfig.log.debug(`:: ENTER :`);
SimbaConfig.printChalkedDirs();
SimbaConfig.log.debug(`:: EXIT :`);
}
/**
* to determine where compiled contracts are stored, based on web3Suite (hardhat, truffle, etc.)
* @returns {string}
*/
static get artifactDirectory() {
SimbaConfig.log.debug(":: ENTER :");
let artifactPath = this.ProjectConfigStore.get("artifactDirectory");
if (artifactPath) {
this.log.debug(`${chalk_1.default.cyanBright(`simba: artifactDirectory path obtained from simba.json. If you wish to have Simba obtain your artifacts from the default location for your web3 project, then please remove the 'artifactDirectory' field from simba.json.`)}`);
return artifactPath;
}
const web3Suite = (0, lib_1.discoverAndSetWeb3Suite)();
switch (web3Suite) {
case WebThreeSuites.HARDHAT: {
artifactPath = path.join((0, process_1.cwd)(), CompiledDirs.ARTIFACTS);
break;
}
case WebThreeSuites.TRUFFLE: {
artifactPath = path.join((0, process_1.cwd)(), CompiledDirs.BUILD);
break;
}
default: {
SimbaConfig.log.error(lib_1.web3SuiteErrorMessage);
break;
}
}
return artifactPath;
}
get artifactDirectory() {
return SimbaConfig.artifactDirectory;
}
/**
* allows user to override default directories for build, contract, artifact, etc.
* @param dirName
* @param dirPath
* @returns {void}
*/
static setDirectory(dirName, dirPath) {
const entryParams = {
dirName,
dirPath,
};
SimbaConfig.log.debug(`:: ENTER : entryParmas : ${JSON.stringify(entryParams)}`);
switch (dirName) {
case (AllDirs.ARTIFACTDIRECTORY): {
SimbaConfig.artifactDirectory = dirPath;
break;
}
case (AllDirs.BUILDDIRECTORY): {
SimbaConfig.buildDirectory = dirPath;
break;
}
case (AllDirs.CONTRACTDIRECTORY): {
SimbaConfig.contractDirectory = dirPath;
break;
}
default: {
SimbaConfig.log.error(`${chalk_1.default.redBright(`\nsimba: unrecognized directory name: ${dirName}`)}`);
return;
}
}
}
setDirectory(dirName, dirPath) {
const entryParams = {
dirName,
dirPath,
};
SimbaConfig.log.debug(`:: ENTER : entryParmas : ${JSON.stringify(entryParams)}`);
SimbaConfig.setDirectory(dirName, dirPath);
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
/**
* setter for artifactDirectory in simba.json
*/
static set artifactDirectory(dirPath) {
SimbaConfig.log.debug(`:: ENTER : dirPath : ${dirPath}`);
if (dirPath === "reset") {
SimbaConfig.log.info(`${chalk_1.default.cyanBright(`\nsimba: resetting artifactDirectory to default settings`)}`);
SimbaConfig.ProjectConfigStore.delete("artifactDirectory");
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
SimbaConfig.log.info(`${chalk_1.default.cyanBright(`\nsimba: setting artifactDirectory to ${dirPath}`)}`);
SimbaConfig.ProjectConfigStore.set("artifactDirectory", dirPath);
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
set artifactDirectory(dirPath) {
SimbaConfig.log.debug(`:: ENTER : dirPath : ${dirPath}`);
SimbaConfig.artifactDirectory = dirPath;
SimbaConfig.log.debug(`:: EXIT :`);
}
/**
* used for Hardhat, since some build info is stored in separate file from main artifact info
*/
static get buildInfoDirectory() {
SimbaConfig.log.debug(":: ENTER :");
return path.join(SimbaConfig.artifactDirectory, "build-info");
}
get buildInfoDirectory() {
return SimbaConfig.buildInfoDirectory;
}
/**
* getter for buildDirectory
* @returns {string}
*/
static get buildDirectory() {
SimbaConfig.log.debug(":: ENTER :");
let buildDir = this.ProjectConfigStore.get("buildDirectory");
if (buildDir) {
this.log.debug(`${chalk_1.default.cyanBright(`simba: buildDirectory path obtained from simba.json. If you wish to have Simba obtain your build artifacts from the default location for your web3 project, then please remove the 'buildDirectory' field from simba.json.`)}`);
return buildDir;
}
return path.join(SimbaConfig.artifactDirectory, "contracts");
}
get buildDirectory() {
return SimbaConfig.buildDirectory;
}
/**
* setter for buildDirectory in simba.json
*/
static set buildDirectory(dirPath) {
SimbaConfig.log.debug(`:: ENTER : dirPath : ${dirPath}`);
if (dirPath.toLowerCase() === "reset") {
SimbaConfig.log.info(`${chalk_1.default.cyanBright(`\nsimba: resetting buildDirectory to default settings`)}`);
SimbaConfig.ProjectConfigStore.delete("buildDirectory");
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
SimbaConfig.log.info(`${chalk_1.default.cyanBright(`\nsimba: setting buildDirectory to ${dirPath}`)}`);
SimbaConfig.ProjectConfigStore.set("buildDirectory", dirPath);
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
set buildDirectory(dirPath) {
SimbaConfig.log.debug(`:: ENTER : dirPath : ${dirPath}`);
SimbaConfig.buildDirectory = dirPath;
SimbaConfig.log.debug(`:: EXIT :`);
}
/**
* getter for contractDirectory
* Not used in standard flow, since users shouldn't typically modify this value
*/
static get contractDirectory() {
let contractDir = this.ProjectConfigStore.get("contractDirectory");
if (contractDir) {
this.log.debug(`${chalk_1.default.cyanBright(`simba: contractDirectory path obtained from simba.json. If you wish to have Simba obtain your build artifacts from the default location for your web3 project, then please remove the 'contractDirectory' field from simba.json.`)}`);
return contractDir;
}
contractDir = path.join((0, process_1.cwd)(), 'contracts');
if (!fs.existsSync(contractDir)) {
fs.mkdirSync(contractDir, { recursive: true });
}
return path.join((0, process_1.cwd)(), 'contracts');
}
get contractDirectory() {
return SimbaConfig.contractDirectory;
}
/**
* setter for contractDirectory in simba.json
*/
static set contractDirectory(dirPath) {
SimbaConfig.log.debug(`:: ENTER : dirPath : ${dirPath}`);
if (dirPath.toLowerCase() === "reset") {
SimbaConfig.log.info(`${chalk_1.default.cyanBright(`\nsimba: resetting contractDirectory to default settings`)}`);
SimbaConfig.ProjectConfigStore.delete("contractDirectory");
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
SimbaConfig.log.info(`${chalk_1.default.cyanBright(`\nsimba: setting contractDirectory to ${dirPath}`)}`);
SimbaConfig.ProjectConfigStore.set("contractDirectory", dirPath);
SimbaConfig.log.debug(`:: EXIT :`);
return;
}
set contractDirectory(dirPath) {
SimbaConfig.log.debug(`:: ENTER : dirPath : ${dirPath}`);
SimbaConfig.contractDirectory = dirPath;
SimbaConfig.log.debug(`:: EXIT :`);
}
/**
* this is what we use for logging throughout our plugins
* @returns {Logger}
*/
static get log() {
const logLevel = SimbaConfig.logLevel;
const logger = new tslog_1.Logger({ minLevel: logLevel });
return logger;
}
get log() {
return SimbaConfig.log;
}
/**
* how we get loglevel throughout our plugins
* @returns {LogLevel}
*/
static get logLevel() {
let logLevel = this.ProjectConfigStore.get('logLevel') ?
this.ProjectConfigStore.get('logLevel').toLowerCase() :
logger_1.LogLevel.INFO;
if (!Object.values(logger_1.LogLevel).includes(logLevel)) {
logLevel = logger_1.LogLevel.INFO;
}
return logLevel;
}
get logLevel() {
return SimbaConfig.logLevel;
}
/**
* how we set loglevel throughout our plugins
*/
static set logLevel(level) {
const lowerLevel = level.toLowerCase();
if (!Object.values(logger_1.LogLevel).includes(lowerLevel)) {
this.log.error(`${chalk_1.default.redBright(`simba: log level can only be one of: 'error', 'debug', 'info', 'warn', 'fatal', 'silly', 'trace'`)}`);
return;
}
this.ProjectConfigStore.set("logLevel", lowerLevel);
}
set logLevel(level) {
SimbaConfig.logLevel = level;
}
/**
* getter for organisation from our simba.json
*/
static get organisation() {
const org = this.ProjectConfigStore.get('organisation') ? this.ProjectConfigStore.get('organisation') : this.ProjectConfigStore.get('organization');
return org;
}
get organisation() {
return SimbaConfig.organisation;
}
/**
* setter for organisation in simba.json
*/
static set organisation(org) {
this.ProjectConfigStore.set('organisation', org);
}
set organisation(org) {
SimbaConfig.organisation = org;
}
/**
* getter for application in simba.json
* @returns {any}
*/
static get application() {
return this.ProjectConfigStore.get('application');
}
get application() {
return SimbaConfig.application;
}
/**
* setter for application in simba.json
*/
static set application(app) {
this.ProjectConfigStore.set('application', app);
}
set application(app) {
SimbaConfig.application = app;
}
}
exports.SimbaConfig = SimbaConfig;
SimbaConfig.help = false;
SimbaConfig.envVars = {}; // do stuff with this...
//# sourceMappingURL=config.js.map