@kaiachain/web3js-ext
Version:
web3.js extension for kaiachain blockchain
75 lines (74 loc) • 3.12 kB
JavaScript
import _ from "lodash";
import { create, decrypt, privateKeyToAccount } from "web3-eth-accounts";
import { toChecksumAddress } from "web3-utils";
import { isKIP3Json, splitKeystoreKIP3 } from "../index.js";
import { context_signTransaction, context_signTransactionAsFeePayer } from "./sign.js";
// Analogous to web3/src/accounts.ts:createWithContext
export function context_create(context) {
return function () {
const account = create();
return wrapAccount(context, account);
};
}
// Analogous to web3/src/accounts.ts:privateKeyToAccountWithContext
export function context_privateKeyToAccount(context) {
return function (privateKey, address) {
const account = privateKeyToAccount(privateKey);
return wrapAccount(context, { ...account, address: address || account.address });
};
}
// Analogous to web3/src/accounts.ts:decryptWithContext
export function context_decrypt(context) {
return async function (keystore, password, options) {
if (!_.isString(keystore)) {
keystore = JSON.stringify(keystore);
}
if (isKIP3Json(keystore)) {
const accounts = await decryptKIP3(keystore, password, options);
return wrapAccount(context, accounts[0]);
}
else {
const account = await decrypt(keystore, password, options?.nonStrict ?? true);
return wrapAccount(context, account);
}
};
}
export function context_decryptList(context) {
return async function (keystore, password, options) {
if (!_.isString(keystore)) {
keystore = JSON.stringify(keystore);
}
if (isKIP3Json(keystore)) {
const accounts = await decryptKIP3(keystore, password, options);
return _.map(accounts, (account) => wrapAccount(context, account));
}
else {
const account = await decrypt(keystore, password, options?.nonStrict ?? true);
return [wrapAccount(context, account)];
}
};
}
async function decryptKIP3(keystore, password, options) {
if (!_.isString(keystore)) {
keystore = JSON.stringify(keystore);
}
const address = JSON.parse(keystore).address;
const jsonList = splitKeystoreKIP3(keystore, false);
const accounts = [];
for (const json of jsonList) {
const account = await decrypt(json, password, options?.nonStrict ?? true);
account.address = toChecksumAddress(address); // the address may not coincide with private keys, get directly from the json.
accounts.push(account);
}
return accounts;
}
// common components of create, privateKeyToAccount, decrypt.
function wrapAccount(context, account) {
const _signTransaction = context_signTransaction(context);
const _signTransactionAsFeePayer = context_signTransactionAsFeePayer(context);
return {
...account,
signTransaction: (transaction) => _signTransaction(transaction, account.privateKey),
signTransactionAsFeePayer: (transaction) => _signTransactionAsFeePayer(transaction, account.privateKey, account.address),
};
}