UNPKG

@bbachain/cli-config

Version:

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

69 lines 2.71 kB
import { Connection, Keypair } from "@bbachain/web3.js"; import { readFileSync, writeFileSync } from "fs"; import { homedir } from "os"; import { parse, stringify } from "yaml"; export const 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; } export 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(BBACHAIN_CLI_CONFIG_RAW_DEFAULT); } static load(path = BBAChainCliConfig.DEFAULT_PATH) { const raw = parse(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 `---` writeFileSync(path, stringify(raw, { directives: true }), { encoding: "utf-8", flag: overwrite ? "w" : "wx", }); } loadKeypair() { return Keypair.fromSecretKey(Buffer.from(JSON.parse(readFileSync(this.keypairPath, { encoding: "utf-8" })))); } createConnection() { return new Connection(this.jsonRpcUrl, { commitment: this.commitment, wsEndpoint: this.websocketUrl, }); } } BBAChainCliConfig.DEFAULT_PATH = `${homedir()}/.bbachain/cli/config.yml`; //# sourceMappingURL=index.js.map