@gearbox-protocol/sdk 13.0.0-beta.4 → 13.0.0-beta.5

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.
Files changed (65) hide show
  1. package/dist/cjs/common-utils/index.js +22 -0
  2. package/dist/cjs/common-utils/package.json +1 -0
  3. package/dist/cjs/{sdk → common-utils}/utils/assetsMath.js +78 -12
  4. package/dist/cjs/common-utils/utils/bigintMath.js +65 -0
  5. package/dist/cjs/common-utils/utils/creditAccount/calcHealthFactor.js +76 -0
  6. package/dist/cjs/common-utils/utils/creditAccount/calcOverallAPY.js +81 -0
  7. package/dist/cjs/{sdk/utils/priceMath.js → common-utils/utils/creditAccount/calcQuotaBorrowRate.js} +19 -12
  8. package/dist/cjs/{sdk/utils/bigintMath.js → common-utils/utils/creditAccount/calcRelativeBaseBorrowRate.js} +11 -10
  9. package/dist/cjs/common-utils/utils/creditAccount/debt.js +64 -0
  10. package/dist/cjs/common-utils/utils/creditAccount/getTimeToLiquidation.js +38 -0
  11. package/dist/cjs/common-utils/utils/creditAccount/index.js +38 -0
  12. package/dist/cjs/common-utils/utils/creditAccount/liquidationPrice.js +47 -0
  13. package/dist/cjs/common-utils/utils/creditAccount/quotaUtils.js +149 -0
  14. package/dist/cjs/common-utils/utils/creditAccount/sort.js +95 -0
  15. package/dist/cjs/common-utils/utils/creditAccount/types.js +16 -0
  16. package/dist/cjs/{sdk → common-utils}/utils/endpoints.js +11 -17
  17. package/dist/cjs/common-utils/utils/index.js +30 -0
  18. package/dist/cjs/common-utils/utils/priceMath.js +66 -0
  19. package/dist/cjs/sdk/utils/index.js +0 -10
  20. package/dist/esm/common-utils/index.js +1 -0
  21. package/dist/esm/common-utils/package.json +1 -0
  22. package/dist/esm/{sdk → common-utils}/utils/assetsMath.js +78 -12
  23. package/dist/esm/common-utils/utils/bigintMath.js +41 -0
  24. package/dist/esm/common-utils/utils/creditAccount/calcHealthFactor.js +55 -0
  25. package/dist/esm/common-utils/utils/creditAccount/calcOverallAPY.js +60 -0
  26. package/dist/esm/common-utils/utils/creditAccount/calcQuotaBorrowRate.js +18 -0
  27. package/dist/esm/common-utils/utils/creditAccount/calcRelativeBaseBorrowRate.js +10 -0
  28. package/dist/esm/common-utils/utils/creditAccount/debt.js +43 -0
  29. package/dist/esm/common-utils/utils/creditAccount/getTimeToLiquidation.js +18 -0
  30. package/dist/esm/common-utils/utils/creditAccount/index.js +9 -0
  31. package/dist/esm/common-utils/utils/creditAccount/liquidationPrice.js +23 -0
  32. package/dist/esm/common-utils/utils/creditAccount/quotaUtils.js +125 -0
  33. package/dist/esm/common-utils/utils/creditAccount/sort.js +67 -0
  34. package/dist/esm/common-utils/utils/creditAccount/types.js +0 -0
  35. package/dist/esm/{sdk → common-utils}/utils/endpoints.js +9 -14
  36. package/dist/esm/common-utils/utils/index.js +5 -0
  37. package/dist/esm/common-utils/utils/priceMath.js +42 -0
  38. package/dist/esm/sdk/utils/index.js +0 -5
  39. package/dist/types/common-utils/index.d.ts +1 -0
  40. package/dist/types/common-utils/utils/assetsMath.d.ts +114 -0
  41. package/dist/types/common-utils/utils/bigintMath.d.ts +43 -0
  42. package/dist/types/common-utils/utils/creditAccount/calcHealthFactor.d.ts +25 -0
  43. package/dist/types/common-utils/utils/creditAccount/calcOverallAPY.d.ts +37 -0
  44. package/dist/types/common-utils/utils/creditAccount/calcQuotaBorrowRate.d.ts +18 -0
  45. package/dist/types/common-utils/utils/creditAccount/calcRelativeBaseBorrowRate.d.ts +15 -0
  46. package/dist/types/common-utils/utils/creditAccount/debt.d.ts +35 -0
  47. package/dist/types/common-utils/utils/creditAccount/getTimeToLiquidation.d.ts +16 -0
  48. package/dist/types/common-utils/utils/creditAccount/index.d.ts +9 -0
  49. package/dist/types/common-utils/utils/creditAccount/liquidationPrice.d.ts +25 -0
  50. package/dist/types/common-utils/utils/creditAccount/quotaUtils.d.ts +81 -0
  51. package/dist/types/common-utils/utils/creditAccount/sort.d.ts +55 -0
  52. package/dist/types/common-utils/utils/creditAccount/types.d.ts +18 -0
  53. package/dist/types/{sdk → common-utils}/utils/endpoints.d.ts +13 -5
  54. package/dist/types/common-utils/utils/index.d.ts +5 -0
  55. package/dist/types/common-utils/utils/priceMath.d.ts +47 -0
  56. package/dist/types/sdk/utils/index.d.ts +0 -5
  57. package/package.json +6 -1
  58. package/dist/cjs/sdk/utils/creditAccount.js +0 -411
  59. package/dist/esm/sdk/utils/bigintMath.js +0 -9
  60. package/dist/esm/sdk/utils/creditAccount.js +0 -396
  61. package/dist/esm/sdk/utils/priceMath.js +0 -11
  62. package/dist/types/sdk/utils/assetsMath.d.ts +0 -42
  63. package/dist/types/sdk/utils/bigintMath.d.ts +0 -6
  64. package/dist/types/sdk/utils/creditAccount.d.ts +0 -128
  65. package/dist/types/sdk/utils/priceMath.d.ts +0 -9
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var quotaUtils_exports = {};
20
+ __export(quotaUtils_exports, {
21
+ calcDefaultQuota: () => calcDefaultQuota,
22
+ calcQuotaUpdate: () => calcQuotaUpdate,
23
+ calcRecommendedQuota: () => calcRecommendedQuota,
24
+ roundUpQuota: () => roundUpQuota
25
+ });
26
+ module.exports = __toCommonJS(quotaUtils_exports);
27
+ var import_sdk = require("../../../sdk/index.js");
28
+ var import_bigintMath = require("../bigintMath.js");
29
+ function roundUpQuota(quotaChange) {
30
+ return quotaChange !== import_sdk.MIN_INT96 ? quotaChange / import_sdk.PERCENTAGE_FACTOR * import_sdk.PERCENTAGE_FACTOR : quotaChange;
31
+ }
32
+ function calcRecommendedQuota({
33
+ amount,
34
+ debt,
35
+ lt,
36
+ quotaReserve
37
+ }) {
38
+ const recommendedBaseQuota = import_bigintMath.BigIntMath.min(
39
+ debt,
40
+ amount * lt / import_sdk.PERCENTAGE_FACTOR
41
+ );
42
+ const recommendedQuota = recommendedBaseQuota * (import_sdk.PERCENTAGE_FACTOR + quotaReserve) / import_sdk.PERCENTAGE_FACTOR;
43
+ return roundUpQuota(recommendedQuota);
44
+ }
45
+ function calcDefaultQuota({
46
+ amount,
47
+ lt,
48
+ quotaReserve
49
+ }) {
50
+ const recommendedBaseQuota = amount * lt / import_sdk.PERCENTAGE_FACTOR;
51
+ const recommendedQuota = recommendedBaseQuota * (import_sdk.PERCENTAGE_FACTOR + quotaReserve) / import_sdk.PERCENTAGE_FACTOR;
52
+ return roundUpQuota(recommendedQuota);
53
+ }
54
+ function calcQuotaUpdate(props) {
55
+ const { quotas, initialQuotas, maxDebt, allowedToSpend, allowedToObtain } = props;
56
+ const quotaDecrease = Object.keys(allowedToSpend).reduce((acc, token) => {
57
+ const ch = getSingleQuotaChange(token, 0n, props);
58
+ if (ch && ch.balance < 0) acc[ch.token] = ch;
59
+ return acc;
60
+ }, {});
61
+ const quotaCap = roundUpQuota(maxDebt * 2n);
62
+ const quotaBought = Object.values(initialQuotas).reduce(
63
+ (sum, q) => sum + roundUpQuota(q?.quota || 0n),
64
+ 0n
65
+ );
66
+ const quotaReduced = Object.values(quotaDecrease).reduce((sum, q) => {
67
+ const quotaBalance = q.balance || 0n;
68
+ const safeBalance = quotaBalance === import_sdk.MIN_INT96 ? import_bigintMath.BigIntMath.neg(roundUpQuota(initialQuotas[q.token]?.quota || 0n)) : quotaBalance;
69
+ return sum + safeBalance;
70
+ }, 0n);
71
+ const maxQuotaIncrease = roundUpQuota(
72
+ import_bigintMath.BigIntMath.max(quotaCap - (quotaBought + quotaReduced), 0n)
73
+ );
74
+ const quotaIncrease = Object.keys(allowedToObtain).reduce((acc, token) => {
75
+ const ch = getSingleQuotaChange(token, maxQuotaIncrease, props);
76
+ if (ch && ch.balance > 0) acc[ch.token] = ch;
77
+ return acc;
78
+ }, {});
79
+ const quotaChange = {
80
+ ...quotaDecrease,
81
+ ...quotaIncrease
82
+ };
83
+ const desiredQuota = Object.values(quotas).reduce(
84
+ (acc, cmQuota) => {
85
+ const { token, isActive } = cmQuota;
86
+ const { quota: initialQuota = 0n } = initialQuotas[token] || {};
87
+ if (!isActive) {
88
+ acc[token] = {
89
+ balance: initialQuota,
90
+ token
91
+ };
92
+ } else {
93
+ const change = quotaChange[token]?.balance || 0n;
94
+ const quotaAfter = change === import_sdk.MIN_INT96 ? 0n : initialQuota + change;
95
+ acc[token] = {
96
+ balance: quotaAfter,
97
+ token
98
+ };
99
+ }
100
+ return acc;
101
+ },
102
+ {}
103
+ );
104
+ return {
105
+ desiredQuota,
106
+ quotaDecrease: Object.values(quotaDecrease),
107
+ quotaIncrease: Object.values(quotaIncrease)
108
+ };
109
+ }
110
+ function getSingleQuotaChange(token, unsafeMaxQuotaIncrease, props) {
111
+ const { isActive = false } = props.quotas[token] || {};
112
+ const { quota: unsafeInitialQuota = 0n } = props.initialQuotas[token] || {};
113
+ if (!isActive) {
114
+ return void 0;
115
+ }
116
+ const assetAfter = props.assetsAfterUpdate[token];
117
+ const { amountInTarget = 0n } = assetAfter || {};
118
+ const lt = props.liquidationThresholds[token] || 0n;
119
+ const maxQuotaIncrease = roundUpQuota(unsafeMaxQuotaIncrease);
120
+ const initialQuota = roundUpQuota(unsafeInitialQuota);
121
+ const defaultQuota = props.calcModification?.type === "recommendedQuota" && props.calcModification.debt > 0 ? calcRecommendedQuota({
122
+ lt,
123
+ quotaReserve: props.quotaReserve,
124
+ amount: amountInTarget,
125
+ debt: props.calcModification.debt
126
+ }) : calcDefaultQuota({
127
+ lt,
128
+ quotaReserve: props.quotaReserve,
129
+ amount: amountInTarget
130
+ });
131
+ const unsafeQuotaChange = roundUpQuota(defaultQuota - initialQuota);
132
+ const quotaChange = unsafeQuotaChange > 0 ? import_bigintMath.BigIntMath.min(maxQuotaIncrease, unsafeQuotaChange) : unsafeQuotaChange < 0 && import_bigintMath.BigIntMath.abs(unsafeQuotaChange) >= initialQuota ? import_sdk.MIN_INT96 : unsafeQuotaChange;
133
+ const correctIncrease = assetAfter && props.allowedToObtain[token] && quotaChange > 0;
134
+ const correctDecrease = assetAfter && props.allowedToSpend[token] && quotaChange < 0;
135
+ if (correctIncrease || correctDecrease) {
136
+ return {
137
+ balance: quotaChange,
138
+ token
139
+ };
140
+ }
141
+ return void 0;
142
+ }
143
+ // Annotate the CommonJS export names for ESM import in node:
144
+ 0 && (module.exports = {
145
+ calcDefaultQuota,
146
+ calcQuotaUpdate,
147
+ calcRecommendedQuota,
148
+ roundUpQuota
149
+ });
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var sort_exports = {};
20
+ __export(sort_exports, {
21
+ amountAbcComparator: () => amountAbcComparator,
22
+ assetComparator: () => assetComparator,
23
+ sortAssets: () => sortAssets,
24
+ sortBalances: () => sortBalances,
25
+ tokensAbcComparator: () => tokensAbcComparator
26
+ });
27
+ module.exports = __toCommonJS(sort_exports);
28
+ var import_sdk = require("../../../sdk/index.js");
29
+ var import_priceMath = require("../priceMath.js");
30
+ function sortBalances(balances, prices, tokens) {
31
+ return Object.entries(balances).sort(
32
+ ([addr1, amount1], [addr2, amount2]) => {
33
+ return assetComparator(
34
+ {
35
+ token: addr1,
36
+ balance: amount1
37
+ },
38
+ {
39
+ token: addr2,
40
+ balance: amount2
41
+ },
42
+ prices,
43
+ prices,
44
+ tokens,
45
+ tokens
46
+ );
47
+ }
48
+ );
49
+ }
50
+ function sortAssets(balances, prices, tokens) {
51
+ return [...balances].sort(
52
+ (t1, t2) => assetComparator(t1, t2, prices, prices, tokens, tokens)
53
+ );
54
+ }
55
+ function assetComparator(t1, t2, prices1, prices2, tokens1, tokens2) {
56
+ const addr1Lc = t1.token.toLowerCase();
57
+ const addr2Lc = t2.token.toLowerCase();
58
+ const token1 = tokens1?.[addr1Lc];
59
+ const token2 = tokens2?.[addr2Lc];
60
+ const price1 = prices1?.[addr1Lc] || import_sdk.PRICE_DECIMALS;
61
+ const price2 = prices2?.[addr2Lc] || import_sdk.PRICE_DECIMALS;
62
+ const totalPrice1 = import_priceMath.PriceUtils.calcTotalPrice(
63
+ price1,
64
+ t1.balance,
65
+ token1?.decimals
66
+ );
67
+ const totalPrice2 = import_priceMath.PriceUtils.calcTotalPrice(
68
+ price2,
69
+ t2.balance,
70
+ token2?.decimals
71
+ );
72
+ if (totalPrice1 === totalPrice2) {
73
+ return t1.balance === t2.balance ? tokensAbcComparator(token1, token2) : amountAbcComparator(t1.balance, t2.balance);
74
+ }
75
+ return amountAbcComparator(totalPrice1, totalPrice2);
76
+ }
77
+ function tokensAbcComparator(t1, t2) {
78
+ const { symbol: symbol1 = "" } = t1 || {};
79
+ const { symbol: symbol2 = "" } = t2 || {};
80
+ const symbol1LC = symbol1.toLowerCase();
81
+ const symbol2LC = symbol2.toLowerCase();
82
+ if (symbol1LC === symbol2LC) return 0;
83
+ return symbol1LC > symbol2LC ? 1 : -1;
84
+ }
85
+ function amountAbcComparator(t1, t2) {
86
+ return t1 > t2 ? -1 : 1;
87
+ }
88
+ // Annotate the CommonJS export names for ESM import in node:
89
+ 0 && (module.exports = {
90
+ amountAbcComparator,
91
+ assetComparator,
92
+ sortAssets,
93
+ sortBalances,
94
+ tokensAbcComparator
95
+ });
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var types_exports = {};
16
+ module.exports = __toCommonJS(types_exports);
@@ -18,11 +18,10 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var endpoints_exports = {};
20
20
  __export(endpoints_exports, {
21
- GearboxBackendApi: () => GearboxBackendApi,
22
- URLApi: () => URLApi
21
+ GearboxBackendApi: () => GearboxBackendApi
23
22
  });
