UNPKG

@bbachain/cli-config

Version:

Typescript bindings for bbachain's CLI config (originally in Rust)

73 lines 2.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BBAChainCliConfig = exports.BBACHAIN_CLI_CONFIG_RAW_DEFAULT = void 0; const web3_js_1 = require("@bbachain/web3.js"); const fs_1 = require("fs"); const os_1 = require("os"); const yaml_1 = require("yaml"); exports.BBACHAIN_CLI_CONFIG_RAW_DEFAULT = { json_rpc_url: "https://api-mainnet.bbachain.com", websocket_url: "", keypair_path: "~/.bbachain/id.json", address_labels: { "11111111111111111111111111111111": "System Program", }, commitment: "confirmed", }; function deriveWebsocketUrl(jsonRpcUrl) { const url = new URL(jsonRpcUrl); const protocol = url.protocol === "http:" ? "ws:" : "wss:"; const portString = url.port ? `:${Number(url.port) + 1}` : ""; // Note trailing / (IMPORTANT) return `${protocol}//${url.hostname}${portString}/`; } function isDerivedWebsocketUrl(jsonRpcUrl, websocketUrl) { return deriveWebsocketUrl(jsonRpcUrl) === websocketUrl; } class BBAChainCliConfig { constructor({ json_rpc_url, websocket_url, keypair_path, address_labels, commitment, }) { this.jsonRpcUrl = json_rpc_url; this.websocketUrl = websocket_url || deriveWebsocketUrl(this.jsonRpcUrl); this.keypairPath = keypair_path; this.commitment = commitment; this.addressLabels = new Map(Object.entries(address_labels)); } static default() { return new BBAChainCliConfig(exports.BBACHAIN_CLI_CONFIG_RAW_DEFAULT); } static load(path = BBAChainCliConfig.DEFAULT_PATH) { const raw = (0, yaml_1.parse)((0, fs_1.readFileSync)(path, { encoding: "utf-8" })); return new BBAChainCliConfig(raw); } toRaw() { return { json_rpc_url: this.jsonRpcUrl, websocket_url: isDerivedWebsocketUrl(this.jsonRpcUrl, this.websocketUrl) ? "" : this.websocketUrl, keypair_path: this.keypairPath, address_labels: Object.fromEntries(this.addressLabels), commitment: this.commitment, }; } save(path = BBAChainCliConfig.DEFAULT_PATH, overwrite = false) { const raw = this.toRaw(); // directives true to include yaml start-of-doc `---` (0, fs_1.writeFileSync)(path, (0, yaml_1.stringify)(raw, { directives: true }), { encoding: "utf-8", flag: overwrite ? "w" : "wx", }); } loadKeypair() { return web3_js_1.Keypair.fromSecretKey(Buffer.from(JSON.parse((0, fs_1.readFileSync)(this.keypairPath, { encoding: "utf-8" })))); } createConnection() { return new web3_js_1.Connection(this.jsonRpcUrl, { commitment: this.commitment, wsEndpoint: this.websocketUrl, }); } } exports.BBAChainCliConfig = BBAChainCliConfig; BBAChainCliConfig.DEFAULT_PATH = `${(0, os_1.homedir)()}/.bbachain/cli/config.yml`; //# sourceMappingURL=index.js.map