@t2000/sdk 0.36.4 → 0.37.1

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/dist/index.js CHANGED
@@ -1,26 +1,57 @@
1
1
  import { Transaction } from '@mysten/sui/transactions';
2
2
  import { AggregatorClient, Env } from '@cetusprotocol/aggregator-sdk';
3
3
  import { EventEmitter } from 'eventemitter3';
4
- import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
5
- import { normalizeSuiAddress, isValidSuiAddress } from '@mysten/sui/utils';
4
+ import { createPaymentTransactionUri } from '@mysten/payment-kit';
5
+ import { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';
6
+ import { normalizeSuiAddress, isValidSuiAddress, normalizeStructTag } from '@mysten/sui/utils';
6
7
  import { Ed25519Keypair, Ed25519PublicKey } from '@mysten/sui/keypairs/ed25519';
7
8
  import { decodeSuiPrivateKey } from '@mysten/sui/cryptography';
8
9
  import { createHash, randomBytes, createCipheriv, createDecipheriv, scryptSync } from 'crypto';
9
10
  import { access, mkdir, writeFile, readFile } from 'fs/promises';
10
- import { join, dirname, resolve } from 'path';
11
+ import { join as join$1, dirname, resolve } from 'path';
11
12
  import { homedir } from 'os';
12
- import { getPools, getUserAvailableLendingRewards, summaryLendingRewards, getLendingPositions, getHealthFactor as getHealthFactor$1, depositCoinPTB, withdrawCoinPTB, borrowCoinPTB, repayCoinPTB, claimLendingRewardsPTB, updateOraclePriceBeforeUserOperationPTB } from '@naviprotocol/lending';
13
+ import { SuiPriceServiceConnection, SuiPythClient } from '@pythnetwork/pyth-sui-js';
14
+ import { bcs as bcs$1 } from '@mysten/sui/bcs';
13
15
  import { readFileSync, existsSync, mkdirSync, writeFileSync } from 'fs';
14
16
 
17
+ var __create = Object.create;
15
18
  var __defProp = Object.defineProperty;
19
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
16
20
  var __getOwnPropNames = Object.getOwnPropertyNames;
21
+ var __getProtoOf = Object.getPrototypeOf;
22
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
23
+ var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
24
+ get: (a, b2) => (typeof require !== "undefined" ? require : a)[b2]
25
+ }) : x2)(function(x2) {
26
+ if (typeof require !== "undefined") return require.apply(this, arguments);
27
+ throw Error('Dynamic require of "' + x2 + '" is not supported');
28
+ });
17
29
  var __esm = (fn, res) => function __init() {
18
30
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
19
31
  };
32
+ var __commonJS = (cb, mod) => function __require2() {
33
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
34
+ };
20
35
  var __export = (target, all) => {
21
36
  for (var name in all)
22
37
  __defProp(target, name, { get: all[name], enumerable: true });
23
38
  };
39
+ var __copyProps = (to, from, except, desc) => {
40
+ if (from && typeof from === "object" || typeof from === "function") {
41
+ for (let key of __getOwnPropNames(from))
42
+ if (!__hasOwnProp.call(to, key) && key !== except)
43
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
44
+ }
45
+ return to;
46
+ };
47
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
48
+ // If the importer is in node compatibility mode or this is not an ESM
49
+ // file that has been converted to a CommonJS file using a Babel-
50
+ // compatible transform (i.e. "__esModule" has not been set), then set
51
+ // "default" to the CommonJS "module.exports" for node compatibility.
52
+ !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
53
+ mod
54
+ ));
24
55
 
25
56
  // src/errors.ts
26
57
  var errors_exports = {};
@@ -185,12 +216,12 @@ var init_token_registry = __esm({
185
216
  BY_TYPE.set(meta.type, meta);
186
217
  }
187
218
  TOKEN_MAP = (() => {
188
- const map = {};
219
+ const map2 = {};
189
220
  for (const [name, meta] of Object.entries(COIN_REGISTRY)) {
190
- map[name] = meta.type;
191
- map[name.toUpperCase()] = meta.type;
221
+ map2[name] = meta.type;
222
+ map2[name.toUpperCase()] = meta.type;
192
223
  }
193
- return map;
224
+ return map2;
194
225
  })();
195
226
  SUI_TYPE = COIN_REGISTRY.SUI.type;
196
227
  USDC_TYPE = COIN_REGISTRY.USDC.type;
@@ -207,6 +238,377 @@ var init_token_registry = __esm({
207
238
  }
208
239
  });
209
240
 
241
+ // ../../node_modules/.pnpm/lodash.camelcase@4.3.0/node_modules/lodash.camelcase/index.js
242
+ var require_lodash = __commonJS({
243
+ "../../node_modules/.pnpm/lodash.camelcase@4.3.0/node_modules/lodash.camelcase/index.js"(exports$1, module) {
244
+ var symbolTag = "[object Symbol]";
245
+ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
246
+ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
247
+ var rsAstralRange = "\\ud800-\\udfff";
248
+ var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23";
249
+ var rsComboSymbolsRange = "\\u20d0-\\u20f0";
250
+ var rsDingbatRange = "\\u2700-\\u27bf";
251
+ var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff";
252
+ var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7";
253
+ var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf";
254
+ var rsPunctuationRange = "\\u2000-\\u206f";
255
+ var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000";
256
+ var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde";
257
+ var rsVarRange = "\\ufe0e\\ufe0f";
258
+ var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
259
+ var rsApos = "['\u2019]";
260
+ var rsAstral = "[" + rsAstralRange + "]";
261
+ var rsBreak = "[" + rsBreakRange + "]";
262
+ var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]";
263
+ var rsDigits = "\\d+";
264
+ var rsDingbat = "[" + rsDingbatRange + "]";
265
+ var rsLower = "[" + rsLowerRange + "]";
266
+ var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]";
267
+ var rsFitz = "\\ud83c[\\udffb-\\udfff]";
268
+ var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")";
269
+ var rsNonAstral = "[^" + rsAstralRange + "]";
270
+ var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}";
271
+ var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]";
272
+ var rsUpper = "[" + rsUpperRange + "]";
273
+ var rsZWJ = "\\u200d";
274
+ var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")";
275
+ var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")";
276
+ var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?";
277
+ var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?";
278
+ var reOptMod = rsModifier + "?";
279
+ var rsOptVar = "[" + rsVarRange + "]?";
280
+ var rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*";
281
+ var rsSeq = rsOptVar + reOptMod + rsOptJoin;
282
+ var rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq;
283
+ var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")";
284
+ var reApos = RegExp(rsApos, "g");
285
+ var reComboMark = RegExp(rsCombo, "g");
286
+ var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
287
+ var reUnicodeWord = RegExp([
288
+ rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")",
289
+ rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [rsBreak, rsUpper + rsLowerMisc, "$"].join("|") + ")",
290
+ rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr,
291
+ rsUpper + "+" + rsOptUpperContr,
292
+ rsDigits,
293
+ rsEmoji
294
+ ].join("|"), "g");
295
+ var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]");
296
+ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
297
+ var deburredLetters = {
298
+ // Latin-1 Supplement block.
299
+ "\xC0": "A",
300
+ "\xC1": "A",
301
+ "\xC2": "A",
302
+ "\xC3": "A",
303
+ "\xC4": "A",
304
+ "\xC5": "A",
305
+ "\xE0": "a",
306
+ "\xE1": "a",
307
+ "\xE2": "a",
308
+ "\xE3": "a",
309
+ "\xE4": "a",
310
+ "\xE5": "a",
311
+ "\xC7": "C",
312
+ "\xE7": "c",
313
+ "\xD0": "D",
314
+ "\xF0": "d",
315
+ "\xC8": "E",
316
+ "\xC9": "E",
317
+ "\xCA": "E",
318
+ "\xCB": "E",
319
+ "\xE8": "e",
320
+ "\xE9": "e",
321
+ "\xEA": "e",
322
+ "\xEB": "e",
323
+ "\xCC": "I",
324
+ "\xCD": "I",
325
+ "\xCE": "I",
326
+ "\xCF": "I",
327
+ "\xEC": "i",
328
+ "\xED": "i",
329
+ "\xEE": "i",
330
+ "\xEF": "i",
331
+ "\xD1": "N",
332
+ "\xF1": "n",
333
+ "\xD2": "O",
334
+ "\xD3": "O",
335
+ "\xD4": "O",
336
+ "\xD5": "O",
337
+ "\xD6": "O",
338
+ "\xD8": "O",
339
+ "\xF2": "o",
340
+ "\xF3": "o",
341
+ "\xF4": "o",
342
+ "\xF5": "o",
343
+ "\xF6": "o",
344
+ "\xF8": "o",
345
+ "\xD9": "U",
346
+ "\xDA": "U",
347
+ "\xDB": "U",
348
+ "\xDC": "U",
349
+ "\xF9": "u",
350
+ "\xFA": "u",
351
+ "\xFB": "u",
352
+ "\xFC": "u",
353
+ "\xDD": "Y",
354
+ "\xFD": "y",
355
+ "\xFF": "y",
356
+ "\xC6": "Ae",
357
+ "\xE6": "ae",
358
+ "\xDE": "Th",
359
+ "\xFE": "th",
360
+ "\xDF": "ss",
361
+ // Latin Extended-A block.
362
+ "\u0100": "A",
363
+ "\u0102": "A",
364
+ "\u0104": "A",
365
+ "\u0101": "a",
366
+ "\u0103": "a",
367
+ "\u0105": "a",
368
+ "\u0106": "C",
369
+ "\u0108": "C",
370
+ "\u010A": "C",
371
+ "\u010C": "C",
372
+ "\u0107": "c",
373
+ "\u0109": "c",
374
+ "\u010B": "c",
375
+ "\u010D": "c",
376
+ "\u010E": "D",
377
+ "\u0110": "D",
378
+ "\u010F": "d",
379
+ "\u0111": "d",
380
+ "\u0112": "E",
381
+ "\u0114": "E",
382
+ "\u0116": "E",
383
+ "\u0118": "E",
384
+ "\u011A": "E",
385
+ "\u0113": "e",
386
+ "\u0115": "e",
387
+ "\u0117": "e",
388
+ "\u0119": "e",
389
+ "\u011B": "e",
390
+ "\u011C": "G",
391
+ "\u011E": "G",
392
+ "\u0120": "G",
393
+ "\u0122": "G",
394
+ "\u011D": "g",
395
+ "\u011F": "g",
396
+ "\u0121": "g",
397
+ "\u0123": "g",
398
+ "\u0124": "H",
399
+ "\u0126": "H",
400
+ "\u0125": "h",
401
+ "\u0127": "h",
402
+ "\u0128": "I",
403
+ "\u012A": "I",
404
+ "\u012C": "I",
405
+ "\u012E": "I",
406
+ "\u0130": "I",
407
+ "\u0129": "i",
408
+ "\u012B": "i",
409
+ "\u012D": "i",
410
+ "\u012F": "i",
411
+ "\u0131": "i",
412
+ "\u0134": "J",
413
+ "\u0135": "j",
414
+ "\u0136": "K",
415
+ "\u0137": "k",
416
+ "\u0138": "k",
417
+ "\u0139": "L",
418
+ "\u013B": "L",
419
+ "\u013D": "L",
420
+ "\u013F": "L",
421
+ "\u0141": "L",
422
+ "\u013A": "l",
423
+ "\u013C": "l",
424
+ "\u013E": "l",
425
+ "\u0140": "l",
426
+ "\u0142": "l",
427
+ "\u0143": "N",
428
+ "\u0145": "N",
429
+ "\u0147": "N",
430
+ "\u014A": "N",
431
+ "\u0144": "n",
432
+ "\u0146": "n",
433
+ "\u0148": "n",
434
+ "\u014B": "n",
435
+ "\u014C": "O",
436
+ "\u014E": "O",
437
+ "\u0150": "O",
438
+ "\u014D": "o",
439
+ "\u014F": "o",
440
+ "\u0151": "o",
441
+ "\u0154": "R",
442
+ "\u0156": "R",
443
+ "\u0158": "R",
444
+ "\u0155": "r",
445
+ "\u0157": "r",
446
+ "\u0159": "r",
447
+ "\u015A": "S",
448
+ "\u015C": "S",
449
+ "\u015E": "S",
450
+ "\u0160": "S",
451
+ "\u015B": "s",
452
+ "\u015D": "s",
453
+ "\u015F": "s",
454
+ "\u0161": "s",
455
+ "\u0162": "T",
456
+ "\u0164": "T",
457
+ "\u0166": "T",
458
+ "\u0163": "t",
459
+ "\u0165": "t",
460
+ "\u0167": "t",
461
+ "\u0168": "U",
462
+ "\u016A": "U",
463
+ "\u016C": "U",
464
+ "\u016E": "U",
465
+ "\u0170": "U",
466
+ "\u0172": "U",
467
+ "\u0169": "u",
468
+ "\u016B": "u",
469
+ "\u016D": "u",
470
+ "\u016F": "u",
471
+ "\u0171": "u",
472
+ "\u0173": "u",
473
+ "\u0174": "W",
474
+ "\u0175": "w",
475
+ "\u0176": "Y",
476
+ "\u0177": "y",
477
+ "\u0178": "Y",
478
+ "\u0179": "Z",
479
+ "\u017B": "Z",
480
+ "\u017D": "Z",
481
+ "\u017A": "z",
482
+ "\u017C": "z",
483
+ "\u017E": "z",
484
+ "\u0132": "IJ",
485
+ "\u0133": "ij",
486
+ "\u0152": "Oe",
487
+ "\u0153": "oe",
488
+ "\u0149": "'n",
489
+ "\u017F": "ss"
490
+ };
491
+ var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
492
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
493
+ var root = freeGlobal || freeSelf || Function("return this")();
494
+ function arrayReduce(array, iteratee, accumulator, initAccum) {
495
+ var index = -1, length = array ? array.length : 0;
496
+ while (++index < length) {
497
+ accumulator = iteratee(accumulator, array[index], index, array);
498
+ }
499
+ return accumulator;
500
+ }
501
+ function asciiToArray(string) {
502
+ return string.split("");
503
+ }
504
+ function asciiWords(string) {
505
+ return string.match(reAsciiWord) || [];
506
+ }
507
+ function basePropertyOf(object) {
508
+ return function(key) {
509
+ return object == null ? void 0 : object[key];
510
+ };
511
+ }
512
+ var deburrLetter = basePropertyOf(deburredLetters);
513
+ function hasUnicode(string) {
514
+ return reHasUnicode.test(string);
515
+ }
516
+ function hasUnicodeWord(string) {
517
+ return reHasUnicodeWord.test(string);
518
+ }
519
+ function stringToArray(string) {
520
+ return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string);
521
+ }
522
+ function unicodeToArray(string) {
523
+ return string.match(reUnicode) || [];
524
+ }
525
+ function unicodeWords(string) {
526
+ return string.match(reUnicodeWord) || [];
527
+ }
528
+ var objectProto = Object.prototype;
529
+ var objectToString = objectProto.toString;
530
+ var Symbol2 = root.Symbol;
531
+ var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
532
+ var symbolToString = symbolProto ? symbolProto.toString : void 0;
533
+ function baseSlice(array, start, end) {
534
+ var index = -1, length = array.length;
535
+ if (start < 0) {
536
+ start = -start > length ? 0 : length + start;
537
+ }
538
+ end = end > length ? length : end;
539
+ if (end < 0) {
540
+ end += length;
541
+ }
542
+ length = start > end ? 0 : end - start >>> 0;
543
+ start >>>= 0;
544
+ var result = Array(length);
545
+ while (++index < length) {
546
+ result[index] = array[index + start];
547
+ }
548
+ return result;
549
+ }
550
+ function baseToString(value) {
551
+ if (typeof value == "string") {
552
+ return value;
553
+ }
554
+ if (isSymbol(value)) {
555
+ return symbolToString ? symbolToString.call(value) : "";
556
+ }
557
+ var result = value + "";
558
+ return result == "0" && 1 / value == -Infinity ? "-0" : result;
559
+ }
560
+ function castSlice(array, start, end) {
561
+ var length = array.length;
562
+ end = end === void 0 ? length : end;
563
+ return !start && end >= length ? array : baseSlice(array, start, end);
564
+ }
565
+ function createCaseFirst(methodName) {
566
+ return function(string) {
567
+ string = toString(string);
568
+ var strSymbols = hasUnicode(string) ? stringToArray(string) : void 0;
569
+ var chr = strSymbols ? strSymbols[0] : string.charAt(0);
570
+ var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1);
571
+ return chr[methodName]() + trailing;
572
+ };
573
+ }
574
+ function createCompounder(callback) {
575
+ return function(string) {
576
+ return arrayReduce(words(deburr(string).replace(reApos, "")), callback, "");
577
+ };
578
+ }
579
+ function isObjectLike(value) {
580
+ return !!value && typeof value == "object";
581
+ }
582
+ function isSymbol(value) {
583
+ return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
584
+ }
585
+ function toString(value) {
586
+ return value == null ? "" : baseToString(value);
587
+ }
588
+ var camelCase = createCompounder(function(result, word, index) {
589
+ word = word.toLowerCase();
590
+ return result + (index ? capitalize(word) : word);
591
+ });
592
+ function capitalize(string) {
593
+ return upperFirst(toString(string).toLowerCase());
594
+ }
595
+ function deburr(string) {
596
+ string = toString(string);
597
+ return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "");
598
+ }
599
+ var upperFirst = createCaseFirst("toUpperCase");
600
+ function words(string, pattern, guard) {
601
+ string = toString(string);
602
+ pattern = pattern;
603
+ if (pattern === void 0) {
604
+ return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
605
+ }
606
+ return string.match(pattern) || [];
607
+ }
608
+ module.exports = camelCase;
609
+ }
610
+ });
611
+
210
612
  // src/protocols/volo.ts
211
613
  var volo_exports = {};
