@argonprotocol/mainchain 1.3.3 → 1.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser/index.d.ts +18 -10
- package/browser/index.js +58 -47
- package/browser/index.js.map +1 -1
- package/lib/{chunk-UZCZ347U.js → chunk-2J7IEVVC.js} +3 -3
- package/lib/chunk-2J7IEVVC.js.map +1 -0
- package/lib/{chunk-IQ3TNLS7.cjs → chunk-BP7Y2NWQ.cjs} +52 -52
- package/lib/{chunk-IQ3TNLS7.cjs.map → chunk-BP7Y2NWQ.cjs.map} +1 -1
- package/lib/{chunk-FCT7GMFN.js → chunk-GZ2TLGCG.js} +64 -53
- package/lib/{chunk-FCT7GMFN.js.map → chunk-GZ2TLGCG.js.map} +1 -1
- package/lib/{chunk-OFYVHBKG.cjs → chunk-P5WWWRSU.cjs} +119 -108
- package/lib/chunk-P5WWWRSU.cjs.map +1 -0
- package/lib/cli.cjs +6 -6
- package/lib/cli.js +2 -2
- package/lib/clis/index.cjs +3 -3
- package/lib/clis/index.js +2 -2
- package/lib/index.cjs +4 -2
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +18 -10
- package/lib/index.d.ts +18 -10
- package/lib/index.js +3 -1
- package/package.json +2 -2
- package/lib/chunk-OFYVHBKG.cjs.map +0 -1
- package/lib/chunk-UZCZ347U.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/mainchain/mainchain/client/nodejs/lib/chunk-IQ3TNLS7.cjs","../src/clis/index.ts","../src/clis/accountCli.ts","../src/clis/vaultCli.ts","../src/clis/miningCli.ts","../src/clis/liquidityCli.ts","../src/clis/bitcoinCli.ts","../src/clis/keyringStore.ts"],"names":["addresses","Command","printTable","unsubscribe","env"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;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AACD,IAAA;AACN,MAAA;AACD,IAAA;AACU,IAAA;AACF,MAAA;AACL,QAAA;AACD,MAAA;AACH,IAAA;AACF,EAAA;AACF;AAEyB;AACf,EAAA;AACI,EAAA;AACH,EAAA;AACS,IAAA;AACJ,IAAA;AACI,IAAA;AAEF,MAAA;AACG,QAAA;AACD,QAAA;AACd,MAAA;AACF,IAAA;AACF,EAAA;AACOG,EAAAA;AACT;AD8kBsB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/mainchain/mainchain/client/nodejs/lib/chunk-IQ3TNLS7.cjs","sourcesContent":[null,"import { Command, Option } from '@commander-js/extra-typings';\nimport accountCli from './accountCli';\nimport { configDotenv } from 'dotenv';\nimport Path from 'node:path';\nimport vaultCli from './vaultCli';\nimport miningCli from './miningCli';\nimport liquidityCli from './liquidityCli';\nimport bitcoinCli from './bitcoinCli';\nimport { Accountset, parseSubaccountRange } from '../Accountset';\nimport { getClient, keyringFromSuri, KeyringPair } from '../index';\nimport { keyringFromFile, saveKeyringPair } from './keyringStore';\n\nexport {\n accountCli,\n vaultCli,\n miningCli,\n liquidityCli,\n bitcoinCli,\n keyringFromFile,\n saveKeyringPair,\n};\n\nexport function globalOptions(program: Command) {\n return program.optsWithGlobals() as IGlobalOptions;\n}\n\nexport function buildCli() {\n return new Command('Argon CLI')\n .option('-e, --env <path>', 'The path to the account .env file to load')\n .addOption(\n new Option('-u, --mainchain-url <url>', 'The mainchain URL to connect to')\n .default('wss://rpc.argon.network')\n .env('MAINCHAIN_URL'),\n )\n .addOption(\n new Option(\n '--account-file-path <jsonPath>',\n 'The path to your json seed file from polkadotjs',\n ).env('ACCOUNT_JSON_PATH'),\n )\n .addOption(\n new Option('--account-suri <secretUri>', 'A secret uri (suri) to use for the account').env(\n 'ACCOUNT_SURI',\n ),\n )\n .addOption(\n new Option('--account-passphrase <password>', 'The password for your seed file').env(\n 'ACCOUNT_PASSPHRASE',\n ),\n )\n .addOption(\n new Option('--account-passphrase-file <path>', 'The path to a password for your seed file'),\n )\n .addOption(\n new Option(\n '-s, --subaccounts <range>',\n 'Restrict this operation to a subset of the subaccounts (eg, 0-10)',\n )\n .env('SUBACCOUNT_RANGE')\n .argParser(parseSubaccountRange),\n )\n .addCommand(accountCli())\n .addCommand(vaultCli())\n .addCommand(miningCli())\n .addCommand(liquidityCli())\n .addCommand(bitcoinCli());\n}\n\nexport async function accountsetFromCli(\n program: Command,\n proxyForAddress?: string,\n): Promise<Accountset> {\n const opts = program.parent?.optsWithGlobals() as unknown as IGlobalOptions;\n\n let keypair: KeyringPair | undefined;\n if (opts.accountSuri) {\n keypair = keyringFromSuri(opts.accountSuri!);\n }\n if (opts.accountFilePath) {\n keypair = await keyringFromFile({\n filePath: opts.accountFilePath,\n passphrase: opts.accountPassphrase,\n passphraseFile: opts.accountPassphraseFile,\n });\n }\n if (!keypair) {\n throw new Error(\n 'No ACCOUNT account loaded (either ACCOUNT_SURI or ACCOUNT_JSON_PATH required)',\n );\n }\n\n const client = getClient(opts.mainchainUrl);\n if (proxyForAddress) {\n return new Accountset({\n client,\n isProxy: true,\n seedAddress: proxyForAddress,\n txSubmitter: keypair,\n });\n } else {\n return new Accountset({\n seedAccount: keypair,\n client,\n });\n }\n}\n\nexport type IGlobalOptions = ReturnType<ReturnType<typeof buildCli>['opts']>;\n\nexport function addGlobalArgs(program: ReturnType<typeof buildCli>) {\n for (const command of program.commands) {\n command.configureHelp({\n showGlobalOptions: true,\n });\n for (const nested of command.commands) {\n nested.configureHelp({\n showGlobalOptions: true,\n });\n }\n }\n}\n\nexport function applyEnv(program: ReturnType<typeof buildCli>): string | undefined {\n program.parseOptions(process.argv);\n const { env } = program.optsWithGlobals();\n if (env) {\n const envPath = Path.resolve(process.cwd(), env);\n const res = configDotenv({ path: envPath });\n if (res.parsed?.ACCOUNT_JSON_PATH) {\n // ensure path is relative to the env file if provided that way\n process.env.ACCOUNT_JSON_PATH = Path.resolve(\n Path.dirname(envPath),\n process.env.ACCOUNT_JSON_PATH!,\n );\n }\n }\n return env;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { filterUndefined, mnemonicGenerate } from '../index';\nimport { printTable } from 'console-table-printer';\nimport { cryptoWaitReady } from '@polkadot/util-crypto';\nimport { writeFileSync } from 'node:fs';\nimport { parseSubaccountRange } from '../Accountset';\nimport Env from '../env';\nimport * as process from 'node:process';\nimport { accountsetFromCli, globalOptions } from './index';\n\nexport default function accountCli() {\n const program = new Command('accounts').description('Manage subaccounts from a single keypair');\n\n program\n .command('watch')\n .description('Watch for blocks closed by subaccounts')\n .action(async () => {\n const accountset = await accountsetFromCli(program);\n const accountMiners = await accountset.watchBlocks();\n\n accountMiners.events.on('mined', (_block, mined) => {\n console.log('Your accounts authored a block', mined);\n });\n accountMiners.events.on('minted', (_block, minted) => {\n console.log('Your accounts minted argons', minted);\n });\n });\n\n program\n .command('list', { isDefault: true })\n .description('Show subaccounts')\n .option('--addresses', 'Just show a list of ids')\n .action(async ({ addresses }) => {\n const { subaccounts } = globalOptions(program);\n const accountset = await accountsetFromCli(program);\n\n if (addresses) {\n const addresses = accountset.addresses;\n console.log(addresses.join(','));\n process.exit(0);\n }\n const [argonots, argons, seats, bids] = await Promise.all([\n accountset.totalArgonotsAt(),\n accountset.totalArgonsAt(),\n accountset.miningSeats(),\n accountset.bids(),\n ]);\n const accountSubset = subaccounts ? accountset.getAccountsInRange(subaccounts) : undefined;\n const status = accountset.status({\n argons,\n argonots,\n accountSubset,\n seats,\n bids,\n });\n printTable(status);\n process.exit(0);\n });\n\n program\n .command('create')\n .description('Create an account \"env\" file and optionally register keys')\n .requiredOption(\n '--path <path>',\n 'The path to an env file to create (convention is .env.<name>)',\n )\n .option('--register-keys-to <url>', 'Register the keys to a url (normally this is localhost)')\n .action(async ({ registerKeysTo, path }) => {\n const { accountPassphrase, accountSuri, accountFilePath } = globalOptions(program);\n const accountset = await accountsetFromCli(program);\n process.env.KEYS_MNEMONIC ||= mnemonicGenerate();\n if (registerKeysTo) {\n await accountset.registerKeys(registerKeysTo);\n console.log('Keys registered to', registerKeysTo);\n }\n const envData = filterUndefined<Env>({\n ACCOUNT_JSON_PATH: accountFilePath,\n ACCOUNT_SURI: accountSuri,\n ACCOUNT_PASSPHRASE: accountPassphrase,\n KEYS_MNEMONIC: process.env.KEYS_MNEMONIC,\n SUBACCOUNT_RANGE: '0-49',\n });\n let envfile = '';\n for (const [key, value] of Object.entries(envData)) {\n if (key) {\n const line = `${key}=${String(value)}`;\n envfile += line + '\\n';\n }\n }\n writeFileSync(path, envfile);\n console.log('Created env file at', path);\n process.exit();\n });\n\n program\n .command('new-key-seed')\n .description('Create a new mnemonic for runtime keys')\n .action(async () => {\n await cryptoWaitReady();\n const mnemonic = mnemonicGenerate();\n console.log('New mnemonic (add this to your .env as KEYS_MNEMONIC):', mnemonic);\n process.exit(0);\n });\n\n program\n .command('register-keys')\n .description('Create an insert-keys script with curl')\n .argument(\n '[node-rpc-url]',\n 'The url to your node host (should be installed on machine via localhost)',\n 'http://localhost:9944',\n )\n .option('--print-only', 'Output as curl commands instead of direct registration')\n .action(async (nodeRpcUrl, { printOnly }) => {\n const accountset = await accountsetFromCli(program);\n if (printOnly) {\n const { gran, seal } = accountset.keys();\n const commands: string[] = [];\n const data = [\n {\n jsonrpc: '2.0',\n id: 0,\n method: 'author_insertKey',\n params: ['gran', gran.privateKey, gran.publicKey],\n },\n {\n jsonrpc: '2.0',\n id: 1,\n method: 'author_insertKey',\n params: ['seal', seal.privateKey, seal.publicKey],\n },\n ];\n for (const key of data) {\n commands.push(\n `curl -X POST -H \"Content-Type: application/json\" -d '${JSON.stringify(key)}' ${nodeRpcUrl}`,\n );\n }\n\n console.log(commands.join(' && '));\n } else {\n await accountset.registerKeys(nodeRpcUrl);\n }\n process.exit();\n });\n\n program\n .command('consolidate')\n .description('Consolidate all argons into parent account')\n .option(\n '-s, --subaccounts <range>',\n 'Restrict this operation to a subset of the subaccounts (eg, 0-10)',\n parseSubaccountRange,\n )\n .action(async ({ subaccounts }) => {\n const accountset = await accountsetFromCli(program);\n const result = await accountset.consolidate(subaccounts);\n printTable(result);\n process.exit(0);\n });\n return program;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { VaultMonitor } from '../VaultMonitor';\nimport { TxSubmitter } from '../TxSubmitter';\nimport { Vault } from '../Vault';\nimport { BitcoinLocks } from '../BitcoinLocks';\nimport { accountsetFromCli } from './index';\nimport { MICROGONS_PER_ARGON } from '../utils';\nimport { hexToU8a } from '@polkadot/util';\n\nexport default function vaultCli() {\n const program = new Command('vaults').description('Monitor vaults and manage securitization');\n\n program\n .command('list', { isDefault: true })\n .description('Show current state of vaults')\n .action(async () => {\n const accountset = await accountsetFromCli(program);\n const vaults = new VaultMonitor(accountset, undefined, {\n vaultOnlyWatchMode: true,\n });\n await vaults.monitor(true);\n process.exit(0);\n });\n\n program\n .command('modify-securitization')\n .description('Change the vault securitization ratio')\n .requiredOption('-v, --vault-id <id>', 'The vault id to use', parseInt)\n .requiredOption(\n '-a, --argons <amount>',\n 'The number of argons to set as securitization',\n parseFloat,\n )\n .option('--ratio <ratio>', 'The new securitization ratio', parseFloat)\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat)\n .action(async ({ tip, argons, vaultId, ratio }) => {\n const accountset = await accountsetFromCli(program);\n const client = await accountset.client;\n const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;\n const microgons = BigInt(argons * MICROGONS_PER_ARGON);\n\n const rawVault = (await client.query.vaults.vaultsById(vaultId)).unwrap();\n if (rawVault.operatorAccountId.toHuman() !== accountset.seedAddress) {\n console.error('Vault does not belong to this account');\n process.exit(1);\n }\n const existingFunds = rawVault.securitization.toBigInt();\n const additionalFunds = microgons > existingFunds ? microgons - existingFunds : 0n;\n const tx = client.tx.vaults.modifyFunding(\n vaultId,\n microgons,\n ratio !== undefined\n ? BigNumber(ratio).times(BigNumber(2).pow(64)).toFixed(0)\n : rawVault.securitizationRatio.toBigInt(),\n );\n const submit = new TxSubmitter(client, tx, accountset.txSubmitterPair);\n const canAfford = await submit.canAfford({\n tip: resolvedTip,\n unavailableBalance: additionalFunds,\n });\n if (!canAfford.canAfford) {\n console.warn('Insufficient balance to modify vault securitization', {\n ...canAfford,\n addedSecuritization: additionalFunds,\n });\n process.exit(1);\n }\n try {\n const result = await submit.submit({ tip: resolvedTip });\n await result.inBlockPromise;\n console.log('Vault securitization modified');\n process.exit();\n } catch (error) {\n console.error('Error modifying vault securitization', error);\n process.exit(1);\n }\n });\n\n program\n .command('make-bitcoin-space')\n .description('Make bitcoin space in a vault and lock it immediately in the same tx.')\n .requiredOption('-v, --vault-id <id>', 'The vault id to use', parseInt)\n .requiredOption('-a, --argons <amount>', 'The number of argons to add', parseFloat)\n .requiredOption('--bitcoin-pubkey <pubkey>', 'The pubkey to use for the bitcoin lock')\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat)\n .action(async ({ tip, argons, vaultId, bitcoinPubkey }) => {\n let pubkey = bitcoinPubkey;\n if (!bitcoinPubkey.startsWith('0x')) {\n pubkey = `0x${bitcoinPubkey}`;\n }\n if (pubkey.length !== 68) {\n throw new Error('Bitcoin pubkey must be 66 characters (add 0x in front optionally)');\n }\n const accountset = await accountsetFromCli(program);\n const client = await accountset.client;\n const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;\n const microgons = BigInt(argons * MICROGONS_PER_ARGON);\n const bitcoinLocks = new BitcoinLocks(Promise.resolve(client));\n const existentialDeposit = client.consts.balances.existentialDeposit.toBigInt();\n const tickDuration = (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();\n\n const rawVault = (await client.query.vaults.vaultsById(vaultId)).unwrap();\n if (rawVault.operatorAccountId.toHuman() !== accountset.seedAddress) {\n console.error('Vault does not belong to this account');\n process.exit(1);\n }\n const vaultModifyTx = client.tx.vaults.modifyFunding(\n vaultId,\n microgons,\n rawVault.securitizationRatio.toBigInt(),\n );\n const vaultTxFee = (\n await vaultModifyTx.paymentInfo(accountset.txSubmitterPair)\n ).partialFee.toBigInt();\n const vault = new Vault(vaultId, rawVault, tickDuration);\n\n const argonsNeeded = microgons - vault.securitization;\n const argonsAvailable = microgons - vault.availableBitcoinSpace();\n\n const account = await client.query.system.account(accountset.seedAddress);\n const freeBalance = account.data.free.toBigInt();\n let satoshis = await bitcoinLocks.requiredSatoshisForArgonLiquidity(argonsAvailable);\n satoshis -= 100n; // keep some wiggle room since price can change\n const {\n tx: lockTx,\n securityFee: btcFee,\n txFee,\n } = await bitcoinLocks.createInitializeLockTx({\n vault,\n argonKeyring: accountset.txSubmitterPair,\n satoshis,\n ownerBitcoinPubkey: hexToU8a(pubkey),\n tip: resolvedTip,\n reducedBalanceBy: argonsNeeded + vaultTxFee + resolvedTip,\n });\n if (\n argonsNeeded + txFee + vaultTxFee + resolvedTip + btcFee + existentialDeposit >\n freeBalance\n ) {\n console.warn('Insufficient balance to add bitcoin space and use bitcoins', {\n freeBalance,\n txFee,\n vaultTxFee,\n btcFee,\n argonsAvailable,\n vaultMicrogons: microgons,\n existentialDeposit,\n neededBalanceAboveED: argonsNeeded + txFee + resolvedTip + btcFee + vaultTxFee,\n });\n process.exit(1);\n }\n console.log('Adding bitcoin space and locking bitcoins...', {\n newArgonsAvailable: argonsAvailable,\n txFee,\n vaultTxFee,\n btcFee,\n resolvedTip,\n });\n\n const txSubmitter = new TxSubmitter(\n client,\n client.tx.utility.batchAll([vaultModifyTx, lockTx]),\n accountset.txSubmitterPair,\n );\n const result = await txSubmitter.submit({ tip: resolvedTip });\n try {\n await result.inBlockPromise;\n console.log('Bitcoin space done');\n } catch (error) {\n console.error('Error using bitcoin space', error);\n process.exit(1);\n }\n });\n return program;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { getClient, type KeyringPair, MICROGONS_PER_ARGON } from '../index';\nimport { printTable } from 'console-table-printer';\nimport { MiningBids } from '../MiningBids';\nimport { formatArgons } from '../utils';\nimport { TxSubmitter } from '../TxSubmitter';\nimport { accountsetFromCli, globalOptions, saveKeyringPair } from './index';\nimport { CohortBidder } from '../CohortBidder';\n\nexport default function miningCli() {\n const program = new Command('mining').description('Watch mining seats or setup bidding');\n\n program\n .command('list', { isDefault: true })\n .description('Monitor all miners')\n .action(async () => {\n const accountset = await accountsetFromCli(program);\n const bids = new MiningBids(accountset.client);\n const api = await accountset.client;\n let lastMiners: {\n [frameId: string]: {\n miner: string;\n bid?: bigint;\n isLastDay?: boolean;\n };\n } = {};\n\n function print(blockNumber: number) {\n console.clear();\n const toPrint = Object.entries(lastMiners).map(([seat, miner]) => ({\n seat,\n ...miner,\n }));\n if (!toPrint.length) {\n console.log('No active miners');\n } else {\n console.log(`Miners at block ${blockNumber}`);\n printTable(\n toPrint.map(x => ({\n ...x,\n bid: x.bid ? formatArgons(x.bid) : '-',\n isLastDay: x.isLastDay ? 'Y' : '',\n miner: x.miner,\n })),\n );\n }\n if (!bids.nextCohort.length) {\n console.log('-------------------------------------\\nNo bids for next cohort');\n } else {\n bids.print();\n }\n }\n\n const { unsubscribe } = await bids.watch(accountset.namedAccounts, undefined, print);\n console.log('Watching miners...');\n const minMiners = api.consts.miningSlot.minCohortSize.toNumber();\n\n const unsub = await api.query.miningSlot.nextFrameId(async nextFrameId => {\n const frames = new Array(nextFrameId.toNumber())\n .fill(0)\n .map((_, i) => nextFrameId.toNumber() - i)\n .sort();\n const unseenFrames = new Set(frames);\n const entries = await api.query.miningSlot.minersByCohort.entries();\n const block = await api.query.system.number();\n\n const sortedEntries = entries.sort((a, b) => {\n const aIndex = a[0].args[0].toNumber();\n const bIndex = b[0].args[0].toNumber();\n return aIndex - bIndex;\n });\n\n for (const [rawFrameId, miners] of sortedEntries) {\n const frameId = rawFrameId.args[0].toNumber();\n unseenFrames.delete(frameId);\n let i = 0;\n for (const miner of miners) {\n const address = miner.accountId.toHuman();\n const startingFrameId = miner.startingFrameId.toNumber();\n lastMiners[`${frameId}-${i}`] = {\n miner: accountset.namedAccounts.get(address) ?? address,\n bid: miner.bid.toBigInt(),\n isLastDay: nextFrameId.toNumber() - startingFrameId === 10,\n };\n i++;\n }\n while (i < minMiners) {\n lastMiners[`${frameId}-${i}`] = {\n miner: 'none',\n };\n i++;\n }\n }\n for (const frameId of unseenFrames) {\n for (let i = 0; i < minMiners; i++) {\n lastMiners[`${frameId}-${i}`] = {\n miner: 'none',\n };\n }\n }\n print(block.toNumber());\n });\n process.on('SIGINT', () => {\n unsubscribe();\n unsub();\n process.exit(0);\n });\n });\n\n program\n .command('bid')\n .description('Submit mining bids within a range of parameters')\n .option('--min-bid <amount>', 'The minimum bid amount to use', parseFloat)\n .option('--max-bid <amount>', 'The maximum bid amount to use', parseFloat)\n .option('--max-seats <n>', 'The maximum number of seats to bid on for the slot', parseInt)\n .option(\n '--max-balance <argons>',\n \"Use a maximum amount of the user's balance for the slot. If this ends in a percent, it will be a percent of the funds\",\n )\n .option('--bid-increment <argons>', 'The bid increment', parseFloat, 0.01)\n .option('--bid-delay <ticks>', 'Delay between bids in ticks', parseInt, 0)\n .option('--run-continuous', 'Keep running and rebid every day')\n .option(\n '--proxy-for-address <address>',\n 'The seed account to proxy for (eg: 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty)',\n )\n .action(\n async ({\n maxSeats,\n runContinuous,\n maxBid,\n minBid,\n maxBalance,\n bidDelay,\n bidIncrement,\n proxyForAddress,\n }) => {\n const accountset = await accountsetFromCli(program, proxyForAddress);\n\n let cohortBidder: CohortBidder | undefined;\n const miningBids = new MiningBids(accountset.client, false);\n const maxCohortSize = await miningBids.maxCohortSize();\n\n const stopBidder = async (unsubscribe: () => void) => {\n if (cohortBidder) {\n const stats = await cohortBidder.stop();\n console.log('Final bidding result', {\n cohortStartingFrameId: cohortBidder.cohortStartingFrameId,\n ...stats,\n });\n cohortBidder = undefined;\n if (!runContinuous) {\n unsubscribe();\n process.exit();\n }\n }\n };\n const { unsubscribe } = await miningBids.onCohortChange({\n async onBiddingEnd(cohortStartingFrameId) {\n if (cohortBidder?.cohortStartingFrameId === cohortStartingFrameId) {\n await stopBidder(unsubscribe);\n }\n },\n async onBiddingStart(cohortStartingFrameId) {\n const seatsToWin = maxSeats ?? maxCohortSize;\n const balance = await accountset.balance();\n const feeWiggleRoom = BigInt(25e3);\n const amountAvailable = balance - feeWiggleRoom;\n let maxBidAmount = maxBid ? BigInt(maxBid * MICROGONS_PER_ARGON) : undefined;\n let maxBalanceToUse = amountAvailable;\n if (maxBalance !== undefined) {\n if (maxBalance!.endsWith('%')) {\n let maxBalancePercent = parseInt(maxBalance);\n let amountToBid = (amountAvailable * BigInt(maxBalancePercent)) / 100n;\n if (amountToBid > balance) {\n amountToBid = balance;\n }\n maxBalanceToUse = amountToBid;\n } else {\n maxBalanceToUse = BigInt(Math.floor(parseFloat(maxBalance) * MICROGONS_PER_ARGON));\n }\n\n maxBidAmount ??= maxBalanceToUse / BigInt(seatsToWin);\n }\n if (maxBalanceToUse > amountAvailable) {\n maxBalanceToUse = amountAvailable;\n }\n if (!maxBidAmount) {\n console.error('No max bid amount set');\n process.exit(1);\n }\n const subaccountRange = await accountset.getAvailableMinerAccounts(seatsToWin);\n\n if (cohortBidder && cohortBidder?.cohortStartingFrameId !== cohortStartingFrameId) {\n await stopBidder(unsubscribe);\n }\n cohortBidder = new CohortBidder(accountset, cohortStartingFrameId, subaccountRange, {\n maxBid: maxBidAmount,\n minBid: BigInt((minBid ?? 0) * MICROGONS_PER_ARGON),\n bidIncrement: BigInt(Math.floor(bidIncrement * MICROGONS_PER_ARGON)),\n maxBudget: maxBalanceToUse,\n bidDelay,\n });\n await cohortBidder.start();\n },\n });\n },\n );\n\n program\n .command('create-bid-proxy')\n .description('Create a mining-bid proxy account for your main account')\n .requiredOption(\n '--outfile <path>',\n 'The file to use to store the proxy account json (eg: proxy.json)',\n )\n .requiredOption(\n '--fee-argons <argons>',\n 'How many argons should be sent to the proxy account for fees (proxies must pay fees)',\n parseFloat,\n )\n .option('--proxy-passphrase <passphrase>', 'The passphrase for your proxy account')\n .action(async ({ outfile, proxyPassphrase, feeArgons }) => {\n const { mainchainUrl } = globalOptions(program);\n const client = await getClient(mainchainUrl);\n\n const keyringPair = await saveKeyringPair({\n filePath: outfile,\n passphrase: proxyPassphrase,\n });\n const address = keyringPair.address;\n console.log(`✅ Created proxy account at \"${outfile}\" with address ${address}`);\n const tx = client.tx.utility.batchAll([\n client.tx.proxy.addProxy(address, 'MiningBid', 0),\n client.tx.balances.transferAllowDeath(address, BigInt(feeArgons * MICROGONS_PER_ARGON)),\n ]);\n let keypair: KeyringPair;\n try {\n const accountset = await accountsetFromCli(program);\n keypair = accountset.txSubmitterPair;\n } catch (e) {\n const polkadotLink = `https://polkadot.js.org/apps/?rpc=${mainchainUrl}#/extrinsics/decode/${tx.toHex()}`;\n console.log(`Complete the registration at this link:`, polkadotLink);\n process.exit(0);\n }\n try {\n await new TxSubmitter(client, tx, keypair).submit({\n waitForBlock: true,\n });\n\n console.log('Mining bid proxy added and funded.');\n process.exit();\n } catch (error) {\n console.error('Error adding mining proxy', error);\n process.exit(1);\n }\n });\n return program;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { BidPool } from '../BidPool';\nimport { VaultMonitor } from '../VaultMonitor';\nimport { formatArgons, MICROGONS_PER_ARGON } from '../utils';\nimport { accountsetFromCli } from './index';\n\nexport default function liquidityCli() {\n const program = new Command('liquidity-pools').description('Monitor or bond to liquidity pools');\n program\n .command('list', { isDefault: true })\n .description('Show or watch the vault bid pool rewards')\n .action(async () => {\n const accountset = await accountsetFromCli(program);\n const bidPool = new BidPool(accountset.client, accountset.txSubmitterPair);\n await bidPool.watch();\n });\n\n program\n .command('bond')\n .description('Bond argons to a liquidity pool')\n .requiredOption('-v, --vault-id <id>', 'The vault id to use', parseInt)\n .requiredOption('-a, --argons <amount>', 'The number of argons to set the vault to', parseFloat)\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat)\n .action(async ({ tip, argons, vaultId }) => {\n const accountset = await accountsetFromCli(program);\n const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;\n\n const microgons = BigInt(argons * MICROGONS_PER_ARGON);\n const bidPool = new BidPool(accountset.client, accountset.txSubmitterPair);\n await bidPool.bondArgons(vaultId, microgons, { tip: resolvedTip });\n console.log('Bonded argons to liquidity pool bond');\n process.exit();\n });\n\n program\n .command('wait-for-space')\n .description('Add bonded argons to a liquidity pool when the market rate is favorable')\n .requiredOption('--max-argons <amount>', 'Max daily argons to use per slot', parseFloat)\n .option(\n '--min-pct-sharing <percent>',\n 'The minimum profit sharing percent to allow',\n parseInt,\n 30,\n )\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat)\n .action(async ({ maxArgons, minPctSharing, tip }) => {\n const maxAmountPerSlot = BigInt(maxArgons * MICROGONS_PER_ARGON);\n\n const accountset = await accountsetFromCli(program);\n const vaults = new VaultMonitor(\n accountset,\n {\n liquidityPoolSpaceAvailable: 1_000_000n,\n },\n { shouldLog: false },\n );\n const bidPool = new BidPool(accountset.client, accountset.txSubmitterPair);\n const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;\n console.log('Waiting for liquidity pool space...');\n\n vaults.events.on('liquidity-pool-space-above', async (vaultId, amount) => {\n const vault = vaults.vaultsById[vaultId];\n if (vault.terms.liquidityPoolProfitSharing.times(100).toNumber() < minPctSharing) {\n console.info(\n `Skipping vault ${vaultId} due to lower profit sharing than ${minPctSharing}%`,\n );\n return;\n }\n let amountToAdd = amount;\n if (amountToAdd > maxAmountPerSlot) {\n amountToAdd = maxAmountPerSlot;\n }\n await bidPool.bondArgons(vaultId, amountToAdd, { tip: resolvedTip });\n console.log('Bonding argons to vault liquidity pool', {\n vaultId,\n amount: formatArgons(amountToAdd),\n });\n });\n await vaults.monitor();\n });\n return program;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { VaultMonitor } from '../VaultMonitor';\nimport { BitcoinLocks } from '../BitcoinLocks';\nimport { formatArgons, MICROGONS_PER_ARGON } from '../utils';\nimport { accountsetFromCli } from './index';\n\nexport default function bitcoinCli() {\n const program = new Command('bitcoin').description('Wait for bitcoin space');\n\n program\n .command('watch')\n .requiredOption(\n '-a, --argons <argons>',\n 'Alert when bitcoin space exceeds this amount',\n parseFloat,\n )\n .description('Watch for bitcoin space available')\n .action(async ({ argons }) => {\n const accountset = await accountsetFromCli(program);\n const bot = new VaultMonitor(accountset, {\n bitcoinSpaceAvailable: argons ? BigInt(argons * MICROGONS_PER_ARGON) : 1n,\n });\n bot.events.on('bitcoin-space-above', async (vaultId, amount) => {\n const vault = bot.vaultsById[vaultId];\n const fee = vault.calculateBitcoinFee(amount);\n const ratio = (100n * fee) / amount;\n console.log(\n `Vault ${vaultId} has ${formatArgons(amount)} argons available for bitcoin. Fee ratio is ${ratio}%`,\n );\n });\n await bot.monitor();\n });\n\n program\n .command('wait-for-space')\n .description('Lock bitcoin when available at a given rate')\n .requiredOption(\n '-a, --argons <amount>',\n 'Bitcoin argons needed. NOTE: your account must have enough to cover fees + tip after this amount.',\n parseFloat,\n )\n .requiredOption('--bitcoin-xpub <xpub>', 'The xpub key to use for bitcoin locking')\n .option('--max-lock-fee <argons>', \"The max lock fee you're willing to pay\", parseFloat)\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat, 0.0)\n .action(async ({ argons, bitcoinXpub, maxLockFee, tip }) => {\n const amountToLock = BigInt(argons * MICROGONS_PER_ARGON);\n\n const accountset = await accountsetFromCli(program);\n await BitcoinLocks.waitForSpace(accountset, {\n argonAmount: amountToLock,\n bitcoinXpub,\n maxLockFee: maxLockFee !== undefined ? BigInt(maxLockFee * MICROGONS_PER_ARGON) : undefined,\n tip: BigInt(tip * MICROGONS_PER_ARGON),\n }).then(({ vaultId, satoshis, txFee, securityFee }) => {\n console.log(\n `Locked ${satoshis} satoshis in vault ${vaultId}. Tx fee=${formatArgons(\n txFee,\n )}, Lock fee=${formatArgons(securityFee)}.`,\n );\n process.exit(0);\n });\n });\n\n return program;\n}\n","import { createKeyringPair, Keyring, KeyringPair } from '../index';\nimport { promises } from 'node:fs';\nimport * as os from 'node:os';\n\nconst { readFile, writeFile } = promises;\n\nexport async function keyringFromFile(opts: {\n filePath: string;\n passphrase?: string;\n passphraseFile?: string;\n}): Promise<KeyringPair> {\n if (!opts.filePath) {\n throw new Error(\n 'No ACCOUNT account loaded (either ACCOUNT_SURI or ACCOUNT_JSON_PATH required)',\n );\n }\n const path = opts.filePath.replace('~', os.homedir());\n const json = JSON.parse(await readFile(path, 'utf-8'));\n let passphrase = opts.passphrase;\n if (opts.passphraseFile) {\n const passphrasePath = opts.passphraseFile.replace('~', os.homedir());\n passphrase = await readFile(passphrasePath, 'utf-8');\n }\n const mainAccount = new Keyring().createFromJson(json);\n mainAccount.decodePkcs8(passphrase);\n return mainAccount;\n}\n\nexport async function saveKeyringPair(opts: {\n filePath: string;\n passphrase?: string;\n cryptoType?: 'sr25519' | 'ed25519';\n}): Promise<KeyringPair> {\n const { filePath, passphrase, cryptoType } = opts;\n const keyring = createKeyringPair({ cryptoType });\n if (filePath) {\n const json = keyring.toJson(passphrase);\n await writeFile(filePath, JSON.stringify(json, null, 2));\n }\n return keyring;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/mainchain/mainchain/client/nodejs/lib/chunk-BP7Y2NWQ.cjs","../src/clis/index.ts","../src/clis/accountCli.ts","../src/clis/vaultCli.ts","../src/clis/miningCli.ts","../src/clis/liquidityCli.ts","../src/clis/bitcoinCli.ts","../src/clis/keyringStore.ts"],"names":["addresses","Command","printTable","unsubscribe","env"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACpBA,2DAAgC;ADsBhC;AACA;AEvBA;AAEA,4DAA2B;AAC3B,mDAAgC;AAChC,wBAA8B;AAG9B,oFAAyB;AAGV,SAAR,UAAA,CAAA,EAA8B;AACnC,EAAA,M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,IAAA;AACJ,IAAA;AACI,IAAA;AAEF,MAAA;AACG,QAAA;AACD,QAAA;AACd,MAAA;AACF,IAAA;AACF,EAAA;AACOG,EAAAA;AACT;AD8kBsB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/mainchain/mainchain/client/nodejs/lib/chunk-BP7Y2NWQ.cjs","sourcesContent":[null,"import { Command, Option } from '@commander-js/extra-typings';\nimport accountCli from './accountCli';\nimport { configDotenv } from 'dotenv';\nimport Path from 'node:path';\nimport vaultCli from './vaultCli';\nimport miningCli from './miningCli';\nimport liquidityCli from './liquidityCli';\nimport bitcoinCli from './bitcoinCli';\nimport { Accountset, parseSubaccountRange } from '../Accountset';\nimport { getClient, keyringFromSuri, KeyringPair } from '../index';\nimport { keyringFromFile, saveKeyringPair } from './keyringStore';\n\nexport {\n accountCli,\n vaultCli,\n miningCli,\n liquidityCli,\n bitcoinCli,\n keyringFromFile,\n saveKeyringPair,\n};\n\nexport function globalOptions(program: Command) {\n return program.optsWithGlobals() as IGlobalOptions;\n}\n\nexport function buildCli() {\n return new Command('Argon CLI')\n .option('-e, --env <path>', 'The path to the account .env file to load')\n .addOption(\n new Option('-u, --mainchain-url <url>', 'The mainchain URL to connect to')\n .default('wss://rpc.argon.network')\n .env('MAINCHAIN_URL'),\n )\n .addOption(\n new Option(\n '--account-file-path <jsonPath>',\n 'The path to your json seed file from polkadotjs',\n ).env('ACCOUNT_JSON_PATH'),\n )\n .addOption(\n new Option('--account-suri <secretUri>', 'A secret uri (suri) to use for the account').env(\n 'ACCOUNT_SURI',\n ),\n )\n .addOption(\n new Option('--account-passphrase <password>', 'The password for your seed file').env(\n 'ACCOUNT_PASSPHRASE',\n ),\n )\n .addOption(\n new Option('--account-passphrase-file <path>', 'The path to a password for your seed file'),\n )\n .addOption(\n new Option(\n '-s, --subaccounts <range>',\n 'Restrict this operation to a subset of the subaccounts (eg, 0-10)',\n )\n .env('SUBACCOUNT_RANGE')\n .argParser(parseSubaccountRange),\n )\n .addCommand(accountCli())\n .addCommand(vaultCli())\n .addCommand(miningCli())\n .addCommand(liquidityCli())\n .addCommand(bitcoinCli());\n}\n\nexport async function accountsetFromCli(\n program: Command,\n proxyForAddress?: string,\n): Promise<Accountset> {\n const opts = program.parent?.optsWithGlobals() as unknown as IGlobalOptions;\n\n let keypair: KeyringPair | undefined;\n if (opts.accountSuri) {\n keypair = keyringFromSuri(opts.accountSuri!);\n }\n if (opts.accountFilePath) {\n keypair = await keyringFromFile({\n filePath: opts.accountFilePath,\n passphrase: opts.accountPassphrase,\n passphraseFile: opts.accountPassphraseFile,\n });\n }\n if (!keypair) {\n throw new Error(\n 'No ACCOUNT account loaded (either ACCOUNT_SURI or ACCOUNT_JSON_PATH required)',\n );\n }\n\n const client = getClient(opts.mainchainUrl);\n if (proxyForAddress) {\n return new Accountset({\n client,\n isProxy: true,\n seedAddress: proxyForAddress,\n txSubmitter: keypair,\n });\n } else {\n return new Accountset({\n seedAccount: keypair,\n client,\n });\n }\n}\n\nexport type IGlobalOptions = ReturnType<ReturnType<typeof buildCli>['opts']>;\n\nexport function addGlobalArgs(program: ReturnType<typeof buildCli>) {\n for (const command of program.commands) {\n command.configureHelp({\n showGlobalOptions: true,\n });\n for (const nested of command.commands) {\n nested.configureHelp({\n showGlobalOptions: true,\n });\n }\n }\n}\n\nexport function applyEnv(program: ReturnType<typeof buildCli>): string | undefined {\n program.parseOptions(process.argv);\n const { env } = program.optsWithGlobals();\n if (env) {\n const envPath = Path.resolve(process.cwd(), env);\n const res = configDotenv({ path: envPath });\n if (res.parsed?.ACCOUNT_JSON_PATH) {\n // ensure path is relative to the env file if provided that way\n process.env.ACCOUNT_JSON_PATH = Path.resolve(\n Path.dirname(envPath),\n process.env.ACCOUNT_JSON_PATH!,\n );\n }\n }\n return env;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { filterUndefined, mnemonicGenerate } from '../index';\nimport { printTable } from 'console-table-printer';\nimport { cryptoWaitReady } from '@polkadot/util-crypto';\nimport { writeFileSync } from 'node:fs';\nimport { parseSubaccountRange } from '../Accountset';\nimport Env from '../env';\nimport * as process from 'node:process';\nimport { accountsetFromCli, globalOptions } from './index';\n\nexport default function accountCli() {\n const program = new Command('accounts').description('Manage subaccounts from a single keypair');\n\n program\n .command('watch')\n .description('Watch for blocks closed by subaccounts')\n .action(async () => {\n const accountset = await accountsetFromCli(program);\n const accountMiners = await accountset.watchBlocks();\n\n accountMiners.events.on('mined', (_block, mined) => {\n console.log('Your accounts authored a block', mined);\n });\n accountMiners.events.on('minted', (_block, minted) => {\n console.log('Your accounts minted argons', minted);\n });\n });\n\n program\n .command('list', { isDefault: true })\n .description('Show subaccounts')\n .option('--addresses', 'Just show a list of ids')\n .action(async ({ addresses }) => {\n const { subaccounts } = globalOptions(program);\n const accountset = await accountsetFromCli(program);\n\n if (addresses) {\n const addresses = accountset.addresses;\n console.log(addresses.join(','));\n process.exit(0);\n }\n const [argonots, argons, seats, bids] = await Promise.all([\n accountset.totalArgonotsAt(),\n accountset.totalArgonsAt(),\n accountset.miningSeats(),\n accountset.bids(),\n ]);\n const accountSubset = subaccounts ? accountset.getAccountsInRange(subaccounts) : undefined;\n const status = accountset.status({\n argons,\n argonots,\n accountSubset,\n seats,\n bids,\n });\n printTable(status);\n process.exit(0);\n });\n\n program\n .command('create')\n .description('Create an account \"env\" file and optionally register keys')\n .requiredOption(\n '--path <path>',\n 'The path to an env file to create (convention is .env.<name>)',\n )\n .option('--register-keys-to <url>', 'Register the keys to a url (normally this is localhost)')\n .action(async ({ registerKeysTo, path }) => {\n const { accountPassphrase, accountSuri, accountFilePath } = globalOptions(program);\n const accountset = await accountsetFromCli(program);\n process.env.KEYS_MNEMONIC ||= mnemonicGenerate();\n if (registerKeysTo) {\n await accountset.registerKeys(registerKeysTo);\n console.log('Keys registered to', registerKeysTo);\n }\n const envData = filterUndefined<Env>({\n ACCOUNT_JSON_PATH: accountFilePath,\n ACCOUNT_SURI: accountSuri,\n ACCOUNT_PASSPHRASE: accountPassphrase,\n KEYS_MNEMONIC: process.env.KEYS_MNEMONIC,\n SUBACCOUNT_RANGE: '0-49',\n });\n let envfile = '';\n for (const [key, value] of Object.entries(envData)) {\n if (key) {\n const line = `${key}=${String(value)}`;\n envfile += line + '\\n';\n }\n }\n writeFileSync(path, envfile);\n console.log('Created env file at', path);\n process.exit();\n });\n\n program\n .command('new-key-seed')\n .description('Create a new mnemonic for runtime keys')\n .action(async () => {\n await cryptoWaitReady();\n const mnemonic = mnemonicGenerate();\n console.log('New mnemonic (add this to your .env as KEYS_MNEMONIC):', mnemonic);\n process.exit(0);\n });\n\n program\n .command('register-keys')\n .description('Create an insert-keys script with curl')\n .argument(\n '[node-rpc-url]',\n 'The url to your node host (should be installed on machine via localhost)',\n 'http://localhost:9944',\n )\n .option('--print-only', 'Output as curl commands instead of direct registration')\n .action(async (nodeRpcUrl, { printOnly }) => {\n const accountset = await accountsetFromCli(program);\n if (printOnly) {\n const { gran, seal } = accountset.keys();\n const commands: string[] = [];\n const data = [\n {\n jsonrpc: '2.0',\n id: 0,\n method: 'author_insertKey',\n params: ['gran', gran.privateKey, gran.publicKey],\n },\n {\n jsonrpc: '2.0',\n id: 1,\n method: 'author_insertKey',\n params: ['seal', seal.privateKey, seal.publicKey],\n },\n ];\n for (const key of data) {\n commands.push(\n `curl -X POST -H \"Content-Type: application/json\" -d '${JSON.stringify(key)}' ${nodeRpcUrl}`,\n );\n }\n\n console.log(commands.join(' && '));\n } else {\n await accountset.registerKeys(nodeRpcUrl);\n }\n process.exit();\n });\n\n program\n .command('consolidate')\n .description('Consolidate all argons into parent account')\n .option(\n '-s, --subaccounts <range>',\n 'Restrict this operation to a subset of the subaccounts (eg, 0-10)',\n parseSubaccountRange,\n )\n .action(async ({ subaccounts }) => {\n const accountset = await accountsetFromCli(program);\n const result = await accountset.consolidate(subaccounts);\n printTable(result);\n process.exit(0);\n });\n return program;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { VaultMonitor } from '../VaultMonitor';\nimport { TxSubmitter } from '../TxSubmitter';\nimport { Vault } from '../Vault';\nimport { BitcoinLocks } from '../BitcoinLocks';\nimport { accountsetFromCli } from './index';\nimport { MICROGONS_PER_ARGON } from '../utils';\nimport { hexToU8a } from '@polkadot/util';\n\nexport default function vaultCli() {\n const program = new Command('vaults').description('Monitor vaults and manage securitization');\n\n program\n .command('list', { isDefault: true })\n .description('Show current state of vaults')\n .action(async () => {\n const accountset = await accountsetFromCli(program);\n const vaults = new VaultMonitor(accountset, undefined, {\n vaultOnlyWatchMode: true,\n });\n await vaults.monitor(true);\n process.exit(0);\n });\n\n program\n .command('modify-securitization')\n .description('Change the vault securitization ratio')\n .requiredOption('-v, --vault-id <id>', 'The vault id to use', parseInt)\n .requiredOption(\n '-a, --argons <amount>',\n 'The number of argons to set as securitization',\n parseFloat,\n )\n .option('--ratio <ratio>', 'The new securitization ratio', parseFloat)\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat)\n .action(async ({ tip, argons, vaultId, ratio }) => {\n const accountset = await accountsetFromCli(program);\n const client = await accountset.client;\n const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;\n const microgons = BigInt(argons * MICROGONS_PER_ARGON);\n\n const rawVault = (await client.query.vaults.vaultsById(vaultId)).unwrap();\n if (rawVault.operatorAccountId.toHuman() !== accountset.seedAddress) {\n console.error('Vault does not belong to this account');\n process.exit(1);\n }\n const existingFunds = rawVault.securitization.toBigInt();\n const additionalFunds = microgons > existingFunds ? microgons - existingFunds : 0n;\n const tx = client.tx.vaults.modifyFunding(\n vaultId,\n microgons,\n ratio !== undefined\n ? BigNumber(ratio).times(BigNumber(2).pow(64)).toFixed(0)\n : rawVault.securitizationRatio.toBigInt(),\n );\n const submit = new TxSubmitter(client, tx, accountset.txSubmitterPair);\n const canAfford = await submit.canAfford({\n tip: resolvedTip,\n unavailableBalance: additionalFunds,\n });\n if (!canAfford.canAfford) {\n console.warn('Insufficient balance to modify vault securitization', {\n ...canAfford,\n addedSecuritization: additionalFunds,\n });\n process.exit(1);\n }\n try {\n const result = await submit.submit({ tip: resolvedTip });\n await result.inBlockPromise;\n console.log('Vault securitization modified');\n process.exit();\n } catch (error) {\n console.error('Error modifying vault securitization', error);\n process.exit(1);\n }\n });\n\n program\n .command('make-bitcoin-space')\n .description('Make bitcoin space in a vault and lock it immediately in the same tx.')\n .requiredOption('-v, --vault-id <id>', 'The vault id to use', parseInt)\n .requiredOption('-a, --argons <amount>', 'The number of argons to add', parseFloat)\n .requiredOption('--bitcoin-pubkey <pubkey>', 'The pubkey to use for the bitcoin lock')\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat)\n .action(async ({ tip, argons, vaultId, bitcoinPubkey }) => {\n let pubkey = bitcoinPubkey;\n if (!bitcoinPubkey.startsWith('0x')) {\n pubkey = `0x${bitcoinPubkey}`;\n }\n if (pubkey.length !== 68) {\n throw new Error('Bitcoin pubkey must be 66 characters (add 0x in front optionally)');\n }\n const accountset = await accountsetFromCli(program);\n const client = await accountset.client;\n const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;\n const microgons = BigInt(argons * MICROGONS_PER_ARGON);\n const bitcoinLocks = new BitcoinLocks(Promise.resolve(client));\n const existentialDeposit = client.consts.balances.existentialDeposit.toBigInt();\n const tickDuration = (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();\n\n const rawVault = (await client.query.vaults.vaultsById(vaultId)).unwrap();\n if (rawVault.operatorAccountId.toHuman() !== accountset.seedAddress) {\n console.error('Vault does not belong to this account');\n process.exit(1);\n }\n const vaultModifyTx = client.tx.vaults.modifyFunding(\n vaultId,\n microgons,\n rawVault.securitizationRatio.toBigInt(),\n );\n const vaultTxFee = (\n await vaultModifyTx.paymentInfo(accountset.txSubmitterPair)\n ).partialFee.toBigInt();\n const vault = new Vault(vaultId, rawVault, tickDuration);\n\n const argonsNeeded = microgons - vault.securitization;\n const argonsAvailable = microgons - vault.availableBitcoinSpace();\n\n const account = await client.query.system.account(accountset.seedAddress);\n const freeBalance = account.data.free.toBigInt();\n let satoshis = await bitcoinLocks.requiredSatoshisForArgonLiquidity(argonsAvailable);\n satoshis -= 20n; // keep some wiggle room since price can change\n const {\n tx: lockTx,\n securityFee: btcFee,\n txFee,\n } = await bitcoinLocks.createInitializeLockTx({\n vault,\n argonKeyring: accountset.txSubmitterPair,\n satoshis,\n ownerBitcoinPubkey: hexToU8a(pubkey),\n tip: resolvedTip,\n reducedBalanceBy: argonsNeeded + vaultTxFee + resolvedTip,\n });\n if (\n argonsNeeded + txFee + vaultTxFee + resolvedTip + btcFee + existentialDeposit >\n freeBalance\n ) {\n console.warn('Insufficient balance to add bitcoin space and use bitcoins', {\n freeBalance,\n txFee,\n vaultTxFee,\n btcFee,\n argonsAvailable,\n vaultMicrogons: microgons,\n existentialDeposit,\n neededBalanceAboveED: argonsNeeded + txFee + resolvedTip + btcFee + vaultTxFee,\n });\n process.exit(1);\n }\n console.log('Adding bitcoin space and locking bitcoins...', {\n newArgonsAvailable: argonsAvailable,\n txFee,\n vaultTxFee,\n btcFee,\n resolvedTip,\n });\n\n const txSubmitter = new TxSubmitter(\n client,\n client.tx.utility.batchAll([vaultModifyTx, lockTx]),\n accountset.txSubmitterPair,\n );\n const result = await txSubmitter.submit({ tip: resolvedTip });\n try {\n await result.inBlockPromise;\n console.log('Bitcoin space done');\n } catch (error) {\n console.error('Error using bitcoin space', error);\n process.exit(1);\n }\n });\n return program;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { getClient, type KeyringPair, MICROGONS_PER_ARGON } from '../index';\nimport { printTable } from 'console-table-printer';\nimport { MiningBids } from '../MiningBids';\nimport { formatArgons } from '../utils';\nimport { TxSubmitter } from '../TxSubmitter';\nimport { accountsetFromCli, globalOptions, saveKeyringPair } from './index';\nimport { CohortBidder } from '../CohortBidder';\n\nexport default function miningCli() {\n const program = new Command('mining').description('Watch mining seats or setup bidding');\n\n program\n .command('list', { isDefault: true })\n .description('Monitor all miners')\n .action(async () => {\n const accountset = await accountsetFromCli(program);\n const bids = new MiningBids(accountset.client);\n const api = await accountset.client;\n let lastMiners: {\n [frameId: string]: {\n miner: string;\n bid?: bigint;\n isLastDay?: boolean;\n };\n } = {};\n\n function print(blockNumber: number) {\n console.clear();\n const toPrint = Object.entries(lastMiners).map(([seat, miner]) => ({\n seat,\n ...miner,\n }));\n if (!toPrint.length) {\n console.log('No active miners');\n } else {\n console.log(`Miners at block ${blockNumber}`);\n printTable(\n toPrint.map(x => ({\n ...x,\n bid: x.bid ? formatArgons(x.bid) : '-',\n isLastDay: x.isLastDay ? 'Y' : '',\n miner: x.miner,\n })),\n );\n }\n if (!bids.nextCohort.length) {\n console.log('-------------------------------------\\nNo bids for next cohort');\n } else {\n bids.print();\n }\n }\n\n const { unsubscribe } = await bids.watch(accountset.namedAccounts, undefined, print);\n console.log('Watching miners...');\n const minMiners = api.consts.miningSlot.minCohortSize.toNumber();\n\n const unsub = await api.query.miningSlot.nextFrameId(async nextFrameId => {\n const frames = new Array(nextFrameId.toNumber())\n .fill(0)\n .map((_, i) => nextFrameId.toNumber() - i)\n .sort();\n const unseenFrames = new Set(frames);\n const entries = await api.query.miningSlot.minersByCohort.entries();\n const block = await api.query.system.number();\n\n const sortedEntries = entries.sort((a, b) => {\n const aIndex = a[0].args[0].toNumber();\n const bIndex = b[0].args[0].toNumber();\n return aIndex - bIndex;\n });\n\n for (const [rawFrameId, miners] of sortedEntries) {\n const frameId = rawFrameId.args[0].toNumber();\n unseenFrames.delete(frameId);\n let i = 0;\n for (const miner of miners) {\n const address = miner.accountId.toHuman();\n const startingFrameId = miner.startingFrameId.toNumber();\n lastMiners[`${frameId}-${i}`] = {\n miner: accountset.namedAccounts.get(address) ?? address,\n bid: miner.bid.toBigInt(),\n isLastDay: nextFrameId.toNumber() - startingFrameId === 10,\n };\n i++;\n }\n while (i < minMiners) {\n lastMiners[`${frameId}-${i}`] = {\n miner: 'none',\n };\n i++;\n }\n }\n for (const frameId of unseenFrames) {\n for (let i = 0; i < minMiners; i++) {\n lastMiners[`${frameId}-${i}`] = {\n miner: 'none',\n };\n }\n }\n print(block.toNumber());\n });\n process.on('SIGINT', () => {\n unsubscribe();\n unsub();\n process.exit(0);\n });\n });\n\n program\n .command('bid')\n .description('Submit mining bids within a range of parameters')\n .option('--min-bid <amount>', 'The minimum bid amount to use', parseFloat)\n .option('--max-bid <amount>', 'The maximum bid amount to use', parseFloat)\n .option('--max-seats <n>', 'The maximum number of seats to bid on for the slot', parseInt)\n .option(\n '--max-balance <argons>',\n \"Use a maximum amount of the user's balance for the slot. If this ends in a percent, it will be a percent of the funds\",\n )\n .option('--bid-increment <argons>', 'The bid increment', parseFloat, 0.01)\n .option('--bid-delay <ticks>', 'Delay between bids in ticks', parseInt, 0)\n .option('--run-continuous', 'Keep running and rebid every day')\n .option(\n '--proxy-for-address <address>',\n 'The seed account to proxy for (eg: 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty)',\n )\n .action(\n async ({\n maxSeats,\n runContinuous,\n maxBid,\n minBid,\n maxBalance,\n bidDelay,\n bidIncrement,\n proxyForAddress,\n }) => {\n const accountset = await accountsetFromCli(program, proxyForAddress);\n\n let cohortBidder: CohortBidder | undefined;\n const miningBids = new MiningBids(accountset.client, false);\n const maxCohortSize = await miningBids.maxCohortSize();\n\n const stopBidder = async (unsubscribe: () => void) => {\n if (cohortBidder) {\n const stats = await cohortBidder.stop();\n console.log('Final bidding result', {\n cohortStartingFrameId: cohortBidder.cohortStartingFrameId,\n ...stats,\n });\n cohortBidder = undefined;\n if (!runContinuous) {\n unsubscribe();\n process.exit();\n }\n }\n };\n const { unsubscribe } = await miningBids.onCohortChange({\n async onBiddingEnd(cohortStartingFrameId) {\n if (cohortBidder?.cohortStartingFrameId === cohortStartingFrameId) {\n await stopBidder(unsubscribe);\n }\n },\n async onBiddingStart(cohortStartingFrameId) {\n const seatsToWin = maxSeats ?? maxCohortSize;\n const balance = await accountset.balance();\n const feeWiggleRoom = BigInt(25e3);\n const amountAvailable = balance - feeWiggleRoom;\n let maxBidAmount = maxBid ? BigInt(maxBid * MICROGONS_PER_ARGON) : undefined;\n let maxBalanceToUse = amountAvailable;\n if (maxBalance !== undefined) {\n if (maxBalance!.endsWith('%')) {\n let maxBalancePercent = parseInt(maxBalance);\n let amountToBid = (amountAvailable * BigInt(maxBalancePercent)) / 100n;\n if (amountToBid > balance) {\n amountToBid = balance;\n }\n maxBalanceToUse = amountToBid;\n } else {\n maxBalanceToUse = BigInt(Math.floor(parseFloat(maxBalance) * MICROGONS_PER_ARGON));\n }\n\n maxBidAmount ??= maxBalanceToUse / BigInt(seatsToWin);\n }\n if (maxBalanceToUse > amountAvailable) {\n maxBalanceToUse = amountAvailable;\n }\n if (!maxBidAmount) {\n console.error('No max bid amount set');\n process.exit(1);\n }\n const subaccountRange = await accountset.getAvailableMinerAccounts(seatsToWin);\n\n if (cohortBidder && cohortBidder?.cohortStartingFrameId !== cohortStartingFrameId) {\n await stopBidder(unsubscribe);\n }\n cohortBidder = new CohortBidder(accountset, cohortStartingFrameId, subaccountRange, {\n maxBid: maxBidAmount,\n minBid: BigInt((minBid ?? 0) * MICROGONS_PER_ARGON),\n bidIncrement: BigInt(Math.floor(bidIncrement * MICROGONS_PER_ARGON)),\n maxBudget: maxBalanceToUse,\n bidDelay,\n });\n await cohortBidder.start();\n },\n });\n },\n );\n\n program\n .command('create-bid-proxy')\n .description('Create a mining-bid proxy account for your main account')\n .requiredOption(\n '--outfile <path>',\n 'The file to use to store the proxy account json (eg: proxy.json)',\n )\n .requiredOption(\n '--fee-argons <argons>',\n 'How many argons should be sent to the proxy account for fees (proxies must pay fees)',\n parseFloat,\n )\n .option('--proxy-passphrase <passphrase>', 'The passphrase for your proxy account')\n .action(async ({ outfile, proxyPassphrase, feeArgons }) => {\n const { mainchainUrl } = globalOptions(program);\n const client = await getClient(mainchainUrl);\n\n const keyringPair = await saveKeyringPair({\n filePath: outfile,\n passphrase: proxyPassphrase,\n });\n const address = keyringPair.address;\n console.log(`✅ Created proxy account at \"${outfile}\" with address ${address}`);\n const tx = client.tx.utility.batchAll([\n client.tx.proxy.addProxy(address, 'MiningBid', 0),\n client.tx.balances.transferAllowDeath(address, BigInt(feeArgons * MICROGONS_PER_ARGON)),\n ]);\n let keypair: KeyringPair;\n try {\n const accountset = await accountsetFromCli(program);\n keypair = accountset.txSubmitterPair;\n } catch (e) {\n const polkadotLink = `https://polkadot.js.org/apps/?rpc=${mainchainUrl}#/extrinsics/decode/${tx.toHex()}`;\n console.log(`Complete the registration at this link:`, polkadotLink);\n process.exit(0);\n }\n try {\n await new TxSubmitter(client, tx, keypair).submit({\n waitForBlock: true,\n });\n\n console.log('Mining bid proxy added and funded.');\n process.exit();\n } catch (error) {\n console.error('Error adding mining proxy', error);\n process.exit(1);\n }\n });\n return program;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { BidPool } from '../BidPool';\nimport { VaultMonitor } from '../VaultMonitor';\nimport { formatArgons, MICROGONS_PER_ARGON } from '../utils';\nimport { accountsetFromCli } from './index';\n\nexport default function liquidityCli() {\n const program = new Command('liquidity-pools').description('Monitor or bond to liquidity pools');\n program\n .command('list', { isDefault: true })\n .description('Show or watch the vault bid pool rewards')\n .action(async () => {\n const accountset = await accountsetFromCli(program);\n const bidPool = new BidPool(accountset.client, accountset.txSubmitterPair);\n await bidPool.watch();\n });\n\n program\n .command('bond')\n .description('Bond argons to a liquidity pool')\n .requiredOption('-v, --vault-id <id>', 'The vault id to use', parseInt)\n .requiredOption('-a, --argons <amount>', 'The number of argons to set the vault to', parseFloat)\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat)\n .action(async ({ tip, argons, vaultId }) => {\n const accountset = await accountsetFromCli(program);\n const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;\n\n const microgons = BigInt(argons * MICROGONS_PER_ARGON);\n const bidPool = new BidPool(accountset.client, accountset.txSubmitterPair);\n await bidPool.bondArgons(vaultId, microgons, { tip: resolvedTip });\n console.log('Bonded argons to liquidity pool bond');\n process.exit();\n });\n\n program\n .command('wait-for-space')\n .description('Add bonded argons to a liquidity pool when the market rate is favorable')\n .requiredOption('--max-argons <amount>', 'Max daily argons to use per slot', parseFloat)\n .option(\n '--min-pct-sharing <percent>',\n 'The minimum profit sharing percent to allow',\n parseInt,\n 30,\n )\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat)\n .action(async ({ maxArgons, minPctSharing, tip }) => {\n const maxAmountPerSlot = BigInt(maxArgons * MICROGONS_PER_ARGON);\n\n const accountset = await accountsetFromCli(program);\n const vaults = new VaultMonitor(\n accountset,\n {\n liquidityPoolSpaceAvailable: 1_000_000n,\n },\n { shouldLog: false },\n );\n const bidPool = new BidPool(accountset.client, accountset.txSubmitterPair);\n const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;\n console.log('Waiting for liquidity pool space...');\n\n vaults.events.on('liquidity-pool-space-above', async (vaultId, amount) => {\n const vault = vaults.vaultsById[vaultId];\n if (vault.terms.liquidityPoolProfitSharing.times(100).toNumber() < minPctSharing) {\n console.info(\n `Skipping vault ${vaultId} due to lower profit sharing than ${minPctSharing}%`,\n );\n return;\n }\n let amountToAdd = amount;\n if (amountToAdd > maxAmountPerSlot) {\n amountToAdd = maxAmountPerSlot;\n }\n await bidPool.bondArgons(vaultId, amountToAdd, { tip: resolvedTip });\n console.log('Bonding argons to vault liquidity pool', {\n vaultId,\n amount: formatArgons(amountToAdd),\n });\n });\n await vaults.monitor();\n });\n return program;\n}\n","import { Command } from '@commander-js/extra-typings';\nimport { VaultMonitor } from '../VaultMonitor';\nimport { BitcoinLocks } from '../BitcoinLocks';\nimport { formatArgons, MICROGONS_PER_ARGON } from '../utils';\nimport { accountsetFromCli } from './index';\n\nexport default function bitcoinCli() {\n const program = new Command('bitcoin').description('Wait for bitcoin space');\n\n program\n .command('watch')\n .requiredOption(\n '-a, --argons <argons>',\n 'Alert when bitcoin space exceeds this amount',\n parseFloat,\n )\n .description('Watch for bitcoin space available')\n .action(async ({ argons }) => {\n const accountset = await accountsetFromCli(program);\n const bot = new VaultMonitor(accountset, {\n bitcoinSpaceAvailable: argons ? BigInt(argons * MICROGONS_PER_ARGON) : 1n,\n });\n bot.events.on('bitcoin-space-above', async (vaultId, amount) => {\n const vault = bot.vaultsById[vaultId];\n const fee = vault.calculateBitcoinFee(amount);\n const ratio = (100n * fee) / amount;\n console.log(\n `Vault ${vaultId} has ${formatArgons(amount)} argons available for bitcoin. Fee ratio is ${ratio}%`,\n );\n });\n await bot.monitor();\n });\n\n program\n .command('wait-for-space')\n .description('Lock bitcoin when available at a given rate')\n .requiredOption(\n '-a, --argons <amount>',\n 'Bitcoin argons needed. NOTE: your account must have enough to cover fees + tip after this amount.',\n parseFloat,\n )\n .requiredOption('--bitcoin-xpub <xpub>', 'The xpub key to use for bitcoin locking')\n .option('--max-lock-fee <argons>', \"The max lock fee you're willing to pay\", parseFloat)\n .option('--tip <amount>', 'The tip to include with the transaction', parseFloat, 0.0)\n .action(async ({ argons, bitcoinXpub, maxLockFee, tip }) => {\n const amountToLock = BigInt(argons * MICROGONS_PER_ARGON);\n\n const accountset = await accountsetFromCli(program);\n await BitcoinLocks.waitForSpace(accountset, {\n argonAmount: amountToLock,\n bitcoinXpub,\n maxLockFee: maxLockFee !== undefined ? BigInt(maxLockFee * MICROGONS_PER_ARGON) : undefined,\n tip: BigInt(tip * MICROGONS_PER_ARGON),\n }).then(({ vaultId, satoshis, txFee, securityFee }) => {\n console.log(\n `Locked ${satoshis} satoshis in vault ${vaultId}. Tx fee=${formatArgons(\n txFee,\n )}, Lock fee=${formatArgons(securityFee)}.`,\n );\n process.exit(0);\n });\n });\n\n return program;\n}\n","import { createKeyringPair, Keyring, KeyringPair } from '../index';\nimport { promises } from 'node:fs';\nimport * as os from 'node:os';\n\nconst { readFile, writeFile } = promises;\n\nexport async function keyringFromFile(opts: {\n filePath: string;\n passphrase?: string;\n passphraseFile?: string;\n}): Promise<KeyringPair> {\n if (!opts.filePath) {\n throw new Error(\n 'No ACCOUNT account loaded (either ACCOUNT_SURI or ACCOUNT_JSON_PATH required)',\n );\n }\n const path = opts.filePath.replace('~', os.homedir());\n const json = JSON.parse(await readFile(path, 'utf-8'));\n let passphrase = opts.passphrase;\n if (opts.passphraseFile) {\n const passphrasePath = opts.passphraseFile.replace('~', os.homedir());\n passphrase = await readFile(passphrasePath, 'utf-8');\n }\n const mainAccount = new Keyring().createFromJson(json);\n mainAccount.decodePkcs8(passphrase);\n return mainAccount;\n}\n\nexport async function saveKeyringPair(opts: {\n filePath: string;\n passphrase?: string;\n cryptoType?: 'sr25519' | 'ed25519';\n}): Promise<KeyringPair> {\n const { filePath, passphrase, cryptoType } = opts;\n const keyring = createKeyringPair({ cryptoType });\n if (filePath) {\n const json = keyring.toJson(passphrase);\n await writeFile(filePath, JSON.stringify(json, null, 2));\n }\n return keyring;\n}\n"]}
|
|
@@ -123,20 +123,21 @@ var TxSubmitter = class {
|
|
|
123
123
|
const { tip, unavailableBalance } = options;
|
|
124
124
|
const account = await this.client.query.system.account(this.pair.address);
|
|
125
125
|
let availableBalance = account.data.free.toBigInt();
|
|
126
|
+
const userBalance = availableBalance;
|
|
126
127
|
if (unavailableBalance) {
|
|
127
128
|
availableBalance -= unavailableBalance;
|
|
128
129
|
}
|
|
129
130
|
const existentialDeposit = options.includeExistentialDeposit ? this.client.consts.balances.existentialDeposit.toBigInt() : 0n;
|
|
130
131
|
const fees = await this.feeEstimate(tip);
|
|
131
132
|
const totalCharge = fees + (tip ?? 0n);
|
|
132
|
-
const canAfford = availableBalance
|
|
133
|
-
return { canAfford, availableBalance, txFee: fees };
|
|
133
|
+
const canAfford = availableBalance >= totalCharge + existentialDeposit;
|
|
134
|
+
return { canAfford, availableBalance: userBalance, txFee: fees };
|
|
134
135
|
}
|
|
135
136
|
async submit(options = {}) {
|
|
136
137
|
const { logResults, waitForBlock, useLatestNonce, ...apiOptions } = options;
|
|
137
138
|
await waitForLoad();
|
|
138
139
|
const result = new TxResult(this.client, logResults);
|
|
139
|
-
result.
|
|
140
|
+
result.txProgressCallback = options.txProgressCallback;
|
|
140
141
|
let toHuman = this.tx.toHuman().method;
|
|
141
142
|
let txString = [];
|
|
142
143
|
let api = formatCall(toHuman);
|
|
@@ -202,7 +203,7 @@ var TxResult = class {
|
|
|
202
203
|
* The fee tip paid for the transaction.
|
|
203
204
|
*/
|
|
204
205
|
finalFeeTip;
|
|
205
|
-
|
|
206
|
+
txProgressCallback;
|
|
206
207
|
inBlockResolve;
|
|
207
208
|
inBlockReject;
|
|
208
209
|
finalizedResolve;
|
|
@@ -240,7 +241,15 @@ var TxResult = class {
|
|
|
240
241
|
if (isFinalized) {
|
|
241
242
|
this.finalizedResolve(status.asFinalized);
|
|
242
243
|
}
|
|
243
|
-
this.
|
|
244
|
+
if (this.txProgressCallback) {
|
|
245
|
+
let percent = 0;
|
|
246
|
+
if (result.status.isBroadcast) {
|
|
247
|
+
percent = 50;
|
|
248
|
+
} else if (result.status.isInBlock) {
|
|
249
|
+
percent = 100;
|
|
250
|
+
}
|
|
251
|
+
this.txProgressCallback(percent, this);
|
|
252
|
+
}
|
|
244
253
|
}
|
|
245
254
|
reject(error) {
|
|
246
255
|
this.inBlockReject(error);
|
|
@@ -250,13 +259,12 @@ var TxResult = class {
|
|
|
250
259
|
|
|
251
260
|
// src/utils.ts
|
|
252
261
|
import BigNumber, * as BN from "bignumber.js";
|
|
253
|
-
import { hexToU8a } from "@polkadot/util";
|
|
254
262
|
var { ROUND_FLOOR } = BN;
|
|
255
263
|
var MICROGONS_PER_ARGON = 1e6;
|
|
256
|
-
function formatArgons(
|
|
257
|
-
if (
|
|
258
|
-
const isNegative =
|
|
259
|
-
let format = BigNumber(
|
|
264
|
+
function formatArgons(microgons) {
|
|
265
|
+
if (microgons === void 0 || microgons === null) return "na";
|
|
266
|
+
const isNegative = microgons < 0;
|
|
267
|
+
let format = BigNumber(microgons.toString()).abs().div(MICROGONS_PER_ARGON).toFormat(2, ROUND_FLOOR);
|
|
260
268
|
if (format.endsWith(".00")) {
|
|
261
269
|
format = format.slice(0, -3);
|
|
262
270
|
}
|
|
@@ -400,7 +408,7 @@ var JsonExt = class {
|
|
|
400
408
|
return BigInt(v.slice(0, -1));
|
|
401
409
|
}
|
|
402
410
|
if (typeof v === "object" && v !== null && v.type === "Buffer" && Array.isArray(v.data)) {
|
|
403
|
-
return
|
|
411
|
+
return Uint8Array.from(v.data);
|
|
404
412
|
}
|
|
405
413
|
return v;
|
|
406
414
|
});
|
|
@@ -1292,21 +1300,21 @@ var MiningBids = class {
|
|
|
1292
1300
|
// src/Vault.ts
|
|
1293
1301
|
import BigNumber2, * as BN2 from "bignumber.js";
|
|
1294
1302
|
import bs58check from "bs58check";
|
|
1295
|
-
import { hexToU8a
|
|
1303
|
+
import { hexToU8a } from "@polkadot/util";
|
|
1296
1304
|
var { ROUND_FLOOR: ROUND_FLOOR2 } = BN2;
|
|
1297
1305
|
var Vault = class _Vault {
|
|
1298
1306
|
constructor(id, vault, tickDuration) {
|
|
1299
1307
|
this.tickDuration = tickDuration;
|
|
1300
1308
|
this.vaultId = id;
|
|
1301
|
-
this.load(vault);
|
|
1302
1309
|
this.openedTick = vault.openedTick.toNumber();
|
|
1303
1310
|
this.openedDate = new Date(this.openedTick * this.tickDuration);
|
|
1311
|
+
this.argonsScheduledForRelease = /* @__PURE__ */ new Map();
|
|
1312
|
+
this.load(vault);
|
|
1304
1313
|
}
|
|
1305
1314
|
securitization;
|
|
1306
|
-
securitizationRatio;
|
|
1307
1315
|
argonsLocked;
|
|
1308
1316
|
argonsPendingActivation;
|
|
1309
|
-
argonsScheduledForRelease
|
|
1317
|
+
argonsScheduledForRelease;
|
|
1310
1318
|
terms;
|
|
1311
1319
|
operatorAccountId;
|
|
1312
1320
|
isClosed;
|
|
@@ -1315,9 +1323,12 @@ var Vault = class _Vault {
|
|
|
1315
1323
|
pendingTermsChangeTick;
|
|
1316
1324
|
openedDate;
|
|
1317
1325
|
openedTick;
|
|
1326
|
+
securitizationRatio;
|
|
1318
1327
|
load(vault) {
|
|
1319
1328
|
this.securitization = vault.securitization.toBigInt();
|
|
1320
|
-
this.securitizationRatio = convertFixedU128ToBigNumber(
|
|
1329
|
+
this.securitizationRatio = convertFixedU128ToBigNumber(
|
|
1330
|
+
vault.securitizationRatio.toBigInt()
|
|
1331
|
+
).toNumber();
|
|
1321
1332
|
this.argonsLocked = vault.argonsLocked.toBigInt();
|
|
1322
1333
|
this.argonsPendingActivation = vault.argonsPendingActivation.toBigInt();
|
|
1323
1334
|
if (vault.argonsScheduledForRelease.size > 0) {
|
|
@@ -1359,21 +1370,21 @@ var Vault = class _Vault {
|
|
|
1359
1370
|
getRelockCapacity() {
|
|
1360
1371
|
return [...this.argonsScheduledForRelease.values()].reduce((acc, val) => acc + val, 0n);
|
|
1361
1372
|
}
|
|
1373
|
+
securitizationRatioBN() {
|
|
1374
|
+
return new BigNumber2(this.securitizationRatio);
|
|
1375
|
+
}
|
|
1362
1376
|
recoverySecuritization() {
|
|
1363
|
-
const reserved = new BigNumber2(1).div(this.
|
|
1377
|
+
const reserved = new BigNumber2(1).div(this.securitizationRatioBN());
|
|
1364
1378
|
return this.securitization - BigInt(reserved.multipliedBy(this.securitization.toString()).toFixed(0, ROUND_FLOOR2));
|
|
1365
1379
|
}
|
|
1366
1380
|
minimumSecuritization() {
|
|
1367
1381
|
return BigInt(
|
|
1368
|
-
this.
|
|
1382
|
+
this.securitizationRatioBN().multipliedBy(this.argonsLocked.toString()).decimalPlaces(0, BigNumber2.ROUND_CEIL).toString()
|
|
1369
1383
|
);
|
|
1370
1384
|
}
|
|
1371
1385
|
activatedSecuritization() {
|
|
1372
1386
|
const activated = this.argonsLocked - this.argonsPendingActivation;
|
|
1373
|
-
|
|
1374
|
-
if (this.securitizationRatio.toNumber() > 2) {
|
|
1375
|
-
maxRatio = BigNumber2(2);
|
|
1376
|
-
}
|
|
1387
|
+
const maxRatio = BigNumber2(Math.min(this.securitizationRatio, 2));
|
|
1377
1388
|
return BigInt(maxRatio.multipliedBy(activated.toString()).toFixed(0, ROUND_FLOOR2));
|
|
1378
1389
|
}
|
|
1379
1390
|
/**
|
|
@@ -1404,9 +1415,9 @@ var Vault = class _Vault {
|
|
|
1404
1415
|
bitcoinXpub,
|
|
1405
1416
|
tip,
|
|
1406
1417
|
doNotExceedBalance,
|
|
1407
|
-
|
|
1418
|
+
txProgressCallback
|
|
1408
1419
|
} = args;
|
|
1409
|
-
let xpubBytes =
|
|
1420
|
+
let xpubBytes = hexToU8a(bitcoinXpub);
|
|
1410
1421
|
if (xpubBytes.length !== 78) {
|
|
1411
1422
|
if (bitcoinXpub.startsWith("xpub") || bitcoinXpub.startsWith("tpub") || bitcoinXpub.startsWith("zpub")) {
|
|
1412
1423
|
const bytes = bs58check.decode(bitcoinXpub);
|
|
@@ -1447,21 +1458,7 @@ var Vault = class _Vault {
|
|
|
1447
1458
|
tip,
|
|
1448
1459
|
useLatestNonce: true,
|
|
1449
1460
|
waitForBlock: true,
|
|
1450
|
-
|
|
1451
|
-
let percent = 0;
|
|
1452
|
-
if (result2.status.isInvalid || result2.status.isDropped || result2.status.isUsurped || result2.status.isRetracted) {
|
|
1453
|
-
percent = 1;
|
|
1454
|
-
} else if (result2.status.isReady) {
|
|
1455
|
-
percent = 0;
|
|
1456
|
-
} else if (result2.status.isBroadcast) {
|
|
1457
|
-
percent = 0.5;
|
|
1458
|
-
} else if (result2.status.isInBlock) {
|
|
1459
|
-
percent = 1;
|
|
1460
|
-
} else if (result2.status.isFinalized) {
|
|
1461
|
-
percent = 1.1;
|
|
1462
|
-
}
|
|
1463
|
-
progressCallback?.(percent, result2.status);
|
|
1464
|
-
}
|
|
1461
|
+
txProgressCallback
|
|
1465
1462
|
});
|
|
1466
1463
|
await result.inBlockPromise;
|
|
1467
1464
|
let vaultId;
|
|
@@ -1568,7 +1565,7 @@ var VaultMonitor = class {
|
|
|
1568
1565
|
id: vaultId,
|
|
1569
1566
|
btcSpace: `${formatArgons(vault.availableBitcoinSpace())} (${formatArgons(vault.argonsPendingActivation)} pending)`,
|
|
1570
1567
|
btcDeal: `${formatArgons(vault.terms.bitcoinBaseFee)} + ${formatPercent(vault.terms.bitcoinAnnualPercentRate)}`,
|
|
1571
|
-
securitization: `${formatArgons(vault.securitization)} at ${vault.securitizationRatio
|
|
1568
|
+
securitization: `${formatArgons(vault.securitization)} at ${vault.securitizationRatio}x`,
|
|
1572
1569
|
securActivated: `${formatArgons(vault.activatedSecuritizationPerSlot())}/slot`,
|
|
1573
1570
|
liquidPoolDeal: `${formatPercent(vault.terms.liquidityPoolProfitSharing)} sharing`,
|
|
1574
1571
|
operator: `${this.accountset.namedAccounts.has(vault.operatorAccountId) ? ` (${this.accountset.namedAccounts.get(vault.operatorAccountId)})` : vault.operatorAccountId}`,
|
|
@@ -2247,7 +2244,7 @@ Raising Funds (Frame ${this.nextFrameId + 1}):`);
|
|
|
2247
2244
|
};
|
|
2248
2245
|
|
|
2249
2246
|
// src/BitcoinLocks.ts
|
|
2250
|
-
import { hexToU8a as
|
|
2247
|
+
import { hexToU8a as hexToU8a2, u8aToHex as u8aToHex2 } from "@polkadot/util";
|
|
2251
2248
|
var SATS_PER_BTC = 100000000n;
|
|
2252
2249
|
var BitcoinLocks = class _BitcoinLocks {
|
|
2253
2250
|
constructor(client) {
|
|
@@ -2287,6 +2284,7 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2287
2284
|
const bitcoinNetwork = await client.query.bitcoinUtxos.bitcoinNetwork();
|
|
2288
2285
|
return {
|
|
2289
2286
|
releaseExpirationBlocks: client.consts.bitcoinLocks.lockReleaseCosignDeadlineBlocks.toNumber(),
|
|
2287
|
+
pendingConfirmationExpirationBlocks: client.consts.bitcoinUtxos.maxPendingConfirmationBlocks.toNumber(),
|
|
2290
2288
|
tickDurationMillis: await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber()),
|
|
2291
2289
|
bitcoinNetwork
|
|
2292
2290
|
};
|
|
@@ -2341,7 +2339,7 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2341
2339
|
return void 0;
|
|
2342
2340
|
}
|
|
2343
2341
|
async submitVaultSignature(args) {
|
|
2344
|
-
const { utxoId, vaultSignature, argonKeyring } = args;
|
|
2342
|
+
const { utxoId, vaultSignature, argonKeyring, txProgressCallback } = args;
|
|
2345
2343
|
const client = await this.client;
|
|
2346
2344
|
if (!vaultSignature || vaultSignature.byteLength < 70 || vaultSignature.byteLength > 73) {
|
|
2347
2345
|
throw new Error(
|
|
@@ -2351,7 +2349,7 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2351
2349
|
const signature = u8aToHex2(vaultSignature);
|
|
2352
2350
|
const tx = client.tx.bitcoinLocks.cosignRelease(utxoId, signature);
|
|
2353
2351
|
const submitter = new TxSubmitter(client, tx, argonKeyring);
|
|
2354
|
-
return await submitter.submit();
|
|
2352
|
+
return await submitter.submit({ txProgressCallback });
|
|
2355
2353
|
}
|
|
2356
2354
|
async getBitcoinLock(utxoId) {
|
|
2357
2355
|
const client = await this.client;
|
|
@@ -2522,11 +2520,16 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2522
2520
|
return { tx, securityFee, txFee };
|
|
2523
2521
|
}
|
|
2524
2522
|
async initializeLock(args) {
|
|
2525
|
-
const { argonKeyring, tip = 0n } = args;
|
|
2523
|
+
const { argonKeyring, tip = 0n, txProgressCallback } = args;
|
|
2526
2524
|
const client = await this.client;
|
|
2527
2525
|
const { tx, securityFee } = await this.createInitializeLockTx(args);
|
|
2528
2526
|
const submitter = new TxSubmitter(client, tx, argonKeyring);
|
|
2529
|
-
const txResult = await submitter.submit({
|
|
2527
|
+
const txResult = await submitter.submit({
|
|
2528
|
+
waitForBlock: true,
|
|
2529
|
+
logResults: true,
|
|
2530
|
+
tip,
|
|
2531
|
+
txProgressCallback
|
|
2532
|
+
});
|
|
2530
2533
|
const blockHash = await txResult.inBlockPromise;
|
|
2531
2534
|
const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
|
|
2532
2535
|
const utxoId = await this.getUtxoIdFromEvents(txResult.events) ?? 0;
|
|
@@ -2549,7 +2552,8 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2549
2552
|
lock,
|
|
2550
2553
|
releaseRequest: { bitcoinNetworkFee, toScriptPubkey },
|
|
2551
2554
|
argonKeyring,
|
|
2552
|
-
tip
|
|
2555
|
+
tip,
|
|
2556
|
+
txProgressCallback
|
|
2553
2557
|
} = args;
|
|
2554
2558
|
if (!toScriptPubkey.startsWith("0x")) {
|
|
2555
2559
|
throw new Error("toScriptPubkey must be a hex string starting with 0x");
|
|
@@ -2572,7 +2576,12 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2572
2576
|
`Insufficient funds to release lock. Available: ${formatArgons(canAfford.availableBalance)}, Required: ${formatArgons(redemptionPrice)}`
|
|
2573
2577
|
);
|
|
2574
2578
|
}
|
|
2575
|
-
const txResult = await submitter.submit({
|
|
2579
|
+
const txResult = await submitter.submit({
|
|
2580
|
+
waitForBlock: true,
|
|
2581
|
+
logResults: true,
|
|
2582
|
+
tip,
|
|
2583
|
+
txProgressCallback
|
|
2584
|
+
});
|
|
2576
2585
|
const blockHash = await txResult.inBlockPromise;
|
|
2577
2586
|
const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
|
|
2578
2587
|
return {
|
|
@@ -2611,7 +2620,7 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2611
2620
|
};
|
|
2612
2621
|
}
|
|
2613
2622
|
async ratchet(args) {
|
|
2614
|
-
const { lock, argonKeyring, tip = 0n, vault } = args;
|
|
2623
|
+
const { lock, argonKeyring, tip = 0n, vault, txProgressCallback } = args;
|
|
2615
2624
|
const client = await this.client;
|
|
2616
2625
|
const ratchetPrice = await this.getRatchetPrice(lock, vault);
|
|
2617
2626
|
const txSubmitter = new TxSubmitter(
|
|
@@ -2632,7 +2641,8 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2632
2641
|
}
|
|
2633
2642
|
const submission = await txSubmitter.submit({
|
|
2634
2643
|
waitForBlock: true,
|
|
2635
|
-
tip
|
|
2644
|
+
tip,
|
|
2645
|
+
txProgressCallback
|
|
2636
2646
|
});
|
|
2637
2647
|
const ratchetEvent = submission.events.find(
|
|
2638
2648
|
(x) => client.events.bitcoinLocks.BitcoinLockRatcheted.is(x)
|
|
@@ -2664,7 +2674,7 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2664
2674
|
const vaults = new VaultMonitor(accountset, {
|
|
2665
2675
|
bitcoinSpaceAvailable: argonAmount
|
|
2666
2676
|
});
|
|
2667
|
-
const bitcoinXpubBuffer =
|
|
2677
|
+
const bitcoinXpubBuffer = hexToU8a2(bitcoinXpub);
|
|
2668
2678
|
return new Promise(async (resolve, reject) => {
|
|
2669
2679
|
vaults.events.on("bitcoin-space-above", async (vaultId, amount) => {
|
|
2670
2680
|
const vault = vaults.vaultsById[vaultId];
|
|
@@ -2721,7 +2731,7 @@ function createKeyringPair(opts) {
|
|
|
2721
2731
|
}
|
|
2722
2732
|
|
|
2723
2733
|
// src/index.ts
|
|
2724
|
-
import { u8aToHex as u8aToHex3, hexToU8a as
|
|
2734
|
+
import { u8aToHex as u8aToHex3, hexToU8a as hexToU8a3, u8aEq } from "@polkadot/util";
|
|
2725
2735
|
import { GenericEvent as GenericEvent2, GenericBlock, GenericAddress } from "@polkadot/types/generic";
|
|
2726
2736
|
import {
|
|
2727
2737
|
BTreeMap,
|
|
@@ -2765,6 +2775,7 @@ export {
|
|
|
2765
2775
|
setConfig,
|
|
2766
2776
|
getConfig,
|
|
2767
2777
|
TxSubmitter,
|
|
2778
|
+
TxResult,
|
|
2768
2779
|
MICROGONS_PER_ARGON,
|
|
2769
2780
|
formatArgons,
|
|
2770
2781
|
formatPercent,
|
|
@@ -2806,7 +2817,7 @@ export {
|
|
|
2806
2817
|
waitForLoad,
|
|
2807
2818
|
getClient,
|
|
2808
2819
|
u8aToHex3 as u8aToHex,
|
|
2809
|
-
|
|
2820
|
+
hexToU8a3 as hexToU8a,
|
|
2810
2821
|
u8aEq,
|
|
2811
2822
|
GenericEvent2 as GenericEvent,
|
|
2812
2823
|
GenericBlock,
|
|
@@ -2834,4 +2845,4 @@ export {
|
|
|
2834
2845
|
u64,
|
|
2835
2846
|
u8
|
|
2836
2847
|
};
|
|
2837
|
-
//# sourceMappingURL=chunk-
|
|
2848
|
+
//# sourceMappingURL=chunk-GZ2TLGCG.js.map
|