@gearbox-protocol/sdk 13.0.0-beta.3 → 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 (106) hide show
  1. package/dist/cjs/abi/iPriceFeed.js +84 -0
  2. package/dist/cjs/common-utils/index.js +22 -0
  3. package/dist/cjs/common-utils/package.json +1 -0
  4. package/dist/cjs/{sdk → common-utils}/utils/assetsMath.js +88 -21
  5. package/dist/cjs/common-utils/utils/bigintMath.js +65 -0
  6. package/dist/cjs/common-utils/utils/creditAccount/calcHealthFactor.js +76 -0
  7. package/dist/cjs/common-utils/utils/creditAccount/calcOverallAPY.js +81 -0
  8. package/dist/cjs/{sdk/utils/priceMath.js → common-utils/utils/creditAccount/calcQuotaBorrowRate.js} +19 -12
  9. package/dist/cjs/{sdk/utils/bigintMath.js → common-utils/utils/creditAccount/calcRelativeBaseBorrowRate.js} +11 -10
  10. package/dist/cjs/common-utils/utils/creditAccount/debt.js +64 -0
  11. package/dist/cjs/common-utils/utils/creditAccount/getTimeToLiquidation.js +38 -0
  12. package/dist/cjs/common-utils/utils/creditAccount/index.js +38 -0
  13. package/dist/cjs/common-utils/utils/creditAccount/liquidationPrice.js +47 -0
  14. package/dist/cjs/common-utils/utils/creditAccount/quotaUtils.js +149 -0
  15. package/dist/cjs/common-utils/utils/creditAccount/sort.js +95 -0
  16. package/dist/cjs/common-utils/utils/creditAccount/types.js +16 -0
  17. package/dist/cjs/{sdk → common-utils}/utils/endpoints.js +11 -17
  18. package/dist/cjs/common-utils/utils/index.js +30 -0
  19. package/dist/cjs/common-utils/utils/priceMath.js +66 -0
  20. package/dist/cjs/permissionless/bindings/cross-chain-multisig.js +3 -3
  21. package/dist/cjs/permissionless/bindings/instance-manager.js +2 -2
  22. package/dist/cjs/plugins/adapters/contracts/MellowDepositQueueAdapterContract.js +0 -6
  23. package/dist/cjs/plugins/adapters/contracts/MellowRedeemQueueAdapterContract.js +0 -6
  24. package/dist/cjs/sdk/GearboxSDK.js +0 -2
  25. package/dist/cjs/sdk/base/BaseContract.js +5 -2
  26. package/dist/cjs/sdk/base/ChainContractsRegister.js +2 -10
  27. package/dist/cjs/sdk/base/Construct.js +25 -19
  28. package/dist/cjs/sdk/base/SDKConstruct.js +1 -1
  29. package/dist/cjs/sdk/market/adapters/PlaceholderAdapterContracts.js +16 -0
  30. package/dist/cjs/sdk/market/pricefeeds/updates/PriceUpdatesCache.js +0 -17
  31. package/dist/cjs/sdk/market/pricefeeds/updates/PythUpdater.js +1 -1
  32. package/dist/cjs/sdk/market/pricefeeds/updates/RedstoneUpdater.js +1 -1
  33. package/dist/cjs/sdk/market/pricefeeds/updates/fetchPythPayloads.js +2 -2
  34. package/dist/cjs/sdk/utils/formatter.js +3 -3
  35. package/dist/cjs/sdk/utils/index.js +0 -10
  36. package/dist/esm/abi/iPriceFeed.js +60 -0
  37. package/dist/esm/common-utils/index.js +1 -0
  38. package/dist/esm/common-utils/package.json +1 -0
  39. package/dist/esm/{sdk → common-utils}/utils/assetsMath.js +80 -13
  40. package/dist/esm/common-utils/utils/bigintMath.js +41 -0
  41. package/dist/esm/common-utils/utils/creditAccount/calcHealthFactor.js +55 -0
  42. package/dist/esm/common-utils/utils/creditAccount/calcOverallAPY.js +60 -0
  43. package/dist/esm/common-utils/utils/creditAccount/calcQuotaBorrowRate.js +18 -0
  44. package/dist/esm/common-utils/utils/creditAccount/calcRelativeBaseBorrowRate.js +10 -0
  45. package/dist/esm/common-utils/utils/creditAccount/debt.js +43 -0
  46. package/dist/esm/common-utils/utils/creditAccount/getTimeToLiquidation.js +18 -0
  47. package/dist/esm/common-utils/utils/creditAccount/index.js +9 -0
  48. package/dist/esm/common-utils/utils/creditAccount/liquidationPrice.js +23 -0
  49. package/dist/esm/common-utils/utils/creditAccount/quotaUtils.js +125 -0
  50. package/dist/esm/common-utils/utils/creditAccount/sort.js +67 -0
  51. package/dist/esm/common-utils/utils/creditAccount/types.js +0 -0
  52. package/dist/esm/{sdk → common-utils}/utils/endpoints.js +9 -14
  53. package/dist/esm/common-utils/utils/index.js +5 -0
  54. package/dist/esm/common-utils/utils/priceMath.js +42 -0
  55. package/dist/esm/permissionless/bindings/cross-chain-multisig.js +3 -3
  56. package/dist/esm/permissionless/bindings/instance-manager.js +2 -2
  57. package/dist/esm/plugins/adapters/contracts/MellowDepositQueueAdapterContract.js +0 -6
  58. package/dist/esm/plugins/adapters/contracts/MellowRedeemQueueAdapterContract.js +0 -6
  59. package/dist/esm/sdk/GearboxSDK.js +0 -2
  60. package/dist/esm/sdk/base/BaseContract.js +5 -2
  61. package/dist/esm/sdk/base/ChainContractsRegister.js +2 -10
  62. package/dist/esm/sdk/base/Construct.js +25 -19
  63. package/dist/esm/sdk/base/SDKConstruct.js +1 -1
  64. package/dist/esm/sdk/market/adapters/PlaceholderAdapterContracts.js +16 -0
  65. package/dist/esm/sdk/market/pricefeeds/updates/PriceUpdatesCache.js +0 -17
  66. package/dist/esm/sdk/market/pricefeeds/updates/PythUpdater.js +1 -1
  67. package/dist/esm/sdk/market/pricefeeds/updates/RedstoneUpdater.js +1 -1
  68. package/dist/esm/sdk/market/pricefeeds/updates/fetchPythPayloads.js +2 -2
  69. package/dist/esm/sdk/utils/formatter.js +1 -1
  70. package/dist/esm/sdk/utils/index.js +0 -5
  71. package/dist/types/abi/iPriceFeed.d.ts +87 -0
  72. package/dist/types/common-utils/index.d.ts +1 -0
  73. package/dist/types/common-utils/utils/assetsMath.d.ts +114 -0
  74. package/dist/types/common-utils/utils/bigintMath.d.ts +43 -0
  75. package/dist/types/common-utils/utils/creditAccount/calcHealthFactor.d.ts +25 -0
  76. package/dist/types/common-utils/utils/creditAccount/calcOverallAPY.d.ts +37 -0
  77. package/dist/types/common-utils/utils/creditAccount/calcQuotaBorrowRate.d.ts +18 -0
  78. package/dist/types/common-utils/utils/creditAccount/calcRelativeBaseBorrowRate.d.ts +15 -0
  79. package/dist/types/common-utils/utils/creditAccount/debt.d.ts +35 -0
  80. package/dist/types/common-utils/utils/creditAccount/getTimeToLiquidation.d.ts +16 -0
  81. package/dist/types/common-utils/utils/creditAccount/index.d.ts +9 -0
  82. package/dist/types/common-utils/utils/creditAccount/liquidationPrice.d.ts +25 -0
  83. package/dist/types/common-utils/utils/creditAccount/quotaUtils.d.ts +81 -0
  84. package/dist/types/common-utils/utils/creditAccount/sort.d.ts +55 -0
  85. package/dist/types/common-utils/utils/creditAccount/types.d.ts +18 -0
  86. package/dist/types/{sdk → common-utils}/utils/endpoints.d.ts +13 -5
  87. package/dist/types/common-utils/utils/index.d.ts +5 -0
  88. package/dist/types/common-utils/utils/priceMath.d.ts +47 -0
  89. package/dist/types/permissionless/bindings/cross-chain-multisig.d.ts +3 -3
  90. package/dist/types/permissionless/bindings/instance-manager.d.ts +3 -3
  91. package/dist/types/plugins/adapters/contracts/MellowDepositQueueAdapterContract.d.ts +1 -4
  92. package/dist/types/plugins/adapters/contracts/MellowRedeemQueueAdapterContract.d.ts +1 -4
  93. package/dist/types/sdk/base/ChainContractsRegister.d.ts +0 -2
  94. package/dist/types/sdk/base/Construct.d.ts +7 -10
  95. package/dist/types/sdk/market/adapters/PlaceholderAdapterContracts.d.ts +2 -1
  96. package/dist/types/sdk/market/pricefeeds/updates/PriceUpdatesCache.d.ts +1 -8
  97. package/dist/types/sdk/utils/index.d.ts +0 -5
  98. package/package.json +11 -2
  99. package/dist/cjs/sdk/utils/creditAccount.js +0 -409
  100. package/dist/esm/sdk/utils/bigintMath.js +0 -9
  101. package/dist/esm/sdk/utils/creditAccount.js +0 -396
  102. package/dist/esm/sdk/utils/priceMath.js +0 -11
  103. package/dist/types/sdk/utils/assetsMath.d.ts +0 -42
  104. package/dist/types/sdk/utils/bigintMath.d.ts +0 -6
  105. package/dist/types/sdk/utils/creditAccount.d.ts +0 -128
  106. package/dist/types/sdk/utils/priceMath.d.ts +0 -9
