@argonprotocol/mainchain 1.1.0-rc.8 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -1,2580 +1,81 @@
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);
30
-
31
- // src/index.ts
32
- var index_exports = {};
33
- __export(index_exports, {
34
- AccountMiners: () => AccountMiners,
35
- AccountRegistry: () => AccountRegistry,
36
- Accountset: () => Accountset,
37
- BidPool: () => BidPool,
38
- BitcoinLocks: () => BitcoinLocks,
39
- BlockWatch: () => BlockWatch,
40
- CohortBidder: () => CohortBidder,
41
- ExtrinsicError: () => ExtrinsicError2,
42
- JsonExt: () => JsonExt,
43
- Keyring: () => import_api.Keyring,
44
- MICROGONS_PER_ARGON: () => MICROGONS_PER_ARGON,
45
- MiningBids: () => MiningBids,
46
- MiningRotations: () => MiningRotations,
47
- TxSubmitter: () => TxSubmitter,
48
- Vault: () => Vault,
49
- VaultMonitor: () => VaultMonitor,
50
- WageProtector: () => WageProtector,
51
- checkForExtrinsicSuccess: () => checkForExtrinsicSuccess,
52
- convertFixedU128ToBigNumber: () => convertFixedU128ToBigNumber,
53
- convertPermillToBigNumber: () => convertPermillToBigNumber,
54
- createKeyringPair: () => createKeyringPair,
55
- decodeAddress: () => import_util_crypto.decodeAddress,
56
- dispatchErrorToExtrinsicError: () => dispatchErrorToExtrinsicError,
57
- dispatchErrorToString: () => dispatchErrorToString,
58
- eventDataToJson: () => eventDataToJson,
59
- filterUndefined: () => filterUndefined,
60
- formatArgons: () => formatArgons,
61
- formatPercent: () => formatPercent,
62
- getAuthorFromHeader: () => getAuthorFromHeader,
63
- getClient: () => getClient,
64
- getTickFromHeader: () => getTickFromHeader,
65
- gettersToObject: () => gettersToObject,
66
- keyringFromSuri: () => keyringFromSuri,
67
- mnemonicGenerate: () => import_util_crypto.mnemonicGenerate,
68
- waitForLoad: () => waitForLoad
69
- });
70
- module.exports = __toCommonJS(index_exports);
71
-
72
- // src/interfaces/augment-api-consts.ts
73
- var import_consts = require("@polkadot/api-base/types/consts");
74
-
75
- // src/interfaces/augment-api-errors.ts
76
- var import_errors = require("@polkadot/api-base/types/errors");
77
-
78
- // src/interfaces/augment-api-events.ts
79
- var import_events = require("@polkadot/api-base/types/events");
80
-
81
- // src/interfaces/augment-api-query.ts
82
- var import_storage = require("@polkadot/api-base/types/storage");
83
-
84
- // src/interfaces/augment-api-tx.ts
85
- var import_submittable = require("@polkadot/api-base/types/submittable");
86
-
87
- // src/interfaces/augment-api-rpc.ts
88
- var import_jsonrpc = require("@polkadot/rpc-core/types/jsonrpc");
89
-
90
- // src/interfaces/augment-api-runtime.ts
91
- var import_calls = require("@polkadot/api-base/types/calls");
92
-
93
- // src/interfaces/augment-types.ts
94
- var import_registry = require("@polkadot/types/types/registry");
95
-
96
- // src/index.ts
97
- var import_api = require("@polkadot/api");
98
- var import_util_crypto = require("@polkadot/util-crypto");
99
- __reExport(index_exports, require("@polkadot/types-codec/types"), module.exports);
100
-
101
- // src/WageProtector.ts
102
- var WageProtector = class _WageProtector {
103
- constructor(latestCpi) {
104
- this.latestCpi = latestCpi;
105
- }
106
- /**
107
- * Converts the base wage to the current wage using the latest CPI snapshot
108
- *
109
- * @param baseWage The base wage to convert
110
- * @returns The protected wage
111
- */
112
- getProtectedWage(baseWage) {
113
- return baseWage * this.latestCpi.argonUsdTargetPrice / this.latestCpi.argonUsdPrice;
114
- }
115
- /**
116
- * Subscribes to the current CPI and calls the callback function whenever the CPI changes
117
- * @param client The ArgonClient to use
118
- * @param callback The callback function to call when the CPI changes
119
- * @returns An object with an unsubscribe function that can be called to stop the subscription
120
- */
121
- static async subscribe(client, callback) {
122
- const unsubscribe = await client.query.priceIndex.current(async (cpi) => {
123
- if (cpi.isNone) {
124
- return;
125
- }
126
- const finalizedBlock = await client.rpc.chain.getFinalizedHead();
127
- callback(
128
- new _WageProtector({
129
- argonUsdTargetPrice: cpi.value.argonUsdTargetPrice.toBigInt(),
130
- argonUsdPrice: cpi.value.argonUsdPrice.toBigInt(),
131
- finalizedBlock: finalizedBlock.toU8a(),
132
- tick: cpi.value.tick.toBigInt()
133
- })
134
- );
135
- });
136
- return { unsubscribe };
137
- }
138
- /**
139
- * Creates a new WageProtector instance by subscribing to the current CPI and waiting for the first value
140
- * @param client The ArgonClient to use
141
- */
142
- static async create(client) {
143
- return new Promise(async (resolve, reject) => {
144
- try {
145
- const { unsubscribe } = await _WageProtector.subscribe(client, (x) => {
146
- resolve(x);
147
- unsubscribe();
148
- });
149
- } catch (e) {
150
- reject(e);
151
- }
152
- });
153
- }
154
- };
155
-
156
- // src/TxSubmitter.ts
157
- function logExtrinsicResult(result) {
158
- if (process.env.DEBUG) {
159
- const json = result.status.toJSON();
160
- const status = Object.keys(json)[0];
161
- console.debug('Transaction update: "%s"', status, json[status]);
162
- }
163
- }
164
- var TxSubmitter = class {
165
- constructor(client, tx, pair) {
166
- this.client = client;
167
- this.tx = tx;
168
- this.pair = pair;
169
- }
170
- async feeEstimate(tip) {
171
- const { partialFee } = await this.tx.paymentInfo(this.pair, { tip });
172
- return partialFee.toBigInt();
173
- }
174
- async canAfford(options = {}) {
175
- const { tip, unavailableBalance } = options;
176
- const account = await this.client.query.system.account(this.pair.address);
177
- let availableBalance = account.data.free.toBigInt();
178
- if (unavailableBalance) {
179
- availableBalance -= unavailableBalance;
180
- }
181
- const existentialDeposit = options.includeExistentialDeposit ? this.client.consts.balances.existentialDeposit.toBigInt() : 0n;
182
- const fees = await this.feeEstimate(tip);
183
- const totalCharge = fees + (tip ?? 0n);
184
- const canAfford = availableBalance > totalCharge + existentialDeposit;
185
- return { canAfford, availableBalance, txFee: fees };
186
- }
187
- async submit(options = {}) {
188
- const { logResults } = options;
189
- const result = new TxResult(this.client, logResults);
190
- let toHuman = this.tx.toHuman().method;
191
- let txString = [];
192
- let api = formatCall(toHuman);
193
- const args = [];
194
- if (api === "proxy.proxy") {
195
- toHuman = toHuman.args.call;
196
- txString.push("Proxy");
197
- api = formatCall(toHuman);
198
- }
199
- if (api.startsWith("utility.batch")) {
200
- const calls = toHuman.args.calls.map(formatCall).join(", ");
201
- txString.push(`Batch[${calls}]`);
202
- } else {
203
- txString.push(api);
204
- args.push(toHuman.args);
205
- }
206
- args.unshift(txString.join("->"));
207
- if (options.useLatestNonce && !options.nonce) {
208
- options.nonce = await this.client.rpc.system.accountNextIndex(
209
- this.pair.address
210
- );
211
- }
212
- console.log("Submitting transaction:", ...args);
213
- await this.tx.signAndSend(this.pair, options, result.onResult.bind(result));
214
- if (options.waitForBlock) {
215
- await result.inBlockPromise;
216
- }
217
- return result;
218
- }
219
- };
220
- function formatCall(call) {
221
- return `${call.section}.${call.method}`;
222
- }
223
- var TxResult = class {
224
- constructor(client, shouldLog = false) {
225
- this.client = client;
226
- this.shouldLog = shouldLog;
227
- this.inBlockPromise = new Promise((resolve, reject) => {
228
- this.inBlockResolve = resolve;
229
- this.inBlockReject = reject;
230
- });
231
- this.finalizedPromise = new Promise((resolve, reject) => {
232
- this.finalizedResolve = resolve;
233
- this.finalizedReject = reject;
234
- });
235
- this.inBlockPromise.catch(() => {
236
- });
237
- this.finalizedPromise.catch(() => {
238
- });
239
- }
240
- inBlockPromise;
241
- finalizedPromise;
242
- status;
243
- events = [];
244
- /**
245
- * The index of the batch that was interrupted, if any.
246
- */
247
- batchInterruptedIndex;
248
- includedInBlock;
249
- /**
250
- * The final fee paid for the transaction, including the fee tip.
251
- */
252
- finalFee;
253
- /**
254
- * The fee tip paid for the transaction.
255
- */
256
- finalFeeTip;
257
- inBlockResolve;
258
- inBlockReject;
259
- finalizedResolve;
260
- finalizedReject;
261
- onResult(result) {
262
- this.status = result.status;
263
- if (this.shouldLog) {
264
- logExtrinsicResult(result);
265
- }
266
- const { events, status, dispatchError, isFinalized } = result;
267
- if (status.isInBlock) {
268
- this.includedInBlock = status.asInBlock.toU8a();
269
- let encounteredError = dispatchError;
270
- let batchErrorIndex;
271
- for (const event of events) {
272
- this.events.push(event.event);
273
- if (this.client.events.utility.BatchInterrupted.is(event.event)) {
274
- batchErrorIndex = event.event.data[0].toNumber();
275
- this.batchInterruptedIndex = batchErrorIndex;
276
- encounteredError = event.event.data[1];
277
- }
278
- if (this.client.events.transactionPayment.TransactionFeePaid.is(
279
- event.event
280
- )) {
281
- const [_who, actualFee, tip] = event.event.data;
282
- this.finalFee = actualFee.toBigInt();
283
- this.finalFeeTip = tip.toBigInt();
284
- }
285
- }
286
- if (encounteredError) {
287
- const error = dispatchErrorToExtrinsicError(
288
- this.client,
289
- encounteredError,
290
- batchErrorIndex
291
- );
292
- this.reject(error);
293
- } else {
294
- this.inBlockResolve(status.asInBlock.toU8a());
295
- }
296
- }
297
- if (isFinalized) {
298
- this.finalizedResolve(status.asFinalized);
299
- }
300
- }
301
- reject(error) {
302
- this.inBlockReject(error);
303
- this.finalizedReject(error);
304
- }
305
- };
306
-
307
- // src/utils.ts
308
- var BN = __toESM(require("bignumber.js"), 1);
309
- var { ROUND_FLOOR } = BN;
310
- var MICROGONS_PER_ARGON = 1e6;
311
- function formatArgons(x) {
312
- if (x === void 0 || x === null) return "na";
313
- const isNegative = x < 0;
314
- let format = (0, BN.default)(x.toString()).abs().div(MICROGONS_PER_ARGON).toFormat(2, ROUND_FLOOR);
315
- if (format.endsWith(".00")) {
316
- format = format.slice(0, -3);
317
- }
318
- return `${isNegative ? "-" : ""}\u20B3${format}`;
319
- }
320
- function formatPercent(x) {
321
- if (!x) return "na";
322
- return `${x.times(100).decimalPlaces(3)}%`;
323
- }
324
- function filterUndefined(obj) {
325
- return Object.fromEntries(
326
- Object.entries(obj).filter(
327
- ([_, value]) => value !== void 0 && value !== null
328
- )
329
- );
330
- }
331
- async function gettersToObject(obj) {
332
- if (obj === null || obj === void 0 || typeof obj !== "object") return obj;
333
- const keys = [];
334
- for (const key in obj) {
335
- keys.push(key);
336
- }
337
- if (Symbol.iterator in obj) {
338
- const iterableToArray = [];
339
- for (const item of obj) {
340
- iterableToArray.push(await gettersToObject(item));
341
- }
342
- return iterableToArray;
343
- }
344
- const result = {};
345
- for (const key of keys) {
346
- const descriptor = Object.getOwnPropertyDescriptor(obj, key);
347
- if (descriptor && typeof descriptor.value === "function") {
348
- continue;
349
- }
350
- const value = descriptor && descriptor.get ? descriptor.get.call(obj) : obj[key];
351
- if (typeof value === "function") continue;
352
- result[key] = await gettersToObject(value);
353
- }
354
- return result;
355
- }
356
- function convertFixedU128ToBigNumber(fixedU128) {
357
- const decimalFactor = new BN.default(10).pow(new BN.default(18));
358
- const rawValue = new BN.default(fixedU128.toString());
359
- return rawValue.div(decimalFactor);
360
- }
361
- function convertPermillToBigNumber(permill) {
362
- const decimalFactor = new BN.default(1e6);
363
- const rawValue = new BN.default(permill.toString());
364
- return rawValue.div(decimalFactor);
365
- }
366
- function eventDataToJson(event) {
367
- const obj = {};
368
- event.data.forEach((data, index) => {
369
- const name = event.data.names?.[index];
370
- obj[name ?? `${index}`] = data.toJSON();
371
- });
372
- return obj;
373
- }
374
- function dispatchErrorToString(client, error) {
375
- let message = error.toString();
376
- if (error.isModule) {
377
- const decoded = client.registry.findMetaError(error.asModule);
378
- const { docs, name, section } = decoded;
379
- message = `${section}.${name}: ${docs.join(" ")}`;
380
- }
381
- return message;
382
- }
383
- var ExtrinsicError2 = class extends Error {
384
- constructor(errorCode, details, batchInterruptedIndex) {
385
- super(errorCode);
386
- this.errorCode = errorCode;
387
- this.details = details;
388
- this.batchInterruptedIndex = batchInterruptedIndex;
389
- }
390
- toString() {
391
- if (this.batchInterruptedIndex !== void 0) {
392
- return `${this.errorCode} ${this.details ?? ""} (Batch interrupted at index ${this.batchInterruptedIndex})`;
393
- }
394
- return `${this.errorCode} ${this.details ?? ""}`;
395
- }
396
- };
397
- function dispatchErrorToExtrinsicError(client, error, batchInterruptedIndex) {
398
- if (error.isModule) {
399
- const decoded = client.registry.findMetaError(error.asModule);
400
- const { docs, name, section } = decoded;
401
- return new ExtrinsicError2(
402
- `${section}.${name}`,
403
- docs.join(" "),
404
- batchInterruptedIndex
405
- );
406
- }
407
- return new ExtrinsicError2(error.toString(), void 0, batchInterruptedIndex);
408
- }
409
- function checkForExtrinsicSuccess(events, client) {
410
- return new Promise((resolve, reject) => {
411
- for (const { event } of events) {
412
- if (client.events.system.ExtrinsicSuccess.is(event)) {
413
- resolve();
414
- } else if (client.events.system.ExtrinsicFailed.is(event)) {
415
- const [dispatchError] = event.data;
416
- let errorInfo = dispatchError.toString();
417
- if (dispatchError.isModule) {
418
- const decoded = client.registry.findMetaError(dispatchError.asModule);
419
- errorInfo = `${decoded.section}.${decoded.name}`;
420
- }
421
- reject(
422
- new Error(
423
- `${event.section}.${event.method}:: ExtrinsicFailed:: ${errorInfo}`
424
- )
425
- );
426
- }
427
- }
428
- });
429
- }
430
- var JsonExt = class {
431
- static stringify(obj, space) {
432
- return JSON.stringify(
433
- obj,
434
- (_, v) => typeof v === "bigint" ? `${v}n` : v,
435
- space
436
- );
437
- }
438
- static parse(str) {
439
- return JSON.parse(str, (_, v) => {
440
- if (typeof v === "string" && v.endsWith("n")) {
441
- return BigInt(v.slice(0, -1));
442
- }
443
- return v;
444
- });
445
- }
446
- };
447
-
448
- // src/AccountRegistry.ts
449
- var AccountRegistry = class _AccountRegistry {
450
- namedAccounts = /* @__PURE__ */ new Map();
451
- me = "me";
452
- constructor(name) {
453
- if (name) {
454
- this.me = name;
455
- }
456
- }
457
- getName(address) {
458
- return this.namedAccounts.get(address);
459
- }
460
- register(address, name) {
461
- this.namedAccounts.set(address, name);
462
- }
463
- static factory = (name) => new _AccountRegistry(name);
464
- };
465
-
466
- // src/Accountset.ts
467
- var process2 = __toESM(require("process"), 1);
468
-
469
- // src/BlockWatch.ts
470
- var import_nanoevents = require("nanoevents");
471
- function getTickFromHeader(client, header) {
472
- for (const x of header.digest.logs) {
473
- if (x.isPreRuntime) {
474
- const [engineId, data] = x.asPreRuntime;
475
- if (engineId.toString() === "aura") {
476
- return client.createType("u64", data).toNumber();
477
- }
478
- }
479
- }
480
- return void 0;
481
- }
482
- function getAuthorFromHeader(client, header) {
483
- for (const x of header.digest.logs) {
484
- if (x.isPreRuntime) {
485
- const [engineId, data] = x.asPreRuntime;
486
- if (engineId.toString() === "pow_") {
487
- return client.createType("AccountId32", data).toHuman();
488
- }
489
- }
490
- }
491
- return void 0;
492
- }
493
- var BlockWatch = class {
494
- constructor(mainchain, options = {}) {
495
- this.mainchain = mainchain;
496
- this.options = options;
497
- this.options.shouldLog ??= true;
498
- this.options.finalizedBlocks ??= false;
499
- }
500
- events = (0, import_nanoevents.createNanoEvents)();
501
- obligationsById = {};
502
- obligationIdByUtxoId = {};
503
- unsubscribe;
504
- stop() {
505
- if (this.unsubscribe) {
506
- this.unsubscribe();
507
- this.unsubscribe = void 0;
508
- }
509
- }
510
- async start() {
511
- await this.watchBlocks();
512
- }
513
- async watchBlocks() {
514
- const client = await this.mainchain;
515
- const onBlock = async (header) => {
516
- try {
517
- await this.processBlock(header);
518
- } catch (e) {
519
- console.error("Error processing block", e);
520
- }
521
- };
522
- if (this.options.finalizedBlocks) {
523
- this.unsubscribe = await client.rpc.chain.subscribeFinalizedHeads(onBlock);
524
- } else {
525
- this.unsubscribe = await client.rpc.chain.subscribeNewHeads(onBlock);
526
- }
527
- }
528
- async processBlock(header) {
529
- const client = await this.mainchain;
530
- if (this.options.shouldLog) {
531
- console.log(`-------------------------------------
532
- BLOCK #${header.number}, ${header.hash.toHuman()}`);
533
- }
534
- const blockHash = header.hash;
535
- const api = await client.at(blockHash);
536
- const isBlockVote = await api.query.blockSeal.isBlockFromVoteSeal();
537
- if (!isBlockVote) {
538
- console.warn("> Compute reactivated!");
539
- }
540
- const events = await api.query.system.events();
541
- const reloadVaults = /* @__PURE__ */ new Set();
542
- let block = void 0;
543
- for (const { event, phase } of events) {
544
- const data = eventDataToJson(event);
545
- if (data.vaultId) {
546
- const vaultId = data.vaultId;
547
- reloadVaults.add(vaultId);
548
- }
549
- let logEvent = false;
550
- if (event.section === "liquidityPools") {
551
- if (client.events.liquidityPools.BidPoolDistributed.is(event)) {
552
- const { bidPoolBurned, bidPoolDistributed } = event.data;
553
- data.burned = formatArgons(bidPoolBurned.toBigInt());
554
- data.distributed = formatArgons(bidPoolDistributed.toBigInt());
555
- logEvent = true;
556
- } else if (client.events.liquidityPools.NextBidPoolCapitalLocked.is(event)) {
557
- const { totalActivatedCapital } = event.data;
558
- data.totalActivatedCapital = formatArgons(
559
- totalActivatedCapital.toBigInt()
560
- );
561
- logEvent = true;
562
- }
563
- } else if (event.section === "bitcoinLocks") {
564
- if (client.events.bitcoinLocks.BitcoinLockCreated.is(event)) {
565
- const { lockPrice, utxoId, accountId, vaultId } = event.data;
566
- this.obligationsById[utxoId.toNumber()] = {
567
- vaultId: vaultId.toNumber(),
568
- amount: lockPrice.toBigInt()
569
- };
570
- data.lockPrice = formatArgons(lockPrice.toBigInt());
571
- data.accountId = accountId.toHuman();
572
- reloadVaults.add(vaultId.toNumber());
573
- }
574
- logEvent = true;
575
- } else if (event.section === "mint") {
576
- logEvent = true;
577
- if (client.events.mint.MiningMint.is(event)) {
578
- const { amount } = event.data;
579
- data.amount = formatArgons(amount.toBigInt());
580
- }
581
- } else if (event.section === "miningSlot") {
582
- logEvent = true;
583
- if (client.events.miningSlot.SlotBidderAdded.is(event)) {
584
- data.amount = formatArgons(event.data.bidAmount.toBigInt());
585
- this.events.emit("mining-bid", header, {
586
- amount: event.data.bidAmount.toBigInt(),
587
- accountId: event.data.accountId.toString()
588
- });
589
- } else if (client.events.miningSlot.SlotBidderDropped.is(event)) {
590
- this.events.emit("mining-bid-ousted", header, {
591
- accountId: event.data.accountId.toString(),
592
- preservedArgonotHold: event.data.preservedArgonotHold.toPrimitive()
593
- });
594
- }
595
- } else if (event.section === "bitcoinUtxos") {
596
- logEvent = true;
597
- if (client.events.bitcoinUtxos.UtxoVerified.is(event)) {
598
- const { utxoId } = event.data;
599
- const details = await this.getBitcoinLockDetails(
600
- utxoId.toNumber(),
601
- blockHash
602
- );
603
- this.events.emit("bitcoin-verified", header, {
604
- utxoId: utxoId.toNumber(),
605
- vaultId: details.vaultId,
606
- amount: details.amount
607
- });
608
- data.amount = formatArgons(details.amount);
609
- reloadVaults.add(details.vaultId);
610
- }
611
- } else if (event.section === "system") {
612
- if (client.events.system.ExtrinsicFailed.is(event)) {
613
- const { dispatchError } = event.data;
614
- if (dispatchError.isModule) {
615
- const decoded = api.registry.findMetaError(dispatchError.asModule);
616
- const { name, section } = decoded;
617
- block ??= await client.rpc.chain.getBlock(header.hash);
618
- const extrinsicIndex = phase.asApplyExtrinsic.toNumber();
619
- const ext = block.block.extrinsics[extrinsicIndex];
620
- if (this.options.shouldLog) {
621
- console.log(
622
- `> [Failed Tx] ${section}.${name} -> ${ext.method.section}.${ext.method.method} (nonce=${ext.nonce})`,
623
- ext.toHuman()?.method?.args
624
- );
625
- }
626
- } else {
627
- if (this.options.shouldLog) {
628
- console.log(`x [Failed Tx] ${dispatchError.toJSON()}`);
629
- }
630
- }
631
- }
632
- }
633
- if (this.options.shouldLog && logEvent) {
634
- console.log(`> ${event.section}.${event.method}`, data);
635
- }
636
- this.events.emit("event", header, event);
637
- }
638
- if (reloadVaults.size)
639
- this.events.emit("vaults-updated", header, reloadVaults);
640
- const tick = getTickFromHeader(client, header);
641
- const author = getAuthorFromHeader(client, header);
642
- this.events.emit(
643
- "block",
644
- header,
645
- { tick, author },
646
- events.map((x) => x.event)
647
- );
648
- }
649
- async getBitcoinLockDetails(utxoId, blockHash) {
650
- const client = await this.mainchain;
651
- const api = await client.at(blockHash);
652
- let obligationId = this.obligationIdByUtxoId[utxoId];
653
- if (!obligationId) {
654
- const lock = await api.query.bitcoinLocks.locksByUtxoId(utxoId);
655
- obligationId = lock.value.obligationId.toNumber();
656
- this.obligationIdByUtxoId[utxoId] = obligationId;
657
- this.obligationsById[obligationId] = {
658
- vaultId: lock.value.vaultId.toNumber(),
659
- amount: lock.value.lockPrice.toBigInt()
660
- };
661
- }
662
- return this.obligationsById[obligationId];
663
- }
664
- };
665
-
666
- // src/MiningRotations.ts
667
- var MiningRotations = class {
668
- miningConfig;
669
- genesisTick;
670
- async getForTick(client, tick) {
671
- this.miningConfig ??= await client.query.miningSlot.miningConfig().then((x) => ({
672
- ticksBetweenSlots: x.ticksBetweenSlots.toNumber(),
673
- slotBiddingStartAfterTicks: x.slotBiddingStartAfterTicks.toNumber()
674
- }));
675
- this.genesisTick ??= await client.query.ticks.genesisTick().then((x) => x.toNumber());
676
- const ticksBetweenSlots = this.miningConfig.ticksBetweenSlots;
677
- const slot1StartTick = this.genesisTick + this.miningConfig.slotBiddingStartAfterTicks + ticksBetweenSlots;
678
- if (tick < slot1StartTick) return 0;
679
- const ticksSinceSlot1 = tick - slot1StartTick;
680
- return Math.floor(ticksSinceSlot1 / ticksBetweenSlots) + 1;
681
- }
682
- async getForHeader(client, header) {
683
- if (header.number.toNumber() === 0) return 0;
684
- const tick = getTickFromHeader(client, header);
685
- if (tick === void 0) return void 0;
686
- return this.getForTick(client, tick);
687
- }
688
- };
689
-
690
- // src/AccountMiners.ts
691
- var import_nanoevents2 = require("nanoevents");
692
- var AccountMiners = class _AccountMiners {
693
- constructor(accountset, registeredMiners, options = { shouldLog: false }) {
694
- this.accountset = accountset;
695
- this.options = options;
696
- this.miningRotations = new MiningRotations();
697
- for (const seat of registeredMiners) {
698
- this.trackedAccountsByAddress[seat.address] = {
699
- cohortId: seat.cohortId,
700
- subaccountIndex: seat.subaccountIndex
701
- };
702
- }
703
- }
704
- events = (0, import_nanoevents2.createNanoEvents)();
705
- miningRotations;
706
- trackedAccountsByAddress = {};
707
- async watch() {
708
- const blockWatch = new BlockWatch(this.accountset.client, {
709
- shouldLog: this.options.shouldLog
710
- });
711
- blockWatch.events.on("block", this.onBlock.bind(this));
712
- await blockWatch.start();
713
- return blockWatch;
714
- }
715
- async onBlock(header, digests, events) {
716
- const { author, tick } = digests;
717
- if (author) {
718
- const voteAuthor = this.trackedAccountsByAddress[author];
719
- if (voteAuthor && this.options.shouldLog) {
720
- console.log(
721
- "> Our vote author",
722
- this.accountset.accountRegistry.getName(author)
723
- );
724
- }
725
- } else {
726
- console.warn("> No vote author found");
727
- }
728
- const client = await this.accountset.client;
729
- const rotation = await this.miningRotations.getForTick(client, tick);
730
- let newMiners;
731
- const dataByCohort = { rotation };
732
- for (const event of events) {
733
- if (client.events.miningSlot.NewMiners.is(event)) {
734
- newMiners = {
735
- cohortId: event.data.cohortId.toNumber(),
736
- addresses: event.data.newMiners.map((x) => x.accountId.toHuman())
737
- };
738
- }
739
- if (client.events.blockRewards.RewardCreated.is(event)) {
740
- const { rewards } = event.data;
741
- for (const reward of rewards) {
742
- const { argons, ownership } = reward;
743
- const entry = this.trackedAccountsByAddress[author];
744
- if (entry) {
745
- dataByCohort[entry.cohortId] ??= {
746
- argonsMinted: 0n,
747
- argonsMined: 0n,
748
- argonotsMined: 0n
749
- };
750
- dataByCohort[entry.cohortId].argonotsMined += ownership.toBigInt();
751
- dataByCohort[entry.cohortId].argonsMined += argons.toBigInt();
752
- this.events.emit("mined", header, {
753
- author,
754
- argons: argons.toBigInt(),
755
- argonots: ownership.toBigInt(),
756
- cohortId: entry.cohortId,
757
- rotation
758
- });
759
- }
760
- }
761
- }
762
- if (client.events.mint.MiningMint.is(event)) {
763
- const { perMiner } = event.data;
764
- const amountPerMiner = perMiner.toBigInt();
765
- if (amountPerMiner > 0n) {
766
- for (const [address, info] of Object.entries(
767
- this.trackedAccountsByAddress
768
- )) {
769
- const { cohortId } = info;
770
- dataByCohort[cohortId] ??= {
771
- argonsMinted: 0n,
772
- argonsMined: 0n,
773
- argonotsMined: 0n
774
- };
775
- dataByCohort[cohortId].argonsMinted += amountPerMiner;
776
- this.events.emit("minted", header, {
777
- accountId: address,
778
- argons: amountPerMiner,
779
- cohortId,
780
- rotation
781
- });
782
- }
783
- }
784
- }
785
- }
786
- if (newMiners) {
787
- this.newCohortMiners(newMiners.cohortId, newMiners.addresses);
788
- }
789
- return dataByCohort;
790
- }
791
- newCohortMiners(cohortId, addresses) {
792
- for (const [address, info] of Object.entries(
793
- this.trackedAccountsByAddress
794
- )) {
795
- if (info.cohortId === cohortId - 10) {
796
- delete this.trackedAccountsByAddress[address];
797
- }
798
- }
799
- for (const address of addresses) {
800
- const entry = this.accountset.subAccountsByAddress[address];
801
- if (entry) {
802
- this.trackedAccountsByAddress[address] = {
803
- cohortId,
804
- subaccountIndex: entry.index
805
- };
806
- }
807
- }
808
- }
809
- static async loadAt(accountset, options = {}) {
810
- const seats = await accountset.miningSeats(options.blockHash);
811
- const registered = seats.filter((x) => x.cohortId !== void 0);
812
- return new _AccountMiners(accountset, registered, {
813
- shouldLog: options.shouldLog ?? false
814
- });
815
- }
816
- };
817
-
818
- // src/Accountset.ts
819
- var Accountset = class {
820
- txSubmitterPair;
821
- isProxy = false;
822
- seedAddress;
823
- subAccountsByAddress = {};
824
- accountRegistry;
825
- client;
826
- get addresses() {
827
- return [this.seedAddress, ...Object.keys(this.subAccountsByAddress)];
828
- }
829
- get namedAccounts() {
830
- return this.accountRegistry.namedAccounts;
831
- }
832
- sessionKeyMnemonic;
833
- constructor(options) {
834
- if ("seedAccount" in options) {
835
- this.txSubmitterPair = options.seedAccount;
836
- this.seedAddress = options.seedAccount.address;
837
- this.isProxy = false;
838
- } else {
839
- this.isProxy = options.isProxy;
840
- this.txSubmitterPair = options.txSubmitter;
841
- this.seedAddress = options.seedAddress;
842
- }
843
- this.sessionKeyMnemonic = options.sessionKeyMnemonic;
844
- this.accountRegistry = options.accountRegistry ?? AccountRegistry.factory(options.name);
845
- this.client = options.client;
846
- const defaultRange = options.subaccountRange ?? getDefaultSubaccountRange();
847
- this.accountRegistry.register(
848
- this.seedAddress,
849
- `${this.accountRegistry.me}//seed`
850
- );
851
- for (const i of defaultRange) {
852
- const pair = this.txSubmitterPair.derive(`//${i}`);
853
- this.subAccountsByAddress[pair.address] = { pair, index: i };
854
- this.accountRegistry.register(
855
- pair.address,
856
- `${this.accountRegistry.me}//${i}`
857
- );
858
- }
859
- }
860
- async submitterBalance(blockHash) {
861
- const client = await this.client;
862
- const api = blockHash ? await client.at(blockHash) : client;
863
- const accountData = await api.query.system.account(
864
- this.txSubmitterPair.address
865
- );
866
- return accountData.data.free.toBigInt();
867
- }
868
- async balance(blockHash) {
869
- const client = await this.client;
870
- const api = blockHash ? await client.at(blockHash) : client;
871
- const accountData = await api.query.system.account(this.seedAddress);
872
- return accountData.data.free.toBigInt();
873
- }
874
- async totalArgonsAt(blockHash) {
875
- const client = await this.client;
876
- const api = blockHash ? await client.at(blockHash) : client;
877
- const addresses = this.addresses;
878
- const results = await api.query.system.account.multi(addresses);
879
- return results.map((account, i) => {
880
- const address = addresses[i];
881
- return {
882
- address,
883
- amount: account.data.free.toBigInt(),
884
- index: this.subAccountsByAddress[address]?.index ?? Number.NaN
885
- };
886
- });
887
- }
888
- async totalArgonotsAt(blockHash) {
889
- const client = await this.client;
890
- const api = blockHash ? await client.at(blockHash) : client;
891
- const addresses = this.addresses;
892
- const results = await api.query.ownership.account.multi(addresses);
893
- return results.map((account, i) => {
894
- const address = addresses[i];
895
- return {
896
- address,
897
- amount: account.free.toBigInt(),
898
- index: this.subAccountsByAddress[address]?.index ?? Number.NaN
899
- };
900
- });
901
- }
902
- async getAvailableMinerAccounts(maxSeats) {
903
- const miningSeats = await this.miningSeats();
904
- const subaccountRange = [];
905
- for (const seat of miningSeats) {
906
- if (seat.hasWinningBid) {
907
- continue;
908
- }
909
- if (seat.isLastDay || seat.seat === void 0) {
910
- subaccountRange.push({
911
- index: seat.subaccountIndex,
912
- isRebid: seat.seat !== void 0,
913
- address: seat.address
914
- });
915
- if (subaccountRange.length >= maxSeats) {
916
- break;
917
- }
918
- }
919
- }
920
- return subaccountRange;
921
- }
922
- async loadRegisteredMiners(api) {
923
- const addresses = Object.keys(this.subAccountsByAddress);
924
- const rawIndices = await api.query.miningSlot.accountIndexLookup.multi(addresses);
925
- const addressToMiningIndex = {};
926
- for (let i = 0; i < addresses.length; i++) {
927
- const address = addresses[i];
928
- if (rawIndices[i].isNone) continue;
929
- addressToMiningIndex[address] = rawIndices[i].value.toNumber();
930
- }
931
- const indices = Object.values(addressToMiningIndex).filter(
932
- (x) => x !== void 0
933
- );
934
- const indexRegistrations = indices.length ? await api.query.miningSlot.activeMinersByIndex.multi(indices) : [];
935
- const registrationBySeatIndex = {};
936
- for (let i = 0; i < indices.length; i++) {
937
- const seatIndex = indices[i];
938
- const registration = indexRegistrations[i];
939
- if (registration?.isSome) {
940
- registrationBySeatIndex[seatIndex] = {
941
- cohortId: registration.value.cohortId.toNumber(),
942
- bidAmount: registration.value.bid.toBigInt()
943
- };
944
- }
945
- }
946
- const nextCohortId = await api.query.miningSlot.nextCohortId();
947
- return addresses.map((address) => {
948
- const seat = addressToMiningIndex[address];
949
- const registration = registrationBySeatIndex[seat];
950
- let isLastDay = false;
951
- if (registration?.cohortId) {
952
- isLastDay = nextCohortId.toNumber() - registration?.cohortId === 10;
953
- }
954
- return {
955
- ...registration,
956
- address,
957
- seat,
958
- isLastDay,
959
- subaccountIndex: this.subAccountsByAddress[address]?.index ?? Number.NaN
960
- };
961
- });
962
- }
963
- async miningSeats(blockHash) {
964
- const client = await this.client;
965
- const api = blockHash ? await client.at(blockHash) : client;
966
- const miners = await this.loadRegisteredMiners(api);
967
- const nextCohort = await api.query.miningSlot.nextSlotCohort();
968
- return miners.map((miner) => {
969
- const bid = nextCohort.find((x) => x.accountId.toHuman() === miner.address);
970
- return {
971
- ...miner,
972
- hasWinningBid: !!bid,
973
- bidAmount: bid?.bid.toBigInt() ?? miner.bidAmount
974
- };
975
- });
976
- }
977
- async bids(blockHash) {
978
- const client = await this.client;
979
- const api = blockHash ? await client.at(blockHash) : client;
980
- const addresses = Object.keys(this.subAccountsByAddress);
981
- const nextCohort = await api.query.miningSlot.nextSlotCohort();
982
- const registrationsByAddress = Object.fromEntries(
983
- nextCohort.map((x, i) => [x.accountId.toHuman(), { ...x, index: i }])
984
- );
985
- return addresses.map((address) => {
986
- const entry = registrationsByAddress[address];
987
- return {
988
- address,
989
- bidPlace: entry?.index,
990
- bidAmount: entry?.bid?.toBigInt(),
991
- index: this.subAccountsByAddress[address]?.index ?? Number.NaN
992
- };
993
- });
994
- }
995
- async consolidate(subaccounts) {
996
- const client = await this.client;
997
- const accounts = this.getAccountsInRange(subaccounts);
998
- const results = [];
999
- await Promise.allSettled(
1000
- accounts.map(({ pair, index }) => {
1001
- if (!pair) {
1002
- results.push({
1003
- index,
1004
- failedError: new Error(`No keypair for //${index}`)
1005
- });
1006
- return Promise.resolve();
1007
- }
1008
- return new Promise((resolve) => {
1009
- client.tx.utility.batchAll([
1010
- client.tx.balances.transferAll(this.seedAddress, true),
1011
- client.tx.ownership.transferAll(this.seedAddress, true)
1012
- ]).signAndSend(pair, (cb) => {
1013
- logExtrinsicResult(cb);
1014
- if (cb.dispatchError) {
1015
- const error = dispatchErrorToString(client, cb.dispatchError);
1016
- results.push({
1017
- index,
1018
- failedError: new Error(
1019
- `Error consolidating //${index}: ${error}`
1020
- )
1021
- });
1022
- resolve();
1023
- }
1024
- if (cb.isInBlock) {
1025
- results.push({ index, inBlock: cb.status.asInBlock.toHex() });
1026
- resolve();
1027
- }
1028
- }).catch((e) => {
1029
- results.push({ index, failedError: e });
1030
- resolve();
1031
- });
1032
- });
1033
- })
1034
- );
1035
- return results;
1036
- }
1037
- status(opts) {
1038
- const { argons, argonots, accountSubset, bids, seats } = opts;
1039
- const accounts = [
1040
- {
1041
- index: "main",
1042
- address: this.seedAddress,
1043
- argons: formatArgons(
1044
- argons.find((x) => x.address === this.seedAddress)?.amount ?? 0n
1045
- ),
1046
- argonots: formatArgons(
1047
- argonots.find((x) => x.address === this.seedAddress)?.amount ?? 0n
1048
- )
1049
- }
1050
- ];
1051
- for (const [address, { index }] of Object.entries(
1052
- this.subAccountsByAddress
1053
- )) {
1054
- const argonAmount = argons.find((x) => x.address === address)?.amount ?? 0n;
1055
- const argonotAmount = argonots.find((x) => x.address === address)?.amount ?? 0n;
1056
- const bid = bids.find((x) => x.address === address);
1057
- const seat = seats.find((x) => x.address === address)?.seat;
1058
- const entry = {
1059
- index: ` //${index}`,
1060
- address,
1061
- argons: formatArgons(argonAmount),
1062
- argonots: formatArgons(argonotAmount),
1063
- seat,
1064
- bidPlace: bid?.bidPlace,
1065
- bidAmount: bid?.bidAmount ?? 0n
1066
- };
1067
- if (accountSubset) {
1068
- entry.isWorkingOn = accountSubset.some((x) => x.address === address);
1069
- }
1070
- accounts.push(entry);
1071
- }
1072
- return accounts;
1073
- }
1074
- async registerKeys(url) {
1075
- const client = await getClient(url.replace("ws:", "http:"));
1076
- const keys = this.keys();
1077
- for (const [name, key] of Object.entries(keys)) {
1078
- console.log("Registering key", name, key.publicKey);
1079
- const result = await client.rpc.author.insertKey(
1080
- name,
1081
- key.privateKey,
1082
- key.publicKey
1083
- );
1084
- const saved = await client.rpc.author.hasKey(key.publicKey, name);
1085
- if (!saved) {
1086
- console.error("Failed to register key", name, key.publicKey);
1087
- throw new Error(`Failed to register ${name} key ${key.publicKey}`);
1088
- }
1089
- console.log(`Registered ${name} key`, result.toHuman());
1090
- }
1091
- await client.disconnect();
1092
- }
1093
- keys(keysVersion) {
1094
- let version = keysVersion ?? 0;
1095
- if (process2.env.KEYS_VERSION) {
1096
- version = parseInt(process2.env.KEYS_VERSION) ?? 0;
1097
- }
1098
- const seedMnemonic = this.sessionKeyMnemonic ?? process2.env.KEYS_MNEMONIC;
1099
- if (!seedMnemonic) {
1100
- throw new Error(
1101
- "KEYS_MNEMONIC environment variable not set. Cannot derive keys."
1102
- );
1103
- }
1104
- const blockSealKey = `${seedMnemonic}//block-seal//${version}`;
1105
- const granKey = `${seedMnemonic}//grandpa//${version}`;
1106
- const blockSealAccount = new import_api.Keyring().createFromUri(blockSealKey, {
1107
- type: "ed25519"
1108
- });
1109
- const grandpaAccount = new import_api.Keyring().createFromUri(granKey, {
1110
- type: "ed25519"
1111
- });
1112
- return {
1113
- seal: {
1114
- privateKey: blockSealKey,
1115
- publicKey: `0x${Buffer.from(blockSealAccount.publicKey).toString("hex")}`,
1116
- rawPublicKey: blockSealAccount.publicKey
1117
- },
1118
- gran: {
1119
- privateKey: granKey,
1120
- publicKey: `0x${Buffer.from(grandpaAccount.publicKey).toString("hex")}`,
1121
- rawPublicKey: grandpaAccount.publicKey
1122
- }
1123
- };
1124
- }
1125
- async tx(tx) {
1126
- const client = await this.client;
1127
- return new TxSubmitter(client, tx, this.txSubmitterPair);
1128
- }
1129
- /**
1130
- * Create but don't submit a mining bid transaction.
1131
- * @param options
1132
- */
1133
- async createMiningBidTx(options) {
1134
- const client = await this.client;
1135
- const { bidAmount, subaccounts, sendRewardsToSeed } = options;
1136
- const batch = client.tx.utility.batch(
1137
- subaccounts.map((x) => {
1138
- const keys = this.keys();
1139
- const rewards = sendRewardsToSeed ? { Account: this.seedAddress } : { Owner: null };
1140
- return client.tx.miningSlot.bid(
1141
- bidAmount,
1142
- rewards,
1143
- {
1144
- grandpa: keys.gran.rawPublicKey,
1145
- blockSealAuthority: keys.seal.rawPublicKey
1146
- },
1147
- x.address
1148
- );
1149
- })
1150
- );
1151
- let tx = batch;
1152
- if (this.isProxy) {
1153
- tx = client.tx.proxy.proxy(this.seedAddress, "MiningBid", batch);
1154
- }
1155
- return new TxSubmitter(client, tx, this.txSubmitterPair);
1156
- }
1157
- /**
1158
- * Create a mining bid. This will create a bid for each account in the given range from the seed account as funding.
1159
- */
1160
- async createMiningBids(options) {
1161
- const accounts = this.getAccountsInRange(options.subaccountRange);
1162
- const client = await this.client;
1163
- const submitter = await this.createMiningBidTx({
1164
- ...options,
1165
- subaccounts: accounts
1166
- });
1167
- const { tip = 0n } = options;
1168
- const txFee = await submitter.feeEstimate(tip);
1169
- let minBalance = options.bidAmount * BigInt(accounts.length);
1170
- let totalFees = tip + 1n + txFee;
1171
- const seedBalance = await client.query.system.account(this.seedAddress).then((x) => x.data.free.toBigInt());
1172
- if (!this.isProxy) {
1173
- minBalance += totalFees;
1174
- }
1175
- if (seedBalance < minBalance) {
1176
- throw new Error(
1177
- `Insufficient balance to create mining bids. Seed account has ${formatArgons(
1178
- seedBalance
1179
- )} but needs ${formatArgons(minBalance)}`
1180
- );
1181
- }
1182
- if (this.isProxy) {
1183
- const { canAfford, availableBalance } = await submitter.canAfford({
1184
- tip
1185
- });
1186
- if (!canAfford) {
1187
- throw new Error(
1188
- `Insufficient balance to pay proxy fees. Proxy account has ${formatArgons(
1189
- availableBalance
1190
- )} but needs ${formatArgons(totalFees)}`
1191
- );
1192
- }
1193
- }
1194
- console.log("Creating bids", {
1195
- perSeatBid: options.bidAmount,
1196
- subaccounts: options.subaccountRange,
1197
- txFee
1198
- });
1199
- const txResult = await submitter.submit({
1200
- tip,
1201
- useLatestNonce: true
1202
- });
1203
- const bidError = await txResult.inBlockPromise.then(() => void 0).catch((x) => x);
1204
- return {
1205
- finalFee: txResult.finalFee,
1206
- bidError,
1207
- blockHash: txResult.includedInBlock,
1208
- successfulBids: txResult.batchInterruptedIndex !== void 0 ? txResult.batchInterruptedIndex : accounts.length
1209
- };
1210
- }
1211
- getAccountsInRange(range) {
1212
- const entries = new Set(range ?? getDefaultSubaccountRange());
1213
- return Object.entries(this.subAccountsByAddress).filter(([_, account]) => {
1214
- return entries.has(account.index);
1215
- }).map(([address, { pair, index }]) => ({ pair, index, address }));
1216
- }
1217
- async watchBlocks(shouldLog = false) {
1218
- const accountMiners = await AccountMiners.loadAt(this, { shouldLog });
1219
- await accountMiners.watch();
1220
- return accountMiners;
1221
- }
1222
- };
1223
- function getDefaultSubaccountRange() {
1224
- try {
1225
- return parseSubaccountRange(process2.env.SUBACCOUNT_RANGE ?? "0-9");
1226
- } catch {
1227
- console.error(
1228
- "Failed to parse SUBACCOUNT_RANGE environment variable. Defaulting to 0-9. Please check the format of the SUBACCOUNT_RANGE variable."
1229
- );
1230
- return Array.from({ length: 10 }, (_, i) => i);
1231
- }
1232
- }
1233
- function parseSubaccountRange(range) {
1234
- if (!range) {
1235
- return void 0;
1236
- }
1237
- const indices = [];
1238
- for (const entry of range.split(",")) {
1239
- if (entry.includes("-")) {
1240
- const [start, end] = entry.split("-").map((x) => parseInt(x, 10));
1241
- for (let i = start; i <= end; i++) {
1242
- indices.push(i);
1243
- }
1244
- continue;
1245
- }
1246
- const record = parseInt(entry.trim(), 10);
1247
- if (Number.isNaN(record) || !Number.isInteger(record)) {
1248
- throw new Error(`Invalid range entry: ${entry}`);
1249
- }
1250
- if (Number.isInteger(record)) {
1251
- indices.push(record);
1252
- }
1253
- }
1254
- return indices;
1255
- }
1256
-
1257
- // src/MiningBids.ts
1258
- var import_console_table_printer = require("console-table-printer");
1259
- var MiningBids = class {
1260
- constructor(client, shouldLog = true) {
1261
- this.client = client;
1262
- this.shouldLog = shouldLog;
1263
- }
1264
- nextCohort = [];
1265
- async maxCohortSize() {
1266
- const client = await this.client;
1267
- return client.consts.miningSlot.maxCohortSize.toNumber();
1268
- }
1269
- async onCohortChange(options) {
1270
- const { onBiddingStart, onBiddingEnd } = options;
1271
- const client = await this.client;
1272
- let openCohortId = 0;
1273
- const unsubscribe = await client.queryMulti(
1274
- [
1275
- client.query.miningSlot.isNextSlotBiddingOpen,
1276
- client.query.miningSlot.nextCohortId
1277
- ],
1278
- async ([isBiddingOpen, rawNextCohortId]) => {
1279
- const nextCohortId = rawNextCohortId.toNumber();
1280
- if (isBiddingOpen.isTrue) {
1281
- if (openCohortId !== 0) {
1282
- await onBiddingEnd?.(openCohortId);
1283
- }
1284
- openCohortId = nextCohortId;
1285
- await onBiddingStart?.(nextCohortId);
1286
- } else {
1287
- await onBiddingEnd?.(nextCohortId);
1288
- openCohortId = 0;
1289
- }
1290
- }
1291
- );
1292
- return { unsubscribe };
1293
- }
1294
- async watch(accountNames, blockHash, printFn) {
1295
- const client = await this.client;
1296
- const api = blockHash ? await client.at(blockHash) : client;
1297
- const unsubscribe = await api.query.miningSlot.nextSlotCohort(
1298
- async (next) => {
1299
- this.nextCohort = await Promise.all(
1300
- next.map((x) => this.toBid(accountNames, x))
1301
- );
1302
- if (!this.shouldLog) return;
1303
- console.clear();
1304
- const block = await client.query.system.number();
1305
- if (!printFn) {
1306
- console.log("At block", block.toNumber());
1307
- this.print();
1308
- } else {
1309
- printFn(block.toNumber());
1310
- }
1311
- }
1312
- );
1313
- return { unsubscribe };
1314
- }
1315
- async loadAt(accountNames, blockHash) {
1316
- const client = await this.client;
1317
- const api = blockHash ? await client.at(blockHash) : client;
1318
- const nextCohort = await api.query.miningSlot.nextSlotCohort();
1319
- this.nextCohort = await Promise.all(
1320
- nextCohort.map((x) => this.toBid(accountNames, x))
1321
- );
1322
- }
1323
- async toBid(accountNames, bid) {
1324
- return {
1325
- accountId: bid.accountId.toString(),
1326
- isOurs: accountNames.get(bid.accountId.toString()) ?? "n",
1327
- bidAmount: bid.bid.toBigInt()
1328
- };
1329
- }
1330
- print() {
1331
- const bids = this.nextCohort.map((bid) => {
1332
- return {
1333
- account: bid.accountId,
1334
- isOurs: bid.isOurs,
1335
- bidAmount: formatArgons(bid.bidAmount)
1336
- };
1337
- });
1338
- if (bids.length) {
1339
- console.log("\n\nMining Bids:");
1340
- (0, import_console_table_printer.printTable)(bids);
1341
- }
1342
- }
1343
- };
1344
-
1345
- // src/Vault.ts
1346
- var BN2 = __toESM(require("bignumber.js"), 1);
1347
- var { ROUND_FLOOR: ROUND_FLOOR2 } = BN2;
1348
- var Vault = class {
1349
- securitization;
1350
- securitizationRatio;
1351
- bitcoinLocked;
1352
- bitcoinPending;
1353
- terms;
1354
- operatorAccountId;
1355
- isClosed;
1356
- vaultId;
1357
- pendingTerms;
1358
- pendingTermsChangeTick;
1359
- openedDate;
1360
- constructor(id, vault, tickDuration) {
1361
- this.securitization = vault.securitization.toBigInt();
1362
- this.securitizationRatio = convertFixedU128ToBigNumber(
1363
- vault.securitizationRatio.toBigInt()
1364
- );
1365
- this.bitcoinLocked = vault.bitcoinLocked.toBigInt();
1366
- this.bitcoinPending = vault.bitcoinPending.toBigInt();
1367
- this.terms = {
1368
- bitcoinAnnualPercentRate: convertFixedU128ToBigNumber(
1369
- vault.terms.bitcoinAnnualPercentRate.toBigInt()
1370
- ),
1371
- bitcoinBaseFee: vault.terms.bitcoinBaseFee.toBigInt(),
1372
- liquidityPoolProfitSharing: convertPermillToBigNumber(
1373
- vault.terms.liquidityPoolProfitSharing.toBigInt()
1374
- )
1375
- };
1376
- this.operatorAccountId = vault.operatorAccountId.toString();
1377
- this.isClosed = vault.isClosed.valueOf();
1378
- this.vaultId = id;
1379
- if (vault.pendingTerms.isSome) {
1380
- const [tickApply, terms] = vault.pendingTerms.value;
1381
- this.pendingTermsChangeTick = tickApply.toNumber();
1382
- this.pendingTerms = {
1383
- bitcoinAnnualPercentRate: convertFixedU128ToBigNumber(
1384
- terms.bitcoinAnnualPercentRate.toBigInt()
1385
- ),
1386
- bitcoinBaseFee: terms.bitcoinBaseFee.toBigInt(),
1387
- liquidityPoolProfitSharing: convertPermillToBigNumber(
1388
- vault.terms.liquidityPoolProfitSharing.toBigInt()
1389
- )
1390
- };
1391
- }
1392
- this.openedDate = vault.openedTick ? new Date(vault.openedTick.toNumber() * tickDuration) : /* @__PURE__ */ new Date();
1393
- }
1394
- availableBitcoinSpace() {
1395
- const recoverySecuritization = this.recoverySecuritization();
1396
- return this.securitization - recoverySecuritization - this.bitcoinLocked;
1397
- }
1398
- recoverySecuritization() {
1399
- const reserved = new BN2.default(1).div(this.securitizationRatio);
1400
- return this.securitization - BigInt(
1401
- reserved.multipliedBy(this.securitization.toString()).toFixed(0, ROUND_FLOOR2)
1402
- );
1403
- }
1404
- minimumSecuritization() {
1405
- return BigInt(
1406
- this.securitizationRatio.multipliedBy(this.bitcoinLocked.toString()).decimalPlaces(0, BN2.default.ROUND_CEIL).toString()
1407
- );
1408
- }
1409
- activatedSecuritization() {
1410
- const activated = this.bitcoinLocked - this.bitcoinPending;
1411
- let maxRatio = this.securitizationRatio;
1412
- if (this.securitizationRatio.toNumber() > 2) {
1413
- maxRatio = (0, BN2.default)(2);
1414
- }
1415
- return BigInt(
1416
- maxRatio.multipliedBy(activated.toString()).toFixed(0, ROUND_FLOOR2)
1417
- );
1418
- }
1419
- /**
1420
- * Returns the amount of Argons available to match per liquidity pool
1421
- */
1422
- activatedSecuritizationPerSlot() {
1423
- const activated = this.activatedSecuritization();
1424
- return activated / 10n;
1425
- }
1426
- calculateBitcoinFee(amount) {
1427
- const fee = this.terms.bitcoinAnnualPercentRate.multipliedBy(Number(amount)).integerValue(BN2.default.ROUND_CEIL);
1428
- return BigInt(fee.toString()) + this.terms.bitcoinBaseFee;
1429
- }
1430
- };
1431
-
1432
- // src/VaultMonitor.ts
1433
- var import_console_table_printer2 = require("console-table-printer");
1434
- var import_nanoevents3 = require("nanoevents");
1435
- var VaultMonitor = class {
1436
- constructor(accountset, alerts = {}, options = {}) {
1437
- this.accountset = accountset;
1438
- this.alerts = alerts;
1439
- this.options = options;
1440
- this.mainchain = accountset.client;
1441
- if (options.vaultOnlyWatchMode !== void 0) {
1442
- this.vaultOnlyWatchMode = options.vaultOnlyWatchMode;
1443
- }
1444
- if (options.shouldLog !== void 0) {
1445
- this.shouldLog = options.shouldLog;
1446
- }
1447
- this.miningBids = new MiningBids(this.mainchain, this.shouldLog);
1448
- this.blockWatch = new BlockWatch(this.mainchain, {
1449
- shouldLog: this.shouldLog
1450
- });
1451
- this.blockWatch.events.on(
1452
- "vaults-updated",
1453
- (header, vaultIds) => this.onVaultsUpdated(header.hash, vaultIds)
1454
- );
1455
- this.blockWatch.events.on("mining-bid", async (header, _bid) => {
1456
- await this.miningBids.loadAt(this.accountset.namedAccounts, header.hash);
1457
- this.printBids(header.hash);
1458
- });
1459
- this.blockWatch.events.on("mining-bid-ousted", async (header) => {
1460
- await this.miningBids.loadAt(this.accountset.namedAccounts, header.hash);
1461
- this.printBids(header.hash);
1462
- });
1463
- }
1464
- events = (0, import_nanoevents3.createNanoEvents)();
1465
- vaultsById = {};
1466
- blockWatch;
1467
- mainchain;
1468
- activatedCapitalByVault = {};
1469
- lastPrintedBids;
1470
- miningBids;
1471
- tickDuration = 0;
1472
- vaultOnlyWatchMode = false;
1473
- shouldLog = true;
1474
- stop() {
1475
- this.blockWatch.stop();
1476
- }
1477
- async monitor(justPrint = false) {
1478
- const client = await this.mainchain;
1479
- this.tickDuration = (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();
1480
- const blockHeader = await client.rpc.chain.getHeader();
1481
- const blockHash = blockHeader.hash.toU8a();
1482
- console.log(
1483
- `${justPrint ? "Run" : "Started"} at block ${blockHeader.number} - ${blockHeader.hash.toHuman()}`
1484
- );
1485
- await this.miningBids.loadAt(this.accountset.namedAccounts, blockHash);
1486
- const vaults = await client.query.vaults.vaultsById.entries();
1487
- for (const [storageKey, rawVault] of vaults) {
1488
- const vaultId = storageKey.args[0].toNumber();
1489
- this.updateVault(vaultId, rawVault);
1490
- }
1491
- await client.query.liquidityPools.nextLiquidityPoolCapital((x) => {
1492
- this.activatedCapitalByVault = {};
1493
- for (const entry of x) {
1494
- const vaultId = entry.vaultId.toNumber();
1495
- this.activatedCapitalByVault[vaultId] = entry.activatedCapital.toBigInt();
1496
- }
1497
- for (const [vaultId, vault] of Object.entries(this.vaultsById)) {
1498
- const id = Number(vaultId);
1499
- this.activatedCapitalByVault[id] ??= 0n;
1500
- this.checkMiningBondAlerts(id, vault);
1501
- }
1502
- });
1503
- this.printVaults();
1504
- if (!this.vaultOnlyWatchMode && this.shouldLog) {
1505
- this.miningBids.print();
1506
- }
1507
- if (!justPrint) await this.blockWatch.start();
1508
- }
1509
- printVaults() {
1510
- if (!this.shouldLog) return;
1511
- const vaults = [];
1512
- for (const [vaultId, vault] of Object.entries(this.vaultsById)) {
1513
- vaults.push({
1514
- id: vaultId,
1515
- btcSpace: `${formatArgons(vault.availableBitcoinSpace())} (${formatArgons(vault.bitcoinPending)} pending)`,
1516
- btcDeal: `${formatArgons(vault.terms.bitcoinBaseFee)} + ${formatPercent(vault.terms.bitcoinAnnualPercentRate)}`,
1517
- securitization: `${formatArgons(vault.securitization)} at ${vault.securitizationRatio.toFormat(1)}x`,
1518
- securActivated: `${formatArgons(vault.activatedSecuritizationPerSlot())}/slot`,
1519
- liquidPoolDeal: `${formatPercent(vault.terms.liquidityPoolProfitSharing)} sharing`,
1520
- operator: `${this.accountset.namedAccounts.has(vault.operatorAccountId) ? ` (${this.accountset.namedAccounts.get(vault.operatorAccountId)})` : vault.operatorAccountId}`,
1521
- state: vault.isClosed ? "closed" : vault.openedDate < /* @__PURE__ */ new Date() ? "open" : "pending"
1522
- });
1523
- }
1524
- if (vaults.length) {
1525
- if (this.vaultOnlyWatchMode) {
1526
- console.clear();
1527
- }
1528
- console.log("\n\nVaults:");
1529
- (0, import_console_table_printer2.printTable)(vaults);
1530
- }
1531
- }
1532
- async recheckAfterActive(vaultId) {
1533
- const activationDate = this.vaultsById[vaultId].openedDate;
1534
- if (this.shouldLog) {
1535
- console.log(`Waiting for vault ${vaultId} to activate ${activationDate}`);
1536
- }
1537
- await new Promise(
1538
- (resolve) => setTimeout(resolve, activationDate.getTime() - Date.now())
1539
- );
1540
- const client = await this.mainchain;
1541
- let isReady = false;
1542
- while (!isReady) {
1543
- const rawVault = await client.query.vaults.vaultsById(vaultId);
1544
- if (!rawVault.isSome) return;
1545
- const vault = new Vault(vaultId, rawVault.value, this.tickDuration);
1546
- this.vaultsById[vaultId] = vault;
1547
- if (vault.isClosed) return;
1548
- if (vault.openedDate < /* @__PURE__ */ new Date()) {
1549
- isReady = true;
1550
- break;
1551
- }
1552
- await new Promise((resolve) => setTimeout(resolve, 100));
1553
- }
1554
- this.checkAlerts(vaultId, this.vaultsById[vaultId]);
1555
- }
1556
- async onVaultsUpdated(blockHash, vaultIds) {
1557
- await this.reloadVaultsAt([...vaultIds], blockHash).catch((err) => {
1558
- console.error(
1559
- `Failed to reload vault ${[...vaultIds]} at block ${blockHash}:`,
1560
- err
1561
- );
1562
- });
1563
- this.printVaults();
1564
- }
1565
- async reloadVaultsAt(vaultIds, blockHash) {
1566
- const client = await this.mainchain;
1567
- const api = await client.at(blockHash);
1568
- const vaults = await api.query.vaults.vaultsById.multi(vaultIds);
1569
- for (let i = 0; i < vaultIds.length; i += 1) {
1570
- this.updateVault(vaultIds[i], vaults[i]);
1571
- }
1572
- }
1573
- updateVault(vaultId, rawVault) {
1574
- if (rawVault.isNone) return;
1575
- const vault = new Vault(vaultId, rawVault.value, this.tickDuration);
1576
- this.vaultsById[vaultId] = vault;
1577
- if (vault.openedDate > /* @__PURE__ */ new Date()) {
1578
- void this.recheckAfterActive(vaultId);
1579
- } else {
1580
- this.checkAlerts(vaultId, vault);
1581
- }
1582
- }
1583
- checkAlerts(vaultId, vault) {
1584
- if (this.alerts.bitcoinSpaceAvailable !== void 0) {
1585
- const availableBitcoinSpace = vault.availableBitcoinSpace();
1586
- if (availableBitcoinSpace >= this.alerts.bitcoinSpaceAvailable) {
1587
- console.warn(
1588
- `Vault ${vaultId} has available bitcoins above ${formatArgons(this.alerts.bitcoinSpaceAvailable)}`
1589
- );
1590
- this.events.emit("bitcoin-space-above", vaultId, availableBitcoinSpace);
1591
- }
1592
- }
1593
- }
1594
- checkMiningBondAlerts(vaultId, vault) {
1595
- if (this.alerts.liquidityPoolSpaceAvailable === void 0) return;
1596
- const activatedSecuritization = vault.activatedSecuritizationPerSlot();
1597
- const capitalization = this.activatedCapitalByVault[vaultId] ?? 0n;
1598
- const available = activatedSecuritization - capitalization;
1599
- if (available >= this.alerts.liquidityPoolSpaceAvailable) {
1600
- this.events.emit("liquidity-pool-space-above", vaultId, available);
1601
- }
1602
- }
1603
- printBids(blockHash) {
1604
- if (!this.shouldLog) return;
1605
- if (this.lastPrintedBids === blockHash) return;
1606
- this.miningBids.print();
1607
- this.lastPrintedBids = blockHash;
1608
- }
1609
- };
1610
-
1611
- // src/CohortBidderHistory.ts
1612
- var CohortBidderHistory = class _CohortBidderHistory {
1613
- constructor(cohortId, subaccounts) {
1614
- this.cohortId = cohortId;
1615
- this.subaccounts = subaccounts;
1616
- this.maxSeatsInPlay = this.subaccounts.length;
1617
- this.subaccounts.forEach((x) => {
1618
- this.myAddresses.add(x.address);
1619
- });
1620
- }
1621
- bidHistory = [];
1622
- stats = {
1623
- // number of seats won
1624
- seatsWon: 0,
1625
- // sum of argons bid in successful bids
1626
- totalArgonsBid: 0n,
1627
- // total number of bids placed (includes 1 per seat)
1628
- bidsAttempted: 0,
1629
- // fees including the tip
1630
- fees: 0n,
1631
- // Max bid per seat
1632
- maxBidPerSeat: 0n,
1633
- // The cost in argonots of each seat
1634
- argonotsPerSeat: 0n,
1635
- // The argonot price in USD for cost basis
1636
- argonotUsdPrice: 0,
1637
- // The cohort expected argons per block
1638
- cohortArgonsPerBlock: 0n,
1639
- // The last block that bids are synced to
1640
- lastBlockNumber: 0
1641
- };
1642
- lastBids = [];
1643
- myAddresses = /* @__PURE__ */ new Set();
1644
- maxSeatsInPlay = 0;
1645
- async init(client) {
1646
- if (!this.stats.argonotsPerSeat) {
1647
- const startingStats = await _CohortBidderHistory.getStartingData(client);
1648
- Object.assign(this.stats, startingStats);
1649
- }
1650
- }
1651
- maybeReducingSeats(maxSeats, reason, historyEntry) {
1652
- if (this.maxSeatsInPlay > maxSeats) {
1653
- historyEntry.maxSeatsReductionReason = reason;
1654
- }
1655
- this.maxSeatsInPlay = maxSeats;
1656
- historyEntry.maxSeatsInPlay = maxSeats;
1657
- }
1658
- trackChange(next, blockNumber, tick, isLastEntry = false) {
1659
- let winningBids = 0;
1660
- let totalArgonsBid = 0n;
1661
- const nextEntrants = [];
1662
- for (const x of next) {
1663
- const bid = x.bid.toBigInt();
1664
- const address = x.accountId.toHuman();
1665
- nextEntrants.push({ address, bid });
1666
- if (this.myAddresses.has(address)) {
1667
- winningBids++;
1668
- totalArgonsBid += bid;
1669
- }
1670
- }
1671
- this.stats.seatsWon = winningBids;
1672
- this.stats.totalArgonsBid = totalArgonsBid;
1673
- this.stats.lastBlockNumber = Math.max(
1674
- blockNumber,
1675
- this.stats.lastBlockNumber
1676
- );
1677
- const historyEntry = {
1678
- cohortId: this.cohortId,
1679
- blockNumber,
1680
- tick,
1681
- bidChanges: [],
1682
- winningSeats: winningBids,
1683
- maxSeatsInPlay: this.maxSeatsInPlay
1684
- };
1685
- const hasDiffs = JsonExt.stringify(nextEntrants) !== JsonExt.stringify(this.lastBids);
1686
- if (!isLastEntry || hasDiffs) {
1687
- this.bidHistory.unshift(historyEntry);
1688
- }
1689
- if (hasDiffs) {
1690
- nextEntrants.forEach(({ address, bid }, i) => {
1691
- const prevBidIndex = this.lastBids.findIndex(
1692
- (y) => y.address === address
1693
- );
1694
- const entry = {
1695
- address,
1696
- bidAmount: bid,
1697
- bidPosition: i,
1698
- prevPosition: prevBidIndex === -1 ? null : prevBidIndex
1699
- };
1700
- if (prevBidIndex !== -1) {
1701
- const prevBidAmount = this.lastBids[prevBidIndex].bid;
1702
- if (prevBidAmount !== bid) {
1703
- entry.prevBidAmount = prevBidAmount;
1704
- }
1705
- }
1706
- historyEntry.bidChanges.push(entry);
1707
- });
1708
- this.lastBids.forEach(({ address, bid }, i) => {
1709
- const nextBid = nextEntrants.some((y) => y.address === address);
1710
- if (!nextBid) {
1711
- historyEntry.bidChanges.push({
1712
- address,
1713
- bidAmount: bid,
1714
- bidPosition: null,
1715
- prevPosition: i
1716
- });
1717
- }
1718
- });
1719
- this.lastBids = nextEntrants;
1720
- }
1721
- return historyEntry;
1722
- }
1723
- onBidResult(historyEntry, param) {
1724
- const {
1725
- txFeePlusTip,
1726
- bidPerSeat,
1727
- bidsAttempted,
1728
- successfulBids,
1729
- blockNumber,
1730
- bidError
1731
- } = param;
1732
- this.stats.fees += txFeePlusTip;
1733
- this.stats.bidsAttempted += bidsAttempted;
1734
- if (bidPerSeat > this.stats.maxBidPerSeat) {
1735
- this.stats.maxBidPerSeat = bidPerSeat;
1736
- }
1737
- if (blockNumber !== void 0) {
1738
- this.stats.lastBlockNumber = Math.max(
1739
- blockNumber,
1740
- this.stats.lastBlockNumber
1741
- );
1742
- }
1743
- historyEntry.myBidsPlaced.failureReason = bidError;
1744
- historyEntry.myBidsPlaced.successfulBids = successfulBids;
1745
- historyEntry.myBidsPlaced.txFeePlusTip = txFeePlusTip;
1746
- }
1747
- static async getStartingData(api) {
1748
- const argonotPrice = await api.query.priceIndex.current();
1749
- let argonotUsdPrice = 0;
1750
- if (argonotPrice.isSome) {
1751
- argonotUsdPrice = convertFixedU128ToBigNumber(
1752
- argonotPrice.unwrap().argonotUsdPrice.toBigInt()
1753
- ).toNumber();
1754
- }
1755
- const argonotsPerSeat = await api.query.miningSlot.argonotsPerMiningSeat().then((x) => x.toBigInt());
1756
- const cohortArgonsPerBlock = await api.query.blockRewards.argonsPerBlock().then((x) => x.toBigInt());
1757
- return { argonotsPerSeat, argonotUsdPrice, cohortArgonsPerBlock };
1758
- }
1759
- };
1760
-
1761
- // src/CohortBidder.ts
1762
- var CohortBidder = class {
1763
- constructor(accountset, cohortId, subaccounts, options) {
1764
- this.accountset = accountset;
1765
- this.cohortId = cohortId;
1766
- this.subaccounts = subaccounts;
1767
- this.options = options;
1768
- this.history = new CohortBidderHistory(cohortId, subaccounts);
1769
- this.subaccounts.forEach((x) => {
1770
- this.myAddresses.add(x.address);
1771
- });
1772
- }
1773
- get client() {
1774
- return this.accountset.client;
1775
- }
1776
- get stats() {
1777
- return this.history.stats;
1778
- }
1779
- get bidHistory() {
1780
- return this.history.bidHistory;
1781
- }
1782
- unsubscribe;
1783
- pendingRequest;
1784
- retryTimeout;
1785
- isStopped = false;
1786
- needsRebid = false;
1787
- lastBidTime = 0;
1788
- history;
1789
- millisPerTick;
1790
- myAddresses = /* @__PURE__ */ new Set();
1791
- async stop() {
1792
- if (this.isStopped) return this.stats;
1793
- this.isStopped = true;
1794
- console.log("Stopping bidder for cohort", this.cohortId);
1795
- clearTimeout(this.retryTimeout);
1796
- if (this.unsubscribe) {
1797
- this.unsubscribe();
1798
- }
1799
- const client = await this.client;
1800
- const [nextCohortId, isBiddingOpen] = await client.queryMulti([
1801
- client.query.miningSlot.nextCohortId,
1802
- client.query.miningSlot.isNextSlotBiddingOpen
1803
- ]);
1804
- if (nextCohortId.toNumber() === this.cohortId && isBiddingOpen.isTrue) {
1805
- console.log("Bidding is still open, waiting for it to close");
1806
- await new Promise(async (resolve) => {
1807
- const unsub = await client.query.miningSlot.isNextSlotBiddingOpen(
1808
- (isOpen) => {
1809
- if (isOpen.isFalse) {
1810
- unsub();
1811
- resolve();
1812
- }
1813
- }
1814
- );
1815
- });
1816
- }
1817
- void await this.pendingRequest;
1818
- let header = await client.rpc.chain.getHeader();
1819
- while (true) {
1820
- const api2 = await client.at(header.hash);
1821
- const cohortId = await api2.query.miningSlot.nextCohortId();
1822
- if (cohortId.toNumber() === this.cohortId) {
1823
- break;
1824
- }
1825
- header = await client.rpc.chain.getHeader(header.parentHash);
1826
- }
1827
- const api = await client.at(header.hash);
1828
- const tick = await api.query.ticks.currentTick().then((x) => x.toNumber());
1829
- const cohort = await api.query.miningSlot.nextSlotCohort();
1830
- this.history.trackChange(cohort, header.number.toNumber(), tick, true);
1831
- console.log("Bidder stopped", {
1832
- cohortId: this.cohortId,
1833
- blockNumber: header.number.toNumber(),
1834
- tick,
1835
- cohort: cohort.map((x) => ({
1836
- address: x.accountId.toHuman(),
1837
- bid: x.bid.toBigInt()
1838
- }))
1839
- });
1840
- return this.stats;
1841
- }
1842
- async start() {
1843
- console.log(`Starting cohort ${this.cohortId} bidder`, {
1844
- maxBid: formatArgons(this.options.maxBid),
1845
- minBid: formatArgons(this.options.minBid),
1846
- bidIncrement: formatArgons(this.options.bidIncrement),
1847
- maxBudget: formatArgons(this.options.maxBudget),
1848
- bidDelay: this.options.bidDelay,
1849
- subaccounts: this.subaccounts
1850
- });
1851
- const client = await this.client;
1852
- await this.history.init(client);
1853
- this.millisPerTick ??= await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
1854
- this.unsubscribe = await client.queryMulti(
1855
- [
1856
- client.query.miningSlot.nextSlotCohort,
1857
- client.query.miningSlot.nextCohortId
1858
- ],
1859
- async ([next, nextCohortId]) => {
1860
- if (nextCohortId.toNumber() === this.cohortId) {
1861
- await this.checkSeats(next);
1862
- }
1863
- }
1864
- );
1865
- }
1866
- async checkSeats(next) {
1867
- if (this.isStopped) return;
1868
- clearTimeout(this.retryTimeout);
1869
- const client = await this.client;
1870
- const bestBlock = await client.rpc.chain.getBlockHash();
1871
- const api = await client.at(bestBlock);
1872
- const blockNumber = await api.query.system.number().then((x) => x.toNumber());
1873
- if (this.bidHistory[0]?.blockNumber >= blockNumber) {
1874
- return;
1875
- }
1876
- const tick = await api.query.ticks.currentTick().then((x) => x.toNumber());
1877
- const historyEntry = this.history.trackChange(next, blockNumber, tick);
1878
- if (this.pendingRequest) return;
1879
- const ticksSinceLastBid = Math.floor(
1880
- (Date.now() - this.lastBidTime) / this.millisPerTick
1881
- );
1882
- if (ticksSinceLastBid < this.options.bidDelay) {
1883
- this.retryTimeout = setTimeout(
1884
- () => void this.checkCurrentSeats(),
1885
- this.millisPerTick
1886
- );
1887
- return;
1888
- }
1889
- console.log(
1890
- "Checking bids for cohort",
1891
- this.cohortId,
1892
- this.subaccounts.map((x) => x.index)
1893
- );
1894
- const winningBids = historyEntry.winningSeats;
1895
- this.needsRebid = winningBids < this.subaccounts.length;
1896
- if (!this.needsRebid) return;
1897
- const winningAddresses = new Set(next.map((x) => x.accountId.toHuman()));
1898
- let lowestBid = -this.options.bidIncrement;
1899
- if (next.length) {
1900
- for (let i = next.length - 1; i >= 0; i--) {
1901
- if (!this.myAddresses.has(next[i].accountId.toHuman())) {
1902
- lowestBid = next.at(i).bid.toBigInt();
1903
- break;
1904
- }
1905
- }
1906
- }
1907
- const MIN_INCREMENT = 10000n;
1908
- let nextBid = lowestBid + this.options.bidIncrement;
1909
- if (nextBid < this.options.minBid) {
1910
- nextBid = this.options.minBid;
1911
- }
1912
- if (nextBid > this.options.maxBid) {
1913
- nextBid = this.options.maxBid;
1914
- }
1915
- const fakeTx = await this.accountset.createMiningBidTx({
1916
- subaccounts: this.subaccounts,
1917
- bidAmount: nextBid,
1918
- sendRewardsToSeed: true
1919
- });
1920
- let availableBalanceForBids = await api.query.system.account(this.accountset.txSubmitterPair.address).then((x) => x.data.free.toBigInt());
1921
- for (const bid of next) {
1922
- if (this.myAddresses.has(bid.accountId.toHuman())) {
1923
- availableBalanceForBids += bid.bid.toBigInt();
1924
- }
1925
- }
1926
- const tip = this.options.tipPerTransaction ?? 0n;
1927
- const feeEstimate = await fakeTx.feeEstimate(tip);
1928
- const feePlusTip = feeEstimate + tip;
1929
- let budgetForSeats = this.options.maxBudget - feePlusTip;
1930
- if (budgetForSeats > availableBalanceForBids) {
1931
- budgetForSeats = availableBalanceForBids - feePlusTip;
1932
- }
1933
- if (nextBid < lowestBid) {
1934
- console.log(
1935
- `Can't bid ${formatArgons(nextBid)}. Current lowest bid is ${formatArgons(
1936
- lowestBid
1937
- )}.`
1938
- );
1939
- this.history.maybeReducingSeats(
1940
- winningBids,
1941
- "MaxBidTooLow" /* MaxBidTooLow */,
1942
- historyEntry
1943
- );
1944
- return;
1945
- }
1946
- if (nextBid - lowestBid < MIN_INCREMENT) {
1947
- console.log(
1948
- `Can't make any more bids for ${this.cohortId} with given constraints.`,
1949
- {
1950
- lowestCurrentBid: formatArgons(lowestBid),
1951
- nextAttemptedBid: formatArgons(nextBid),
1952
- maxBid: formatArgons(this.options.maxBid)
1953
- }
1954
- );
1955
- this.history.maybeReducingSeats(
1956
- winningBids,
1957
- "MaxBidTooLow" /* MaxBidTooLow */,
1958
- historyEntry
1959
- );
1960
- return;
1961
- }
1962
- const seatsInBudget = nextBid === 0n ? this.subaccounts.length : Number(budgetForSeats / nextBid);
1963
- let accountsToUse = [...this.subaccounts];
1964
- if (accountsToUse.length > seatsInBudget) {
1965
- const reason = availableBalanceForBids - feePlusTip < nextBid * BigInt(seatsInBudget) ? "InsufficientFunds" /* InsufficientFunds */ : "MaxBudgetTooLow" /* MaxBudgetTooLow */;
1966
- this.history.maybeReducingSeats(seatsInBudget, reason, historyEntry);
1967
- accountsToUse.sort((a, b) => {
1968
- const isWinningA = winningAddresses.has(a.address);
1969
- const isWinningB = winningAddresses.has(b.address);
1970
- if (isWinningA && !isWinningB) return -1;
1971
- if (!isWinningA && isWinningB) return 1;
1972
- if (a.isRebid && !b.isRebid) return -1;
1973
- if (!a.isRebid && b.isRebid) return 1;
1974
- return a.index - b.index;
1975
- });
1976
- accountsToUse.length = seatsInBudget;
1977
- }
1978
- if (accountsToUse.length > winningBids) {
1979
- historyEntry.myBidsPlaced = {
1980
- bids: accountsToUse.length,
1981
- bidPerSeat: nextBid,
1982
- txFeePlusTip: feePlusTip,
1983
- successfulBids: 0
1984
- };
1985
- this.pendingRequest = this.bid(nextBid, accountsToUse, historyEntry);
1986
- } else if (historyEntry.bidChanges.length === 0) {
1987
- this.history.bidHistory.shift();
1988
- }
1989
- this.needsRebid = false;
1990
- }
1991
- async bid(bidPerSeat, subaccounts, historyEntry) {
1992
- const prevLastBidTime = this.lastBidTime;
1993
- try {
1994
- this.lastBidTime = Date.now();
1995
- const submitter = await this.accountset.createMiningBidTx({
1996
- subaccounts,
1997
- bidAmount: bidPerSeat,
1998
- sendRewardsToSeed: true
1999
- });
2000
- const tip = this.options.tipPerTransaction ?? 0n;
2001
- const txResult = await submitter.submit({
2002
- tip,
2003
- useLatestNonce: true
2004
- });
2005
- const bidError = await txResult.inBlockPromise.then(() => void 0).catch((x) => x);
2006
- let blockNumber;
2007
- if (txResult.includedInBlock) {
2008
- const client = await this.client;
2009
- const api = await client.at(txResult.includedInBlock);
2010
- blockNumber = await api.query.system.number().then((x) => x.toNumber());
2011
- }
2012
- const successfulBids = txResult.batchInterruptedIndex ?? subaccounts.length;
2013
- this.history.onBidResult(historyEntry, {
2014
- blockNumber,
2015
- successfulBids,
2016
- bidPerSeat,
2017
- txFeePlusTip: txResult.finalFee ?? 0n,
2018
- bidsAttempted: subaccounts.length,
2019
- bidError
2020
- });
2021
- console.log("Done creating bids for cohort", {
2022
- successfulBids,
2023
- bidPerSeat,
2024
- blockNumber
2025
- });
2026
- if (bidError) throw bidError;
2027
- } catch (err) {
2028
- this.lastBidTime = prevLastBidTime;
2029
- console.error(`Error bidding for cohort ${this.cohortId}:`, err);
2030
- clearTimeout(this.retryTimeout);
2031
- this.retryTimeout = setTimeout(() => void this.checkCurrentSeats(), 1e3);
2032
- } finally {
2033
- this.pendingRequest = void 0;
2034
- }
2035
- if (this.needsRebid) {
2036
- this.needsRebid = false;
2037
- await this.checkCurrentSeats();
2038
- }
2039
- }
2040
- async checkCurrentSeats() {
2041
- const client = await this.client;
2042
- const next = await client.query.miningSlot.nextSlotCohort();
2043
- await this.checkSeats(next);
2044
- }
2045
- };
2046
-
2047
- // src/BidPool.ts
2048
- var import_console_table_printer3 = require("console-table-printer");
2049
- var EMPTY_TABLE = {
2050
- headerBottom: { left: " ", mid: " ", other: "\u2500", right: " " },
2051
- headerTop: { left: " ", mid: " ", other: " ", right: " " },
2052
- rowSeparator: { left: " ", mid: " ", other: " ", right: " " },
2053
- tableBottom: { left: " ", mid: " ", other: " ", right: " " },
2054
- vertical: " "
2055
- };
2056
- var BidPool = class {
2057
- constructor(client, keypair, accountRegistry = AccountRegistry.factory()) {
2058
- this.client = client;
2059
- this.keypair = keypair;
2060
- this.accountRegistry = accountRegistry;
2061
- this.blockWatch = new BlockWatch(client, { shouldLog: false });
2062
- }
2063
- bidPoolAmount = 0n;
2064
- nextCohortId = 1;
2065
- poolVaultCapitalByCohort = {};
2066
- vaultSecuritization = [];
2067
- printTimeout;
2068
- blockWatch;
2069
- vaultsById = {};
2070
- tickDuration;
2071
- lastDistributedCohortId;
2072
- cohortSubscriptions = {};
2073
- async onVaultsUpdated(blockHash, vaultIdSet) {
2074
- const client = await this.client;
2075
- this.tickDuration ??= (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();
2076
- const api = await client.at(blockHash);
2077
- const vaultIds = [...vaultIdSet];
2078
- const rawVaults = await api.query.vaults.vaultsById.multi(vaultIds);
2079
- for (let i = 0; i < vaultIds.length; i += 1) {
2080
- const rawVault = rawVaults[i];
2081
- if (rawVault.isNone) continue;
2082
- const vaultId = vaultIds[i];
2083
- this.vaultsById[vaultId] = new Vault(
2084
- vaultId,
2085
- rawVault.unwrap(),
2086
- this.tickDuration
2087
- );
2088
- }
2089
- const vaults = Object.entries(this.vaultsById);
2090
- const newSecuritization = [];
2091
- for (const [vaultId, vault] of vaults) {
2092
- const amount = vault.activatedSecuritizationPerSlot();
2093
- newSecuritization.push({
2094
- vaultId: Number(vaultId),
2095
- bitcoinSpace: vault.availableBitcoinSpace(),
2096
- activatedSecuritization: amount,
2097
- vaultSharingPercent: vault.terms.liquidityPoolProfitSharing
2098
- });
2099
- }
2100
- newSecuritization.sort((a, b) => {
2101
- const diff2 = b.activatedSecuritization - a.activatedSecuritization;
2102
- if (diff2 !== 0n) return Number(diff2);
2103
- return a.vaultId - b.vaultId;
2104
- });
2105
- this.vaultSecuritization = newSecuritization;
2106
- this.printDebounce();
2107
- }
2108
- async getBidPool() {
2109
- const client = await this.client;
2110
- const balanceBytes = await client.rpc.state.call(
2111
- "MiningSlotApi_bid_pool",
2112
- ""
2113
- );
2114
- const balance = client.createType("U128", balanceBytes);
2115
- return balance.toBigInt();
2116
- }
2117
- async loadAt(blockHash) {
2118
- const client = await this.client;
2119
- blockHash ??= (await client.rpc.chain.getHeader()).hash.toU8a();
2120
- const api = await client.at(blockHash);
2121
- const rawVaultIds = await api.query.vaults.vaultsById.keys();
2122
- const vaultIds = rawVaultIds.map((x) => x.args[0].toNumber());
2123
- this.bidPoolAmount = await this.getBidPool();
2124
- this.nextCohortId = (await api.query.miningSlot.nextCohortId()).toNumber();
2125
- const contributors = await api.query.liquidityPools.liquidityPoolsByCohort.entries();
2126
- for (const [cohortId, funds] of contributors) {
2127
- const cohortIdNumber = cohortId.args[0].toNumber();
2128
- this.loadCohortData(cohortIdNumber, funds);
2129
- }
2130
- for (const entrant of await api.query.liquidityPools.openLiquidityPoolCapital()) {
2131
- this.setVaultCohortData(this.nextCohortId, entrant.vaultId.toNumber(), {
2132
- activatedCapital: entrant.activatedCapital.toBigInt()
2133
- });
2134
- }
2135
- for (const entrant of await api.query.liquidityPools.nextLiquidityPoolCapital()) {
2136
- this.setVaultCohortData(this.nextCohortId, entrant.vaultId.toNumber(), {
2137
- activatedCapital: entrant.activatedCapital.toBigInt()
2138
- });
2139
- }
2140
- await this.onVaultsUpdated(blockHash, new Set(vaultIds));
2141
- this.print();
2142
- }
2143
- async watch() {
2144
- await this.loadAt();
2145
- await this.blockWatch.start();
2146
- this.blockWatch.events.on(
2147
- "vaults-updated",
2148
- (b, v) => this.onVaultsUpdated(b.hash, v)
2149
- );
2150
- const api = await this.client;
2151
- this.blockWatch.events.on("event", async (_, event) => {
2152
- if (api.events.liquidityPools.BidPoolDistributed.is(event)) {
2153
- const { cohortId: rawCohortId } = event.data;
2154
- this.lastDistributedCohortId = rawCohortId.toNumber();
2155
- this.bidPoolAmount = await this.getBidPool();
2156
- this.cohortSubscriptions[rawCohortId.toNumber()]?.();
2157
- const entrant = await api.query.liquidityPools.liquidityPoolsByCohort(rawCohortId);
2158
- this.loadCohortData(rawCohortId.toNumber(), entrant);
2159
- this.printDebounce();
2160
- }
2161
- if (api.events.liquidityPools.NextBidPoolCapitalLocked.is(event)) {
2162
- const { cohortId } = event.data;
2163
- for (let inc = 0; inc < 2; inc++) {
2164
- const id = cohortId.toNumber() + inc;
2165
- if (!this.cohortSubscriptions[id]) {
2166
- this.cohortSubscriptions[id] = await api.query.liquidityPools.liquidityPoolsByCohort(
2167
- id,
2168
- async (entrant) => {
2169
- this.loadCohortData(id, entrant);
2170
- this.printDebounce();
2171
- }
2172
- );
2173
- }
2174
- }
2175
- }
2176
- });
2177
- const unsubscribe = await api.queryMulti(
2178
- [
2179
- api.query.miningSlot.nextSlotCohort,
2180
- api.query.miningSlot.nextCohortId,
2181
- api.query.liquidityPools.openLiquidityPoolCapital,
2182
- api.query.liquidityPools.nextLiquidityPoolCapital
2183
- ],
2184
- async ([
2185
- _nextSlotCohort,
2186
- nextCohortId,
2187
- openVaultBidPoolCapital,
2188
- nextPoolCapital
2189
- ]) => {
2190
- this.bidPoolAmount = await this.getBidPool();
2191
- this.nextCohortId = nextCohortId.toNumber();
2192
- for (const entrant of [
2193
- ...openVaultBidPoolCapital,
2194
- ...nextPoolCapital
2195
- ]) {
2196
- this.setVaultCohortData(
2197
- entrant.cohortId.toNumber(),
2198
- entrant.vaultId.toNumber(),
2199
- {
2200
- activatedCapital: entrant.activatedCapital.toBigInt()
2201
- }
2202
- );
2203
- }
2204
- this.printDebounce();
2205
- }
2206
- );
2207
- return { unsubscribe };
2208
- }
2209
- async bondArgons(vaultId, amount, options) {
2210
- const client = await this.client;
2211
- const tx = client.tx.liquidityPools.bondArgons(vaultId, amount);
2212
- const txSubmitter = new TxSubmitter(client, tx, this.keypair);
2213
- const affordability = await txSubmitter.canAfford({
2214
- tip: options?.tip,
2215
- unavailableBalance: amount
2216
- });
2217
- if (!affordability.canAfford) {
2218
- console.warn("Insufficient balance to bond argons to liquidity pool", {
2219
- ...affordability,
2220
- argonsNeeded: amount
2221
- });
2222
- throw new Error("Insufficient balance to bond argons to liquidity pool");
2223
- }
2224
- const result = await txSubmitter.submit({
2225
- tip: options?.tip,
2226
- useLatestNonce: true
2227
- });
2228
- await result.inBlockPromise;
2229
- return result;
2230
- }
2231
- printDebounce() {
2232
- if (this.printTimeout) {
2233
- clearTimeout(this.printTimeout);
2234
- }
2235
- this.printTimeout = setTimeout(() => {
2236
- this.print();
2237
- }, 100);
2238
- }
2239
- getOperatorName(vaultId) {
2240
- const vault = this.vaultsById[vaultId];
2241
- return this.accountRegistry.getName(vault.operatorAccountId) ?? vault.operatorAccountId;
2242
- }
2243
- print() {
2244
- console.clear();
2245
- const lastDistributedCohortId = this.lastDistributedCohortId;
2246
- const distributedCohort = this.poolVaultCapitalByCohort[this.lastDistributedCohortId ?? -1] ?? {};
2247
- if (Object.keys(distributedCohort).length > 0) {
2248
- console.log(`
2249
-
2250
- Distributed (cohort ${lastDistributedCohortId})`);
2251
- const rows = [];
2252
- let maxWidth2 = 0;
2253
- for (const [key, entry] of Object.entries(distributedCohort)) {
2254
- const { table, width } = this.createBondCapitalTable(
2255
- entry.earnings ?? 0n,
2256
- entry.contributors ?? [],
2257
- `Earnings (shared = ${formatPercent(entry.vaultSharingPercent)})`
2258
- );
2259
- if (width > maxWidth2) {
2260
- maxWidth2 = width;
2261
- }
2262
- rows.push({
2263
- Vault: key,
2264
- Who: this.getOperatorName(Number(key)),
2265
- Balances: table
2266
- });
2267
- }
2268
- new import_console_table_printer3.Table({
2269
- columns: [
2270
- { name: "Vault", alignment: "left" },
2271
- { name: "Who", alignment: "left" },
2272
- {
2273
- name: "Balances",
2274
- title: "Contributor Balances",
2275
- alignment: "center",
2276
- minLen: maxWidth2
2277
- }
2278
- ],
2279
- rows
2280
- }).printTable();
2281
- }
2282
- console.log(
2283
- `
2284
-
2285
- Active Bid Pool: ${formatArgons(this.bidPoolAmount)} (cohort ${this.nextCohortId})`
2286
- );
2287
- const cohort = this.poolVaultCapitalByCohort[this.nextCohortId];
2288
- if (Object.keys(cohort ?? {}).length > 0) {
2289
- const rows = [];
2290
- let maxWidth2 = 0;
2291
- for (const [key, entry] of Object.entries(cohort)) {
2292
- const { table, width } = this.createBondCapitalTable(
2293
- entry.activatedCapital,
2294
- entry.contributors ?? []
2295
- );
2296
- if (width > maxWidth2) {
2297
- maxWidth2 = width;
2298
- }
2299
- rows.push({
2300
- Vault: key,
2301
- Who: this.getOperatorName(Number(key)),
2302
- "Pool Capital": table
2303
- });
2304
- }
2305
- new import_console_table_printer3.Table({
2306
- columns: [
2307
- { name: "Vault", alignment: "left" },
2308
- { name: "Who", alignment: "left" },
2309
- { name: "Pool Capital", alignment: "left", minLen: maxWidth2 }
2310
- ],
2311
- rows
2312
- }).printTable();
2313
- }
2314
- const nextPool = this.poolVaultCapitalByCohort[this.nextCohortId + 1] ?? [];
2315
- let maxWidth = 0;
2316
- const nextCapital = [];
2317
- for (const x of this.vaultSecuritization) {
2318
- const entry = nextPool[x.vaultId] ?? {};
2319
- const { table, width } = this.createBondCapitalTable(
2320
- x.activatedSecuritization,
2321
- entry.contributors ?? []
2322
- );
2323
- if (width > maxWidth) {
2324
- maxWidth = width;
2325
- }
2326
- nextCapital.push({
2327
- Vault: x.vaultId,
2328
- Owner: this.getOperatorName(x.vaultId),
2329
- "Bitcoin Space": formatArgons(x.bitcoinSpace),
2330
- "Activated Securitization": `${formatArgons(x.activatedSecuritization)} / slot`,
2331
- "Liquidity Pool": `${formatPercent(x.vaultSharingPercent)} profit sharing${table}`
2332
- });
2333
- }
2334
- if (nextCapital.length) {
2335
- console.log(`
2336
-
2337
- Next (cohort ${this.nextCohortId + 1}):`);
2338
- new import_console_table_printer3.Table({
2339
- columns: [
2340
- { name: "Vault", alignment: "left" },
2341
- { name: "Owner", alignment: "left" },
2342
- { name: "Bitcoin Space", alignment: "right" },
2343
- { name: "Activated Securitization", alignment: "right" },
2344
- { name: "Liquidity Pool", alignment: "left", minLen: maxWidth }
2345
- ],
2346
- rows: nextCapital
2347
- }).printTable();
2348
- }
2349
- }
2350
- setVaultCohortData(cohortId, vaultId, data) {
2351
- this.poolVaultCapitalByCohort ??= {};
2352
- this.poolVaultCapitalByCohort[cohortId] ??= {};
2353
- this.poolVaultCapitalByCohort[cohortId][vaultId] ??= {
2354
- activatedCapital: data.activatedCapital ?? data.contributors?.reduce((a, b) => a + b.amount, 0n) ?? 0n
2355
- };
2356
- Object.assign(
2357
- this.poolVaultCapitalByCohort[cohortId][vaultId],
2358
- filterUndefined(data)
2359
- );
2360
- }
2361
- createBondCapitalTable(total, contributors, title = "Total") {
2362
- const table = new import_console_table_printer3.Table({
2363
- style: EMPTY_TABLE,
2364
- columns: [
2365
- { name: "who", title, minLen: 10, alignment: "right" },
2366
- {
2367
- name: "amount",
2368
- title: formatArgons(total),
2369
- minLen: 7,
2370
- alignment: "left"
2371
- }
2372
- ]
2373
- });
2374
- for (const x of contributors) {
2375
- table.addRow({
2376
- who: this.accountRegistry.getName(x.address) ?? x.address,
2377
- amount: formatArgons(x.amount)
2378
- });
2379
- }
2380
- const str = table.render();
2381
- const width = str.indexOf("\n");
2382
- return { table: str, width };
2383
- }
2384
- loadCohortData(cohortId, vaultFunds) {
2385
- for (const [vaultId, fund] of vaultFunds) {
2386
- const vaultIdNumber = vaultId.toNumber();
2387
- const contributors = fund.contributorBalances.map(([a, b]) => ({
2388
- address: a.toHuman(),
2389
- amount: b.toBigInt()
2390
- }));
2391
- if (fund.distributedProfits.isSome) {
2392
- if (cohortId > (this.lastDistributedCohortId ?? 0)) {
2393
- this.lastDistributedCohortId = cohortId;
2394
- }
2395
- }
2396
- this.setVaultCohortData(cohortId, vaultIdNumber, {
2397
- earnings: fund.distributedProfits.isSome ? fund.distributedProfits.unwrap().toBigInt() : void 0,
2398
- vaultSharingPercent: convertPermillToBigNumber(
2399
- fund.vaultSharingPercent.toBigInt()
2400
- ),
2401
- contributors
2402
- });
2403
- }
2404
- }
2405
- };
2406
-
2407
- // src/BitcoinLocks.ts
2408
- var SATS_PER_BTC = 100000000n;
2409
- var BitcoinLocks = class _BitcoinLocks {
2410
- constructor(client) {
2411
- this.client = client;
2412
- }
2413
- async getMarketRate(satoshis) {
2414
- const client = await this.client;
2415
- const sats = client.createType("U64", satoshis.toString());
2416
- const marketRate = await client.rpc.state.call(
2417
- "BitcoinApis_market_rate",
2418
- sats.toHex(true)
2419
- );
2420
- const rate = client.createType("Option<U128>", marketRate);
2421
- if (!rate.isSome) {
2422
- throw new Error("Market rate not available");
2423
- }
2424
- return rate.value.toBigInt();
2425
- }
2426
- async buildBitcoinLockTx(args) {
2427
- const { vaultId, keypair, bitcoinXpub, tip } = args;
2428
- let amount = args.amount;
2429
- const marketRatePerBitcoin = await this.getMarketRate(100000000n);
2430
- const client = await this.client;
2431
- const account = await client.query.system.account(keypair.address);
2432
- const freeBalance = account.data.free.toBigInt();
2433
- let availableBalance = freeBalance;
2434
- if (args.reducedBalanceBy) {
2435
- availableBalance -= args.reducedBalanceBy;
2436
- }
2437
- const satoshisNeeded = amount * SATS_PER_BTC / marketRatePerBitcoin - 500n;
2438
- const tx = client.tx.bitcoinLocks.initialize(
2439
- vaultId,
2440
- satoshisNeeded,
2441
- bitcoinXpub
2442
- );
2443
- const existentialDeposit = client.consts.balances.existentialDeposit.toBigInt();
2444
- const finalTip = tip ?? 0n;
2445
- const fees = await tx.paymentInfo(keypair.address, { tip });
2446
- const txFee = fees.partialFee.toBigInt();
2447
- const tickDuration = (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();
2448
- const rawVault = await client.query.vaults.vaultsById(vaultId);
2449
- const vault = new Vault(vaultId, rawVault.unwrap(), tickDuration);
2450
- const btcFee = vault.calculateBitcoinFee(amount);
2451
- const totalCharge = txFee + finalTip + btcFee;
2452
- if (amount + totalCharge + existentialDeposit > availableBalance) {
2453
- throw new Error("Insufficient balance to lock bitcoins");
2454
- }
2455
- console.log(
2456
- `Locking ${satoshisNeeded} satoshis in vault ${vaultId} with market rate of ${formatArgons(marketRatePerBitcoin)}/btc. Xpub: ${bitcoinXpub}`
2457
- );
2458
- return { tx, txFee, btcFee, satoshis: satoshisNeeded, freeBalance };
2459
- }
2460
- static async waitForSpace(accountset, options) {
2461
- const { argonAmount, bitcoinXpub, maxLockFee, tip = 0n } = options;
2462
- const vaults = new VaultMonitor(accountset, {
2463
- bitcoinSpaceAvailable: argonAmount
2464
- });
2465
- return new Promise(async (resolve, reject) => {
2466
- vaults.events.on("bitcoin-space-above", async (vaultId, amount) => {
2467
- const vault = vaults.vaultsById[vaultId];
2468
- const fee = vault.calculateBitcoinFee(amount);
2469
- console.log(
2470
- `Vault ${vaultId} has ${formatArgons(amount)} argons available for bitcoin. Lock fee is ${formatArgons(fee)}`
2471
- );
2472
- if (maxLockFee !== void 0 && fee > maxLockFee) {
2473
- console.log(
2474
- `Skipping vault ${vaultId} due to high lock fee: ${formatArgons(maxLockFee)}`
2475
- );
2476
- return;
2477
- }
2478
- try {
2479
- const bitcoinLock = new _BitcoinLocks(accountset.client);
2480
- const { tx, satoshis, btcFee, txFee } = await bitcoinLock.buildBitcoinLockTx({
2481
- vaultId,
2482
- keypair: accountset.txSubmitterPair,
2483
- amount: argonAmount,
2484
- bitcoinXpub,
2485
- tip
2486
- });
2487
- const result = await accountset.tx(tx).then((x) => x.submit({ waitForBlock: true, tip }));
2488
- const client = await accountset.client;
2489
- const utxoId = result.events.find((x) => client.events.bitcoinLocks.BitcoinLockCreated.is(x))?.data.utxoId?.toNumber();
2490
- if (!utxoId) {
2491
- throw new Error("Failed to find UTXO ID");
2492
- }
2493
- resolve({
2494
- satoshis,
2495
- argons: argonAmount,
2496
- vaultId,
2497
- btcFee,
2498
- txFee,
2499
- finalizedPromise: result.finalizedPromise,
2500
- utxoId
2501
- });
2502
- } catch (err) {
2503
- console.error("Error submitting bitcoin lock tx:", err);
2504
- reject(err);
2505
- } finally {
2506
- vaults.stop();
2507
- }
2508
- });
2509
- await vaults.monitor();
2510
- });
2511
- }
2512
- };
2513
-
2514
- // src/keyringUtils.ts
2515
- function keyringFromSuri(suri, cryptoType = "sr25519") {
2516
- return new import_api.Keyring({ type: cryptoType }).createFromUri(suri);
2517
- }
2518
- function createKeyringPair(opts) {
2519
- const { cryptoType } = opts;
2520
- const seed = (0, import_util_crypto.mnemonicGenerate)();
2521
- return keyringFromSuri(seed, cryptoType);
2522
- }
2523
-
2524
- // src/index.ts
2525
- __reExport(index_exports, require("@polkadot/types"), module.exports);
2526
- __reExport(index_exports, require("@polkadot/types/interfaces"), module.exports);
2527
- async function waitForLoad() {
2528
- await (0, import_util_crypto.cryptoWaitReady)();
2529
- }
2530
- async function getClient(host) {
2531
- let provider;
2532
- if (host.startsWith("http:")) {
2533
- provider = new import_api.HttpProvider(host);
2534
- } else {
2535
- provider = new import_api.WsProvider(host);
2536
- }
2537
- return await import_api.ApiPromise.create({ provider, noInitWarn: true });
2538
- }
2539
- // Annotate the CommonJS export names for ESM import in node:
2540
- 0 && (module.exports = {
2541
- AccountMiners,
2542
- AccountRegistry,
2543
- Accountset,
2544
- BidPool,
2545
- BitcoinLocks,
2546
- BlockWatch,
2547
- CohortBidder,
2548
- ExtrinsicError,
2549
- JsonExt,
2550
- Keyring,
2551
- MICROGONS_PER_ARGON,
2552
- MiningBids,
2553
- MiningRotations,
2554
- TxSubmitter,
2555
- Vault,
2556
- VaultMonitor,
2557
- WageProtector,
2558
- checkForExtrinsicSuccess,
2559
- convertFixedU128ToBigNumber,
2560
- convertPermillToBigNumber,
2561
- createKeyringPair,
2562
- decodeAddress,
2563
- dispatchErrorToExtrinsicError,
2564
- dispatchErrorToString,
2565
- eventDataToJson,
2566
- filterUndefined,
2567
- formatArgons,
2568
- formatPercent,
2569
- getAuthorFromHeader,
2570
- getClient,
2571
- getTickFromHeader,
2572
- gettersToObject,
2573
- keyringFromSuri,
2574
- mnemonicGenerate,
2575
- waitForLoad,
2576
- ...require("@polkadot/types-codec/types"),
2577
- ...require("@polkadot/types"),
2578
- ...require("@polkadot/types/interfaces")
2579
- });
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+ var _chunkCHGCEO2Ucjs = require('./chunk-CHGCEO2U.cjs');
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+ exports.AccountMiners = _chunkCHGCEO2Ucjs.AccountMiners; exports.AccountRegistry = _chunkCHGCEO2Ucjs.AccountRegistry; exports.Accountset = _chunkCHGCEO2Ucjs.Accountset; exports.BidPool = _chunkCHGCEO2Ucjs.BidPool; exports.BitcoinLocks = _chunkCHGCEO2Ucjs.BitcoinLocks; exports.BlockWatch = _chunkCHGCEO2Ucjs.BlockWatch; exports.CohortBidder = _chunkCHGCEO2Ucjs.CohortBidder; exports.CohortBidderHistory = _chunkCHGCEO2Ucjs.CohortBidderHistory; exports.ExtrinsicError = _chunkCHGCEO2Ucjs.ExtrinsicError; exports.FrameCalculator = _chunkCHGCEO2Ucjs.FrameCalculator; exports.JsonExt = _chunkCHGCEO2Ucjs.JsonExt; exports.Keyring = _chunkCHGCEO2Ucjs.Keyring; exports.MICROGONS_PER_ARGON = _chunkCHGCEO2Ucjs.MICROGONS_PER_ARGON; exports.MiningBids = _chunkCHGCEO2Ucjs.MiningBids; exports.TxSubmitter = _chunkCHGCEO2Ucjs.TxSubmitter; exports.TypedEmitter = _chunkCHGCEO2Ucjs.TypedEmitter; exports.Vault = _chunkCHGCEO2Ucjs.Vault; exports.VaultMonitor = _chunkCHGCEO2Ucjs.VaultMonitor; exports.WageProtector = _chunkCHGCEO2Ucjs.WageProtector; exports.checkForExtrinsicSuccess = _chunkCHGCEO2Ucjs.checkForExtrinsicSuccess; exports.convertFixedU128ToBigNumber = _chunkCHGCEO2Ucjs.convertFixedU128ToBigNumber; exports.convertPermillToBigNumber = _chunkCHGCEO2Ucjs.convertPermillToBigNumber; exports.createKeyringPair = _chunkCHGCEO2Ucjs.createKeyringPair; exports.createNanoEvents = _chunkCHGCEO2Ucjs.createNanoEvents; exports.decodeAddress = _chunkCHGCEO2Ucjs.decodeAddress; exports.dispatchErrorToExtrinsicError = _chunkCHGCEO2Ucjs.dispatchErrorToExtrinsicError; exports.dispatchErrorToString = _chunkCHGCEO2Ucjs.dispatchErrorToString; exports.eventDataToJson = _chunkCHGCEO2Ucjs.eventDataToJson; exports.filterUndefined = _chunkCHGCEO2Ucjs.filterUndefined; exports.formatArgons = _chunkCHGCEO2Ucjs.formatArgons; exports.formatPercent = _chunkCHGCEO2Ucjs.formatPercent; exports.getAuthorFromHeader = _chunkCHGCEO2Ucjs.getAuthorFromHeader; exports.getClient = _chunkCHGCEO2Ucjs.getClient; exports.getTickFromHeader = _chunkCHGCEO2Ucjs.getTickFromHeader; exports.gettersToObject = _chunkCHGCEO2Ucjs.gettersToObject; exports.keyringFromSuri = _chunkCHGCEO2Ucjs.keyringFromSuri; exports.mnemonicGenerate = _chunkCHGCEO2Ucjs.mnemonicGenerate; exports.waitForLoad = _chunkCHGCEO2Ucjs.waitForLoad;
2580
81
  //# sourceMappingURL=index.cjs.map