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