@argonprotocol/mainchain 1.3.1 → 1.3.3

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