From 963cff5cbde2f7e46fe49e17ea4b16adf0fe11c3 Mon Sep 17 00:00:00 2001 From: PFC <81114960+PFC-developer@users.noreply.github.com> Date: Mon, 9 Sep 2024 17:31:56 -0500 Subject: [PATCH] feat: allow keys to be read from environment variables, and allow different key types to be created --- src/lib/chainPair.ts | 73 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 59 insertions(+), 14 deletions(-) diff --git a/src/lib/chainPair.ts b/src/lib/chainPair.ts index 374e076..d07ee59 100644 --- a/src/lib/chainPair.ts +++ b/src/lib/chainPair.ts @@ -1,19 +1,13 @@ -import { MnemonicKey, RawKey } from '@initia/initia.js' +import { Key, MnemonicKey, RawKey } from '@initia/initia.js' import { Chain } from 'src/chain' import { SyncInfo } from 'src/chain/types' +import { env } from 'node:process' export async function runPair( config: ConfigPair ): Promise<{ name: string; chainA: Chain; chainB: Chain }> { - const keyA = - config.chainA.key.type === 'mnemonic' - ? new MnemonicKey({ mnemonic: config.chainA.key.privateKey }) - : new RawKey(Buffer.from(config.chainA.key.privateKey, 'hex')) - - const keyB = - config.chainB.key.type === 'mnemonic' - ? new MnemonicKey({ mnemonic: config.chainB.key.privateKey }) - : new RawKey(Buffer.from(config.chainB.key.privateKey, 'hex')) + const keyA = createKey(config.chainA.key) + const keyB = createKey(config.chainB.key) const chainA = await Chain.init({ ...config.chainA, @@ -35,16 +29,67 @@ export async function runPair( } } +function createKey(rawKey: ChainRawKeyConfig): Key { + let keyReturn + switch (rawKey.type) { + case 'mnemonic': { + const options = rawKey.options || {} + + keyReturn = new MnemonicKey({ mnemonic: rawKey.privateKey, ...options }) + break + } + case 'env_mnemonic': { + const key = env[rawKey.privateKey] + if (!key) { + throw Error(`missing environment ${rawKey.privateKey}`) + } + const options = rawKey.options || {} + + keyReturn = new MnemonicKey({ mnemonic: key, ...options }) + break + } + case 'raw': { + keyReturn = new RawKey(Buffer.from(rawKey.privateKey, 'hex')) + break + } + case 'env_raw': { + const key = env[rawKey.privateKey] + if (!key) { + throw Error(`missing environment ${rawKey.privateKey}`) + } + keyReturn = new RawKey(Buffer.from(key, 'hex')) + break + } + } + return keyReturn +} + +interface ChainRawKeyConfig { + type: 'raw' | 'mnemonic' | 'env_raw' | 'env_mnemonic' + privateKey: string + /** + * for mnemonic type keys only + */ + options?: { + account?: number + /** + * BIP44 index number + */ + index?: number + /** + * Coin type. Default is INIT, 118. + */ + coinType?: number + } +} + interface ChainRawConfig { bech32Prefix: string chainId: string gasPrice: string lcdUri: string rpcUri: string - key: { - type: 'raw' | 'mnemonic' - privateKey: string - } + key: ChainRawKeyConfig connectionId: string syncInfo?: SyncInfo // if syncInfo file exists, ignore start height }