@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.cjs CHANGED
@@ -1,6 +1,1079 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
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 _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;// src/interfaces/augment-api-consts.ts
2
+ require('@polkadot/api-base/types/consts');
3
+
4
+ // src/interfaces/augment-api-errors.ts
5
+ require('@polkadot/api-base/types/errors');
6
+
7
+ // src/interfaces/augment-api-events.ts
8
+ require('@polkadot/api-base/types/events');
9
+
10
+ // src/interfaces/augment-api-query.ts
11
+ require('@polkadot/api-base/types/storage');
12
+
13
+ // src/interfaces/augment-api-tx.ts
14
+ require('@polkadot/api-base/types/submittable');
15
+
16
+ // src/interfaces/augment-api-rpc.ts
17
+ require('@polkadot/rpc-core/types/jsonrpc');
18
+
19
+ // src/interfaces/augment-api-runtime.ts
20
+ require('@polkadot/api-base/types/calls');
21
+
22
+ // src/interfaces/augment-types.ts
23
+ require('@polkadot/types/types/registry');
24
+
25
+ // src/index.ts
26
+ var _api = require('@polkadot/api');
27
+ var _utilcrypto = require('@polkadot/util-crypto');
28
+
29
+ // src/WageProtector.ts
30
+ var WageProtector = class _WageProtector {
31
+ constructor(latestCpi) {
32
+ this.latestCpi = latestCpi;
33
+ }
34
+ /**
35
+ * Converts the base wage to the current wage using the latest CPI snapshot
36
+ *
37
+ * @param baseWage The base wage to convert
38
+ * @returns The protected wage
39
+ */
40
+ getProtectedWage(baseWage) {
41
+ return baseWage * this.latestCpi.argonUsdTargetPrice / this.latestCpi.argonUsdPrice;
42
+ }
43
+ /**
44
+ * Subscribes to the current CPI and calls the callback function whenever the CPI changes
45
+ * @param client The ArgonClient to use
46
+ * @param callback The callback function to call when the CPI changes
47
+ * @returns An object with an unsubscribe function that can be called to stop the subscription
48
+ */
49
+ static async subscribe(client, callback) {
50
+ const unsubscribe = await client.query.priceIndex.current(async (cpi) => {
51
+ if (cpi.isNone) {
52
+ return;
53
+ }
54
+ const finalizedBlock = await client.rpc.chain.getFinalizedHead();
55
+ callback(
56
+ new _WageProtector({
57
+ argonUsdTargetPrice: cpi.value.argonUsdTargetPrice.toBigInt(),
58
+ argonUsdPrice: cpi.value.argonUsdPrice.toBigInt(),
59
+ finalizedBlock: 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 + (_nullishCoalesce(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 = class {
151
+ constructor(client, shouldLog = false) {;_class.prototype.__init.call(this);
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
+
166
+
167
+
168
+ __init() {this.events = []}
169
+ /**
170
+ * The index of the batch that was interrupted, if any.
171
+ */
172
+
173
+
174
+ /**
175
+ * The final fee paid for the transaction, including the fee tip.
176
+ */
177
+
178
+ /**
179
+ * The fee tip paid for the transaction.
180
+ */
181
+
182
+
183
+
184
+
185
+
186
+
187
+ onResult(result) {
188
+ this.status = result.status;
189
+ if (this.shouldLog) {
190
+ logExtrinsicResult(result);
191
+ }
192
+ const { events, status, dispatchError, isFinalized } = result;
193
+ if (status.isInBlock) {
194
+ this.includedInBlock = 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
+ }, _class);
235
+
236
+ // src/utils.ts
237
+ var _bignumberjs = require('bignumber.js'); var BN = _interopRequireWildcard(_bignumberjs); var BN2 = _interopRequireWildcard(_bignumberjs);
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 = BN.default.call(void 0, 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} ${_nullishCoalesce(this.details, () => ( ""))} (Batch interrupted at index ${this.batchInterruptedIndex})`;
293
+ }
294
+ return `${this.errorCode} ${_nullishCoalesce(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 (0, _api.Keyring)({ type: cryptoType }).createFromUri(suri);
326
+ }
327
+ function createKeyringPair(opts) {
328
+ const { cryptoType } = opts;
329
+ const seed = _utilcrypto.mnemonicGenerate.call(void 0, );
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
+
359
+ var _bs58check = require('bs58check'); var _bs58check2 = _interopRequireDefault(_bs58check);
360
+ var _util = require('@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
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+
382
+
383
+
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 (0, BN.default)(this.securitizationRatio);
437
+ }
438
+ recoverySecuritization() {
439
+ const reserved = new (0, BN.default)(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, BN.default.ROUND_CEIL).toString()
445
+ );
446
+ }
447
+ activatedSecuritization() {
448
+ const activated = this.argonsLocked - this.argonsPendingActivation;
449
+ const maxRatio = BN.default.call(void 0, 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(BN.default.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 = await _asyncNullishCoalesce(tickDurationMillis, async () => ( 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 = _util.hexToU8a.call(void 0, bitcoinXpub);
483
+ if (xpubBytes.length !== 78) {
484
+ if (bitcoinXpub.startsWith("xpub") || bitcoinXpub.startsWith("tpub") || bitcoinXpub.startsWith("zpub")) {
485
+ const bytes = _bs58check2.default.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 = _nullishCoalesce(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 = await _asyncNullishCoalesce(config.tickDurationMillis, async () => ( 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
+
548
+ function toFixedNumber(value, decimals) {
549
+ const factor = new (0, BN.default)(10).pow(decimals);
550
+ const bn = new (0, BN.default)(value);
551
+ const int = bn.times(factor).integerValue(BN.default.ROUND_DOWN);
552
+ return BigInt(int.toFixed(0));
553
+ }
554
+ function fromFixedNumber(value, decimals = FIXED_U128_DECIMALS) {
555
+ const factor = new (0, BN.default)(10).pow(decimals);
556
+ const bn = new (0, BN.default)(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
+
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) => _nullishCoalesce(_optionalChain([x, 'access', _ => _.value, 'optionalAccess', _2 => _2.blockHeight, 'access', _3 => _3.toNumber, 'call', _4 => _4()]), () => ( 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 = _nullishCoalesce(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 = _util.u8aToHex.call(void 0, ref.txid);
651
+ const bitcoinTxid = _util.u8aToHex.call(void 0, ref.txid.reverse());
652
+ const vout = ref.outputIndex.toNumber();
653
+ return { txid, vout, bitcoinTxid };
654
+ }
655
+ async getReleaseRequest(utxoId, clientAtHeight) {
656
+ const client = _nullishCoalesce(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 = _util.u8aToHex.call(void 0, 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
+ _optionalChain([unsub, 'optionalCall', _5 => _5()]);
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
+ _optionalChain([unsub, 'optionalCall', _6 => _6()]);
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 + (_nullishCoalesce(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 _asyncNullishCoalesce(await this.getUtxoIdFromEvents(txResult.events), async () => ( 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: _nullishCoalesce(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
+
1018
+ var PriceIndex = class {
1019
+
1020
+
1021
+
1022
+
1023
+
1024
+
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(BN.default.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
+ };
2
1073
 
1074
+ // src/index.ts
3
1075
 
1076
+ var _generic = require('@polkadot/types/generic');
4
1077
 
5
1078
 
6
1079
 
@@ -24,6 +1097,19 @@
24
1097
 
25
1098
 
26
1099
 
1100
+ var _typescodec = require('@polkadot/types-codec');
1101
+ async function waitForLoad() {
1102
+ await _utilcrypto.cryptoWaitReady.call(void 0, );
1103
+ }
1104
+ async function getClient(host, options) {
1105
+ let provider;
1106
+ if (host.startsWith("http")) {
1107
+ provider = new (0, _api.HttpProvider)(host);
1108
+ } else {
1109
+ provider = new (0, _api.WsProvider)(host);
1110
+ }
1111
+ return await _api.ApiPromise.create({ provider, noInitWarn: true, ..._nullishCoalesce(options, () => ( {})) });
1112
+ }
27
1113
 
28
1114
 
29
1115
 
@@ -72,7 +1158,6 @@
72
1158
 
73
1159
 
74
1160
 
75
- var _chunkVXYWJG66cjs = require('./chunk-VXYWJG66.cjs');
76
1161
 
77
1162
 
78
1163
 
@@ -81,71 +1166,5 @@ var _chunkVXYWJG66cjs = require('./chunk-VXYWJG66.cjs');
81
1166
 
82
1167
 
83
1168
 
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
121
-
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
-
141
-
142
-
143
-
144
-
145
-
146
-
147
-
148
-
149
-
150
- exports.AccountMiners = _chunkVXYWJG66cjs.AccountMiners; exports.AccountRegistry = _chunkVXYWJG66cjs.AccountRegistry; exports.Accountset = _chunkVXYWJG66cjs.Accountset; exports.BTreeMap = _chunkVXYWJG66cjs.BTreeMap; exports.BidPool = _chunkVXYWJG66cjs.BidPool; exports.BitcoinLocks = _chunkVXYWJG66cjs.BitcoinLocks; exports.BlockWatch = _chunkVXYWJG66cjs.BlockWatch; exports.Bool = _chunkVXYWJG66cjs.Bool; exports.Bytes = _chunkVXYWJG66cjs.Bytes; exports.CohortBidder = _chunkVXYWJG66cjs.CohortBidder; exports.Compact = _chunkVXYWJG66cjs.Compact; exports.Enum = _chunkVXYWJG66cjs.Enum; exports.ExtrinsicError = _chunkVXYWJG66cjs.ExtrinsicError; exports.FrameCalculator = _chunkVXYWJG66cjs.FrameCalculator; exports.GenericAddress = _chunkVXYWJG66cjs.GenericAddress; exports.GenericBlock = _chunkVXYWJG66cjs.GenericBlock; exports.GenericEvent = _chunkVXYWJG66cjs.GenericEvent; exports.JsonExt = _chunkVXYWJG66cjs.JsonExt; exports.Keyring = _chunkVXYWJG66cjs.Keyring; exports.MICROGONS_PER_ARGON = _chunkVXYWJG66cjs.MICROGONS_PER_ARGON; exports.MiningBids = _chunkVXYWJG66cjs.MiningBids; exports.Null = _chunkVXYWJG66cjs.Null; exports.Option = _chunkVXYWJG66cjs.Option; exports.Range = _chunkVXYWJG66cjs.Range; exports.Result = _chunkVXYWJG66cjs.Result; exports.SATS_PER_BTC = _chunkVXYWJG66cjs.SATS_PER_BTC; exports.Struct = _chunkVXYWJG66cjs.Struct; exports.Text = _chunkVXYWJG66cjs.Text; exports.Tuple = _chunkVXYWJG66cjs.Tuple; exports.TxResult = _chunkVXYWJG66cjs.TxResult; exports.TxSubmitter = _chunkVXYWJG66cjs.TxSubmitter; exports.TypedEmitter = _chunkVXYWJG66cjs.TypedEmitter; exports.U256 = _chunkVXYWJG66cjs.U256; exports.U8aFixed = _chunkVXYWJG66cjs.U8aFixed; exports.Vault = _chunkVXYWJG66cjs.Vault; exports.VaultMonitor = _chunkVXYWJG66cjs.VaultMonitor; exports.Vec = _chunkVXYWJG66cjs.Vec; exports.WageProtector = _chunkVXYWJG66cjs.WageProtector; exports.bool = _chunkVXYWJG66cjs.bool; exports.checkForExtrinsicSuccess = _chunkVXYWJG66cjs.checkForExtrinsicSuccess; exports.convertFixedU128ToBigNumber = _chunkVXYWJG66cjs.convertFixedU128ToBigNumber; exports.convertNumberToFixedU128 = _chunkVXYWJG66cjs.convertNumberToFixedU128; exports.convertNumberToPermill = _chunkVXYWJG66cjs.convertNumberToPermill; exports.convertPermillToBigNumber = _chunkVXYWJG66cjs.convertPermillToBigNumber; exports.createKeyringPair = _chunkVXYWJG66cjs.createKeyringPair; exports.createNanoEvents = _chunkVXYWJG66cjs.createNanoEvents; exports.decodeAddress = _chunkVXYWJG66cjs.decodeAddress; exports.dispatchErrorToExtrinsicError = _chunkVXYWJG66cjs.dispatchErrorToExtrinsicError; exports.dispatchErrorToString = _chunkVXYWJG66cjs.dispatchErrorToString; exports.eventDataToJson = _chunkVXYWJG66cjs.eventDataToJson; exports.filterUndefined = _chunkVXYWJG66cjs.filterUndefined; exports.formatArgons = _chunkVXYWJG66cjs.formatArgons; exports.formatPercent = _chunkVXYWJG66cjs.formatPercent; exports.getAuthorFromHeader = _chunkVXYWJG66cjs.getAuthorFromHeader; exports.getClient = _chunkVXYWJG66cjs.getClient; exports.getConfig = _chunkVXYWJG66cjs.getConfig; exports.getTickFromHeader = _chunkVXYWJG66cjs.getTickFromHeader; exports.gettersToObject = _chunkVXYWJG66cjs.gettersToObject; exports.hexToU8a = _chunkVXYWJG66cjs.hexToU8a; exports.i128 = _chunkVXYWJG66cjs.i128; exports.keyringFromSuri = _chunkVXYWJG66cjs.keyringFromSuri; exports.miniSecretFromUri = _chunkVXYWJG66cjs.miniSecretFromUri; exports.mnemonicGenerate = _chunkVXYWJG66cjs.mnemonicGenerate; exports.setConfig = _chunkVXYWJG66cjs.setConfig; exports.toFixedNumber = _chunkVXYWJG66cjs.toFixedNumber; exports.u128 = _chunkVXYWJG66cjs.u128; exports.u16 = _chunkVXYWJG66cjs.u16; exports.u32 = _chunkVXYWJG66cjs.u32; exports.u64 = _chunkVXYWJG66cjs.u64; exports.u8 = _chunkVXYWJG66cjs.u8; exports.u8aEq = _chunkVXYWJG66cjs.u8aEq; exports.u8aToHex = _chunkVXYWJG66cjs.u8aToHex; exports.waitForLoad = _chunkVXYWJG66cjs.waitForLoad;
1169
+ exports.BTreeMap = _typescodec.BTreeMap; exports.BitcoinLocks = BitcoinLocks; exports.Bool = _typescodec.Bool; exports.Bytes = _typescodec.Bytes; exports.Compact = _typescodec.Compact; exports.Enum = _typescodec.Enum; exports.ExtrinsicError = ExtrinsicError2; exports.FIXED_U128_DECIMALS = FIXED_U128_DECIMALS; exports.GenericAddress = _generic.GenericAddress; exports.GenericBlock = _generic.GenericBlock; exports.GenericEvent = _generic.GenericEvent; exports.Keyring = _api.Keyring; exports.MICROGONS_PER_ARGON = MICROGONS_PER_ARGON; exports.Null = _typescodec.Null; exports.Option = _typescodec.Option; exports.PERMILL_DECIMALS = PERMILL_DECIMALS; exports.PriceIndex = PriceIndex; exports.Range = _typescodec.Range; exports.Result = _typescodec.Result; exports.SATS_PER_BTC = SATS_PER_BTC; exports.Struct = _typescodec.Struct; exports.Text = _typescodec.Text; exports.Tuple = _typescodec.Tuple; exports.TxResult = TxResult; exports.TxSubmitter = TxSubmitter; exports.U256 = _typescodec.U256; exports.U8aFixed = _typescodec.U8aFixed; exports.Vault = Vault; exports.Vec = _typescodec.Vec; exports.WageProtector = WageProtector; exports.bool = _typescodec.bool; exports.checkForExtrinsicSuccess = checkForExtrinsicSuccess; exports.createKeyringPair = createKeyringPair; exports.decodeAddress = _utilcrypto.decodeAddress; exports.dispatchErrorToExtrinsicError = dispatchErrorToExtrinsicError; exports.dispatchErrorToString = dispatchErrorToString; exports.formatArgons = formatArgons; exports.fromFixedNumber = fromFixedNumber; exports.getAuthorFromHeader = getAuthorFromHeader; exports.getClient = getClient; exports.getTickFromHeader = getTickFromHeader; exports.gettersToObject = gettersToObject; exports.hexToU8a = _util.hexToU8a; exports.i128 = _typescodec.i128; exports.keyringFromSuri = keyringFromSuri; exports.mnemonicGenerate = _utilcrypto.mnemonicGenerate; exports.toFixedNumber = toFixedNumber; exports.u128 = _typescodec.u128; exports.u16 = _typescodec.u16; exports.u32 = _typescodec.u32; exports.u64 = _typescodec.u64; exports.u8 = _typescodec.u8; exports.u8aEq = _util.u8aEq; exports.u8aToHex = _util.u8aToHex; exports.waitForLoad = waitForLoad;
151
1170
  //# sourceMappingURL=index.cjs.map