212
614
  __export(volo_exports, {
@@ -774,214 +1176,3818 @@ async function fetchSuiPrice(client) {
774
1176
  return _cachedSuiPrice;
775
1177
  }
776
1178
  try {
777
- const pool = await client.getObject({
778
- id: CETUS_USDC_SUI_POOL,
1179
+ const pool = await client.getObject({
1180
+ id: CETUS_USDC_SUI_POOL,
1181
+ options: { showContent: true }
1182
+ });
1183
+ if (pool.data?.content?.dataType === "moveObject") {
1184
+ const fields = pool.data.content.fields;
1185
+ const currentSqrtPrice = BigInt(String(fields.current_sqrt_price ?? "0"));
1186
+ if (currentSqrtPrice > 0n) {
1187
+ const Q64 = 2n ** 64n;
1188
+ const sqrtPriceFloat = Number(currentSqrtPrice) / Number(Q64);
1189
+ const rawPrice = sqrtPriceFloat * sqrtPriceFloat;
1190
+ const price = 1e3 / rawPrice;
1191
+ if (price > 0.01 && price < 1e3) {
1192
+ _cachedSuiPrice = price;
1193
+ _priceLastFetched = now;
1194
+ }
1195
+ }
1196
+ }
1197
+ } catch {
1198
+ }
1199
+ return _cachedSuiPrice || SUI_PRICE_FALLBACK;
1200
+ }
1201
+ async function queryBalance(client, address) {
1202
+ const stableBalancePromises = STABLE_ASSETS.map(
1203
+ (asset) => client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS[asset].type }).then((b2) => ({ asset, amount: Number(b2.totalBalance) / 10 ** SUPPORTED_ASSETS[asset].decimals })).catch(() => ({ asset, amount: 0 }))
1204
+ );
1205
+ const [suiBalance, suiPriceUsd, ...stableResults] = await Promise.all([
1206
+ client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS.SUI.type }),
1207
+ fetchSuiPrice(client),
1208
+ ...stableBalancePromises
1209
+ ]);
1210
+ const stables = {};
1211
+ let totalStables = 0;
1212
+ for (const { asset, amount } of stableResults) {
1213
+ stables[asset] = amount;
1214
+ totalStables += amount;
1215
+ }
1216
+ const suiAmount = Number(suiBalance.totalBalance) / Number(MIST_PER_SUI);
1217
+ const savings = 0;
1218
+ const usdEquiv = suiAmount * suiPriceUsd;
1219
+ const total = totalStables + savings + usdEquiv;
1220
+ return {
1221
+ available: totalStables,
1222
+ savings,
1223
+ debt: 0,
1224
+ pendingRewards: 0,
1225
+ gasReserve: {
1226
+ sui: suiAmount,
1227
+ usdEquiv
1228
+ },
1229
+ total,
1230
+ stables
1231
+ };
1232
+ }
1233
+
1234
+ // src/wallet/history.ts
1235
+ init_token_registry();
1236
+ var KNOWN_TARGETS = [
1237
+ [/::suilend|::obligation/, "lending"],
1238
+ [/::navi|::incentive_v\d+|::oracle_pro/, "lending"],
1239
+ [/::cetus|::pool/, "swap"],
1240
+ [/::deepbook/, "swap"],
1241
+ [/::transfer::public_transfer/, "send"]
1242
+ ];
1243
+ async function queryHistory(client, address, limit = 20) {
1244
+ const txns = await client.queryTransactionBlocks({
1245
+ filter: { FromAddress: address },
1246
+ options: { showEffects: true, showInput: true, showBalanceChanges: true },
1247
+ limit,
1248
+ order: "descending"
1249
+ });
1250
+ return txns.data.map((tx) => parseTxRecord(tx, address));
1251
+ }
1252
+ async function queryTransaction(client, digest, senderAddress) {
1253
+ try {
1254
+ const tx = await client.getTransactionBlock({
1255
+ digest,
1256
+ options: { showEffects: true, showInput: true, showBalanceChanges: true }
1257
+ });
1258
+ return parseTxRecord(tx, senderAddress);
1259
+ } catch {
1260
+ return null;
1261
+ }
1262
+ }
1263
+ function parseTxRecord(tx, address) {
1264
+ const gasUsed = tx.effects?.gasUsed;
1265
+ const gasCost = gasUsed ? (Number(gasUsed.computationCost) + Number(gasUsed.storageCost) - Number(gasUsed.storageRebate)) / 1e9 : void 0;
1266
+ const { moveCallTargets, commandTypes } = extractCommands(tx.transaction);
1267
+ const { amount, asset, recipient } = extractTransferDetails(tx.balanceChanges, address);
1268
+ const action = classifyAction(moveCallTargets, commandTypes);
1269
+ return {
1270
+ digest: tx.digest,
1271
+ action,
1272
+ amount,
1273
+ asset,
1274
+ recipient,
1275
+ timestamp: Number(tx.timestampMs ?? 0),
1276
+ gasCost
1277
+ };
1278
+ }
1279
+ function resolveOwner(owner) {
1280
+ if (typeof owner === "object" && owner.AddressOwner) return owner.AddressOwner;
1281
+ if (typeof owner === "string") return owner;
1282
+ return null;
1283
+ }
1284
+ function extractTransferDetails(changes, sender) {
1285
+ if (!changes || changes.length === 0) return {};
1286
+ const outflows = changes.filter((c) => resolveOwner(c.owner) === sender && BigInt(c.amount) < 0n);
1287
+ const inflows = changes.filter((c) => resolveOwner(c.owner) !== sender && BigInt(c.amount) > 0n);
1288
+ const primaryOutflow = outflows.filter((c) => c.coinType !== SUI_TYPE).sort((a, b2) => Number(BigInt(a.amount) - BigInt(b2.amount)))[0] ?? outflows[0];
1289
+ if (!primaryOutflow) return {};
1290
+ const coinType = primaryOutflow.coinType;
1291
+ const decimals = getDecimalsForCoinType(coinType);
1292
+ const amount = Math.abs(Number(BigInt(primaryOutflow.amount))) / 10 ** decimals;
1293
+ const asset = resolveSymbol(coinType);
1294
+ const recipientChange = inflows.find((c) => c.coinType === coinType);
1295
+ const recipient = recipientChange ? resolveOwner(recipientChange.owner) ?? void 0 : void 0;
1296
+ return { amount, asset, recipient };
1297
+ }
1298
+ function extractCommands(txBlock) {
1299
+ const result = { moveCallTargets: [], commandTypes: [] };
1300
+ try {
1301
+ if (!txBlock || typeof txBlock !== "object") return result;
1302
+ const data = "data" in txBlock ? txBlock.data : void 0;
1303
+ if (!data || typeof data !== "object") return result;
1304
+ const inner = "transaction" in data ? data.transaction : void 0;
1305
+ if (!inner || typeof inner !== "object") return result;
1306
+ const commands = "commands" in inner ? inner.commands : "transactions" in inner ? inner.transactions : void 0;
1307
+ if (!Array.isArray(commands)) return result;
1308
+ for (const cmd of commands) {
1309
+ if (cmd.MoveCall) {
1310
+ const mc = cmd.MoveCall;
1311
+ result.moveCallTargets.push(`${mc.package}::${mc.module}::${mc.function}`);
1312
+ result.commandTypes.push("MoveCall");
1313
+ } else if (cmd.TransferObjects) {
1314
+ result.commandTypes.push("TransferObjects");
1315
+ }
1316
+ }
1317
+ } catch {
1318
+ }
1319
+ return result;
1320
+ }
1321
+ function classifyAction(targets, commandTypes) {
1322
+ for (const target of targets) {
1323
+ for (const [pattern, label] of KNOWN_TARGETS) {
1324
+ if (pattern.test(target)) return label;
1325
+ }
1326
+ }
1327
+ const hasTransfer = commandTypes.includes("TransferObjects");
1328
+ const hasMoveCall = commandTypes.includes("MoveCall");
1329
+ if (hasTransfer && !hasMoveCall) return "send";
1330
+ if (hasMoveCall) return "transaction";
1331
+ return "transaction";
1332
+ }
1333
+
1334
+ // src/t2000.ts
1335
+ init_token_registry();
1336
+
1337
+ // src/protocols/protocolFee.ts
1338
+ var FEE_RATES = {
1339
+ save: SAVE_FEE_BPS,
1340
+ borrow: BORROW_FEE_BPS
1341
+ };
1342
+ var OP_CODES = {
1343
+ save: 0,
1344
+ borrow: 2
1345
+ };
1346
+ function calculateFee(operation, amount) {
1347
+ const bps = FEE_RATES[operation];
1348
+ const feeAmount = amount * Number(bps) / Number(BPS_DENOMINATOR);
1349
+ const rawAmount = usdcToRaw(feeAmount);
1350
+ return {
1351
+ amount: feeAmount,
1352
+ asset: "USDC",
1353
+ rate: Number(bps) / Number(BPS_DENOMINATOR),
1354
+ rawAmount
1355
+ };
1356
+ }
1357
+ function addCollectFeeToTx(tx, paymentCoin, operation) {
1358
+ const bps = FEE_RATES[operation];
1359
+ if (bps <= 0n) return;
1360
+ tx.moveCall({
1361
+ target: `${T2000_PACKAGE_ID}::treasury::collect_fee`,
1362
+ typeArguments: [SUPPORTED_ASSETS.USDC.type],
1363
+ arguments: [
1364
+ tx.object(T2000_TREASURY_ID),
1365
+ tx.object(T2000_CONFIG_ID),
1366
+ paymentCoin,
1367
+ tx.pure.u8(OP_CODES[operation])
1368
+ ]
1369
+ });
1370
+ }
1371
+ async function reportFee(agentAddress, operation, feeAmount, feeRate, txDigest) {
1372
+ try {
1373
+ await fetch(`${API_BASE_URL}/api/fees`, {
1374
+ method: "POST",
1375
+ headers: { "Content-Type": "application/json" },
1376
+ body: JSON.stringify({
1377
+ agentAddress,
1378
+ operation,
1379
+ feeAmount: feeAmount.toString(),
1380
+ feeRate: feeRate.toString(),
1381
+ txDigest
1382
+ })
1383
+ });
1384
+ } catch {
1385
+ }
1386
+ }
1387
+
1388
+ // ../../node_modules/.pnpm/@mysten+bcs@2.0.2/node_modules/@mysten/bcs/dist/uleb.mjs
1389
+ function ulebEncode(num) {
1390
+ let bigNum = BigInt(num);
1391
+ const arr = [];
1392
+ let len = 0;
1393
+ if (bigNum === 0n) return [0];
1394
+ while (bigNum > 0) {
1395
+ arr[len] = Number(bigNum & 127n);
1396
+ bigNum >>= 7n;
1397
+ if (bigNum > 0n) arr[len] |= 128;
1398
+ len += 1;
1399
+ }
1400
+ return arr;
1401
+ }
1402
+ function ulebDecode(arr) {
1403
+ let total = 0n;
1404
+ let shift = 0n;
1405
+ let len = 0;
1406
+ while (true) {
1407
+ if (len >= arr.length) throw new Error("ULEB decode error: buffer overflow");
1408
+ const byte = arr[len];
1409
+ len += 1;
1410
+ total += BigInt(byte & 127) << shift;
1411
+ if ((byte & 128) === 0) break;
1412
+ shift += 7n;
1413
+ }
1414
+ if (total > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("ULEB decode error: value exceeds MAX_SAFE_INTEGER");
1415
+ return {
1416
+ value: Number(total),
1417
+ length: len
1418
+ };
1419
+ }
1420
+
1421
+ // ../../node_modules/.pnpm/@mysten+bcs@2.0.2/node_modules/@mysten/bcs/dist/reader.mjs
1422
+ var BcsReader = class {
1423
+ /**
1424
+ * @param {Uint8Array} data Data to use as a buffer.
1425
+ */
1426
+ constructor(data) {
1427
+ this.bytePosition = 0;
1428
+ this.dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
1429
+ }
1430
+ /**
1431
+ * Shift current cursor position by `bytes`.
1432
+ *
1433
+ * @param {Number} bytes Number of bytes to
1434
+ * @returns {this} Self for possible chaining.
1435
+ */
1436
+ shift(bytes) {
1437
+ this.bytePosition += bytes;
1438
+ return this;
1439
+ }
1440
+ /**
1441
+ * Read U8 value from the buffer and shift cursor by 1.
1442
+ * @returns
1443
+ */
1444
+ read8() {
1445
+ const value = this.dataView.getUint8(this.bytePosition);
1446
+ this.shift(1);
1447
+ return value;
1448
+ }
1449
+ /**
1450
+ * Read U16 value from the buffer and shift cursor by 2.
1451
+ * @returns
1452
+ */
1453
+ read16() {
1454
+ const value = this.dataView.getUint16(this.bytePosition, true);
1455
+ this.shift(2);
1456
+ return value;
1457
+ }
1458
+ /**
1459
+ * Read U32 value from the buffer and shift cursor by 4.
1460
+ * @returns
1461
+ */
1462
+ read32() {
1463
+ const value = this.dataView.getUint32(this.bytePosition, true);
1464
+ this.shift(4);
1465
+ return value;
1466
+ }
1467
+ /**
1468
+ * Read U64 value from the buffer and shift cursor by 8.
1469
+ * @returns
1470
+ */
1471
+ read64() {
1472
+ const value1 = this.read32();
1473
+ const result = this.read32().toString(16) + value1.toString(16).padStart(8, "0");
1474
+ return BigInt("0x" + result).toString(10);
1475
+ }
1476
+ /**
1477
+ * Read U128 value from the buffer and shift cursor by 16.
1478
+ */
1479
+ read128() {
1480
+ const value1 = BigInt(this.read64());
1481
+ const result = BigInt(this.read64()).toString(16) + value1.toString(16).padStart(16, "0");
1482
+ return BigInt("0x" + result).toString(10);
1483
+ }
1484
+ /**
1485
+ * Read U128 value from the buffer and shift cursor by 32.
1486
+ * @returns
1487
+ */
1488
+ read256() {
1489
+ const value1 = BigInt(this.read128());
1490
+ const result = BigInt(this.read128()).toString(16) + value1.toString(16).padStart(32, "0");
1491
+ return BigInt("0x" + result).toString(10);
1492
+ }
1493
+ /**
1494
+ * Read `num` number of bytes from the buffer and shift cursor by `num`.
1495
+ * @param num Number of bytes to read.
1496
+ */
1497
+ readBytes(num) {
1498
+ const start = this.bytePosition + this.dataView.byteOffset;
1499
+ const value = new Uint8Array(this.dataView.buffer, start, num);
1500
+ this.shift(num);
1501
+ return value;
1502
+ }
1503
+ /**
1504
+ * Read ULEB value - an integer of varying size. Used for enum indexes and
1505
+ * vector lengths.
1506
+ * @returns {Number} The ULEB value.
1507
+ */
1508
+ readULEB() {
1509
+ const start = this.bytePosition + this.dataView.byteOffset;
1510
+ const { value, length } = ulebDecode(new Uint8Array(this.dataView.buffer, start));
1511
+ this.shift(length);
1512
+ return value;
1513
+ }
1514
+ /**
1515
+ * Read a BCS vector: read a length and then apply function `cb` X times
1516
+ * where X is the length of the vector, defined as ULEB in BCS bytes.
1517
+ * @param cb Callback to process elements of vector.
1518
+ * @returns {Array<Any>} Array of the resulting values, returned by callback.
1519
+ */
1520
+ readVec(cb) {
1521
+ const length = this.readULEB();
1522
+ const result = [];
1523
+ for (let i = 0; i < length; i++) result.push(cb(this, i, length));
1524
+ return result;
1525
+ }
1526
+ };
1527
+
1528
+ // ../../node_modules/.pnpm/@scure+base@2.0.0/node_modules/@scure/base/index.js
1529
+ function isBytes(a) {
1530
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1531
+ }
1532
+ function isArrayOf(isString, arr) {
1533
+ if (!Array.isArray(arr))
1534
+ return false;
1535
+ if (arr.length === 0)
1536
+ return true;
1537
+ if (isString) {
1538
+ return arr.every((item) => typeof item === "string");
1539
+ } else {
1540
+ return arr.every((item) => Number.isSafeInteger(item));
1541
+ }
1542
+ }
1543
+ function astr(label, input) {
1544
+ if (typeof input !== "string")
1545
+ throw new Error(`${label}: string expected`);
1546
+ return true;
1547
+ }
1548
+ function anumber(n) {
1549
+ if (!Number.isSafeInteger(n))
1550
+ throw new Error(`invalid integer: ${n}`);
1551
+ }
1552
+ function aArr(input) {
1553
+ if (!Array.isArray(input))
1554
+ throw new Error("array expected");
1555
+ }
1556
+ function astrArr(label, input) {
1557
+ if (!isArrayOf(true, input))
1558
+ throw new Error(`${label}: array of strings expected`);
1559
+ }
1560
+ function anumArr(label, input) {
1561
+ if (!isArrayOf(false, input))
1562
+ throw new Error(`${label}: array of numbers expected`);
1563
+ }
1564
+ // @__NO_SIDE_EFFECTS__
1565
+ function chain(...args) {
1566
+ const id = (a) => a;
1567
+ const wrap = (a, b2) => (c) => a(b2(c));
1568
+ const encode = args.map((x2) => x2.encode).reduceRight(wrap, id);
1569
+ const decode = args.map((x2) => x2.decode).reduce(wrap, id);
1570
+ return { encode, decode };
1571
+ }
1572
+ // @__NO_SIDE_EFFECTS__
1573
+ function alphabet(letters) {
1574
+ const lettersA = letters.split("") ;
1575
+ const len = lettersA.length;
1576
+ astrArr("alphabet", lettersA);
1577
+ const indexes = new Map(lettersA.map((l, i) => [l, i]));
1578
+ return {
1579
+ encode: (digits) => {
1580
+ aArr(digits);
1581
+ return digits.map((i) => {
1582
+ if (!Number.isSafeInteger(i) || i < 0 || i >= len)
1583
+ throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
1584
+ return lettersA[i];
1585
+ });
1586
+ },
1587
+ decode: (input) => {
1588
+ aArr(input);
1589
+ return input.map((letter) => {
1590
+ astr("alphabet.decode", letter);
1591
+ const i = indexes.get(letter);
1592
+ if (i === void 0)
1593
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
1594
+ return i;
1595
+ });
1596
+ }
1597
+ };
1598
+ }
1599
+ // @__NO_SIDE_EFFECTS__
1600
+ function join(separator = "") {
1601
+ astr("join", separator);
1602
+ return {
1603
+ encode: (from) => {
1604
+ astrArr("join.decode", from);
1605
+ return from.join(separator);
1606
+ },
1607
+ decode: (to) => {
1608
+ astr("join.decode", to);
1609
+ return to.split(separator);
1610
+ }
1611
+ };
1612
+ }
1613
+ function convertRadix(data, from, to) {
1614
+ if (from < 2)
1615
+ throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
1616
+ if (to < 2)
1617
+ throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
1618
+ aArr(data);
1619
+ if (!data.length)
1620
+ return [];
1621
+ let pos = 0;
1622
+ const res = [];
1623
+ const digits = Array.from(data, (d) => {
1624
+ anumber(d);
1625
+ if (d < 0 || d >= from)
1626
+ throw new Error(`invalid integer: ${d}`);
1627
+ return d;
1628
+ });
1629
+ const dlen = digits.length;
1630
+ while (true) {
1631
+ let carry = 0;
1632
+ let done = true;
1633
+ for (let i = pos; i < dlen; i++) {
1634
+ const digit = digits[i];
1635
+ const fromCarry = from * carry;
1636
+ const digitBase = fromCarry + digit;
1637
+ if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) {
1638
+ throw new Error("convertRadix: carry overflow");
1639
+ }
1640
+ const div = digitBase / to;
1641
+ carry = digitBase % to;
1642
+ const rounded = Math.floor(div);
1643
+ digits[i] = rounded;
1644
+ if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
1645
+ throw new Error("convertRadix: carry overflow");
1646
+ if (!done)
1647
+ continue;
1648
+ else if (!rounded)
1649
+ pos = i;
1650
+ else
1651
+ done = false;
1652
+ }
1653
+ res.push(carry);
1654
+ if (done)
1655
+ break;
1656
+ }
1657
+ for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
1658
+ res.push(0);
1659
+ return res.reverse();
1660
+ }
1661
+ // @__NO_SIDE_EFFECTS__
1662
+ function radix(num) {
1663
+ anumber(num);
1664
+ const _256 = 2 ** 8;
1665
+ return {
1666
+ encode: (bytes) => {
1667
+ if (!isBytes(bytes))
1668
+ throw new Error("radix.encode input should be Uint8Array");
1669
+ return convertRadix(Array.from(bytes), _256, num);
1670
+ },
1671
+ decode: (digits) => {
1672
+ anumArr("radix.decode", digits);
1673
+ return Uint8Array.from(convertRadix(digits, num, _256));
1674
+ }
1675
+ };
1676
+ }
1677
+ var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join(""));
1678
+ var base58 = /* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
1679
+
1680
+ // ../../node_modules/.pnpm/@mysten+utils@0.3.1/node_modules/@mysten/utils/dist/b58.mjs
1681
+ var toBase58 = (buffer) => base58.encode(buffer);
1682
+ var fromBase58 = (str) => base58.decode(str);
1683
+
1684
+ // ../../node_modules/.pnpm/@mysten+utils@0.3.1/node_modules/@mysten/utils/dist/b64.mjs
1685
+ function fromBase64(base64String) {
1686
+ return Uint8Array.from(atob(base64String), (char) => char.charCodeAt(0));
1687
+ }
1688
+ var CHUNK_SIZE = 8192;
1689
+ function toBase64(bytes) {
1690
+ if (bytes.length < CHUNK_SIZE) return btoa(String.fromCharCode(...bytes));
1691
+ let output = "";
1692
+ for (var i = 0; i < bytes.length; i += CHUNK_SIZE) {
1693
+ const chunk = bytes.slice(i, i + CHUNK_SIZE);
1694
+ output += String.fromCharCode(...chunk);
1695
+ }
1696
+ return btoa(output);
1697
+ }
1698
+
1699
+ // ../../node_modules/.pnpm/@mysten+utils@0.3.1/node_modules/@mysten/utils/dist/hex.mjs
1700
+ function fromHex(hexStr) {
1701
+ const normalized = hexStr.startsWith("0x") ? hexStr.slice(2) : hexStr;
1702
+ const padded = normalized.length % 2 === 0 ? normalized : `0${normalized}`;
1703
+ const intArr = padded.match(/[0-9a-fA-F]{2}/g)?.map((byte) => parseInt(byte, 16)) ?? [];
1704
+ if (intArr.length !== padded.length / 2) throw new Error(`Invalid hex string ${hexStr}`);
1705
+ return Uint8Array.from(intArr);
1706
+ }
1707
+ function toHex(bytes) {
1708
+ return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
1709
+ }
1710
+
1711
+ // ../../node_modules/.pnpm/@mysten+bcs@2.0.2/node_modules/@mysten/bcs/dist/utils.mjs
1712
+ function encodeStr(data, encoding) {
1713
+ switch (encoding) {
1714
+ case "base58":
1715
+ return toBase58(data);
1716
+ case "base64":
1717
+ return toBase64(data);
1718
+ case "hex":
1719
+ return toHex(data);
1720
+ default:
1721
+ throw new Error("Unsupported encoding, supported values are: base64, hex");
1722
+ }
1723
+ }
1724
+
1725
+ // ../../node_modules/.pnpm/@mysten+bcs@2.0.2/node_modules/@mysten/bcs/dist/writer.mjs
1726
+ var BcsWriter = class {
1727
+ constructor({ initialSize = 1024, maxSize = Infinity, allocateSize = 1024 } = {}) {
1728
+ this.bytePosition = 0;
1729
+ this.size = initialSize;
1730
+ this.maxSize = maxSize;
1731
+ this.allocateSize = allocateSize;
1732
+ this.dataView = new DataView(new ArrayBuffer(initialSize));
1733
+ }
1734
+ ensureSizeOrGrow(bytes) {
1735
+ const requiredSize = this.bytePosition + bytes;
1736
+ if (requiredSize > this.size) {
1737
+ const nextSize = Math.min(this.maxSize, Math.max(this.size + requiredSize, this.size + this.allocateSize));
1738
+ if (requiredSize > nextSize) throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${requiredSize}`);
1739
+ this.size = nextSize;
1740
+ const nextBuffer = new ArrayBuffer(this.size);
1741
+ new Uint8Array(nextBuffer).set(new Uint8Array(this.dataView.buffer));
1742
+ this.dataView = new DataView(nextBuffer);
1743
+ }
1744
+ }
1745
+ /**
1746
+ * Shift current cursor position by `bytes`.
1747
+ *
1748
+ * @param {Number} bytes Number of bytes to
1749
+ * @returns {this} Self for possible chaining.
1750
+ */
1751
+ shift(bytes) {
1752
+ this.bytePosition += bytes;
1753
+ return this;
1754
+ }
1755
+ /**
1756
+ * Write a U8 value into a buffer and shift cursor position by 1.
1757
+ * @param {Number} value Value to write.
1758
+ * @returns {this}
1759
+ */
1760
+ write8(value) {
1761
+ this.ensureSizeOrGrow(1);
1762
+ this.dataView.setUint8(this.bytePosition, Number(value));
1763
+ return this.shift(1);
1764
+ }
1765
+ /**
1766
+ * Write a U8 value into a buffer and shift cursor position by 1.
1767
+ * @param {Number} value Value to write.
1768
+ * @returns {this}
1769
+ */
1770
+ writeBytes(bytes) {
1771
+ this.ensureSizeOrGrow(bytes.length);
1772
+ for (let i = 0; i < bytes.length; i++) this.dataView.setUint8(this.bytePosition + i, bytes[i]);
1773
+ return this.shift(bytes.length);
1774
+ }
1775
+ /**
1776
+ * Write a U16 value into a buffer and shift cursor position by 2.
1777
+ * @param {Number} value Value to write.
1778
+ * @returns {this}
1779
+ */
1780
+ write16(value) {
1781
+ this.ensureSizeOrGrow(2);
1782
+ this.dataView.setUint16(this.bytePosition, Number(value), true);
1783
+ return this.shift(2);
1784
+ }
1785
+ /**
1786
+ * Write a U32 value into a buffer and shift cursor position by 4.
1787
+ * @param {Number} value Value to write.
1788
+ * @returns {this}
1789
+ */
1790
+ write32(value) {
1791
+ this.ensureSizeOrGrow(4);
1792
+ this.dataView.setUint32(this.bytePosition, Number(value), true);
1793
+ return this.shift(4);
1794
+ }
1795
+ /**
1796
+ * Write a U64 value into a buffer and shift cursor position by 8.
1797
+ * @param {bigint} value Value to write.
1798
+ * @returns {this}
1799
+ */
1800
+ write64(value) {
1801
+ toLittleEndian(BigInt(value), 8).forEach((el) => this.write8(el));
1802
+ return this;
1803
+ }
1804
+ /**
1805
+ * Write a U128 value into a buffer and shift cursor position by 16.
1806
+ *
1807
+ * @param {bigint} value Value to write.
1808
+ * @returns {this}
1809
+ */
1810
+ write128(value) {
1811
+ toLittleEndian(BigInt(value), 16).forEach((el) => this.write8(el));
1812
+ return this;
1813
+ }
1814
+ /**
1815
+ * Write a U256 value into a buffer and shift cursor position by 16.
1816
+ *
1817
+ * @param {bigint} value Value to write.
1818
+ * @returns {this}
1819
+ */
1820
+ write256(value) {
1821
+ toLittleEndian(BigInt(value), 32).forEach((el) => this.write8(el));
1822
+ return this;
1823
+ }
1824
+ /**
1825
+ * Write a ULEB value into a buffer and shift cursor position by number of bytes
1826
+ * written.
1827
+ * @param {Number} value Value to write.
1828
+ * @returns {this}
1829
+ */
1830
+ writeULEB(value) {
1831
+ ulebEncode(value).forEach((el) => this.write8(el));
1832
+ return this;
1833
+ }
1834
+ /**
1835
+ * Write a vector into a buffer by first writing the vector length and then calling
1836
+ * a callback on each passed value.
1837
+ *
1838
+ * @param {Array<Any>} vector Array of elements to write.
1839
+ * @param {WriteVecCb} cb Callback to call on each element of the vector.
1840
+ * @returns {this}
1841
+ */
1842
+ writeVec(vector2, cb) {
1843
+ this.writeULEB(vector2.length);
1844
+ Array.from(vector2).forEach((el, i) => cb(this, el, i, vector2.length));
1845
+ return this;
1846
+ }
1847
+ /**
1848
+ * Adds support for iterations over the object.
1849
+ * @returns {Uint8Array}
1850
+ */
1851
+ *[Symbol.iterator]() {
1852
+ for (let i = 0; i < this.bytePosition; i++) yield this.dataView.getUint8(i);
1853
+ return this.toBytes();
1854
+ }
1855
+ /**
1856
+ * Get underlying buffer taking only value bytes (in case initial buffer size was bigger).
1857
+ * @returns {Uint8Array} Resulting bcs.
1858
+ */
1859
+ toBytes() {
1860
+ return new Uint8Array(this.dataView.buffer.slice(0, this.bytePosition));
1861
+ }
1862
+ /**
1863
+ * Represent data as 'hex' or 'base64'
1864
+ * @param encoding Encoding to use: 'base64' or 'hex'
1865
+ */
1866
+ toString(encoding) {
1867
+ return encodeStr(this.toBytes(), encoding);
1868
+ }
1869
+ };
1870
+ function toLittleEndian(bigint, size) {
1871
+ const result = new Uint8Array(size);
1872
+ let i = 0;
1873
+ while (bigint > 0) {
1874
+ result[i] = Number(bigint % BigInt(256));
1875
+ bigint = bigint / BigInt(256);
1876
+ i += 1;
1877
+ }
1878
+ return result;
1879
+ }
1880
+
1881
+ // ../../node_modules/.pnpm/@mysten+bcs@2.0.2/node_modules/@mysten/bcs/dist/bcs-type.mjs
1882
+ var BcsType = class BcsType2 {
1883
+ #write;
1884
+ #serialize;
1885
+ constructor(options) {
1886
+ this.name = options.name;
1887
+ this.read = options.read;
1888
+ this.serializedSize = options.serializedSize ?? (() => null);
1889
+ this.#write = options.write;
1890
+ this.#serialize = options.serialize ?? ((value, options$1) => {
1891
+ const writer = new BcsWriter({
1892
+ initialSize: this.serializedSize(value) ?? void 0,
1893
+ ...options$1
1894
+ });
1895
+ this.#write(value, writer);
1896
+ return writer.toBytes();
1897
+ });
1898
+ this.validate = options.validate ?? (() => {
1899
+ });
1900
+ }
1901
+ write(value, writer) {
1902
+ this.validate(value);
1903
+ this.#write(value, writer);
1904
+ }
1905
+ serialize(value, options) {
1906
+ this.validate(value);
1907
+ return new SerializedBcs(this, this.#serialize(value, options));
1908
+ }
1909
+ parse(bytes) {
1910
+ const reader = new BcsReader(bytes);
1911
+ return this.read(reader);
1912
+ }
1913
+ fromHex(hex) {
1914
+ return this.parse(fromHex(hex));
1915
+ }
1916
+ fromBase58(b64) {
1917
+ return this.parse(fromBase58(b64));
1918
+ }
1919
+ fromBase64(b64) {
1920
+ return this.parse(fromBase64(b64));
1921
+ }
1922
+ transform({ name, input, output, validate }) {
1923
+ return new BcsType2({
1924
+ name: name ?? this.name,
1925
+ read: (reader) => output ? output(this.read(reader)) : this.read(reader),
1926
+ write: (value, writer) => this.#write(input ? input(value) : value, writer),
1927
+ serializedSize: (value) => this.serializedSize(input ? input(value) : value),
1928
+ serialize: (value, options) => this.#serialize(input ? input(value) : value, options),
1929
+ validate: (value) => {
1930
+ validate?.(value);
1931
+ this.validate(input ? input(value) : value);
1932
+ }
1933
+ });
1934
+ }
1935
+ };
1936
+ var SERIALIZED_BCS_BRAND = /* @__PURE__ */ Symbol.for("@mysten/serialized-bcs");
1937
+ var SerializedBcs = class {
1938
+ #schema;
1939
+ #bytes;
1940
+ get [SERIALIZED_BCS_BRAND]() {
1941
+ return true;
1942
+ }
1943
+ constructor(schema, bytes) {
1944
+ this.#schema = schema;
1945
+ this.#bytes = bytes;
1946
+ }
1947
+ toBytes() {
1948
+ return this.#bytes;
1949
+ }
1950
+ toHex() {
1951
+ return toHex(this.#bytes);
1952
+ }
1953
+ toBase64() {
1954
+ return toBase64(this.#bytes);
1955
+ }
1956
+ toBase58() {
1957
+ return toBase58(this.#bytes);
1958
+ }
1959
+ parse() {
1960
+ return this.#schema.parse(this.#bytes);
1961
+ }
1962
+ };
1963
+ function fixedSizeBcsType({ size, ...options }) {
1964
+ return new BcsType({
1965
+ ...options,
1966
+ serializedSize: () => size
1967
+ });
1968
+ }
1969
+ function uIntBcsType({ readMethod, writeMethod, ...options }) {
1970
+ return fixedSizeBcsType({
1971
+ ...options,
1972
+ read: (reader) => reader[readMethod](),
1973
+ write: (value, writer) => writer[writeMethod](value),
1974
+ validate: (value) => {
1975
+ if (value < 0 || value > options.maxValue) throw new TypeError(`Invalid ${options.name} value: ${value}. Expected value in range 0-${options.maxValue}`);
1976
+ options.validate?.(value);
1977
+ }
1978
+ });
1979
+ }
1980
+ function bigUIntBcsType({ readMethod, writeMethod, ...options }) {
1981
+ return fixedSizeBcsType({
1982
+ ...options,
1983
+ read: (reader) => reader[readMethod](),
1984
+ write: (value, writer) => writer[writeMethod](BigInt(value)),
1985
+ validate: (val) => {
1986
+ const value = BigInt(val);
1987
+ if (value < 0 || value > options.maxValue) throw new TypeError(`Invalid ${options.name} value: ${value}. Expected value in range 0-${options.maxValue}`);
1988
+ options.validate?.(value);
1989
+ }
1990
+ });
1991
+ }
1992
+ function dynamicSizeBcsType({ serialize, ...options }) {
1993
+ const type = new BcsType({
1994
+ ...options,
1995
+ serialize,
1996
+ write: (value, writer) => {
1997
+ for (const byte of type.serialize(value).toBytes()) writer.write8(byte);
1998
+ }
1999
+ });
2000
+ return type;
2001
+ }
2002
+ function stringLikeBcsType({ toBytes, fromBytes, ...options }) {
2003
+ return new BcsType({
2004
+ ...options,
2005
+ read: (reader) => {
2006
+ const length = reader.readULEB();
2007
+ return fromBytes(reader.readBytes(length));
2008
+ },
2009
+ write: (hex, writer) => {
2010
+ const bytes = toBytes(hex);
2011
+ writer.writeULEB(bytes.length);
2012
+ for (let i = 0; i < bytes.length; i++) writer.write8(bytes[i]);
2013
+ },
2014
+ serialize: (value) => {
2015
+ const bytes = toBytes(value);
2016
+ const size = ulebEncode(bytes.length);
2017
+ const result = new Uint8Array(size.length + bytes.length);
2018
+ result.set(size, 0);
2019
+ result.set(bytes, size.length);
2020
+ return result;
2021
+ },
2022
+ validate: (value) => {
2023
+ if (typeof value !== "string") throw new TypeError(`Invalid ${options.name} value: ${value}. Expected string`);
2024
+ options.validate?.(value);
2025
+ }
2026
+ });
2027
+ }
2028
+ function lazyBcsType(cb) {
2029
+ let lazyType = null;
2030
+ function getType() {
2031
+ if (!lazyType) lazyType = cb();
2032
+ return lazyType;
2033
+ }
2034
+ return new BcsType({
2035
+ name: "lazy",
2036
+ read: (data) => getType().read(data),
2037
+ serializedSize: (value) => getType().serializedSize(value),
2038
+ write: (value, writer) => getType().write(value, writer),
2039
+ serialize: (value, options) => getType().serialize(value, options).toBytes()
2040
+ });
2041
+ }
2042
+ var BcsStruct = class extends BcsType {
2043
+ constructor({ name, fields, ...options }) {
2044
+ const canonicalOrder = Object.entries(fields);
2045
+ super({
2046
+ name,
2047
+ serializedSize: (values) => {
2048
+ let total = 0;
2049
+ for (const [field, type] of canonicalOrder) {
2050
+ const size = type.serializedSize(values[field]);
2051
+ if (size == null) return null;
2052
+ total += size;
2053
+ }
2054
+ return total;
2055
+ },
2056
+ read: (reader) => {
2057
+ const result = {};
2058
+ for (const [field, type] of canonicalOrder) result[field] = type.read(reader);
2059
+ return result;
2060
+ },
2061
+ write: (value, writer) => {
2062
+ for (const [field, type] of canonicalOrder) type.write(value[field], writer);
2063
+ },
2064
+ ...options,
2065
+ validate: (value) => {
2066
+ options?.validate?.(value);
2067
+ if (typeof value !== "object" || value == null) throw new TypeError(`Expected object, found ${typeof value}`);
2068
+ }
2069
+ });
2070
+ }
2071
+ };
2072
+ var BcsEnum = class extends BcsType {
2073
+ constructor({ fields, ...options }) {
2074
+ const canonicalOrder = Object.entries(fields);
2075
+ super({
2076
+ read: (reader) => {
2077
+ const index = reader.readULEB();
2078
+ const enumEntry = canonicalOrder[index];
2079
+ if (!enumEntry) throw new TypeError(`Unknown value ${index} for enum ${options.name}`);
2080
+ const [kind, type] = enumEntry;
2081
+ return {
2082
+ [kind]: type?.read(reader) ?? true,
2083
+ $kind: kind
2084
+ };
2085
+ },
2086
+ write: (value, writer) => {
2087
+ const [name, val] = Object.entries(value).filter(([name$1]) => Object.hasOwn(fields, name$1))[0];
2088
+ for (let i = 0; i < canonicalOrder.length; i++) {
2089
+ const [optionName, optionType] = canonicalOrder[i];
2090
+ if (optionName === name) {
2091
+ writer.writeULEB(i);
2092
+ optionType?.write(val, writer);
2093
+ return;
2094
+ }
2095
+ }
2096
+ },
2097
+ ...options,
2098
+ validate: (value) => {
2099
+ options?.validate?.(value);
2100
+ if (typeof value !== "object" || value == null) throw new TypeError(`Expected object, found ${typeof value}`);
2101
+ const keys = Object.keys(value).filter((k2) => value[k2] !== void 0 && Object.hasOwn(fields, k2));
2102
+ if (keys.length !== 1) throw new TypeError(`Expected object with one key, but found ${keys.length} for type ${options.name}}`);
2103
+ const [variant] = keys;
2104
+ if (!Object.hasOwn(fields, variant)) throw new TypeError(`Invalid enum variant ${variant}`);
2105
+ }
2106
+ });
2107
+ }
2108
+ };
2109
+ var BcsTuple = class extends BcsType {
2110
+ constructor({ fields, name, ...options }) {
2111
+ super({
2112
+ name: name ?? `(${fields.map((t) => t.name).join(", ")})`,
2113
+ serializedSize: (values) => {
2114
+ let total = 0;
2115
+ for (let i = 0; i < fields.length; i++) {
2116
+ const size = fields[i].serializedSize(values[i]);
2117
+ if (size == null) return null;
2118
+ total += size;
2119
+ }
2120
+ return total;
2121
+ },
2122
+ read: (reader) => {
2123
+ const result = [];
2124
+ for (const field of fields) result.push(field.read(reader));
2125
+ return result;
2126
+ },
2127
+ write: (value, writer) => {
2128
+ for (let i = 0; i < fields.length; i++) fields[i].write(value[i], writer);
2129
+ },
2130
+ ...options,
2131
+ validate: (value) => {
2132
+ options?.validate?.(value);
2133
+ if (!Array.isArray(value)) throw new TypeError(`Expected array, found ${typeof value}`);
2134
+ if (value.length !== fields.length) throw new TypeError(`Expected array of length ${fields.length}, found ${value.length}`);
2135
+ }
2136
+ });
2137
+ }
2138
+ };
2139
+
2140
+ // ../../node_modules/.pnpm/@mysten+bcs@2.0.2/node_modules/@mysten/bcs/dist/bcs.mjs
2141
+ function fixedArray(size, type, options) {
2142
+ return new BcsType({
2143
+ read: (reader) => {
2144
+ const result = new Array(size);
2145
+ for (let i = 0; i < size; i++) result[i] = type.read(reader);
2146
+ return result;
2147
+ },
2148
+ write: (value, writer) => {
2149
+ for (const item of value) type.write(item, writer);
2150
+ },
2151
+ ...options,
2152
+ name: options?.name ?? `${type.name}[${size}]`,
2153
+ validate: (value) => {
2154
+ options?.validate?.(value);
2155
+ if (!value || typeof value !== "object" || !("length" in value)) throw new TypeError(`Expected array, found ${typeof value}`);
2156
+ if (value.length !== size) throw new TypeError(`Expected array of length ${size}, found ${value.length}`);
2157
+ }
2158
+ });
2159
+ }
2160
+ function option(type) {
2161
+ return bcs.enum(`Option<${type.name}>`, {
2162
+ None: null,
2163
+ Some: type
2164
+ }).transform({
2165
+ input: (value) => {
2166
+ if (value == null) return { None: true };
2167
+ return { Some: value };
2168
+ },
2169
+ output: (value) => {
2170
+ if (value.$kind === "Some") return value.Some;
2171
+ return null;
2172
+ }
2173
+ });
2174
+ }
2175
+ function vector(type, options) {
2176
+ return new BcsType({
2177
+ read: (reader) => {
2178
+ const length = reader.readULEB();
2179
+ const result = new Array(length);
2180
+ for (let i = 0; i < length; i++) result[i] = type.read(reader);
2181
+ return result;
2182
+ },
2183
+ write: (value, writer) => {
2184
+ writer.writeULEB(value.length);
2185
+ for (const item of value) type.write(item, writer);
2186
+ },
2187
+ ...options,
2188
+ name: options?.name ?? `vector<${type.name}>`,
2189
+ validate: (value) => {
2190
+ options?.validate?.(value);
2191
+ if (!value || typeof value !== "object" || !("length" in value)) throw new TypeError(`Expected array, found ${typeof value}`);
2192
+ }
2193
+ });
2194
+ }
2195
+ function compareBcsBytes(a, b2) {
2196
+ for (let i = 0; i < Math.min(a.length, b2.length); i++) if (a[i] !== b2[i]) return a[i] - b2[i];
2197
+ return a.length - b2.length;
2198
+ }
2199
+ function map(keyType, valueType) {
2200
+ return new BcsType({
2201
+ name: `Map<${keyType.name}, ${valueType.name}>`,
2202
+ read: (reader) => {
2203
+ const length = reader.readULEB();
2204
+ const result = /* @__PURE__ */ new Map();
2205
+ for (let i = 0; i < length; i++) result.set(keyType.read(reader), valueType.read(reader));
2206
+ return result;
2207
+ },
2208
+ write: (value, writer) => {
2209
+ const entries = [...value.entries()].map(([key, val]) => [keyType.serialize(key).toBytes(), val]);
2210
+ entries.sort(([a], [b2]) => compareBcsBytes(a, b2));
2211
+ writer.writeULEB(entries.length);
2212
+ for (const [keyBytes, val] of entries) {
2213
+ writer.writeBytes(keyBytes);
2214
+ valueType.write(val, writer);
2215
+ }
2216
+ }
2217
+ });
2218
+ }
2219
+ var bcs = {
2220
+ u8(options) {
2221
+ return uIntBcsType({
2222
+ readMethod: "read8",
2223
+ writeMethod: "write8",
2224
+ size: 1,
2225
+ maxValue: 2 ** 8 - 1,
2226
+ ...options,
2227
+ name: options?.name ?? "u8"
2228
+ });
2229
+ },
2230
+ u16(options) {
2231
+ return uIntBcsType({
2232
+ readMethod: "read16",
2233
+ writeMethod: "write16",
2234
+ size: 2,
2235
+ maxValue: 2 ** 16 - 1,
2236
+ ...options,
2237
+ name: options?.name ?? "u16"
2238
+ });
2239
+ },
2240
+ u32(options) {
2241
+ return uIntBcsType({
2242
+ readMethod: "read32",
2243
+ writeMethod: "write32",
2244
+ size: 4,
2245
+ maxValue: 2 ** 32 - 1,
2246
+ ...options,
2247
+ name: options?.name ?? "u32"
2248
+ });
2249
+ },
2250
+ u64(options) {
2251
+ return bigUIntBcsType({
2252
+ readMethod: "read64",
2253
+ writeMethod: "write64",
2254
+ size: 8,
2255
+ maxValue: 2n ** 64n - 1n,
2256
+ ...options,
2257
+ name: options?.name ?? "u64"
2258
+ });
2259
+ },
2260
+ u128(options) {
2261
+ return bigUIntBcsType({
2262
+ readMethod: "read128",
2263
+ writeMethod: "write128",
2264
+ size: 16,
2265
+ maxValue: 2n ** 128n - 1n,
2266
+ ...options,
2267
+ name: options?.name ?? "u128"
2268
+ });
2269
+ },
2270
+ u256(options) {
2271
+ return bigUIntBcsType({
2272
+ readMethod: "read256",
2273
+ writeMethod: "write256",
2274
+ size: 32,
2275
+ maxValue: 2n ** 256n - 1n,
2276
+ ...options,
2277
+ name: options?.name ?? "u256"
2278
+ });
2279
+ },
2280
+ bool(options) {
2281
+ return fixedSizeBcsType({
2282
+ size: 1,
2283
+ read: (reader) => reader.read8() === 1,
2284
+ write: (value, writer) => writer.write8(value ? 1 : 0),
2285
+ ...options,
2286
+ name: options?.name ?? "bool",
2287
+ validate: (value) => {
2288
+ options?.validate?.(value);
2289
+ if (typeof value !== "boolean") throw new TypeError(`Expected boolean, found ${typeof value}`);
2290
+ }
2291
+ });
2292
+ },
2293
+ uleb128(options) {
2294
+ return dynamicSizeBcsType({
2295
+ read: (reader) => reader.readULEB(),
2296
+ serialize: (value) => {
2297
+ return Uint8Array.from(ulebEncode(value));
2298
+ },
2299
+ ...options,
2300
+ name: options?.name ?? "uleb128"
2301
+ });
2302
+ },
2303
+ bytes(size, options) {
2304
+ return fixedSizeBcsType({
2305
+ size,
2306
+ read: (reader) => reader.readBytes(size),
2307
+ write: (value, writer) => {
2308
+ writer.writeBytes(new Uint8Array(value));
2309
+ },
2310
+ ...options,
2311
+ name: options?.name ?? `bytes[${size}]`,
2312
+ validate: (value) => {
2313
+ options?.validate?.(value);
2314
+ if (!value || typeof value !== "object" || !("length" in value)) throw new TypeError(`Expected array, found ${typeof value}`);
2315
+ if (value.length !== size) throw new TypeError(`Expected array of length ${size}, found ${value.length}`);
2316
+ }
2317
+ });
2318
+ },
2319
+ byteVector(options) {
2320
+ return new BcsType({
2321
+ read: (reader) => {
2322
+ const length = reader.readULEB();
2323
+ return reader.readBytes(length);
2324
+ },
2325
+ write: (value, writer) => {
2326
+ const array = new Uint8Array(value);
2327
+ writer.writeULEB(array.length);
2328
+ writer.writeBytes(array);
2329
+ },
2330
+ ...options,
2331
+ name: options?.name ?? "vector<u8>",
2332
+ serializedSize: (value) => {
2333
+ const length = "length" in value ? value.length : null;
2334
+ return length == null ? null : ulebEncode(length).length + length;
2335
+ },
2336
+ validate: (value) => {
2337
+ options?.validate?.(value);
2338
+ if (!value || typeof value !== "object" || !("length" in value)) throw new TypeError(`Expected array, found ${typeof value}`);
2339
+ }
2340
+ });
2341
+ },
2342
+ string(options) {
2343
+ return stringLikeBcsType({
2344
+ toBytes: (value) => new TextEncoder().encode(value),
2345
+ fromBytes: (bytes) => new TextDecoder().decode(bytes),
2346
+ ...options,
2347
+ name: options?.name ?? "string"
2348
+ });
2349
+ },
2350
+ fixedArray,
2351
+ option,
2352
+ vector,
2353
+ tuple(fields, options) {
2354
+ return new BcsTuple({
2355
+ fields,
2356
+ ...options
2357
+ });
2358
+ },
2359
+ struct(name, fields, options) {
2360
+ return new BcsStruct({
2361
+ name,
2362
+ fields,
2363
+ ...options
2364
+ });
2365
+ },
2366
+ enum(name, fields, options) {
2367
+ return new BcsEnum({
2368
+ name,
2369
+ fields,
2370
+ ...options
2371
+ });
2372
+ },
2373
+ map,
2374
+ lazy(cb) {
2375
+ return lazyBcsType(cb);
2376
+ }
2377
+ };
2378
+
2379
+ // ../../node_modules/.pnpm/@naviprotocol+lending@1.4.0_patch_hash=f5361914099eac610a549dc571b1248d29f6a1f4195ed017_05ba4b180e35cb4ccd9db84691f20fcb/node_modules/@naviprotocol/lending/dist/index.esm.js
2380
+ __toESM(require_lodash());
2381
+
2382
+ // ../../node_modules/.pnpm/bignumber.js@9.1.2/node_modules/bignumber.js/bignumber.mjs
2383
+ var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
2384
+ var mathceil = Math.ceil;
2385
+ var mathfloor = Math.floor;
2386
+ var bignumberError = "[BigNumber Error] ";
2387
+ var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: ";
2388
+ var BASE = 1e14;
2389
+ var LOG_BASE = 14;
2390
+ var MAX_SAFE_INTEGER = 9007199254740991;
2391
+ var POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13];
2392
+ var SQRT_BASE = 1e7;
2393
+ var MAX = 1e9;
2394
+ function clone(configObject) {
2395
+ var div, convertBase, parseNumeric, P2 = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = {
2396
+ prefix: "",
2397
+ groupSize: 3,
2398
+ secondaryGroupSize: 0,
2399
+ groupSeparator: ",",
2400
+ decimalSeparator: ".",
2401
+ fractionGroupSize: 0,
2402
+ fractionGroupSeparator: "\xA0",
2403
+ // non-breaking space
2404
+ suffix: ""
2405
+ }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true;
2406
+ function BigNumber2(v, b2) {
2407
+ var alphabet2, c, caseChanged, e, i, isNum, len, str, x2 = this;
2408
+ if (!(x2 instanceof BigNumber2)) return new BigNumber2(v, b2);
2409
+ if (b2 == null) {
2410
+ if (v && v._isBigNumber === true) {
2411
+ x2.s = v.s;
2412
+ if (!v.c || v.e > MAX_EXP) {
2413
+ x2.c = x2.e = null;
2414
+ } else if (v.e < MIN_EXP) {
2415
+ x2.c = [x2.e = 0];
2416
+ } else {
2417
+ x2.e = v.e;
2418
+ x2.c = v.c.slice();
2419
+ }
2420
+ return;
2421
+ }
2422
+ if ((isNum = typeof v == "number") && v * 0 == 0) {
2423
+ x2.s = 1 / v < 0 ? (v = -v, -1) : 1;
2424
+ if (v === ~~v) {
2425
+ for (e = 0, i = v; i >= 10; i /= 10, e++) ;
2426
+ if (e > MAX_EXP) {
2427
+ x2.c = x2.e = null;
2428
+ } else {
2429
+ x2.e = e;
2430
+ x2.c = [v];
2431
+ }
2432
+ return;
2433
+ }
2434
+ str = String(v);
2435
+ } else {
2436
+ if (!isNumeric.test(str = String(v))) return parseNumeric(x2, str, isNum);
2437
+ x2.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;
2438
+ }
2439
+ if ((e = str.indexOf(".")) > -1) str = str.replace(".", "");
2440
+ if ((i = str.search(/e/i)) > 0) {
2441
+ if (e < 0) e = i;
2442
+ e += +str.slice(i + 1);
2443
+ str = str.substring(0, i);
2444
+ } else if (e < 0) {
2445
+ e = str.length;
2446
+ }
2447
+ } else {
2448
+ intCheck(b2, 2, ALPHABET.length, "Base");
2449
+ if (b2 == 10 && alphabetHasNormalDecimalDigits) {
2450
+ x2 = new BigNumber2(v);
2451
+ return round(x2, DECIMAL_PLACES + x2.e + 1, ROUNDING_MODE);
2452
+ }
2453
+ str = String(v);
2454
+ if (isNum = typeof v == "number") {
2455
+ if (v * 0 != 0) return parseNumeric(x2, str, isNum, b2);
2456
+ x2.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;
2457
+ if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) {
2458
+ throw Error(tooManyDigits + v);
2459
+ }
2460
+ } else {
2461
+ x2.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;
2462
+ }
2463
+ alphabet2 = ALPHABET.slice(0, b2);
2464
+ e = i = 0;
2465
+ for (len = str.length; i < len; i++) {
2466
+ if (alphabet2.indexOf(c = str.charAt(i)) < 0) {
2467
+ if (c == ".") {
2468
+ if (i > e) {
2469
+ e = len;
2470
+ continue;
2471
+ }
2472
+ } else if (!caseChanged) {
2473
+ if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) {
2474
+ caseChanged = true;
2475
+ i = -1;
2476
+ e = 0;
2477
+ continue;
2478
+ }
2479
+ }
2480
+ return parseNumeric(x2, String(v), isNum, b2);
2481
+ }
2482
+ }
2483
+ isNum = false;
2484
+ str = convertBase(str, b2, 10, x2.s);
2485
+ if ((e = str.indexOf(".")) > -1) str = str.replace(".", "");
2486
+ else e = str.length;
2487
+ }
2488
+ for (i = 0; str.charCodeAt(i) === 48; i++) ;
2489
+ for (len = str.length; str.charCodeAt(--len) === 48; ) ;
2490
+ if (str = str.slice(i, ++len)) {
2491
+ len -= i;
2492
+ if (isNum && BigNumber2.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {
2493
+ throw Error(tooManyDigits + x2.s * v);
2494
+ }
2495
+ if ((e = e - i - 1) > MAX_EXP) {
2496
+ x2.c = x2.e = null;
2497
+ } else if (e < MIN_EXP) {
2498
+ x2.c = [x2.e = 0];
2499
+ } else {
2500
+ x2.e = e;
2501
+ x2.c = [];
2502
+ i = (e + 1) % LOG_BASE;
2503
+ if (e < 0) i += LOG_BASE;
2504
+ if (i < len) {
2505
+ if (i) x2.c.push(+str.slice(0, i));
2506
+ for (len -= LOG_BASE; i < len; ) {
2507
+ x2.c.push(+str.slice(i, i += LOG_BASE));
2508
+ }
2509
+ i = LOG_BASE - (str = str.slice(i)).length;
2510
+ } else {
2511
+ i -= len;
2512
+ }
2513
+ for (; i--; str += "0") ;
2514
+ x2.c.push(+str);
2515
+ }
2516
+ } else {
2517
+ x2.c = [x2.e = 0];
2518
+ }
2519
+ }
2520
+ BigNumber2.clone = clone;
2521
+ BigNumber2.ROUND_UP = 0;
2522
+ BigNumber2.ROUND_DOWN = 1;
2523
+ BigNumber2.ROUND_CEIL = 2;
2524
+ BigNumber2.ROUND_FLOOR = 3;
2525
+ BigNumber2.ROUND_HALF_UP = 4;
2526
+ BigNumber2.ROUND_HALF_DOWN = 5;
2527
+ BigNumber2.ROUND_HALF_EVEN = 6;
2528
+ BigNumber2.ROUND_HALF_CEIL = 7;
2529
+ BigNumber2.ROUND_HALF_FLOOR = 8;
2530
+ BigNumber2.EUCLID = 9;
2531
+ BigNumber2.config = BigNumber2.set = function(obj) {
2532
+ var p, v;
2533
+ if (obj != null) {
2534
+ if (typeof obj == "object") {
2535
+ if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) {
2536
+ v = obj[p];
2537
+ intCheck(v, 0, MAX, p);
2538
+ DECIMAL_PLACES = v;
2539
+ }
2540
+ if (obj.hasOwnProperty(p = "ROUNDING_MODE")) {
2541
+ v = obj[p];
2542
+ intCheck(v, 0, 8, p);
2543
+ ROUNDING_MODE = v;
2544
+ }
2545
+ if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) {
2546
+ v = obj[p];
2547
+ if (v && v.pop) {
2548
+ intCheck(v[0], -MAX, 0, p);
2549
+ intCheck(v[1], 0, MAX, p);
2550
+ TO_EXP_NEG = v[0];
2551
+ TO_EXP_POS = v[1];
2552
+ } else {
2553
+ intCheck(v, -MAX, MAX, p);
2554
+ TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);
2555
+ }
2556
+ }
2557
+ if (obj.hasOwnProperty(p = "RANGE")) {
2558
+ v = obj[p];
2559
+ if (v && v.pop) {
2560
+ intCheck(v[0], -MAX, -1, p);
2561
+ intCheck(v[1], 1, MAX, p);
2562
+ MIN_EXP = v[0];
2563
+ MAX_EXP = v[1];
2564
+ } else {
2565
+ intCheck(v, -MAX, MAX, p);
2566
+ if (v) {
2567
+ MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);
2568
+ } else {
2569
+ throw Error(bignumberError + p + " cannot be zero: " + v);
2570
+ }
2571
+ }
2572
+ }
2573
+ if (obj.hasOwnProperty(p = "CRYPTO")) {
2574
+ v = obj[p];
2575
+ if (v === !!v) {
2576
+ if (v) {
2577
+ if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
2578
+ CRYPTO = v;
2579
+ } else {
2580
+ CRYPTO = !v;
2581
+ throw Error(bignumberError + "crypto unavailable");
2582
+ }
2583
+ } else {
2584
+ CRYPTO = v;
2585
+ }
2586
+ } else {
2587
+ throw Error(bignumberError + p + " not true or false: " + v);
2588
+ }
2589
+ }
2590
+ if (obj.hasOwnProperty(p = "MODULO_MODE")) {
2591
+ v = obj[p];
2592
+ intCheck(v, 0, 9, p);
2593
+ MODULO_MODE = v;
2594
+ }
2595
+ if (obj.hasOwnProperty(p = "POW_PRECISION")) {
2596
+ v = obj[p];
2597
+ intCheck(v, 0, MAX, p);
2598
+ POW_PRECISION = v;
2599
+ }
2600
+ if (obj.hasOwnProperty(p = "FORMAT")) {
2601
+ v = obj[p];
2602
+ if (typeof v == "object") FORMAT = v;
2603
+ else throw Error(bignumberError + p + " not an object: " + v);
2604
+ }
2605
+ if (obj.hasOwnProperty(p = "ALPHABET")) {
2606
+ v = obj[p];
2607
+ if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) {
2608
+ alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789";
2609
+ ALPHABET = v;
2610
+ } else {
2611
+ throw Error(bignumberError + p + " invalid: " + v);
2612
+ }
2613
+ }
2614
+ } else {
2615
+ throw Error(bignumberError + "Object expected: " + obj);
2616
+ }
2617
+ }
2618
+ return {
2619
+ DECIMAL_PLACES,
2620
+ ROUNDING_MODE,
2621
+ EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],
2622
+ RANGE: [MIN_EXP, MAX_EXP],
2623
+ CRYPTO,
2624
+ MODULO_MODE,
2625
+ POW_PRECISION,
2626
+ FORMAT,
2627
+ ALPHABET
2628
+ };
2629
+ };
2630
+ BigNumber2.isBigNumber = function(v) {
2631
+ if (!v || v._isBigNumber !== true) return false;
2632
+ if (!BigNumber2.DEBUG) return true;
2633
+ var i, n, c = v.c, e = v.e, s = v.s;
2634
+ out: if ({}.toString.call(c) == "[object Array]") {
2635
+ if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {
2636
+ if (c[0] === 0) {
2637
+ if (e === 0 && c.length === 1) return true;
2638
+ break out;
2639
+ }
2640
+ i = (e + 1) % LOG_BASE;
2641
+ if (i < 1) i += LOG_BASE;
2642
+ if (String(c[0]).length == i) {
2643
+ for (i = 0; i < c.length; i++) {
2644
+ n = c[i];
2645
+ if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;
2646
+ }
2647
+ if (n !== 0) return true;
2648
+ }
2649
+ }
2650
+ } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {
2651
+ return true;
2652
+ }
2653
+ throw Error(bignumberError + "Invalid BigNumber: " + v);
2654
+ };
2655
+ BigNumber2.maximum = BigNumber2.max = function() {
2656
+ return maxOrMin(arguments, -1);
2657
+ };
2658
+ BigNumber2.minimum = BigNumber2.min = function() {
2659
+ return maxOrMin(arguments, 1);
2660
+ };
2661
+ BigNumber2.random = (function() {
2662
+ var pow2_53 = 9007199254740992;
2663
+ var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() {
2664
+ return mathfloor(Math.random() * pow2_53);
2665
+ } : function() {
2666
+ return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0);
2667
+ };
2668
+ return function(dp) {
2669
+ var a, b2, e, k2, v, i = 0, c = [], rand = new BigNumber2(ONE);
2670
+ if (dp == null) dp = DECIMAL_PLACES;
2671
+ else intCheck(dp, 0, MAX);
2672
+ k2 = mathceil(dp / LOG_BASE);
2673
+ if (CRYPTO) {
2674
+ if (crypto.getRandomValues) {
2675
+ a = crypto.getRandomValues(new Uint32Array(k2 *= 2));
2676
+ for (; i < k2; ) {
2677
+ v = a[i] * 131072 + (a[i + 1] >>> 11);
2678
+ if (v >= 9e15) {
2679
+ b2 = crypto.getRandomValues(new Uint32Array(2));
2680
+ a[i] = b2[0];
2681
+ a[i + 1] = b2[1];
2682
+ } else {
2683
+ c.push(v % 1e14);
2684
+ i += 2;
2685
+ }
2686
+ }
2687
+ i = k2 / 2;
2688
+ } else if (crypto.randomBytes) {
2689
+ a = crypto.randomBytes(k2 *= 7);
2690
+ for (; i < k2; ) {
2691
+ v = (a[i] & 31) * 281474976710656 + a[i + 1] * 1099511627776 + a[i + 2] * 4294967296 + a[i + 3] * 16777216 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];
2692
+ if (v >= 9e15) {
2693
+ crypto.randomBytes(7).copy(a, i);
2694
+ } else {
2695
+ c.push(v % 1e14);
2696
+ i += 7;
2697
+ }
2698
+ }
2699
+ i = k2 / 7;
2700
+ } else {
2701
+ CRYPTO = false;
2702
+ throw Error(bignumberError + "crypto unavailable");
2703
+ }
2704
+ }
2705
+ if (!CRYPTO) {
2706
+ for (; i < k2; ) {
2707
+ v = random53bitInt();
2708
+ if (v < 9e15) c[i++] = v % 1e14;
2709
+ }
2710
+ }
2711
+ k2 = c[--i];
2712
+ dp %= LOG_BASE;
2713
+ if (k2 && dp) {
2714
+ v = POWS_TEN[LOG_BASE - dp];
2715
+ c[i] = mathfloor(k2 / v) * v;
2716
+ }
2717
+ for (; c[i] === 0; c.pop(), i--) ;
2718
+ if (i < 0) {
2719
+ c = [e = 0];
2720
+ } else {
2721
+ for (e = -1; c[0] === 0; c.splice(0, 1), e -= LOG_BASE) ;
2722
+ for (i = 1, v = c[0]; v >= 10; v /= 10, i++) ;
2723
+ if (i < LOG_BASE) e -= LOG_BASE - i;
2724
+ }
2725
+ rand.e = e;
2726
+ rand.c = c;
2727
+ return rand;
2728
+ };
2729
+ })();
2730
+ BigNumber2.sum = function() {
2731
+ var i = 1, args = arguments, sum = new BigNumber2(args[0]);
2732
+ for (; i < args.length; ) sum = sum.plus(args[i++]);
2733
+ return sum;
2734
+ };
2735
+ convertBase = /* @__PURE__ */ (function() {
2736
+ var decimal = "0123456789";
2737
+ function toBaseOut(str, baseIn, baseOut, alphabet2) {
2738
+ var j, arr = [0], arrL, i = 0, len = str.length;
2739
+ for (; i < len; ) {
2740
+ for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) ;
2741
+ arr[0] += alphabet2.indexOf(str.charAt(i++));
2742
+ for (j = 0; j < arr.length; j++) {
2743
+ if (arr[j] > baseOut - 1) {
2744
+ if (arr[j + 1] == null) arr[j + 1] = 0;
2745
+ arr[j + 1] += arr[j] / baseOut | 0;
2746
+ arr[j] %= baseOut;
2747
+ }
2748
+ }
2749
+ }
2750
+ return arr.reverse();
2751
+ }
2752
+ return function(str, baseIn, baseOut, sign, callerIsToString) {
2753
+ var alphabet2, d, e, k2, r, x2, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE;
2754
+ if (i >= 0) {
2755
+ k2 = POW_PRECISION;
2756
+ POW_PRECISION = 0;
2757
+ str = str.replace(".", "");
2758
+ y = new BigNumber2(baseIn);
2759
+ x2 = y.pow(str.length - i);
2760
+ POW_PRECISION = k2;
2761
+ y.c = toBaseOut(
2762
+ toFixedPoint(coeffToString(x2.c), x2.e, "0"),
2763
+ 10,
2764
+ baseOut,
2765
+ decimal
2766
+ );
2767
+ y.e = y.c.length;
2768
+ }
2769
+ xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET));
2770
+ e = k2 = xc.length;
2771
+ for (; xc[--k2] == 0; xc.pop()) ;
2772
+ if (!xc[0]) return alphabet2.charAt(0);
2773
+ if (i < 0) {
2774
+ --e;
2775
+ } else {
2776
+ x2.c = xc;
2777
+ x2.e = e;
2778
+ x2.s = sign;
2779
+ x2 = div(x2, y, dp, rm, baseOut);
2780
+ xc = x2.c;
2781
+ r = x2.r;
2782
+ e = x2.e;
2783
+ }
2784
+ d = e + dp + 1;
2785
+ i = xc[d];
2786
+ k2 = baseOut / 2;
2787
+ r = r || d < 0 || xc[d + 1] != null;
2788
+ r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x2.s < 0 ? 3 : 2)) : i > k2 || i == k2 && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x2.s < 0 ? 8 : 7));
2789
+ if (d < 1 || !xc[0]) {
2790
+ str = r ? toFixedPoint(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0);
2791
+ } else {
2792
+ xc.length = d;
2793
+ if (r) {
2794
+ for (--baseOut; ++xc[--d] > baseOut; ) {
2795
+ xc[d] = 0;
2796
+ if (!d) {
2797
+ ++e;
2798
+ xc = [1].concat(xc);
2799
+ }
2800
+ }
2801
+ }
2802
+ for (k2 = xc.length; !xc[--k2]; ) ;
2803
+ for (i = 0, str = ""; i <= k2; str += alphabet2.charAt(xc[i++])) ;
2804
+ str = toFixedPoint(str, e, alphabet2.charAt(0));
2805
+ }
2806
+ return str;
2807
+ };
2808
+ })();
2809
+ div = /* @__PURE__ */ (function() {
2810
+ function multiply(x2, k2, base) {
2811
+ var m, temp, xlo, xhi, carry = 0, i = x2.length, klo = k2 % SQRT_BASE, khi = k2 / SQRT_BASE | 0;
2812
+ for (x2 = x2.slice(); i--; ) {
2813
+ xlo = x2[i] % SQRT_BASE;
2814
+ xhi = x2[i] / SQRT_BASE | 0;
2815
+ m = khi * xlo + xhi * klo;
2816
+ temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;
2817
+ carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;
2818
+ x2[i] = temp % base;
2819
+ }
2820
+ if (carry) x2 = [carry].concat(x2);
2821
+ return x2;
2822
+ }
2823
+ function compare2(a, b2, aL, bL) {
2824
+ var i, cmp;
2825
+ if (aL != bL) {
2826
+ cmp = aL > bL ? 1 : -1;
2827
+ } else {
2828
+ for (i = cmp = 0; i < aL; i++) {
2829
+ if (a[i] != b2[i]) {
2830
+ cmp = a[i] > b2[i] ? 1 : -1;
2831
+ break;
2832
+ }
2833
+ }
2834
+ }
2835
+ return cmp;
2836
+ }
2837
+ function subtract(a, b2, aL, base) {
2838
+ var i = 0;
2839
+ for (; aL--; ) {
2840
+ a[aL] -= i;
2841
+ i = a[aL] < b2[aL] ? 1 : 0;
2842
+ a[aL] = i * base + a[aL] - b2[aL];
2843
+ }
2844
+ for (; !a[0] && a.length > 1; a.splice(0, 1)) ;
2845
+ }
2846
+ return function(x2, y, dp, rm, base) {
2847
+ var cmp, e, i, more, n, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x2.s == y.s ? 1 : -1, xc = x2.c, yc = y.c;
2848
+ if (!xc || !xc[0] || !yc || !yc[0]) {
2849
+ return new BigNumber2(
2850
+ // Return NaN if either NaN, or both Infinity or 0.
2851
+ !x2.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : (
2852
+ // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
2853
+ xc && xc[0] == 0 || !yc ? s * 0 : s / 0
2854
+ )
2855
+ );
2856
+ }
2857
+ q2 = new BigNumber2(s);
2858
+ qc = q2.c = [];
2859
+ e = x2.e - y.e;
2860
+ s = dp + e + 1;
2861
+ if (!base) {
2862
+ base = BASE;
2863
+ e = bitFloor(x2.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);
2864
+ s = s / LOG_BASE | 0;
2865
+ }
2866
+ for (i = 0; yc[i] == (xc[i] || 0); i++) ;
2867
+ if (yc[i] > (xc[i] || 0)) e--;
2868
+ if (s < 0) {
2869
+ qc.push(1);
2870
+ more = true;
2871
+ } else {
2872
+ xL = xc.length;
2873
+ yL = yc.length;
2874
+ i = 0;
2875
+ s += 2;
2876
+ n = mathfloor(base / (yc[0] + 1));
2877
+ if (n > 1) {
2878
+ yc = multiply(yc, n, base);
2879
+ xc = multiply(xc, n, base);
2880
+ yL = yc.length;
2881
+ xL = xc.length;
2882
+ }
2883
+ xi = yL;
2884
+ rem = xc.slice(0, yL);
2885
+ remL = rem.length;
2886
+ for (; remL < yL; rem[remL++] = 0) ;
2887
+ yz = yc.slice();
2888
+ yz = [0].concat(yz);
2889
+ yc0 = yc[0];
2890
+ if (yc[1] >= base / 2) yc0++;
2891
+ do {
2892
+ n = 0;
2893
+ cmp = compare2(yc, rem, yL, remL);
2894
+ if (cmp < 0) {
2895
+ rem0 = rem[0];
2896
+ if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
2897
+ n = mathfloor(rem0 / yc0);
2898
+ if (n > 1) {
2899
+ if (n >= base) n = base - 1;
2900
+ prod = multiply(yc, n, base);
2901
+ prodL = prod.length;
2902
+ remL = rem.length;
2903
+ while (compare2(prod, rem, prodL, remL) == 1) {
2904
+ n--;
2905
+ subtract(prod, yL < prodL ? yz : yc, prodL, base);
2906
+ prodL = prod.length;
2907
+ cmp = 1;
2908
+ }
2909
+ } else {
2910
+ if (n == 0) {
2911
+ cmp = n = 1;
2912
+ }
2913
+ prod = yc.slice();
2914
+ prodL = prod.length;
2915
+ }
2916
+ if (prodL < remL) prod = [0].concat(prod);
2917
+ subtract(rem, prod, remL, base);
2918
+ remL = rem.length;
2919
+ if (cmp == -1) {
2920
+ while (compare2(yc, rem, yL, remL) < 1) {
2921
+ n++;
2922
+ subtract(rem, yL < remL ? yz : yc, remL, base);
2923
+ remL = rem.length;
2924
+ }
2925
+ }
2926
+ } else if (cmp === 0) {
2927
+ n++;
2928
+ rem = [0];
2929
+ }
2930
+ qc[i++] = n;
2931
+ if (rem[0]) {
2932
+ rem[remL++] = xc[xi] || 0;
2933
+ } else {
2934
+ rem = [xc[xi]];
2935
+ remL = 1;
2936
+ }
2937
+ } while ((xi++ < xL || rem[0] != null) && s--);
2938
+ more = rem[0] != null;
2939
+ if (!qc[0]) qc.splice(0, 1);
2940
+ }
2941
+ if (base == BASE) {
2942
+ for (i = 1, s = qc[0]; s >= 10; s /= 10, i++) ;
2943
+ round(q2, dp + (q2.e = i + e * LOG_BASE - 1) + 1, rm, more);
2944
+ } else {
2945
+ q2.e = e;
2946
+ q2.r = +more;
2947
+ }
2948
+ return q2;
2949
+ };
2950
+ })();
2951
+ function format(n, i, rm, id) {
2952
+ var c0, e, ne2, len, str;
2953
+ if (rm == null) rm = ROUNDING_MODE;
2954
+ else intCheck(rm, 0, 8);
2955
+ if (!n.c) return n.toString();
2956
+ c0 = n.c[0];
2957
+ ne2 = n.e;
2958
+ if (i == null) {
2959
+ str = coeffToString(n.c);
2960
+ str = id == 1 || id == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential(str, ne2) : toFixedPoint(str, ne2, "0");
2961
+ } else {
2962
+ n = round(new BigNumber2(n), i, rm);
2963
+ e = n.e;
2964
+ str = coeffToString(n.c);
2965
+ len = str.length;
2966
+ if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {
2967
+ for (; len < i; str += "0", len++) ;
2968
+ str = toExponential(str, e);
2969
+ } else {
2970
+ i -= ne2;
2971
+ str = toFixedPoint(str, e, "0");
2972
+ if (e + 1 > len) {
2973
+ if (--i > 0) for (str += "."; i--; str += "0") ;
2974
+ } else {
2975
+ i += e - len;
2976
+ if (i > 0) {
2977
+ if (e + 1 == len) str += ".";
2978
+ for (; i--; str += "0") ;
2979
+ }
2980
+ }
2981
+ }
2982
+ }
2983
+ return n.s < 0 && c0 ? "-" + str : str;
2984
+ }
2985
+ function maxOrMin(args, n) {
2986
+ var k2, y, i = 1, x2 = new BigNumber2(args[0]);
2987
+ for (; i < args.length; i++) {
2988
+ y = new BigNumber2(args[i]);
2989
+ if (!y.s || (k2 = compare(x2, y)) === n || k2 === 0 && x2.s === n) {
2990
+ x2 = y;
2991
+ }
2992
+ }
2993
+ return x2;
2994
+ }
2995
+ function normalise(n, c, e) {
2996
+ var i = 1, j = c.length;
2997
+ for (; !c[--j]; c.pop()) ;
2998
+ for (j = c[0]; j >= 10; j /= 10, i++) ;
2999
+ if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {
3000
+ n.c = n.e = null;
3001
+ } else if (e < MIN_EXP) {
3002
+ n.c = [n.e = 0];
3003
+ } else {
3004
+ n.e = e;
3005
+ n.c = c;
3006
+ }
3007
+ return n;
3008
+ }
3009
+ parseNumeric = /* @__PURE__ */ (function() {
3010
+ var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
3011
+ return function(x2, str, isNum, b2) {
3012
+ var base, s = isNum ? str : str.replace(whitespaceOrPlus, "");
3013
+ if (isInfinityOrNaN.test(s)) {
3014
+ x2.s = isNaN(s) ? null : s < 0 ? -1 : 1;
3015
+ } else {
3016
+ if (!isNum) {
3017
+ s = s.replace(basePrefix, function(m, p1, p2) {
3018
+ base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8;
3019
+ return !b2 || b2 == base ? p1 : m;
3020
+ });
3021
+ if (b2) {
3022
+ base = b2;
3023
+ s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1");
3024
+ }
3025
+ if (str != s) return new BigNumber2(s, base);
3026
+ }
3027
+ if (BigNumber2.DEBUG) {
3028
+ throw Error(bignumberError + "Not a" + (b2 ? " base " + b2 : "") + " number: " + str);
3029
+ }
3030
+ x2.s = null;
3031
+ }
3032
+ x2.c = x2.e = null;
3033
+ };
3034
+ })();
3035
+ function round(x2, sd, rm, r) {
3036
+ var d, i, j, k2, n, ni, rd, xc = x2.c, pows10 = POWS_TEN;
3037
+ if (xc) {
3038
+ out: {
3039
+ for (d = 1, k2 = xc[0]; k2 >= 10; k2 /= 10, d++) ;
3040
+ i = sd - d;
3041
+ if (i < 0) {
3042
+ i += LOG_BASE;
3043
+ j = sd;
3044
+ n = xc[ni = 0];
3045
+ rd = mathfloor(n / pows10[d - j - 1] % 10);
3046
+ } else {
3047
+ ni = mathceil((i + 1) / LOG_BASE);
3048
+ if (ni >= xc.length) {
3049
+ if (r) {
3050
+ for (; xc.length <= ni; xc.push(0)) ;
3051
+ n = rd = 0;
3052
+ d = 1;
3053
+ i %= LOG_BASE;
3054
+ j = i - LOG_BASE + 1;
3055
+ } else {
3056
+ break out;
3057
+ }
3058
+ } else {
3059
+ n = k2 = xc[ni];
3060
+ for (d = 1; k2 >= 10; k2 /= 10, d++) ;
3061
+ i %= LOG_BASE;
3062
+ j = i - LOG_BASE + d;
3063
+ rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);
3064
+ }
3065
+ }
3066
+ r = r || sd < 0 || // Are there any non-zero digits after the rounding digit?
3067
+ // The expression n % pows10[d - j - 1] returns all digits of n to the right
3068
+ // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
3069
+ xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);
3070
+ r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x2.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd.
3071
+ (i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x2.s < 0 ? 8 : 7));
3072
+ if (sd < 1 || !xc[0]) {
3073
+ xc.length = 0;
3074
+ if (r) {
3075
+ sd -= x2.e + 1;
3076
+ xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];
3077
+ x2.e = -sd || 0;
3078
+ } else {
3079
+ xc[0] = x2.e = 0;
3080
+ }
3081
+ return x2;
3082
+ }
3083
+ if (i == 0) {
3084
+ xc.length = ni;
3085
+ k2 = 1;
3086
+ ni--;
3087
+ } else {
3088
+ xc.length = ni + 1;
3089
+ k2 = pows10[LOG_BASE - i];
3090
+ xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k2 : 0;
3091
+ }
3092
+ if (r) {
3093
+ for (; ; ) {
3094
+ if (ni == 0) {
3095
+ for (i = 1, j = xc[0]; j >= 10; j /= 10, i++) ;
3096
+ j = xc[0] += k2;
3097
+ for (k2 = 1; j >= 10; j /= 10, k2++) ;
3098
+ if (i != k2) {
3099
+ x2.e++;
3100
+ if (xc[0] == BASE) xc[0] = 1;
3101
+ }
3102
+ break;
3103
+ } else {
3104
+ xc[ni] += k2;
3105
+ if (xc[ni] != BASE) break;
3106
+ xc[ni--] = 0;
3107
+ k2 = 1;
3108
+ }
3109
+ }
3110
+ }
3111
+ for (i = xc.length; xc[--i] === 0; xc.pop()) ;
3112
+ }
3113
+ if (x2.e > MAX_EXP) {
3114
+ x2.c = x2.e = null;
3115
+ } else if (x2.e < MIN_EXP) {
3116
+ x2.c = [x2.e = 0];
3117
+ }
3118
+ }
3119
+ return x2;
3120
+ }
3121
+ function valueOf(n) {
3122
+ var str, e = n.e;
3123
+ if (e === null) return n.toString();
3124
+ str = coeffToString(n.c);
3125
+ str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(str, e) : toFixedPoint(str, e, "0");
3126
+ return n.s < 0 ? "-" + str : str;
3127
+ }
3128
+ P2.absoluteValue = P2.abs = function() {
3129
+ var x2 = new BigNumber2(this);
3130
+ if (x2.s < 0) x2.s = 1;
3131
+ return x2;
3132
+ };
3133
+ P2.comparedTo = function(y, b2) {
3134
+ return compare(this, new BigNumber2(y, b2));
3135
+ };
3136
+ P2.decimalPlaces = P2.dp = function(dp, rm) {
3137
+ var c, n, v, x2 = this;
3138
+ if (dp != null) {
3139
+ intCheck(dp, 0, MAX);
3140
+ if (rm == null) rm = ROUNDING_MODE;
3141
+ else intCheck(rm, 0, 8);
3142
+ return round(new BigNumber2(x2), dp + x2.e + 1, rm);
3143
+ }
3144
+ if (!(c = x2.c)) return null;
3145
+ n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;
3146
+ if (v = c[v]) for (; v % 10 == 0; v /= 10, n--) ;
3147
+ if (n < 0) n = 0;
3148
+ return n;
3149
+ };
3150
+ P2.dividedBy = P2.div = function(y, b2) {
3151
+ return div(this, new BigNumber2(y, b2), DECIMAL_PLACES, ROUNDING_MODE);
3152
+ };
3153
+ P2.dividedToIntegerBy = P2.idiv = function(y, b2) {
3154
+ return div(this, new BigNumber2(y, b2), 0, 1);
3155
+ };
3156
+ P2.exponentiatedBy = P2.pow = function(n, m) {
3157
+ var half, isModExp, i, k2, more, nIsBig, nIsNeg, nIsOdd, y, x2 = this;
3158
+ n = new BigNumber2(n);
3159
+ if (n.c && !n.isInteger()) {
3160
+ throw Error(bignumberError + "Exponent not an integer: " + valueOf(n));
3161
+ }
3162
+ if (m != null) m = new BigNumber2(m);
3163
+ nIsBig = n.e > 14;
3164
+ if (!x2.c || !x2.c[0] || x2.c[0] == 1 && !x2.e && x2.c.length == 1 || !n.c || !n.c[0]) {
3165
+ y = new BigNumber2(Math.pow(+valueOf(x2), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));
3166
+ return m ? y.mod(m) : y;
3167
+ }
3168
+ nIsNeg = n.s < 0;
3169
+ if (m) {
3170
+ if (m.c ? !m.c[0] : !m.s) return new BigNumber2(NaN);
3171
+ isModExp = !nIsNeg && x2.isInteger() && m.isInteger();
3172
+ if (isModExp) x2 = x2.mod(m);
3173
+ } else if (n.e > 9 && (x2.e > 0 || x2.e < -1 || (x2.e == 0 ? x2.c[0] > 1 || nIsBig && x2.c[1] >= 24e7 : x2.c[0] < 8e13 || nIsBig && x2.c[0] <= 9999975e7))) {
3174
+ k2 = x2.s < 0 && isOdd(n) ? -0 : 0;
3175
+ if (x2.e > -1) k2 = 1 / k2;
3176
+ return new BigNumber2(nIsNeg ? 1 / k2 : k2);
3177
+ } else if (POW_PRECISION) {
3178
+ k2 = mathceil(POW_PRECISION / LOG_BASE + 2);
3179
+ }
3180
+ if (nIsBig) {
3181
+ half = new BigNumber2(0.5);
3182
+ if (nIsNeg) n.s = 1;
3183
+ nIsOdd = isOdd(n);
3184
+ } else {
3185
+ i = Math.abs(+valueOf(n));
3186
+ nIsOdd = i % 2;
3187
+ }
3188
+ y = new BigNumber2(ONE);
3189
+ for (; ; ) {
3190
+ if (nIsOdd) {
3191
+ y = y.times(x2);
3192
+ if (!y.c) break;
3193
+ if (k2) {
3194
+ if (y.c.length > k2) y.c.length = k2;
3195
+ } else if (isModExp) {
3196
+ y = y.mod(m);
3197
+ }
3198
+ }
3199
+ if (i) {
3200
+ i = mathfloor(i / 2);
3201
+ if (i === 0) break;
3202
+ nIsOdd = i % 2;
3203
+ } else {
3204
+ n = n.times(half);
3205
+ round(n, n.e + 1, 1);
3206
+ if (n.e > 14) {
3207
+ nIsOdd = isOdd(n);
3208
+ } else {
3209
+ i = +valueOf(n);
3210
+ if (i === 0) break;
3211
+ nIsOdd = i % 2;
3212
+ }
3213
+ }
3214
+ x2 = x2.times(x2);
3215
+ if (k2) {
3216
+ if (x2.c && x2.c.length > k2) x2.c.length = k2;
3217
+ } else if (isModExp) {
3218
+ x2 = x2.mod(m);
3219
+ }
3220
+ }
3221
+ if (isModExp) return y;
3222
+ if (nIsNeg) y = ONE.div(y);
3223
+ return m ? y.mod(m) : k2 ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;
3224
+ };
3225
+ P2.integerValue = function(rm) {
3226
+ var n = new BigNumber2(this);
3227
+ if (rm == null) rm = ROUNDING_MODE;
3228
+ else intCheck(rm, 0, 8);
3229
+ return round(n, n.e + 1, rm);
3230
+ };
3231
+ P2.isEqualTo = P2.eq = function(y, b2) {
3232
+ return compare(this, new BigNumber2(y, b2)) === 0;
3233
+ };
3234
+ P2.isFinite = function() {
3235
+ return !!this.c;
3236
+ };
3237
+ P2.isGreaterThan = P2.gt = function(y, b2) {
3238
+ return compare(this, new BigNumber2(y, b2)) > 0;
3239
+ };
3240
+ P2.isGreaterThanOrEqualTo = P2.gte = function(y, b2) {
3241
+ return (b2 = compare(this, new BigNumber2(y, b2))) === 1 || b2 === 0;
3242
+ };
3243
+ P2.isInteger = function() {
3244
+ return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;
3245
+ };
3246
+ P2.isLessThan = P2.lt = function(y, b2) {
3247
+ return compare(this, new BigNumber2(y, b2)) < 0;
3248
+ };
3249
+ P2.isLessThanOrEqualTo = P2.lte = function(y, b2) {
3250
+ return (b2 = compare(this, new BigNumber2(y, b2))) === -1 || b2 === 0;
3251
+ };
3252
+ P2.isNaN = function() {
3253
+ return !this.s;
3254
+ };
3255
+ P2.isNegative = function() {
3256
+ return this.s < 0;
3257
+ };
3258
+ P2.isPositive = function() {
3259
+ return this.s > 0;
3260
+ };
3261
+ P2.isZero = function() {
3262
+ return !!this.c && this.c[0] == 0;
3263
+ };
3264
+ P2.minus = function(y, b2) {
3265
+ var i, j, t, xLTy, x2 = this, a = x2.s;
3266
+ y = new BigNumber2(y, b2);
3267
+ b2 = y.s;
3268
+ if (!a || !b2) return new BigNumber2(NaN);
3269
+ if (a != b2) {
3270
+ y.s = -b2;
3271
+ return x2.plus(y);
3272
+ }
3273
+ var xe2 = x2.e / LOG_BASE, ye2 = y.e / LOG_BASE, xc = x2.c, yc = y.c;
3274
+ if (!xe2 || !ye2) {
3275
+ if (!xc || !yc) return xc ? (y.s = -b2, y) : new BigNumber2(yc ? x2 : NaN);
3276
+ if (!xc[0] || !yc[0]) {
3277
+ return yc[0] ? (y.s = -b2, y) : new BigNumber2(xc[0] ? x2 : (
3278
+ // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
3279
+ ROUNDING_MODE == 3 ? -0 : 0
3280
+ ));
3281
+ }
3282
+ }
3283
+ xe2 = bitFloor(xe2);
3284
+ ye2 = bitFloor(ye2);
3285
+ xc = xc.slice();
3286
+ if (a = xe2 - ye2) {
3287
+ if (xLTy = a < 0) {
3288
+ a = -a;
3289
+ t = xc;
3290
+ } else {
3291
+ ye2 = xe2;
3292
+ t = yc;
3293
+ }
3294
+ t.reverse();
3295
+ for (b2 = a; b2--; t.push(0)) ;
3296
+ t.reverse();
3297
+ } else {
3298
+ j = (xLTy = (a = xc.length) < (b2 = yc.length)) ? a : b2;
3299
+ for (a = b2 = 0; b2 < j; b2++) {
3300
+ if (xc[b2] != yc[b2]) {
3301
+ xLTy = xc[b2] < yc[b2];
3302
+ break;
3303
+ }
3304
+ }
3305
+ }
3306
+ if (xLTy) {
3307
+ t = xc;
3308
+ xc = yc;
3309
+ yc = t;
3310
+ y.s = -y.s;
3311
+ }
3312
+ b2 = (j = yc.length) - (i = xc.length);
3313
+ if (b2 > 0) for (; b2--; xc[i++] = 0) ;
3314
+ b2 = BASE - 1;
3315
+ for (; j > a; ) {
3316
+ if (xc[--j] < yc[j]) {
3317
+ for (i = j; i && !xc[--i]; xc[i] = b2) ;
3318
+ --xc[i];
3319
+ xc[j] += BASE;
3320
+ }
3321
+ xc[j] -= yc[j];
3322
+ }
3323
+ for (; xc[0] == 0; xc.splice(0, 1), --ye2) ;
3324
+ if (!xc[0]) {
3325
+ y.s = ROUNDING_MODE == 3 ? -1 : 1;
3326
+ y.c = [y.e = 0];
3327
+ return y;
3328
+ }
3329
+ return normalise(y, xc, ye2);
3330
+ };
3331
+ P2.modulo = P2.mod = function(y, b2) {
3332
+ var q2, s, x2 = this;
3333
+ y = new BigNumber2(y, b2);
3334
+ if (!x2.c || !y.s || y.c && !y.c[0]) {
3335
+ return new BigNumber2(NaN);
3336
+ } else if (!y.c || x2.c && !x2.c[0]) {
3337
+ return new BigNumber2(x2);
3338
+ }
3339
+ if (MODULO_MODE == 9) {
3340
+ s = y.s;
3341
+ y.s = 1;
3342
+ q2 = div(x2, y, 0, 3);
3343
+ y.s = s;
3344
+ q2.s *= s;
3345
+ } else {
3346
+ q2 = div(x2, y, 0, MODULO_MODE);
3347
+ }
3348
+ y = x2.minus(q2.times(y));
3349
+ if (!y.c[0] && MODULO_MODE == 1) y.s = x2.s;
3350
+ return y;
3351
+ };
3352
+ P2.multipliedBy = P2.times = function(y, b2) {
3353
+ var c, e, i, j, k2, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x2 = this, xc = x2.c, yc = (y = new BigNumber2(y, b2)).c;
3354
+ if (!xc || !yc || !xc[0] || !yc[0]) {
3355
+ if (!x2.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
3356
+ y.c = y.e = y.s = null;
3357
+ } else {
3358
+ y.s *= x2.s;
3359
+ if (!xc || !yc) {
3360
+ y.c = y.e = null;
3361
+ } else {
3362
+ y.c = [0];
3363
+ y.e = 0;
3364
+ }
3365
+ }
3366
+ return y;
3367
+ }
3368
+ e = bitFloor(x2.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);
3369
+ y.s *= x2.s;
3370
+ xcL = xc.length;
3371
+ ycL = yc.length;
3372
+ if (xcL < ycL) {
3373
+ zc = xc;
3374
+ xc = yc;
3375
+ yc = zc;
3376
+ i = xcL;
3377
+ xcL = ycL;
3378
+ ycL = i;
3379
+ }
3380
+ for (i = xcL + ycL, zc = []; i--; zc.push(0)) ;
3381
+ base = BASE;
3382
+ sqrtBase = SQRT_BASE;
3383
+ for (i = ycL; --i >= 0; ) {
3384
+ c = 0;
3385
+ ylo = yc[i] % sqrtBase;
3386
+ yhi = yc[i] / sqrtBase | 0;
3387
+ for (k2 = xcL, j = i + k2; j > i; ) {
3388
+ xlo = xc[--k2] % sqrtBase;
3389
+ xhi = xc[k2] / sqrtBase | 0;
3390
+ m = yhi * xlo + xhi * ylo;
3391
+ xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c;
3392
+ c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;
3393
+ zc[j--] = xlo % base;
3394
+ }
3395
+ zc[j] = c;
3396
+ }
3397
+ if (c) {
3398
+ ++e;
3399
+ } else {
3400
+ zc.splice(0, 1);
3401
+ }
3402
+ return normalise(y, zc, e);
3403
+ };
3404
+ P2.negated = function() {
3405
+ var x2 = new BigNumber2(this);
3406
+ x2.s = -x2.s || null;
3407
+ return x2;
3408
+ };
3409
+ P2.plus = function(y, b2) {
3410
+ var t, x2 = this, a = x2.s;
3411
+ y = new BigNumber2(y, b2);
3412
+ b2 = y.s;
3413
+ if (!a || !b2) return new BigNumber2(NaN);
3414
+ if (a != b2) {
3415
+ y.s = -b2;
3416
+ return x2.minus(y);
3417
+ }
3418
+ var xe2 = x2.e / LOG_BASE, ye2 = y.e / LOG_BASE, xc = x2.c, yc = y.c;
3419
+ if (!xe2 || !ye2) {
3420
+ if (!xc || !yc) return new BigNumber2(a / 0);
3421
+ if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber2(xc[0] ? x2 : a * 0);
3422
+ }
3423
+ xe2 = bitFloor(xe2);
3424
+ ye2 = bitFloor(ye2);
3425
+ xc = xc.slice();
3426
+ if (a = xe2 - ye2) {
3427
+ if (a > 0) {
3428
+ ye2 = xe2;
3429
+ t = yc;
3430
+ } else {
3431
+ a = -a;
3432
+ t = xc;
3433
+ }
3434
+ t.reverse();
3435
+ for (; a--; t.push(0)) ;
3436
+ t.reverse();
3437
+ }
3438
+ a = xc.length;
3439
+ b2 = yc.length;
3440
+ if (a - b2 < 0) {
3441
+ t = yc;
3442
+ yc = xc;
3443
+ xc = t;
3444
+ b2 = a;
3445
+ }
3446
+ for (a = 0; b2; ) {
3447
+ a = (xc[--b2] = xc[b2] + yc[b2] + a) / BASE | 0;
3448
+ xc[b2] = BASE === xc[b2] ? 0 : xc[b2] % BASE;
3449
+ }
3450
+ if (a) {
3451
+ xc = [a].concat(xc);
3452
+ ++ye2;
3453
+ }
3454
+ return normalise(y, xc, ye2);
3455
+ };
3456
+ P2.precision = P2.sd = function(sd, rm) {
3457
+ var c, n, v, x2 = this;
3458
+ if (sd != null && sd !== !!sd) {
3459
+ intCheck(sd, 1, MAX);
3460
+ if (rm == null) rm = ROUNDING_MODE;
3461
+ else intCheck(rm, 0, 8);
3462
+ return round(new BigNumber2(x2), sd, rm);
3463
+ }
3464
+ if (!(c = x2.c)) return null;
3465
+ v = c.length - 1;
3466
+ n = v * LOG_BASE + 1;
3467
+ if (v = c[v]) {
3468
+ for (; v % 10 == 0; v /= 10, n--) ;
3469
+ for (v = c[0]; v >= 10; v /= 10, n++) ;
3470
+ }
3471
+ if (sd && x2.e + 1 > n) n = x2.e + 1;
3472
+ return n;
3473
+ };
3474
+ P2.shiftedBy = function(k2) {
3475
+ intCheck(k2, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
3476
+ return this.times("1e" + k2);
3477
+ };
3478
+ P2.squareRoot = P2.sqrt = function() {
3479
+ var m, n, r, rep, t, x2 = this, c = x2.c, s = x2.s, e = x2.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5");
3480
+ if (s !== 1 || !c || !c[0]) {
3481
+ return new BigNumber2(!s || s < 0 && (!c || c[0]) ? NaN : c ? x2 : 1 / 0);
3482
+ }
3483
+ s = Math.sqrt(+valueOf(x2));
3484
+ if (s == 0 || s == 1 / 0) {
3485
+ n = coeffToString(c);
3486
+ if ((n.length + e) % 2 == 0) n += "0";
3487
+ s = Math.sqrt(+n);
3488
+ e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);
3489
+ if (s == 1 / 0) {
3490
+ n = "5e" + e;
3491
+ } else {
3492
+ n = s.toExponential();
3493
+ n = n.slice(0, n.indexOf("e") + 1) + e;
3494
+ }
3495
+ r = new BigNumber2(n);
3496
+ } else {
3497
+ r = new BigNumber2(s + "");
3498
+ }
3499
+ if (r.c[0]) {
3500
+ e = r.e;
3501
+ s = e + dp;
3502
+ if (s < 3) s = 0;
3503
+ for (; ; ) {
3504
+ t = r;
3505
+ r = half.times(t.plus(div(x2, t, dp, 1)));
3506
+ if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {
3507
+ if (r.e < e) --s;
3508
+ n = n.slice(s - 3, s + 1);
3509
+ if (n == "9999" || !rep && n == "4999") {
3510
+ if (!rep) {
3511
+ round(t, t.e + DECIMAL_PLACES + 2, 0);
3512
+ if (t.times(t).eq(x2)) {
3513
+ r = t;
3514
+ break;
3515
+ }
3516
+ }
3517
+ dp += 4;
3518
+ s += 4;
3519
+ rep = 1;
3520
+ } else {
3521
+ if (!+n || !+n.slice(1) && n.charAt(0) == "5") {
3522
+ round(r, r.e + DECIMAL_PLACES + 2, 1);
3523
+ m = !r.times(r).eq(x2);
3524
+ }
3525
+ break;
3526
+ }
3527
+ }
3528
+ }
3529
+ }
3530
+ return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);
3531
+ };
3532
+ P2.toExponential = function(dp, rm) {
3533
+ if (dp != null) {
3534
+ intCheck(dp, 0, MAX);
3535
+ dp++;
3536
+ }
3537
+ return format(this, dp, rm, 1);
3538
+ };
3539
+ P2.toFixed = function(dp, rm) {
3540
+ if (dp != null) {
3541
+ intCheck(dp, 0, MAX);
3542
+ dp = dp + this.e + 1;
3543
+ }
3544
+ return format(this, dp, rm);
3545
+ };
3546
+ P2.toFormat = function(dp, rm, format2) {
3547
+ var str, x2 = this;
3548
+ if (format2 == null) {
3549
+ if (dp != null && rm && typeof rm == "object") {
3550
+ format2 = rm;
3551
+ rm = null;
3552
+ } else if (dp && typeof dp == "object") {
3553
+ format2 = dp;
3554
+ dp = rm = null;
3555
+ } else {
3556
+ format2 = FORMAT;
3557
+ }
3558
+ } else if (typeof format2 != "object") {
3559
+ throw Error(bignumberError + "Argument not an object: " + format2);
3560
+ }
3561
+ str = x2.toFixed(dp, rm);
3562
+ if (x2.c) {
3563
+ var i, arr = str.split("."), g1 = +format2.groupSize, g2 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x2.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length;
3564
+ if (g2) {
3565
+ i = g1;
3566
+ g1 = g2;
3567
+ g2 = i;
3568
+ len -= i;
3569
+ }
3570
+ if (g1 > 0 && len > 0) {
3571
+ i = len % g1 || g1;
3572
+ intPart = intDigits.substr(0, i);
3573
+ for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);
3574
+ if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);
3575
+ if (isNeg) intPart = "-" + intPart;
3576
+ }
3577
+ str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g2 = +format2.fractionGroupSize) ? fractionPart.replace(
3578
+ new RegExp("\\d{" + g2 + "}\\B", "g"),
3579
+ "$&" + (format2.fractionGroupSeparator || "")
3580
+ ) : fractionPart) : intPart;
3581
+ }
3582
+ return (format2.prefix || "") + str + (format2.suffix || "");
3583
+ };
3584
+ P2.toFraction = function(md) {
3585
+ var d, d0, d1, d2, e, exp, n, n0, n1, q2, r, s, x2 = this, xc = x2.c;
3586
+ if (md != null) {
3587
+ n = new BigNumber2(md);
3588
+ if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {
3589
+ throw Error(bignumberError + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n));
3590
+ }
3591
+ }
3592
+ if (!xc) return new BigNumber2(x2);
3593
+ d = new BigNumber2(ONE);
3594
+ n1 = d0 = new BigNumber2(ONE);
3595
+ d1 = n0 = new BigNumber2(ONE);
3596
+ s = coeffToString(xc);
3597
+ e = d.e = s.length - x2.e - 1;
3598
+ d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];
3599
+ md = !md || n.comparedTo(d) > 0 ? e > 0 ? d : n1 : n;
3600
+ exp = MAX_EXP;
3601
+ MAX_EXP = 1 / 0;
3602
+ n = new BigNumber2(s);
3603
+ n0.c[0] = 0;
3604
+ for (; ; ) {
3605
+ q2 = div(n, d, 0, 1);
3606
+ d2 = d0.plus(q2.times(d1));
3607
+ if (d2.comparedTo(md) == 1) break;
3608
+ d0 = d1;
3609
+ d1 = d2;
3610
+ n1 = n0.plus(q2.times(d2 = n1));
3611
+ n0 = d2;
3612
+ d = n.minus(q2.times(d2 = d));
3613
+ n = d2;
3614
+ }
3615
+ d2 = div(md.minus(d0), d1, 0, 1);
3616
+ n0 = n0.plus(d2.times(n1));
3617
+ d0 = d0.plus(d2.times(d1));
3618
+ n0.s = n1.s = x2.s;
3619
+ e = e * 2;
3620
+ r = div(n1, d1, e, ROUNDING_MODE).minus(x2).abs().comparedTo(
3621
+ div(n0, d0, e, ROUNDING_MODE).minus(x2).abs()
3622
+ ) < 1 ? [n1, d1] : [n0, d0];
3623
+ MAX_EXP = exp;
3624
+ return r;
3625
+ };
3626
+ P2.toNumber = function() {
3627
+ return +valueOf(this);
3628
+ };
3629
+ P2.toPrecision = function(sd, rm) {
3630
+ if (sd != null) intCheck(sd, 1, MAX);
3631
+ return format(this, sd, rm, 2);
3632
+ };
3633
+ P2.toString = function(b2) {
3634
+ var str, n = this, s = n.s, e = n.e;
3635
+ if (e === null) {
3636
+ if (s) {
3637
+ str = "Infinity";
3638
+ if (s < 0) str = "-" + str;
3639
+ } else {
3640
+ str = "NaN";
3641
+ }
3642
+ } else {
3643
+ if (b2 == null) {
3644
+ str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(coeffToString(n.c), e) : toFixedPoint(coeffToString(n.c), e, "0");
3645
+ } else if (b2 === 10 && alphabetHasNormalDecimalDigits) {
3646
+ n = round(new BigNumber2(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);
3647
+ str = toFixedPoint(coeffToString(n.c), n.e, "0");
3648
+ } else {
3649
+ intCheck(b2, 2, ALPHABET.length, "Base");
3650
+ str = convertBase(toFixedPoint(coeffToString(n.c), e, "0"), 10, b2, s, true);
3651
+ }
3652
+ if (s < 0 && n.c[0]) str = "-" + str;
3653
+ }
3654
+ return str;
3655
+ };
3656
+ P2.valueOf = P2.toJSON = function() {
3657
+ return valueOf(this);
3658
+ };
3659
+ P2._isBigNumber = true;
3660
+ P2[Symbol.toStringTag] = "BigNumber";
3661
+ P2[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")] = P2.valueOf;
3662
+ if (configObject != null) BigNumber2.set(configObject);
3663
+ return BigNumber2;
3664
+ }
3665
+ function bitFloor(n) {
3666
+ var i = n | 0;
3667
+ return n > 0 || n === i ? i : i - 1;
3668
+ }
3669
+ function coeffToString(a) {
3670
+ var s, z2, i = 1, j = a.length, r = a[0] + "";
3671
+ for (; i < j; ) {
3672
+ s = a[i++] + "";
3673
+ z2 = LOG_BASE - s.length;
3674
+ for (; z2--; s = "0" + s) ;
3675
+ r += s;
3676
+ }
3677
+ for (j = r.length; r.charCodeAt(--j) === 48; ) ;
3678
+ return r.slice(0, j + 1 || 1);
3679
+ }
3680
+ function compare(x2, y) {
3681
+ var a, b2, xc = x2.c, yc = y.c, i = x2.s, j = y.s, k2 = x2.e, l = y.e;
3682
+ if (!i || !j) return null;
3683
+ a = xc && !xc[0];
3684
+ b2 = yc && !yc[0];
3685
+ if (a || b2) return a ? b2 ? 0 : -j : i;
3686
+ if (i != j) return i;
3687
+ a = i < 0;
3688
+ b2 = k2 == l;
3689
+ if (!xc || !yc) return b2 ? 0 : !xc ^ a ? 1 : -1;
3690
+ if (!b2) return k2 > l ^ a ? 1 : -1;
3691
+ j = (k2 = xc.length) < (l = yc.length) ? k2 : l;
3692
+ for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;
3693
+ return k2 == l ? 0 : k2 > l ^ a ? 1 : -1;
3694
+ }
3695
+ function intCheck(n, min, max, name) {
3696
+ if (n < min || n > max || n !== mathfloor(n)) {
3697
+ throw Error(bignumberError + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n));
3698
+ }
3699
+ }
3700
+ function isOdd(n) {
3701
+ var k2 = n.c.length - 1;
3702
+ return bitFloor(n.e / LOG_BASE) == k2 && n.c[k2] % 2 != 0;
3703
+ }
3704
+ function toExponential(str, e) {
3705
+ return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e < 0 ? "e" : "e+") + e;
3706
+ }
3707
+ function toFixedPoint(str, e, z2) {
3708
+ var len, zs;
3709
+ if (e < 0) {
3710
+ for (zs = z2 + "."; ++e; zs += z2) ;
3711
+ str = zs + str;
3712
+ } else {
3713
+ len = str.length;
3714
+ if (++e > len) {
3715
+ for (zs = z2, e -= len; --e; zs += z2) ;
3716
+ str += zs;
3717
+ } else if (e < len) {
3718
+ str = str.slice(0, e) + "." + str.slice(e);
3719
+ }
3720
+ }
3721
+ return str;
3722
+ }
3723
+ var BigNumber = clone();
3724
+ var bignumber_default = BigNumber;
3725
+ var z = bcs.bytes(32).transform({
3726
+ // To change the input type, you need to provide a type definition for the input
3727
+ input: (e) => fromHex(e),
3728
+ output: (e) => toHex(e)
3729
+ });
3730
+ bcs.struct("IncentiveAPYInfo", {
3731
+ /** Asset identifier */
3732
+ asset_id: bcs.u8(),
3733
+ /** Annual Percentage Yield as a 256-bit integer */
3734
+ apy: bcs.u256(),
3735
+ /** List of supported coin types for this incentive */
3736
+ coin_types: bcs.vector(bcs.string())
3737
+ });
3738
+ var me = bcs.struct("IncentivePoolInfo", {
3739
+ /** Unique pool identifier */
3740
+ pool_id: z,
3741
+ /** Address holding the incentive funds */
3742
+ funds: z,
3743
+ /** Current phase of the incentive program */
3744
+ phase: bcs.u64(),
3745
+ /** Timestamp when the incentive started */
3746
+ start_at: bcs.u64(),
3747
+ /** Timestamp when the incentive ends */
3748
+ end_at: bcs.u64(),
3749
+ /** Timestamp when the incentive was closed */
3750
+ closed_at: bcs.u64(),
3751
+ /** Total supply of incentive tokens */
3752
+ total_supply: bcs.u64(),
3753
+ /** Asset identifier for the incentive */
3754
+ asset_id: bcs.u8(),
3755
+ /** Option type for the incentive */
3756
+ option: bcs.u8(),
3757
+ /** Factor used in incentive calculations */
3758
+ factor: bcs.u256(),
3759
+ /** Amount of incentives already distributed */
3760
+ distributed: bcs.u64(),
3761
+ /** Amount of incentives currently available */
3762
+ available: bcs.u256(),
3763
+ /** Total amount of incentives */
3764
+ total: bcs.u256()
3765
+ });
3766
+ bcs.struct("IncentivePoolInfoByPhase", {
3767
+ /** Phase number */
3768
+ phase: bcs.u64(),
3769
+ /** List of incentive pools in this phase */
3770
+ pools: bcs.vector(me)
3771
+ });
3772
+ bcs.struct("OracleInfo", {
3773
+ /** Oracle identifier */
3774
+ oracle_id: bcs.u8(),
3775
+ /** Current price as a 256-bit integer */
3776
+ price: bcs.u256(),
3777
+ /** Number of decimal places for the price */
3778
+ decimals: bcs.u8(),
3779
+ /** Whether the oracle data is valid */
3780
+ valid: bcs.bool()
3781
+ });
3782
+ bcs.struct("FlashLoanAssetConfig", {
3783
+ /** Unique identifier for the flash loan asset */
3784
+ id: bcs.string(),
3785
+ /** Asset identifier */
3786
+ asset_id: bcs.u8(),
3787
+ /** Coin type for the asset */
3788
+ coin_type: bcs.string(),
3789
+ /** Pool identifier for the flash loan */
3790
+ pool_id: bcs.string(),
3791
+ /** Rate paid to suppliers for flash loans */
3792
+ rate_to_supplier: bcs.u64(),
3793
+ /** Rate paid to treasury for flash loans */
3794
+ rate_to_treasury: bcs.u64(),
3795
+ /** Maximum flash loan amount */
3796
+ max: bcs.u64(),
3797
+ /** Minimum flash loan amount */
3798
+ min: bcs.u64()
3799
+ });
3800
+ bcs.struct("ReserveDataInfo", {
3801
+ /** Reserve identifier */
3802
+ id: bcs.u8(),
3803
+ /** Oracle identifier for price feeds */
3804
+ oracle_id: bcs.u8(),
3805
+ /** Coin type for the reserve */
3806
+ coin_type: bcs.string(),
3807
+ /** Maximum supply capacity */
3808
+ supply_cap: bcs.u256(),
3809
+ /** Maximum borrow capacity */
3810
+ borrow_cap: bcs.u256(),
3811
+ /** Current supply interest rate */
3812
+ supply_rate: bcs.u256(),
3813
+ /** Current borrow interest rate */
3814
+ borrow_rate: bcs.u256(),
3815
+ /** Current supply index for interest calculation */
3816
+ supply_index: bcs.u256(),
3817
+ /** Current borrow index for interest calculation */
3818
+ borrow_index: bcs.u256(),
3819
+ /** Total amount supplied to the reserve */
3820
+ total_supply: bcs.u256(),
3821
+ /** Total amount borrowed from the reserve */
3822
+ total_borrow: bcs.u256(),
3823
+ /** Timestamp of last update */
3824
+ last_update_at: bcs.u64(),
3825
+ /** Loan-to-Value ratio for collateral */
3826
+ ltv: bcs.u256(),
3827
+ /** Treasury factor for fee calculations */
3828
+ treasury_factor: bcs.u256(),
3829
+ /** Current treasury balance */
3830
+ treasury_balance: bcs.u256(),
3831
+ /** Base interest rate */
3832
+ base_rate: bcs.u256(),
3833
+ /** Interest rate multiplier */
3834
+ multiplier: bcs.u256(),
3835
+ /** Jump rate multiplier for high utilization */
3836
+ jump_rate_multiplier: bcs.u256(),
3837
+ /** Reserve factor for protocol fees */
3838
+ reserve_factor: bcs.u256(),
3839
+ /** Optimal utilization rate */
3840
+ optimal_utilization: bcs.u256(),
3841
+ /** Liquidation ratio threshold */
3842
+ liquidation_ratio: bcs.u256(),
3843
+ /** Liquidation bonus for liquidators */
3844
+ liquidation_bonus: bcs.u256(),
3845
+ /** Liquidation threshold */
3846
+ liquidation_threshold: bcs.u256()
3847
+ });
3848
+ var fe = bcs.struct("UserStateInfo", {
3849
+ /** Asset identifier */
3850
+ asset_id: bcs.u8(),
3851
+ /** User's current borrow balance */
3852
+ borrow_balance: bcs.u256(),
3853
+ /** User's current supply balance */
3854
+ supply_balance: bcs.u256()
3855
+ });
3856
+ var ye = "1.4.0";
3857
+ var V = {
3858
+ version: ye
3859
+ };
3860
+ var ge = V.version;
3861
+ var he = () => {
3862
+ if (typeof process < "u" && process.versions && process.versions.node)
3863
+ try {
3864
+ const e = __require("os"), n = process.version, o = e.type(), r = e.arch();
3865
+ return `Node.js ${n.startsWith("v") ? n.substring(1) : n}; ${o}/${r}`;
3866
+ } catch {
3867
+ return `Node.js ${process.version}; OS/Unknown (Error)`;
3868
+ }
3869
+ return "Node/Unknown";
3870
+ };
3871
+ var ve = () => {
3872
+ let e = "";
3873
+ return typeof process < "u" && process.versions && process.versions.node && (e = `lending/${ge} (${he()})`), e;
3874
+ };
3875
+ var K = ve();
3876
+ var P = new SuiJsonRpcClient({
3877
+ url: getJsonRpcFullnodeUrl("mainnet")
3878
+ });
3879
+ function Q(e) {
3880
+ const n = [];
3881
+ return e.forEach((o, r) => {
3882
+ const t = r === e.length - 1;
3883
+ if (typeof o == "object" && o !== null && t) {
3884
+ const { client: a, disableCache: s, cacheTime: i, ...c } = o;
3885
+ n.push(c);
3886
+ } else
3887
+ n.push(o);
3888
+ }), JSON.stringify(n);
3889
+ }
3890
+ function B(e) {
3891
+ const n = {};
3892
+ return (...o) => {
3893
+ const r = Q(o);
3894
+ return n[r] || (n[r] = e(...o).finally(() => {
3895
+ delete n[r];
3896
+ })), n[r];
3897
+ };
3898
+ }
3899
+ function $(e) {
3900
+ let n = {};
3901
+ return (...o) => {
3902
+ const r = o[o.length - 1], t = Q(o), a = n[t];
3903
+ return !r?.disableCache && typeof a?.data < "u" && (typeof r?.cacheTime > "u" || r.cacheTime > Date.now() - a.cacheAt) ? a.data : e(...o).then((s) => (n[t] = {
3904
+ data: s,
3905
+ cacheAt: Date.now()
3906
+ }, s));
3907
+ };
3908
+ }
3909
+ function g(e, n) {
3910
+ return typeof e == "object" ? e : n(e);
3911
+ }
3912
+ function we(e, n) {
3913
+ return typeof n == "string" ? e.object(n) : typeof n == "object" && n.$kind ? n : e.object(n.contract.pool);
3914
+ }
3915
+ function L(e, n, o) {
3916
+ if (e.results && e.results.length > 0) {
3917
+ if (e.results[0].returnValues && e.results[0].returnValues.length > 0)
3918
+ return e.results[0].returnValues.map((r, t) => (n[t] || n[0]).parse(Uint8Array.from(r[0])));
3919
+ } else if (e.error)
3920
+ return console.log(`Get an error, msg: ${e.error}`), [];
3921
+ return [];
3922
+ }
3923
+ function b(e) {
3924
+ return normalizeStructTag(e);
3925
+ }
3926
+ function X(e) {
3927
+ const n = (e || 0) / Math.pow(10, 27);
3928
+ return n > Math.pow(10, 5) ? 1 / 0 : n;
3929
+ }
3930
+ new SuiPriceServiceConnection("https://hermes.pyth.network", {
3931
+ timeout: 2e4
3932
+ });
3933
+ var be = 27;
3934
+ var Y = (e, n) => {
3935
+ if (!Number(e) || !Number(n)) return new bignumber_default(0);
3936
+ const o = new bignumber_default(1).shiftedBy(1 * be), r = o.multipliedBy(new bignumber_default(0.5));
3937
+ return new bignumber_default(e).multipliedBy(new bignumber_default(n)).plus(r).dividedBy(o).integerValue(bignumber_default.ROUND_DOWN);
3938
+ };
3939
+ var E = K ? {
3940
+ "User-Agent": K
3941
+ } : {};
3942
+ function H(e, n = "uniqueId") {
3943
+ return e.reduce(
3944
+ (o, r) => (o[r[n]] = r, o),
3945
+ {}
3946
+ );
3947
+ }
3948
+ function q(e, n) {
3949
+ const o = e.emodes.find((t) => t.emodeId === n.emodeId);
3950
+ if (!o)
3951
+ throw new Error("EMode not found in pool");
3952
+ const r = o.assets.find((t) => t.assetId === e.id);
3953
+ return {
3954
+ ...e,
3955
+ emode: {
3956
+ ...r,
3957
+ emodeId: o.emodeId
3958
+ },
3959
+ isEMode: true
3960
+ };
3961
+ }
3962
+ function ke(e) {
3963
+ const [n, o] = e.split("-");
3964
+ return !n || !o ? null : {
3965
+ marketKey: n,
3966
+ poolId: parseInt(o)
3967
+ };
3968
+ }
3969
+ function T() {
3970
+ return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
3971
+ }
3972
+ var R = $(
3973
+ B(
3974
+ async (e) => {
3975
+ const n = (e?.markets || [M.main]).map((t) => _(t)), o = `https://open-api.naviprotocol.io/api/navi/pools?env=${e?.env || "prod"}&sdk=${V.version}&market=${n.map(
3976
+ (t) => t.key
3977
+ )}`, r = await fetch(o, { headers: E }).then((t) => t.json());
3978
+ return r.data.forEach((t) => {
3979
+ const s = r.meta.emodes.filter((h) => {
3980
+ const j = _(h.marketId);
3981
+ return t.market === j.key && h.isActive;
3982
+ }).filter((h) => !!h.assets.find((j) => j.assetId === t.id));
3983
+ t.emodes = s;
3984
+ const i = bignumber_default(t.totalSupplyAmount).div(Math.pow(10, 9)).decimalPlaces(t.token.decimals, bignumber_default.ROUND_DOWN).toString(), c = bignumber_default(t.borrowedAmount).shiftedBy(-9).decimalPlaces(t.token.decimals, bignumber_default.ROUND_DOWN).toString(), u = bignumber_default(i).multipliedBy(t.oracle.price).toString(), d = bignumber_default(c).multipliedBy(t.oracle.price).toString(), f = bignumber_default(t.supplyCapCeiling).shiftedBy(-27).decimalPlaces(t.token.decimals, bignumber_default.ROUND_DOWN).toString(), v = bignumber_default.max(
3985
+ bignumber_default(t.borrowedAmount),
3986
+ bignumber_default(t.validBorrowAmount)
3987
+ ).shiftedBy(-9).decimalPlaces(t.token.decimals, bignumber_default.ROUND_DOWN).toString(), y = bignumber_default(f).multipliedBy(t.oracle.price).toString(), l = bignumber_default(v).multipliedBy(t.oracle.price).toString();
3988
+ t.poolSupplyAmount = i, t.poolBorrowAmount = c, t.poolSupplyValue = u, t.poolBorrowValue = d, t.poolSupplyCapAmount = f, t.poolBorrowCapAmount = v, t.poolSupplyCapValue = y, t.poolBorrowCapValue = l;
3989
+ }), r.data;
3990
+ }
3991
+ )
3992
+ );
3993
+ async function A(e, n) {
3994
+ let o = n?.market;
3995
+ if (typeof e == "string") {
3996
+ const a = ke(e);
3997
+ a && (o = a.marketKey, e = a.poolId);
3998
+ }
3999
+ const r = await R({
4000
+ ...n,
4001
+ markets: [o || N],
4002
+ cacheTime: w
4003
+ });
4004
+ if (typeof e == "object")
4005
+ return e;
4006
+ const t = r.find((a) => typeof e == "string" ? b(a.suiCoinType) === b(e) : typeof e == "number" ? a.id === e : false);
4007
+ if (!t)
4008
+ throw new Error("Pool not found");
4009
+ return t.isDeprecated && console.log(`The lending pool for coinType ${t.suiCoinType} is going to be deprecated.`), t;
4010
+ }
4011
+ async function Ce(e, n, o, r) {
4012
+ const t = await k({
4013
+ ...r,
4014
+ cacheTime: w
4015
+ }), a = await A(n, r);
4016
+ if (a?.deprecatedAt && Date.now() > a.deprecatedAt)
4017
+ throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);
4018
+ const s = typeof o == "object" && o.$kind === "GasCoin";
4019
+ if (b(a.suiCoinType) === b("0x2::sui::SUI") && s) {
4020
+ if (!r?.amount)
4021
+ throw new Error("Amount is required for sui coin");
4022
+ o = e.splitCoins(o, [r.amount]);
4023
+ }
4024
+ let i;
4025
+ return typeof r?.amount < "u" ? i = g(r.amount, e.pure.u64) : i = e.moveCall({
4026
+ target: "0x2::coin::value",
4027
+ arguments: [g(o, e.object)],
4028
+ typeArguments: [a.suiCoinType]
4029
+ }), r?.accountCap ? e.moveCall({
4030
+ target: `${t.package}::incentive_v3::deposit_with_account_cap`,
4031
+ arguments: [
4032
+ e.object("0x06"),
4033
+ e.object(t.storage),
4034
+ e.object(a.contract.pool),
4035
+ e.pure.u8(a.id),
4036
+ g(o, e.object),
4037
+ e.object(t.incentiveV2),
4038
+ e.object(t.incentiveV3),
4039
+ g(r.accountCap, e.object)
4040
+ ],
4041
+ typeArguments: [a.suiCoinType]
4042
+ }) : e.moveCall({
4043
+ target: `${t.package}::incentive_v3::entry_deposit`,
4044
+ arguments: [
4045
+ e.object("0x06"),
4046
+ e.object(t.storage),
4047
+ e.object(a.contract.pool),
4048
+ e.pure.u8(a.id),
4049
+ g(o, e.object),
4050
+ i,
4051
+ e.object(t.incentiveV2),
4052
+ e.object(t.incentiveV3)
4053
+ ],
4054
+ typeArguments: [a.suiCoinType]
4055
+ }), t.version === 2 && a.id === 0 && (!r?.env || r?.env === "prod") && e.moveCall({
4056
+ target: `${t.package}::pool::refresh_stake`,
4057
+ arguments: [e.object(a.contract.pool), e.object("0x05")]
4058
+ }), e;
4059
+ }
4060
+ async function Qe(e, n, o, r) {
4061
+ const t = await k({
4062
+ ...r,
4063
+ cacheTime: w
4064
+ }), a = await A(n, r), s = g(o, e.pure.u64);
4065
+ let i;
4066
+ if (t.version === 1)
4067
+ if (r?.accountCap) {
4068
+ const [u] = e.moveCall({
4069
+ target: `${t.package}::incentive_v3::withdraw_with_account_cap`,
4070
+ arguments: [
4071
+ e.object("0x06"),
4072
+ e.object(t.priceOracle),
4073
+ e.object(t.storage),
4074
+ e.object(a.contract.pool),
4075
+ e.pure.u8(a.id),
4076
+ s,
4077
+ e.object(t.incentiveV2),
4078
+ e.object(t.incentiveV3),
4079
+ g(r.accountCap, e.object)
4080
+ ],
4081
+ typeArguments: [a.suiCoinType]
4082
+ });
4083
+ i = u;
4084
+ } else {
4085
+ const [u] = e.moveCall({
4086
+ target: `${t.package}::incentive_v3::withdraw`,
4087
+ arguments: [
4088
+ e.object("0x06"),
4089
+ e.object(t.priceOracle),
4090
+ e.object(t.storage),
4091
+ e.object(a.contract.pool),
4092
+ e.pure.u8(a.id),
4093
+ s,
4094
+ e.object(t.incentiveV2),
4095
+ e.object(t.incentiveV3)
4096
+ ],
4097
+ typeArguments: [a.suiCoinType]
4098
+ });
4099
+ i = u;
4100
+ }
4101
+ else if (r?.accountCap) {
4102
+ const [u] = e.moveCall({
4103
+ target: `${t.package}::incentive_v3::withdraw_with_account_cap_v2`,
4104
+ arguments: [
4105
+ e.object("0x06"),
4106
+ e.object(t.priceOracle),
4107
+ e.object(t.storage),
4108
+ e.object(a.contract.pool),
4109
+ e.pure.u8(a.id),
4110
+ s,
4111
+ e.object(t.incentiveV2),
4112
+ e.object(t.incentiveV3),
4113
+ g(r.accountCap, e.object),
4114
+ e.object("0x05")
4115
+ ],
4116
+ typeArguments: [a.suiCoinType]
4117
+ });
4118
+ i = u;
4119
+ } else {
4120
+ const [u] = e.moveCall({
4121
+ target: `${t.package}::incentive_v3::withdraw_v2`,
4122
+ arguments: [
4123
+ e.object("0x06"),
4124
+ e.object(t.priceOracle),
4125
+ e.object(t.storage),
4126
+ e.object(a.contract.pool),
4127
+ e.pure.u8(a.id),
4128
+ s,
4129
+ e.object(t.incentiveV2),
4130
+ e.object(t.incentiveV3),
4131
+ e.object("0x05")
4132
+ ],
4133
+ typeArguments: [a.suiCoinType]
4134
+ });
4135
+ i = u;
4136
+ }
4137
+ return e.moveCall({
4138
+ target: "0x2::coin::from_balance",
4139
+ arguments: [i],
4140
+ typeArguments: [a.suiCoinType]
4141
+ });
4142
+ }
4143
+ async function Xe(e, n, o, r) {
4144
+ const t = await k({
4145
+ ...r,
4146
+ cacheTime: w
4147
+ }), a = await A(n, r);
4148
+ if (a?.deprecatedAt && Date.now() > a.deprecatedAt)
4149
+ throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);
4150
+ const s = g(o, e.pure.u64);
4151
+ let i;
4152
+ if (t.version === 1)
4153
+ if (r?.accountCap) {
4154
+ const [u] = e.moveCall({
4155
+ target: `${t.package}::incentive_v3::borrow_with_account_cap`,
4156
+ arguments: [
4157
+ e.object("0x06"),
4158
+ e.object(t.priceOracle),
4159
+ e.object(t.storage),
4160
+ e.object(a.contract.pool),
4161
+ e.pure.u8(a.id),
4162
+ s,
4163
+ e.object(t.incentiveV2),
4164
+ e.object(t.incentiveV3),
4165
+ g(r.accountCap, e.object)
4166
+ ],
4167
+ typeArguments: [a.suiCoinType]
4168
+ });
4169
+ i = u;
4170
+ } else {
4171
+ const [u] = e.moveCall({
4172
+ target: `${t.package}::incentive_v3::borrow`,
4173
+ arguments: [
4174
+ e.object("0x06"),
4175
+ e.object(t.priceOracle),
4176
+ e.object(t.storage),
4177
+ e.object(a.contract.pool),
4178
+ e.pure.u8(a.id),
4179
+ s,
4180
+ e.object(t.incentiveV2),
4181
+ e.object(t.incentiveV3)
4182
+ ],
4183
+ typeArguments: [a.suiCoinType]
4184
+ });
4185
+ i = u;
4186
+ }
4187
+ else if (r?.accountCap) {
4188
+ const [u] = e.moveCall({
4189
+ target: `${t.package}::incentive_v3::borrow_with_account_cap_v2`,
4190
+ arguments: [
4191
+ e.object("0x06"),
4192
+ e.object(t.priceOracle),
4193
+ e.object(t.storage),
4194
+ e.object(a.contract.pool),
4195
+ e.pure.u8(a.id),
4196
+ s,
4197
+ e.object(t.incentiveV2),
4198
+ e.object(t.incentiveV3),
4199
+ g(r.accountCap, e.object),
4200
+ e.object("0x05")
4201
+ ],
4202
+ typeArguments: [a.suiCoinType]
4203
+ });
4204
+ i = u;
4205
+ } else {
4206
+ const [u] = e.moveCall({
4207
+ target: `${t.package}::incentive_v3::borrow_v2`,
4208
+ arguments: [
4209
+ e.object("0x06"),
4210
+ e.object(t.priceOracle),
4211
+ e.object(t.storage),
4212
+ e.object(a.contract.pool),
4213
+ e.pure.u8(a.id),
4214
+ s,
4215
+ e.object(t.incentiveV2),
4216
+ e.object(t.incentiveV3),
4217
+ e.object("0x05")
4218
+ ],
4219
+ typeArguments: [a.suiCoinType]
4220
+ });
4221
+ i = u;
4222
+ }
4223
+ return e.moveCall({
4224
+ target: "0x2::coin::from_balance",
4225
+ arguments: [e.object(i)],
4226
+ typeArguments: [a.suiCoinType]
4227
+ });
4228
+ }
4229
+ async function xe(e, n, o, r) {
4230
+ const t = await k({
4231
+ ...r,
4232
+ cacheTime: w
4233
+ }), a = await A(n, r), s = typeof o == "object" && o.$kind === "GasCoin";
4234
+ if (b(a.suiCoinType) === b("0x2::sui::SUI") && s) {
4235
+ if (!r?.amount)
4236
+ throw new Error("Amount is required for sui coin");
4237
+ o = e.splitCoins(o, [r.amount]);
4238
+ }
4239
+ let i;
4240
+ if (typeof r?.amount < "u" ? i = g(r.amount, e.pure.u64) : i = e.moveCall({
4241
+ target: "0x2::coin::value",
4242
+ arguments: [g(o, e.object)],
4243
+ typeArguments: [a.suiCoinType]
4244
+ }), r?.accountCap) {
4245
+ const [c] = e.moveCall({
4246
+ target: `${t.package}::incentive_v3::repay_with_account_cap`,
4247
+ arguments: [
4248
+ e.object("0x06"),
4249
+ e.object(t.priceOracle),
4250
+ e.object(t.storage),
4251
+ e.object(a.contract.pool),
4252
+ e.pure.u8(a.id),
4253
+ g(o, e.object),
4254
+ e.object(t.incentiveV2),
4255
+ e.object(t.incentiveV3),
4256
+ g(r.accountCap, e.object)
4257
+ ],
4258
+ typeArguments: [a.suiCoinType]
4259
+ });
4260
+ return e.moveCall({
4261
+ target: "0x2::coin::from_balance",
4262
+ arguments: [c],
4263
+ typeArguments: [a.suiCoinType]
4264
+ });
4265
+ } else
4266
+ return e.moveCall({
4267
+ target: `${t.package}::incentive_v3::entry_repay`,
4268
+ arguments: [
4269
+ e.object("0x06"),
4270
+ e.object(t.priceOracle),
4271
+ e.object(t.storage),
4272
+ e.object(a.contract.pool),
4273
+ e.pure.u8(a.id),
4274
+ g(o, e.object),
4275
+ i,
4276
+ e.object(t.incentiveV2),
4277
+ e.object(t.incentiveV3)
4278
+ ],
4279
+ typeArguments: [a.suiCoinType]
4280
+ }), e;
4281
+ }
4282
+ var N = "main";
4283
+ var M = {
4284
+ main: {
4285
+ id: 0,
4286
+ key: "main",
4287
+ name: "Main Market"
4288
+ }
4289
+ };
4290
+ var _ = (e) => {
4291
+ const o = Object.values(M).find((r) => typeof e == "number" ? r.id === e : typeof e == "string" ? r.key === e : r.id === e.id);
4292
+ if (!o)
4293
+ throw new Error("Market not found");
4294
+ return o;
4295
+ };
4296
+ var k = $(
4297
+ B(
4298
+ async (e) => {
4299
+ const n = _(e?.market || N), o = `https://open-api.naviprotocol.io/api/navi/config?env=${e?.env || "prod"}&sdk=${V.version}&market=${n.key}`;
4300
+ return (await fetch(o, { headers: E }).then((t) => t.json())).data;
4301
+ }
4302
+ )
4303
+ );
4304
+ var w = 1e3 * 60 * 5;
4305
+ var x = $(
4306
+ B(
4307
+ async (e, n) => {
4308
+ const o = await k({
4309
+ cacheTime: w,
4310
+ ...n
4311
+ }), r = new Transaction(), t = n?.client ?? P;
4312
+ r.moveCall({
4313
+ target: `${o.emode.contract.registryPackage}::registry::find_user_emode_account_caps`,
4314
+ arguments: [r.object(o.emode.contract.registryObject), r.pure.address(e)]
4315
+ });
4316
+ const s = (await t.devInspectTransactionBlock({
4317
+ transactionBlock: r,
4318
+ sender: e
4319
+ })).results[0].returnValues, i = bcs$1.vector(bcs$1.u64()).parse(Uint8Array.from(s[0][0])), c = bcs$1.vector(bcs$1.u64()).parse(Uint8Array.from(s[1][0])), u = bcs$1.vector(bcs$1.Address).parse(Uint8Array.from(s[2][0]));
4320
+ return i.map((d, f) => ({
4321
+ marketId: Number(d),
4322
+ emodeId: Number(c[f]),
4323
+ accountCap: u[f].toString()
4324
+ }));
4325
+ }
4326
+ )
4327
+ );
4328
+ async function ee(e, n, o, r, t, a, s) {
4329
+ const i = await k({
4330
+ ...s,
4331
+ cacheTime: w
4332
+ }), c = await A(o, s);
4333
+ return e.moveCall({
4334
+ target: `${i.uiGetter}::calculator_unchecked::dynamic_health_factor`,
4335
+ arguments: [
4336
+ e.object("0x06"),
4337
+ e.object(i.storage),
4338
+ e.object(i.oracle.priceOracle),
4339
+ we(e, c),
4340
+ g(n, e.pure.address),
4341
+ g(c.id, e.pure.u8),
4342
+ g(r, e.pure.u64),
4343
+ g(t, e.pure.u64),
4344
+ g(a, e.pure.bool)
4345
+ ],
4346
+ typeArguments: [c.suiCoinType]
4347
+ });
4348
+ }
4349
+ async function Ae(e, n, o) {
4350
+ return ee(e, n, 0, 0, 0, false, o);
4351
+ }
4352
+ async function te(e, n, o) {
4353
+ const r = new Transaction(), t = o?.client ?? P, a = await R({
4354
+ ...o,
4355
+ markets: Object.values(M)
4356
+ }), s = H(a);
4357
+ for (let d of n) {
4358
+ const f = await k({
4359
+ ...o,
4360
+ cacheTime: w,
4361
+ market: d.market
4362
+ });
4363
+ r.moveCall({
4364
+ target: `${f.uiGetter}::getter_unchecked::get_user_state`,
4365
+ arguments: [r.object(f.storage), r.pure.address(d.address)]
4366
+ });
4367
+ }
4368
+ const c = ((await t.devInspectTransactionBlock({
4369
+ transactionBlock: r,
4370
+ sender: e
4371
+ })).results || []).map((d) => d.returnValues?.map((f) => bcs$1.vector(fe).parse(Uint8Array.from(f[0])))[0] || []), u = [];
4372
+ return c.forEach((d, f) => {
4373
+ const v = n[f], y = _(v.market);
4374
+ d.forEach((l) => {
4375
+ if (l.supply_balance === "0" && l.borrow_balance === "0" && (v.emodeId === void 0 || !o?.includeZeroBalanceEmodePositions))
4376
+ return;
4377
+ const h = s[`${y.key}-${l.asset_id}`];
4378
+ if (!h)
4379
+ return;
4380
+ const j = Y(
4381
+ l.supply_balance,
4382
+ h.currentSupplyIndex
4383
+ ).toString(), I = Y(
4384
+ l.borrow_balance,
4385
+ h.currentBorrowIndex
4386
+ ).toString();
4387
+ u.push({
4388
+ supplyBalance: j,
4389
+ borrowBalance: I,
4390
+ assetId: l.asset_id,
4391
+ market: y.key,
4392
+ pool: h,
4393
+ emodeId: v.emodeId
4394
+ });
4395
+ });
4396
+ }), u;
4397
+ }
4398
+ async function ct(e, n) {
4399
+ const o = n?.client ?? P, r = new Transaction();
4400
+ await Ae(r, e, n);
4401
+ const t = await o.devInspectTransactionBlock({
4402
+ transactionBlock: r,
4403
+ sender: e
4404
+ }), a = L(t, [bcs$1.u256()]);
4405
+ return X(Number(a[0]) || 0);
4406
+ }
4407
+ var $e = $(
4408
+ async (e, n) => {
4409
+ const o = [], r = (n?.markets || Object.keys(M)).map((i) => _(i));
4410
+ let t = [];
4411
+ try {
4412
+ t = await x(e, n);
4413
+ } catch (i) {
4414
+ console.error(i);
4415
+ }
4416
+ const a = r.map((i) => ({
4417
+ address: e,
4418
+ market: i.key
4419
+ })).concat(
4420
+ t.filter((i) => !!r.find((c) => c.id === i.marketId)).map((i) => ({
4421
+ address: i.accountCap,
4422
+ market: _(i.marketId).key,
4423
+ emodeId: i.emodeId
4424
+ }))
4425
+ );
4426
+ return (await te(e, a, n)).forEach((i) => {
4427
+ const c = typeof i.emodeId == "number" ? t.find((u) => {
4428
+ const d = _(i.market);
4429
+ return u.emodeId === i.emodeId && u.marketId === d.id;
4430
+ }) : void 0;
4431
+ if (c) {
4432
+ if (!i.pool.emodes.find((d) => d.emodeId === c.emodeId))
4433
+ return;
4434
+ if (bignumber_default(i.supplyBalance).gte(0)) {
4435
+ const d = bignumber_default(i.supplyBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, bignumber_default.ROUND_DOWN), f = q(i.pool, c);
4436
+ if (d.gt(0) || f.emode.isCollateral)
4437
+ try {
4438
+ o.push({
4439
+ id: `${i.pool.uniqueId}_${c.emodeId}_navi-lending-emode-supply-${T()}`,
4440
+ wallet: e,
4441
+ protocol: "navi",
4442
+ market: i.market,
4443
+ type: "navi-lending-emode-supply",
4444
+ "navi-lending-emode-supply": {
4445
+ amount: d.toString(),
4446
+ pool: q(i.pool, c),
4447
+ token: i.pool.token,
4448
+ valueUSD: d.multipliedBy(i.pool.oracle.price).toString(),
4449
+ emodeCap: c
4450
+ }
4451
+ });
4452
+ } catch (v) {
4453
+ console.error(v);
4454
+ }
4455
+ }
4456
+ if (bignumber_default(i.borrowBalance).gte(0)) {
4457
+ const d = bignumber_default(i.borrowBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, bignumber_default.ROUND_DOWN), f = q(i.pool, c);
4458
+ if (d.gt(0) || f.emode.isDebt)
4459
+ try {
4460
+ o.push({
4461
+ id: `${i.pool.uniqueId}_${c.emodeId}_navi-lending-emode-borrow-${T()}`,
4462
+ wallet: e,
4463
+ protocol: "navi",
4464
+ market: i.market,
4465
+ type: "navi-lending-emode-borrow",
4466
+ "navi-lending-emode-borrow": {
4467
+ amount: d.toString(),
4468
+ pool: q(i.pool, c),
4469
+ token: i.pool.token,
4470
+ valueUSD: d.multipliedBy(i.pool.oracle.price).toString(),
4471
+ emodeCap: c
4472
+ }
4473
+ });
4474
+ } catch (v) {
4475
+ console.error(v);
4476
+ }
4477
+ }
4478
+ } else {
4479
+ if (bignumber_default(i.supplyBalance).gt(0)) {
4480
+ const u = bignumber_default(i.supplyBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, bignumber_default.ROUND_DOWN);
4481
+ o.push({
4482
+ id: `${i.pool.uniqueId}_navi-lending-supply-${T()}`,
4483
+ wallet: e,
4484
+ protocol: "navi",
4485
+ type: "navi-lending-supply",
4486
+ market: i.market,
4487
+ "navi-lending-supply": {
4488
+ amount: u.toString(),
4489
+ pool: i.pool,
4490
+ token: i.pool.token,
4491
+ valueUSD: u.multipliedBy(i.pool.oracle.price).toString()
4492
+ }
4493
+ });
4494
+ }
4495
+ if (bignumber_default(i.borrowBalance).gt(0)) {
4496
+ const u = bignumber_default(i.borrowBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, bignumber_default.ROUND_DOWN);
4497
+ o.push({
4498
+ id: `${i.pool.uniqueId}_navi-lending-borrow-${T()}`,
4499
+ wallet: e,
4500
+ protocol: "navi",
4501
+ market: i.market,
4502
+ type: "navi-lending-borrow",
4503
+ "navi-lending-borrow": {
4504
+ amount: u.toString(),
4505
+ pool: i.pool,
4506
+ token: i.pool.token,
4507
+ valueUSD: u.multipliedBy(i.pool.oracle.price).toString()
4508
+ }
4509
+ });
4510
+ }
4511
+ }
4512
+ }), o;
4513
+ }
4514
+ );
4515
+ var oe = new SuiPriceServiceConnection("https://hermes.pyth.network", {
4516
+ timeout: 1e4
4517
+ });
4518
+ async function Pe(e, n) {
4519
+ try {
4520
+ const o = [], r = n?.client ?? P, t = e.map((s) => s.priceInfoObject), a = await r.multiGetObjects({
4521
+ ids: Array.from(new Set(t)),
779
4522
  options: { showContent: true }
780
4523
  });
781
- if (pool.data?.content?.dataType === "moveObject") {
782
- const fields = pool.data.content.fields;
783
- const currentSqrtPrice = BigInt(String(fields.current_sqrt_price ?? "0"));
784
- if (currentSqrtPrice > 0n) {
785
- const Q64 = 2n ** 64n;
786
- const sqrtPriceFloat = Number(currentSqrtPrice) / Number(Q64);
787
- const rawPrice = sqrtPriceFloat * sqrtPriceFloat;
788
- const price = 1e3 / rawPrice;
789
- if (price > 0.01 && price < 1e3) {
790
- _cachedSuiPrice = price;
791
- _priceLastFetched = now;
792
- }
4524
+ for (const s of a) {
4525
+ const i = s.data;
4526
+ if (!i || !i.content || i.content.dataType !== "moveObject") {
4527
+ console.warn(`fetched object ${i?.objectId} datatype should be moveObject`);
4528
+ continue;
4529
+ }
4530
+ const c = e.find((l) => l.priceInfoObject == i.objectId);
4531
+ if (!c) {
4532
+ console.warn(`unable to find pyth info from array, priceInfoObject: ${i.objectId}`);
4533
+ continue;
793
4534
  }
4535
+ const u = i.content.fields.price_info.fields.price_feed.fields.price.fields, { magnitude: d, negative: f } = u.price.fields, v = u.conf, y = u.timestamp;
4536
+ o.push({
4537
+ priceFeedId: c.priceFeedId,
4538
+ priceInfoObject: c.priceInfoObject,
4539
+ price: f ? "-" + d : d,
4540
+ conf: v,
4541
+ publishTime: Number(y),
4542
+ expiration: c.expiration
4543
+ });
794
4544
  }
795
- } catch {
4545
+ return o;
4546
+ } catch (o) {
4547
+ console.error(o, `Polling Sui on-chain price for ${e} failed.`);
4548
+ return;
796
4549
  }
797
- return _cachedSuiPrice || SUI_PRICE_FALLBACK;
798
4550
  }
799
- async function queryBalance(client, address) {
800
- const stableBalancePromises = STABLE_ASSETS.map(
801
- (asset) => client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS[asset].type }).then((b) => ({ asset, amount: Number(b.totalBalance) / 10 ** SUPPORTED_ASSETS[asset].decimals })).catch(() => ({ asset, amount: 0 }))
802
- );
803
- const [suiBalance, suiPriceUsd, ...stableResults] = await Promise.all([
804
- client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS.SUI.type }),
805
- fetchSuiPrice(client),
806
- ...stableBalancePromises
807
- ]);
808
- const stables = {};
809
- let totalStables = 0;
810
- for (const { asset, amount } of stableResults) {
811
- stables[asset] = amount;
812
- totalStables += amount;
4551
+ async function Se(e, n) {
4552
+ try {
4553
+ const o = [], r = await Pe(e, n);
4554
+ if (!r) return o;
4555
+ const t = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
4556
+ for (const a of r) {
4557
+ if (a.publishTime > t) {
4558
+ console.warn(
4559
+ `pyth price feed is invalid, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${t}`
4560
+ );
4561
+ continue;
4562
+ }
4563
+ const s = a.expiration || 60;
4564
+ t - a.publishTime > s && (console.info(
4565
+ `stale price feed, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${t}`
4566
+ ), o.push(a.priceFeedId));
4567
+ }
4568
+ return o;
4569
+ } catch (o) {
4570
+ throw new Error(`failed to get pyth stale price feed id, msg: ${o.message}`);
813
4571
  }
814
- const suiAmount = Number(suiBalance.totalBalance) / Number(MIST_PER_SUI);
815
- const savings = 0;
816
- const usdEquiv = suiAmount * suiPriceUsd;
817
- const total = totalStables + savings + usdEquiv;
818
- return {
819
- available: totalStables,
820
- savings,
821
- debt: 0,
822
- pendingRewards: 0,
823
- gasReserve: {
824
- sui: suiAmount,
825
- usdEquiv
826
- },
827
- total,
828
- stables
829
- };
830
4572
  }
831
-
832
- // src/wallet/history.ts
833
- init_token_registry();
834
- var KNOWN_TARGETS = [
835
- [/::suilend|::obligation/, "lending"],
836
- [/::navi|::incentive_v\d+|::oracle_pro/, "lending"],
837
- [/::cetus|::pool/, "swap"],
838
- [/::deepbook/, "swap"],
839
- [/::transfer::public_transfer/, "send"]
840
- ];
841
- async function queryHistory(client, address, limit = 20) {
842
- const txns = await client.queryTransactionBlocks({
843
- filter: { FromAddress: address },
844
- options: { showEffects: true, showInput: true, showBalanceChanges: true },
845
- limit,
846
- order: "descending"
4573
+ async function Ve(e, n, o) {
4574
+ const r = o?.client ?? P, t = await k({
4575
+ ...o,
4576
+ cacheTime: w
847
4577
  });
848
- return txns.data.map((tx) => parseTxRecord(tx, address));
849
- }
850
- async function queryTransaction(client, digest, senderAddress) {
851
4578
  try {
852
- const tx = await client.getTransactionBlock({
853
- digest,
854
- options: { showEffects: true, showInput: true, showBalanceChanges: true }
855
- });
856
- return parseTxRecord(tx, senderAddress);
857
- } catch {
858
- return null;
4579
+ const a = await oe.getPriceFeedsUpdateData(n);
4580
+ return await new SuiPythClient(
4581
+ r,
4582
+ t.oracle.pythStateId,
4583
+ t.oracle.wormholeStateId
4584
+ ).updatePriceFeeds(e, a, n);
4585
+ } catch (a) {
4586
+ throw new Error(`failed to update pyth price feeds, msg: ${a.message}`);
859
4587
  }
860
4588
  }
861
- function parseTxRecord(tx, address) {
862
- const gasUsed = tx.effects?.gasUsed;
863
- const gasCost = gasUsed ? (Number(gasUsed.computationCost) + Number(gasUsed.storageCost) - Number(gasUsed.storageRebate)) / 1e9 : void 0;
864
- const { moveCallTargets, commandTypes } = extractCommands(tx.transaction);
865
- const { amount, asset, recipient } = extractTransferDetails(tx.balanceChanges, address);
866
- const action = classifyAction(moveCallTargets, commandTypes);
867
- return {
868
- digest: tx.digest,
869
- action,
870
- amount,
871
- asset,
872
- recipient,
873
- timestamp: Number(tx.timestampMs ?? 0),
874
- gasCost
875
- };
4589
+ async function Ee(e, n, o) {
4590
+ const r = await k({
4591
+ ...o,
4592
+ cacheTime: w
4593
+ });
4594
+ if (o?.updatePythPriceFeeds) {
4595
+ const t = n.filter((a) => !!a.pythPriceFeedId && !!a.pythPriceInfoObject).map((a) => ({
4596
+ priceFeedId: a.pythPriceFeedId,
4597
+ priceInfoObject: a.pythPriceInfoObject,
4598
+ expiration: 30
4599
+ }));
4600
+ try {
4601
+ const a = await Se(t, o);
4602
+ a.length > 0 && await Ve(e, a, o);
4603
+ } catch {
4604
+ console.error("Failed to update Pyth price feeds");
4605
+ }
4606
+ }
4607
+ for (const t of n)
4608
+ o?.env === "dev" ? e.moveCall({
4609
+ target: `${r.oracle.packageId}::oracle_pro::update_single_price`,
4610
+ arguments: [
4611
+ e.object("0x6"),
4612
+ // Clock object
4613
+ e.object(r.oracle.oracleConfig),
4614
+ // Oracle configuration
4615
+ e.object(r.oracle.priceOracle),
4616
+ // Price oracle contract
4617
+ e.object(r.oracle.supraOracleHolder),
4618
+ // Supra oracle holder
4619
+ e.object(t.pythPriceInfoObject),
4620
+ // Pyth price info object
4621
+ e.pure.address(t.feedId)
4622
+ // Price feed ID
4623
+ ]
4624
+ }) : e.moveCall({
4625
+ target: `${r.oracle.packageId}::oracle_pro::update_single_price_v2`,
4626
+ arguments: [
4627
+ e.object("0x6"),
4628
+ // Clock object
4629
+ e.object(r.oracle.oracleConfig),
4630
+ // Oracle configuration
4631
+ e.object(r.oracle.priceOracle),
4632
+ // Price oracle contract
4633
+ e.object(r.oracle.supraOracleHolder),
4634
+ // Supra oracle holder
4635
+ e.object(t.pythPriceInfoObject),
4636
+ // Pyth price info object
4637
+ e.object(r.oracle.switchboardAggregator),
4638
+ e.pure.address(t.feedId)
4639
+ // Price feed ID
4640
+ ]
4641
+ });
4642
+ return e;
876
4643
  }
877
- function resolveOwner(owner) {
878
- if (typeof owner === "object" && owner.AddressOwner) return owner.AddressOwner;
879
- if (typeof owner === "string") return owner;
880
- return null;
4644
+ async function ne(e) {
4645
+ return (await k({
4646
+ ...e,
4647
+ cacheTime: w
4648
+ })).oracle.feeds;
881
4649
  }
882
- function extractTransferDetails(changes, sender) {
883
- if (!changes || changes.length === 0) return {};
884
- const outflows = changes.filter((c) => resolveOwner(c.owner) === sender && BigInt(c.amount) < 0n);
885
- const inflows = changes.filter((c) => resolveOwner(c.owner) !== sender && BigInt(c.amount) > 0n);
886
- const primaryOutflow = outflows.filter((c) => c.coinType !== SUI_TYPE).sort((a, b) => Number(BigInt(a.amount) - BigInt(b.amount)))[0] ?? outflows[0];
887
- if (!primaryOutflow) return {};
888
- const coinType = primaryOutflow.coinType;
889
- const decimals = getDecimalsForCoinType(coinType);
890
- const amount = Math.abs(Number(BigInt(primaryOutflow.amount))) / 10 ** decimals;
891
- const asset = resolveSymbol(coinType);
892
- const recipientChange = inflows.find((c) => c.coinType === coinType);
893
- const recipient = recipientChange ? resolveOwner(recipientChange.owner) ?? void 0 : void 0;
894
- return { amount, asset, recipient };
4650
+ function Me(e, n) {
4651
+ return e.filter((o) => !!(n?.lendingState && n.lendingState.find((t) => t.assetId === o.assetId) || n?.lendingPositions && n.lendingPositions.find((t) => [
4652
+ "navi-lending-supply",
4653
+ "navi-lending-borrow",
4654
+ "navi-lending-emode-supply",
4655
+ "navi-lending-emode-borrow"
4656
+ ].includes(t.type) ? t[t.type]?.pool?.id === o.assetId : false) || n?.pools && n.pools.find((t) => t.id === o.assetId)));
895
4657
  }
896
- function extractCommands(txBlock) {
897
- const result = { moveCallTargets: [], commandTypes: [] };
4658
+ async function mt(e, n, o, r) {
898
4659
  try {
899
- if (!txBlock || typeof txBlock !== "object") return result;
900
- const data = "data" in txBlock ? txBlock.data : void 0;
901
- if (!data || typeof data !== "object") return result;
902
- const inner = "transaction" in data ? data.transaction : void 0;
903
- if (!inner || typeof inner !== "object") return result;
904
- const commands = "commands" in inner ? inner.commands : "transactions" in inner ? inner.transactions : void 0;
905
- if (!Array.isArray(commands)) return result;
906
- for (const cmd of commands) {
907
- if (cmd.MoveCall) {
908
- const mc = cmd.MoveCall;
909
- result.moveCallTargets.push(`${mc.package}::${mc.module}::${mc.function}`);
910
- result.commandTypes.push("MoveCall");
911
- } else if (cmd.TransferObjects) {
912
- result.commandTypes.push("TransferObjects");
913
- }
914
- }
915
- } catch {
4660
+ const t = await ne({
4661
+ ...r
4662
+ }), a = [];
4663
+ o.forEach((u) => {
4664
+ a.includes(u.market) || a.push(u.market);
4665
+ });
4666
+ const s = await $e(n, {
4667
+ ...r,
4668
+ markets: a
4669
+ }), i = Me(t, {
4670
+ lendingPositions: s,
4671
+ pools: o
4672
+ });
4673
+ return await Ee(e, i, {
4674
+ updatePythPriceFeeds: true,
4675
+ ...r
4676
+ });
4677
+ } catch (t) {
4678
+ if (r?.throws)
4679
+ throw t;
4680
+ return console.error(t), e;
916
4681
  }
917
- return result;
918
4682
  }
919
- function classifyAction(targets, commandTypes) {
920
- for (const target of targets) {
921
- for (const [pattern, label] of KNOWN_TARGETS) {
922
- if (pattern.test(target)) return label;
923
- }
4683
+ async function De(e, n, o) {
4684
+ const r = o?.client ?? P, t = new Transaction(), a = await R({
4685
+ ...o,
4686
+ markets: Object.values(M),
4687
+ cacheTime: w
4688
+ }), s = await ne(o);
4689
+ for (let d of n) {
4690
+ const f = await k({
4691
+ ...o,
4692
+ cacheTime: w,
4693
+ market: d.market
4694
+ });
4695
+ t.moveCall({
4696
+ target: `${f.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,
4697
+ arguments: [
4698
+ t.object("0x06"),
4699
+ // Clock object
4700
+ t.object(f.storage),
4701
+ // Protocol storage
4702
+ t.object(f.incentiveV3),
4703
+ // Incentive V3 contract
4704
+ t.pure.address(d.address)
4705
+ // User address
4706
+ ]
4707
+ });
924
4708
  }
925
- const hasTransfer = commandTypes.includes("TransferObjects");
926
- const hasMoveCall = commandTypes.includes("MoveCall");
927
- if (hasTransfer && !hasMoveCall) return "send";
928
- if (hasMoveCall) return "transaction";
929
- return "transaction";
930
- }
931
-
932
- // src/t2000.ts
933
- init_token_registry();
934
-
935
- // src/protocols/protocolFee.ts
936
- var FEE_RATES = {
937
- save: SAVE_FEE_BPS,
938
- borrow: BORROW_FEE_BPS
939
- };
940
- var OP_CODES = {
941
- save: 0,
942
- borrow: 2
943
- };
944
- function calculateFee(operation, amount) {
945
- const bps = FEE_RATES[operation];
946
- const feeAmount = amount * Number(bps) / Number(BPS_DENOMINATOR);
947
- const rawAmount = usdcToRaw(feeAmount);
948
- return {
949
- amount: feeAmount,
950
- asset: "USDC",
951
- rate: Number(bps) / Number(BPS_DENOMINATOR),
952
- rawAmount
953
- };
954
- }
955
- function addCollectFeeToTx(tx, paymentCoin, operation) {
956
- const bps = FEE_RATES[operation];
957
- if (bps <= 0n) return;
958
- tx.moveCall({
959
- target: `${T2000_PACKAGE_ID}::treasury::collect_fee`,
960
- typeArguments: [SUPPORTED_ASSETS.USDC.type],
961
- arguments: [
962
- tx.object(T2000_TREASURY_ID),
963
- tx.object(T2000_CONFIG_ID),
964
- paymentCoin,
965
- tx.pure.u8(OP_CODES[operation])
966
- ]
4709
+ const i = await r.devInspectTransactionBlock({
4710
+ transactionBlock: t,
4711
+ sender: e
4712
+ }), c = [];
4713
+ i?.results?.forEach((d) => {
4714
+ c.push(
4715
+ L(
4716
+ {
4717
+ results: [d]
4718
+ },
4719
+ [
4720
+ bcs$1.vector(bcs$1.string()),
4721
+ // Asset coin types
4722
+ bcs$1.vector(bcs$1.string()),
4723
+ // Reward coin types
4724
+ bcs$1.vector(bcs$1.u8()),
4725
+ // Reward options
4726
+ bcs$1.vector(bcs$1.Address),
4727
+ // Rule IDs
4728
+ bcs$1.vector(bcs$1.u256())
4729
+ // Claimable amounts
4730
+ ]
4731
+ )
4732
+ );
967
4733
  });
4734
+ const u = [];
4735
+ return c.forEach((d, f) => {
4736
+ const v = n[f];
4737
+ if (d.length === 5 && Array.isArray(d[0])) {
4738
+ const y = d[0].length;
4739
+ for (let l = 0; l < y; l++) {
4740
+ const h = s.find(
4741
+ (I) => b(I.coinType) === b(d[1][l])
4742
+ ), j = a.find(
4743
+ (I) => b(I.coinType) === b(d[0][l]) && I.market === v.market
4744
+ );
4745
+ !h || !j || u.push({
4746
+ assetId: j.id,
4747
+ assetCoinType: b(d[0][l]),
4748
+ rewardCoinType: b(d[1][l]),
4749
+ option: Number(d[2][l]),
4750
+ userClaimableReward: Number(d[4][l]) / Math.pow(10, h.priceDecimal),
4751
+ ruleIds: Array.isArray(d[3][l]) ? d[3][l] : [d[3][l]],
4752
+ market: v.market,
4753
+ owner: v.owner,
4754
+ address: v.address,
4755
+ emodeId: v.emodeId
4756
+ });
4757
+ }
4758
+ }
4759
+ }), u;
968
4760
  }
969
- async function reportFee(agentAddress, operation, feeAmount, feeRate, txDigest) {
4761
+ async function vt(e, n) {
4762
+ const o = (n?.markets || [M.main]).map((a) => _(a));
4763
+ let r = [];
970
4764
  try {
971
- await fetch(`${API_BASE_URL}/api/fees`, {
972
- method: "POST",
973
- headers: { "Content-Type": "application/json" },
974
- body: JSON.stringify({
975
- agentAddress,
976
- operation,
977
- feeAmount: feeAmount.toString(),
978
- feeRate: feeRate.toString(),
979
- txDigest
980
- })
4765
+ r = await x(e, n);
4766
+ } catch (a) {
4767
+ console.error(a);
4768
+ }
4769
+ const t = o.map((a) => ({
4770
+ address: e,
4771
+ owner: e,
4772
+ market: a.key
4773
+ })).concat(
4774
+ r.filter((a) => !!o.find((s) => s.id === a.marketId)).map((a) => {
4775
+ const s = _(a.marketId);
4776
+ return {
4777
+ address: a.accountCap,
4778
+ owner: e,
4779
+ market: s.key,
4780
+ emodeId: a.emodeId
4781
+ };
4782
+ })
4783
+ );
4784
+ return await De(e, t, n);
4785
+ }
4786
+ function wt(e) {
4787
+ const n = /* @__PURE__ */ new Map();
4788
+ e.forEach((r) => {
4789
+ const t = r.assetId, a = r.option, s = `${t}-${a}-${r.rewardCoinType}-${r.market}`;
4790
+ n.has(s) ? n.get(s).total += r.userClaimableReward : n.set(s, {
4791
+ assetId: t,
4792
+ rewardType: a,
4793
+ coinType: r.rewardCoinType,
4794
+ total: Number(r.userClaimableReward),
4795
+ market: r.market
981
4796
  });
982
- } catch {
4797
+ });
4798
+ const o = /* @__PURE__ */ new Map();
4799
+ for (const { assetId: r, rewardType: t, coinType: a, total: s, market: i } of n.values()) {
4800
+ const c = `${r}-${t}-${i}`;
4801
+ o.has(c) || o.set(c, { assetId: r, rewardType: t, market: i, rewards: /* @__PURE__ */ new Map() });
4802
+ const u = o.get(c);
4803
+ u.rewards.set(a, (u.rewards.get(a) || 0) + s);
4804
+ }
4805
+ return Array.from(o.values()).map((r) => ({
4806
+ assetId: r.assetId,
4807
+ rewardType: r.rewardType,
4808
+ market: r.market,
4809
+ rewards: Array.from(r.rewards.entries()).map(([t, a]) => ({
4810
+ coinType: t,
4811
+ available: a.toFixed(6)
4812
+ }))
4813
+ }));
4814
+ }
4815
+ async function Ct(e, n, o) {
4816
+ const r = await R({
4817
+ ...o,
4818
+ markets: Object.values(M),
4819
+ cacheTime: w
4820
+ }), t = /* @__PURE__ */ new Map();
4821
+ for (const s of n) {
4822
+ const { rewardCoinType: i, ruleIds: c, market: u, owner: d, address: f, emodeId: v } = s, y = `${i}___${f}`;
4823
+ for (const l of c) {
4824
+ t.has(y) || t.set(y, {
4825
+ assetIds: [],
4826
+ ruleIds: [],
4827
+ amount: 0,
4828
+ market: u,
4829
+ owner: d,
4830
+ address: f,
4831
+ isEMode: typeof v < "u"
4832
+ });
4833
+ const h = t.get(y);
4834
+ h.assetIds.push(s.assetCoinType.replace("0x", "")), h.ruleIds.push(l), h.amount += s.userClaimableReward;
4835
+ }
983
4836
  }
4837
+ const a = [];
4838
+ for (const [
4839
+ s,
4840
+ { assetIds: i, ruleIds: c, amount: u, market: d, owner: f, address: v, isEMode: y }
4841
+ ] of t) {
4842
+ const l = await k({
4843
+ ...o,
4844
+ cacheTime: w,
4845
+ market: d
4846
+ }), h = s.split("___")[0], j = r.find(
4847
+ (S) => b(S.suiCoinType) === b(h) && S.market === d
4848
+ );
4849
+ if (!j || !j.contract.rewardFundId)
4850
+ throw new Error(`No matching rewardFund found for reward coin: ${h} ${d}`);
4851
+ const I = j.contract.rewardFundId;
4852
+ if (o?.accountCap && !o.customCoinReceive)
4853
+ throw new Error("customCoinReceive is required when accountCap is provided");
4854
+ if (o?.customCoinReceive) {
4855
+ let S;
4856
+ o.accountCap ? S = e.moveCall({
4857
+ target: `${l.package}::incentive_v3::claim_reward_with_account_cap`,
4858
+ arguments: [
4859
+ e.object("0x06"),
4860
+ // Clock object
4861
+ e.object(l.incentiveV3),
4862
+ // Incentive V3 contract
4863
+ e.object(l.storage),
4864
+ // Protocol storage
4865
+ e.object(I),
4866
+ // Reward fund
4867
+ e.pure.vector("string", i),
4868
+ // Asset IDs
4869
+ e.pure.vector("address", c),
4870
+ // Rule IDs
4871
+ g(o.accountCap, e.object)
4872
+ // Account capability
4873
+ ],
4874
+ typeArguments: [h]
4875
+ }) : y ? S = e.moveCall({
4876
+ target: `${l.package}::incentive_v3::claim_reward_with_account_cap`,
4877
+ arguments: [
4878
+ e.object("0x06"),
4879
+ // Clock object
4880
+ e.object(l.incentiveV3),
4881
+ // Incentive V3 contract
4882
+ e.object(l.storage),
4883
+ // Protocol storage
4884
+ e.object(I),
4885
+ // Reward fund
4886
+ e.pure.vector("string", i),
4887
+ // Asset IDs
4888
+ e.pure.vector("address", c),
4889
+ // Rule IDs
4890
+ g(v, e.object)
4891
+ // Account capability
4892
+ ],
4893
+ typeArguments: [h]
4894
+ }) : S = e.moveCall({
4895
+ target: `${l.package}::incentive_v3::claim_reward`,
4896
+ arguments: [
4897
+ e.object("0x06"),
4898
+ // Clock object
4899
+ e.object(l.incentiveV3),
4900
+ // Incentive V3 contract
4901
+ e.object(l.storage),
4902
+ // Protocol storage
4903
+ e.object(I),
4904
+ // Reward fund
4905
+ e.pure.vector("string", i),
4906
+ // Asset IDs
4907
+ e.pure.vector("address", c)
4908
+ // Rule IDs
4909
+ ],
4910
+ typeArguments: [h]
4911
+ });
4912
+ const [D] = e.moveCall({
4913
+ target: "0x2::coin::from_balance",
4914
+ arguments: [S],
4915
+ typeArguments: [h]
4916
+ });
4917
+ if (o?.customCoinReceive.type === "transfer") {
4918
+ if (!o.customCoinReceive.transfer)
4919
+ throw new Error("customCoinReceive.transfer is required");
4920
+ e.transferObjects(
4921
+ [D],
4922
+ g(o.customCoinReceive.transfer, e.pure.address)
4923
+ );
4924
+ }
4925
+ if (o?.customCoinReceive.type === "depositNAVI") {
4926
+ const re = bignumber_default(j.totalSupplyAmount).shiftedBy(-9), ae = bignumber_default(j.supplyCapCeiling).shiftedBy(-27);
4927
+ re.plus(u).isGreaterThan(ae) && o?.customCoinReceive.depositNAVI?.fallbackReceiveAddress ? e.transferObjects(
4928
+ [D],
4929
+ e.pure.address(o.customCoinReceive.depositNAVI.fallbackReceiveAddress)
4930
+ ) : await Ce(e, j, D, o);
4931
+ } else
4932
+ a.push({
4933
+ coin: D,
4934
+ identifier: j,
4935
+ owner: f,
4936
+ isEMode: y
4937
+ });
4938
+ } else if (o?.accountCap || y) {
4939
+ const S = e.moveCall({
4940
+ target: `${l.package}::incentive_v3::claim_reward_with_account_cap`,
4941
+ arguments: [
4942
+ e.object("0x06"),
4943
+ // Clock object
4944
+ e.object(l.incentiveV3),
4945
+ // Incentive V3 contract
4946
+ e.object(l.storage),
4947
+ // Protocol storage
4948
+ e.object(I),
4949
+ // Reward fund
4950
+ e.pure.vector("string", i),
4951
+ // Asset IDs
4952
+ e.pure.vector("address", c),
4953
+ // Rule IDs
4954
+ g(o?.accountCap || v, e.object)
4955
+ // Account capability
4956
+ ],
4957
+ typeArguments: [h]
4958
+ }), [D] = e.moveCall({
4959
+ target: "0x2::coin::from_balance",
4960
+ arguments: [S],
4961
+ typeArguments: [h]
4962
+ });
4963
+ e.transferObjects(
4964
+ [D],
4965
+ g(o?.accountCap || f, e.pure.address)
4966
+ );
4967
+ } else
4968
+ e.moveCall({
4969
+ target: `${l.package}::incentive_v3::claim_reward_entry`,
4970
+ arguments: [
4971
+ e.object("0x06"),
4972
+ // Clock object
4973
+ e.object(l.incentiveV3),
4974
+ // Incentive V3 contract
4975
+ e.object(l.storage),
4976
+ // Protocol storage
4977
+ e.object(I),
4978
+ // Reward fund
4979
+ e.pure.vector("string", i),
4980
+ // Asset IDs
4981
+ e.pure.vector("address", c)
4982
+ // Rule IDs
4983
+ ],
4984
+ typeArguments: [h]
4985
+ });
4986
+ }
4987
+ return a;
984
4988
  }
4989
+
4990
+ // src/protocols/navi.ts
985
4991
  init_errors();
986
4992
  var MIN_HEALTH_FACTOR = 1.5;
987
4993
  function sdkOptions(client) {
@@ -1000,7 +5006,7 @@ async function refreshOracle(tx, client, address, options) {
1000
5006
  origWarn.apply(console, args);
1001
5007
  };
1002
5008
  try {
1003
- const pools = await getPools(sdkOptions(client));
5009
+ const pools = await R(sdkOptions(client));
1004
5010
  const oracleOpts = {
1005
5011
  ...sdkOptions(client),
1006
5012
  throws: false,
@@ -1008,7 +5014,7 @@ async function refreshOracle(tx, client, address, options) {
1008
5014
  // with sponsored transactions where tx.gas belongs to the sponsor.
1009
5015
  updatePythPriceFeeds: !options?.skipPythUpdate
1010
5016
  };
1011
- await updateOraclePriceBeforeUserOperationPTB(tx, address, pools, oracleOpts);
5017
+ await mt(tx, address, pools, oracleOpts);
1012
5018
  } catch {
1013
5019
  } finally {
1014
5020
  console.info = origInfo;
@@ -1070,7 +5076,7 @@ function mergeCoins(tx, coins) {
1070
5076
  }
1071
5077
  async function getPositions(client, address) {
1072
5078
  try {
1073
- const naviPositions = await getLendingPositions(address, {
5079
+ const naviPositions = await $e(address, {
1074
5080
  ...sdkOptions(client),
1075
5081
  markets: ["main"]
1076
5082
  });
@@ -1104,7 +5110,7 @@ async function getPositions(client, address) {
1104
5110
  }
1105
5111
  async function getRates(client) {
1106
5112
  try {
1107
- const pools = await getPools(sdkOptions(client));
5113
+ const pools = await R(sdkOptions(client));
1108
5114
  const result = {};
1109
5115
  for (const asset of ALL_NAVI_ASSETS) {
1110
5116
  const targetType = SUPPORTED_ASSETS[asset].type;
@@ -1137,7 +5143,7 @@ async function getHealthFactor(client, address) {
1137
5143
  }
1138
5144
  let healthFactor;
1139
5145
  try {
1140
- const hf = await getHealthFactor$1(address, sdkOptions(client));
5146
+ const hf = await ct(address, sdkOptions(client));
1141
5147
  healthFactor = hf > 1e5 ? Infinity : hf;
1142
5148
  } catch {
1143
5149
  healthFactor = borrowed > 0 ? supplied * 0.75 / borrowed : Infinity;
@@ -1169,7 +5175,7 @@ async function buildSaveTx(client, address, amount, options = {}) {
1169
5175
  }
1170
5176
  const rawAmount = Math.min(Number(stableToRaw(amount, assetInfo.decimals)), Number(totalBalance));
1171
5177
  try {
1172
- await depositCoinPTB(tx, assetInfo.type, coinObj, {
5178
+ await Ce(tx, assetInfo.type, coinObj, {
1173
5179
  ...sdkOptions(client),
1174
5180
  amount: rawAmount
1175
5181
  });
@@ -1198,7 +5204,7 @@ async function buildWithdrawTx(client, address, amount, options = {}) {
1198
5204
  tx.setSender(address);
1199
5205
  await refreshOracle(tx, client, address, { skipPythUpdate: options.sponsored });
1200
5206
  try {
1201
- const coin = await withdrawCoinPTB(tx, assetInfo.type, rawAmount, sdkOptions(client));
5207
+ const coin = await Qe(tx, assetInfo.type, rawAmount, sdkOptions(client));
1202
5208
  tx.transferObjects([coin], address);
1203
5209
  } catch (err) {
1204
5210
  const msg = err instanceof Error ? err.message : String(err);
@@ -1228,7 +5234,7 @@ async function addWithdrawToTx(tx, client, address, amount, options = {}) {
1228
5234
  }
1229
5235
  await refreshOracle(tx, client, address, { skipPythUpdate: sponsored });
1230
5236
  try {
1231
- const coin = await withdrawCoinPTB(tx, assetInfo.type, rawAmount, sdkOptions(client));
5237
+ const coin = await Qe(tx, assetInfo.type, rawAmount, sdkOptions(client));
1232
5238
  return { coin, effectiveAmount };
1233
5239
  } catch (err) {
1234
5240
  const msg = err instanceof Error ? err.message : String(err);
@@ -1242,7 +5248,7 @@ async function addSaveToTx(tx, _client, _address, coin, options = {}) {
1242
5248
  addCollectFeeToTx(tx, coin, "save");
1243
5249
  }
1244
5250
  try {
1245
- await depositCoinPTB(tx, assetInfo.type, coin, { env: "prod" });
5251
+ await Ce(tx, assetInfo.type, coin, { env: "prod" });
1246
5252
  } catch (err) {
1247
5253
  const msg = err instanceof Error ? err.message : String(err);
1248
5254
  throw new T2000Error("PROTOCOL_UNAVAILABLE", `NAVI deposit failed: ${msg}`);
@@ -1254,7 +5260,7 @@ async function addRepayToTx(tx, client, address, coin, options = {}) {
1254
5260
  const assetInfo = resolveAssetInfo(asset);
1255
5261
  await refreshOracle(tx, client, address, { skipPythUpdate: sponsored });
1256
5262
  try {
1257
- await repayCoinPTB(tx, assetInfo.type, coin, { env: "prod" });
5263
+ await xe(tx, assetInfo.type, coin, { env: "prod" });
1258
5264
  } catch (err) {
1259
5265
  const msg = err instanceof Error ? err.message : String(err);
1260
5266
  throw new T2000Error("PROTOCOL_UNAVAILABLE", `NAVI repay failed: ${msg}`);
@@ -1271,7 +5277,7 @@ async function buildBorrowTx(client, address, amount, options = {}) {
1271
5277
  tx.setSender(address);
1272
5278
  await refreshOracle(tx, client, address, { skipPythUpdate: options.sponsored });
1273
5279
  try {
1274
- const borrowedCoin = await borrowCoinPTB(tx, assetInfo.type, rawAmount, sdkOptions(client));
5280
+ const borrowedCoin = await Xe(tx, assetInfo.type, rawAmount, sdkOptions(client));
1275
5281
  if (options.collectFee) {
1276
5282
  addCollectFeeToTx(tx, borrowedCoin, "borrow");
1277
5283
  }
@@ -1305,7 +5311,7 @@ async function buildRepayTx(client, address, amount, options = {}) {
1305
5311
  skipOracle: options.skipOracle
1306
5312
  });
1307
5313
  try {
1308
- await repayCoinPTB(tx, assetInfo.type, repayCoin, {
5314
+ await xe(tx, assetInfo.type, repayCoin, {
1309
5315
  ...sdkOptions(client),
1310
5316
  amount: rawAmount
1311
5317
  });
@@ -1336,12 +5342,12 @@ async function maxBorrowAmount(client, address) {
1336
5342
  }
1337
5343
  async function getPendingRewards(client, address) {
1338
5344
  try {
1339
- const rewards = await getUserAvailableLendingRewards(address, {
5345
+ const rewards = await vt(address, {
1340
5346
  ...sdkOptions(client),
1341
5347
  markets: ["main"]
1342
5348
  });
1343
5349
  if (!rewards || rewards.length === 0) return [];
1344
- const summary = summaryLendingRewards(rewards);
5350
+ const summary = wt(rewards);
1345
5351
  const result = [];
1346
5352
  for (const s of summary) {
1347
5353
  for (const rw of s.rewards) {
@@ -1365,7 +5371,7 @@ async function getPendingRewards(client, address) {
1365
5371
  }
1366
5372
  async function addClaimRewardsToTx(tx, client, address) {
1367
5373
  try {
1368
- const rewards = await getUserAvailableLendingRewards(address, {
5374
+ const rewards = await vt(address, {
1369
5375
  ...sdkOptions(client),
1370
5376
  markets: ["main"]
1371
5377
  });
@@ -1374,7 +5380,7 @@ async function addClaimRewardsToTx(tx, client, address) {
1374
5380
  (r) => Number(r.userClaimableReward) > 0
1375
5381
  );
1376
5382
  if (claimable.length === 0) return [];
1377
- const claimed = await claimLendingRewardsPTB(tx, claimable, {
5383
+ const claimed = await Ct(tx, claimable, {
1378
5384
  env: "prod",
1379
5385
  customCoinReceive: { type: "transfer", transfer: address }
1380
5386
  });
@@ -1439,7 +5445,7 @@ var ProtocolRegistry = class {
1439
5445
  if (candidates.length === 0) {
1440
5446
  throw new T2000Error("ASSET_NOT_SUPPORTED", `No lending adapter supports saving ${asset}`);
1441
5447
  }
1442
- candidates.sort((a, b) => b.rate.saveApy - a.rate.saveApy);
5448
+ candidates.sort((a, b2) => b2.rate.saveApy - a.rate.saveApy);
1443
5449
  return candidates[0];
1444
5450
  }
1445
5451
  async bestBorrowRate(asset, opts) {
@@ -1457,7 +5463,7 @@ var ProtocolRegistry = class {
1457
5463
  if (candidates.length === 0) {
1458
5464
  throw new T2000Error("ASSET_NOT_SUPPORTED", `No lending adapter supports borrowing ${asset}`);
1459
5465
  }
1460
- candidates.sort((a, b) => a.rate.borrowApy - b.rate.borrowApy);
5466
+ candidates.sort((a, b2) => a.rate.borrowApy - b2.rate.borrowApy);
1461
5467
  return candidates[0];
1462
5468
  }
1463
5469
  async bestSaveRateAcrossAssets() {
@@ -1476,7 +5482,7 @@ var ProtocolRegistry = class {
1476
5482
  if (candidates.length === 0) {
1477
5483
  throw new T2000Error("ASSET_NOT_SUPPORTED", "No lending adapter found for any stablecoin");
1478
5484
  }
1479
- candidates.sort((a, b) => b.rate.saveApy - a.rate.saveApy);
5485
+ candidates.sort((a, b2) => b2.rate.saveApy - a.rate.saveApy);
1480
5486
  return candidates[0];
1481
5487
  }
1482
5488
  async allRatesAcrossAssets() {
@@ -1688,12 +5694,12 @@ async function executeAutoTopUp(_client, _signer) {
1688
5694
  init_errors();
1689
5695
 
1690
5696
  // src/utils/base64.ts
1691
- function toBase64(bytes) {
5697
+ function toBase642(bytes) {
1692
5698
  let binary = "";
1693
5699
  for (const byte of bytes) binary += String.fromCharCode(byte);
1694
5700
  return btoa(binary);
1695
5701
  }
1696
- function fromBase64(b64) {
5702
+ function fromBase642(b64) {
1697
5703
  const binary = atob(b64);
1698
5704
  const bytes = new Uint8Array(binary.length);
1699
5705
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
@@ -1707,7 +5713,7 @@ async function requestGasSponsorship(txJson, sender, type, txBcsBytes) {
1707
5713
  payload.txBcsBytes = txBcsBytes;
1708
5714
  } else {
1709
5715
  payload.txJson = txJson;
1710
- payload.txBytes = toBase64(new TextEncoder().encode(txJson));
5716
+ payload.txBytes = toBase642(new TextEncoder().encode(txJson));
1711
5717
  }
1712
5718
  const res = await fetch(`${API_BASE_URL}/api/gas`, {
1713
5719
  method: "POST",
@@ -1789,7 +5795,7 @@ async function trySelfFunded(client, signer, tx) {
1789
5795
  const builtBytes = await tx.build({ client });
1790
5796
  const { signature } = await signer.signTransaction(builtBytes);
1791
5797
  const result = await client.executeTransactionBlock({
1792
- transactionBlock: toBase64(builtBytes),
5798
+ transactionBlock: toBase642(builtBytes),
1793
5799
  signature: [signature],
1794
5800
  options: { showEffects: true, showBalanceChanges: true }
1795
5801
  });
@@ -1815,7 +5821,7 @@ async function tryAutoTopUpThenSelfFund(client, signer, buildTx) {
1815
5821
  const builtBytes = await tx.build({ client });
1816
5822
  const { signature } = await signer.signTransaction(builtBytes);
1817
5823
  const result = await client.executeTransactionBlock({
1818
- transactionBlock: toBase64(builtBytes),
5824
+ transactionBlock: toBase642(builtBytes),
1819
5825
  signature: [signature],
1820
5826
  options: { showEffects: true, showBalanceChanges: true }
1821
5827
  });
@@ -1840,10 +5846,10 @@ async function trySponsored(client, signer, tx) {
1840
5846
  txJson = tx.serialize();
1841
5847
  } catch {
1842
5848
  const bcsBytes = await tx.build({ client });
1843
- txBcsBase64 = toBase64(bcsBytes);
5849
+ txBcsBase64 = toBase642(bcsBytes);
1844
5850
  }
1845
5851
  const sponsoredResult = await requestGasSponsorship(txJson ?? "", address, void 0, txBcsBase64);
1846
- const sponsoredTxBytes = fromBase64(sponsoredResult.txBytes);
5852
+ const sponsoredTxBytes = fromBase642(sponsoredResult.txBytes);
1847
5853
  const { signature: agentSig } = await signer.signTransaction(sponsoredTxBytes);
1848
5854
  const result = await client.executeTransactionBlock({
1849
5855
  transactionBlock: sponsoredResult.txBytes,
@@ -2029,7 +6035,7 @@ var SafeguardEnforcer = class {
2029
6035
  configPath;
2030
6036
  constructor(configDir) {
2031
6037
  this.config = { ...DEFAULT_SAFEGUARD_CONFIG };
2032
- this.configPath = configDir ? join(configDir, "config.json") : null;
6038
+ this.configPath = configDir ? join$1(configDir, "config.json") : null;
2033
6039
  }
2034
6040
  load() {
2035
6041
  if (!this.configPath) return;
@@ -2146,8 +6152,8 @@ var ContactManager = class {
2146
6152
  filePath;
2147
6153
  dir;
2148
6154
  constructor(configDir) {
2149
- this.dir = configDir ?? join(homedir(), ".t2000");
2150
- this.filePath = join(this.dir, "contacts.json");
6155
+ this.dir = configDir ?? join$1(homedir(), ".t2000");
6156
+ this.filePath = join$1(this.dir, "contacts.json");
2151
6157
  this.load();
2152
6158
  }
2153
6159
  load() {
@@ -2217,7 +6223,7 @@ var ContactManager = class {
2217
6223
  }
2218
6224
  }
2219
6225
  };
2220
- var DEFAULT_CONFIG_DIR = join(homedir(), ".t2000");
6226
+ var DEFAULT_CONFIG_DIR = join$1(homedir(), ".t2000");
2221
6227
  var T2000 = class _T2000 extends EventEmitter {
2222
6228
  _signer;
2223
6229
  _keypair;
@@ -2626,13 +6632,28 @@ var T2000 = class _T2000 extends EventEmitter {
2626
6632
  const currency = params?.currency ?? "USDC";
2627
6633
  const memo = params?.memo ?? null;
2628
6634
  const label = params?.label ?? null;
2629
- const qrParts = [`sui:${this._address}`];
2630
- const queryParams = [];
2631
- if (amount != null) queryParams.push(`amount=${amount}`);
2632
- if (currency !== "SUI") queryParams.push(`currency=${currency}`);
2633
- if (memo) queryParams.push(`memo=${encodeURIComponent(memo)}`);
2634
- if (label) queryParams.push(`label=${encodeURIComponent(label)}`);
2635
- const qrUri = queryParams.length > 0 ? `${qrParts[0]}?${queryParams.join("&")}` : qrParts[0];
6635
+ const nonce = crypto.randomUUID();
6636
+ let qrUri;
6637
+ if (amount != null && amount > 0) {
6638
+ const decimals = currency === "SUI" ? 9 : 6;
6639
+ const coinType = currency === "SUI" ? "0x2::sui::SUI" : SUPPORTED_ASSETS.USDC.type;
6640
+ const rawAmount = BigInt(Math.floor(amount * 10 ** decimals));
6641
+ qrUri = createPaymentTransactionUri({
6642
+ receiverAddress: this._address,
6643
+ amount: rawAmount,
6644
+ coinType,
6645
+ nonce,
6646
+ ...label ? { label } : {},
6647
+ ...memo ? { message: memo } : {}
6648
+ });
6649
+ } else {
6650
+ const qrParts = [`sui:${this._address}`];
6651
+ const queryParams = [];
6652
+ if (currency !== "SUI") queryParams.push(`currency=${currency}`);
6653
+ if (memo) queryParams.push(`memo=${encodeURIComponent(memo)}`);
6654
+ if (label) queryParams.push(`label=${encodeURIComponent(label)}`);
6655
+ qrUri = queryParams.length > 0 ? `${qrParts[0]}?${queryParams.join("&")}` : qrParts[0];
6656
+ }
2636
6657
  const amountStr = amount != null ? `$${amount.toFixed(2)} ` : "";
2637
6658
  const displayParts = [`Send ${amountStr}${currency} to ${truncateAddress(this._address)}`];
2638
6659
  if (memo) displayParts.push(`Memo: ${memo}`);
@@ -2643,6 +6664,7 @@ var T2000 = class _T2000 extends EventEmitter {
2643
6664
  currency,
2644
6665
  memo,
2645
6666
  label,
6667
+ nonce,
2646
6668
  qrUri,
2647
6669
  displayText: displayParts.join("\n")
2648
6670
  };
@@ -2747,11 +6769,11 @@ var T2000 = class _T2000 extends EventEmitter {
2747
6769
  if (supplies.length === 0) {
2748
6770
  throw new T2000Error("NO_COLLATERAL", params.asset ? `No ${params.asset} savings to withdraw` : "No savings to withdraw");
2749
6771
  }
2750
- supplies.sort((a, b) => {
6772
+ supplies.sort((a, b2) => {
2751
6773
  const aIsUsdc = a.asset === "USDC" ? 0 : 1;
2752
- const bIsUsdc = b.asset === "USDC" ? 0 : 1;
6774
+ const bIsUsdc = b2.asset === "USDC" ? 0 : 1;
2753
6775
  if (aIsUsdc !== bIsUsdc) return aIsUsdc - bIsUsdc;
2754
- return a.apy - b.apy;
6776
+ return a.apy - b2.apy;
2755
6777
  });
2756
6778
  const target = supplies[0];
2757
6779
  const adapter = this.registry.getLending(target.protocolId);
@@ -2994,8 +7016,8 @@ var T2000 = class _T2000 extends EventEmitter {
2994
7016
  const borrows = [];
2995
7017
  for (const pos of allPositions) {
2996
7018
  if (params.protocol && pos.protocolId !== params.protocol) continue;
2997
- for (const b of pos.positions.borrows) {
2998
- if (b.amount > 1e-3) borrows.push({ protocolId: pos.protocolId, asset: b.asset, amount: b.amount, apy: b.apy });
7019
+ for (const b2 of pos.positions.borrows) {
7020
+ if (b2.amount > 1e-3) borrows.push({ protocolId: pos.protocolId, asset: b2.asset, amount: b2.amount, apy: b2.apy });
2999
7021
  }
3000
7022
  }
3001
7023
  if (borrows.length === 0) {
@@ -3004,7 +7026,7 @@ var T2000 = class _T2000 extends EventEmitter {
3004
7026
  if (params.amount === "all") {
3005
7027
  return this._repayAllBorrows(borrows);
3006
7028
  }
3007
- borrows.sort((a, b) => b.apy - a.apy);
7029
+ borrows.sort((a, b2) => b2.apy - a.apy);
3008
7030
  const target = borrows[0];
3009
7031
  const adapter = this.registry.getLending(target.protocolId);
3010
7032
  if (!adapter) throw new T2000Error("PROTOCOL_UNAVAILABLE", `Protocol ${target.protocolId} not found`);
@@ -3036,7 +7058,7 @@ var T2000 = class _T2000 extends EventEmitter {
3036
7058
  };
3037
7059
  }
3038
7060
  async _repayAllBorrows(borrows) {
3039
- borrows.sort((a, b) => b.apy - a.apy);
7061
+ borrows.sort((a, b2) => b2.apy - a.apy);
3040
7062
  const entries = [];
3041
7063
  for (const borrow of borrows) {
3042
7064
  const adapter = this.registry.getLending(borrow.protocolId);
@@ -3279,13 +7301,13 @@ var T2000 = class _T2000 extends EventEmitter {
3279
7301
  amountUsd: s.amountUsd,
3280
7302
  apy: s.apy
3281
7303
  })),
3282
- ...p.positions.borrows.filter((b) => b.amount > 5e-3).map((b) => ({
7304
+ ...p.positions.borrows.filter((b2) => b2.amount > 5e-3).map((b2) => ({
3283
7305
  protocol: p.protocolId,
3284
- asset: b.asset,
7306
+ asset: b2.asset,
3285
7307
  type: "borrow",
3286
- amount: b.amount,
3287
- amountUsd: b.amountUsd,
3288
- apy: b.apy
7308
+ amount: b2.amount,
7309
+ amountUsd: b2.amountUsd,
7310
+ apy: b2.apy
3289
7311
  }))
3290
7312
  ]
3291
7313
  );
@@ -3739,10 +7761,15 @@ async function verifyScopedIntent(intent, adminPublicKeyBytes) {
3739
7761
  }
3740
7762
  function canonicalIntentBytes(payload) {
3741
7763
  const sorted = Object.fromEntries(
3742
- Object.entries(payload).sort(([a], [b]) => a.localeCompare(b))
7764
+ Object.entries(payload).sort(([a], [b2]) => a.localeCompare(b2))
3743
7765
  );
3744
7766
  return new TextEncoder().encode(JSON.stringify(sorted));
3745
7767
  }
7768
+ /*! Bundled license information:
7769
+
7770
+ @scure/base/index.js:
7771
+ (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
7772
+ */
3746
7773
 
3747
7774
  export { ALLOWANCE_FEATURES, ALL_NAVI_ASSETS, BPS_DENOMINATOR, CETUS_USDC_SUI_POOL, CLOCK_ID, COIN_REGISTRY, ContactManager, DEFAULT_NETWORK, DEFAULT_SAFEGUARD_CONFIG, ETH_TYPE, GAS_RESERVE_MIN, HF_CRITICAL_THRESHOLD, HF_WARN_THRESHOLD, IKA_TYPE, KeypairSigner, LOFI_TYPE, MANIFEST_TYPE, MIST_PER_SUI, NAVX_TYPE, NaviAdapter, OPERATION_ASSETS, OUTBOUND_OPS, ProtocolRegistry, STABLE_ASSETS, SUI_DECIMALS, SUI_TYPE, SUPPORTED_ASSETS, SafeguardEnforcer, SafeguardError, T2000, T2000Error, TOKEN_MAP, USDC_DECIMALS, USDC_TYPE, USDE_TYPE, USDSUI_TYPE, USDT_TYPE, VOLO_METADATA, VOLO_PKG, VOLO_POOL, VSUI_TYPE, WAL_TYPE, WBTC_TYPE, ZkLoginSigner, addCollectFeeToTx, addDepositAllowanceTx, allDescriptors, assertAllowedAsset, buildAdminDepositAllowanceTx, buildCreateAllowanceTx, buildDeductAllowanceTx, buildDepositAllowanceTx, buildScopedIntent, buildStakeVSuiTx, buildSwapTx, buildUnstakeVSuiTx, buildWithdrawAllowanceTx, buildWithdrawAmountAllowanceTx, calculateFee, executeAutoTopUp, executeWithGas, exportPrivateKey, findSwapRoute, formatAssetAmount, formatSui, formatUsd, generateKeypair, getAddress, getAllowance, getAllowanceBalance, getDecimals, getDecimalsForCoinType, getFinancialSummary, getGasStatus, getPendingRewards, getRates, getSwapQuote, getTier, getVoloStats, isAllowedAsset, isSupported, isTier1, isTier2, keypairFromPrivateKey, loadKey, mapMoveAbortCode, mapWalletError, mistToSui, naviDescriptor, rawToStable, rawToUsdc, resolveSymbol, resolveTokenType, saveKey, shouldAutoTopUp, simulateTransaction, solveHashcash, stableToRaw, suiToMist, throwIfSimulationFailed, truncateAddress, usdcToRaw, validateAddress, verifyScopedIntent, walletExists };
3748
7775
  //# sourceMappingURL=index.js.map