@@ -0,0 +1,5 @@
1
+ export * from "./assetsMath.js";
2
+ export * from "./bigintMath.js";
3
+ export * from "./creditAccount/index.js";
4
+ export * from "./endpoints.js";
5
+ export * from "./priceMath.js";
@@ -0,0 +1,47 @@
1
+ interface Target {
2
+ price: bigint;
3
+ decimals: number | undefined;
4
+ }
5
+ /**
6
+ * Static utility namespace for converting between token amounts and
7
+ * normalized value using oracle-like prices.
8
+ *
9
+ * All helpers rely on shared fixed-point constants (`WAD` and
10
+ * `PRICE_DECIMALS`) to keep arithmetic consistent across assets
11
+ * with different token decimal precisions.
12
+ */
13
+ export declare class PriceUtils {
14
+ /**
15
+ * This class is intentionally non-instantiable.
16
+ */
17
+ private constructor();
18
+ /**
19
+ * Calculates normalized total value for a token amount at a given price.
20
+ *
21
+ * Formula:
22
+ * `(amount * WAD * price) / 10^decimals / PRICE_DECIMALS`
23
+ *
24
+ * @param price Token unit price in `PRICE_DECIMALS` precision.
25
+ * @param amount Token amount in raw token units.
26
+ * @param decimals Token decimals used to normalize `amount` (defaults to `18`).
27
+ * @returns Total value in WAD-normalized units.
28
+ */
29
+ static calcTotalPrice: (price: bigint, amount: bigint, decimals?: number | undefined) => bigint;
30
+ /**
31
+ * Converts a normalized monetary value into target token amount by price.
32
+ *
33
+ * Formula:
34
+ * `(totalMoney * 10^targetDecimals * PRICE_DECIMALS) / targetPrice / WAD`
35
+ *
36
+ * Safety behavior:
37
+ * - returns `0n` when `targetPrice <= 0n` to avoid invalid division
38
+ *
39
+ * @param totalMoney Value to convert, expected in WAD-normalized units.
40
+ * @param target Conversion target configuration:
41
+ * - `price`: target token unit price in `PRICE_DECIMALS` precision
42
+ * - `decimals`: target token decimals (defaults to `18`)
43
+ * @returns Target token amount in raw token units.
44
+ */
45
+ static convertByPrice(totalMoney: bigint, { price: targetPrice, decimals: targetDecimals }: Target): bigint;
46
+ }
47
+ export {};
@@ -1,6 +1,6 @@
1
- import { type Address, type Chain, type DecodeFunctionDataReturnType, type Hex, type PublicClient, type Transport, type WalletClient } from "viem";
1
+ import { type Address, type DecodeFunctionDataReturnType, type Hex, type WalletClient } from "viem";
2
2
  import type { RawTx } from "../../sdk/index.js";
