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