@argonprotocol/mainchain 1.1.0-rc.8 → 1.2.0

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