Import from keystore file
A keystore file is an encrypted version of your private key, often used in web3-enabled applications (e.g. those using ethers.js or web3.js) and in some legacy DEXes or crypto wallets.
ChainGate supports both Web3-compatible keystores (commonly generated via libraries like ethers.js or web3.js) and legacy JSON keystores used in some older crypto applications.
If someone gains access to your keystore and the password, they can control your wallet and funds.
If the keystore contains a BIP39 mnemonic, the result is a PhraseWallet (HD wallet, multiple addresses).
If it contains a raw private key, the result is a PrivateKeyWallet (single address only).
Import from a keystore
Use a keystore file (JSON string) and its password to create a wallet instance. This is the only wallet import function that is async, since decryption is involved:
import { importFromKeystore } from 'chaingate'
const wallet = await importFromKeystore(
'{"version":3,"crypto":{...}}', // keystore JSON string
'your-keystore-password'
)
ChainGate automatically detects the keystore type (Web3-like or legacy) and imports it accordingly.
Using the wallet
import { importFromKeystore, ChainGate } from 'chaingate'
const wallet = await importFromKeystore(keystoreJson, password)
const cg = new ChainGate({ apiKey: 'your-api-key' })
const ethereum = cg.connect(cg.networks.ethereum, wallet)
console.log(await ethereum.address())
Check keystore validity
Before importing, validate the keystore using isValidKeystore():
import { readFileSync } from 'fs'
import { isValidKeystore, importFromKeystore } from 'chaingate'
const keystore = readFileSync('keystore.json').toString()
if (!isValidKeystore(keystore)) {
throw new Error('Invalid keystore format')
}
const wallet = await importFromKeystore(keystore, 'your-password')
Error handling
InvalidKeystoreError— Thrown if the JSON is not a recognized keystore format.IncorrectKeystorePasswordError— Thrown if the password is wrong.
Exporting a wallet
Wallets created from a keystore cannot be exported back into a keystore file. To back up or persist your wallet, you must serialize it instead.