Skip to content

Commit

Permalink
Merge pull request #9 from PFC-developer/feat/priv_key_env
Browse files Browse the repository at this point in the history
feat: allow keys to be read from environment variables,
  • Loading branch information
ALPAC-4 authored Sep 12, 2024
2 parents 5cb282b + 963cff5 commit 38cad68
Showing 1 changed file with 59 additions and 14 deletions.
73 changes: 59 additions & 14 deletions src/lib/chainPair.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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
}
Expand Down

0 comments on commit 38cad68

Please sign in to comment.