@argonprotocol/mainchain 1.1.0-rc.8 → 1.2.0

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/lib/clis/index.js CHANGED
@@ -1,3346 +1,18 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
-
19
- // src/clis/index.ts
20
- import { Command as Command6, Option as Option2 } from "@commander-js/extra-typings";
21
-
22
- // src/clis/accountCli.ts
23
- import { Command } from "@commander-js/extra-typings";
24
-
25
- // src/index.ts
26
- var index_exports = {};
27
- __export(index_exports, {
28
- AccountMiners: () => AccountMiners,
29
- AccountRegistry: () => AccountRegistry,
30
- Accountset: () => Accountset,
31
- BidPool: () => BidPool,
32
- BitcoinLocks: () => BitcoinLocks,
33
- BlockWatch: () => BlockWatch,
34
- CohortBidder: () => CohortBidder,
35
- ExtrinsicError: () => ExtrinsicError2,
36
- JsonExt: () => JsonExt,
37
- Keyring: () => Keyring,
38
- MICROGONS_PER_ARGON: () => MICROGONS_PER_ARGON,
39
- MiningBids: () => MiningBids,
40
- MiningRotations: () => MiningRotations,
41
- TxSubmitter: () => TxSubmitter,
42
- Vault: () => Vault,
43
- VaultMonitor: () => VaultMonitor,
44
- WageProtector: () => WageProtector,
45
- checkForExtrinsicSuccess: () => checkForExtrinsicSuccess,
46
- convertFixedU128ToBigNumber: () => convertFixedU128ToBigNumber,
47
- convertPermillToBigNumber: () => convertPermillToBigNumber,
48
- createKeyringPair: () => createKeyringPair,
49
- decodeAddress: () => decodeAddress,
50
- dispatchErrorToExtrinsicError: () => dispatchErrorToExtrinsicError,
51
- dispatchErrorToString: () => dispatchErrorToString,
52
- eventDataToJson: () => eventDataToJson,
53
- filterUndefined: () => filterUndefined,
54
- formatArgons: () => formatArgons,
55
- formatPercent: () => formatPercent,
56
- getAuthorFromHeader: () => getAuthorFromHeader,
57
- getClient: () => getClient,
58
- getTickFromHeader: () => getTickFromHeader,
59
- gettersToObject: () => gettersToObject,
60
- keyringFromSuri: () => keyringFromSuri,
61
- mnemonicGenerate: () => mnemonicGenerate,
62
- waitForLoad: () => waitForLoad
63
- });
64
-
65
- // src/interfaces/augment-api-consts.ts
66
- import "@polkadot/api-base/types/consts";
67
-
68
- // src/interfaces/augment-api-errors.ts
69
- import "@polkadot/api-base/types/errors";
70
-
71
- // src/interfaces/augment-api-events.ts
72
- import "@polkadot/api-base/types/events";
73
-
74
- // src/interfaces/augment-api-query.ts
75
- import "@polkadot/api-base/types/storage";
76
-
77
- // src/interfaces/augment-api-tx.ts
78
- import "@polkadot/api-base/types/submittable";
79
-
80
- // src/interfaces/augment-api-rpc.ts
81
- import "@polkadot/rpc-core/types/jsonrpc";
82
-
83
- // src/interfaces/augment-api-runtime.ts
84
- import "@polkadot/api-base/types/calls";
85
-
86
- // src/interfaces/augment-types.ts
87
- import "@polkadot/types/types/registry";
88
-
89
- // src/index.ts
90
- __reExport(index_exports, types_star);
91
- import { ApiPromise, HttpProvider, Keyring, WsProvider } from "@polkadot/api";
92
1
  import {
93
- cryptoWaitReady,
94
- decodeAddress,
95
- mnemonicGenerate
96
- } from "@polkadot/util-crypto";
97
- import * as types_star from "@polkadot/types-codec/types";
98
-
99
- // src/WageProtector.ts
100
- var WageProtector = class _WageProtector {
101
- constructor(latestCpi) {
102
- this.latestCpi = latestCpi;
103
- }
104
- /**
105
- * Converts the base wage to the current wage using the latest CPI snapshot
106
- *
107
- * @param baseWage The base wage to convert
108
- * @returns The protected wage
109
- */
110
- getProtectedWage(baseWage) {
111
- return baseWage * this.latestCpi.argonUsdTargetPrice / this.latestCpi.argonUsdPrice;
112
- }
113
- /**
114
- * Subscribes to the current CPI and calls the callback function whenever the CPI changes
115
- * @param client The ArgonClient to use
116
- * @param callback The callback function to call when the CPI changes
117
- * @returns An object with an unsubscribe function that can be called to stop the subscription
118
- */
119
- static async subscribe(client, callback) {
120
- const unsubscribe = await client.query.priceIndex.current(async (cpi) => {
121
- if (cpi.isNone) {
122
- return;
123
- }
124
- const finalizedBlock = await client.rpc.chain.getFinalizedHead();
125
- callback(
126
- new _WageProtector({
127
- argonUsdTargetPrice: cpi.value.argonUsdTargetPrice.toBigInt(),
128
- argonUsdPrice: cpi.value.argonUsdPrice.toBigInt(),
129
- finalizedBlock: finalizedBlock.toU8a(),
130
- tick: cpi.value.tick.toBigInt()
131
- })
132
- );
133
- });
134
- return { unsubscribe };
135
- }
136
- /**
137
- * Creates a new WageProtector instance by subscribing to the current CPI and waiting for the first value
138
- * @param client The ArgonClient to use
139
- */
140
- static async create(client) {
141
- return new Promise(async (resolve, reject) => {
142
- try {
143
- const { unsubscribe } = await _WageProtector.subscribe(client, (x) => {
144
- resolve(x);
145
- unsubscribe();
146
- });
147
- } catch (e) {
148
- reject(e);
149
- }
150
- });
151
- }
152
- };
153
-
154
- // src/TxSubmitter.ts
155
- function logExtrinsicResult(result) {
156
- if (process.env.DEBUG) {
157
- const json = result.status.toJSON();
158
- const status = Object.keys(json)[0];
159
- console.debug('Transaction update: "%s"', status, json[status]);
160
- }
161
- }
162
- var TxSubmitter = class {
163
- constructor(client, tx, pair) {
164
- this.client = client;
165
- this.tx = tx;
166
- this.pair = pair;
167
- }
168
- async feeEstimate(tip) {
169
- const { partialFee } = await this.tx.paymentInfo(this.pair, { tip });
170
- return partialFee.toBigInt();
171
- }
172
- async canAfford(options = {}) {
173
- const { tip, unavailableBalance } = options;
174
- const account = await this.client.query.system.account(this.pair.address);
175
- let availableBalance = account.data.free.toBigInt();
176
- if (unavailableBalance) {
177
- availableBalance -= unavailableBalance;
178
- }
179
- const existentialDeposit = options.includeExistentialDeposit ? this.client.consts.balances.existentialDeposit.toBigInt() : 0n;
180
- const fees = await this.feeEstimate(tip);
181
- const totalCharge = fees + (tip ?? 0n);
182
- const canAfford = availableBalance > totalCharge + existentialDeposit;
183
- return { canAfford, availableBalance, txFee: fees };
184
- }
185
- async submit(options = {}) {
186
- const { logResults } = options;
187
- const result = new TxResult(this.client, logResults);
188
- let toHuman = this.tx.toHuman().method;
189
- let txString = [];
190
- let api = formatCall(toHuman);
191
- const args = [];
192
- if (api === "proxy.proxy") {
193
- toHuman = toHuman.args.call;
194
- txString.push("Proxy");
195
- api = formatCall(toHuman);
196
- }
197
- if (api.startsWith("utility.batch")) {
198
- const calls = toHuman.args.calls.map(formatCall).join(", ");
199
- txString.push(`Batch[${calls}]`);
200
- } else {
201
- txString.push(api);
202
- args.push(toHuman.args);
203
- }
204
- args.unshift(txString.join("->"));
205
- if (options.useLatestNonce && !options.nonce) {
206
- options.nonce = await this.client.rpc.system.accountNextIndex(
207
- this.pair.address
208
- );
209
- }
210
- console.log("Submitting transaction:", ...args);
211
- await this.tx.signAndSend(this.pair, options, result.onResult.bind(result));
212
- if (options.waitForBlock) {
213
- await result.inBlockPromise;
214
- }
215
- return result;
216
- }
217
- };
218
- function formatCall(call) {
219
- return `${call.section}.${call.method}`;
220
- }
221
- var TxResult = class {
222
- constructor(client, shouldLog = false) {
223
- this.client = client;
224
- this.shouldLog = shouldLog;
225
- this.inBlockPromise = new Promise((resolve, reject) => {
226
- this.inBlockResolve = resolve;
227
- this.inBlockReject = reject;
228
- });
229
- this.finalizedPromise = new Promise((resolve, reject) => {
230
- this.finalizedResolve = resolve;
231
- this.finalizedReject = reject;
232
- });
233
- this.inBlockPromise.catch(() => {
234
- });
235
- this.finalizedPromise.catch(() => {
236
- });
237
- }
238
- inBlockPromise;
239
- finalizedPromise;
240
- status;
241
- events = [];
242
- /**
243
- * The index of the batch that was interrupted, if any.
244
- */
245
- batchInterruptedIndex;
246
- includedInBlock;
247
- /**
248
- * The final fee paid for the transaction, including the fee tip.
249
- */
250
- finalFee;
251
- /**
252
- * The fee tip paid for the transaction.
253
- */
254
- finalFeeTip;
255
- inBlockResolve;
256
- inBlockReject;
257
- finalizedResolve;
258
- finalizedReject;
259
- onResult(result) {
260
- this.status = result.status;
261
- if (this.shouldLog) {
262
- logExtrinsicResult(result);
263
- }
264
- const { events, status, dispatchError, isFinalized } = result;
265
- if (status.isInBlock) {
266
- this.includedInBlock = status.asInBlock.toU8a();
267
- let encounteredError = dispatchError;
268
- let batchErrorIndex;
269
- for (const event of events) {
270
- this.events.push(event.event);
271
- if (this.client.events.utility.BatchInterrupted.is(event.event)) {
272
- batchErrorIndex = event.event.data[0].toNumber();
273
- this.batchInterruptedIndex = batchErrorIndex;
274
- encounteredError = event.event.data[1];
275
- }
276
- if (this.client.events.transactionPayment.TransactionFeePaid.is(
277
- event.event
278
- )) {
279
- const [_who, actualFee, tip] = event.event.data;
280
- this.finalFee = actualFee.toBigInt();
281
- this.finalFeeTip = tip.toBigInt();
282
- }
283
- }
284
- if (encounteredError) {
285
- const error = dispatchErrorToExtrinsicError(
286
- this.client,
287
- encounteredError,
288
- batchErrorIndex
289
- );
290
- this.reject(error);
291
- } else {
292
- this.inBlockResolve(status.asInBlock.toU8a());
293
- }
294
- }
295
- if (isFinalized) {
296
- this.finalizedResolve(status.asFinalized);
297
- }
298
- }
299
- reject(error) {
300
- this.inBlockReject(error);
301
- this.finalizedReject(error);
302
- }
303
- };
304
-
305
- // src/utils.ts
306
- import BigNumber2, * as BN from "bignumber.js";
307
- var { ROUND_FLOOR } = BN;
308
- var MICROGONS_PER_ARGON = 1e6;
309
- function formatArgons(x) {
310
- if (x === void 0 || x === null) return "na";
311
- const isNegative = x < 0;
312
- let format = BigNumber2(x.toString()).abs().div(MICROGONS_PER_ARGON).toFormat(2, ROUND_FLOOR);
313
- if (format.endsWith(".00")) {
314
- format = format.slice(0, -3);
315
- }
316
- return `${isNegative ? "-" : ""}\u20B3${format}`;
317
- }
318
- function formatPercent(x) {
319
- if (!x) return "na";
320
- return `${x.times(100).decimalPlaces(3)}%`;
321
- }
322
- function filterUndefined(obj) {
323
- return Object.fromEntries(
324
- Object.entries(obj).filter(
325
- ([_, value]) => value !== void 0 && value !== null
326
- )
327
- );
328
- }
329
- async function gettersToObject(obj) {
330
- if (obj === null || obj === void 0 || typeof obj !== "object") return obj;
331
- const keys = [];
332
- for (const key in obj) {
333
- keys.push(key);
334
- }
335
- if (Symbol.iterator in obj) {
336
- const iterableToArray = [];
337
- for (const item of obj) {
338
- iterableToArray.push(await gettersToObject(item));
339
- }
340
- return iterableToArray;
341
- }
342
- const result = {};
343
- for (const key of keys) {
344
- const descriptor = Object.getOwnPropertyDescriptor(obj, key);
345
- if (descriptor && typeof descriptor.value === "function") {
346
- continue;
347
- }
348
- const value = descriptor && descriptor.get ? descriptor.get.call(obj) : obj[key];
349
- if (typeof value === "function") continue;
350
- result[key] = await gettersToObject(value);
351
- }
352
- return result;
353
- }
354
- function convertFixedU128ToBigNumber(fixedU128) {
355
- const decimalFactor = new BigNumber2(10).pow(new BigNumber2(18));
356
- const rawValue = new BigNumber2(fixedU128.toString());
357
- return rawValue.div(decimalFactor);
358
- }
359
- function convertPermillToBigNumber(permill) {
360
- const decimalFactor = new BigNumber2(1e6);
361
- const rawValue = new BigNumber2(permill.toString());
362
- return rawValue.div(decimalFactor);
363
- }
364
- function eventDataToJson(event) {
365
- const obj = {};
366
- event.data.forEach((data, index) => {
367
- const name = event.data.names?.[index];
368
- obj[name ?? `${index}`] = data.toJSON();
369
- });
370
- return obj;
371
- }
372
- function dispatchErrorToString(client, error) {
373
- let message = error.toString();
374
- if (error.isModule) {
375
- const decoded = client.registry.findMetaError(error.asModule);
376
- const { docs, name, section } = decoded;
377
- message = `${section}.${name}: ${docs.join(" ")}`;
378
- }
379
- return message;
380
- }
381
- var ExtrinsicError2 = class extends Error {
382
- constructor(errorCode, details, batchInterruptedIndex) {
383
- super(errorCode);
384
- this.errorCode = errorCode;
385
- this.details = details;
386
- this.batchInterruptedIndex = batchInterruptedIndex;
387
- }
388
- toString() {
389
- if (this.batchInterruptedIndex !== void 0) {
390
- return `${this.errorCode} ${this.details ?? ""} (Batch interrupted at index ${this.batchInterruptedIndex})`;
391
- }
392
- return `${this.errorCode} ${this.details ?? ""}`;
393
- }
394
- };
395
- function dispatchErrorToExtrinsicError(client, error, batchInterruptedIndex) {
396
- if (error.isModule) {
397
- const decoded = client.registry.findMetaError(error.asModule);
398
- const { docs, name, section } = decoded;
399
- return new ExtrinsicError2(
400
- `${section}.${name}`,
401
- docs.join(" "),
402
- batchInterruptedIndex
403
- );
404
- }
405
- return new ExtrinsicError2(error.toString(), void 0, batchInterruptedIndex);
406
- }
407
- function checkForExtrinsicSuccess(events, client) {
408
- return new Promise((resolve, reject) => {
409
- for (const { event } of events) {
410
- if (client.events.system.ExtrinsicSuccess.is(event)) {
411
- resolve();
412
- } else if (client.events.system.ExtrinsicFailed.is(event)) {
413
- const [dispatchError] = event.data;
414
- let errorInfo = dispatchError.toString();
415
- if (dispatchError.isModule) {
416
- const decoded = client.registry.findMetaError(dispatchError.asModule);
417
- errorInfo = `${decoded.section}.${decoded.name}`;
418
- }
419
- reject(
420
- new Error(
421
- `${event.section}.${event.method}:: ExtrinsicFailed:: ${errorInfo}`
422
- )
423
- );
424
- }
425
- }
426
- });
427
- }
428
- var JsonExt = class {
429
- static stringify(obj, space) {
430
- return JSON.stringify(
431
- obj,
432
- (_, v) => typeof v === "bigint" ? `${v}n` : v,
433
- space
434
- );
435
- }
436
- static parse(str) {
437
- return JSON.parse(str, (_, v) => {
438
- if (typeof v === "string" && v.endsWith("n")) {
439
- return BigInt(v.slice(0, -1));
440
- }
441
- return v;
442
- });
443
- }
444
- };
445
-
446
- // src/AccountRegistry.ts
447
- var AccountRegistry = class _AccountRegistry {
448
- namedAccounts = /* @__PURE__ */ new Map();
449
- me = "me";
450
- constructor(name) {
451
- if (name) {
452
- this.me = name;
453
- }
454
- }
455
- getName(address) {
456
- return this.namedAccounts.get(address);
457
- }
458
- register(address, name) {
459
- this.namedAccounts.set(address, name);
460
- }
461
- static factory = (name) => new _AccountRegistry(name);
462
- };
463
-
464
- // src/Accountset.ts
465
- import * as process2 from "node:process";
466
-
467
- // src/BlockWatch.ts
468
- import { createNanoEvents } from "nanoevents";
469
- function getTickFromHeader(client, header) {
470
- for (const x of header.digest.logs) {
471
- if (x.isPreRuntime) {
472
- const [engineId, data] = x.asPreRuntime;
473
- if (engineId.toString() === "aura") {
474
- return client.createType("u64", data).toNumber();
475
- }
476
- }
477
- }
478
- return void 0;
479
- }
480
- function getAuthorFromHeader(client, header) {
481
- for (const x of header.digest.logs) {
482
- if (x.isPreRuntime) {
483
- const [engineId, data] = x.asPreRuntime;
484
- if (engineId.toString() === "pow_") {
485
- return client.createType("AccountId32", data).toHuman();
486
- }
487
- }
488
- }
489
- return void 0;
490
- }
491
- var BlockWatch = class {
492
- constructor(mainchain, options = {}) {
493
- this.mainchain = mainchain;
494
- this.options = options;
495
- this.options.shouldLog ??= true;
496
- this.options.finalizedBlocks ??= false;
497
- }
498
- events = createNanoEvents();
499
- obligationsById = {};
500
- obligationIdByUtxoId = {};
501
- unsubscribe;
502
- stop() {
503
- if (this.unsubscribe) {
504
- this.unsubscribe();
505
- this.unsubscribe = void 0;
506
- }
507
- }
508
- async start() {
509
- await this.watchBlocks();
510
- }
511
- async watchBlocks() {
512
- const client = await this.mainchain;
513
- const onBlock = async (header) => {
514
- try {
515
- await this.processBlock(header);
516
- } catch (e) {
517
- console.error("Error processing block", e);
518
- }
519
- };
520
- if (this.options.finalizedBlocks) {
521
- this.unsubscribe = await client.rpc.chain.subscribeFinalizedHeads(onBlock);
522
- } else {
523
- this.unsubscribe = await client.rpc.chain.subscribeNewHeads(onBlock);
524
- }
525
- }
526
- async processBlock(header) {
527
- const client = await this.mainchain;
528
- if (this.options.shouldLog) {
529
- console.log(`-------------------------------------
530
- BLOCK #${header.number}, ${header.hash.toHuman()}`);
531
- }
532
- const blockHash = header.hash;
533
- const api = await client.at(blockHash);
534
- const isBlockVote = await api.query.blockSeal.isBlockFromVoteSeal();
535
- if (!isBlockVote) {
536
- console.warn("> Compute reactivated!");
537
- }
538
- const events = await api.query.system.events();
539
- const reloadVaults = /* @__PURE__ */ new Set();
540
- let block = void 0;
541
- for (const { event, phase } of events) {
542
- const data = eventDataToJson(event);
543
- if (data.vaultId) {
544
- const vaultId = data.vaultId;
545
- reloadVaults.add(vaultId);
546
- }
547
- let logEvent = false;
548
- if (event.section === "liquidityPools") {
549
- if (client.events.liquidityPools.BidPoolDistributed.is(event)) {
550
- const { bidPoolBurned, bidPoolDistributed } = event.data;
551
- data.burned = formatArgons(bidPoolBurned.toBigInt());
552
- data.distributed = formatArgons(bidPoolDistributed.toBigInt());
553
- logEvent = true;
554
- } else if (client.events.liquidityPools.NextBidPoolCapitalLocked.is(event)) {
555
- const { totalActivatedCapital } = event.data;
556
- data.totalActivatedCapital = formatArgons(
557
- totalActivatedCapital.toBigInt()
558
- );
559
- logEvent = true;
560
- }
561
- } else if (event.section === "bitcoinLocks") {
562
- if (client.events.bitcoinLocks.BitcoinLockCreated.is(event)) {
563
- const { lockPrice, utxoId, accountId, vaultId } = event.data;
564
- this.obligationsById[utxoId.toNumber()] = {
565
- vaultId: vaultId.toNumber(),
566
- amount: lockPrice.toBigInt()
567
- };
568
- data.lockPrice = formatArgons(lockPrice.toBigInt());
569
- data.accountId = accountId.toHuman();
570
- reloadVaults.add(vaultId.toNumber());
571
- }
572
- logEvent = true;
573
- } else if (event.section === "mint") {
574
- logEvent = true;
575
- if (client.events.mint.MiningMint.is(event)) {
576
- const { amount } = event.data;
577
- data.amount = formatArgons(amount.toBigInt());
578
- }
579
- } else if (event.section === "miningSlot") {
580
- logEvent = true;
581
- if (client.events.miningSlot.SlotBidderAdded.is(event)) {
582
- data.amount = formatArgons(event.data.bidAmount.toBigInt());
583
- this.events.emit("mining-bid", header, {
584
- amount: event.data.bidAmount.toBigInt(),
585
- accountId: event.data.accountId.toString()
586
- });
587
- } else if (client.events.miningSlot.SlotBidderDropped.is(event)) {
588
- this.events.emit("mining-bid-ousted", header, {
589
- accountId: event.data.accountId.toString(),
590
- preservedArgonotHold: event.data.preservedArgonotHold.toPrimitive()
591
- });
592
- }
593
- } else if (event.section === "bitcoinUtxos") {
594
- logEvent = true;
595
- if (client.events.bitcoinUtxos.UtxoVerified.is(event)) {
596
- const { utxoId } = event.data;
597
- const details = await this.getBitcoinLockDetails(
598
- utxoId.toNumber(),
599
- blockHash
600
- );
601
- this.events.emit("bitcoin-verified", header, {
602
- utxoId: utxoId.toNumber(),
603
- vaultId: details.vaultId,
604
- amount: details.amount
605
- });
606
- data.amount = formatArgons(details.amount);
607
- reloadVaults.add(details.vaultId);
608
- }
609
- } else if (event.section === "system") {
610
- if (client.events.system.ExtrinsicFailed.is(event)) {
611
- const { dispatchError } = event.data;
612
- if (dispatchError.isModule) {
613
- const decoded = api.registry.findMetaError(dispatchError.asModule);
614
- const { name, section } = decoded;
615
- block ??= await client.rpc.chain.getBlock(header.hash);
616
- const extrinsicIndex = phase.asApplyExtrinsic.toNumber();
617
- const ext = block.block.extrinsics[extrinsicIndex];
618
- if (this.options.shouldLog) {
619
- console.log(
620
- `> [Failed Tx] ${section}.${name} -> ${ext.method.section}.${ext.method.method} (nonce=${ext.nonce})`,
621
- ext.toHuman()?.method?.args
622
- );
623
- }
624
- } else {
625
- if (this.options.shouldLog) {
626
- console.log(`x [Failed Tx] ${dispatchError.toJSON()}`);
627
- }
628
- }
629
- }
630
- }
631
- if (this.options.shouldLog && logEvent) {
632
- console.log(`> ${event.section}.${event.method}`, data);
633
- }
634
- this.events.emit("event", header, event);
635
- }
636
- if (reloadVaults.size)
637
- this.events.emit("vaults-updated", header, reloadVaults);
638
- const tick = getTickFromHeader(client, header);
639
- const author = getAuthorFromHeader(client, header);
640
- this.events.emit(
641
- "block",
642
- header,
643
- { tick, author },
644
- events.map((x) => x.event)
645
- );
646
- }
647
- async getBitcoinLockDetails(utxoId, blockHash) {
648
- const client = await this.mainchain;
649
- const api = await client.at(blockHash);
650
- let obligationId = this.obligationIdByUtxoId[utxoId];
651
- if (!obligationId) {
652
- const lock = await api.query.bitcoinLocks.locksByUtxoId(utxoId);
653
- obligationId = lock.value.obligationId.toNumber();
654
- this.obligationIdByUtxoId[utxoId] = obligationId;
655
- this.obligationsById[obligationId] = {
656
- vaultId: lock.value.vaultId.toNumber(),
657
- amount: lock.value.lockPrice.toBigInt()
658
- };
659
- }
660
- return this.obligationsById[obligationId];
661
- }
662
- };
663
-
664
- // src/MiningRotations.ts
665
- var MiningRotations = class {
666
- miningConfig;
667
- genesisTick;
668
- async getForTick(client, tick) {
669
- this.miningConfig ??= await client.query.miningSlot.miningConfig().then((x) => ({
670
- ticksBetweenSlots: x.ticksBetweenSlots.toNumber(),
671
- slotBiddingStartAfterTicks: x.slotBiddingStartAfterTicks.toNumber()
672
- }));
673
- this.genesisTick ??= await client.query.ticks.genesisTick().then((x) => x.toNumber());
674
- const ticksBetweenSlots = this.miningConfig.ticksBetweenSlots;
675
- const slot1StartTick = this.genesisTick + this.miningConfig.slotBiddingStartAfterTicks + ticksBetweenSlots;
676
- if (tick < slot1StartTick) return 0;
677
- const ticksSinceSlot1 = tick - slot1StartTick;
678
- return Math.floor(ticksSinceSlot1 / ticksBetweenSlots) + 1;
679
- }
680
- async getForHeader(client, header) {
681
- if (header.number.toNumber() === 0) return 0;
682
- const tick = getTickFromHeader(client, header);
683
- if (tick === void 0) return void 0;
684
- return this.getForTick(client, tick);
685
- }
686
- };
687
-
688
- // src/AccountMiners.ts
689
- import { createNanoEvents as createNanoEvents2 } from "nanoevents";
690
- var AccountMiners = class _AccountMiners {
691
- constructor(accountset, registeredMiners, options = { shouldLog: false }) {
692
- this.accountset = accountset;
693
- this.options = options;
694
- this.miningRotations = new MiningRotations();
695
- for (const seat of registeredMiners) {
696
- this.trackedAccountsByAddress[seat.address] = {
697
- cohortId: seat.cohortId,
698
- subaccountIndex: seat.subaccountIndex
699
- };
700
- }
701
- }
702
- events = createNanoEvents2();
703
- miningRotations;
704
- trackedAccountsByAddress = {};
705
- async watch() {
706
- const blockWatch = new BlockWatch(this.accountset.client, {
707
- shouldLog: this.options.shouldLog
708
- });
709
- blockWatch.events.on("block", this.onBlock.bind(this));
710
- await blockWatch.start();
711
- return blockWatch;
712
- }
713
- async onBlock(header, digests, events) {
714
- const { author, tick } = digests;
715
- if (author) {
716
- const voteAuthor = this.trackedAccountsByAddress[author];
717
- if (voteAuthor && this.options.shouldLog) {
718
- console.log(
719
- "> Our vote author",
720
- this.accountset.accountRegistry.getName(author)
721
- );
722
- }
723
- } else {
724
- console.warn("> No vote author found");
725
- }
726
- const client = await this.accountset.client;
727
- const rotation = await this.miningRotations.getForTick(client, tick);
728
- let newMiners;
729
- const dataByCohort = { rotation };
730
- for (const event of events) {
731
- if (client.events.miningSlot.NewMiners.is(event)) {
732
- newMiners = {
733
- cohortId: event.data.cohortId.toNumber(),
734
- addresses: event.data.newMiners.map((x) => x.accountId.toHuman())
735
- };
736
- }
737
- if (client.events.blockRewards.RewardCreated.is(event)) {
738
- const { rewards } = event.data;
739
- for (const reward of rewards) {
740
- const { argons, ownership } = reward;
741
- const entry = this.trackedAccountsByAddress[author];
742
- if (entry) {
743
- dataByCohort[entry.cohortId] ??= {
744
- argonsMinted: 0n,
745
- argonsMined: 0n,
746
- argonotsMined: 0n
747
- };
748
- dataByCohort[entry.cohortId].argonotsMined += ownership.toBigInt();
749
- dataByCohort[entry.cohortId].argonsMined += argons.toBigInt();
750
- this.events.emit("mined", header, {
751
- author,
752
- argons: argons.toBigInt(),
753
- argonots: ownership.toBigInt(),
754
- cohortId: entry.cohortId,
755
- rotation
756
- });
757
- }
758
- }
759
- }
760
- if (client.events.mint.MiningMint.is(event)) {
761
- const { perMiner } = event.data;
762
- const amountPerMiner = perMiner.toBigInt();
763
- if (amountPerMiner > 0n) {
764
- for (const [address, info] of Object.entries(
765
- this.trackedAccountsByAddress
766
- )) {
767
- const { cohortId } = info;
768
- dataByCohort[cohortId] ??= {
769
- argonsMinted: 0n,
770
- argonsMined: 0n,
771
- argonotsMined: 0n
772
- };
773
- dataByCohort[cohortId].argonsMinted += amountPerMiner;
774
- this.events.emit("minted", header, {
775
- accountId: address,
776
- argons: amountPerMiner,
777
- cohortId,
778
- rotation
779
- });
780
- }
781
- }
782
- }
783
- }
784
- if (newMiners) {
785
- this.newCohortMiners(newMiners.cohortId, newMiners.addresses);
786
- }
787
- return dataByCohort;
788
- }
789
- newCohortMiners(cohortId, addresses) {
790
- for (const [address, info] of Object.entries(
791
- this.trackedAccountsByAddress
792
- )) {
793
- if (info.cohortId === cohortId - 10) {
794
- delete this.trackedAccountsByAddress[address];
795
- }
796
- }
797
- for (const address of addresses) {
798
- const entry = this.accountset.subAccountsByAddress[address];
799
- if (entry) {
800
- this.trackedAccountsByAddress[address] = {
801
- cohortId,
802
- subaccountIndex: entry.index
803
- };
804
- }
805
- }
806
- }
807
- static async loadAt(accountset, options = {}) {
808
- const seats = await accountset.miningSeats(options.blockHash);
809
- const registered = seats.filter((x) => x.cohortId !== void 0);
810
- return new _AccountMiners(accountset, registered, {
811
- shouldLog: options.shouldLog ?? false
812
- });
813
- }
814
- };
815
-
816
- // src/Accountset.ts
817
- var Accountset = class {
818
- txSubmitterPair;
819
- isProxy = false;
820
- seedAddress;
821
- subAccountsByAddress = {};
822
- accountRegistry;
823
- client;
824
- get addresses() {
825
- return [this.seedAddress, ...Object.keys(this.subAccountsByAddress)];
826
- }
827
- get namedAccounts() {
828
- return this.accountRegistry.namedAccounts;
829
- }
830
- sessionKeyMnemonic;
831
- constructor(options) {
832
- if ("seedAccount" in options) {
833
- this.txSubmitterPair = options.seedAccount;
834
- this.seedAddress = options.seedAccount.address;
835
- this.isProxy = false;
836
- } else {
837
- this.isProxy = options.isProxy;
838
- this.txSubmitterPair = options.txSubmitter;
839
- this.seedAddress = options.seedAddress;
840
- }
841
- this.sessionKeyMnemonic = options.sessionKeyMnemonic;
842
- this.accountRegistry = options.accountRegistry ?? AccountRegistry.factory(options.name);
843
- this.client = options.client;
844
- const defaultRange = options.subaccountRange ?? getDefaultSubaccountRange();
845
- this.accountRegistry.register(
846
- this.seedAddress,
847
- `${this.accountRegistry.me}//seed`
848
- );
849
- for (const i of defaultRange) {
850
- const pair = this.txSubmitterPair.derive(`//${i}`);
851
- this.subAccountsByAddress[pair.address] = { pair, index: i };
852
- this.accountRegistry.register(
853
- pair.address,
854
- `${this.accountRegistry.me}//${i}`
855
- );
856
- }
857
- }
858
- async submitterBalance(blockHash) {
859
- const client = await this.client;
860
- const api = blockHash ? await client.at(blockHash) : client;
861
- const accountData = await api.query.system.account(
862
- this.txSubmitterPair.address
863
- );
864
- return accountData.data.free.toBigInt();
865
- }
866
- async balance(blockHash) {
867
- const client = await this.client;
868
- const api = blockHash ? await client.at(blockHash) : client;
869
- const accountData = await api.query.system.account(this.seedAddress);
870
- return accountData.data.free.toBigInt();
871
- }
872
- async totalArgonsAt(blockHash) {
873
- const client = await this.client;
874
- const api = blockHash ? await client.at(blockHash) : client;
875
- const addresses = this.addresses;
876
- const results = await api.query.system.account.multi(addresses);
877
- return results.map((account, i) => {
878
- const address = addresses[i];
879
- return {
880
- address,
881
- amount: account.data.free.toBigInt(),
882
- index: this.subAccountsByAddress[address]?.index ?? Number.NaN
883
- };
884
- });
885
- }
886
- async totalArgonotsAt(blockHash) {
887
- const client = await this.client;
888
- const api = blockHash ? await client.at(blockHash) : client;
889
- const addresses = this.addresses;
890
- const results = await api.query.ownership.account.multi(addresses);
891
- return results.map((account, i) => {
892
- const address = addresses[i];
893
- return {
894
- address,
895
- amount: account.free.toBigInt(),
896
- index: this.subAccountsByAddress[address]?.index ?? Number.NaN
897
- };
898
- });
899
- }
900
- async getAvailableMinerAccounts(maxSeats) {
901
- const miningSeats = await this.miningSeats();
902
- const subaccountRange = [];
903
- for (const seat of miningSeats) {
904
- if (seat.hasWinningBid) {
905
- continue;
906
- }
907
- if (seat.isLastDay || seat.seat === void 0) {
908
- subaccountRange.push({
909
- index: seat.subaccountIndex,
910
- isRebid: seat.seat !== void 0,
911
- address: seat.address
912
- });
913
- if (subaccountRange.length >= maxSeats) {
914
- break;
915
- }
916
- }
917
- }
918
- return subaccountRange;
919
- }
920
- async loadRegisteredMiners(api) {
921
- const addresses = Object.keys(this.subAccountsByAddress);
922
- const rawIndices = await api.query.miningSlot.accountIndexLookup.multi(addresses);
923
- const addressToMiningIndex = {};
924
- for (let i = 0; i < addresses.length; i++) {
925
- const address = addresses[i];
926
- if (rawIndices[i].isNone) continue;
927
- addressToMiningIndex[address] = rawIndices[i].value.toNumber();
928
- }
929
- const indices = Object.values(addressToMiningIndex).filter(
930
- (x) => x !== void 0
931
- );
932
- const indexRegistrations = indices.length ? await api.query.miningSlot.activeMinersByIndex.multi(indices) : [];
933
- const registrationBySeatIndex = {};
934
- for (let i = 0; i < indices.length; i++) {
935
- const seatIndex = indices[i];
936
- const registration = indexRegistrations[i];
937
- if (registration?.isSome) {
938
- registrationBySeatIndex[seatIndex] = {
939
- cohortId: registration.value.cohortId.toNumber(),
940
- bidAmount: registration.value.bid.toBigInt()
941
- };
942
- }
943
- }
944
- const nextCohortId = await api.query.miningSlot.nextCohortId();
945
- return addresses.map((address) => {
946
- const seat = addressToMiningIndex[address];
947
- const registration = registrationBySeatIndex[seat];
948
- let isLastDay = false;
949
- if (registration?.cohortId) {
950
- isLastDay = nextCohortId.toNumber() - registration?.cohortId === 10;
951
- }
952
- return {
953
- ...registration,
954
- address,
955
- seat,
956
- isLastDay,
957
- subaccountIndex: this.subAccountsByAddress[address]?.index ?? Number.NaN
958
- };
959
- });
960
- }
961
- async miningSeats(blockHash) {
962
- const client = await this.client;
963
- const api = blockHash ? await client.at(blockHash) : client;
964
- const miners = await this.loadRegisteredMiners(api);
965
- const nextCohort = await api.query.miningSlot.nextSlotCohort();
966
- return miners.map((miner) => {
967
- const bid = nextCohort.find((x) => x.accountId.toHuman() === miner.address);
968
- return {
969
- ...miner,
970
- hasWinningBid: !!bid,
971
- bidAmount: bid?.bid.toBigInt() ?? miner.bidAmount
972
- };
973
- });
974
- }
975
- async bids(blockHash) {
976
- const client = await this.client;
977
- const api = blockHash ? await client.at(blockHash) : client;
978
- const addresses = Object.keys(this.subAccountsByAddress);
979
- const nextCohort = await api.query.miningSlot.nextSlotCohort();
980
- const registrationsByAddress = Object.fromEntries(
981
- nextCohort.map((x, i) => [x.accountId.toHuman(), { ...x, index: i }])
982
- );
983
- return addresses.map((address) => {
984
- const entry = registrationsByAddress[address];
985
- return {
986
- address,
987
- bidPlace: entry?.index,
988
- bidAmount: entry?.bid?.toBigInt(),
989
- index: this.subAccountsByAddress[address]?.index ?? Number.NaN
990
- };
991
- });
992
- }
993
- async consolidate(subaccounts) {
994
- const client = await this.client;
995
- const accounts = this.getAccountsInRange(subaccounts);
996
- const results = [];
997
- await Promise.allSettled(
998
- accounts.map(({ pair, index }) => {
999
- if (!pair) {
1000
- results.push({
1001
- index,
1002
- failedError: new Error(`No keypair for //${index}`)
1003
- });
1004
- return Promise.resolve();
1005
- }
1006
- return new Promise((resolve) => {
1007
- client.tx.utility.batchAll([
1008
- client.tx.balances.transferAll(this.seedAddress, true),
1009
- client.tx.ownership.transferAll(this.seedAddress, true)
1010
- ]).signAndSend(pair, (cb) => {
1011
- logExtrinsicResult(cb);
1012
- if (cb.dispatchError) {
1013
- const error = dispatchErrorToString(client, cb.dispatchError);
1014
- results.push({
1015
- index,
1016
- failedError: new Error(
1017
- `Error consolidating //${index}: ${error}`
1018
- )
1019
- });
1020
- resolve();
1021
- }
1022
- if (cb.isInBlock) {
1023
- results.push({ index, inBlock: cb.status.asInBlock.toHex() });
1024
- resolve();
1025
- }
1026
- }).catch((e) => {
1027
- results.push({ index, failedError: e });
1028
- resolve();
1029
- });
1030
- });
1031
- })
1032
- );
1033
- return results;
1034
- }
1035
- status(opts) {
1036
- const { argons, argonots, accountSubset, bids, seats } = opts;
1037
- const accounts = [
1038
- {
1039
- index: "main",
1040
- address: this.seedAddress,
1041
- argons: formatArgons(
1042
- argons.find((x) => x.address === this.seedAddress)?.amount ?? 0n
1043
- ),
1044
- argonots: formatArgons(
1045
- argonots.find((x) => x.address === this.seedAddress)?.amount ?? 0n
1046
- )
1047
- }
1048
- ];
1049
- for (const [address, { index }] of Object.entries(
1050
- this.subAccountsByAddress
1051
- )) {
1052
- const argonAmount = argons.find((x) => x.address === address)?.amount ?? 0n;
1053
- const argonotAmount = argonots.find((x) => x.address === address)?.amount ?? 0n;
1054
- const bid = bids.find((x) => x.address === address);
1055
- const seat = seats.find((x) => x.address === address)?.seat;
1056
- const entry = {
1057
- index: ` //${index}`,
1058
- address,
1059
- argons: formatArgons(argonAmount),
1060
- argonots: formatArgons(argonotAmount),
1061
- seat,
1062
- bidPlace: bid?.bidPlace,
1063
- bidAmount: bid?.bidAmount ?? 0n
1064
- };
1065
- if (accountSubset) {
1066
- entry.isWorkingOn = accountSubset.some((x) => x.address === address);
1067
- }
1068
- accounts.push(entry);
1069
- }
1070
- return accounts;
1071
- }
1072
- async registerKeys(url) {
1073
- const client = await getClient(url.replace("ws:", "http:"));
1074
- const keys = this.keys();
1075
- for (const [name, key] of Object.entries(keys)) {
1076
- console.log("Registering key", name, key.publicKey);
1077
- const result = await client.rpc.author.insertKey(
1078
- name,
1079
- key.privateKey,
1080
- key.publicKey
1081
- );
1082
- const saved = await client.rpc.author.hasKey(key.publicKey, name);
1083
- if (!saved) {
1084
- console.error("Failed to register key", name, key.publicKey);
1085
- throw new Error(`Failed to register ${name} key ${key.publicKey}`);
1086
- }
1087
- console.log(`Registered ${name} key`, result.toHuman());
1088
- }
1089
- await client.disconnect();
1090
- }
1091
- keys(keysVersion) {
1092
- let version = keysVersion ?? 0;
1093
- if (process2.env.KEYS_VERSION) {
1094
- version = parseInt(process2.env.KEYS_VERSION) ?? 0;
1095
- }
1096
- const seedMnemonic = this.sessionKeyMnemonic ?? process2.env.KEYS_MNEMONIC;
1097
- if (!seedMnemonic) {
1098
- throw new Error(
1099
- "KEYS_MNEMONIC environment variable not set. Cannot derive keys."
1100
- );
1101
- }
1102
- const blockSealKey = `${seedMnemonic}//block-seal//${version}`;
1103
- const granKey = `${seedMnemonic}//grandpa//${version}`;
1104
- const blockSealAccount = new Keyring().createFromUri(blockSealKey, {
1105
- type: "ed25519"
1106
- });
1107
- const grandpaAccount = new Keyring().createFromUri(granKey, {
1108
- type: "ed25519"
1109
- });
1110
- return {
1111
- seal: {
1112
- privateKey: blockSealKey,
1113
- publicKey: `0x${Buffer.from(blockSealAccount.publicKey).toString("hex")}`,
1114
- rawPublicKey: blockSealAccount.publicKey
1115
- },
1116
- gran: {
1117
- privateKey: granKey,
1118
- publicKey: `0x${Buffer.from(grandpaAccount.publicKey).toString("hex")}`,
1119
- rawPublicKey: grandpaAccount.publicKey
1120
- }
1121
- };
1122
- }
1123
- async tx(tx) {
1124
- const client = await this.client;
1125
- return new TxSubmitter(client, tx, this.txSubmitterPair);
1126
- }
1127
- /**
1128
- * Create but don't submit a mining bid transaction.
1129
- * @param options
1130
- */
1131
- async createMiningBidTx(options) {
1132
- const client = await this.client;
1133
- const { bidAmount, subaccounts, sendRewardsToSeed } = options;
1134
- const batch = client.tx.utility.batch(
1135
- subaccounts.map((x) => {
1136
- const keys = this.keys();
1137
- const rewards = sendRewardsToSeed ? { Account: this.seedAddress } : { Owner: null };
1138
- return client.tx.miningSlot.bid(
1139
- bidAmount,
1140
- rewards,
1141
- {
1142
- grandpa: keys.gran.rawPublicKey,
1143
- blockSealAuthority: keys.seal.rawPublicKey
1144
- },
1145
- x.address
1146
- );
1147
- })
1148
- );
1149
- let tx = batch;
1150
- if (this.isProxy) {
1151
- tx = client.tx.proxy.proxy(this.seedAddress, "MiningBid", batch);
1152
- }
1153
- return new TxSubmitter(client, tx, this.txSubmitterPair);
1154
- }
1155
- /**
1156
- * Create a mining bid. This will create a bid for each account in the given range from the seed account as funding.
1157
- */
1158
- async createMiningBids(options) {
1159
- const accounts = this.getAccountsInRange(options.subaccountRange);
1160
- const client = await this.client;
1161
- const submitter = await this.createMiningBidTx({
1162
- ...options,
1163
- subaccounts: accounts
1164
- });
1165
- const { tip = 0n } = options;
1166
- const txFee = await submitter.feeEstimate(tip);
1167
- let minBalance = options.bidAmount * BigInt(accounts.length);
1168
- let totalFees = tip + 1n + txFee;
1169
- const seedBalance = await client.query.system.account(this.seedAddress).then((x) => x.data.free.toBigInt());
1170
- if (!this.isProxy) {
1171
- minBalance += totalFees;
1172
- }
1173
- if (seedBalance < minBalance) {
1174
- throw new Error(
1175
- `Insufficient balance to create mining bids. Seed account has ${formatArgons(
1176
- seedBalance
1177
- )} but needs ${formatArgons(minBalance)}`
1178
- );
1179
- }
1180
- if (this.isProxy) {
1181
- const { canAfford, availableBalance } = await submitter.canAfford({
1182
- tip
1183
- });
1184
- if (!canAfford) {
1185
- throw new Error(
1186
- `Insufficient balance to pay proxy fees. Proxy account has ${formatArgons(
1187
- availableBalance
1188
- )} but needs ${formatArgons(totalFees)}`
1189
- );
1190
- }
1191
- }
1192
- console.log("Creating bids", {
1193
- perSeatBid: options.bidAmount,
1194
- subaccounts: options.subaccountRange,
1195
- txFee
1196
- });
1197
- const txResult = await submitter.submit({
1198
- tip,
1199
- useLatestNonce: true
1200
- });
1201
- const bidError = await txResult.inBlockPromise.then(() => void 0).catch((x) => x);
1202
- return {
1203
- finalFee: txResult.finalFee,
1204
- bidError,
1205
- blockHash: txResult.includedInBlock,
1206
- successfulBids: txResult.batchInterruptedIndex !== void 0 ? txResult.batchInterruptedIndex : accounts.length
1207
- };
1208
- }
1209
- getAccountsInRange(range) {
1210
- const entries = new Set(range ?? getDefaultSubaccountRange());
1211
- return Object.entries(this.subAccountsByAddress).filter(([_, account]) => {
1212
- return entries.has(account.index);
1213
- }).map(([address, { pair, index }]) => ({ pair, index, address }));
1214
- }
1215
- async watchBlocks(shouldLog = false) {
1216
- const accountMiners = await AccountMiners.loadAt(this, { shouldLog });
1217
- await accountMiners.watch();
1218
- return accountMiners;
1219
- }
1220
- };
1221
- function getDefaultSubaccountRange() {
1222
- try {
1223
- return parseSubaccountRange(process2.env.SUBACCOUNT_RANGE ?? "0-9");
1224
- } catch {
1225
- console.error(
1226
- "Failed to parse SUBACCOUNT_RANGE environment variable. Defaulting to 0-9. Please check the format of the SUBACCOUNT_RANGE variable."
1227
- );
1228
- return Array.from({ length: 10 }, (_, i) => i);
1229
- }
1230
- }
1231
- function parseSubaccountRange(range) {
1232
- if (!range) {
1233
- return void 0;
1234
- }
1235
- const indices = [];
1236
- for (const entry of range.split(",")) {
1237
- if (entry.includes("-")) {
1238
- const [start, end] = entry.split("-").map((x) => parseInt(x, 10));
1239
- for (let i = start; i <= end; i++) {
1240
- indices.push(i);
1241
- }
1242
- continue;
1243
- }
1244
- const record = parseInt(entry.trim(), 10);
1245
- if (Number.isNaN(record) || !Number.isInteger(record)) {
1246
- throw new Error(`Invalid range entry: ${entry}`);
1247
- }
1248
- if (Number.isInteger(record)) {
1249
- indices.push(record);
1250
- }
1251
- }
1252
- return indices;
1253
- }
1254
-
1255
- // src/MiningBids.ts
1256
- import { printTable } from "console-table-printer";
1257
- var MiningBids = class {
1258
- constructor(client, shouldLog = true) {
1259
- this.client = client;
1260
- this.shouldLog = shouldLog;
1261
- }
1262
- nextCohort = [];
1263
- async maxCohortSize() {
1264
- const client = await this.client;
1265
- return client.consts.miningSlot.maxCohortSize.toNumber();
1266
- }
1267
- async onCohortChange(options) {
1268
- const { onBiddingStart, onBiddingEnd } = options;
1269
- const client = await this.client;
1270
- let openCohortId = 0;
1271
- const unsubscribe = await client.queryMulti(
1272
- [
1273
- client.query.miningSlot.isNextSlotBiddingOpen,
1274
- client.query.miningSlot.nextCohortId
1275
- ],
1276
- async ([isBiddingOpen, rawNextCohortId]) => {
1277
- const nextCohortId = rawNextCohortId.toNumber();
1278
- if (isBiddingOpen.isTrue) {
1279
- if (openCohortId !== 0) {
1280
- await onBiddingEnd?.(openCohortId);
1281
- }
1282
- openCohortId = nextCohortId;
1283
- await onBiddingStart?.(nextCohortId);
1284
- } else {
1285
- await onBiddingEnd?.(nextCohortId);
1286
- openCohortId = 0;
1287
- }
1288
- }
1289
- );
1290
- return { unsubscribe };
1291
- }
1292
- async watch(accountNames, blockHash, printFn) {
1293
- const client = await this.client;
1294
- const api = blockHash ? await client.at(blockHash) : client;
1295
- const unsubscribe = await api.query.miningSlot.nextSlotCohort(
1296
- async (next) => {
1297
- this.nextCohort = await Promise.all(
1298
- next.map((x) => this.toBid(accountNames, x))
1299
- );
1300
- if (!this.shouldLog) return;
1301
- console.clear();
1302
- const block = await client.query.system.number();
1303
- if (!printFn) {
1304
- console.log("At block", block.toNumber());
1305
- this.print();
1306
- } else {
1307
- printFn(block.toNumber());
1308
- }
1309
- }
1310
- );
1311
- return { unsubscribe };
1312
- }
1313
- async loadAt(accountNames, blockHash) {
1314
- const client = await this.client;
1315
- const api = blockHash ? await client.at(blockHash) : client;
1316
- const nextCohort = await api.query.miningSlot.nextSlotCohort();
1317
- this.nextCohort = await Promise.all(
1318
- nextCohort.map((x) => this.toBid(accountNames, x))
1319
- );
1320
- }
1321
- async toBid(accountNames, bid) {
1322
- return {
1323
- accountId: bid.accountId.toString(),
1324
- isOurs: accountNames.get(bid.accountId.toString()) ?? "n",
1325
- bidAmount: bid.bid.toBigInt()
1326
- };
1327
- }
1328
- print() {
1329
- const bids = this.nextCohort.map((bid) => {
1330
- return {
1331
- account: bid.accountId,
1332
- isOurs: bid.isOurs,
1333
- bidAmount: formatArgons(bid.bidAmount)
1334
- };
1335
- });
1336
- if (bids.length) {
1337
- console.log("\n\nMining Bids:");
1338
- printTable(bids);
1339
- }
1340
- }
1341
- };
1342
-
1343
- // src/Vault.ts
1344
- import BigNumber3, * as BN2 from "bignumber.js";
1345
- var { ROUND_FLOOR: ROUND_FLOOR2 } = BN2;
1346
- var Vault = class {
1347
- securitization;
1348
- securitizationRatio;
1349
- bitcoinLocked;
1350
- bitcoinPending;
1351
- terms;
1352
- operatorAccountId;
1353
- isClosed;
1354
- vaultId;
1355
- pendingTerms;
1356
- pendingTermsChangeTick;
1357
- openedDate;
1358
- constructor(id, vault, tickDuration) {
1359
- this.securitization = vault.securitization.toBigInt();
1360
- this.securitizationRatio = convertFixedU128ToBigNumber(
1361
- vault.securitizationRatio.toBigInt()
1362
- );
1363
- this.bitcoinLocked = vault.bitcoinLocked.toBigInt();
1364
- this.bitcoinPending = vault.bitcoinPending.toBigInt();
1365
- this.terms = {
1366
- bitcoinAnnualPercentRate: convertFixedU128ToBigNumber(
1367
- vault.terms.bitcoinAnnualPercentRate.toBigInt()
1368
- ),
1369
- bitcoinBaseFee: vault.terms.bitcoinBaseFee.toBigInt(),
1370
- liquidityPoolProfitSharing: convertPermillToBigNumber(
1371
- vault.terms.liquidityPoolProfitSharing.toBigInt()
1372
- )
1373
- };
1374
- this.operatorAccountId = vault.operatorAccountId.toString();
1375
- this.isClosed = vault.isClosed.valueOf();
1376
- this.vaultId = id;
1377
- if (vault.pendingTerms.isSome) {
1378
- const [tickApply, terms] = vault.pendingTerms.value;
1379
- this.pendingTermsChangeTick = tickApply.toNumber();
1380
- this.pendingTerms = {
1381
- bitcoinAnnualPercentRate: convertFixedU128ToBigNumber(
1382
- terms.bitcoinAnnualPercentRate.toBigInt()
1383
- ),
1384
- bitcoinBaseFee: terms.bitcoinBaseFee.toBigInt(),
1385
- liquidityPoolProfitSharing: convertPermillToBigNumber(
1386
- vault.terms.liquidityPoolProfitSharing.toBigInt()
1387
- )
1388
- };
1389
- }
1390
- this.openedDate = vault.openedTick ? new Date(vault.openedTick.toNumber() * tickDuration) : /* @__PURE__ */ new Date();
1391
- }
1392
- availableBitcoinSpace() {
1393
- const recoverySecuritization = this.recoverySecuritization();
1394
- return this.securitization - recoverySecuritization - this.bitcoinLocked;
1395
- }
1396
- recoverySecuritization() {
1397
- const reserved = new BigNumber3(1).div(this.securitizationRatio);
1398
- return this.securitization - BigInt(
1399
- reserved.multipliedBy(this.securitization.toString()).toFixed(0, ROUND_FLOOR2)
1400
- );
1401
- }
1402
- minimumSecuritization() {
1403
- return BigInt(
1404
- this.securitizationRatio.multipliedBy(this.bitcoinLocked.toString()).decimalPlaces(0, BigNumber3.ROUND_CEIL).toString()
1405
- );
1406
- }
1407
- activatedSecuritization() {
1408
- const activated = this.bitcoinLocked - this.bitcoinPending;
1409
- let maxRatio = this.securitizationRatio;
1410
- if (this.securitizationRatio.toNumber() > 2) {
1411
- maxRatio = BigNumber3(2);
1412
- }
1413
- return BigInt(
1414
- maxRatio.multipliedBy(activated.toString()).toFixed(0, ROUND_FLOOR2)
1415
- );
1416
- }
1417
- /**
1418
- * Returns the amount of Argons available to match per liquidity pool
1419
- */
1420
- activatedSecuritizationPerSlot() {
1421
- const activated = this.activatedSecuritization();
1422
- return activated / 10n;
1423
- }
1424
- calculateBitcoinFee(amount) {
1425
- const fee = this.terms.bitcoinAnnualPercentRate.multipliedBy(Number(amount)).integerValue(BigNumber3.ROUND_CEIL);
1426
- return BigInt(fee.toString()) + this.terms.bitcoinBaseFee;
1427
- }
1428
- };
1429
-
1430
- // src/VaultMonitor.ts
1431
- import { printTable as printTable2 } from "console-table-printer";
1432
- import { createNanoEvents as createNanoEvents3 } from "nanoevents";
1433
- var VaultMonitor = class {
1434
- constructor(accountset, alerts = {}, options = {}) {
1435
- this.accountset = accountset;
1436
- this.alerts = alerts;
1437
- this.options = options;
1438
- this.mainchain = accountset.client;
1439
- if (options.vaultOnlyWatchMode !== void 0) {
1440
- this.vaultOnlyWatchMode = options.vaultOnlyWatchMode;
1441
- }
1442
- if (options.shouldLog !== void 0) {
1443
- this.shouldLog = options.shouldLog;
1444
- }
1445
- this.miningBids = new MiningBids(this.mainchain, this.shouldLog);
1446
- this.blockWatch = new BlockWatch(this.mainchain, {
1447
- shouldLog: this.shouldLog
1448
- });
1449
- this.blockWatch.events.on(
1450
- "vaults-updated",
1451
- (header, vaultIds) => this.onVaultsUpdated(header.hash, vaultIds)
1452
- );
1453
- this.blockWatch.events.on("mining-bid", async (header, _bid) => {
1454
- await this.miningBids.loadAt(this.accountset.namedAccounts, header.hash);
1455
- this.printBids(header.hash);
1456
- });
1457
- this.blockWatch.events.on("mining-bid-ousted", async (header) => {
1458
- await this.miningBids.loadAt(this.accountset.namedAccounts, header.hash);
1459
- this.printBids(header.hash);
1460
- });
1461
- }
1462
- events = createNanoEvents3();
1463
- vaultsById = {};
1464
- blockWatch;
1465
- mainchain;
1466
- activatedCapitalByVault = {};
1467
- lastPrintedBids;
1468
- miningBids;
1469
- tickDuration = 0;
1470
- vaultOnlyWatchMode = false;
1471
- shouldLog = true;
1472
- stop() {
1473
- this.blockWatch.stop();
1474
- }
1475
- async monitor(justPrint = false) {
1476
- const client = await this.mainchain;
1477
- this.tickDuration = (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();
1478
- const blockHeader = await client.rpc.chain.getHeader();
1479
- const blockHash = blockHeader.hash.toU8a();
1480
- console.log(
1481
- `${justPrint ? "Run" : "Started"} at block ${blockHeader.number} - ${blockHeader.hash.toHuman()}`
1482
- );
1483
- await this.miningBids.loadAt(this.accountset.namedAccounts, blockHash);
1484
- const vaults = await client.query.vaults.vaultsById.entries();
1485
- for (const [storageKey, rawVault] of vaults) {
1486
- const vaultId = storageKey.args[0].toNumber();
1487
- this.updateVault(vaultId, rawVault);
1488
- }
1489
- await client.query.liquidityPools.nextLiquidityPoolCapital((x) => {
1490
- this.activatedCapitalByVault = {};
1491
- for (const entry of x) {
1492
- const vaultId = entry.vaultId.toNumber();
1493
- this.activatedCapitalByVault[vaultId] = entry.activatedCapital.toBigInt();
1494
- }
1495
- for (const [vaultId, vault] of Object.entries(this.vaultsById)) {
1496
- const id = Number(vaultId);
1497
- this.activatedCapitalByVault[id] ??= 0n;
1498
- this.checkMiningBondAlerts(id, vault);
1499
- }
1500
- });
1501
- this.printVaults();
1502
- if (!this.vaultOnlyWatchMode && this.shouldLog) {
1503
- this.miningBids.print();
1504
- }
1505
- if (!justPrint) await this.blockWatch.start();
1506
- }
1507
- printVaults() {
1508
- if (!this.shouldLog) return;
1509
- const vaults = [];
1510
- for (const [vaultId, vault] of Object.entries(this.vaultsById)) {
1511
- vaults.push({
1512
- id: vaultId,
1513
- btcSpace: `${formatArgons(vault.availableBitcoinSpace())} (${formatArgons(vault.bitcoinPending)} pending)`,
1514
- btcDeal: `${formatArgons(vault.terms.bitcoinBaseFee)} + ${formatPercent(vault.terms.bitcoinAnnualPercentRate)}`,
1515
- securitization: `${formatArgons(vault.securitization)} at ${vault.securitizationRatio.toFormat(1)}x`,
1516
- securActivated: `${formatArgons(vault.activatedSecuritizationPerSlot())}/slot`,
1517
- liquidPoolDeal: `${formatPercent(vault.terms.liquidityPoolProfitSharing)} sharing`,
1518
- operator: `${this.accountset.namedAccounts.has(vault.operatorAccountId) ? ` (${this.accountset.namedAccounts.get(vault.operatorAccountId)})` : vault.operatorAccountId}`,
1519
- state: vault.isClosed ? "closed" : vault.openedDate < /* @__PURE__ */ new Date() ? "open" : "pending"
1520
- });
1521
- }
1522
- if (vaults.length) {
1523
- if (this.vaultOnlyWatchMode) {
1524
- console.clear();
1525
- }
1526
- console.log("\n\nVaults:");
1527
- printTable2(vaults);
1528
- }
1529
- }
1530
- async recheckAfterActive(vaultId) {
1531
- const activationDate = this.vaultsById[vaultId].openedDate;
1532
- if (this.shouldLog) {
1533
- console.log(`Waiting for vault ${vaultId} to activate ${activationDate}`);
1534
- }
1535
- await new Promise(
1536
- (resolve) => setTimeout(resolve, activationDate.getTime() - Date.now())
1537
- );
1538
- const client = await this.mainchain;
1539
- let isReady = false;
1540
- while (!isReady) {
1541
- const rawVault = await client.query.vaults.vaultsById(vaultId);
1542
- if (!rawVault.isSome) return;
1543
- const vault = new Vault(vaultId, rawVault.value, this.tickDuration);
1544
- this.vaultsById[vaultId] = vault;
1545
- if (vault.isClosed) return;
1546
- if (vault.openedDate < /* @__PURE__ */ new Date()) {
1547
- isReady = true;
1548
- break;
1549
- }
1550
- await new Promise((resolve) => setTimeout(resolve, 100));
1551
- }
1552
- this.checkAlerts(vaultId, this.vaultsById[vaultId]);
1553
- }
1554
- async onVaultsUpdated(blockHash, vaultIds) {
1555
- await this.reloadVaultsAt([...vaultIds], blockHash).catch((err) => {
1556
- console.error(
1557
- `Failed to reload vault ${[...vaultIds]} at block ${blockHash}:`,
1558
- err
1559
- );
1560
- });
1561
- this.printVaults();
1562
- }
1563
- async reloadVaultsAt(vaultIds, blockHash) {
1564
- const client = await this.mainchain;
1565
- const api = await client.at(blockHash);
1566
- const vaults = await api.query.vaults.vaultsById.multi(vaultIds);
1567
- for (let i = 0; i < vaultIds.length; i += 1) {
1568
- this.updateVault(vaultIds[i], vaults[i]);
1569
- }
1570
- }
1571
- updateVault(vaultId, rawVault) {
1572
- if (rawVault.isNone) return;
1573
- const vault = new Vault(vaultId, rawVault.value, this.tickDuration);
1574
- this.vaultsById[vaultId] = vault;
1575
- if (vault.openedDate > /* @__PURE__ */ new Date()) {
1576
- void this.recheckAfterActive(vaultId);
1577
- } else {
1578
- this.checkAlerts(vaultId, vault);
1579
- }
1580
- }
1581
- checkAlerts(vaultId, vault) {
1582
- if (this.alerts.bitcoinSpaceAvailable !== void 0) {
1583
- const availableBitcoinSpace = vault.availableBitcoinSpace();
1584
- if (availableBitcoinSpace >= this.alerts.bitcoinSpaceAvailable) {
1585
- console.warn(
1586
- `Vault ${vaultId} has available bitcoins above ${formatArgons(this.alerts.bitcoinSpaceAvailable)}`
1587
- );
1588
- this.events.emit("bitcoin-space-above", vaultId, availableBitcoinSpace);
1589
- }
1590
- }
1591
- }
1592
- checkMiningBondAlerts(vaultId, vault) {
1593
- if (this.alerts.liquidityPoolSpaceAvailable === void 0) return;
1594
- const activatedSecuritization = vault.activatedSecuritizationPerSlot();
1595
- const capitalization = this.activatedCapitalByVault[vaultId] ?? 0n;
1596
- const available = activatedSecuritization - capitalization;
1597
- if (available >= this.alerts.liquidityPoolSpaceAvailable) {
1598
- this.events.emit("liquidity-pool-space-above", vaultId, available);
1599
- }
1600
- }
1601
- printBids(blockHash) {
1602
- if (!this.shouldLog) return;
1603
- if (this.lastPrintedBids === blockHash) return;
1604
- this.miningBids.print();
1605
- this.lastPrintedBids = blockHash;
1606
- }
1607
- };
1608
-
1609
- // src/CohortBidderHistory.ts
1610
- var CohortBidderHistory = class _CohortBidderHistory {
1611
- constructor(cohortId, subaccounts) {
1612
- this.cohortId = cohortId;
1613
- this.subaccounts = subaccounts;
1614
- this.maxSeatsInPlay = this.subaccounts.length;
1615
- this.subaccounts.forEach((x) => {
1616
- this.myAddresses.add(x.address);
1617
- });
1618
- }
1619
- bidHistory = [];
1620
- stats = {
1621
- // number of seats won
1622
- seatsWon: 0,
1623
- // sum of argons bid in successful bids
1624
- totalArgonsBid: 0n,
1625
- // total number of bids placed (includes 1 per seat)
1626
- bidsAttempted: 0,
1627
- // fees including the tip
1628
- fees: 0n,
1629
- // Max bid per seat
1630
- maxBidPerSeat: 0n,
1631
- // The cost in argonots of each seat
1632
- argonotsPerSeat: 0n,
1633
- // The argonot price in USD for cost basis
1634
- argonotUsdPrice: 0,
1635
- // The cohort expected argons per block
1636
- cohortArgonsPerBlock: 0n,
1637
- // The last block that bids are synced to
1638
- lastBlockNumber: 0
1639
- };
1640
- lastBids = [];
1641
- myAddresses = /* @__PURE__ */ new Set();
1642
- maxSeatsInPlay = 0;
1643
- async init(client) {
1644
- if (!this.stats.argonotsPerSeat) {
1645
- const startingStats = await _CohortBidderHistory.getStartingData(client);
1646
- Object.assign(this.stats, startingStats);
1647
- }
1648
- }
1649
- maybeReducingSeats(maxSeats, reason, historyEntry) {
1650
- if (this.maxSeatsInPlay > maxSeats) {
1651
- historyEntry.maxSeatsReductionReason = reason;
1652
- }
1653
- this.maxSeatsInPlay = maxSeats;
1654
- historyEntry.maxSeatsInPlay = maxSeats;
1655
- }
1656
- trackChange(next, blockNumber, tick, isLastEntry = false) {
1657
- let winningBids = 0;
1658
- let totalArgonsBid = 0n;
1659
- const nextEntrants = [];
1660
- for (const x of next) {
1661
- const bid = x.bid.toBigInt();
1662
- const address = x.accountId.toHuman();
1663
- nextEntrants.push({ address, bid });
1664
- if (this.myAddresses.has(address)) {
1665
- winningBids++;
1666
- totalArgonsBid += bid;
1667
- }
1668
- }
1669
- this.stats.seatsWon = winningBids;
1670
- this.stats.totalArgonsBid = totalArgonsBid;
1671
- this.stats.lastBlockNumber = Math.max(
1672
- blockNumber,
1673
- this.stats.lastBlockNumber
1674
- );
1675
- const historyEntry = {
1676
- cohortId: this.cohortId,
1677
- blockNumber,
1678
- tick,
1679
- bidChanges: [],
1680
- winningSeats: winningBids,
1681
- maxSeatsInPlay: this.maxSeatsInPlay
1682
- };
1683
- const hasDiffs = JsonExt.stringify(nextEntrants) !== JsonExt.stringify(this.lastBids);
1684
- if (!isLastEntry || hasDiffs) {
1685
- this.bidHistory.unshift(historyEntry);
1686
- }
1687
- if (hasDiffs) {
1688
- nextEntrants.forEach(({ address, bid }, i) => {
1689
- const prevBidIndex = this.lastBids.findIndex(
1690
- (y) => y.address === address
1691
- );
1692
- const entry = {
1693
- address,
1694
- bidAmount: bid,
1695
- bidPosition: i,
1696
- prevPosition: prevBidIndex === -1 ? null : prevBidIndex
1697
- };
1698
- if (prevBidIndex !== -1) {
1699
- const prevBidAmount = this.lastBids[prevBidIndex].bid;
1700
- if (prevBidAmount !== bid) {
1701
- entry.prevBidAmount = prevBidAmount;
1702
- }
1703
- }
1704
- historyEntry.bidChanges.push(entry);
1705
- });
1706
- this.lastBids.forEach(({ address, bid }, i) => {
1707
- const nextBid = nextEntrants.some((y) => y.address === address);
1708
- if (!nextBid) {
1709
- historyEntry.bidChanges.push({
1710
- address,
1711
- bidAmount: bid,
1712
- bidPosition: null,
1713
- prevPosition: i
1714
- });
1715
- }
1716
- });
1717
- this.lastBids = nextEntrants;
1718
- }
1719
- return historyEntry;
1720
- }
1721
- onBidResult(historyEntry, param) {
1722
- const {
1723
- txFeePlusTip,
1724
- bidPerSeat,
1725
- bidsAttempted,
1726
- successfulBids,
1727
- blockNumber,
1728
- bidError
1729
- } = param;
1730
- this.stats.fees += txFeePlusTip;
1731
- this.stats.bidsAttempted += bidsAttempted;
1732
- if (bidPerSeat > this.stats.maxBidPerSeat) {
1733
- this.stats.maxBidPerSeat = bidPerSeat;
1734
- }
1735
- if (blockNumber !== void 0) {
1736
- this.stats.lastBlockNumber = Math.max(
1737
- blockNumber,
1738
- this.stats.lastBlockNumber
1739
- );
1740
- }
1741
- historyEntry.myBidsPlaced.failureReason = bidError;
1742
- historyEntry.myBidsPlaced.successfulBids = successfulBids;
1743
- historyEntry.myBidsPlaced.txFeePlusTip = txFeePlusTip;
1744
- }
1745
- static async getStartingData(api) {
1746
- const argonotPrice = await api.query.priceIndex.current();
1747
- let argonotUsdPrice = 0;
1748
- if (argonotPrice.isSome) {
1749
- argonotUsdPrice = convertFixedU128ToBigNumber(
1750
- argonotPrice.unwrap().argonotUsdPrice.toBigInt()
1751
- ).toNumber();
1752
- }
1753
- const argonotsPerSeat = await api.query.miningSlot.argonotsPerMiningSeat().then((x) => x.toBigInt());
1754
- const cohortArgonsPerBlock = await api.query.blockRewards.argonsPerBlock().then((x) => x.toBigInt());
1755
- return { argonotsPerSeat, argonotUsdPrice, cohortArgonsPerBlock };
1756
- }
1757
- };
1758
-
1759
- // src/CohortBidder.ts
1760
- var CohortBidder = class {
1761
- constructor(accountset, cohortId, subaccounts, options) {
1762
- this.accountset = accountset;
1763
- this.cohortId = cohortId;
1764
- this.subaccounts = subaccounts;
1765
- this.options = options;
1766
- this.history = new CohortBidderHistory(cohortId, subaccounts);
1767
- this.subaccounts.forEach((x) => {
1768
- this.myAddresses.add(x.address);
1769
- });
1770
- }
1771
- get client() {
1772
- return this.accountset.client;
1773
- }
1774
- get stats() {
1775
- return this.history.stats;
1776
- }
1777
- get bidHistory() {
1778
- return this.history.bidHistory;
1779
- }
1780
- unsubscribe;
1781
- pendingRequest;
1782
- retryTimeout;
1783
- isStopped = false;
1784
- needsRebid = false;
1785
- lastBidTime = 0;
1786
- history;
1787
- millisPerTick;
1788
- myAddresses = /* @__PURE__ */ new Set();
1789
- async stop() {
1790
- if (this.isStopped) return this.stats;
1791
- this.isStopped = true;
1792
- console.log("Stopping bidder for cohort", this.cohortId);
1793
- clearTimeout(this.retryTimeout);
1794
- if (this.unsubscribe) {
1795
- this.unsubscribe();
1796
- }
1797
- const client = await this.client;
1798
- const [nextCohortId, isBiddingOpen] = await client.queryMulti([
1799
- client.query.miningSlot.nextCohortId,
1800
- client.query.miningSlot.isNextSlotBiddingOpen
1801
- ]);
1802
- if (nextCohortId.toNumber() === this.cohortId && isBiddingOpen.isTrue) {
1803
- console.log("Bidding is still open, waiting for it to close");
1804
- await new Promise(async (resolve) => {
1805
- const unsub = await client.query.miningSlot.isNextSlotBiddingOpen(
1806
- (isOpen) => {
1807
- if (isOpen.isFalse) {
1808
- unsub();
1809
- resolve();
1810
- }
1811
- }
1812
- );
1813
- });
1814
- }
1815
- void await this.pendingRequest;
1816
- let header = await client.rpc.chain.getHeader();
1817
- while (true) {
1818
- const api2 = await client.at(header.hash);
1819
- const cohortId = await api2.query.miningSlot.nextCohortId();
1820
- if (cohortId.toNumber() === this.cohortId) {
1821
- break;
1822
- }
1823
- header = await client.rpc.chain.getHeader(header.parentHash);
1824
- }
1825
- const api = await client.at(header.hash);
1826
- const tick = await api.query.ticks.currentTick().then((x) => x.toNumber());
1827
- const cohort = await api.query.miningSlot.nextSlotCohort();
1828
- this.history.trackChange(cohort, header.number.toNumber(), tick, true);
1829
- console.log("Bidder stopped", {
1830
- cohortId: this.cohortId,
1831
- blockNumber: header.number.toNumber(),
1832
- tick,
1833
- cohort: cohort.map((x) => ({
1834
- address: x.accountId.toHuman(),
1835
- bid: x.bid.toBigInt()
1836
- }))
1837
- });
1838
- return this.stats;
1839
- }
1840
- async start() {
1841
- console.log(`Starting cohort ${this.cohortId} bidder`, {
1842
- maxBid: formatArgons(this.options.maxBid),
1843
- minBid: formatArgons(this.options.minBid),
1844
- bidIncrement: formatArgons(this.options.bidIncrement),
1845
- maxBudget: formatArgons(this.options.maxBudget),
1846
- bidDelay: this.options.bidDelay,
1847
- subaccounts: this.subaccounts
1848
- });
1849
- const client = await this.client;
1850
- await this.history.init(client);
1851
- this.millisPerTick ??= await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
1852
- this.unsubscribe = await client.queryMulti(
1853
- [
1854
- client.query.miningSlot.nextSlotCohort,
1855
- client.query.miningSlot.nextCohortId
1856
- ],
1857
- async ([next, nextCohortId]) => {
1858
- if (nextCohortId.toNumber() === this.cohortId) {
1859
- await this.checkSeats(next);
1860
- }
1861
- }
1862
- );
1863
- }
1864
- async checkSeats(next) {
1865
- if (this.isStopped) return;
1866
- clearTimeout(this.retryTimeout);
1867
- const client = await this.client;
1868
- const bestBlock = await client.rpc.chain.getBlockHash();
1869
- const api = await client.at(bestBlock);
1870
- const blockNumber = await api.query.system.number().then((x) => x.toNumber());
1871
- if (this.bidHistory[0]?.blockNumber >= blockNumber) {
1872
- return;
1873
- }
1874
- const tick = await api.query.ticks.currentTick().then((x) => x.toNumber());
1875
- const historyEntry = this.history.trackChange(next, blockNumber, tick);
1876
- if (this.pendingRequest) return;
1877
- const ticksSinceLastBid = Math.floor(
1878
- (Date.now() - this.lastBidTime) / this.millisPerTick
1879
- );
1880
- if (ticksSinceLastBid < this.options.bidDelay) {
1881
- this.retryTimeout = setTimeout(
1882
- () => void this.checkCurrentSeats(),
1883
- this.millisPerTick
1884
- );
1885
- return;
1886
- }
1887
- console.log(
1888
- "Checking bids for cohort",
1889
- this.cohortId,
1890
- this.subaccounts.map((x) => x.index)
1891
- );
1892
- const winningBids = historyEntry.winningSeats;
1893
- this.needsRebid = winningBids < this.subaccounts.length;
1894
- if (!this.needsRebid) return;
1895
- const winningAddresses = new Set(next.map((x) => x.accountId.toHuman()));
1896
- let lowestBid = -this.options.bidIncrement;
1897
- if (next.length) {
1898
- for (let i = next.length - 1; i >= 0; i--) {
1899
- if (!this.myAddresses.has(next[i].accountId.toHuman())) {
1900
- lowestBid = next.at(i).bid.toBigInt();
1901
- break;
1902
- }
1903
- }
1904
- }
1905
- const MIN_INCREMENT = 10000n;
1906
- let nextBid = lowestBid + this.options.bidIncrement;
1907
- if (nextBid < this.options.minBid) {
1908
- nextBid = this.options.minBid;
1909
- }
1910
- if (nextBid > this.options.maxBid) {
1911
- nextBid = this.options.maxBid;
1912
- }
1913
- const fakeTx = await this.accountset.createMiningBidTx({
1914
- subaccounts: this.subaccounts,
1915
- bidAmount: nextBid,
1916
- sendRewardsToSeed: true
1917
- });
1918
- let availableBalanceForBids = await api.query.system.account(this.accountset.txSubmitterPair.address).then((x) => x.data.free.toBigInt());
1919
- for (const bid of next) {
1920
- if (this.myAddresses.has(bid.accountId.toHuman())) {
1921
- availableBalanceForBids += bid.bid.toBigInt();
1922
- }
1923
- }
1924
- const tip = this.options.tipPerTransaction ?? 0n;
1925
- const feeEstimate = await fakeTx.feeEstimate(tip);
1926
- const feePlusTip = feeEstimate + tip;
1927
- let budgetForSeats = this.options.maxBudget - feePlusTip;
1928
- if (budgetForSeats > availableBalanceForBids) {
1929
- budgetForSeats = availableBalanceForBids - feePlusTip;
1930
- }
1931
- if (nextBid < lowestBid) {
1932
- console.log(
1933
- `Can't bid ${formatArgons(nextBid)}. Current lowest bid is ${formatArgons(
1934
- lowestBid
1935
- )}.`
1936
- );
1937
- this.history.maybeReducingSeats(
1938
- winningBids,
1939
- "MaxBidTooLow" /* MaxBidTooLow */,
1940
- historyEntry
1941
- );
1942
- return;
1943
- }
1944
- if (nextBid - lowestBid < MIN_INCREMENT) {
1945
- console.log(
1946
- `Can't make any more bids for ${this.cohortId} with given constraints.`,
1947
- {
1948
- lowestCurrentBid: formatArgons(lowestBid),
1949
- nextAttemptedBid: formatArgons(nextBid),
1950
- maxBid: formatArgons(this.options.maxBid)
1951
- }
1952
- );
1953
- this.history.maybeReducingSeats(
1954
- winningBids,
1955
- "MaxBidTooLow" /* MaxBidTooLow */,
1956
- historyEntry
1957
- );
1958
- return;
1959
- }
1960
- const seatsInBudget = nextBid === 0n ? this.subaccounts.length : Number(budgetForSeats / nextBid);
1961
- let accountsToUse = [...this.subaccounts];
1962
- if (accountsToUse.length > seatsInBudget) {
1963
- const reason = availableBalanceForBids - feePlusTip < nextBid * BigInt(seatsInBudget) ? "InsufficientFunds" /* InsufficientFunds */ : "MaxBudgetTooLow" /* MaxBudgetTooLow */;
1964
- this.history.maybeReducingSeats(seatsInBudget, reason, historyEntry);
1965
- accountsToUse.sort((a, b) => {
1966
- const isWinningA = winningAddresses.has(a.address);
1967
- const isWinningB = winningAddresses.has(b.address);
1968
- if (isWinningA && !isWinningB) return -1;
1969
- if (!isWinningA && isWinningB) return 1;
1970
- if (a.isRebid && !b.isRebid) return -1;
1971
- if (!a.isRebid && b.isRebid) return 1;
1972
- return a.index - b.index;
1973
- });
1974
- accountsToUse.length = seatsInBudget;
1975
- }
1976
- if (accountsToUse.length > winningBids) {
1977
- historyEntry.myBidsPlaced = {
1978
- bids: accountsToUse.length,
1979
- bidPerSeat: nextBid,
1980
- txFeePlusTip: feePlusTip,
1981
- successfulBids: 0
1982
- };
1983
- this.pendingRequest = this.bid(nextBid, accountsToUse, historyEntry);
1984
- } else if (historyEntry.bidChanges.length === 0) {
1985
- this.history.bidHistory.shift();
1986
- }
1987
- this.needsRebid = false;
1988
- }
1989
- async bid(bidPerSeat, subaccounts, historyEntry) {
1990
- const prevLastBidTime = this.lastBidTime;
1991
- try {
1992
- this.lastBidTime = Date.now();
1993
- const submitter = await this.accountset.createMiningBidTx({
1994
- subaccounts,
1995
- bidAmount: bidPerSeat,
1996
- sendRewardsToSeed: true
1997
- });
1998
- const tip = this.options.tipPerTransaction ?? 0n;
1999
- const txResult = await submitter.submit({
2000
- tip,
2001
- useLatestNonce: true
2002
- });
2003
- const bidError = await txResult.inBlockPromise.then(() => void 0).catch((x) => x);
2004
- let blockNumber;
2005
- if (txResult.includedInBlock) {
2006
- const client = await this.client;
2007
- const api = await client.at(txResult.includedInBlock);
2008
- blockNumber = await api.query.system.number().then((x) => x.toNumber());
2009
- }
2010
- const successfulBids = txResult.batchInterruptedIndex ?? subaccounts.length;
2011
- this.history.onBidResult(historyEntry, {
2012
- blockNumber,
2013
- successfulBids,
2014
- bidPerSeat,
2015
- txFeePlusTip: txResult.finalFee ?? 0n,
2016
- bidsAttempted: subaccounts.length,
2017
- bidError
2018
- });
2019
- console.log("Done creating bids for cohort", {
2020
- successfulBids,
2021
- bidPerSeat,
2022
- blockNumber
2023
- });
2024
- if (bidError) throw bidError;
2025
- } catch (err) {
2026
- this.lastBidTime = prevLastBidTime;
2027
- console.error(`Error bidding for cohort ${this.cohortId}:`, err);
2028
- clearTimeout(this.retryTimeout);
2029
- this.retryTimeout = setTimeout(() => void this.checkCurrentSeats(), 1e3);
2030
- } finally {
2031
- this.pendingRequest = void 0;
2032
- }
2033
- if (this.needsRebid) {
2034
- this.needsRebid = false;
2035
- await this.checkCurrentSeats();
2036
- }
2037
- }
2038
- async checkCurrentSeats() {
2039
- const client = await this.client;
2040
- const next = await client.query.miningSlot.nextSlotCohort();
2041
- await this.checkSeats(next);
2042
- }
2043
- };
2044
-
2045
- // src/BidPool.ts
2046
- import { Table } from "console-table-printer";
2047
- var EMPTY_TABLE = {
2048
- headerBottom: { left: " ", mid: " ", other: "\u2500", right: " " },
2049
- headerTop: { left: " ", mid: " ", other: " ", right: " " },
2050
- rowSeparator: { left: " ", mid: " ", other: " ", right: " " },
2051
- tableBottom: { left: " ", mid: " ", other: " ", right: " " },
2052
- vertical: " "
2053
- };
2054
- var BidPool = class {
2055
- constructor(client, keypair, accountRegistry = AccountRegistry.factory()) {
2056
- this.client = client;
2057
- this.keypair = keypair;
2058
- this.accountRegistry = accountRegistry;
2059
- this.blockWatch = new BlockWatch(client, { shouldLog: false });
2060
- }
2061
- bidPoolAmount = 0n;
2062
- nextCohortId = 1;
2063
- poolVaultCapitalByCohort = {};
2064
- vaultSecuritization = [];
2065
- printTimeout;
2066
- blockWatch;
2067
- vaultsById = {};
2068
- tickDuration;
2069
- lastDistributedCohortId;
2070
- cohortSubscriptions = {};
2071
- async onVaultsUpdated(blockHash, vaultIdSet) {
2072
- const client = await this.client;
2073
- this.tickDuration ??= (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();
2074
- const api = await client.at(blockHash);
2075
- const vaultIds = [...vaultIdSet];
2076
- const rawVaults = await api.query.vaults.vaultsById.multi(vaultIds);
2077
- for (let i = 0; i < vaultIds.length; i += 1) {
2078
- const rawVault = rawVaults[i];
2079
- if (rawVault.isNone) continue;
2080
- const vaultId = vaultIds[i];
2081
- this.vaultsById[vaultId] = new Vault(
2082
- vaultId,
2083
- rawVault.unwrap(),
2084
- this.tickDuration
2085
- );
2086
- }
2087
- const vaults = Object.entries(this.vaultsById);
2088
- const newSecuritization = [];
2089
- for (const [vaultId, vault] of vaults) {
2090
- const amount = vault.activatedSecuritizationPerSlot();
2091
- newSecuritization.push({
2092
- vaultId: Number(vaultId),
2093
- bitcoinSpace: vault.availableBitcoinSpace(),
2094
- activatedSecuritization: amount,
2095
- vaultSharingPercent: vault.terms.liquidityPoolProfitSharing
2096
- });
2097
- }
2098
- newSecuritization.sort((a, b) => {
2099
- const diff2 = b.activatedSecuritization - a.activatedSecuritization;
2100
- if (diff2 !== 0n) return Number(diff2);
2101
- return a.vaultId - b.vaultId;
2102
- });
2103
- this.vaultSecuritization = newSecuritization;
2104
- this.printDebounce();
2105
- }
2106
- async getBidPool() {
2107
- const client = await this.client;
2108
- const balanceBytes = await client.rpc.state.call(
2109
- "MiningSlotApi_bid_pool",
2110
- ""
2111
- );
2112
- const balance = client.createType("U128", balanceBytes);
2113
- return balance.toBigInt();
2114
- }
2115
- async loadAt(blockHash) {
2116
- const client = await this.client;
2117
- blockHash ??= (await client.rpc.chain.getHeader()).hash.toU8a();
2118
- const api = await client.at(blockHash);
2119
- const rawVaultIds = await api.query.vaults.vaultsById.keys();
2120
- const vaultIds = rawVaultIds.map((x) => x.args[0].toNumber());
2121
- this.bidPoolAmount = await this.getBidPool();
2122
- this.nextCohortId = (await api.query.miningSlot.nextCohortId()).toNumber();
2123
- const contributors = await api.query.liquidityPools.liquidityPoolsByCohort.entries();
2124
- for (const [cohortId, funds] of contributors) {
2125
- const cohortIdNumber = cohortId.args[0].toNumber();
2126
- this.loadCohortData(cohortIdNumber, funds);
2127
- }
2128
- for (const entrant of await api.query.liquidityPools.openLiquidityPoolCapital()) {
2129
- this.setVaultCohortData(this.nextCohortId, entrant.vaultId.toNumber(), {
2130
- activatedCapital: entrant.activatedCapital.toBigInt()
2131
- });
2132
- }
2133
- for (const entrant of await api.query.liquidityPools.nextLiquidityPoolCapital()) {
2134
- this.setVaultCohortData(this.nextCohortId, entrant.vaultId.toNumber(), {
2135
- activatedCapital: entrant.activatedCapital.toBigInt()
2136
- });
2137
- }
2138
- await this.onVaultsUpdated(blockHash, new Set(vaultIds));
2139
- this.print();
2140
- }
2141
- async watch() {
2142
- await this.loadAt();
2143
- await this.blockWatch.start();
2144
- this.blockWatch.events.on(
2145
- "vaults-updated",
2146
- (b, v) => this.onVaultsUpdated(b.hash, v)
2147
- );
2148
- const api = await this.client;
2149
- this.blockWatch.events.on("event", async (_, event) => {
2150
- if (api.events.liquidityPools.BidPoolDistributed.is(event)) {
2151
- const { cohortId: rawCohortId } = event.data;
2152
- this.lastDistributedCohortId = rawCohortId.toNumber();
2153
- this.bidPoolAmount = await this.getBidPool();
2154
- this.cohortSubscriptions[rawCohortId.toNumber()]?.();
2155
- const entrant = await api.query.liquidityPools.liquidityPoolsByCohort(rawCohortId);
2156
- this.loadCohortData(rawCohortId.toNumber(), entrant);
2157
- this.printDebounce();
2158
- }
2159
- if (api.events.liquidityPools.NextBidPoolCapitalLocked.is(event)) {
2160
- const { cohortId } = event.data;
2161
- for (let inc = 0; inc < 2; inc++) {
2162
- const id = cohortId.toNumber() + inc;
2163
- if (!this.cohortSubscriptions[id]) {
2164
- this.cohortSubscriptions[id] = await api.query.liquidityPools.liquidityPoolsByCohort(
2165
- id,
2166
- async (entrant) => {
2167
- this.loadCohortData(id, entrant);
2168
- this.printDebounce();
2169
- }
2170
- );
2171
- }
2172
- }
2173
- }
2174
- });
2175
- const unsubscribe = await api.queryMulti(
2176
- [
2177
- api.query.miningSlot.nextSlotCohort,
2178
- api.query.miningSlot.nextCohortId,
2179
- api.query.liquidityPools.openLiquidityPoolCapital,
2180
- api.query.liquidityPools.nextLiquidityPoolCapital
2181
- ],
2182
- async ([
2183
- _nextSlotCohort,
2184
- nextCohortId,
2185
- openVaultBidPoolCapital,
2186
- nextPoolCapital
2187
- ]) => {
2188
- this.bidPoolAmount = await this.getBidPool();
2189
- this.nextCohortId = nextCohortId.toNumber();
2190
- for (const entrant of [
2191
- ...openVaultBidPoolCapital,
2192
- ...nextPoolCapital
2193
- ]) {
2194
- this.setVaultCohortData(
2195
- entrant.cohortId.toNumber(),
2196
- entrant.vaultId.toNumber(),
2197
- {
2198
- activatedCapital: entrant.activatedCapital.toBigInt()
2199
- }
2200
- );
2201
- }
2202
- this.printDebounce();
2203
- }
2204
- );
2205
- return { unsubscribe };
2206
- }
2207
- async bondArgons(vaultId, amount, options) {
2208
- const client = await this.client;
2209
- const tx = client.tx.liquidityPools.bondArgons(vaultId, amount);
2210
- const txSubmitter = new TxSubmitter(client, tx, this.keypair);
2211
- const affordability = await txSubmitter.canAfford({
2212
- tip: options?.tip,
2213
- unavailableBalance: amount
2214
- });
2215
- if (!affordability.canAfford) {
2216
- console.warn("Insufficient balance to bond argons to liquidity pool", {
2217
- ...affordability,
2218
- argonsNeeded: amount
2219
- });
2220
- throw new Error("Insufficient balance to bond argons to liquidity pool");
2221
- }
2222
- const result = await txSubmitter.submit({
2223
- tip: options?.tip,
2224
- useLatestNonce: true
2225
- });
2226
- await result.inBlockPromise;
2227
- return result;
2228
- }
2229
- printDebounce() {
2230
- if (this.printTimeout) {
2231
- clearTimeout(this.printTimeout);
2232
- }
2233
- this.printTimeout = setTimeout(() => {
2234
- this.print();
2235
- }, 100);
2236
- }
2237
- getOperatorName(vaultId) {
2238
- const vault = this.vaultsById[vaultId];
2239
- return this.accountRegistry.getName(vault.operatorAccountId) ?? vault.operatorAccountId;
2240
- }
2241
- print() {
2242
- console.clear();
2243
- const lastDistributedCohortId = this.lastDistributedCohortId;
2244
- const distributedCohort = this.poolVaultCapitalByCohort[this.lastDistributedCohortId ?? -1] ?? {};
2245
- if (Object.keys(distributedCohort).length > 0) {
2246
- console.log(`
2247
-
2248
- Distributed (cohort ${lastDistributedCohortId})`);
2249
- const rows = [];
2250
- let maxWidth2 = 0;
2251
- for (const [key, entry] of Object.entries(distributedCohort)) {
2252
- const { table, width } = this.createBondCapitalTable(
2253
- entry.earnings ?? 0n,
2254
- entry.contributors ?? [],
2255
- `Earnings (shared = ${formatPercent(entry.vaultSharingPercent)})`
2256
- );
2257
- if (width > maxWidth2) {
2258
- maxWidth2 = width;
2259
- }
2260
- rows.push({
2261
- Vault: key,
2262
- Who: this.getOperatorName(Number(key)),
2263
- Balances: table
2264
- });
2265
- }
2266
- new Table({
2267
- columns: [
2268
- { name: "Vault", alignment: "left" },
2269
- { name: "Who", alignment: "left" },
2270
- {
2271
- name: "Balances",
2272
- title: "Contributor Balances",
2273
- alignment: "center",
2274
- minLen: maxWidth2
2275
- }
2276
- ],
2277
- rows
2278
- }).printTable();
2279
- }
2280
- console.log(
2281
- `
2282
-
2283
- Active Bid Pool: ${formatArgons(this.bidPoolAmount)} (cohort ${this.nextCohortId})`
2284
- );
2285
- const cohort = this.poolVaultCapitalByCohort[this.nextCohortId];
2286
- if (Object.keys(cohort ?? {}).length > 0) {
2287
- const rows = [];
2288
- let maxWidth2 = 0;
2289
- for (const [key, entry] of Object.entries(cohort)) {
2290
- const { table, width } = this.createBondCapitalTable(
2291
- entry.activatedCapital,
2292
- entry.contributors ?? []
2293
- );
2294
- if (width > maxWidth2) {
2295
- maxWidth2 = width;
2296
- }
2297
- rows.push({
2298
- Vault: key,
2299
- Who: this.getOperatorName(Number(key)),
2300
- "Pool Capital": table
2301
- });
2302
- }
2303
- new Table({
2304
- columns: [
2305
- { name: "Vault", alignment: "left" },
2306
- { name: "Who", alignment: "left" },
2307
- { name: "Pool Capital", alignment: "left", minLen: maxWidth2 }
2308
- ],
2309
- rows
2310
- }).printTable();
2311
- }
2312
- const nextPool = this.poolVaultCapitalByCohort[this.nextCohortId + 1] ?? [];
2313
- let maxWidth = 0;
2314
- const nextCapital = [];
2315
- for (const x of this.vaultSecuritization) {
2316
- const entry = nextPool[x.vaultId] ?? {};
2317
- const { table, width } = this.createBondCapitalTable(
2318
- x.activatedSecuritization,
2319
- entry.contributors ?? []
2320
- );
2321
- if (width > maxWidth) {
2322
- maxWidth = width;
2323
- }
2324
- nextCapital.push({
2325
- Vault: x.vaultId,
2326
- Owner: this.getOperatorName(x.vaultId),
2327
- "Bitcoin Space": formatArgons(x.bitcoinSpace),
2328
- "Activated Securitization": `${formatArgons(x.activatedSecuritization)} / slot`,
2329
- "Liquidity Pool": `${formatPercent(x.vaultSharingPercent)} profit sharing${table}`
2330
- });
2331
- }
2332
- if (nextCapital.length) {
2333
- console.log(`
2334
-
2335
- Next (cohort ${this.nextCohortId + 1}):`);
2336
- new Table({
2337
- columns: [
2338
- { name: "Vault", alignment: "left" },
2339
- { name: "Owner", alignment: "left" },
2340
- { name: "Bitcoin Space", alignment: "right" },
2341
- { name: "Activated Securitization", alignment: "right" },
2342
- { name: "Liquidity Pool", alignment: "left", minLen: maxWidth }
2343
- ],
2344
- rows: nextCapital
2345
- }).printTable();
2346
- }
2347
- }
2348
- setVaultCohortData(cohortId, vaultId, data) {
2349
- this.poolVaultCapitalByCohort ??= {};
2350
- this.poolVaultCapitalByCohort[cohortId] ??= {};
2351
- this.poolVaultCapitalByCohort[cohortId][vaultId] ??= {
2352
- activatedCapital: data.activatedCapital ?? data.contributors?.reduce((a, b) => a + b.amount, 0n) ?? 0n
2353
- };
2354
- Object.assign(
2355
- this.poolVaultCapitalByCohort[cohortId][vaultId],
2356
- filterUndefined(data)
2357
- );
2358
- }
2359
- createBondCapitalTable(total, contributors, title = "Total") {
2360
- const table = new Table({
2361
- style: EMPTY_TABLE,
2362
- columns: [
2363
- { name: "who", title, minLen: 10, alignment: "right" },
2364
- {
2365
- name: "amount",
2366
- title: formatArgons(total),
2367
- minLen: 7,
2368
- alignment: "left"
2369
- }
2370
- ]
2371
- });
2372
- for (const x of contributors) {
2373
- table.addRow({
2374
- who: this.accountRegistry.getName(x.address) ?? x.address,
2375
- amount: formatArgons(x.amount)
2376
- });
2377
- }
2378
- const str = table.render();
2379
- const width = str.indexOf("\n");
2380
- return { table: str, width };
2381
- }
2382
- loadCohortData(cohortId, vaultFunds) {
2383
- for (const [vaultId, fund] of vaultFunds) {
2384
- const vaultIdNumber = vaultId.toNumber();
2385
- const contributors = fund.contributorBalances.map(([a, b]) => ({
2386
- address: a.toHuman(),
2387
- amount: b.toBigInt()
2388
- }));
2389
- if (fund.distributedProfits.isSome) {
2390
- if (cohortId > (this.lastDistributedCohortId ?? 0)) {
2391
- this.lastDistributedCohortId = cohortId;
2392
- }
2393
- }
2394
- this.setVaultCohortData(cohortId, vaultIdNumber, {
2395
- earnings: fund.distributedProfits.isSome ? fund.distributedProfits.unwrap().toBigInt() : void 0,
2396
- vaultSharingPercent: convertPermillToBigNumber(
2397
- fund.vaultSharingPercent.toBigInt()
2398
- ),
2399
- contributors
2400
- });
2401
- }
2402
- }
2403
- };
2404
-
2405
- // src/BitcoinLocks.ts
2406
- var SATS_PER_BTC = 100000000n;
2407
- var BitcoinLocks = class _BitcoinLocks {
2408
- constructor(client) {
2409
- this.client = client;
2410
- }
2411
- async getMarketRate(satoshis) {
2412
- const client = await this.client;
2413
- const sats = client.createType("U64", satoshis.toString());
2414
- const marketRate = await client.rpc.state.call(
2415
- "BitcoinApis_market_rate",
2416
- sats.toHex(true)
2417
- );
2418
- const rate = client.createType("Option<U128>", marketRate);
2419
- if (!rate.isSome) {
2420
- throw new Error("Market rate not available");
2421
- }
2422
- return rate.value.toBigInt();
2423
- }
2424
- async buildBitcoinLockTx(args) {
2425
- const { vaultId, keypair, bitcoinXpub, tip } = args;
2426
- let amount = args.amount;
2427
- const marketRatePerBitcoin = await this.getMarketRate(100000000n);
2428
- const client = await this.client;
2429
- const account = await client.query.system.account(keypair.address);
2430
- const freeBalance = account.data.free.toBigInt();
2431
- let availableBalance = freeBalance;
2432
- if (args.reducedBalanceBy) {
2433
- availableBalance -= args.reducedBalanceBy;
2434
- }
2435
- const satoshisNeeded = amount * SATS_PER_BTC / marketRatePerBitcoin - 500n;
2436
- const tx = client.tx.bitcoinLocks.initialize(
2437
- vaultId,
2438
- satoshisNeeded,
2439
- bitcoinXpub
2440
- );
2441
- const existentialDeposit = client.consts.balances.existentialDeposit.toBigInt();
2442
- const finalTip = tip ?? 0n;
2443
- const fees = await tx.paymentInfo(keypair.address, { tip });
2444
- const txFee = fees.partialFee.toBigInt();
2445
- const tickDuration = (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();
2446
- const rawVault = await client.query.vaults.vaultsById(vaultId);
2447
- const vault = new Vault(vaultId, rawVault.unwrap(), tickDuration);
2448
- const btcFee = vault.calculateBitcoinFee(amount);
2449
- const totalCharge = txFee + finalTip + btcFee;
2450
- if (amount + totalCharge + existentialDeposit > availableBalance) {
2451
- throw new Error("Insufficient balance to lock bitcoins");
2452
- }
2453
- console.log(
2454
- `Locking ${satoshisNeeded} satoshis in vault ${vaultId} with market rate of ${formatArgons(marketRatePerBitcoin)}/btc. Xpub: ${bitcoinXpub}`
2455
- );
2456
- return { tx, txFee, btcFee, satoshis: satoshisNeeded, freeBalance };
2457
- }
2458
- static async waitForSpace(accountset, options) {
2459
- const { argonAmount, bitcoinXpub, maxLockFee, tip = 0n } = options;
2460
- const vaults = new VaultMonitor(accountset, {
2461
- bitcoinSpaceAvailable: argonAmount
2462
- });
2463
- return new Promise(async (resolve, reject) => {
2464
- vaults.events.on("bitcoin-space-above", async (vaultId, amount) => {
2465
- const vault = vaults.vaultsById[vaultId];
2466
- const fee = vault.calculateBitcoinFee(amount);
2467
- console.log(
2468
- `Vault ${vaultId} has ${formatArgons(amount)} argons available for bitcoin. Lock fee is ${formatArgons(fee)}`
2469
- );
2470
- if (maxLockFee !== void 0 && fee > maxLockFee) {
2471
- console.log(
2472
- `Skipping vault ${vaultId} due to high lock fee: ${formatArgons(maxLockFee)}`
2473
- );
2474
- return;
2475
- }
2476
- try {
2477
- const bitcoinLock = new _BitcoinLocks(accountset.client);
2478
- const { tx, satoshis, btcFee, txFee } = await bitcoinLock.buildBitcoinLockTx({
2479
- vaultId,
2480
- keypair: accountset.txSubmitterPair,
2481
- amount: argonAmount,
2482
- bitcoinXpub,
2483
- tip
2484
- });
2485
- const result = await accountset.tx(tx).then((x) => x.submit({ waitForBlock: true, tip }));
2486
- const client = await accountset.client;
2487
- const utxoId = result.events.find((x) => client.events.bitcoinLocks.BitcoinLockCreated.is(x))?.data.utxoId?.toNumber();
2488
- if (!utxoId) {
2489
- throw new Error("Failed to find UTXO ID");
2490
- }
2491
- resolve({
2492
- satoshis,
2493
- argons: argonAmount,
2494
- vaultId,
2495
- btcFee,
2496
- txFee,
2497
- finalizedPromise: result.finalizedPromise,
2498
- utxoId
2499
- });
2500
- } catch (err) {
2501
- console.error("Error submitting bitcoin lock tx:", err);
2502
- reject(err);
2503
- } finally {
2504
- vaults.stop();
2505
- }
2506
- });
2507
- await vaults.monitor();
2508
- });
2509
- }
2510
- };
2511
-
2512
- // src/keyringUtils.ts
2513
- function keyringFromSuri(suri, cryptoType = "sr25519") {
2514
- return new Keyring({ type: cryptoType }).createFromUri(suri);
2515
- }
2516
- function createKeyringPair(opts) {
2517
- const { cryptoType } = opts;
2518
- const seed = mnemonicGenerate();
2519
- return keyringFromSuri(seed, cryptoType);
2520
- }
2521
-
2522
- // src/index.ts
2523
- __reExport(index_exports, types_star2);
2524
- __reExport(index_exports, interfaces_star);
2525
- import * as types_star2 from "@polkadot/types";
2526
- import * as interfaces_star from "@polkadot/types/interfaces";
2527
- async function waitForLoad() {
2528
- await cryptoWaitReady();
2529
- }
2530
- async function getClient(host) {
2531
- let provider;
2532
- if (host.startsWith("http:")) {
2533
- provider = new HttpProvider(host);
2534
- } else {
2535
- provider = new WsProvider(host);
2536
- }
2537
- return await ApiPromise.create({ provider, noInitWarn: true });
2538
- }
2539
-
2540
- // src/clis/accountCli.ts
2541
- import { printTable as printTable3 } from "console-table-printer";
2542
- import { cryptoWaitReady as cryptoWaitReady2 } from "@polkadot/util-crypto";
2543
- import { writeFileSync } from "node:fs";
2544
- import * as process3 from "node:process";
2545
- function accountCli() {
2546
- const program = new Command("accounts").description(
2547
- "Manage subaccounts from a single keypair"
2548
- );
2549
- program.command("watch").description("Watch for blocks closed by subaccounts").action(async () => {
2550
- const accountset = await accountsetFromCli(program);
2551
- const accountMiners = await accountset.watchBlocks();
2552
- accountMiners.events.on("mined", (_block, mined) => {
2553
- console.log("Your accounts authored a block", mined);
2554
- });
2555
- accountMiners.events.on("minted", (_block, minted) => {
2556
- console.log("Your accounts minted argons", minted);
2557
- });
2558
- });
2559
- program.command("list", { isDefault: true }).description("Show subaccounts").option("--addresses", "Just show a list of ids").action(async ({ addresses }) => {
2560
- const { subaccounts } = globalOptions(program);
2561
- const accountset = await accountsetFromCli(program);
2562
- if (addresses) {
2563
- const addresses2 = accountset.addresses;
2564
- console.log(addresses2.join(","));
2565
- process3.exit(0);
2566
- }
2567
- const [argonots, argons, seats, bids] = await Promise.all([
2568
- accountset.totalArgonotsAt(),
2569
- accountset.totalArgonsAt(),
2570
- accountset.miningSeats(),
2571
- accountset.bids()
2572
- ]);
2573
- const accountSubset = subaccounts ? accountset.getAccountsInRange(subaccounts) : void 0;
2574
- const status = accountset.status({
2575
- argons,
2576
- argonots,
2577
- accountSubset,
2578
- seats,
2579
- bids
2580
- });
2581
- printTable3(status);
2582
- process3.exit(0);
2583
- });
2584
- program.command("create").description('Create an account "env" file and optionally register keys').requiredOption(
2585
- "--path <path>",
2586
- "The path to an env file to create (convention is .env.<name>)"
2587
- ).option(
2588
- "--register-keys-to <url>",
2589
- "Register the keys to a url (normally this is localhost)"
2590
- ).action(async ({ registerKeysTo, path }) => {
2591
- const { accountPassphrase, accountSuri, accountFilePath } = globalOptions(program);
2592
- const accountset = await accountsetFromCli(program);
2593
- process3.env.KEYS_MNEMONIC ||= mnemonicGenerate();
2594
- if (registerKeysTo) {
2595
- await accountset.registerKeys(registerKeysTo);
2596
- console.log("Keys registered to", registerKeysTo);
2597
- }
2598
- const envData = {
2599
- ACCOUNT_JSON_PATH: accountFilePath,
2600
- ACCOUNT_SURI: accountSuri,
2601
- ACCOUNT_PASSPHRASE: accountPassphrase,
2602
- KEYS_MNEMONIC: process3.env.KEYS_MNEMONIC,
2603
- SUBACCOUNT_RANGE: "0-49"
2604
- };
2605
- let envfile = "";
2606
- for (const [key, value] of Object.entries(envData)) {
2607
- if (key) {
2608
- const line = `${key}=${String(value)}`;
2609
- envfile += line + "\n";
2610
- }
2611
- }
2612
- writeFileSync(path, envfile);
2613
- console.log("Created env file at", path);
2614
- process3.exit();
2615
- });
2616
- program.command("new-key-seed").description("Create a new mnemonic for runtime keys").action(async () => {
2617
- await cryptoWaitReady2();
2618
- const mnemonic = mnemonicGenerate();
2619
- console.log(
2620
- "New mnemonic (add this to your .env as KEYS_MNEMONIC):",
2621
- mnemonic
2622
- );
2623
- process3.exit(0);
2624
- });
2625
- program.command("register-keys").description("Create an insert-keys script with curl").argument(
2626
- "[node-rpc-url]",
2627
- "The url to your node host (should be installed on machine via localhost)",
2628
- "http://localhost:9944"
2629
- ).option(
2630
- "--print-only",
2631
- "Output as curl commands instead of direct registration"
2632
- ).action(async (nodeRpcUrl, { printOnly }) => {
2633
- const accountset = await accountsetFromCli(program);
2634
- if (printOnly) {
2635
- const { gran, seal } = accountset.keys();
2636
- const commands = [];
2637
- const data = [
2638
- {
2639
- jsonrpc: "2.0",
2640
- id: 0,
2641
- method: "author_insertKey",
2642
- params: ["gran", gran.privateKey, gran.publicKey]
2643
- },
2644
- {
2645
- jsonrpc: "2.0",
2646
- id: 1,
2647
- method: "author_insertKey",
2648
- params: ["seal", seal.privateKey, seal.publicKey]
2649
- }
2650
- ];
2651
- for (const key of data) {
2652
- commands.push(
2653
- `curl -X POST -H "Content-Type: application/json" -d '${JSON.stringify(key)}' ${nodeRpcUrl}`
2654
- );
2655
- }
2656
- console.log(commands.join(" && "));
2657
- } else {
2658
- await accountset.registerKeys(nodeRpcUrl);
2659
- }
2660
- process3.exit();
2661
- });
2662
- program.command("consolidate").description("Consolidate all argons into parent account").option(
2663
- "-s, --subaccounts <range>",
2664
- "Restrict this operation to a subset of the subaccounts (eg, 0-10)",
2665
- parseSubaccountRange
2666
- ).action(async ({ subaccounts }) => {
2667
- const accountset = await accountsetFromCli(program);
2668
- const result = await accountset.consolidate(subaccounts);
2669
- printTable3(result);
2670
- process3.exit(0);
2671
- });
2672
- return program;
2673
- }
2674
-
2675
- // src/clis/index.ts
2676
- import { configDotenv } from "dotenv";
2677
- import Path from "node:path";
2678
-
2679
- // src/clis/vaultCli.ts
2680
- import { Command as Command2 } from "@commander-js/extra-typings";
2681
- function vaultCli() {
2682
- const program = new Command2("vaults").description(
2683
- "Monitor vaults and manage securitization"
2684
- );
2685
- program.command("list", { isDefault: true }).description("Show current state of vaults").action(async () => {
2686
- const accountset = await accountsetFromCli(program);
2687
- const vaults = new VaultMonitor(accountset, void 0, {
2688
- vaultOnlyWatchMode: true
2689
- });
2690
- await vaults.monitor(true);
2691
- process.exit(0);
2692
- });
2693
- program.command("modify-securitization").description("Change the vault securitization ratio").requiredOption("-v, --vault-id <id>", "The vault id to use", parseInt).requiredOption(
2694
- "-a, --argons <amount>",
2695
- "The number of argons to set as securitization",
2696
- parseFloat
2697
- ).option("--ratio <ratio>", "The new securitization ratio", parseFloat).option(
2698
- "--tip <amount>",
2699
- "The tip to include with the transaction",
2700
- parseFloat
2701
- ).action(async ({ tip, argons, vaultId, ratio }) => {
2702
- const accountset = await accountsetFromCli(program);
2703
- const client = await accountset.client;
2704
- const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;
2705
- const microgons = BigInt(argons * MICROGONS_PER_ARGON);
2706
- const rawVault = (await client.query.vaults.vaultsById(vaultId)).unwrap();
2707
- if (rawVault.operatorAccountId.toHuman() !== accountset.seedAddress) {
2708
- console.error("Vault does not belong to this account");
2709
- process.exit(1);
2710
- }
2711
- const existingFunds = rawVault.securitization.toBigInt();
2712
- const additionalFunds = microgons > existingFunds ? microgons - existingFunds : 0n;
2713
- const tx = client.tx.vaults.modifyFunding(
2714
- vaultId,
2715
- microgons,
2716
- ratio !== void 0 ? BigNumber(ratio).times(BigNumber(2).pow(64)).toFixed(0) : rawVault.securitizationRatio.toBigInt()
2717
- );
2718
- const submit = new TxSubmitter(client, tx, accountset.txSubmitterPair);
2719
- const canAfford = await submit.canAfford({
2720
- tip: resolvedTip,
2721
- unavailableBalance: additionalFunds
2722
- });
2723
- if (!canAfford.canAfford) {
2724
- console.warn("Insufficient balance to modify vault securitization", {
2725
- ...canAfford,
2726
- addedSecuritization: additionalFunds
2727
- });
2728
- process.exit(1);
2729
- }
2730
- try {
2731
- const result = await submit.submit({ tip: resolvedTip });
2732
- await result.inBlockPromise;
2733
- console.log("Vault securitization modified");
2734
- process.exit();
2735
- } catch (error) {
2736
- console.error("Error modifying vault securitization", error);
2737
- process.exit(1);
2738
- }
2739
- });
2740
- program.command("make-bitcoin-space").description(
2741
- "Make bitcoin space in a vault and lock it immediately in the same tx."
2742
- ).requiredOption("-v, --vault-id <id>", "The vault id to use", parseInt).requiredOption(
2743
- "-a, --argons <amount>",
2744
- "The number of argons to add",
2745
- parseFloat
2746
- ).requiredOption(
2747
- "--bitcoin-pubkey <pubkey>",
2748
- "The pubkey to use for the bitcoin lock"
2749
- ).option(
2750
- "--tip <amount>",
2751
- "The tip to include with the transaction",
2752
- parseFloat
2753
- ).action(async ({ tip, argons, vaultId, bitcoinPubkey }) => {
2754
- let pubkey = bitcoinPubkey;
2755
- if (!bitcoinPubkey.startsWith("0x")) {
2756
- pubkey = `0x${bitcoinPubkey}`;
2757
- }
2758
- if (pubkey.length !== 68) {
2759
- throw new Error(
2760
- "Bitcoin pubkey must be 66 characters (add 0x in front optionally)"
2761
- );
2762
- }
2763
- const accountset = await accountsetFromCli(program);
2764
- const client = await accountset.client;
2765
- const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;
2766
- const microgons = BigInt(argons * MICROGONS_PER_ARGON);
2767
- const bitcoinLocks = new BitcoinLocks(Promise.resolve(client));
2768
- const existentialDeposit = client.consts.balances.existentialDeposit.toBigInt();
2769
- const tickDuration = (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();
2770
- const rawVault = (await client.query.vaults.vaultsById(vaultId)).unwrap();
2771
- if (rawVault.operatorAccountId.toHuman() !== accountset.seedAddress) {
2772
- console.error("Vault does not belong to this account");
2773
- process.exit(1);
2774
- }
2775
- const vaultModifyTx = client.tx.vaults.modifyFunding(
2776
- vaultId,
2777
- microgons,
2778
- rawVault.securitizationRatio.toBigInt()
2779
- );
2780
- const vaultTxFee = (await vaultModifyTx.paymentInfo(accountset.txSubmitterPair)).partialFee.toBigInt();
2781
- const vault = new Vault(vaultId, rawVault, tickDuration);
2782
- const argonsNeeded = microgons - vault.securitization;
2783
- const argonsAvailable = microgons - vault.availableBitcoinSpace();
2784
- const account = await client.query.system.account(accountset.seedAddress);
2785
- const freeBalance = account.data.free.toBigInt();
2786
- const {
2787
- tx: lockTx,
2788
- btcFee,
2789
- txFee
2790
- } = await bitcoinLocks.buildBitcoinLockTx({
2791
- vaultId,
2792
- keypair: accountset.txSubmitterPair,
2793
- amount: argonsAvailable,
2794
- bitcoinXpub: pubkey,
2795
- tip: resolvedTip,
2796
- reducedBalanceBy: argonsNeeded + vaultTxFee + resolvedTip
2797
- });
2798
- if (argonsNeeded + txFee + vaultTxFee + resolvedTip + btcFee + existentialDeposit > freeBalance) {
2799
- console.warn(
2800
- "Insufficient balance to add bitcoin space and use bitcoins",
2801
- {
2802
- freeBalance,
2803
- txFee,
2804
- vaultTxFee,
2805
- btcFee,
2806
- argonsAvailable,
2807
- vaultMicrogons: microgons,
2808
- existentialDeposit,
2809
- neededBalanceAboveED: argonsNeeded + txFee + resolvedTip + btcFee + vaultTxFee
2810
- }
2811
- );
2812
- process.exit(1);
2813
- }
2814
- console.log("Adding bitcoin space and locking bitcoins...", {
2815
- newArgonsAvailable: argonsAvailable,
2816
- txFee,
2817
- vaultTxFee,
2818
- btcFee,
2819
- resolvedTip
2820
- });
2821
- const txSubmitter = new TxSubmitter(
2822
- client,
2823
- client.tx.utility.batchAll([vaultModifyTx, lockTx]),
2824
- accountset.txSubmitterPair
2825
- );
2826
- const result = await txSubmitter.submit({ tip: resolvedTip });
2827
- try {
2828
- await result.inBlockPromise;
2829
- console.log("Bitcoin space done");
2830
- } catch (error) {
2831
- console.error("Error using bitcoin space", error);
2832
- process.exit(1);
2833
- }
2834
- });
2835
- return program;
2836
- }
2837
-
2838
- // src/clis/miningCli.ts
2839
- import { Command as Command3 } from "@commander-js/extra-typings";
2840
- import { printTable as printTable4 } from "console-table-printer";
2841
- function miningCli() {
2842
- const program = new Command3("mining").description(
2843
- "Watch mining seats or setup bidding"
2844
- );
2845
- program.command("list", { isDefault: true }).description("Monitor all miners").action(async () => {
2846
- const accountset = await accountsetFromCli(program);
2847
- const bids = new MiningBids(accountset.client);
2848
- const api = await accountset.client;
2849
- let lastMiners = {};
2850
- function print(blockNumber) {
2851
- console.clear();
2852
- const toPrint = Object.entries(lastMiners).map(([seat, miner]) => ({
2853
- seat,
2854
- ...miner
2855
- }));
2856
- if (!toPrint.length) {
2857
- console.log("No active miners");
2858
- } else {
2859
- console.log(`Miners at block ${blockNumber}`);
2860
- printTable4(
2861
- toPrint.map((x) => ({
2862
- ...x,
2863
- bid: x.bid ? formatArgons(x.bid) : "-",
2864
- cohort: x.cohort,
2865
- isLastDay: x.isLastDay ? "Y" : "",
2866
- miner: x.miner
2867
- }))
2868
- );
2869
- }
2870
- if (!bids.nextCohort.length) {
2871
- console.log(
2872
- "-------------------------------------\nNo bids for next cohort"
2873
- );
2874
- } else {
2875
- bids.print();
2876
- }
2877
- }
2878
- const { unsubscribe } = await bids.watch(
2879
- accountset.namedAccounts,
2880
- void 0,
2881
- print
2882
- );
2883
- const maxMiners = api.consts.miningSlot.maxMiners.toNumber();
2884
- const seatIndices = new Array(maxMiners).fill(0).map((_, i) => i);
2885
- console.log("Watching miners...");
2886
- const unsub = await api.query.miningSlot.nextCohortId(
2887
- async (nextCohortId) => {
2888
- const entries = await api.query.miningSlot.activeMinersByIndex.entries();
2889
- const block = await api.query.system.number();
2890
- const seatsWithMiner = new Set(seatIndices);
2891
- for (const [rawIndex, maybeMiner] of entries) {
2892
- const index = rawIndex.args[0].toNumber();
2893
- if (!maybeMiner.isSome) {
2894
- continue;
2895
- }
2896
- seatsWithMiner.delete(index);
2897
- const miner = maybeMiner.unwrap();
2898
- const address = miner.accountId.toHuman();
2899
- const cohortId = miner.cohortId.toNumber();
2900
- lastMiners[index] = {
2901
- miner: accountset.namedAccounts.get(address) ?? address,
2902
- bid: miner.bid.toBigInt(),
2903
- cohort: cohortId,
2904
- isLastDay: nextCohortId.toNumber() - cohortId === 10
2905
- };
2906
- }
2907
- for (const index of seatsWithMiner) {
2908
- lastMiners[index] = {
2909
- miner: "none"
2910
- };
2911
- }
2912
- print(block.toNumber());
2913
- }
2914
- );
2915
- process.on("SIGINT", () => {
2916
- unsubscribe();
2917
- unsub();
2918
- process.exit(0);
2919
- });
2920
- });
2921
- program.command("bid").description("Submit mining bids within a range of parameters").option("--min-bid <amount>", "The minimum bid amount to use", parseFloat).option("--max-bid <amount>", "The maximum bid amount to use", parseFloat).option(
2922
- "--max-seats <n>",
2923
- "The maximum number of seats to bid on for the slot",
2924
- parseInt
2925
- ).option(
2926
- "--max-balance <argons>",
2927
- "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"
2928
- ).option("--bid-increment <argons>", "The bid increment", parseFloat, 0.01).option("--bid-delay <ticks>", "Delay between bids in ticks", parseInt, 0).option("--run-continuous", "Keep running and rebid every day").option(
2929
- "--proxy-for-address <address>",
2930
- "The seed account to proxy for (eg: 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty)"
2931
- ).action(
2932
- async ({
2933
- maxSeats,
2934
- runContinuous,
2935
- maxBid,
2936
- minBid,
2937
- maxBalance,
2938
- bidDelay,
2939
- bidIncrement,
2940
- proxyForAddress
2941
- }) => {
2942
- const accountset = await accountsetFromCli(program, proxyForAddress);
2943
- let cohortBidder;
2944
- const miningBids = new MiningBids(accountset.client, false);
2945
- const maxCohortSize = await miningBids.maxCohortSize();
2946
- const stopBidder = async (unsubscribe2) => {
2947
- if (cohortBidder) {
2948
- const stats = await cohortBidder.stop();
2949
- console.log("Final bidding result", {
2950
- cohortId: cohortBidder.cohortId,
2951
- ...stats
2952
- });
2953
- cohortBidder = void 0;
2954
- if (!runContinuous) {
2955
- unsubscribe2();
2956
- process.exit();
2957
- }
2958
- }
2959
- };
2960
- const { unsubscribe } = await miningBids.onCohortChange({
2961
- async onBiddingEnd(cohortId) {
2962
- if (cohortBidder?.cohortId === cohortId) {
2963
- await stopBidder(unsubscribe);
2964
- }
2965
- },
2966
- async onBiddingStart(cohortId) {
2967
- const seatsToWin = maxSeats ?? maxCohortSize;
2968
- const balance = await accountset.balance();
2969
- const feeWiggleRoom = BigInt(25e3);
2970
- const amountAvailable = balance - feeWiggleRoom;
2971
- let maxBidAmount = maxBid ? BigInt(maxBid * MICROGONS_PER_ARGON) : void 0;
2972
- let maxBalanceToUse = amountAvailable;
2973
- if (maxBalance !== void 0) {
2974
- if (maxBalance.endsWith("%")) {
2975
- let maxBalancePercent = parseInt(maxBalance);
2976
- let amountToBid = amountAvailable * BigInt(maxBalancePercent) / 100n;
2977
- if (amountToBid > balance) {
2978
- amountToBid = balance;
2979
- }
2980
- maxBalanceToUse = amountToBid;
2981
- } else {
2982
- maxBalanceToUse = BigInt(
2983
- Math.floor(parseFloat(maxBalance) * MICROGONS_PER_ARGON)
2984
- );
2985
- }
2986
- maxBidAmount ??= maxBalanceToUse / BigInt(seatsToWin);
2987
- }
2988
- if (maxBalanceToUse > amountAvailable) {
2989
- maxBalanceToUse = amountAvailable;
2990
- }
2991
- if (!maxBidAmount) {
2992
- console.error("No max bid amount set");
2993
- process.exit(1);
2994
- }
2995
- const subaccountRange = await accountset.getAvailableMinerAccounts(seatsToWin);
2996
- if (cohortBidder && cohortBidder?.cohortId !== cohortId) {
2997
- await stopBidder(unsubscribe);
2998
- }
2999
- cohortBidder = new CohortBidder(
3000
- accountset,
3001
- cohortId,
3002
- subaccountRange,
3003
- {
3004
- maxBid: maxBidAmount,
3005
- minBid: BigInt((minBid ?? 0) * MICROGONS_PER_ARGON),
3006
- bidIncrement: BigInt(
3007
- Math.floor(bidIncrement * MICROGONS_PER_ARGON)
3008
- ),
3009
- maxBudget: maxBalanceToUse,
3010
- bidDelay
3011
- }
3012
- );
3013
- await cohortBidder.start();
3014
- }
3015
- });
3016
- }
3017
- );
3018
- program.command("create-bid-proxy").description("Create a mining-bid proxy account for your main account").requiredOption(
3019
- "--outfile <path>",
3020
- "The file to use to store the proxy account json (eg: proxy.json)"
3021
- ).requiredOption(
3022
- "--fee-argons <argons>",
3023
- "How many argons should be sent to the proxy account for fees (proxies must pay fees)",
3024
- parseFloat
3025
- ).option(
3026
- "--proxy-passphrase <passphrase>",
3027
- "The passphrase for your proxy account"
3028
- ).action(async ({ outfile, proxyPassphrase, feeArgons }) => {
3029
- const { mainchainUrl } = globalOptions(program);
3030
- const client = await getClient(mainchainUrl);
3031
- const keyringPair = await saveKeyringPair({
3032
- filePath: outfile,
3033
- passphrase: proxyPassphrase
3034
- });
3035
- const address = keyringPair.address;
3036
- console.log(
3037
- `\u2705 Created proxy account at "${outfile}" with address ${address}`
3038
- );
3039
- const tx = client.tx.utility.batchAll([
3040
- client.tx.proxy.addProxy(address, "MiningBid", 0),
3041
- client.tx.balances.transferAllowDeath(
3042
- address,
3043
- BigInt(feeArgons * MICROGONS_PER_ARGON)
3044
- )
3045
- ]);
3046
- let keypair;
3047
- try {
3048
- const accountset = await accountsetFromCli(program);
3049
- keypair = accountset.txSubmitterPair;
3050
- } catch (e) {
3051
- const polkadotLink = `https://polkadot.js.org/apps/?rpc=${mainchainUrl}#/extrinsics/decode/${tx.toHex()}`;
3052
- console.log(`Complete the registration at this link:`, polkadotLink);
3053
- process.exit(0);
3054
- }
3055
- try {
3056
- await new TxSubmitter(client, tx, keypair).submit({
3057
- waitForBlock: true
3058
- });
3059
- console.log("Mining bid proxy added and funded.");
3060
- process.exit();
3061
- } catch (error) {
3062
- console.error("Error adding mining proxy", error);
3063
- process.exit(1);
3064
- }
3065
- });
3066
- return program;
3067
- }
3068
-
3069
- // src/clis/liquidityCli.ts
3070
- import { Command as Command4 } from "@commander-js/extra-typings";
3071
- function liquidityCli() {
3072
- const program = new Command4("liquidity-pools").description(
3073
- "Monitor or bond to liquidity pools"
3074
- );
3075
- program.command("list", { isDefault: true }).description("Show or watch the vault bid pool rewards").action(async () => {
3076
- const accountset = await accountsetFromCli(program);
3077
- const bidPool = new BidPool(
3078
- accountset.client,
3079
- accountset.txSubmitterPair
3080
- );
3081
- await bidPool.watch();
3082
- });
3083
- program.command("bond").description("Bond argons to a liquidity pool").requiredOption("-v, --vault-id <id>", "The vault id to use", parseInt).requiredOption(
3084
- "-a, --argons <amount>",
3085
- "The number of argons to set the vault to",
3086
- parseFloat
3087
- ).option(
3088
- "--tip <amount>",
3089
- "The tip to include with the transaction",
3090
- parseFloat
3091
- ).action(async ({ tip, argons, vaultId }) => {
3092
- const accountset = await accountsetFromCli(program);
3093
- const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;
3094
- const microgons = BigInt(argons * MICROGONS_PER_ARGON);
3095
- const bidPool = new BidPool(
3096
- accountset.client,
3097
- accountset.txSubmitterPair
3098
- );
3099
- await bidPool.bondArgons(vaultId, microgons, { tip: resolvedTip });
3100
- console.log("Bonded argons to liquidity pool bond");
3101
- process.exit();
3102
- });
3103
- program.command("wait-for-space").description(
3104
- "Add bonded argons to a liquidity pool when the market rate is favorable"
3105
- ).requiredOption(
3106
- "--max-argons <amount>",
3107
- "Max daily argons to use per slot",
3108
- parseFloat
3109
- ).option(
3110
- "--min-pct-sharing <percent>",
3111
- "The minimum profit sharing percent to allow",
3112
- parseInt,
3113
- 100
3114
- ).option(
3115
- "--tip <amount>",
3116
- "The tip to include with the transaction",
3117
- parseFloat
3118
- ).action(async ({ maxArgons, minPctSharing, tip }) => {
3119
- const maxAmountPerSlot = BigInt(maxArgons * MICROGONS_PER_ARGON);
3120
- const accountset = await accountsetFromCli(program);
3121
- const vaults = new VaultMonitor(
3122
- accountset,
3123
- {
3124
- liquidityPoolSpaceAvailable: 1000000n
3125
- },
3126
- { shouldLog: false }
3127
- );
3128
- const bidPool = new BidPool(
3129
- accountset.client,
3130
- accountset.txSubmitterPair
3131
- );
3132
- const resolvedTip = tip ? BigInt(tip * MICROGONS_PER_ARGON) : 0n;
3133
- console.log("Waiting for liquidity pool space...");
3134
- vaults.events.on(
3135
- "liquidity-pool-space-above",
3136
- async (vaultId, amount) => {
3137
- const vault = vaults.vaultsById[vaultId];
3138
- if (vault.terms.liquidityPoolProfitSharing.times(100).toNumber() < minPctSharing) {
3139
- console.info(
3140
- `Skipping vault ${vaultId} due to lower profit sharing than ${minPctSharing}%`
3141
- );
3142
- return;
3143
- }
3144
- let amountToAdd = amount;
3145
- if (amountToAdd > maxAmountPerSlot) {
3146
- amountToAdd = maxAmountPerSlot;
3147
- }
3148
- await bidPool.bondArgons(vaultId, amountToAdd, { tip: resolvedTip });
3149
- console.log("Bonding argons to vault liquidity pool", {
3150
- vaultId,
3151
- amount: formatArgons(amountToAdd)
3152
- });
3153
- }
3154
- );
3155
- await vaults.monitor();
3156
- });
3157
- return program;
3158
- }
3159
-
3160
- // src/clis/bitcoinCli.ts
3161
- import { Command as Command5 } from "@commander-js/extra-typings";
3162
- function bitcoinCli() {
3163
- const program = new Command5("bitcoin").description("Wait for bitcoin space");
3164
- program.command("watch").requiredOption(
3165
- "-a, --argons <argons>",
3166
- "Alert when bitcoin space exceeds this amount",
3167
- parseFloat
3168
- ).description("Watch for bitcoin space available").action(async ({ argons }) => {
3169
- const accountset = await accountsetFromCli(program);
3170
- const bot = new VaultMonitor(accountset, {
3171
- bitcoinSpaceAvailable: argons ? BigInt(argons * MICROGONS_PER_ARGON) : 1n
3172
- });
3173
- bot.events.on("bitcoin-space-above", async (vaultId, amount) => {
3174
- const vault = bot.vaultsById[vaultId];
3175
- const fee = vault.calculateBitcoinFee(amount);
3176
- const ratio = 100n * fee / amount;
3177
- console.log(
3178
- `Vault ${vaultId} has ${formatArgons(amount)} argons available for bitcoin. Fee ratio is ${ratio}%`
3179
- );
3180
- });
3181
- await bot.monitor();
3182
- });
3183
- program.command("wait-for-space").description("Lock bitcoin when available at a given rate").requiredOption(
3184
- "-a, --argons <amount>",
3185
- "Bitcoin argons needed. NOTE: your account must have enough to cover fees + tip after this amount.",
3186
- parseFloat
3187
- ).requiredOption(
3188
- "--bitcoin-xpub <xpub>",
3189
- "The xpub key to use for bitcoin locking"
3190
- ).option(
3191
- "--max-lock-fee <argons>",
3192
- "The max lock fee you're willing to pay",
3193
- parseFloat
3194
- ).option(
3195
- "--tip <amount>",
3196
- "The tip to include with the transaction",
3197
- parseFloat,
3198
- 0
3199
- ).action(async ({ argons, bitcoinXpub, maxLockFee, tip }) => {
3200
- const amountToLock = BigInt(argons * MICROGONS_PER_ARGON);
3201
- const accountset = await accountsetFromCli(program);
3202
- await BitcoinLocks.waitForSpace(accountset, {
3203
- argonAmount: amountToLock,
3204
- bitcoinXpub,
3205
- maxLockFee: maxLockFee !== void 0 ? BigInt(maxLockFee * MICROGONS_PER_ARGON) : void 0,
3206
- tip: BigInt(tip * MICROGONS_PER_ARGON)
3207
- }).then(({ vaultId, satoshis, txFee, btcFee }) => {
3208
- console.log(
3209
- `Locked ${satoshis} satoshis in vault ${vaultId}. Tx fee=${formatArgons(
3210
- txFee
3211
- )}, Lock fee=${formatArgons(btcFee)}.`
3212
- );
3213
- process.exit(0);
3214
- });
3215
- });
3216
- return program;
3217
- }
3218
-
3219
- // src/clis/keyringStore.ts
3220
- import { promises } from "node:fs";
3221
- import * as os from "node:os";
3222
- var { readFile, writeFile } = promises;
3223
- async function keyringFromFile(opts) {
3224
- if (!opts.filePath) {
3225
- throw new Error(
3226
- "No ACCOUNT account loaded (either ACCOUNT_SURI or ACCOUNT_JSON_PATH required)"
3227
- );
3228
- }
3229
- const path = opts.filePath.replace("~", os.homedir());
3230
- const json = JSON.parse(await readFile(path, "utf-8"));
3231
- let passphrase = opts.passphrase;
3232
- if (opts.passphraseFile) {
3233
- const passphrasePath = opts.passphraseFile.replace("~", os.homedir());
3234
- passphrase = await readFile(passphrasePath, "utf-8");
3235
- }
3236
- const mainAccount = new Keyring().createFromJson(json);
3237
- mainAccount.decodePkcs8(passphrase);
3238
- return mainAccount;
3239
- }
3240
- async function saveKeyringPair(opts) {
3241
- const { filePath, passphrase, cryptoType } = opts;
3242
- const keyring = createKeyringPair({ cryptoType });
3243
- if (filePath) {
3244
- const json = keyring.toJson(passphrase);
3245
- await writeFile(filePath, JSON.stringify(json, null, 2));
3246
- }
3247
- return keyring;
3248
- }
3249
-
3250
- // src/clis/index.ts
3251
- function globalOptions(program) {
3252
- return program.optsWithGlobals();
3253
- }
3254
- function buildCli() {
3255
- return new Command6("Argon CLI").option("-e, --env <path>", "The path to the account .env file to load").addOption(
3256
- new Option2("-u, --mainchain-url <url>", "The mainchain URL to connect to").default("wss://rpc.argon.network").env("MAINCHAIN_URL")
3257
- ).addOption(
3258
- new Option2(
3259
- "--account-file-path <jsonPath>",
3260
- "The path to your json seed file from polkadotjs"
3261
- ).env("ACCOUNT_JSON_PATH")
3262
- ).addOption(
3263
- new Option2(
3264
- "--account-suri <secretUri>",
3265
- "A secret uri (suri) to use for the account"
3266
- ).env("ACCOUNT_SURI")
3267
- ).addOption(
3268
- new Option2(
3269
- "--account-passphrase <password>",
3270
- "The password for your seed file"
3271
- ).env("ACCOUNT_PASSPHRASE")
3272
- ).addOption(
3273
- new Option2(
3274
- "--account-passphrase-file <path>",
3275
- "The path to a password for your seed file"
3276
- )
3277
- ).addOption(
3278
- new Option2(
3279
- "-s, --subaccounts <range>",
3280
- "Restrict this operation to a subset of the subaccounts (eg, 0-10)"
3281
- ).env("SUBACCOUNT_RANGE").argParser(parseSubaccountRange)
3282
- ).addCommand(accountCli()).addCommand(vaultCli()).addCommand(miningCli()).addCommand(liquidityCli()).addCommand(bitcoinCli());
3283
- }
3284
- async function accountsetFromCli(program, proxyForAddress) {
3285
- const opts = program.parent?.optsWithGlobals();
3286
- let keypair;
3287
- if (opts.accountSuri) {
3288
- keypair = keyringFromSuri(opts.accountSuri);
3289
- }
3290
- if (opts.accountFilePath) {
3291
- keypair = await keyringFromFile({
3292
- filePath: opts.accountFilePath,
3293
- passphrase: opts.accountPassphrase,
3294
- passphraseFile: opts.accountPassphraseFile
3295
- });
3296
- }
3297
- if (!keypair) {
3298
- throw new Error(
3299
- "No ACCOUNT account loaded (either ACCOUNT_SURI or ACCOUNT_JSON_PATH required)"
3300
- );
3301
- }
3302
- const client = getClient(opts.mainchainUrl);
3303
- if (proxyForAddress) {
3304
- return new Accountset({
3305
- client,
3306
- isProxy: true,
3307
- seedAddress: proxyForAddress,
3308
- txSubmitter: keypair
3309
- });
3310
- } else {
3311
- return new Accountset({
3312
- seedAccount: keypair,
3313
- client
3314
- });
3315
- }
3316
- }
3317
- function addGlobalArgs(program) {
3318
- for (const command of program.commands) {
3319
- command.configureHelp({
3320
- showGlobalOptions: true
3321
- });
3322
- for (const nested of command.commands) {
3323
- nested.configureHelp({
3324
- showGlobalOptions: true
3325
- });
3326
- }
3327
- }
3328
- }
3329
- function applyEnv(program) {
3330
- program.parseOptions(process.argv);
3331
- const { env: env3 } = program.optsWithGlobals();
3332
- if (env3) {
3333
- const envPath = Path.resolve(process.cwd(), env3);
3334
- const res = configDotenv({ path: envPath });
3335
- if (res.parsed?.ACCOUNT_JSON_PATH) {
3336
- process.env.ACCOUNT_JSON_PATH = Path.relative(
3337
- envPath,
3338
- process.env.ACCOUNT_JSON_PATH
3339
- );
3340
- }
3341
- }
3342
- return env3;
3343
- }
2
+ accountCli,
3
+ accountsetFromCli,
4
+ addGlobalArgs,
5
+ applyEnv,
6
+ bitcoinCli,
7
+ buildCli,
8
+ globalOptions,
9
+ keyringFromFile,
10
+ liquidityCli,
11
+ miningCli,
12
+ saveKeyringPair,
13
+ vaultCli
14
+ } from "../chunk-BQR6FEVP.js";
15
+ import "../chunk-RXCQYVE7.js";
3344
16
  export {
3345
17
  accountCli,
3346
18
  accountsetFromCli,