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