3
- import { BaseContract, type ParsedCallArgs } from "../../sdk/index.js";
3
+ import { BaseContract, type ChainContractsRegister, type ParsedCallArgs } from "../../sdk/index.js";
4
4
  import type { Batch, RecoveryMessage } from "../core/proposal.js";
5
5
  declare const abi: readonly [{
6
6
  readonly type: "constructor";
@@ -726,7 +726,7 @@ export interface Proposal {
726
726
  }
727
727
  export declare class CrossChainMultisigContract extends BaseContract<typeof abi> {
728
728
  #private;
729
- constructor(addr: Address, client: PublicClient<Transport, Chain>);
729
+ constructor(addr: Address, register: ChainContractsRegister);
730
730
  getExecutedBatches(fromBlock: bigint, toBlock: bigint): Promise<Omit<Batch, "timestamp">[]>;
731
731
  getCurrentBatches(): Promise<Batch[]>;
732
732
  getBatchData(args: {
@@ -1,6 +1,6 @@
1
- import { type Address, type Chain, type DecodeFunctionDataReturnType, type Hex, type PublicClient, type Transport } from "viem";
1
+ import { type Address, type DecodeFunctionDataReturnType, type Hex } from "viem";
2
2
  import type { RawTx } from "../../sdk/index.js";
3
- import { BaseContract, type ParsedCall, type ParsedCallArgs } from "../../sdk/index.js";
3
+ import { BaseContract, type ChainContractsRegister, type ParsedCall, type ParsedCallArgs } from "../../sdk/index.js";
4
4
  declare const abi: readonly [{
5
5
  readonly type: "constructor";
6
6
  readonly inputs: readonly [{
@@ -329,7 +329,7 @@ declare const abi: readonly [{
329
329
  }];
330
330
  export declare class InstanceManagerContract extends BaseContract<typeof abi> {
331
331
  #private;
332
- constructor(addr: Address, client: PublicClient<Transport, Chain>);
332
+ constructor(addr: Address, register: ChainContractsRegister);
333
333
  mustParseFunctionData(calldata: Hex): ParsedCall;
334
334
  protected parseFunctionParams(params: DecodeFunctionDataReturnType<typeof abi>): ParsedCallArgs;
335
335
  isActivated(): Promise<boolean>;
@@ -1,6 +1,5 @@
1
1
  import { type Address } from "viem";
2
- import { type ConstructOptions, type ParsedCallV2 } from "../../../sdk/index.js";
3
- import type { LegacyAdapterOperation, Transfers } from "../legacyAdapterOperations.js";
2
+ import { type ConstructOptions } from "../../../sdk/index.js";
4
3
  import type { ConcreteAdapterContractOptions } from "./AbstractAdapter.js";
5
4
  import { AbstractAdapterContract } from "./AbstractAdapter.js";
6
5
  declare const abi: readonly [];
@@ -23,7 +22,5 @@ export declare class MellowDepositQueueAdapterContract extends AbstractAdapterCo
23
22
  version: number;
24
23
  contractType?: string;
25
24
  };
26
- /** Legacy adapter not present in integrations-v3. */
27
- protected classifyLegacyOperation(_parsed: ParsedCallV2, _transfers: Transfers): LegacyAdapterOperation;
28
25
  }
29
26
  export {};
@@ -1,6 +1,5 @@
1
1
  import { type Address } from "viem";
2
- import { type ConstructOptions, type ParsedCallV2 } from "../../../sdk/index.js";
3
- import type { LegacyAdapterOperation, Transfers } from "../legacyAdapterOperations.js";
2
+ import { type ConstructOptions } from "../../../sdk/index.js";
4
3
  import type { ConcreteAdapterContractOptions } from "./AbstractAdapter.js";
5
4
  import { AbstractAdapterContract } from "./AbstractAdapter.js";
6
5
  declare const abi: readonly [];
@@ -21,7 +20,5 @@ export declare class MellowRedeemQueueAdapterContract extends AbstractAdapterCon
21
20
  version: number;
22
21
  contractType?: string;
23
22
  };
24
- /** Legacy adapter not present in integrations-v3. */
25
- protected classifyLegacyOperation(_parsed: ParsedCallV2, _transfers: Transfers): LegacyAdapterOperation;
26
23
  }
27
24
  export {};
@@ -6,8 +6,6 @@ import { TokensMeta } from "./TokensMeta.js";
6
6
  import type { ParsedCall, ParsedCallV2 } from "./types.js";
7
7
  export type ContractOrInterface<T> = T extends Abi | readonly unknown[] ? BaseContract<T> : T;
8
8
  export declare class ChainContractsRegister {
9
- #private;
10
- static for(client: PublicClient<Transport, Chain>, logger?: ILogger): ChainContractsRegister;
11
9
  private readonly contracts;
12
10
  private readonly labels;
13
11
  readonly client: PublicClient<Transport, Chain>;
@@ -3,7 +3,7 @@ import type { NetworkType } from "../chain/index.js";
3
3
  import type { ILogger } from "../types/index.js";
4
4
  import { ChainContractsRegister } from "./ChainContractsRegister.js";
5
5
  import type { TokensMeta } from "./TokensMeta.js";
6
- export type ConstructOptions = {
6
+ export type ConstructOptions = ChainContractsRegister | {
7
7
  client: PublicClient<Transport, Chain>;
8
8
  logger?: ILogger;
9
9
  } | {
@@ -14,8 +14,13 @@ export declare class Construct {
14
14
  #private;
15
15
  readonly logger?: ILogger;
16
16
  readonly client: PublicClient<Transport, Chain>;
17
- readonly register: ChainContractsRegister;
18
17
  constructor(options: ConstructOptions);
18
+ /**
19
+ * Throws if register was not provided in constructor options
20
+ * Ephemeral contracts that do not need to access other contracts may not need it
21
+ */
22
+ get register(): ChainContractsRegister;
23
+ protected safeGetRegister(): ChainContractsRegister | undefined;
19
24
  get chain(): Chain;
20
25
  get chainId(): number;
21
26
  get networkType(): NetworkType;
@@ -24,15 +29,7 @@ export declare class Construct {
24
29
  */
25
30
  get dirty(): boolean;
26
31
  protected set dirty(value: boolean);
27
- /**
28
- * Syntax sugar for rgister.tokensMeta
29
- */
30
32
  protected get tokensMeta(): TokensMeta;
31
- /**
32
- * Syntax suggar for getting contract labels
33
- * @param address
34
- * @returns
35
- */
36
33
  protected labelAddress(address: Address, omitAddress?: boolean): string;
37
34
  /**
38
35
  * Returns list of addresses that should be watched for events to sync state
@@ -1,4 +1,4 @@
1
- import type { Address } from "viem";
1
+ import { type Address } from "viem";
2
2
  import type { ConstructOptions } from "../../base/index.js";
3
3
  import { PlaceholderContract } from "../../base/index.js";
4
4
  import type { RelaxedBaseParams } from "../../index.js";
@@ -10,4 +10,5 @@ export declare class PlaceholderAdapterContract extends PlaceholderContract impl
10
10
  #private;
11
11
  constructor(options: ConstructOptions, args: PlaceholderAdapterContractOptions);
12
12
  get targetContract(): Address;
13
+ get creditManager(): Address;
13
14
  }
@@ -11,14 +11,7 @@ export interface PriceUpdatesCacheOptions {
11
11
  }
12
12
  export declare class PriceUpdatesCache {
13
13
  #private;
14
- /**
15
- * Price update caches can be shared across networks
16
- * @param id - unique key to identify the cache
17
- * @param opts
18
- * @returns
19
- */
20
- static get(id: string, opts: PriceUpdatesCacheOptions): PriceUpdatesCache;
21
- private constructor();
14
+ constructor(opts: PriceUpdatesCacheOptions);
22
15
  get(...path: Array<number | string>): Omit<TimestampedCalldata, "cached"> | undefined;
23
16
  set(value: Omit<TimestampedCalldata, "cached">, ...path: Array<number | string>): void;
24
17
  }
@@ -1,13 +1,9 @@
1
1
  export * from "./AddressMap.js";
2
2
  export * from "./AddressSet.js";
3
3
  export * from "./abi-decode.js";
4
- export * from "./assetsMath.js";
5
- export * from "./bigintMath.js";
6
4
  export * from "./bytes32ToString.js";
7
5
  export * from "./childLogger.js";
8
6
  export * from "./createRawTx.js";
9
- export * from "./creditAccount.js";
10
- export * from "./endpoints.js";
11
7
  export * from "./etherscan.js";
12
8
  export * from "./filterDust.js";
13
9
  export * from "./formatter.js";
@@ -15,7 +11,6 @@ export * from "./hex.js";
15
11
  export * from "./isDust.js";
16
12
  export * from "./json.js";
17
13
  export * from "./mappers.js";
18
- export * from "./priceMath.js";
19
14
  export * from "./retry.js";
20
15
  export * from "./toAddress.js";
21
16
  export * from "./type-utils.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gearbox-protocol/sdk",
3
- "version": "13.0.0-beta.3",
3
+ "version": "13.0.0-beta.5",
4
4
  "description": "Gearbox SDK",
5
5
  "license": "MIT",
6
6
  "main": "./dist/cjs/sdk/index.js",
@@ -39,6 +39,11 @@
39
39
  "types": "./dist/types/permissionless/index.d.ts",
40
40
  "import": "./dist/esm/permissionless/index.js",
41
41
  "default": "./dist/cjs/permissionless/index.js"
42
+ },
43
+ "./common-utils": {
44
+ "types": "./dist/types/common-utils/index.d.ts",
45
+ "import": "./dist/esm/common-utils/index.js",
46
+ "default": "./dist/cjs/common-utils/index.js"
42
47
  }
43
48
  },
44
49
  "files": [
@@ -49,7 +54,11 @@
49
54
  "build": "tsup",
50
55
  "dev": "tsup --watch",
51
56
  "example": "tsx --env-file .env scripts/example.ts | pino-pretty",
52
- "test": "vitest",
57
+ "test:watch": "vitest --project unit",
58
+ "test:unit": "vitest run --project unit",
59
+ "test:e2e": "vitest run --project e2e",
60
+ "test:all": "vitest run",
61
+ "generate:e2e": "NODE_OPTIONS='--max-old-space-size=8192' tsx --env-file .env scripts/generate-e2e-fixtures.ts",
53
62
  "prepare": "husky",
54
63
  "check": "biome check --write",
55
64
  "check:ci": "biome check --diagnostic-level=error",
@@ -1,409 +0,0 @@
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 creditAccount_exports = {};
20
- __export(creditAccount_exports, {
21
- CreditAccountDataUtils: () => CreditAccountDataUtils
22
- });
23
- module.exports = __toCommonJS(creditAccount_exports);
24
- var import__ = require("../index.js");
25
- const MAX_UINT16 = 65535;
26
- class CreditAccountDataUtils {
27
- constructor() {
28
- }
29
- static sortBalances(balances, prices, tokens) {
30
- return Object.entries(balances).sort(
31
- ([addr1, amount1], [addr2, amount2]) => {
32
- return CreditAccountDataUtils.assetComparator(
33
- {
34
- token: addr1,
35
- balance: amount1
36
- },
37
- {
38
- token: addr2,
39
- balance: amount2
40
- },
41
- prices,
42
- prices,
43
- tokens,
44
- tokens
45
- );
46
- }
47
- );
48
- }
49
- static sortAssets(balances, prices, tokens) {
50
- return [...balances].sort(
51
- (t1, t2) => CreditAccountDataUtils.assetComparator(
52
- t1,
53
- t2,
54
- prices,
55
- prices,
56
- tokens,
57
- tokens
58
- )
59
- );
60
- }
61
- static assetComparator(t1, t2, prices1, prices2, tokens1, tokens2) {
62
- const addr1Lc = t1.token.toLowerCase();
63
- const addr2Lc = t2.token.toLowerCase();
64
- const token1 = tokens1?.[addr1Lc];
65
- const token2 = tokens2?.[addr2Lc];
66
- const price1 = prices1?.[addr1Lc] || import__.PRICE_DECIMALS;
67
- const price2 = prices2?.[addr2Lc] || import__.PRICE_DECIMALS;
68
- const totalPrice1 = import__.PriceUtils.calcTotalPrice(
69
- price1,
70
- t1.balance,
71
- token1?.decimals
72
- );
73
- const totalPrice2 = import__.PriceUtils.calcTotalPrice(
74
- price2,
75
- t2.balance,
76
- token2?.decimals
77
- );
78
- if (totalPrice1 === totalPrice2) {
79
- return t1.balance === t2.balance ? CreditAccountDataUtils.tokensAbcComparator(token1, token2) : CreditAccountDataUtils.amountAbcComparator(t1.balance, t2.balance);
80
- }
81
- return CreditAccountDataUtils.amountAbcComparator(totalPrice1, totalPrice2);
82
- }
83
- static tokensAbcComparator(t1, t2) {
84
- const { symbol: symbol1 = "" } = t1 || {};
85
- const { symbol: symbol2 = "" } = t2 || {};
86
- const symbol1LC = symbol1.toLowerCase();
87
- const symbol2LC = symbol2.toLowerCase();
88
- if (symbol1LC === symbol2LC) return 0;
89
- return symbol1LC > symbol2LC ? 1 : -1;
90
- }
91
- static amountAbcComparator(t1, t2) {
92
- return t1 > t2 ? -1 : 1;
93
- }
94
- static calcMaxDebtIncrease(healthFactor, debt, underlyingLT, minHf = Number(import__.PERCENTAGE_FACTOR)) {
95
- const result = debt * BigInt(healthFactor - minHf) / BigInt(minHf - underlyingLT);
96
- return import__.BigIntMath.max(0n, result);
97
- }
98
- static calcMaxLendingDebt({
99
- assets,
100
- liquidationThresholds,
101
- underlyingToken,
102
- prices,
103
- tokensList,
104
- targetHF = import__.PERCENTAGE_FACTOR
105
- }) {
106
- const assetsLTMoney = assets.reduce(
107
- (acc, { token: tokenAddress, balance: amount }) => {
108
- const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
109
- const lt = liquidationThresholds[tokenAddress] || 0n;
110
- const price = prices[tokenAddress] || 0n;
111
- const tokenMoney = import__.PriceUtils.calcTotalPrice(
112
- price,
113
- amount,
114
- tokenDecimals
115
- );
116
- const tokenLtMoney = tokenMoney * lt;
117
- return acc + tokenLtMoney;
118
- },
119
- 0n
120
- );
121
- const underlyingPrice = prices[underlyingToken] || 0n;
122
- const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
123
- const max = underlyingPrice > 0 ? assetsLTMoney * 10n ** BigInt(underlyingDecimals) / underlyingPrice / targetHF / 10n ** BigInt(import__.WAD_DECIMALS_POW - import__.PRICE_DECIMALS_POW) : 0n;
124
- return max;
125
- }
126
- // [
127
- // Sum(amount_i * price_i * apy_i - quota_i * quotaPrice * quotaRate_i * (1 + feeInterest)) -
128
- // debt * debtPrice * baseRateWithFee
129
- // ] / (totalValue - debt) * debtPrice
130
- static calcOverallAPY({
131
- caAssets,
132
- lpAPY,
133
- prices,
134
- quotas,
135
- quotaRates,
136
- feeInterest,
137
- totalValue,
138
- debt,
139
- baseRateWithFee,
140
- underlyingToken,
141
- tokensList
142
- }) {
143
- if (!lpAPY || !totalValue || totalValue <= 0n || !debt || totalValue <= debt)
144
- return void 0;
145
- const underlyingTokenDecimals = tokensList[underlyingToken]?.decimals || 18;
146
- const underlyingPrice = prices[underlyingToken];
147
- const assetAPYMoney = caAssets.reduce(
148
- (acc, { token: tokenAddress, balance: amount }) => {
149
- const apy = lpAPY[tokenAddress] || 0;
150
- const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
151
- const price = prices[tokenAddress] || 0n;
152
- const money = import__.PriceUtils.calcTotalPrice(price, amount, tokenDecimals);
153
- const apyMoney = money * BigInt(apy);
154
- const { rate: quotaAPY = 0n, isActive = false } = quotaRates?.[tokenAddress] || {};
155
- const { balance: quotaBalance = 0n } = quotas[tokenAddress] || {};
156
- const quotaAmount = isActive ? quotaBalance : 0n;
157
- const quotaMoney = import__.PriceUtils.calcTotalPrice(
158
- underlyingPrice || 0n,
159
- quotaAmount,
160
- underlyingTokenDecimals
161
- );
162
- const quotaRate = quotaAPY * (BigInt(feeInterest) + import__.PERCENTAGE_FACTOR) / import__.PERCENTAGE_FACTOR;
163
- const quotaAPYMoney = quotaMoney * quotaRate;
164
- return acc + apyMoney - quotaAPYMoney;
165
- },
166
- 0n
167
- );
168
- const debtMoney = import__.PriceUtils.calcTotalPrice(
169
- underlyingPrice || 0n,
170
- debt,
171
- underlyingTokenDecimals
172
- );
173
- const debtAPYMoney = debtMoney * BigInt(baseRateWithFee);
174
- const yourAssetsMoney = import__.PriceUtils.calcTotalPrice(
175
- underlyingPrice || import__.PRICE_DECIMALS,
176
- totalValue - debt,
177
- underlyingTokenDecimals
178
- );
179
- const apyInPercent = (assetAPYMoney - debtAPYMoney) / yourAssetsMoney;
180
- return apyInPercent;
181
- }
182
- static calcHealthFactor({
183
- assets,
184
- quotas,
185
- quotasInfo,
186
- liquidationThresholds,
187
- underlyingToken,
188
- debt,
189
- prices,
190
- tokensList
191
- }) {
192
- if (debt === 0n) return MAX_UINT16;
193
- const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
194
- const underlyingPrice = prices[underlyingToken] || 0n;
195
- const assetMoney = assets.reduce(
196
- (acc, { token: tokenAddress, balance: amount }) => {
197
- const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
198
- const lt = liquidationThresholds[tokenAddress] || 0n;
199
- const price = prices[tokenAddress] || 0n;
200
- const tokenMoney = import__.PriceUtils.calcTotalPrice(
201
- price,
202
- amount,
203
- tokenDecimals
204
- );
205
- const tokenLtMoney = tokenMoney * lt / import__.PERCENTAGE_FACTOR;
206
- const { isActive = false } = quotasInfo?.[tokenAddress] || {};
207
- const quota = quotas[tokenAddress];
208
- const quotaBalance = isActive ? quota?.balance || 0n : 0n;
209
- const quotaMoney = import__.PriceUtils.calcTotalPrice(
210
- underlyingPrice,
211
- quotaBalance,
212
- underlyingDecimals
213
- );
214
- const money = quota ? import__.BigIntMath.min(quotaMoney, tokenLtMoney) : tokenLtMoney;
215
- return acc + money;
216
- },
217
- 0n
218
- );
219
- const borrowedMoney = import__.PriceUtils.calcTotalPrice(
220
- underlyingPrice || import__.PRICE_DECIMALS,
221
- debt,
222
- underlyingDecimals
223
- );
224
- const hfInPercent = borrowedMoney > 0n ? assetMoney * import__.PERCENTAGE_FACTOR / borrowedMoney : 0n;
225
- return Number(hfInPercent);
226
- }
227
- static roundUpQuota(quotaChange) {
228
- return quotaChange !== import__.MIN_INT96 ? quotaChange / import__.PERCENTAGE_FACTOR * import__.PERCENTAGE_FACTOR : quotaChange;
229
- }
230
- static calcRecommendedQuota({
231
- amount,
232
- debt,
233
- lt,
234
- quotaReserve
235
- }) {
236
- const recommendedBaseQuota = import__.BigIntMath.min(
237
- debt,
238
- amount * lt / import__.PERCENTAGE_FACTOR
239
- );
240
- const recommendedQuota = recommendedBaseQuota * (import__.PERCENTAGE_FACTOR + quotaReserve) / import__.PERCENTAGE_FACTOR;
241
- return CreditAccountDataUtils.roundUpQuota(recommendedQuota);
242
- }
243
- static calcDefaultQuota({ amount, lt, quotaReserve }) {
244
- const recommendedBaseQuota = amount * lt / import__.PERCENTAGE_FACTOR;
245
- const recommendedQuota = recommendedBaseQuota * (import__.PERCENTAGE_FACTOR + quotaReserve) / import__.PERCENTAGE_FACTOR;
246
- return CreditAccountDataUtils.roundUpQuota(recommendedQuota);
247
- }
248
- static calcQuotaUpdate(props) {
249
- const { quotas, initialQuotas, maxDebt, allowedToSpend, allowedToObtain } = props;
250
- const quotaDecrease = Object.keys(allowedToSpend).reduce((acc, token) => {
251
- const ch = CreditAccountDataUtils.getSingleQuotaChange(
252
- token,
253
- 0n,
254
- props
255
- );
256
- if (ch && ch.balance < 0) acc[ch.token] = ch;
257
- return acc;
258
- }, {});
259
- const quotaCap = CreditAccountDataUtils.roundUpQuota(maxDebt * 2n);
260
- const quotaBought = Object.values(initialQuotas).reduce(
261
- (sum, q) => sum + CreditAccountDataUtils.roundUpQuota(q?.quota || 0n),
262
- 0n
263
- );
264
- const quotaReduced = Object.values(quotaDecrease).reduce((sum, q) => {
265
- const quotaBalance = q.balance || 0n;
266
- const safeBalance = quotaBalance === import__.MIN_INT96 ? import__.BigIntMath.neg(
267
- CreditAccountDataUtils.roundUpQuota(
268
- initialQuotas[q.token]?.quota || 0n
269
- )
270
- ) : quotaBalance;
271
- return sum + safeBalance;
272
- }, 0n);
273
- const maxQuotaIncrease = CreditAccountDataUtils.roundUpQuota(
274
- import__.BigIntMath.max(quotaCap - (quotaBought + quotaReduced), 0n)
275
- );
276
- const quotaIncrease = Object.keys(allowedToObtain).reduce((acc, token) => {
277
- const ch = CreditAccountDataUtils.getSingleQuotaChange(
278
- token,
279
- maxQuotaIncrease,
280
- props
281
- );
282
- if (ch && ch.balance > 0) acc[ch.token] = ch;
283
- return acc;
284
- }, {});
285
- const quotaChange = {
286
- ...quotaDecrease,
287
- ...quotaIncrease
288
- };
289
- const desiredQuota = Object.values(quotas).reduce(
290
- (acc, cmQuota) => {
291
- const { token, isActive } = cmQuota;
292
- const { quota: initialQuota = 0n } = initialQuotas[token] || {};
293
- if (!isActive) {
294
- acc[token] = {
295
- balance: initialQuota,
296
- token
297
- };
298
- } else {
299
- const change = quotaChange[token]?.balance || 0n;
300
- const quotaAfter = change === import__.MIN_INT96 ? 0n : initialQuota + change;
301
- acc[token] = {
302
- balance: quotaAfter,
303
- token
304
- };
305
- }
306
- return acc;
307
- },
308
- {}
309
- );
310
- return {
311
- desiredQuota,
312
- quotaDecrease: Object.values(quotaDecrease),
313
- quotaIncrease: Object.values(quotaIncrease)
314
- };
315
- }
316
- static getSingleQuotaChange(token, unsafeMaxQuotaIncrease, props) {
317
- const { isActive = false } = props.quotas[token] || {};
318
- const { quota: unsafeInitialQuota = 0n } = props.initialQuotas[token] || {};
319
- if (!isActive) {
320
- return void 0;
321
- }
322
- const assetAfter = props.assetsAfterUpdate[token];
323
- const { amountInTarget = 0n } = assetAfter || {};
324
- const lt = props.liquidationThresholds[token] || 0n;
325
- const maxQuotaIncrease = CreditAccountDataUtils.roundUpQuota(
326
- unsafeMaxQuotaIncrease
327
- );
328
- const initialQuota = CreditAccountDataUtils.roundUpQuota(unsafeInitialQuota);
329
- const defaultQuota = props.calcModification?.type === "recommendedQuota" && props.calcModification.debt > 0 ? CreditAccountDataUtils.calcRecommendedQuota({
330
- lt,
331
- quotaReserve: props.quotaReserve,
332
- amount: amountInTarget,
333
- debt: props.calcModification.debt
334
- }) : CreditAccountDataUtils.calcDefaultQuota({
335
- lt,
336
- quotaReserve: props.quotaReserve,
337
- amount: amountInTarget
338
- });
339
- const unsafeQuotaChange = CreditAccountDataUtils.roundUpQuota(
340
- defaultQuota - initialQuota
341
- );
342
- const quotaChange = unsafeQuotaChange > 0 ? import__.BigIntMath.min(maxQuotaIncrease, unsafeQuotaChange) : unsafeQuotaChange < 0 && import__.BigIntMath.abs(unsafeQuotaChange) >= initialQuota ? import__.MIN_INT96 : unsafeQuotaChange;
343
- const correctIncrease = assetAfter && props.allowedToObtain[token] && quotaChange > 0;
344
- const correctDecrease = assetAfter && props.allowedToSpend[token] && quotaChange < 0;
345
- if (correctIncrease || correctDecrease) {
346
- return {
347
- balance: quotaChange,
348
- token
349
- };
350
- }
351
- return void 0;
352
- }
353
- static calcQuotaBorrowRate({ quotas, quotaRates }) {
354
- const totalRateBalance = Object.values(quotas).reduce(
355
- (acc, { token, balance }) => {
356
- const { rate = 0, isActive = false } = quotaRates?.[token] || {};
357
- const quotaBalance = isActive ? balance : 0n;
358
- const rateBalance = quotaBalance * BigInt(rate);
359
- return acc + rateBalance;
360
- },
361
- 0n
362
- );
363
- return totalRateBalance;
364
- }
365
- static calcRelativeBaseBorrowRate({
366
- debt,
367
- baseRateWithFee,
368
- assetAmountInUnderlying
369
- }) {
370
- return debt * BigInt(baseRateWithFee) * assetAmountInUnderlying;
371
- }
372
- static liquidationPrice({
373
- liquidationThresholds,
374
- debt,
375
- underlyingToken,
376
- targetToken,
377
- assets,
378
- tokensList
379
- }) {
380
- const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
381
- const { balance: underlyingBalance = 0n } = assets[underlyingToken] || {};
382
- const ltUnderlying = liquidationThresholds[underlyingToken] || 0n;
383
- const effectiveDebt = (debt - underlyingBalance * ltUnderlying / import__.PERCENTAGE_FACTOR) * import__.WAD / 10n ** BigInt(underlyingDecimals);
384
- const targetDecimals = tokensList[targetToken]?.decimals || 18;
385
- const { balance: targetBalance = 0n } = assets[targetToken] || {};
386
- const effectiveTargetBalance = targetBalance * import__.WAD / 10n ** BigInt(targetDecimals);
387
- const lpLT = liquidationThresholds[targetToken] || 0n;
388
- if (targetBalance <= 0n || lpLT <= 0n) return 0n;
389
- return effectiveDebt * import__.PRICE_DECIMALS * import__.PERCENTAGE_FACTOR / (effectiveTargetBalance * lpLT);
390
- }
391
- /**
392
- * Calculates the time remaining until liquidation for a credit account.
393
- * @returns The time remaining until liquidation in milliseconds.
394
- */
395
- static getTimeToLiquidation({
396
- healthFactor,
397
- totalBorrowRate_debt
398
- }) {
399
- if (healthFactor <= import__.PERCENTAGE_FACTOR || totalBorrowRate_debt === 0n)
400
- return null;
401
- const HF_1 = BigInt(healthFactor) - import__.PERCENTAGE_FACTOR;
402
- const brPerYear = BigInt(import__.SECONDS_PER_YEAR) * import__.PERCENTAGE_FACTOR * import__.PERCENTAGE_DECIMALS / totalBorrowRate_debt;
403
- return HF_1 * brPerYear * 1000n / import__.PERCENTAGE_FACTOR;
404
- }
405
- }
406
- // Annotate the CommonJS export names for ESM import in node:
407
- 0 && (module.exports = {
408
- CreditAccountDataUtils
409
- });
@@ -1,9 +0,0 @@
1
- class BigIntMath {
2
- static abs = (x) => x < 0n ? -x : x;
3
- static max = (a, b) => a > b ? a : b;
4
- static min = (a, b) => a < b ? a : b;
5
- static neg = (a) => a > 0 ? a * -1n : a;
6
- }
7
- export {
8
- BigIntMath
9
- };