@argonprotocol/mainchain 1.2.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 +3 -8
- package/lib/{chunk-RXCQYVE7.js → chunk-CGXT6XF7.js} +586 -288
- package/lib/chunk-CGXT6XF7.js.map +1 -0
- package/lib/{chunk-BQR6FEVP.js → chunk-FNSFV3MO.js} +114 -227
- package/lib/chunk-FNSFV3MO.js.map +1 -0
- package/lib/{chunk-EY3HYZMJ.cjs → chunk-NU36V3JQ.cjs} +152 -265
- package/lib/chunk-NU36V3JQ.cjs.map +1 -0
- package/lib/{chunk-CHGCEO2U.cjs → chunk-SHAEHPI5.cjs} +587 -289
- package/lib/chunk-SHAEHPI5.cjs.map +1 -0
- package/lib/cli.cjs +6 -6
- 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 +3 -3
- package/lib/cli.js.map +1 -1
- package/lib/clis/index.cjs +3 -3
- package/lib/clis/index.js +2 -2
- package/lib/index.cjs +10 -2
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +542 -363
- package/lib/index.d.ts +542 -363
- package/lib/index.js +9 -1
- package/package.json +15 -14
- package/lib/chunk-BQR6FEVP.js.map +0 -1
- package/lib/chunk-CHGCEO2U.cjs.map +0 -1
- package/lib/chunk-EY3HYZMJ.cjs.map +0 -1
- package/lib/chunk-RXCQYVE7.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
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 _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(); } } 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
|
|
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
2
|
require('@polkadot/api-base/types/consts');
|
|
3
3
|
|
|
4
4
|
// src/interfaces/augment-api-errors.ts
|
|
@@ -24,10 +24,6 @@ require('@polkadot/types/types/registry');
|
|
|
24
24
|
|
|
25
25
|
// src/index.ts
|
|
26
26
|
var _api = require('@polkadot/api');
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
27
|
var _utilcrypto = require('@polkadot/util-crypto');
|
|
32
28
|
|
|
33
29
|
// src/WageProtector.ts
|
|
@@ -60,7 +56,7 @@ var WageProtector = class _WageProtector {
|
|
|
60
56
|
new _WageProtector({
|
|
61
57
|
argonUsdTargetPrice: cpi.value.argonUsdTargetPrice.toBigInt(),
|
|
62
58
|
argonUsdPrice: cpi.value.argonUsdPrice.toBigInt(),
|
|
63
|
-
finalizedBlock:
|
|
59
|
+
finalizedBlock: Buffer.from(finalizedBlock),
|
|
64
60
|
tick: cpi.value.tick.toBigInt()
|
|
65
61
|
})
|
|
66
62
|
);
|
|
@@ -137,9 +133,7 @@ var TxSubmitter = class {
|
|
|
137
133
|
}
|
|
138
134
|
args.unshift(txString.join("->"));
|
|
139
135
|
if (options.useLatestNonce && !options.nonce) {
|
|
140
|
-
options.nonce = await this.client.rpc.system.accountNextIndex(
|
|
141
|
-
this.pair.address
|
|
142
|
-
);
|
|
136
|
+
options.nonce = await this.client.rpc.system.accountNextIndex(this.pair.address);
|
|
143
137
|
}
|
|
144
138
|
console.log("Submitting transaction:", ...args);
|
|
145
139
|
await this.tx.signAndSend(this.pair, options, result.onResult.bind(result));
|
|
@@ -197,7 +191,7 @@ var TxResult = (_class = class {
|
|
|
197
191
|
}
|
|
198
192
|
const { events, status, dispatchError, isFinalized } = result;
|
|
199
193
|
if (status.isInBlock) {
|
|
200
|
-
this.includedInBlock = status.asInBlock
|
|
194
|
+
this.includedInBlock = Buffer.from(status.asInBlock);
|
|
201
195
|
let encounteredError = dispatchError;
|
|
202
196
|
let batchErrorIndex;
|
|
203
197
|
for (const event of events) {
|
|
@@ -207,23 +201,17 @@ var TxResult = (_class = class {
|
|
|
207
201
|
this.batchInterruptedIndex = batchErrorIndex;
|
|
208
202
|
encounteredError = event.event.data[1];
|
|
209
203
|
}
|
|
210
|
-
if (this.client.events.transactionPayment.TransactionFeePaid.is(
|
|
211
|
-
event.event
|
|
212
|
-
)) {
|
|
204
|
+
if (this.client.events.transactionPayment.TransactionFeePaid.is(event.event)) {
|
|
213
205
|
const [_who, actualFee, tip] = event.event.data;
|
|
214
206
|
this.finalFee = actualFee.toBigInt();
|
|
215
207
|
this.finalFeeTip = tip.toBigInt();
|
|
216
208
|
}
|
|
217
209
|
}
|
|
218
210
|
if (encounteredError) {
|
|
219
|
-
const error = dispatchErrorToExtrinsicError(
|
|
220
|
-
this.client,
|
|
221
|
-
encounteredError,
|
|
222
|
-
batchErrorIndex
|
|
223
|
-
);
|
|
211
|
+
const error = dispatchErrorToExtrinsicError(this.client, encounteredError, batchErrorIndex);
|
|
224
212
|
this.reject(error);
|
|
225
213
|
} else {
|
|
226
|
-
this.inBlockResolve(status.asInBlock
|
|
214
|
+
this.inBlockResolve(Buffer.from(status.asInBlock));
|
|
227
215
|
}
|
|
228
216
|
}
|
|
229
217
|
if (isFinalized) {
|
|
@@ -255,9 +243,7 @@ function formatPercent(x) {
|
|
|
255
243
|
}
|
|
256
244
|
function filterUndefined(obj) {
|
|
257
245
|
return Object.fromEntries(
|
|
258
|
-
Object.entries(obj).filter(
|
|
259
|
-
([_, value]) => value !== void 0 && value !== null
|
|
260
|
-
)
|
|
246
|
+
Object.entries(obj).filter(([_, value]) => value !== void 0 && value !== null)
|
|
261
247
|
);
|
|
262
248
|
}
|
|
263
249
|
async function gettersToObject(obj) {
|
|
@@ -285,6 +271,14 @@ async function gettersToObject(obj) {
|
|
|
285
271
|
}
|
|
286
272
|
return result;
|
|
287
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
|
+
}
|
|
288
282
|
function convertFixedU128ToBigNumber(fixedU128) {
|
|
289
283
|
const decimalFactor = new (0, BN.default)(10).pow(new (0, BN.default)(18));
|
|
290
284
|
const rawValue = new (0, BN.default)(fixedU128.toString());
|
|
@@ -295,6 +289,9 @@ function convertPermillToBigNumber(permill) {
|
|
|
295
289
|
const rawValue = new (0, BN.default)(permill.toString());
|
|
296
290
|
return rawValue.div(decimalFactor);
|
|
297
291
|
}
|
|
292
|
+
function convertNumberToPermill(value) {
|
|
293
|
+
return toFixedNumber(value, 6);
|
|
294
|
+
}
|
|
298
295
|
function eventDataToJson(event) {
|
|
299
296
|
const obj = {};
|
|
300
297
|
event.data.forEach((data, index) => {
|
|
@@ -330,11 +327,7 @@ function dispatchErrorToExtrinsicError(client, error, batchInterruptedIndex) {
|
|
|
330
327
|
if (error.isModule) {
|
|
331
328
|
const decoded = client.registry.findMetaError(error.asModule);
|
|
332
329
|
const { docs, name, section } = decoded;
|
|
333
|
-
return new ExtrinsicError2(
|
|
334
|
-
`${section}.${name}`,
|
|
335
|
-
docs.join(" "),
|
|
336
|
-
batchInterruptedIndex
|
|
337
|
-
);
|
|
330
|
+
return new ExtrinsicError2(`${section}.${name}`, docs.join(" "), batchInterruptedIndex);
|
|
338
331
|
}
|
|
339
332
|
return new ExtrinsicError2(error.toString(), void 0, batchInterruptedIndex);
|
|
340
333
|
}
|
|
@@ -350,11 +343,7 @@ function checkForExtrinsicSuccess(events, client) {
|
|
|
350
343
|
const decoded = client.registry.findMetaError(dispatchError.asModule);
|
|
351
344
|
errorInfo = `${decoded.section}.${decoded.name}`;
|
|
352
345
|
}
|
|
353
|
-
reject(
|
|
354
|
-
new Error(
|
|
355
|
-
`${event.section}.${event.method}:: ExtrinsicFailed:: ${errorInfo}`
|
|
356
|
-
)
|
|
357
|
-
);
|
|
346
|
+
reject(new Error(`${event.section}.${event.method}:: ExtrinsicFailed:: ${errorInfo}`));
|
|
358
347
|
}
|
|
359
348
|
}
|
|
360
349
|
});
|
|
@@ -363,15 +352,26 @@ var JsonExt = class {
|
|
|
363
352
|
static stringify(obj, space) {
|
|
364
353
|
return JSON.stringify(
|
|
365
354
|
obj,
|
|
366
|
-
(_, v) =>
|
|
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
|
+
},
|
|
367
364
|
space
|
|
368
365
|
);
|
|
369
366
|
}
|
|
370
367
|
static parse(str) {
|
|
371
368
|
return JSON.parse(str, (_, v) => {
|
|
372
|
-
if (typeof v === "string" && v.
|
|
369
|
+
if (typeof v === "string" && v.match(/^\d+n$/)) {
|
|
373
370
|
return BigInt(v.slice(0, -1));
|
|
374
371
|
}
|
|
372
|
+
if (typeof v === "object" && v !== null && v.type === "Buffer" && Array.isArray(v.data)) {
|
|
373
|
+
return Buffer.from(v.data);
|
|
374
|
+
}
|
|
375
375
|
return v;
|
|
376
376
|
});
|
|
377
377
|
}
|
|
@@ -502,9 +502,7 @@ BLOCK #${header.number}, ${header.hash.toHuman()}`);
|
|
|
502
502
|
logEvent = true;
|
|
503
503
|
} else if (client.events.liquidityPools.NextBidPoolCapitalLocked.is(event)) {
|
|
504
504
|
const { totalActivatedCapital } = event.data;
|
|
505
|
-
data.totalActivatedCapital = formatArgons(
|
|
506
|
-
totalActivatedCapital.toBigInt()
|
|
507
|
-
);
|
|
505
|
+
data.totalActivatedCapital = formatArgons(totalActivatedCapital.toBigInt());
|
|
508
506
|
logEvent = true;
|
|
509
507
|
}
|
|
510
508
|
} else if (event.section === "bitcoinLocks") {
|
|
@@ -543,10 +541,7 @@ BLOCK #${header.number}, ${header.hash.toHuman()}`);
|
|
|
543
541
|
logEvent = true;
|
|
544
542
|
if (client.events.bitcoinUtxos.UtxoVerified.is(event)) {
|
|
545
543
|
const { utxoId } = event.data;
|
|
546
|
-
const details = await this.getBitcoinLockDetails(
|
|
547
|
-
utxoId.toNumber(),
|
|
548
|
-
blockHash
|
|
549
|
-
);
|
|
544
|
+
const details = await this.getBitcoinLockDetails(utxoId.toNumber(), blockHash);
|
|
550
545
|
this.events.emit("bitcoin-verified", header, {
|
|
551
546
|
utxoId: utxoId.toNumber(),
|
|
552
547
|
vaultId: details.vaultId,
|
|
@@ -582,8 +577,7 @@ BLOCK #${header.number}, ${header.hash.toHuman()}`);
|
|
|
582
577
|
}
|
|
583
578
|
this.events.emit("event", header, event);
|
|
584
579
|
}
|
|
585
|
-
if (reloadVaults.size)
|
|
586
|
-
this.events.emit("vaults-updated", header, reloadVaults);
|
|
580
|
+
if (reloadVaults.size) this.events.emit("vaults-updated", header, reloadVaults);
|
|
587
581
|
const tick = getTickFromHeader(client, header);
|
|
588
582
|
const author = getAuthorFromHeader(client, header);
|
|
589
583
|
this.events.emit(
|
|
@@ -674,10 +668,7 @@ var AccountMiners = (_class5 = class _AccountMiners {
|
|
|
674
668
|
if (author) {
|
|
675
669
|
const voteAuthor = this.trackedAccountsByAddress[author];
|
|
676
670
|
if (voteAuthor && this.options.shouldLog) {
|
|
677
|
-
console.log(
|
|
678
|
-
"> Our vote author",
|
|
679
|
-
this.accountset.accountRegistry.getName(author)
|
|
680
|
-
);
|
|
671
|
+
console.log("> Our vote author", this.accountset.accountRegistry.getName(author));
|
|
681
672
|
}
|
|
682
673
|
} else {
|
|
683
674
|
console.warn("> No vote author found");
|
|
@@ -720,9 +711,7 @@ var AccountMiners = (_class5 = class _AccountMiners {
|
|
|
720
711
|
const { perMiner } = event.data;
|
|
721
712
|
const amountPerMiner = perMiner.toBigInt();
|
|
722
713
|
if (amountPerMiner > 0n) {
|
|
723
|
-
for (const [address, info] of Object.entries(
|
|
724
|
-
this.trackedAccountsByAddress
|
|
725
|
-
)) {
|
|
714
|
+
for (const [address, info] of Object.entries(this.trackedAccountsByAddress)) {
|
|
726
715
|
const { startingFrameId } = info;
|
|
727
716
|
dataByCohort[startingFrameId] ??= {
|
|
728
717
|
argonsMinted: 0n,
|
|
@@ -746,9 +735,7 @@ var AccountMiners = (_class5 = class _AccountMiners {
|
|
|
746
735
|
return dataByCohort;
|
|
747
736
|
}
|
|
748
737
|
newCohortMiners(frameId, addresses) {
|
|
749
|
-
for (const [address, info] of Object.entries(
|
|
750
|
-
this.trackedAccountsByAddress
|
|
751
|
-
)) {
|
|
738
|
+
for (const [address, info] of Object.entries(this.trackedAccountsByAddress)) {
|
|
752
739
|
if (info.startingFrameId === frameId - 10) {
|
|
753
740
|
delete this.trackedAccountsByAddress[address];
|
|
754
741
|
}
|
|
@@ -801,25 +788,17 @@ var Accountset = (_class6 = class {
|
|
|
801
788
|
this.accountRegistry = _nullishCoalesce(options.accountRegistry, () => ( AccountRegistry.factory(options.name)));
|
|
802
789
|
this.client = options.client;
|
|
803
790
|
const defaultRange = _nullishCoalesce(options.subaccountRange, () => ( getDefaultSubaccountRange()));
|
|
804
|
-
this.accountRegistry.register(
|
|
805
|
-
this.seedAddress,
|
|
806
|
-
`${this.accountRegistry.me}//seed`
|
|
807
|
-
);
|
|
791
|
+
this.accountRegistry.register(this.seedAddress, `${this.accountRegistry.me}//seed`);
|
|
808
792
|
for (const i of defaultRange) {
|
|
809
793
|
const pair = this.txSubmitterPair.derive(`//${i}`);
|
|
810
794
|
this.subAccountsByAddress[pair.address] = { pair, index: i };
|
|
811
|
-
this.accountRegistry.register(
|
|
812
|
-
pair.address,
|
|
813
|
-
`${this.accountRegistry.me}//${i}`
|
|
814
|
-
);
|
|
795
|
+
this.accountRegistry.register(pair.address, `${this.accountRegistry.me}//${i}`);
|
|
815
796
|
}
|
|
816
797
|
}
|
|
817
798
|
async submitterBalance(blockHash) {
|
|
818
799
|
const client = await this.client;
|
|
819
800
|
const api = blockHash ? await client.at(blockHash) : client;
|
|
820
|
-
const accountData = await api.query.system.account(
|
|
821
|
-
this.txSubmitterPair.address
|
|
822
|
-
);
|
|
801
|
+
const accountData = await api.query.system.account(this.txSubmitterPair.address);
|
|
823
802
|
return accountData.data.free.toBigInt();
|
|
824
803
|
}
|
|
825
804
|
async balance(blockHash) {
|
|
@@ -978,9 +957,7 @@ var Accountset = (_class6 = class {
|
|
|
978
957
|
const error = dispatchErrorToString(client, cb.dispatchError);
|
|
979
958
|
results.push({
|
|
980
959
|
index,
|
|
981
|
-
failedError: new Error(
|
|
982
|
-
`Error consolidating //${index}: ${error}`
|
|
983
|
-
)
|
|
960
|
+
failedError: new Error(`Error consolidating //${index}: ${error}`)
|
|
984
961
|
});
|
|
985
962
|
resolve();
|
|
986
963
|
}
|
|
@@ -1003,17 +980,11 @@ var Accountset = (_class6 = class {
|
|
|
1003
980
|
{
|
|
1004
981
|
index: "main",
|
|
1005
982
|
address: this.seedAddress,
|
|
1006
|
-
argons: formatArgons(
|
|
1007
|
-
|
|
1008
|
-
),
|
|
1009
|
-
argonots: formatArgons(
|
|
1010
|
-
_nullishCoalesce(_optionalChain([argonots, 'access', _39 => _39.find, 'call', _40 => _40((x) => x.address === this.seedAddress), 'optionalAccess', _41 => _41.amount]), () => ( 0n))
|
|
1011
|
-
)
|
|
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)))
|
|
1012
985
|
}
|
|
1013
986
|
];
|
|
1014
|
-
for (const [address, { index }] of Object.entries(
|
|
1015
|
-
this.subAccountsByAddress
|
|
1016
|
-
)) {
|
|
987
|
+
for (const [address, { index }] of Object.entries(this.subAccountsByAddress)) {
|
|
1017
988
|
const argonAmount = _nullishCoalesce(_optionalChain([argons, 'access', _42 => _42.find, 'call', _43 => _43((x) => x.address === address), 'optionalAccess', _44 => _44.amount]), () => ( 0n));
|
|
1018
989
|
const argonotAmount = _nullishCoalesce(_optionalChain([argonots, 'access', _45 => _45.find, 'call', _46 => _46((x) => x.address === address), 'optionalAccess', _47 => _47.amount]), () => ( 0n));
|
|
1019
990
|
const bid = bids.find((x) => x.address === address);
|
|
@@ -1039,11 +1010,7 @@ var Accountset = (_class6 = class {
|
|
|
1039
1010
|
const keys = this.keys();
|
|
1040
1011
|
for (const [name, key] of Object.entries(keys)) {
|
|
1041
1012
|
console.log("Registering key", name, key.publicKey);
|
|
1042
|
-
const result = await client.rpc.author.insertKey(
|
|
1043
|
-
name,
|
|
1044
|
-
key.privateKey,
|
|
1045
|
-
key.publicKey
|
|
1046
|
-
);
|
|
1013
|
+
const result = await client.rpc.author.insertKey(name, key.privateKey, key.publicKey);
|
|
1047
1014
|
const saved = await client.rpc.author.hasKey(key.publicKey, name);
|
|
1048
1015
|
if (!saved) {
|
|
1049
1016
|
console.error("Failed to register key", name, key.publicKey);
|
|
@@ -1060,9 +1027,7 @@ var Accountset = (_class6 = class {
|
|
|
1060
1027
|
}
|
|
1061
1028
|
const seedMnemonic = _nullishCoalesce(this.sessionKeyMnemonic, () => ( process2.env.KEYS_MNEMONIC));
|
|
1062
1029
|
if (!seedMnemonic) {
|
|
1063
|
-
throw new Error(
|
|
1064
|
-
"KEYS_MNEMONIC environment variable not set. Cannot derive keys."
|
|
1065
|
-
);
|
|
1030
|
+
throw new Error("KEYS_MNEMONIC environment variable not set. Cannot derive keys.");
|
|
1066
1031
|
}
|
|
1067
1032
|
const blockSealKey = `${seedMnemonic}//block-seal//${version}`;
|
|
1068
1033
|
const granKey = `${seedMnemonic}//grandpa//${version}`;
|
|
@@ -1255,31 +1220,25 @@ var MiningBids = (_class7 = class {
|
|
|
1255
1220
|
async watch(accountNames, blockHash, printFn) {
|
|
1256
1221
|
const client = await this.client;
|
|
1257
1222
|
const api = blockHash ? await client.at(blockHash) : client;
|
|
1258
|
-
const unsubscribe = await api.query.miningSlot.bidsForNextSlotCohort(
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
console.
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
this.print();
|
|
1269
|
-
} else {
|
|
1270
|
-
printFn(block.toNumber());
|
|
1271
|
-
}
|
|
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());
|
|
1272
1233
|
}
|
|
1273
|
-
);
|
|
1234
|
+
});
|
|
1274
1235
|
return { unsubscribe };
|
|
1275
1236
|
}
|
|
1276
1237
|
async loadAt(accountNames, blockHash) {
|
|
1277
1238
|
const client = await this.client;
|
|
1278
1239
|
const api = blockHash ? await client.at(blockHash) : client;
|
|
1279
1240
|
const nextCohort = await api.query.miningSlot.bidsForNextSlotCohort();
|
|
1280
|
-
this.nextCohort = await Promise.all(
|
|
1281
|
-
nextCohort.map((x) => this.toBid(accountNames, x))
|
|
1282
|
-
);
|
|
1241
|
+
this.nextCohort = await Promise.all(nextCohort.map((x) => this.toBid(accountNames, x)));
|
|
1283
1242
|
}
|
|
1284
1243
|
async toBid(accountNames, bid) {
|
|
1285
1244
|
return {
|
|
@@ -1305,25 +1264,13 @@ var MiningBids = (_class7 = class {
|
|
|
1305
1264
|
|
|
1306
1265
|
// src/Vault.ts
|
|
1307
1266
|
|
|
1267
|
+
var _bs58check = require('bs58check'); var _bs58check2 = _interopRequireDefault(_bs58check);
|
|
1308
1268
|
var { ROUND_FLOOR: ROUND_FLOOR2 } = BN2;
|
|
1309
|
-
var Vault = (_class8 = class {
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
__init12() {this.argonsScheduledForRelease = /* @__PURE__ */ new Map()}
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1269
|
+
var Vault = (_class8 = class _Vault {
|
|
1322
1270
|
constructor(id, vault, tickDuration) {;_class8.prototype.__init12.call(this);
|
|
1271
|
+
this.tickDuration = tickDuration;
|
|
1323
1272
|
this.securitization = vault.securitization.toBigInt();
|
|
1324
|
-
this.securitizationRatio = convertFixedU128ToBigNumber(
|
|
1325
|
-
vault.securitizationRatio.toBigInt()
|
|
1326
|
-
);
|
|
1273
|
+
this.securitizationRatio = convertFixedU128ToBigNumber(vault.securitizationRatio.toBigInt());
|
|
1327
1274
|
this.argonsLocked = vault.argonsLocked.toBigInt();
|
|
1328
1275
|
this.argonsPendingActivation = vault.argonsPendingActivation.toBigInt();
|
|
1329
1276
|
if (vault.argonsScheduledForRelease.size > 0) {
|
|
@@ -1357,24 +1304,33 @@ var Vault = (_class8 = class {
|
|
|
1357
1304
|
)
|
|
1358
1305
|
};
|
|
1359
1306
|
}
|
|
1360
|
-
this.
|
|
1307
|
+
this.openedTick = vault.openedTick.toNumber();
|
|
1308
|
+
this.openedDate = new Date(this.openedTick * tickDuration);
|
|
1361
1309
|
}
|
|
1310
|
+
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
|
|
1314
|
+
__init12() {this.argonsScheduledForRelease = /* @__PURE__ */ new Map()}
|
|
1315
|
+
|
|
1316
|
+
|
|
1317
|
+
|
|
1318
|
+
|
|
1319
|
+
|
|
1320
|
+
|
|
1321
|
+
|
|
1322
|
+
|
|
1362
1323
|
availableBitcoinSpace() {
|
|
1363
1324
|
const recoverySecuritization = this.recoverySecuritization();
|
|
1364
1325
|
const reLockable = this.getRelockCapacity();
|
|
1365
1326
|
return this.securitization - recoverySecuritization - this.argonsLocked + reLockable;
|
|
1366
1327
|
}
|
|
1367
1328
|
getRelockCapacity() {
|
|
1368
|
-
return [...this.argonsScheduledForRelease.values()].reduce(
|
|
1369
|
-
(acc, val) => acc + val,
|
|
1370
|
-
0n
|
|
1371
|
-
);
|
|
1329
|
+
return [...this.argonsScheduledForRelease.values()].reduce((acc, val) => acc + val, 0n);
|
|
1372
1330
|
}
|
|
1373
1331
|
recoverySecuritization() {
|
|
1374
1332
|
const reserved = new (0, BN.default)(1).div(this.securitizationRatio);
|
|
1375
|
-
return this.securitization - BigInt(
|
|
1376
|
-
reserved.multipliedBy(this.securitization.toString()).toFixed(0, ROUND_FLOOR2)
|
|
1377
|
-
);
|
|
1333
|
+
return this.securitization - BigInt(reserved.multipliedBy(this.securitization.toString()).toFixed(0, ROUND_FLOOR2));
|
|
1378
1334
|
}
|
|
1379
1335
|
minimumSecuritization() {
|
|
1380
1336
|
return BigInt(
|
|
@@ -1387,9 +1343,7 @@ var Vault = (_class8 = class {
|
|
|
1387
1343
|
if (this.securitizationRatio.toNumber() > 2) {
|
|
1388
1344
|
maxRatio = BN.default.call(void 0, 2);
|
|
1389
1345
|
}
|
|
1390
|
-
return BigInt(
|
|
1391
|
-
maxRatio.multipliedBy(activated.toString()).toFixed(0, ROUND_FLOOR2)
|
|
1392
|
-
);
|
|
1346
|
+
return BigInt(maxRatio.multipliedBy(activated.toString()).toFixed(0, ROUND_FLOOR2));
|
|
1393
1347
|
}
|
|
1394
1348
|
/**
|
|
1395
1349
|
* Returns the amount of Argons available to match per liquidity pool
|
|
@@ -1402,6 +1356,65 @@ var Vault = (_class8 = class {
|
|
|
1402
1356
|
const fee = this.terms.bitcoinAnnualPercentRate.multipliedBy(Number(amount)).integerValue(BN.default.ROUND_CEIL);
|
|
1403
1357
|
return BigInt(fee.toString()) + this.terms.bitcoinBaseFee;
|
|
1404
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
|
+
}
|
|
1405
1418
|
}, _class8);
|
|
1406
1419
|
|
|
1407
1420
|
// src/VaultMonitor.ts
|
|
@@ -1452,7 +1465,7 @@ var VaultMonitor = (_class9 = class {
|
|
|
1452
1465
|
const client = await this.mainchain;
|
|
1453
1466
|
this.tickDuration = (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();
|
|
1454
1467
|
const blockHeader = await client.rpc.chain.getHeader();
|
|
1455
|
-
const blockHash = blockHeader.hash
|
|
1468
|
+
const blockHash = Buffer.from(blockHeader.hash);
|
|
1456
1469
|
console.log(
|
|
1457
1470
|
`${justPrint ? "Run" : "Started"} at block ${blockHeader.number} - ${blockHeader.hash.toHuman()}`
|
|
1458
1471
|
);
|
|
@@ -1508,9 +1521,7 @@ var VaultMonitor = (_class9 = class {
|
|
|
1508
1521
|
if (this.shouldLog) {
|
|
1509
1522
|
console.log(`Waiting for vault ${vaultId} to activate ${activationDate}`);
|
|
1510
1523
|
}
|
|
1511
|
-
await new Promise(
|
|
1512
|
-
(resolve) => setTimeout(resolve, activationDate.getTime() - Date.now())
|
|
1513
|
-
);
|
|
1524
|
+
await new Promise((resolve) => setTimeout(resolve, activationDate.getTime() - Date.now()));
|
|
1514
1525
|
const client = await this.mainchain;
|
|
1515
1526
|
let isReady = false;
|
|
1516
1527
|
while (!isReady) {
|
|
@@ -1529,10 +1540,7 @@ var VaultMonitor = (_class9 = class {
|
|
|
1529
1540
|
}
|
|
1530
1541
|
async onVaultsUpdated(blockHash, vaultIds) {
|
|
1531
1542
|
await this.reloadVaultsAt([...vaultIds], blockHash).catch((err) => {
|
|
1532
|
-
console.error(
|
|
1533
|
-
`Failed to reload vault ${[...vaultIds]} at block ${blockHash}:`,
|
|
1534
|
-
err
|
|
1535
|
-
);
|
|
1543
|
+
console.error(`Failed to reload vault ${[...vaultIds]} at block ${blockHash}:`, err);
|
|
1536
1544
|
});
|
|
1537
1545
|
this.printVaults();
|
|
1538
1546
|
}
|
|
@@ -1644,10 +1652,7 @@ var CohortBidderHistory = (_class10 = class _CohortBidderHistory {
|
|
|
1644
1652
|
}
|
|
1645
1653
|
this.stats.seatsWon = winningBids;
|
|
1646
1654
|
this.stats.totalArgonsBid = totalArgonsBid;
|
|
1647
|
-
this.stats.lastBlockNumber = Math.max(
|
|
1648
|
-
blockNumber,
|
|
1649
|
-
this.stats.lastBlockNumber
|
|
1650
|
-
);
|
|
1655
|
+
this.stats.lastBlockNumber = Math.max(blockNumber, this.stats.lastBlockNumber);
|
|
1651
1656
|
const historyEntry = {
|
|
1652
1657
|
cohortStartingFrameId: this.cohortStartingFrameId,
|
|
1653
1658
|
blockNumber,
|
|
@@ -1662,9 +1667,7 @@ var CohortBidderHistory = (_class10 = class _CohortBidderHistory {
|
|
|
1662
1667
|
}
|
|
1663
1668
|
if (hasDiffs) {
|
|
1664
1669
|
nextEntrants.forEach(({ address, bid }, i) => {
|
|
1665
|
-
const prevBidIndex = this.lastBids.findIndex(
|
|
1666
|
-
(y) => y.address === address
|
|
1667
|
-
);
|
|
1670
|
+
const prevBidIndex = this.lastBids.findIndex((y) => y.address === address);
|
|
1668
1671
|
const entry = {
|
|
1669
1672
|
address,
|
|
1670
1673
|
bidAmount: bid,
|
|
@@ -1695,24 +1698,14 @@ var CohortBidderHistory = (_class10 = class _CohortBidderHistory {
|
|
|
1695
1698
|
return historyEntry;
|
|
1696
1699
|
}
|
|
1697
1700
|
onBidResult(historyEntry, param) {
|
|
1698
|
-
const {
|
|
1699
|
-
txFeePlusTip,
|
|
1700
|
-
bidPerSeat,
|
|
1701
|
-
bidsAttempted,
|
|
1702
|
-
successfulBids,
|
|
1703
|
-
blockNumber,
|
|
1704
|
-
bidError
|
|
1705
|
-
} = param;
|
|
1701
|
+
const { txFeePlusTip, bidPerSeat, bidsAttempted, successfulBids, blockNumber, bidError } = param;
|
|
1706
1702
|
this.stats.fees += txFeePlusTip;
|
|
1707
1703
|
this.stats.bidsAttempted += bidsAttempted;
|
|
1708
1704
|
if (bidPerSeat > this.stats.maxBidPerSeat) {
|
|
1709
1705
|
this.stats.maxBidPerSeat = bidPerSeat;
|
|
1710
1706
|
}
|
|
1711
1707
|
if (blockNumber !== void 0) {
|
|
1712
|
-
this.stats.lastBlockNumber = Math.max(
|
|
1713
|
-
blockNumber,
|
|
1714
|
-
this.stats.lastBlockNumber
|
|
1715
|
-
);
|
|
1708
|
+
this.stats.lastBlockNumber = Math.max(blockNumber, this.stats.lastBlockNumber);
|
|
1716
1709
|
}
|
|
1717
1710
|
if (historyEntry.myBidsPlaced) {
|
|
1718
1711
|
historyEntry.myBidsPlaced.failureReason = bidError;
|
|
@@ -1780,14 +1773,12 @@ var CohortBidder = (_class11 = class {
|
|
|
1780
1773
|
if (nextFrameId.toNumber() === this.cohortStartingFrameId && isBiddingOpen.isTrue) {
|
|
1781
1774
|
console.log("Bidding is still open, waiting for it to close");
|
|
1782
1775
|
await new Promise(async (resolve) => {
|
|
1783
|
-
const unsub = await client.query.miningSlot.isNextSlotBiddingOpen(
|
|
1784
|
-
(isOpen)
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
resolve();
|
|
1788
|
-
}
|
|
1776
|
+
const unsub = await client.query.miningSlot.isNextSlotBiddingOpen((isOpen) => {
|
|
1777
|
+
if (isOpen.isFalse) {
|
|
1778
|
+
unsub();
|
|
1779
|
+
resolve();
|
|
1789
1780
|
}
|
|
1790
|
-
);
|
|
1781
|
+
});
|
|
1791
1782
|
});
|
|
1792
1783
|
}
|
|
1793
1784
|
void await this.pendingRequest;
|
|
@@ -1852,14 +1843,9 @@ var CohortBidder = (_class11 = class {
|
|
|
1852
1843
|
const tick = await api.query.ticks.currentTick().then((x) => x.toNumber());
|
|
1853
1844
|
const historyEntry = this.history.trackChange(bids, blockNumber, tick);
|
|
1854
1845
|
if (this.pendingRequest) return;
|
|
1855
|
-
const ticksSinceLastBid = Math.floor(
|
|
1856
|
-
(Date.now() - this.lastBidTime) / this.millisPerTick
|
|
1857
|
-
);
|
|
1846
|
+
const ticksSinceLastBid = Math.floor((Date.now() - this.lastBidTime) / this.millisPerTick);
|
|
1858
1847
|
if (ticksSinceLastBid < this.options.bidDelay) {
|
|
1859
|
-
this.retryTimeout = setTimeout(
|
|
1860
|
-
() => void this.checkCurrentSeats(),
|
|
1861
|
-
this.millisPerTick
|
|
1862
|
-
);
|
|
1848
|
+
this.retryTimeout = setTimeout(() => void this.checkCurrentSeats(), this.millisPerTick);
|
|
1863
1849
|
return;
|
|
1864
1850
|
}
|
|
1865
1851
|
console.log(
|
|
@@ -1907,15 +1893,9 @@ var CohortBidder = (_class11 = class {
|
|
|
1907
1893
|
}
|
|
1908
1894
|
if (nextBid < lowestBid) {
|
|
1909
1895
|
console.log(
|
|
1910
|
-
`Can't bid ${formatArgons(nextBid)}. Current lowest bid is ${formatArgons(
|
|
1911
|
-
lowestBid
|
|
1912
|
-
)}.`
|
|
1913
|
-
);
|
|
1914
|
-
this.history.maybeReducingSeats(
|
|
1915
|
-
winningBids,
|
|
1916
|
-
"MaxBidTooLow" /* MaxBidTooLow */,
|
|
1917
|
-
historyEntry
|
|
1896
|
+
`Can't bid ${formatArgons(nextBid)}. Current lowest bid is ${formatArgons(lowestBid)}.`
|
|
1918
1897
|
);
|
|
1898
|
+
this.history.maybeReducingSeats(winningBids, "MaxBidTooLow" /* MaxBidTooLow */, historyEntry);
|
|
1919
1899
|
return;
|
|
1920
1900
|
}
|
|
1921
1901
|
if (nextBid - lowestBid < MIN_INCREMENT) {
|
|
@@ -1927,11 +1907,7 @@ var CohortBidder = (_class11 = class {
|
|
|
1927
1907
|
maxBid: formatArgons(this.options.maxBid)
|
|
1928
1908
|
}
|
|
1929
1909
|
);
|
|
1930
|
-
this.history.maybeReducingSeats(
|
|
1931
|
-
winningBids,
|
|
1932
|
-
"MaxBidTooLow" /* MaxBidTooLow */,
|
|
1933
|
-
historyEntry
|
|
1934
|
-
);
|
|
1910
|
+
this.history.maybeReducingSeats(winningBids, "MaxBidTooLow" /* MaxBidTooLow */, historyEntry);
|
|
1935
1911
|
return;
|
|
1936
1912
|
}
|
|
1937
1913
|
const seatsInBudget = nextBid === 0n ? this.subaccounts.length : Number(budgetForSeats / nextBid);
|
|
@@ -2000,10 +1976,7 @@ var CohortBidder = (_class11 = class {
|
|
|
2000
1976
|
if (bidError) throw bidError;
|
|
2001
1977
|
} catch (err) {
|
|
2002
1978
|
this.lastBidTime = prevLastBidTime;
|
|
2003
|
-
console.error(
|
|
2004
|
-
`Error bidding for cohort ${this.cohortStartingFrameId}:`,
|
|
2005
|
-
err
|
|
2006
|
-
);
|
|
1979
|
+
console.error(`Error bidding for cohort ${this.cohortStartingFrameId}:`, err);
|
|
2007
1980
|
clearTimeout(this.retryTimeout);
|
|
2008
1981
|
this.retryTimeout = setTimeout(() => void this.checkCurrentSeats(), 1e3);
|
|
2009
1982
|
} finally {
|
|
@@ -2057,11 +2030,7 @@ var BidPool = (_class12 = class {
|
|
|
2057
2030
|
const rawVault = rawVaults[i];
|
|
2058
2031
|
if (rawVault.isNone) continue;
|
|
2059
2032
|
const vaultId = vaultIds[i];
|
|
2060
|
-
this.vaultsById[vaultId] = new Vault(
|
|
2061
|
-
vaultId,
|
|
2062
|
-
rawVault.unwrap(),
|
|
2063
|
-
this.tickDuration
|
|
2064
|
-
);
|
|
2033
|
+
this.vaultsById[vaultId] = new Vault(vaultId, rawVault.unwrap(), this.tickDuration);
|
|
2065
2034
|
}
|
|
2066
2035
|
const vaults = Object.entries(this.vaultsById);
|
|
2067
2036
|
const newSecuritization = [];
|
|
@@ -2084,16 +2053,13 @@ var BidPool = (_class12 = class {
|
|
|
2084
2053
|
}
|
|
2085
2054
|
async getBidPool() {
|
|
2086
2055
|
const client = await this.client;
|
|
2087
|
-
const balanceBytes = await client.rpc.state.call(
|
|
2088
|
-
"MiningSlotApi_bid_pool",
|
|
2089
|
-
""
|
|
2090
|
-
);
|
|
2056
|
+
const balanceBytes = await client.rpc.state.call("MiningSlotApi_bid_pool", "");
|
|
2091
2057
|
const balance = client.createType("U128", balanceBytes);
|
|
2092
2058
|
return balance.toBigInt();
|
|
2093
2059
|
}
|
|
2094
2060
|
async loadAt(blockHash) {
|
|
2095
2061
|
const client = await this.client;
|
|
2096
|
-
blockHash ??= (await client.rpc.chain.getHeader()).hash
|
|
2062
|
+
blockHash ??= Buffer.from((await client.rpc.chain.getHeader()).hash);
|
|
2097
2063
|
const api = await client.at(blockHash);
|
|
2098
2064
|
const rawVaultIds = await api.query.vaults.vaultsById.keys();
|
|
2099
2065
|
const vaultIds = rawVaultIds.map((x) => x.args[0].toNumber());
|
|
@@ -2105,22 +2071,14 @@ var BidPool = (_class12 = class {
|
|
|
2105
2071
|
this.loadFrameData(FrameIdNumber, funds);
|
|
2106
2072
|
}
|
|
2107
2073
|
for (const entrant of await api.query.liquidityPools.capitalActive()) {
|
|
2108
|
-
this.setVaultFrameData(
|
|
2109
|
-
entrant.
|
|
2110
|
-
|
|
2111
|
-
{
|
|
2112
|
-
activatedCapital: entrant.activatedCapital.toBigInt()
|
|
2113
|
-
}
|
|
2114
|
-
);
|
|
2074
|
+
this.setVaultFrameData(entrant.frameId.toNumber(), entrant.vaultId.toNumber(), {
|
|
2075
|
+
activatedCapital: entrant.activatedCapital.toBigInt()
|
|
2076
|
+
});
|
|
2115
2077
|
}
|
|
2116
2078
|
for (const entrant of await api.query.liquidityPools.capitalRaising()) {
|
|
2117
|
-
this.setVaultFrameData(
|
|
2118
|
-
entrant.
|
|
2119
|
-
|
|
2120
|
-
{
|
|
2121
|
-
activatedCapital: entrant.activatedCapital.toBigInt()
|
|
2122
|
-
}
|
|
2123
|
-
);
|
|
2079
|
+
this.setVaultFrameData(entrant.frameId.toNumber(), entrant.vaultId.toNumber(), {
|
|
2080
|
+
activatedCapital: entrant.activatedCapital.toBigInt()
|
|
2081
|
+
});
|
|
2124
2082
|
}
|
|
2125
2083
|
await this.onVaultsUpdated(blockHash, new Set(vaultIds));
|
|
2126
2084
|
this.print();
|
|
@@ -2128,10 +2086,7 @@ var BidPool = (_class12 = class {
|
|
|
2128
2086
|
async watch() {
|
|
2129
2087
|
await this.loadAt();
|
|
2130
2088
|
await this.blockWatch.start();
|
|
2131
|
-
this.blockWatch.events.on(
|
|
2132
|
-
"vaults-updated",
|
|
2133
|
-
(b, v) => this.onVaultsUpdated(b.hash, v)
|
|
2134
|
-
);
|
|
2089
|
+
this.blockWatch.events.on("vaults-updated", (b, v) => this.onVaultsUpdated(b.hash, v));
|
|
2135
2090
|
const api = await this.client;
|
|
2136
2091
|
this.blockWatch.events.on("event", async (_, event) => {
|
|
2137
2092
|
if (api.events.liquidityPools.BidPoolDistributed.is(event)) {
|
|
@@ -2166,25 +2121,13 @@ var BidPool = (_class12 = class {
|
|
|
2166
2121
|
api.query.liquidityPools.capitalActive,
|
|
2167
2122
|
api.query.liquidityPools.capitalRaising
|
|
2168
2123
|
],
|
|
2169
|
-
async ([
|
|
2170
|
-
_bids,
|
|
2171
|
-
nextFrameId,
|
|
2172
|
-
openVaultBidPoolCapital,
|
|
2173
|
-
nextPoolCapital
|
|
2174
|
-
]) => {
|
|
2124
|
+
async ([_bids, nextFrameId, openVaultBidPoolCapital, nextPoolCapital]) => {
|
|
2175
2125
|
this.bidPoolAmount = await this.getBidPool();
|
|
2176
2126
|
this.nextFrameId = nextFrameId.toNumber();
|
|
2177
|
-
for (const entrant of [
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
this.setVaultFrameData(
|
|
2182
|
-
entrant.frameId.toNumber(),
|
|
2183
|
-
entrant.vaultId.toNumber(),
|
|
2184
|
-
{
|
|
2185
|
-
activatedCapital: entrant.activatedCapital.toBigInt()
|
|
2186
|
-
}
|
|
2187
|
-
);
|
|
2127
|
+
for (const entrant of [...openVaultBidPoolCapital, ...nextPoolCapital]) {
|
|
2128
|
+
this.setVaultFrameData(entrant.frameId.toNumber(), entrant.vaultId.toNumber(), {
|
|
2129
|
+
activatedCapital: entrant.activatedCapital.toBigInt()
|
|
2130
|
+
});
|
|
2188
2131
|
}
|
|
2189
2132
|
this.printDebounce();
|
|
2190
2133
|
}
|
|
@@ -2338,10 +2281,7 @@ Raising Funds (Frame ${this.nextFrameId + 1}):`);
|
|
|
2338
2281
|
this.poolVaultCapitalByFrame[frameId][vaultId] ??= {
|
|
2339
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))
|
|
2340
2283
|
};
|
|
2341
|
-
Object.assign(
|
|
2342
|
-
this.poolVaultCapitalByFrame[frameId][vaultId],
|
|
2343
|
-
filterUndefined(data)
|
|
2344
|
-
);
|
|
2284
|
+
Object.assign(this.poolVaultCapitalByFrame[frameId][vaultId], filterUndefined(data));
|
|
2345
2285
|
}
|
|
2346
2286
|
createBondCapitalTable(total, contributors, title = "Total") {
|
|
2347
2287
|
const table = new (0, _consoletableprinter.Table)({
|
|
@@ -2380,9 +2320,7 @@ Raising Funds (Frame ${this.nextFrameId + 1}):`);
|
|
|
2380
2320
|
}
|
|
2381
2321
|
this.setVaultFrameData(frameId, vaultIdNumber, {
|
|
2382
2322
|
earnings: fund.distributedProfits.isSome ? fund.distributedProfits.unwrap().toBigInt() : void 0,
|
|
2383
|
-
vaultSharingPercent: convertPermillToBigNumber(
|
|
2384
|
-
fund.vaultSharingPercent.toBigInt()
|
|
2385
|
-
),
|
|
2323
|
+
vaultSharingPercent: convertPermillToBigNumber(fund.vaultSharingPercent.toBigInt()),
|
|
2386
2324
|
contributors
|
|
2387
2325
|
});
|
|
2388
2326
|
}
|
|
@@ -2395,58 +2333,418 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2395
2333
|
constructor(client) {
|
|
2396
2334
|
this.client = client;
|
|
2397
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
|
+
}
|
|
2398
2345
|
async getMarketRate(satoshis) {
|
|
2399
2346
|
const client = await this.client;
|
|
2400
2347
|
const sats = client.createType("U64", satoshis.toString());
|
|
2401
|
-
const marketRate = await client.rpc.state.call(
|
|
2402
|
-
"BitcoinApis_market_rate",
|
|
2403
|
-
sats.toHex(true)
|
|
2404
|
-
);
|
|
2348
|
+
const marketRate = await client.rpc.state.call("BitcoinApis_market_rate", sats.toHex(true));
|
|
2405
2349
|
const rate = client.createType("Option<U128>", marketRate);
|
|
2406
2350
|
if (!rate.isSome) {
|
|
2407
2351
|
throw new Error("Market rate not available");
|
|
2408
2352
|
}
|
|
2409
2353
|
return rate.value.toBigInt();
|
|
2410
2354
|
}
|
|
2411
|
-
async
|
|
2412
|
-
const
|
|
2413
|
-
|
|
2414
|
-
const
|
|
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() {
|
|
2415
2375
|
const client = await this.client;
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
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,
|
|
2424
2470
|
vaultId,
|
|
2425
|
-
|
|
2426
|
-
|
|
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
|
|
2427
2589
|
);
|
|
2428
|
-
const
|
|
2429
|
-
const
|
|
2430
|
-
const
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
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
|
+
);
|
|
2439
2601
|
}
|
|
2440
|
-
|
|
2441
|
-
|
|
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)
|
|
2442
2719
|
);
|
|
2443
|
-
|
|
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
|
+
};
|
|
2444
2741
|
}
|
|
2445
2742
|
static async waitForSpace(accountset, options) {
|
|
2446
2743
|
const { argonAmount, bitcoinXpub, maxLockFee, tip = 0n } = options;
|
|
2447
2744
|
const vaults = new VaultMonitor(accountset, {
|
|
2448
2745
|
bitcoinSpaceAvailable: argonAmount
|
|
2449
2746
|
});
|
|
2747
|
+
const bitcoinXpubBuffer = Buffer.from(bitcoinXpub.replace(/^0x(.+)/, "$1"), "hex");
|
|
2450
2748
|
return new Promise(async (resolve, reject) => {
|
|
2451
2749
|
vaults.events.on("bitcoin-space-above", async (vaultId, amount) => {
|
|
2452
2750
|
const vault = vaults.vaultsById[vaultId];
|
|
@@ -2462,27 +2760,23 @@ var BitcoinLocks = class _BitcoinLocks {
|
|
|
2462
2760
|
}
|
|
2463
2761
|
try {
|
|
2464
2762
|
const bitcoinLock = new _BitcoinLocks(accountset.client);
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
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,
|
|
2470
2770
|
tip
|
|
2471
2771
|
});
|
|
2472
|
-
const result = await accountset.tx(tx).then((x) => x.submit({ waitForBlock: true, tip }));
|
|
2473
|
-
const client = await accountset.client;
|
|
2474
|
-
const utxoId = _optionalChain([result, 'access', _67 => _67.events, 'access', _68 => _68.find, 'call', _69 => _69((x) => client.events.bitcoinLocks.BitcoinLockCreated.is(x)), 'optionalAccess', _70 => _70.data, 'access', _71 => _71.utxoId, 'optionalAccess', _72 => _72.toNumber, 'call', _73 => _73()]);
|
|
2475
|
-
if (!utxoId) {
|
|
2476
|
-
throw new Error("Failed to find UTXO ID");
|
|
2477
|
-
}
|
|
2478
2772
|
resolve({
|
|
2479
2773
|
satoshis,
|
|
2480
2774
|
argons: argonAmount,
|
|
2481
2775
|
vaultId,
|
|
2482
|
-
|
|
2483
|
-
txFee,
|
|
2484
|
-
finalizedPromise:
|
|
2485
|
-
utxoId
|
|
2776
|
+
securityFee,
|
|
2777
|
+
txFee: txResult.finalFee,
|
|
2778
|
+
finalizedPromise: txResult.finalizedPromise,
|
|
2779
|
+
utxoId: lock.utxoId
|
|
2486
2780
|
});
|
|
2487
2781
|
} catch (err) {
|
|
2488
2782
|
console.error("Error submitting bitcoin lock tx:", err);
|
|
@@ -2515,7 +2809,7 @@ async function waitForLoad() {
|
|
|
2515
2809
|
}
|
|
2516
2810
|
async function getClient(host) {
|
|
2517
2811
|
let provider;
|
|
2518
|
-
if (host.startsWith("http
|
|
2812
|
+
if (host.startsWith("http")) {
|
|
2519
2813
|
provider = new (0, _api.HttpProvider)(host);
|
|
2520
2814
|
} else {
|
|
2521
2815
|
provider = new (0, _api.WsProvider)(host);
|
|
@@ -2563,5 +2857,9 @@ async function getClient(host) {
|
|
|
2563
2857
|
|
|
2564
2858
|
|
|
2565
2859
|
|
|
2566
|
-
|
|
2567
|
-
|
|
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
|