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