@argonprotocol/mainchain 1.1.0-rc.8 → 1.2.0

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