24
23
  module.exports = __toCommonJS(endpoints_exports);
25
- var import_chains = require("../chain/chains.js");
24
+ var import_sdk = require("../../sdk/index.js");
26
25
  const CHARTS_BACKEND_ADDRESS = "https://charts-server.fly.dev";
27
26
  const STATIC_TOKEN = "https://static.gearbox.finance/tokens/";
28
27
  class GearboxBackendApi {
@@ -31,8 +30,8 @@ class GearboxBackendApi {
31
30
  static getChartsUrl = (url, chainId, options = { params: {} }, priceSource) => {
32
31
  const domain = CHARTS_BACKEND_ADDRESS;
33
32
  const priceSourceArr = priceSource ? [priceSource] : [];
34
- const isMain = (0, import_chains.isSupportedNetwork)(chainId);
35
- const relativePath = URLApi.getRelativeUrl(
33
+ const isMain = (0, import_sdk.isSupportedNetwork)(chainId);
34
+ const relativePath = getRelativeUrl(
36
35
  url,
37
36
  isMain ? {
38
37
  ...options,
@@ -51,21 +50,16 @@ class GearboxBackendApi {
51
50
  const url = `https://dm.gearbox.finance/${network.toLowerCase()}_${root}.json`;
52
51
  return url;
53
52
  };
54
- static apyAllRewards = () => URLApi.getRelativeUrl(
53
+ static apyAllRewards = () => getRelativeUrl(
55
54
  "https://state-cache.gearbox.foundation/apy-server/latest.json"
56
55
  );
57
56
  }
58
- class URLApi {
59
- constructor() {
60
- }
61
- static getRelativeUrl = (url, options) => {
62
- const { params = {} } = options || {};
63
- const paramsString = Object.entries(params).map(([key, value]) => `${key}=${value}`).join("&");
64
- return [url, ...paramsString ? [paramsString] : []].join("?");
65
- };
66
- }
57
+ const getRelativeUrl = (url, options) => {
58
+ const { params = {} } = options || {};
59
+ const paramsString = Object.entries(params).map(([key, value]) => `${key}=${value}`).join("&");
60
+ return [url, ...paramsString ? [paramsString] : []].join("?");
61
+ };
67
62
  // Annotate the CommonJS export names for ESM import in node:
68
63
  0 && (module.exports = {
69
- GearboxBackendApi,
70
- URLApi
64
+ GearboxBackendApi
71
65
  });
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var utils_exports = {};
17
+ module.exports = __toCommonJS(utils_exports);
18
+ __reExport(utils_exports, require("./assetsMath.js"), module.exports);
19
+ __reExport(utils_exports, require("./bigintMath.js"), module.exports);
20
+ __reExport(utils_exports, require("./creditAccount/index.js"), module.exports);
21
+ __reExport(utils_exports, require("./endpoints.js"), module.exports);
22
+ __reExport(utils_exports, require("./priceMath.js"), module.exports);
23
+ // Annotate the CommonJS export names for ESM import in node:
24
+ 0 && (module.exports = {
25
+ ...require("./assetsMath.js"),
26
+ ...require("./bigintMath.js"),
27
+ ...require("./creditAccount/index.js"),
28
+ ...require("./endpoints.js"),
29
+ ...require("./priceMath.js")
30
+ });
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var priceMath_exports = {};
20
+ __export(priceMath_exports, {
21
+ PriceUtils: () => PriceUtils
22
+ });
23
+ module.exports = __toCommonJS(priceMath_exports);
24
+ var import_sdk = require("../../sdk/index.js");
25
+ class PriceUtils {
26
+ /**
27
+ * This class is intentionally non-instantiable.
28
+ */
29
+ constructor() {
30
+ }
31
+ /**
32
+ * Calculates normalized total value for a token amount at a given price.
33
+ *
34
+ * Formula:
35
+ * `(amount * WAD * price) / 10^decimals / PRICE_DECIMALS`
36
+ *
37
+ * @param price Token unit price in `PRICE_DECIMALS` precision.
38
+ * @param amount Token amount in raw token units.
39
+ * @param decimals Token decimals used to normalize `amount` (defaults to `18`).
40
+ * @returns Total value in WAD-normalized units.
41
+ */
42
+ static calcTotalPrice = (price, amount, decimals = 18) => amount * import_sdk.WAD * price / 10n ** BigInt(decimals) / import_sdk.PRICE_DECIMALS;
43
+ /**
44
+ * Converts a normalized monetary value into target token amount by price.
45
+ *
46
+ * Formula:
47
+ * `(totalMoney * 10^targetDecimals * PRICE_DECIMALS) / targetPrice / WAD`
48
+ *
49
+ * Safety behavior:
50
+ * - returns `0n` when `targetPrice <= 0n` to avoid invalid division
51
+ *
52
+ * @param totalMoney Value to convert, expected in WAD-normalized units.
53
+ * @param target Conversion target configuration:
54
+ * - `price`: target token unit price in `PRICE_DECIMALS` precision
55
+ * - `decimals`: target token decimals (defaults to `18`)
56
+ * @returns Target token amount in raw token units.
57
+ */
58
+ static convertByPrice(totalMoney, { price: targetPrice, decimals: targetDecimals = 18 }) {
59
+ if (targetPrice <= 0n) return 0n;
60
+ return totalMoney * 10n ** BigInt(targetDecimals) * import_sdk.PRICE_DECIMALS / targetPrice / import_sdk.WAD;
61
+ }
62
+ }
63
+ // Annotate the CommonJS export names for ESM import in node:
64
+ 0 && (module.exports = {
65
+ PriceUtils
66
+ });
@@ -18,13 +18,9 @@ module.exports = __toCommonJS(utils_exports);
18
18
  __reExport(utils_exports, require("./AddressMap.js"), module.exports);
19
19
  __reExport(utils_exports, require("./AddressSet.js"), module.exports);
20
20
  __reExport(utils_exports, require("./abi-decode.js"), module.exports);
21
- __reExport(utils_exports, require("./assetsMath.js"), module.exports);
22
- __reExport(utils_exports, require("./bigintMath.js"), module.exports);
23
21
  __reExport(utils_exports, require("./bytes32ToString.js"), module.exports);
24
22
  __reExport(utils_exports, require("./childLogger.js"), module.exports);
25
23
  __reExport(utils_exports, require("./createRawTx.js"), module.exports);
26
- __reExport(utils_exports, require("./creditAccount.js"), module.exports);
27
- __reExport(utils_exports, require("./endpoints.js"), module.exports);
28
24
  __reExport(utils_exports, require("./etherscan.js"), module.exports);
29
25
  __reExport(utils_exports, require("./filterDust.js"), module.exports);
30
26
  __reExport(utils_exports, require("./formatter.js"), module.exports);
@@ -32,7 +28,6 @@ __reExport(utils_exports, require("./hex.js"), module.exports);
32
28
  __reExport(utils_exports, require("./isDust.js"), module.exports);
33
29
  __reExport(utils_exports, require("./json.js"), module.exports);
34
30
  __reExport(utils_exports, require("./mappers.js"), module.exports);
35
- __reExport(utils_exports, require("./priceMath.js"), module.exports);
36
31
  __reExport(utils_exports, require("./retry.js"), module.exports);
37
32
  __reExport(utils_exports, require("./toAddress.js"), module.exports);
38
33
  __reExport(utils_exports, require("./type-utils.js"), module.exports);
@@ -42,13 +37,9 @@ __reExport(utils_exports, require("./zod.js"), module.exports);
42
37
  ...require("./AddressMap.js"),
43
38
  ...require("./AddressSet.js"),
44
39
  ...require("./abi-decode.js"),
45
- ...require("./assetsMath.js"),
46
- ...require("./bigintMath.js"),
47
40
  ...require("./bytes32ToString.js"),
48
41
  ...require("./childLogger.js"),
49
42
  ...require("./createRawTx.js"),
50
- ...require("./creditAccount.js"),
51
- ...require("./endpoints.js"),
52
43
  ...require("./etherscan.js"),
53
44
  ...require("./filterDust.js"),
54
45
  ...require("./formatter.js"),
@@ -56,7 +47,6 @@ __reExport(utils_exports, require("./zod.js"), module.exports);
56
47
  ...require("./isDust.js"),
57
48
  ...require("./json.js"),
58
49
  ...require("./mappers.js"),
59
- ...require("./priceMath.js"),
60
50
  ...require("./retry.js"),
61
51
  ...require("./toAddress.js"),
62
52
  ...require("./type-utils.js"),
@@ -0,0 +1 @@
1
+ export * from "./utils/index.js";
@@ -0,0 +1 @@
1
+ {"type": "module","sideEffects":false}
@@ -1,7 +1,22 @@
1
1
  import { BigIntMath } from "./bigintMath.js";
2
- import { CreditAccountDataUtils } from "./creditAccount.js";
2
+ import { sortBalances } from "./creditAccount/sort.js";
3
3
  import { PriceUtils } from "./priceMath.js";
4
4
  class AssetUtils {
5
+ constructor() {
6
+ }
7
+ /**
8
+ * Selects the next candidate token to add to a selected-asset list.
9
+ *
10
+ * Flow:
11
+ * 1) Removes tokens already present in `selectedAssets`
12
+ * 2) Builds balances for the remaining allowed tokens
13
+ * 3) Sorts the balances using `CreditAccountDataUtils.sortBalances`
14
+ * 4) Returns the highest-priority token address, if any
15
+ *
16
+ * Addresses are normalized to lowercase for matching.
17
+ *
18
+ * @returns The next token address to select, or `undefined` if no candidates remain.
19
+ */
5
20
  static nextAsset({
6
21
  allowedTokens,
7
22
  selectedAssets,
@@ -20,7 +35,7 @@ class AssetUtils {
20
35
  const alreadySelected = selectedRecord[allowedToken.toLowerCase()];
21
36
  return !alreadySelected;
22
37
  });
23
- const sorted = CreditAccountDataUtils.sortBalances(
38
+ const sorted = sortBalances(
24
39
  AssetUtils.getBalances(notSelected, balances),
25
40
  prices,
26
41
  tokensList
@@ -28,15 +43,30 @@ class AssetUtils {
28
43
  const [address] = sorted[0] || [];
29
44
  return address;
30
45
  }
46
+ /**
47
+ * Builds a normalized balance record for a specific token subset.
48
+ *
49
+ * Missing balances are defaulted to `0n`.
50
+ *
51
+ * @param allowedTokens Tokens to include in the output record.
52
+ * @param externalBalances Source balances keyed by lowercase address.
53
+ * @returns A record that contains only `allowedTokens`.
54
+ */
31
55
  static getBalances(allowedTokens, externalBalances) {
32
56
  return allowedTokens.reduce((acc, address) => {
33
57
  const addressLc = address.toLowerCase();
34
- return {
35
- ...acc,
36
- [addressLc]: externalBalances[addressLc] || 0n
37
- };
58
+ acc[addressLc] = externalBalances[addressLc] || 0n;
59
+ return acc;
38
60
  }, {});
39
61
  }
62
+ /**
63
+ * Converts an asset array into a token-address keyed record.
64
+ *
65
+ * If duplicate token addresses are present, the last occurrence wins.
66
+ *
67
+ * @param a Source asset list.
68
+ * @returns Record keyed by `asset.token`.
69
+ */
40
70
  static constructAssetRecord(a) {
41
71
  const record = a.reduce((acc, asset) => {
42
72
  acc[asset.token] = asset;
@@ -44,6 +74,18 @@ class AssetUtils {
44
74
  }, {});
45
75
  return record;
46
76
  }
77
+ /**
78
+ * Creates a reusable wrapper function that merges "unwrapped" and "wrapped"
79
+ * token balances into the wrapped token representation.
80
+ *
81
+ * The returned function:
82
+ * - converts non-negative unwrapped balance into wrapped units by price
83
+ * - adds the converted amount to the wrapped token balance
84
+ * - removes the unwrapped token from the result list
85
+ * - leaves input untouched when no unwrapped token is present
86
+ *
87
+ * @returns A function producing `[assets, convertedUnwrapped, originalWrapped]`.
88
+ */
47
89
  static memoWrap = (unwrappedAddress, wrappedAddress, prices, tokensList) => function wrap(assets) {
48
90
  const assetsRecord = AssetUtils.constructAssetRecord(assets);
49
91
  const unwrapped = assetsRecord[unwrappedAddress];
@@ -76,8 +118,16 @@ class AssetUtils {
76
118
  return [Object.values(assetsRecord), 0n, wrappedAmount];
77
119
  };
78
120
  /**
79
- * Sums the the second assets list into the first assets list
80
- * Balances cant be negative; creates new assets.
121
+ * Adds balances from the second asset list into the first list.
122
+ *
123
+ * Behavior:
124
+ * - balances are clamped to non-negative before summation
125
+ * - tokens found only in `b` are created in the output
126
+ * - existing asset metadata is preserved from `a` when possible
127
+ *
128
+ * @param a Base asset list.
129
+ * @param b Asset deltas to add.
130
+ * @returns A merged list containing assets from both inputs.
81
131
  */
82
132
  static sumAssets(a, b) {
83
133
  const aRecord = AssetUtils.constructAssetRecord(a);
@@ -95,8 +145,16 @@ class AssetUtils {
95
145
  return Object.values(resRecord);
96
146
  }
97
147
  /**
98
- * Sums the the second assets list into the first assets list
99
- * Balances cant be negative; doesn't create new assets.
148
+ * Adds balances from the second list to matching assets in the first list.
149
+ *
150
+ * Behavior:
151
+ * - balances are clamped to non-negative before summation
152
+ * - only assets already present in `a` are returned
153
+ * - no new token entries are created
154
+ *
155
+ * @param a Base asset list.
156
+ * @param b Asset deltas keyed by token.
157
+ * @returns Updated version of `a` with adjusted balances.
100
158
  */
101
159
  static addBalances(a, b) {
102
160
  const bRecord = AssetUtils.constructAssetRecord(b);
@@ -108,8 +166,16 @@ class AssetUtils {
108
166
  });
109
167
  }
110
168
  /**
111
- * Subtracts the the second assets list from the first assets list
112
- * Balances cant be negative; doesn't create new assets.
169
+ * Subtracts balances in the second list from matching assets in the first list.
170
+ *
171
+ * Behavior:
172
+ * - both operands are clamped to non-negative before subtraction
173
+ * - output balances are clamped to non-negative after subtraction
174
+ * - only assets already present in `a` are returned
175
+ *
176
+ * @param a Base asset list.
177
+ * @param b Asset amounts to subtract by token.
178
+ * @returns Updated `a` list with non-negative post-subtraction balances.
113
179
  */
114
180
  static subAssets(a, b) {
115
181
  const bRecord = AssetUtils.constructAssetRecord(b);
@@ -0,0 +1,41 @@
1
+ class BigIntMath {
2
+ constructor() {
3
+ }
4
+ /**
5
+ * Returns the absolute (non-negative) value of a bigint.
6
+ *
7
+ * @param x Input value.
8
+ * @returns `x` when `x` is already non-negative, otherwise `-x`.
9
+ */
10
+ static abs = (x) => x < 0n ? -x : x;
11
+ /**
12
+ * Returns the greater of two bigint values.
13
+ *
14
+ * @param a First candidate value.
15
+ * @param b Second candidate value.
16
+ * @returns The larger value between `a` and `b`.
17
+ */
18
+ static max = (a, b) => a > b ? a : b;
19
+ /**
20
+ * Returns the smaller of two bigint values.
21
+ *
22
+ * @param a First candidate value.
23
+ * @param b Second candidate value.
24
+ * @returns The smaller value between `a` and `b`.
25
+ */
26
+ static min = (a, b) => a < b ? a : b;
27
+ /**
28
+ * Returns the negative form of a bigint if it is currently positive.
29
+ *
30
+ * Useful when a value should be represented as an outflow/debit:
31
+ * - positive values become negative
32
+ * - zero and negative values are returned unchanged
33
+ *
34
+ * @param a Input value.
35
+ * @returns A non-positive bigint representation of `a`.
36
+ */
37
+ static neg = (a) => a > 0 ? a * -1n : a;
38
+ }
39
+ export {
40
+ BigIntMath
41
+ };