@argonprotocol/mainchain 1.3.7 → 1.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,102 +1,1133 @@
1
+ // src/interfaces/augment-api-consts.ts
2
+ import "@polkadot/api-base/types/consts";
3
+
4
+ // src/interfaces/augment-api-errors.ts
5
+ import "@polkadot/api-base/types/errors";
6
+
7
+ // src/interfaces/augment-api-events.ts
8
+ import "@polkadot/api-base/types/events";
9
+
10
+ // src/interfaces/augment-api-query.ts
11
+ import "@polkadot/api-base/types/storage";
12
+
13
+ // src/interfaces/augment-api-tx.ts
14
+ import "@polkadot/api-base/types/submittable";
15
+
16
+ // src/interfaces/augment-api-rpc.ts
17
+ import "@polkadot/rpc-core/types/jsonrpc";
18
+
19
+ // src/interfaces/augment-api-runtime.ts
20
+ import "@polkadot/api-base/types/calls";
21
+
22
+ // src/interfaces/augment-types.ts
23
+ import "@polkadot/types/types/registry";
24
+
25
+ // src/index.ts
26
+ import { ApiPromise, HttpProvider, Keyring, WsProvider } from "@polkadot/api";
27
+ import { cryptoWaitReady, decodeAddress, mnemonicGenerate } from "@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: new Uint8Array(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
+ const json = result.status.toJSON();
87
+ const status = Object.keys(json)[0];
88
+ console.debug('Transaction update: "%s"', status, json[status]);
89
+ }
90
+ var TxSubmitter = class {
91
+ constructor(client, tx, pair) {
92
+ this.client = client;
93
+ this.tx = tx;
94
+ this.pair = pair;
95
+ }
96
+ async feeEstimate(tip) {
97
+ const { partialFee } = await this.tx.paymentInfo(this.pair, { tip });
98
+ return partialFee.toBigInt();
99
+ }
100
+ async canAfford(options = {}) {
101
+ const { tip, unavailableBalance } = options;
102
+ const account = await this.client.query.system.account(this.pair.address);
103
+ let availableBalance = account.data.free.toBigInt();
104
+ const userBalance = availableBalance;
105
+ if (unavailableBalance) {
106
+ availableBalance -= unavailableBalance;
107
+ }
108
+ const existentialDeposit = options.includeExistentialDeposit ? this.client.consts.balances.existentialDeposit.toBigInt() : 0n;
109
+ const fees = await this.feeEstimate(tip);
110
+ const totalCharge = fees + (tip ?? 0n);
111
+ const canAfford = availableBalance >= totalCharge + existentialDeposit;
112
+ return { canAfford, availableBalance: userBalance, txFee: fees };
113
+ }
114
+ async submit(options = {}) {
115
+ const { logResults, waitForBlock, useLatestNonce, ...apiOptions } = options;
116
+ await waitForLoad();
117
+ const result = new TxResult(this.client, logResults);
118
+ result.txProgressCallback = options.txProgressCallback;
119
+ let toHuman = this.tx.toHuman().method;
120
+ const txString = [];
121
+ let api = formatCall(toHuman);
122
+ const args = [];
123
+ if (api === "proxy.proxy") {
124
+ toHuman = toHuman.args.call;
125
+ txString.push("Proxy");
126
+ api = formatCall(toHuman);
127
+ }
128
+ if (api.startsWith("utility.batch")) {
129
+ const calls = toHuman.args.calls.map(formatCall).join(", ");
130
+ txString.push(`Batch[${calls}]`);
131
+ } else {
132
+ txString.push(api);
133
+ args.push(toHuman.args);
134
+ }
135
+ args.unshift(txString.join("->"));
136
+ if (useLatestNonce && !apiOptions.nonce) {
137
+ apiOptions.nonce = await this.client.rpc.system.accountNextIndex(this.pair.address);
138
+ }
139
+ console.log("Submitting transaction from %s:", this.pair.address, ...args);
140
+ await this.tx.signAndSend(this.pair, apiOptions, result.onResult.bind(result));
141
+ if (waitForBlock) {
142
+ await result.inBlockPromise;
143
+ }
144
+ return result;
145
+ }
146
+ };
147
+ function formatCall(call) {
148
+ return `${call.section}.${call.method}`;
149
+ }
150
+ var TxResult = class {
151
+ constructor(client, shouldLog = false) {
152
+ this.client = client;
153
+ this.shouldLog = shouldLog;
154
+ this.inBlockPromise = new Promise((resolve, reject) => {
155
+ this.inBlockResolve = resolve;
156
+ this.inBlockReject = reject;
157
+ });
158
+ this.finalizedPromise = new Promise((resolve, reject) => {
159
+ this.finalizedResolve = resolve;
160
+ this.finalizedReject = reject;
161
+ });
162
+ this.inBlockPromise.catch(() => null);
163
+ this.finalizedPromise.catch(() => null);
164
+ }
165
+ inBlockPromise;
166
+ finalizedPromise;
167
+ status;
168
+ events = [];
169
+ /**
170
+ * The index of the batch that was interrupted, if any.
171
+ */
172
+ batchInterruptedIndex;
173
+ includedInBlock;
174
+ /**
175
+ * The final fee paid for the transaction, including the fee tip.
176
+ */
177
+ finalFee;
178
+ /**
179
+ * The fee tip paid for the transaction.
180
+ */
181
+ finalFeeTip;
182
+ txProgressCallback;
183
+ inBlockResolve;
184
+ inBlockReject;
185
+ finalizedResolve;
186
+ finalizedReject;
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 = new Uint8Array(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(new Uint8Array(status.asInBlock));
215
+ }
216
+ }
217
+ if (isFinalized) {
218
+ this.finalizedResolve(status.asFinalized);
219
+ }
220
+ if (this.txProgressCallback) {
221
+ let percent = 0;
222
+ if (result.status.isBroadcast) {
223
+ percent = 50;
224
+ } else if (result.status.isInBlock) {
225
+ percent = 100;
226
+ }
227
+ this.txProgressCallback(percent, this);
228
+ }
229
+ }
230
+ reject(error) {
231
+ this.inBlockReject(error);
232
+ this.finalizedReject(error);
233
+ }
234
+ };
235
+
236
+ // src/utils.ts
237
+ import BigNumber, * as BN from "bignumber.js";
238
+ var { ROUND_FLOOR } = BN;
239
+ var MICROGONS_PER_ARGON = 1e6;
240
+ function formatArgons(microgons) {
241
+ if (microgons === void 0 || microgons === null) return "na";
242
+ const isNegative = microgons < 0;
243
+ let format = BigNumber(microgons.toString()).abs().div(MICROGONS_PER_ARGON).toFormat(2, ROUND_FLOOR);
244
+ if (format.endsWith(".00")) {
245
+ format = format.slice(0, -3);
246
+ }
247
+ return `${isNegative ? "-" : ""}\u20B3${format}`;
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 dispatchErrorToString(client, error) {
275
+ let message = error.toString();
276
+ if (error.isModule) {
277
+ const decoded = client.registry.findMetaError(error.asModule);
278
+ const { docs, name, section } = decoded;
279
+ message = `${section}.${name}: ${docs.join(" ")}`;
280
+ }
281
+ return message;
282
+ }
283
+ var ExtrinsicError2 = class extends Error {
284
+ constructor(errorCode, details, batchInterruptedIndex) {
285
+ super(errorCode);
286
+ this.errorCode = errorCode;
287
+ this.details = details;
288
+ this.batchInterruptedIndex = batchInterruptedIndex;
289
+ }
290
+ toString() {
291
+ if (this.batchInterruptedIndex !== void 0) {
292
+ return `${this.errorCode} ${this.details ?? ""} (Batch interrupted at index ${this.batchInterruptedIndex})`;
293
+ }
294
+ return `${this.errorCode} ${this.details ?? ""}`;
295
+ }
296
+ };
297
+ function dispatchErrorToExtrinsicError(client, error, batchInterruptedIndex) {
298
+ if (error.isModule) {
299
+ const decoded = client.registry.findMetaError(error.asModule);
300
+ const { docs, name, section } = decoded;
301
+ return new ExtrinsicError2(`${section}.${name}`, docs.join(" "), batchInterruptedIndex);
302
+ }
303
+ return new ExtrinsicError2(error.toString(), void 0, batchInterruptedIndex);
304
+ }
305
+ function checkForExtrinsicSuccess(events, client) {
306
+ return new Promise((resolve, reject) => {
307
+ for (const { event } of events) {
308
+ if (client.events.system.ExtrinsicSuccess.is(event)) {
309
+ resolve();
310
+ } else if (client.events.system.ExtrinsicFailed.is(event)) {
311
+ const [dispatchError] = event.data;
312
+ let errorInfo = dispatchError.toString();
313
+ if (dispatchError.isModule) {
314
+ const decoded = client.registry.findMetaError(dispatchError.asModule);
315
+ errorInfo = `${decoded.section}.${decoded.name}`;
316
+ }
317
+ reject(new Error(`${event.section}.${event.method}:: ExtrinsicFailed:: ${errorInfo}`));
318
+ }
319
+ }
320
+ });
321
+ }
322
+
323
+ // src/keyringUtils.ts
324
+ function keyringFromSuri(suri, cryptoType = "sr25519") {
325
+ return new Keyring({ type: cryptoType }).createFromUri(suri);
326
+ }
327
+ function createKeyringPair(opts) {
328
+ const { cryptoType } = opts;
329
+ const seed = mnemonicGenerate();
330
+ return keyringFromSuri(seed, cryptoType);
331
+ }
332
+
333
+ // src/header.ts
334
+ function getTickFromHeader(client, header) {
335
+ for (const x of header.digest.logs) {
336
+ if (x.isPreRuntime) {
337
+ const [engineId, data] = x.asPreRuntime;
338
+ if (engineId.toString() === "aura") {
339
+ return client.createType("u64", data).toNumber();
340
+ }
341
+ }
342
+ }
343
+ return void 0;
344
+ }
345
+ function getAuthorFromHeader(client, header) {
346
+ for (const x of header.digest.logs) {
347
+ if (x.isPreRuntime) {
348
+ const [engineId, data] = x.asPreRuntime;
349
+ if (engineId.toString() === "pow_") {
350
+ return client.createType("AccountId32", data).toHuman();
351
+ }
352
+ }
353
+ }
354
+ return void 0;
355
+ }
356
+
357
+ // src/Vault.ts
358
+ import BigNumber2, * as BN2 from "bignumber.js";
359
+ import bs58check from "bs58check";
360
+ import { hexToU8a } from "@polkadot/util";
361
+ var { ROUND_FLOOR: ROUND_FLOOR2 } = BN2;
362
+ var Vault = class _Vault {
363
+ constructor(id, vault, tickDuration) {
364
+ this.tickDuration = tickDuration;
365
+ this.vaultId = id;
366
+ this.openedTick = vault.openedTick.toNumber();
367
+ this.openedDate = new Date(this.openedTick * this.tickDuration);
368
+ this.argonsScheduledForRelease = /* @__PURE__ */ new Map();
369
+ this.load(vault);
370
+ }
371
+ securitization;
372
+ argonsLocked;
373
+ argonsPendingActivation;
374
+ argonsScheduledForRelease;
375
+ terms;
376
+ operatorAccountId;
377
+ isClosed;
378
+ vaultId;
379
+ pendingTerms;
380
+ pendingTermsChangeTick;
381
+ openedDate;
382
+ openedTick;
383
+ securitizationRatio;
384
+ load(vault) {
385
+ this.securitization = vault.securitization.toBigInt();
386
+ this.securitizationRatio = fromFixedNumber(
387
+ vault.securitizationRatio.toBigInt(),
388
+ FIXED_U128_DECIMALS
389
+ ).toNumber();
390
+ this.argonsLocked = vault.argonsLocked.toBigInt();
391
+ this.argonsPendingActivation = vault.argonsPendingActivation.toBigInt();
392
+ if (vault.argonsScheduledForRelease.size > 0) {
393
+ this.argonsScheduledForRelease.clear();
394
+ for (const [tick, amount] of vault.argonsScheduledForRelease.entries()) {
395
+ this.argonsScheduledForRelease.set(tick.toNumber(), amount.toBigInt());
396
+ }
397
+ }
398
+ this.terms = {
399
+ bitcoinAnnualPercentRate: fromFixedNumber(
400
+ vault.terms.bitcoinAnnualPercentRate.toBigInt(),
401
+ FIXED_U128_DECIMALS
402
+ ),
403
+ bitcoinBaseFee: vault.terms.bitcoinBaseFee.toBigInt(),
404
+ treasuryProfitSharing: fromFixedNumber(
405
+ vault.terms.treasuryProfitSharing.toBigInt(),
406
+ PERMILL_DECIMALS
407
+ )
408
+ };
409
+ this.operatorAccountId = vault.operatorAccountId.toString();
410
+ this.isClosed = vault.isClosed.valueOf();
411
+ if (vault.pendingTerms.isSome) {
412
+ const [tickApply, terms] = vault.pendingTerms.value;
413
+ this.pendingTermsChangeTick = tickApply.toNumber();
414
+ this.pendingTerms = {
415
+ bitcoinAnnualPercentRate: fromFixedNumber(
416
+ terms.bitcoinAnnualPercentRate.toBigInt(),
417
+ FIXED_U128_DECIMALS
418
+ ),
419
+ bitcoinBaseFee: terms.bitcoinBaseFee.toBigInt(),
420
+ treasuryProfitSharing: fromFixedNumber(
421
+ vault.terms.treasuryProfitSharing.toBigInt(),
422
+ PERMILL_DECIMALS
423
+ )
424
+ };
425
+ }
426
+ }
427
+ availableBitcoinSpace() {
428
+ const recoverySecuritization = this.recoverySecuritization();
429
+ const reLockable = this.getRelockCapacity();
430
+ return this.securitization - recoverySecuritization - this.argonsLocked + reLockable;
431
+ }
432
+ getRelockCapacity() {
433
+ return [...this.argonsScheduledForRelease.values()].reduce((acc, val) => acc + val, 0n);
434
+ }
435
+ securitizationRatioBN() {
436
+ return new BigNumber2(this.securitizationRatio);
437
+ }
438
+ recoverySecuritization() {
439
+ const reserved = new BigNumber2(1).div(this.securitizationRatioBN());
440
+ return this.securitization - BigInt(reserved.multipliedBy(this.securitization.toString()).toFixed(0, ROUND_FLOOR2));
441
+ }
442
+ minimumSecuritization() {
443
+ return BigInt(
444
+ this.securitizationRatioBN().multipliedBy(this.argonsLocked.toString()).decimalPlaces(0, BigNumber2.ROUND_CEIL).toString()
445
+ );
446
+ }
447
+ activatedSecuritization() {
448
+ const activated = this.argonsLocked - this.argonsPendingActivation;
449
+ const maxRatio = BigNumber2(Math.min(this.securitizationRatio, 2));
450
+ return BigInt(maxRatio.multipliedBy(activated.toString()).toFixed(0, ROUND_FLOOR2));
451
+ }
452
+ /**
453
+ * Returns the amount of Argons available to match per treasury pool
454
+ */
455
+ activatedSecuritizationPerSlot() {
456
+ const activated = this.activatedSecuritization();
457
+ return activated / 10n;
458
+ }
459
+ calculateBitcoinFee(amount) {
460
+ const fee = this.terms.bitcoinAnnualPercentRate.multipliedBy(Number(amount)).integerValue(BigNumber2.ROUND_CEIL);
461
+ return BigInt(fee.toString()) + this.terms.bitcoinBaseFee;
462
+ }
463
+ static async get(client, vaultId, tickDurationMillis) {
464
+ const rawVault = await client.query.vaults.vaultsById(vaultId);
465
+ if (rawVault.isNone) {
466
+ throw new Error(`Vault with id ${vaultId} not found`);
467
+ }
468
+ const tickDuration = tickDurationMillis ?? await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
469
+ return new _Vault(vaultId, rawVault.unwrap(), tickDuration);
470
+ }
471
+ static async create(client, keypair, args, config = {}) {
472
+ const {
473
+ securitization,
474
+ securitizationRatio,
475
+ annualPercentRate,
476
+ baseFee,
477
+ bitcoinXpub,
478
+ tip,
479
+ doNotExceedBalance,
480
+ txProgressCallback
481
+ } = args;
482
+ let xpubBytes = hexToU8a(bitcoinXpub);
483
+ if (xpubBytes.length !== 78) {
484
+ if (bitcoinXpub.startsWith("xpub") || bitcoinXpub.startsWith("tpub") || bitcoinXpub.startsWith("zpub")) {
485
+ const bytes = bs58check.decode(bitcoinXpub);
486
+ if (bytes.length !== 78) {
487
+ throw new Error("Invalid Bitcoin xpub key length, must be 78 bytes");
488
+ }
489
+ xpubBytes = bytes;
490
+ }
491
+ }
492
+ const vaultParams = {
493
+ terms: {
494
+ // convert to fixed u128
495
+ bitcoinAnnualPercentRate: toFixedNumber(annualPercentRate, FIXED_U128_DECIMALS),
496
+ bitcoinBaseFee: BigInt(baseFee),
497
+ treasuryProfitSharing: toFixedNumber(args.treasuryProfitSharing, PERMILL_DECIMALS)
498
+ },
499
+ securitizationRatio: toFixedNumber(securitizationRatio, FIXED_U128_DECIMALS),
500
+ securitization: BigInt(securitization),
501
+ bitcoinXpubkey: xpubBytes
502
+ };
503
+ const tx = new TxSubmitter(client, client.tx.vaults.create(vaultParams), keypair);
504
+ if (doNotExceedBalance) {
505
+ const finalTip = tip ?? 0n;
506
+ let txFee = await tx.feeEstimate(finalTip);
507
+ while (txFee + finalTip + vaultParams.securitization > doNotExceedBalance) {
508
+ vaultParams.securitization = doNotExceedBalance - txFee - finalTip;
509
+ tx.tx = client.tx.vaults.create(vaultParams);
510
+ txFee = await tx.feeEstimate(finalTip);
511
+ }
512
+ }
513
+ const canAfford = await tx.canAfford({ tip, unavailableBalance: BigInt(securitization) });
514
+ if (!canAfford.canAfford) {
515
+ throw new Error(
516
+ `Insufficient balance to create vault. Required: ${formatArgons(securitization)}, Available: ${formatArgons(canAfford.availableBalance)}`
517
+ );
518
+ }
519
+ const result = await tx.submit({
520
+ tip,
521
+ useLatestNonce: true,
522
+ waitForBlock: true,
523
+ txProgressCallback
524
+ });
525
+ await result.inBlockPromise;
526
+ let vaultId;
527
+ for (const event of result.events) {
528
+ if (client.events.vaults.VaultCreated.is(event)) {
529
+ vaultId = event.data.vaultId.toNumber();
530
+ break;
531
+ }
532
+ }
533
+ if (vaultId === void 0) {
534
+ throw new Error("Vault creation failed, no VaultCreated event found");
535
+ }
536
+ const rawVault = await client.query.vaults.vaultsById(vaultId);
537
+ if (rawVault.isNone) {
538
+ throw new Error("Vault creation failed, vault not found");
539
+ }
540
+ const tickDuration = config.tickDurationMillis ?? await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
541
+ const vault = new _Vault(vaultId, rawVault.unwrap(), tickDuration);
542
+ return { vault, txResult: result };
543
+ }
544
+ };
545
+
546
+ // src/convert.ts
547
+ import BigNumber3 from "bignumber.js";
548
+ function toFixedNumber(value, decimals) {
549
+ const factor = new BigNumber3(10).pow(decimals);
550
+ const bn = new BigNumber3(value);
551
+ const int = bn.times(factor).integerValue(BigNumber3.ROUND_DOWN);
552
+ return BigInt(int.toFixed(0));
553
+ }
554
+ function fromFixedNumber(value, decimals = FIXED_U128_DECIMALS) {
555
+ const factor = new BigNumber3(10).pow(decimals);
556
+ const bn = new BigNumber3(value.toString());
557
+ return bn.div(factor);
558
+ }
559
+ var FIXED_U128_DECIMALS = 18;
560
+ var PERMILL_DECIMALS = 6;
561
+
562
+ // src/BitcoinLocks.ts
563
+ import { u8aToHex } from "@polkadot/util";
564
+ var SATS_PER_BTC = 100000000n;
565
+ var BitcoinLocks = class {
566
+ constructor(client) {
567
+ this.client = client;
568
+ }
569
+ async getUtxoIdFromEvents(events) {
570
+ for (const event of events) {
571
+ if (this.client.events.bitcoinLocks.BitcoinLockCreated.is(event)) {
572
+ return event.data.utxoId.toNumber();
573
+ }
574
+ }
575
+ return void 0;
576
+ }
577
+ async getMarketRate(priceIndex, satoshis) {
578
+ return priceIndex.getBtcMicrogonPrice(satoshis);
579
+ }
580
+ async getRedemptionRate(priceIndex, details) {
581
+ const { satoshis, peggedPrice } = details;
582
+ const satsPerArgon = Number(SATS_PER_BTC) / MICROGONS_PER_ARGON;
583
+ let price = Number(priceIndex.btcUsdPrice);
584
+ price = price / satsPerArgon * Number(satoshis);
585
+ if (peggedPrice !== void 0 && peggedPrice < price) {
586
+ price = Number(peggedPrice);
587
+ }
588
+ const r = Number(priceIndex.rValue);
589
+ let multiplier;
590
+ if (r >= 1) {
591
+ multiplier = 1;
592
+ } else if (r >= 0.9) {
593
+ multiplier = 20 * (r * r) - 38 * r + 19;
594
+ } else if (r >= 0.01) {
595
+ multiplier = (0.5618 * r + 0.3944) / r;
596
+ } else {
597
+ multiplier = 1 / r * (0.576 * r + 0.4);
598
+ }
599
+ return BigInt(Math.floor(price * multiplier));
600
+ }
601
+ async getMarketRateApi(satoshis) {
602
+ const client = this.client;
603
+ const sats = client.createType("U64", satoshis.toString());
604
+ const marketRate = await client.rpc.state.call("BitcoinApis_market_rate", sats.toHex(true));
605
+ const rate = client.createType("Option<U128>", marketRate);
606
+ if (!rate.isSome) {
607
+ throw new Error("Market rate not available");
608
+ }
609
+ return rate.value.toBigInt();
610
+ }
611
+ async getRedemptionRateApi(satoshis) {
612
+ const client = this.client;
613
+ const sats = client.createType("U64", satoshis.toString());
614
+ const marketRate = await client.rpc.state.call("BitcoinApis_redemption_rate", sats.toHex(true));
615
+ const rate = client.createType("Option<U128>", marketRate);
616
+ if (!rate.isSome) {
617
+ throw new Error("Redemption rate not available");
618
+ }
619
+ return rate.value.toBigInt();
620
+ }
621
+ async getConfig() {
622
+ const client = this.client;
623
+ const bitcoinNetwork = await client.query.bitcoinUtxos.bitcoinNetwork();
624
+ return {
625
+ lockReleaseCosignDeadlineFrames: client.consts.bitcoinLocks.lockReleaseCosignDeadlineFrames.toNumber(),
626
+ pendingConfirmationExpirationBlocks: client.consts.bitcoinUtxos.maxPendingConfirmationBlocks.toNumber(),
627
+ tickDurationMillis: await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber()),
628
+ bitcoinNetwork
629
+ };
630
+ }
631
+ async getBitcoinConfirmedBlockHeight() {
632
+ return await this.client.query.bitcoinUtxos.confirmedBitcoinBlockTip().then((x) => x.value?.blockHeight.toNumber() ?? 0);
633
+ }
634
+ /**
635
+ * Gets the UTXO reference by ID.
636
+ * @param utxoId - The UTXO ID to look up.
637
+ * @param clientAtHeight - Optional client at the block height to query the UTXO reference at a specific point in time.
638
+ * @return An object containing the transaction ID and output index, or undefined if not found.
639
+ * @return.txid - The Bitcoin transaction ID of the UTXO.
640
+ * @return.vout - The output index of the UTXO in the transaction.
641
+ * @return.bitcoinTxid - The Bitcoin transaction ID of the UTXO formatted in little endian
642
+ */
643
+ async getUtxoRef(utxoId, clientAtHeight) {
644
+ const client = clientAtHeight ?? this.client;
645
+ const refRaw = await client.query.bitcoinUtxos.utxoIdToRef(utxoId);
646
+ if (!refRaw) {
647
+ return;
648
+ }
649
+ const ref = refRaw.unwrap();
650
+ const txid = u8aToHex(ref.txid);
651
+ const bitcoinTxid = u8aToHex(ref.txid.reverse());
652
+ const vout = ref.outputIndex.toNumber();
653
+ return { txid, vout, bitcoinTxid };
654
+ }
655
+ async getReleaseRequest(utxoId, clientAtHeight) {
656
+ const client = clientAtHeight ?? this.client;
657
+ const requestMaybe = await client.query.bitcoinLocks.lockReleaseRequestsByUtxoId(utxoId);
658
+ if (!requestMaybe.isSome) {
659
+ return void 0;
660
+ }
661
+ const request = requestMaybe.unwrap();
662
+ return {
663
+ toScriptPubkey: request.toScriptPubkey.toHex(),
664
+ bitcoinNetworkFee: request.bitcoinNetworkFee.toBigInt(),
665
+ dueFrame: request.cosignDueFrame.toNumber(),
666
+ vaultId: request.vaultId.toNumber(),
667
+ redemptionPrice: request.redemptionPrice.toBigInt()
668
+ };
669
+ }
670
+ async submitVaultSignature(args) {
671
+ const { utxoId, vaultSignature, argonKeyring, txProgressCallback } = args;
672
+ const client = this.client;
673
+ if (!vaultSignature || vaultSignature.byteLength < 70 || vaultSignature.byteLength > 73) {
674
+ throw new Error(
675
+ `Invalid vault signature length: ${vaultSignature.byteLength}. Must be 70-73 bytes.`
676
+ );
677
+ }
678
+ const signature = u8aToHex(vaultSignature);
679
+ const tx = client.tx.bitcoinLocks.cosignRelease(utxoId, signature);
680
+ const submitter = new TxSubmitter(client, tx, argonKeyring);
681
+ return await submitter.submit({ txProgressCallback });
682
+ }
683
+ async getBitcoinLock(utxoId) {
684
+ const utxoRaw = await this.client.query.bitcoinLocks.locksByUtxoId(utxoId);
685
+ if (!utxoRaw.isSome) {
686
+ return;
687
+ }
688
+ const utxo = utxoRaw.unwrap();
689
+ const p2shBytesPrefix = "0020";
690
+ const wscriptHash = utxo.utxoScriptPubkey.asP2wsh.wscriptHash.toHex().replace("0x", "");
691
+ const p2wshScriptHashHex = `0x${p2shBytesPrefix}${wscriptHash}`;
692
+ const vaultId = utxo.vaultId.toNumber();
693
+ const peggedPrice = utxo.peggedPrice.toBigInt();
694
+ const liquidityPromised = utxo.liquidityPromised.toBigInt();
695
+ const ownerAccount = utxo.ownerAccount.toHuman();
696
+ const satoshis = utxo.satoshis.toBigInt();
697
+ const vaultPubkey = utxo.vaultPubkey.toHex();
698
+ const vaultClaimPubkey = utxo.vaultClaimPubkey.toHex();
699
+ const ownerPubkey = utxo.ownerPubkey.toHex();
700
+ const [fingerprint, cosign_hd_index, claim_hd_index] = utxo.vaultXpubSources;
701
+ const vaultXpubSources = {
702
+ parentFingerprint: new Uint8Array(fingerprint),
703
+ cosignHdIndex: cosign_hd_index.toNumber(),
704
+ claimHdIndex: claim_hd_index.toNumber()
705
+ };
706
+ const securityFees = utxo.securityFees.toBigInt();
707
+ const vaultClaimHeight = utxo.vaultClaimHeight.toNumber();
708
+ const openClaimHeight = utxo.openClaimHeight.toNumber();
709
+ const createdAtHeight = utxo.createdAtHeight.toNumber();
710
+ const isVerified = utxo.isVerified.toJSON();
711
+ const isRejectedNeedsRelease = utxo.isRejectedNeedsRelease.toJSON();
712
+ const fundHoldExtensionsByBitcoinExpirationHeight = Object.fromEntries(
713
+ [...utxo.fundHoldExtensions.entries()].map(([x, y]) => [x.toNumber(), y.toBigInt()])
714
+ );
715
+ return {
716
+ utxoId,
717
+ p2wshScriptHashHex,
718
+ vaultId,
719
+ peggedPrice,
720
+ liquidityPromised,
721
+ ownerAccount,
722
+ satoshis,
723
+ vaultPubkey,
724
+ vaultClaimPubkey,
725
+ ownerPubkey,
726
+ vaultXpubSources,
727
+ vaultClaimHeight,
728
+ openClaimHeight,
729
+ createdAtHeight,
730
+ securityFees,
731
+ isVerified,
732
+ isRejectedNeedsRelease,
733
+ fundHoldExtensionsByBitcoinExpirationHeight
734
+ };
735
+ }
736
+ /**
737
+ * Finds the cosign signature for a vault lock by UTXO ID. Optionally waits for the signature
738
+ * @param utxoId - The UTXO ID of the bitcoin lock
739
+ * @param waitForSignatureMillis - Optional timeout in milliseconds to wait for the signature. If -1, waits indefinitely.
740
+ */
741
+ async findVaultCosignSignature(utxoId, waitForSignatureMillis) {
742
+ const client = this.client;
743
+ const releaseHeight = await client.query.bitcoinLocks.lockReleaseCosignHeightById(utxoId);
744
+ if (releaseHeight.isSome) {
745
+ const releaseHeightValue = releaseHeight.unwrap().toNumber();
746
+ const signature = await this.getVaultCosignSignature(utxoId, releaseHeightValue);
747
+ if (signature) {
748
+ return { blockHeight: releaseHeightValue, signature };
749
+ }
750
+ }
751
+ if (!waitForSignatureMillis) {
752
+ return void 0;
753
+ }
754
+ return await new Promise(async (resolve, reject) => {
755
+ let timeout;
756
+ const unsub = await client.rpc.chain.subscribeNewHeads((header) => {
757
+ const atHeight = header.number.toNumber();
758
+ this.getVaultCosignSignature(utxoId, atHeight).then((signature) => {
759
+ if (signature) {
760
+ unsub?.();
761
+ clearTimeout(timeout);
762
+ resolve({ signature, blockHeight: atHeight });
763
+ }
764
+ }).catch((err) => {
765
+ console.error(`Error checking for cosign signature at height ${atHeight}:`, err);
766
+ });
767
+ });
768
+ if (waitForSignatureMillis !== -1) {
769
+ timeout = setTimeout(() => {
770
+ unsub?.();
771
+ reject(new Error(`Timeout waiting for cosign signature for UTXO ID ${utxoId}`));
772
+ }, waitForSignatureMillis);
773
+ }
774
+ });
775
+ }
776
+ async blockHashAtHeight(atHeight) {
777
+ const client = this.client;
778
+ for (let i = 0; i < 10; i++) {
779
+ const currentHeight = await client.query.system.number().then((x) => x.toNumber());
780
+ if (atHeight > currentHeight) {
781
+ console.warn(
782
+ `Requested block height ${atHeight} is greater than current height ${currentHeight}. Retrying...`
783
+ );
784
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
785
+ continue;
786
+ }
787
+ const hash = await client.rpc.chain.getBlockHash(atHeight).then((x) => x.toHex());
788
+ if (hash === "0x0000000000000000000000000000000000000000000000000000000000000000") {
789
+ console.warn(`Block hash not found for height ${atHeight}. Retrying...`);
790
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
791
+ continue;
792
+ }
793
+ return hash;
794
+ }
795
+ return void 0;
796
+ }
797
+ async getVaultCosignSignature(utxoId, atHeight) {
798
+ const client = this.client;
799
+ const blockHash = await this.blockHashAtHeight(atHeight);
800
+ if (!blockHash) {
801
+ console.warn(`Block hash not found for height ${atHeight}`);
802
+ return void 0;
803
+ }
804
+ const blockEvents = await client.at(blockHash).then((api) => api.query.system.events());
805
+ for (const event of blockEvents) {
806
+ if (client.events.bitcoinLocks.BitcoinUtxoCosigned.is(event.event)) {
807
+ const { utxoId: id, signature } = event.event.data;
808
+ if (id.toNumber() === utxoId) {
809
+ return new Uint8Array(signature);
810
+ }
811
+ }
812
+ }
813
+ return void 0;
814
+ }
815
+ async findPendingMints(utxoId) {
816
+ const pendingMint = await this.client.query.mint.pendingMintUtxos();
817
+ const mintsPending = [];
818
+ for (const [utxoIdRaw, _accountId, mintAmountRaw] of pendingMint) {
819
+ if (utxoIdRaw.toNumber() === utxoId) {
820
+ mintsPending.push(mintAmountRaw.toBigInt());
821
+ }
822
+ }
823
+ return mintsPending;
824
+ }
825
+ async createInitializeLockTx(args) {
826
+ const { vault, priceIndex, argonKeyring, satoshis, tip = 0n, ownerBitcoinPubkey } = args;
827
+ const client = this.client;
828
+ if (ownerBitcoinPubkey.length !== 33) {
829
+ throw new Error(
830
+ `Invalid Bitcoin key length: ${ownerBitcoinPubkey.length}. Must be a compressed pukey (33 bytes).`
831
+ );
832
+ }
833
+ const tx = client.tx.bitcoinLocks.initialize(vault.vaultId, satoshis, ownerBitcoinPubkey);
834
+ const submitter = new TxSubmitter(
835
+ client,
836
+ client.tx.bitcoinLocks.initialize(vault.vaultId, satoshis, ownerBitcoinPubkey),
837
+ argonKeyring
838
+ );
839
+ const marketPrice = await this.getMarketRate(priceIndex, satoshis);
840
+ const isVaultOwner = argonKeyring.address === vault.operatorAccountId;
841
+ const securityFee = isVaultOwner ? 0n : vault.calculateBitcoinFee(marketPrice);
842
+ const { canAfford, availableBalance, txFee } = await submitter.canAfford({
843
+ tip,
844
+ unavailableBalance: securityFee + (args.reducedBalanceBy ?? 0n),
845
+ includeExistentialDeposit: true
846
+ });
847
+ if (!canAfford) {
848
+ throw new Error(
849
+ `Insufficient funds to initialize lock. Available: ${formatArgons(availableBalance)}, Required: ${satoshis}`
850
+ );
851
+ }
852
+ return { tx, securityFee, txFee };
853
+ }
854
+ async getBitcoinLockFromTxResult(txResult) {
855
+ const client = this.client;
856
+ const blockHash = await txResult.inBlockPromise;
857
+ const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
858
+ const utxoId = await this.getUtxoIdFromEvents(txResult.events) ?? 0;
859
+ if (utxoId === 0) {
860
+ throw new Error("Bitcoin lock creation failed, no UTXO ID found in transaction events");
861
+ }
862
+ const lock = await this.getBitcoinLock(utxoId);
863
+ if (!lock) {
864
+ throw new Error(`Lock with ID ${utxoId} not found after initialization`);
865
+ }
866
+ return { lock, createdAtHeight: blockHeight, txResult };
867
+ }
868
+ async initializeLock(args) {
869
+ const { argonKeyring, tip = 0n, txProgressCallback } = args;
870
+ const client = this.client;
871
+ const { tx, securityFee } = await this.createInitializeLockTx(args);
872
+ const submitter = new TxSubmitter(client, tx, argonKeyring);
873
+ const txResult = await submitter.submit({
874
+ waitForBlock: true,
875
+ logResults: true,
876
+ tip,
877
+ txProgressCallback
878
+ });
879
+ const { lock, createdAtHeight } = await this.getBitcoinLockFromTxResult(txResult);
880
+ return {
881
+ lock,
882
+ createdAtHeight,
883
+ txResult,
884
+ securityFee
885
+ };
886
+ }
887
+ async requiredSatoshisForArgonLiquidity(priceIndex, argonAmount) {
888
+ const marketRatePerBitcoin = priceIndex.getBtcMicrogonPrice(SATS_PER_BTC);
889
+ return argonAmount * SATS_PER_BTC / marketRatePerBitcoin;
890
+ }
891
+ async requestRelease(args) {
892
+ const client = this.client;
893
+ const {
894
+ lock,
895
+ priceIndex,
896
+ releaseRequest: { bitcoinNetworkFee, toScriptPubkey },
897
+ argonKeyring,
898
+ tip,
899
+ txProgressCallback
900
+ } = args;
901
+ if (!toScriptPubkey.startsWith("0x")) {
902
+ throw new Error("toScriptPubkey must be a hex string starting with 0x");
903
+ }
904
+ const submitter = new TxSubmitter(
905
+ client,
906
+ client.tx.bitcoinLocks.requestRelease(lock.utxoId, toScriptPubkey, bitcoinNetworkFee),
907
+ argonKeyring
908
+ );
909
+ const redemptionPrice = await this.getRedemptionRate(priceIndex, lock);
910
+ const canAfford = await submitter.canAfford({
911
+ tip,
912
+ unavailableBalance: BigInt(redemptionPrice)
913
+ });
914
+ if (!canAfford.canAfford) {
915
+ throw new Error(
916
+ `Insufficient funds to release lock. Available: ${formatArgons(canAfford.availableBalance)}, Required: ${formatArgons(redemptionPrice)}`
917
+ );
918
+ }
919
+ const txResult = await submitter.submit({
920
+ waitForBlock: true,
921
+ logResults: true,
922
+ tip,
923
+ txProgressCallback
924
+ });
925
+ const blockHash = await txResult.inBlockPromise;
926
+ const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
927
+ return {
928
+ blockHash,
929
+ blockHeight
930
+ };
931
+ }
932
+ async releasePrice(priceIndex, lock) {
933
+ return await this.getRedemptionRate(priceIndex, lock);
934
+ }
935
+ async getRatchetPrice(lock, priceIndex, vault) {
936
+ const { createdAtHeight, vaultClaimHeight, peggedPrice, satoshis } = lock;
937
+ const client = this.client;
938
+ const marketRate = await this.getMarketRate(priceIndex, BigInt(satoshis));
939
+ let ratchetingFee = vault.terms.bitcoinBaseFee;
940
+ let burnAmount = 0n;
941
+ if (marketRate > peggedPrice) {
942
+ const lockFee = vault.calculateBitcoinFee(marketRate);
943
+ const currentBitcoinHeight = await client.query.bitcoinUtxos.confirmedBitcoinBlockTip().then((x) => x.unwrap().blockHeight.toNumber());
944
+ const blockLength = vaultClaimHeight - createdAtHeight;
945
+ const elapsed = (currentBitcoinHeight - createdAtHeight) / blockLength;
946
+ const remainingDuration = 1 - elapsed;
947
+ ratchetingFee = BigInt(remainingDuration * Number(lockFee));
948
+ } else {
949
+ burnAmount = await this.releasePrice(priceIndex, lock);
950
+ }
951
+ return {
952
+ ratchetingFee,
953
+ burnAmount,
954
+ marketRate
955
+ };
956
+ }
957
+ async ratchet(args) {
958
+ const { lock, priceIndex, argonKeyring, tip = 0n, vault, txProgressCallback } = args;
959
+ const client = this.client;
960
+ const ratchetPrice = await this.getRatchetPrice(lock, priceIndex, vault);
961
+ const txSubmitter = new TxSubmitter(
962
+ client,
963
+ client.tx.bitcoinLocks.ratchet(lock.utxoId),
964
+ argonKeyring
965
+ );
966
+ const canAfford = await txSubmitter.canAfford({
967
+ tip,
968
+ unavailableBalance: BigInt(ratchetPrice.burnAmount + ratchetPrice.ratchetingFee)
969
+ });
970
+ if (!canAfford.canAfford) {
971
+ throw new Error(
972
+ `Insufficient funds to ratchet lock. Available: ${formatArgons(canAfford.availableBalance)}, Required: ${formatArgons(
973
+ ratchetPrice.burnAmount + ratchetPrice.ratchetingFee
974
+ )}`
975
+ );
976
+ }
977
+ const submission = await txSubmitter.submit({
978
+ waitForBlock: true,
979
+ tip,
980
+ txProgressCallback
981
+ });
982
+ const ratchetEvent = submission.events.find(
983
+ (x) => client.events.bitcoinLocks.BitcoinLockRatcheted.is(x)
984
+ );
985
+ if (!ratchetEvent) {
986
+ throw new Error(`Ratchet event not found in transaction events`);
987
+ }
988
+ const blockHash = await submission.inBlockPromise;
989
+ const api = await client.at(blockHash);
990
+ const blockHeight = await api.query.system.number().then((x) => x.toNumber());
991
+ const bitcoinBlockHeight = await api.query.bitcoinUtxos.confirmedBitcoinBlockTip().then((x) => x.unwrap().blockHeight.toNumber());
992
+ const {
993
+ amountBurned,
994
+ liquidityPromised: liquidityPromisedRaw,
995
+ newPeggedPrice,
996
+ originalPeggedPrice
997
+ } = ratchetEvent.data;
998
+ const liquidityPromised = liquidityPromisedRaw.toBigInt();
999
+ let mintAmount = liquidityPromised;
1000
+ if (liquidityPromised > originalPeggedPrice.toBigInt()) {
1001
+ mintAmount -= originalPeggedPrice.toBigInt();
1002
+ }
1003
+ return {
1004
+ txFee: submission.finalFee ?? 0n,
1005
+ securityFee: ratchetPrice.ratchetingFee,
1006
+ pendingMint: mintAmount,
1007
+ liquidityPromised,
1008
+ newPeggedPrice: newPeggedPrice.toBigInt(),
1009
+ burned: amountBurned.toBigInt(),
1010
+ blockHeight,
1011
+ bitcoinBlockHeight
1012
+ };
1013
+ }
1014
+ };
1015
+
1016
+ // src/PriceIndex.ts
1017
+ import BigNumber4 from "bignumber.js";
1018
+ var PriceIndex = class {
1019
+ btcUsdPrice;
1020
+ argonotUsdPrice;
1021
+ argonUsdPrice;
1022
+ argonUsdTargetPrice;
1023
+ argonTimeWeightedAverageLiquidity;
1024
+ lastUpdatedTick;
1025
+ async load(client) {
1026
+ const current = await client.query.priceIndex.current();
1027
+ if (!current.isSome) {
1028
+ this.argonUsdPrice = void 0;
1029
+ this.argonotUsdPrice = void 0;
1030
+ this.btcUsdPrice = void 0;
1031
+ this.argonUsdTargetPrice = void 0;
1032
+ this.argonTimeWeightedAverageLiquidity = void 0;
1033
+ this.lastUpdatedTick = void 0;
1034
+ return this;
1035
+ }
1036
+ const value = current.unwrap();
1037
+ this.btcUsdPrice = fromFixedNumber(value.btcUsdPrice.toBigInt(), FIXED_U128_DECIMALS);
1038
+ this.argonotUsdPrice = fromFixedNumber(value.argonotUsdPrice.toBigInt(), FIXED_U128_DECIMALS);
1039
+ this.argonUsdPrice = fromFixedNumber(value.argonUsdPrice.toBigInt(), FIXED_U128_DECIMALS);
1040
+ this.argonUsdTargetPrice = fromFixedNumber(
1041
+ value.argonUsdTargetPrice.toBigInt(),
1042
+ FIXED_U128_DECIMALS
1043
+ );
1044
+ this.argonTimeWeightedAverageLiquidity = fromFixedNumber(
1045
+ value.argonTimeWeightedAverageLiquidity.toBigInt(),
1046
+ FIXED_U128_DECIMALS
1047
+ );
1048
+ this.lastUpdatedTick = value.tick.toNumber();
1049
+ return this;
1050
+ }
1051
+ getBtcMicrogonPrice(satoshis) {
1052
+ if (this.btcUsdPrice === void 0 || this.argonUsdPrice === void 0) {
1053
+ throw new Error("PriceIndex not loaded");
1054
+ }
1055
+ const satoshiCents = this.btcUsdPrice.multipliedBy(satoshis).dividedBy(SATS_PER_BTC);
1056
+ const microgons = satoshiCents.multipliedBy(MICROGONS_PER_ARGON).dividedBy(this.argonUsdPrice);
1057
+ return BigInt(microgons.integerValue(BigNumber4.ROUND_DOWN).toString());
1058
+ }
1059
+ get rValue() {
1060
+ if (this.argonUsdTargetPrice === void 0 || this.argonUsdPrice === void 0) {
1061
+ throw new Error("PriceIndex not loaded");
1062
+ }
1063
+ return this.argonUsdPrice.div(this.argonUsdTargetPrice);
1064
+ }
1065
+ get argonCpi() {
1066
+ if (this.argonUsdTargetPrice === void 0 || this.argonUsdPrice === void 0) {
1067
+ throw new Error("PriceIndex not loaded");
1068
+ }
1069
+ const ratio = this.argonUsdTargetPrice.div(this.argonUsdPrice);
1070
+ return ratio.minus(1);
1071
+ }
1072
+ };
1073
+
1074
+ // src/index.ts
1075
+ import { u8aToHex as u8aToHex2, hexToU8a as hexToU8a2, u8aEq } from "@polkadot/util";
1076
+ import { GenericEvent as GenericEvent2, GenericBlock, GenericAddress } from "@polkadot/types/generic";
1
1077
  import {
2
- AccountMiners,
3
- AccountRegistry,
4
- Accountset,
5
1078
  BTreeMap,
6
- BidPool,
7
- BitcoinLocks,
8
- BlockWatch,
9
- Bool,
10
1079
  Bytes,
11
- CohortBidder,
12
1080
  Compact,
13
1081
  Enum,
14
- ExtrinsicError,
15
- FrameCalculator,
16
- GenericAddress,
17
- GenericBlock,
18
- GenericEvent,
19
- JsonExt,
20
- Keyring,
21
- MICROGONS_PER_ARGON,
22
- MiningBids,
23
1082
  Null,
24
1083
  Option,
25
- Range,
26
1084
  Result,
27
- SATS_PER_BTC,
1085
+ Bool,
1086
+ Tuple,
1087
+ Range,
28
1088
  Struct,
29
1089
  Text,
30
- Tuple,
31
- TxResult,
32
- TxSubmitter,
33
- TypedEmitter,
34
1090
  U256,
35
1091
  U8aFixed,
36
- Vault,
37
- VaultMonitor,
38
1092
  Vec,
39
- WageProtector,
40
1093
  bool,
41
- checkForExtrinsicSuccess,
42
- convertFixedU128ToBigNumber,
43
- convertNumberToFixedU128,
44
- convertNumberToPermill,
45
- convertPermillToBigNumber,
46
- createKeyringPair,
47
- createNanoEvents,
48
- decodeAddress,
49
- dispatchErrorToExtrinsicError,
50
- dispatchErrorToString,
51
- eventDataToJson,
52
- filterUndefined,
53
- formatArgons,
54
- formatPercent,
55
- getAuthorFromHeader,
56
- getClient,
57
- getConfig,
58
- getTickFromHeader,
59
- gettersToObject,
60
- hexToU8a,
61
1094
  i128,
62
- keyringFromSuri,
63
- miniSecretFromUri,
64
- mnemonicGenerate,
65
- setConfig,
66
- toFixedNumber,
67
1095
  u128,
68
1096
  u16,
69
1097
  u32,
70
1098
  u64,
71
- u8,
72
- u8aEq,
73
- u8aToHex,
74
- waitForLoad
75
- } from "./chunk-PXZPYJ4P.js";
1099
+ u8
1100
+ } from "@polkadot/types-codec";
1101
+ async function waitForLoad() {
1102
+ await cryptoWaitReady();
1103
+ }
1104
+ async function getClient(host, options) {
1105
+ let provider;
1106
+ if (host.startsWith("http")) {
1107
+ provider = new HttpProvider(host);
1108
+ } else {
1109
+ provider = new WsProvider(host);
1110
+ }
1111
+ return await ApiPromise.create({ provider, noInitWarn: true, ...options ?? {} });
1112
+ }
76
1113
  export {
77
- AccountMiners,
78
- AccountRegistry,
79
- Accountset,
80
1114
  BTreeMap,
81
- BidPool,
82
1115
  BitcoinLocks,
83
- BlockWatch,
84
1116
  Bool,
85
1117
  Bytes,
86
- CohortBidder,
87
1118
  Compact,
88
1119
  Enum,
89
- ExtrinsicError,
90
- FrameCalculator,
1120
+ ExtrinsicError2 as ExtrinsicError,
1121
+ FIXED_U128_DECIMALS,
91
1122
  GenericAddress,
92
1123
  GenericBlock,
93
- GenericEvent,
94
- JsonExt,
1124
+ GenericEvent2 as GenericEvent,
95
1125
  Keyring,
96
1126
  MICROGONS_PER_ARGON,
97
- MiningBids,
98
1127
  Null,
99
1128
  Option,
1129
+ PERMILL_DECIMALS,
1130
+ PriceIndex,
100
1131
  Range,
101
1132
  Result,
102
1133
  SATS_PER_BTC,
@@ -105,39 +1136,27 @@ export {
105
1136
  Tuple,
106
1137
  TxResult,
107
1138
  TxSubmitter,
108
- TypedEmitter,
109
1139
  U256,
110
1140
  U8aFixed,
111
1141
  Vault,
112
- VaultMonitor,
113
1142
  Vec,
114
1143
  WageProtector,
115
1144
  bool,
116
1145
  checkForExtrinsicSuccess,
117
- convertFixedU128ToBigNumber,
118
- convertNumberToFixedU128,
119
- convertNumberToPermill,
120
- convertPermillToBigNumber,
121
1146
  createKeyringPair,
122
- createNanoEvents,
123
1147
  decodeAddress,
124
1148
  dispatchErrorToExtrinsicError,
125
1149
  dispatchErrorToString,
126
- eventDataToJson,
127
- filterUndefined,
128
1150
  formatArgons,
129
- formatPercent,
1151
+ fromFixedNumber,
130
1152
  getAuthorFromHeader,
131
1153
  getClient,
132
- getConfig,
133
1154
  getTickFromHeader,
134
1155
  gettersToObject,
135
- hexToU8a,
1156
+ hexToU8a2 as hexToU8a,
136
1157
  i128,
137
1158
  keyringFromSuri,
138
- miniSecretFromUri,
139
1159
  mnemonicGenerate,
140
- setConfig,
141
1160
  toFixedNumber,
142
1161
  u128,
143
1162
  u16,
@@ -145,7 +1164,7 @@ export {
145
1164
  u64,
146
1165
  u8,
147
1166
  u8aEq,
148
- u8aToHex,
1167
+ u8aToHex2 as u8aToHex,
149
1168
  waitForLoad
150
1169
  };
151
1170
  //# sourceMappingURL=index.js.map