@flarenetwork/flare-stake-tool
Version:
Utilities for staking on the Flare network
787 lines • 36 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.interactiveCli = interactiveCli;
exports.getPathsAndAddresses = getPathsAndAddresses;
const fs_1 = __importDefault(require("fs"));
const chalk_1 = __importDefault(require("chalk"));
const commander_1 = require("commander");
const bn_js_1 = require("bn.js");
const context_1 = require("../context");
const prompts_1 = require("./prompts");
const utils_1 = require("../utils");
const cli_1 = require("../cli");
const ledger = __importStar(require("../ledger"));
const output_1 = require("../output");
const evmTx_1 = require("../forDefi/evmTx");
const web3_1 = __importDefault(require("web3"));
const chain_1 = require("../flare/chain");
const DEFAULT_EVM_TX_FEE = new bn_js_1.BN(1);
const DEFAULT_EVM_TX_BASE_FEE = new bn_js_1.BN(25);
/***
* @description Handles all operations pertaining to the interactive CLL. Creates a list of arguments and internally calls the commander based CLI after taking the relevant inputs from the user.
* @param baseargv List of base arguments passed to the application to invoke the interactive CLI
* @returns {void}
*/
async function interactiveCli(baseargv) {
let initialised = false;
let walletProperties = null;
while (true) {
if (!initialised) {
walletProperties = await connectWallet();
initialised = true;
}
if (!walletProperties) {
throw new Error("Cannot connect to wallet");
}
const task = String(await selectTask());
const program = new commander_1.Command("Flare Stake Tool");
(0, cli_1.cli)(program);
// First 4 info functions
if (["addresses", "balance", "network", "validators"].includes(task)) {
if (walletProperties.wallet === "ledger") {
const argsInfo = [...baseargv.slice(0, 2), "info", task, `--ctx-file=ctx.json`];
await program.parseAsync(argsInfo);
}
else if (walletProperties.wallet === "privateKey" && walletProperties.path && walletProperties.network) {
const argsInfo = [
...baseargv.slice(0, 2),
"info",
task,
`--env-path=${walletProperties.path}`,
`--network=${walletProperties.network}`,
"--get-hacked",
];
await program.parseAsync(argsInfo);
}
else {
console.log("Incorrect arguments passed!");
}
}
// Functions for export and import to move funds between chains
else if (task === "CP" || task === "PC") {
if (walletProperties.wallet === "ledger" && fileExists("ctx.json")) {
const { network: ctxNetwork, derivationPath: ctxDerivationPath, publicKey, flareAddress: ctxPAddress, } = readInfoFromCtx("ctx.json");
if (ctxNetwork && ctxDerivationPath) {
// if exportPC, default amount is total balance of P chain minus fees
let amount;
if (task.slice(0, 1) === "P" && ctxPAddress) {
const exportFee = await (0, chain_1.getPTxDefaultFee)(ctxNetwork);
const pBalance = await (0, chain_1.getPBalance)(ctxNetwork, ctxPAddress);
const defaultAmount = pBalance.sub(exportFee);
const defaultAmountFLR = (0, utils_1.integerToDecimal)(defaultAmount.toString(), 9);
amount = await prompts_1.prompts.amount("", defaultAmountFLR);
}
else {
amount = await prompts_1.prompts.amount("");
}
const argsExport = [
...baseargv.slice(0, 2),
"transaction",
`export${task}`,
"-a",
`${amount.amount}`,
"--blind",
"--derivation-path",
ctxDerivationPath,
"--network",
`${ctxNetwork}`,
"--ledger",
];
// ask for fees if its exportCP transaction
if (task.slice(0, 1) === "C") {
const exportFees = await prompts_1.prompts.fees(DEFAULT_EVM_TX_FEE);
argsExport.push("-f", `${exportFees.fees}`);
// for exportCP we wait for the finalization before doing import
console.log("Please approve export transaction");
await (0, utils_1.waitFinalize)((0, context_1.getContext)(ctxNetwork, publicKey), program.parseAsync(argsExport));
console.log(chalk_1.default.green("Transaction finalized!"));
}
else {
console.log("Please approve export transaction");
await program.parseAsync(argsExport);
}
const argsImport = [
...baseargv.slice(0, 2),
"transaction",
`import${task}`,
"--blind",
"--derivation-path",
ctxDerivationPath,
"--network",
`${ctxNetwork}`,
"--ledger",
];
// ask for fees if its importTxPC
if (task.slice(0, 1) === "P") {
const importFees = await prompts_1.prompts.fees(DEFAULT_EVM_TX_FEE);
argsImport.push("-f", `${importFees.fees}`);
}
console.log("Please approve import transaction");
await program.parseAsync(argsImport);
}
else {
console.log("Missing params in ctx file");
}
}
else if (walletProperties.wallet === "privateKey" && walletProperties.network && walletProperties.path) {
// explicitly throw error when ctx.json doesn't exist
let amount;
const network = walletProperties.network;
const ctx = (0, context_1.contextEnv)(walletProperties.path, network);
const ctxPAddress = ctx.pAddressBech32;
if (!ctxPAddress) {
throw new Error("Context does not have a valid pAddressBech32");
}
// if exportPC, default amount is total balance of P chain minus fees
if (task.slice(0, 1) === "P" && ctxPAddress) {
const exportFee = await (0, chain_1.getPTxDefaultFee)(network);
const pBalance = await (0, chain_1.getPBalance)(network, ctxPAddress);
const defaultAmount = pBalance.sub(exportFee);
const defaultAmountFLR = (0, utils_1.integerToDecimal)(defaultAmount.toString(), 9);
amount = await prompts_1.prompts.amount("", defaultAmountFLR);
}
else {
amount = await prompts_1.prompts.amount("");
}
const argsExport = [
...baseargv.slice(0, 2),
"transaction",
`export${task}`,
"-a",
`${amount.amount}`,
`--env-path=${walletProperties.path}`,
`--network=${walletProperties.network}`,
"--get-hacked",
];
// ask for fees if its exportCP transaction
if (task.slice(0, 1) === "C") {
const exportFees = await prompts_1.prompts.baseFee(DEFAULT_EVM_TX_BASE_FEE);
argsExport.push("-f", `${exportFees.baseFee}`);
await (0, utils_1.waitFinalize)((0, context_1.contextEnv)(walletProperties.path, walletProperties.network), program.parseAsync(argsExport));
console.log(chalk_1.default.green("Transaction finalized!"));
}
else {
await program.parseAsync(argsExport);
}
const argsImport = [
...baseargv.slice(0, 2),
"transaction",
`import${task}`,
`--env-path=${walletProperties.path}`,
`--network=${walletProperties.network}`,
"--get-hacked",
];
// ask for fees if its importTxPC
if (task.slice(0, 1) === "P") {
const exportFees = await prompts_1.prompts.baseFee(DEFAULT_EVM_TX_BASE_FEE);
argsImport.push("-f", `${exportFees.baseFee}`);
}
await program.parseAsync(argsImport);
}
else {
console.log("Incorrect arguments passed!");
}
}
else if (task === "transfer") {
// transfer funds between p-chain addresses
if (walletProperties.wallet === "ledger" && fileExists("ctx.json")) {
const { network: ctxNetwork, derivationPath: ctxDerivationPath, publicKey: ctxPublicKey, } = readInfoFromCtx("ctx.json");
const ctxPAddress = "P-" + (0, utils_1.publicKeyToBech32AddressString)(ctxPublicKey, ctxNetwork);
if (ctxNetwork && ctxDerivationPath && ctxPAddress) {
const { amount, transferAddress } = await getDetailsForTransfer(task);
if (ctxNetwork && ctxDerivationPath) {
const argsValidator = [
...baseargv.slice(0, 2),
"transaction",
task,
"-a",
`${amount}`,
"--transfer-address",
`${transferAddress}`,
"--blind",
"--derivation-path",
ctxDerivationPath,
`--network`,
`${ctxNetwork}`,
"--ledger",
];
await program.parseAsync(argsValidator);
}
else {
console.log("Missing values for certain params");
}
}
}
else if (walletProperties.wallet === "privateKey" && walletProperties.network && walletProperties.path) {
const { amount, transferAddress } = await getDetailsForTransfer(task);
const argsValidator = [
...baseargv.slice(0, 2),
"transaction",
task,
`--network=${walletProperties.network}`,
"-a",
`${amount}`,
"--transfer-address",
`${transferAddress}`,
`--env-path=${walletProperties.path}`,
"--get-hacked",
];
await program.parseAsync(argsValidator);
}
else {
console.log("only pvt key and ledger supported for staking right now");
}
}
// Adding a validator
else if ("stake" === task) {
if (walletProperties.wallet === "ledger" && fileExists("ctx.json")) {
const { network: ctxNetwork, derivationPath: ctxDerivationPath, publicKey: ctxPublicKey, } = readInfoFromCtx("ctx.json");
const ctxPAddress = "P-" + (0, utils_1.publicKeyToBech32AddressString)(ctxPublicKey, ctxNetwork);
const ctxCAddress = (0, utils_1.publicKeyToEthereumAddressString)(ctxPublicKey);
if (ctxNetwork && ctxDerivationPath && ctxPAddress && ctxCAddress) {
const { amount, nodeId, startTime, endTime, delegationFee, popBLSPublicKey, popBLSSignature } = await getDetailsForDelegation(task, (0, context_1.isDurango)(ctxNetwork));
if (ctxNetwork && ctxDerivationPath && delegationFee && popBLSPublicKey && popBLSSignature) {
const argsValidator = [
...baseargv.slice(0, 2),
"transaction",
task,
"-n",
`${nodeId}`,
"-a",
`${amount}`,
"-s",
`${startTime}`,
"-e",
`${endTime}`,
"--delegation-fee",
`${delegationFee}`,
"--blind",
"--derivation-path",
ctxDerivationPath,
`--network`,
`${ctxNetwork}`,
`--pop-bls-public-key`,
popBLSPublicKey,
`--pop-bls-signature`,
popBLSSignature,
"--ledger",
];
await program.parseAsync(argsValidator);
}
else {
console.log("Missing values for certain params");
}
}
}
else if (walletProperties.wallet === "privateKey" && walletProperties.network && walletProperties.path) {
const { amount, nodeId, startTime, endTime, delegationFee, popBLSPublicKey, popBLSSignature } = await getDetailsForDelegation(task, (0, context_1.isDurango)(walletProperties.network));
if (!popBLSPublicKey || !popBLSSignature) {
throw new Error("Missing popBLSPublicKey or popBLSSignature");
}
const argsValidator = [
...baseargv.slice(0, 2),
"transaction",
task,
"-n",
`${nodeId}`,
`--network=${walletProperties.network}`,
"-a",
`${amount}`,
"-s",
`${startTime}`,
"-e",
`${endTime}`,
"--delegation-fee",
`${delegationFee}`,
`--env-path=${walletProperties.path}`,
"--get-hacked",
`--pop-bls-public-key`,
popBLSPublicKey,
`--pop-bls-signature`,
popBLSSignature,
];
await program.parseAsync(argsValidator);
}
else {
console.log("only pvt key and ledger supported for staking right now");
}
}
// Delegating to a Validator
else if ("delegate" === task) {
if (walletProperties.wallet === "ledger" && fileExists("ctx.json")) {
const { network: ctxNetwork, derivationPath: ctxDerivationPath, ethAddress: ctxCAddress,
// publicKey: ctxPublicKey,
flareAddress: ctxPAddress, } = readInfoFromCtx("ctx.json");
if (ctxNetwork && ctxDerivationPath && ctxPAddress && ctxCAddress) {
const { amount, nodeId, startTime, endTime } = await getDetailsForDelegation(task, (0, context_1.isDurango)(ctxNetwork));
const argsDelegate = [
...baseargv.slice(0, 2),
"transaction",
task,
"-n",
`${nodeId}`,
"-a",
`${amount}`,
"-s",
`${startTime}`,
"-e",
`${endTime}`,
"--blind",
"--derivation-path",
ctxDerivationPath,
`--network`,
`${ctxNetwork}`,
"--ledger",
];
await program.parseAsync(argsDelegate);
}
else {
console.log("Missing params in ctx file");
}
}
else if (walletProperties.wallet === "privateKey" && walletProperties.network && walletProperties.path) {
const { amount, nodeId, startTime, endTime } = await getDetailsForDelegation(task, (0, context_1.isDurango)(walletProperties.network));
const argsDelegate = [
...baseargv.slice(0, 2),
"transaction",
task,
"-n",
`${nodeId}`,
`--network=${walletProperties.network}`,
"-a",
`${amount}`,
"-s",
`${startTime}`,
"-e",
`${endTime}`,
`--env-path=${walletProperties.path}`,
"--get-hacked",
];
await program.parseAsync(argsDelegate);
}
else {
console.log("only private key and ledger are supported for delegation");
}
}
// Mirror funds
else if ("mirror" === task) {
if (walletProperties.wallet === "ledger") {
const argsInfo = [...baseargv.slice(0, 2), "info", task, `--ctx-file=ctx.json`];
await program.parseAsync(argsInfo);
}
else if (walletProperties.wallet === "privateKey" && walletProperties.path && walletProperties.network) {
const argsInfo = [
...baseargv.slice(0, 2),
"info",
task,
`--env-path=${walletProperties.path}`,
`--network=${walletProperties.network}`,
"--get-hacked",
];
await program.parseAsync(argsInfo);
}
else {
console.log("Incorrect arguments passed!");
}
}
else if ("import" === task) {
const importDestChain = await prompts_1.prompts.importTrxType();
let trxType;
if (importDestChain.type === "P")
trxType = "CP";
if (importDestChain.type === "C")
trxType = "PC";
if (walletProperties.wallet === "ledger" && fileExists("ctx.json")) {
const { network: ctxNetwork, derivationPath: ctxDerivationPath } = readInfoFromCtx("ctx.json");
if (ctxNetwork && ctxDerivationPath) {
const argsImport = [
...baseargv.slice(0, 2),
"transaction",
`import${trxType}`,
"--blind",
"--derivation-path",
ctxDerivationPath,
`--network=${ctxNetwork}`,
"--ledger",
];
// ask for fees if its importTxPC
if (importDestChain.type === "C") {
const importFees = await prompts_1.prompts.fees(DEFAULT_EVM_TX_FEE);
argsImport.push("-f", `${importFees.fees}`);
}
console.log("Please approve import transaction");
await program.parseAsync(argsImport);
}
else {
console.log("Missing params in ctx file");
}
}
else if (walletProperties.wallet === "privateKey" && walletProperties.network && walletProperties.path) {
const argsImport = [
...baseargv.slice(0, 2),
"transaction",
`import${trxType}`,
`--env-path=${walletProperties.path}`,
`--network=${walletProperties.network}`,
"--get-hacked",
];
// ask for fees if its importTxPC
if (importDestChain.type === "C") {
const importFees = await prompts_1.prompts.baseFee(DEFAULT_EVM_TX_BASE_FEE);
argsImport.push("-f", `${importFees.baseFee}`);
}
console.log("Please approve import transaction");
await program.parseAsync(argsImport);
}
else {
console.log("Incorrect arguments passed!");
}
}
else if ("claim" === task) {
if (walletProperties.wallet === "ledger" && fileExists("ctx.json")) {
const { network: ctxNetwork, derivationPath: ctxDerivationPath, ethAddress: ctxCAddress,
// publicKey: ctxPublicKey,
flareAddress: ctxPAddress, } = readInfoFromCtx("ctx.json");
const networkConfig = (0, context_1.getNetworkConfig)(ctxNetwork);
const path = "/ext/bc/C/rpc";
const port = networkConfig.port;
const ip = networkConfig.ip;
const protocol = networkConfig.protocol;
const iport = port ? `${ip}:${port}` : `${ip}`;
const rpcurl = `${protocol}://${iport}`;
const web3 = new web3_1.default(`${rpcurl}${path}`);
if (ctxNetwork && ctxDerivationPath && ctxPAddress && ctxCAddress) {
const { unclaimedRewards, totalRewards, claimedRewards } = await (0, evmTx_1.getStateOfRewards)(web3, ctxCAddress);
console.log(chalk_1.default.yellow(`State of rewards for ${ctxCAddress}:\n` +
`Total rewards: ${totalRewards} ${cli_1.networkTokenSymbol[ctxNetwork]}\n` +
`Claimed rewards: ${claimedRewards} ${cli_1.networkTokenSymbol[ctxNetwork]}\n` +
`Unclaimed rewards: ${unclaimedRewards} ${cli_1.networkTokenSymbol[ctxNetwork]}`));
if (Number(unclaimedRewards) === 0) {
console.log(chalk_1.default.green("Nothing to claim!"));
break;
}
const claimAll = await prompts_1.prompts.claimAllUnclaimed(unclaimedRewards, cli_1.networkTokenSymbol[networkConfig.hrp]);
const amount = claimAll.claimAllUnclaimed ? undefined : (await prompts_1.prompts.claimAmount()).claimAmount;
const wrapRewards = await prompts_1.prompts.wrapRewards();
const recipientAddress = await prompts_1.prompts.recipientAddress(ctxCAddress);
const argsDelegate = [
...baseargv.slice(0, 2),
"claim",
...(amount ? [`-a`] : []),
...(amount ? [`${amount}`] : []),
"-r",
`${recipientAddress.recipientAddress}`,
"--blind",
"--derivation-path",
ctxDerivationPath,
`--network`,
`${ctxNetwork}`,
"--ledger",
...(wrapRewards.wrapRewards ? ["-w"] : []),
];
await program.parseAsync(argsDelegate);
}
else {
console.log("Missing params in ctx file");
}
}
else if (walletProperties.wallet === "privateKey" && walletProperties.network && walletProperties.path) {
const ctx = (0, context_1.contextEnv)(walletProperties.path, walletProperties.network);
const ctxCAddress = ctx.cAddressHex;
if (!ctxCAddress) {
throw new Error("Context does not have a valid cAddressHex");
}
const { unclaimedRewards, totalRewards, claimedRewards } = await (0, evmTx_1.getStateOfRewards)(ctx.web3, ctxCAddress);
const symbol = cli_1.networkTokenSymbol[ctx.config.hrp];
console.log(chalk_1.default.yellow(`State of rewards for ${ctxCAddress}:\n` +
`Total rewards: ${totalRewards} ${symbol}\n` +
`Claimed rewards: ${claimedRewards} ${symbol}\n` +
`Unclaimed rewards: ${unclaimedRewards} ${symbol}`));
if (Number(unclaimedRewards) === 0) {
console.log(chalk_1.default.green("Nothing to claim!"));
break;
}
const claimAll = await prompts_1.prompts.claimAllUnclaimed(unclaimedRewards, symbol);
const amount = claimAll.claimAllUnclaimed ? undefined : (await prompts_1.prompts.claimAmount()).claimAmount;
const wrapRewards = await prompts_1.prompts.wrapRewards();
const recipientAddress = await prompts_1.prompts.recipientAddress(ctx.cAddressHex);
const argsDelegate = [
...baseargv.slice(0, 2),
"claim",
...(amount ? [`-a`] : []),
...(amount ? [`${amount}`] : []),
"-r",
`${recipientAddress.recipientAddress}`,
`--env-path=${walletProperties.path}`,
"--get-hacked",
`--network=${walletProperties.network}`,
...(wrapRewards.wrapRewards ? ["-w"] : []),
];
await program.parseAsync(argsDelegate);
}
else {
console.log("only private key and ledger are supported");
}
}
// exit the interactive cli
else if ("quit" === task) {
// exit the application
(0, output_1.logInfo)("Exiting interactive cli.");
process.exit(0);
}
else {
console.log("Task not supported");
}
}
}
async function connectWallet() {
const walletPrompt = await prompts_1.prompts.connectWallet();
const wallet = walletPrompt.wallet;
if (wallet === "privateKey") {
const pvtKeyPath = await prompts_1.prompts.pvtKeyPath();
const path = pvtKeyPath.pvtKeyPath;
// check if the file exists
if (!fileExists(path)) {
throw new Error("File doesn't exist");
}
const network = await selectNetwork();
// check if the file is a valid private key
(0, context_1.contextEnv)(path, network);
return { wallet, path, network };
}
else if (wallet === "ledger") {
const isCreateCtx = await getCtxStatus(wallet);
let network;
if (isCreateCtx) {
network = await selectNetwork();
const selectedDerivationPath = await selectDerivationPath(network);
const optionsObject = {
network,
blind: false,
ctxFile: "ctx.json",
ledger: true,
};
await (0, cli_1.initCtxJsonFromOptions)(optionsObject, selectedDerivationPath);
}
return { wallet };
}
else {
return { wallet };
}
}
async function selectNetwork() {
const network = await prompts_1.prompts.selectNetwork();
return network.network;
}
async function selectTask() {
const task = await prompts_1.prompts.selectTask();
return task.task;
}
function fileExists(filePath) {
try {
fs_1.default.accessSync(filePath, fs_1.default.constants.F_OK);
return true;
}
catch {
console.error(chalk_1.default.red(`File ${filePath} doesn't exist`));
return false;
}
}
function readInfoFromCtx(_filePath) {
const ctxContent = fs_1.default.readFileSync("ctx.json", "utf-8");
const ctxData = JSON.parse(ctxContent);
const wallet = ctxData.wallet;
const publicKey = ctxData.publicKey;
const network = ctxData.network;
const ethAddress = (0, utils_1.publicKeyToEthereumAddressString)(publicKey);
const flareAddress = "P-" + (0, utils_1.publicKeyToBech32AddressString)(publicKey, network);
const derivationPath = ctxData.derivationPath || undefined;
const vaultId = ctxData.vaultId || undefined;
return {
wallet,
publicKey,
network,
ethAddress,
flareAddress,
derivationPath,
vaultId,
};
}
function createChoicesFromAddress(pathList) {
const choiceList = [];
for (let i = 0; i < 10; i++) {
const choice = pathList[i].ethAddress;
choiceList.push(`${i + 1}. ${choice}`);
}
return choiceList;
}
async function getCtxStatus(wallet) {
let isCreateCtx = true;
const fileExist = fileExists("ctx.json");
if (fileExist) {
const { wallet: ctxWallet, network: ctxNetwork, publicKey: ctxPublicKey, ethAddress: ctxEthAddress, vaultId: ctxVaultId, } = readInfoFromCtx("ctx.json");
if (wallet !== ctxWallet) {
deleteFile();
return isCreateCtx;
}
console.log(chalk_1.default.magenta("You already have an existing Ctx file with the following parameters:"));
console.log(chalk_1.default.hex("#FFA500")("Public Key:"), ctxPublicKey);
console.log(chalk_1.default.hex("#FFA500")("Network:"), ctxNetwork);
if (ctxEthAddress) {
console.log(chalk_1.default.hex("#FFA500")("Eth Address:"), ctxEthAddress);
}
if (ctxVaultId) {
console.log(chalk_1.default.hex("#FFA500")("Vault Id:"), ctxVaultId);
}
const getUserChoice = await prompts_1.prompts.ctxFile();
const isContinue = getUserChoice.isContinue;
if (isContinue) {
isCreateCtx = false;
}
else {
deleteFile();
}
}
return isCreateCtx;
}
function deleteFile() {
try {
fs_1.default.unlinkSync("ctx.json");
console.log('File "ctx.json" has been deleted.');
}
catch (error) {
console.error("An error occurred while deleting the file:", error);
}
}
async function getDetailsForDelegation(task, isDurango) {
const amount = await prompts_1.prompts.amount("");
const nodeId = await prompts_1.prompts.nodeId();
let startTime = "0";
if (!isDurango) {
const { time } = await prompts_1.prompts.unixTime("start");
startTime = time;
}
const { time: endTime } = await prompts_1.prompts.unixTime("end");
const delegationDetails = {
amount: amount.amount,
nodeId: nodeId.id,
startTime: startTime,
endTime: endTime,
};
if (task === "stake") {
const fee = await prompts_1.prompts.delegationFee();
const popBLSPublicKey = await prompts_1.prompts.popBLSPublicKey();
const popBLSSignature = await prompts_1.prompts.popBLSSignature();
return {
...delegationDetails,
delegationFee: fee.fee,
popBLSPublicKey: popBLSPublicKey.popBLSPublicKey,
popBLSSignature: popBLSSignature.popBLSSignature,
};
}
return delegationDetails;
}
async function getDetailsForTransfer(task) {
const { amount } = await prompts_1.prompts.amount("");
const { transferAddress } = await prompts_1.prompts.transferAddress();
return { amount, transferAddress };
}
//async function getDetailsForValidation(task: string): Promise<DelegationDetailsInterface> {
// const amount = await prompts.amount()
// const nodeId = await prompts.nodeId()
// const startTime = await prompts.unixTime('start')
// const endTime = await prompts.unixTime('end')
// const popBLSPublicKey = await prompts.popBLSPublicKey()
// const popBLSSignature = await prompts.popBLSSignature()
// const validationDetails = {
// amount: amount.amount,
// nodeId: nodeId.id,
// startTime: startTime.time,
// endTime: endTime.time,
// popBLSPublicKey: popBLSPublicKey,
// popBLSSignature: popBLSSignature
// }
// if (task === 'stake') {
// const fee = await prompts.delegationFee()
// return {
// TODO: popBLS stuff?
// ...validationDetails,
// delegationFee: fee.fee
// }
// }
// return delegationDetails
//}
async function getPathsAndAddresses(network, derivationMode = "default") {
const LEDGER_LIVE_BASE_PATH = "m/44'/60'/"; // Full: m/44'/60'/*'/0/0
const BIP44_BASE_PATH = "m/44'/60'/0'/0/"; // Full: m/44'/60'/0'/0/*
const PATH_LIST = [];
for (let i = 0; i < 10; i++) {
if (derivationMode === "ledger_live") {
PATH_LIST.push(LEDGER_LIVE_BASE_PATH + i + "'/0/0");
}
else {
PATH_LIST.push(BIP44_BASE_PATH + i);
}
}
const results = [];
for (const path of PATH_LIST) {
const publicKey = await ledger.getPublicKey(path, network);
const ethAddress = (0, utils_1.publicKeyToEthereumAddressString)(publicKey);
const derivedAddress = {
ethAddress: ethAddress,
derivationPath: path,
publicKey: publicKey,
};
results.push(derivedAddress);
}
return results;
}
// queries user for their derivation path
async function selectDerivationPath(network) {
const derivationTypePrompt = await prompts_1.prompts.derivationType();
const derivation = derivationTypePrompt.derivation;
console.log("Fetching Addresses...");
const pathList = await getPathsAndAddresses(network, derivation);
const choiceList = createChoicesFromAddress(pathList);
const selectedAddress = await prompts_1.prompts.selectAddress(choiceList);
const selectedDerivedAddress = pathList.find((item) => item.ethAddress === selectedAddress.address);
const selectedDerivationPath = selectedDerivedAddress?.derivationPath;
return selectedDerivationPath;
}
//# sourceMappingURL=cli.js.map