@gearbox-protocol/sdk 17.10.0 → 17.10.1-next.2

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 (88) hide show
  1. package/dist/cjs/onchain/accounts/index.js +1 -0
  2. package/dist/cjs/onchain/accounts/intents/guards.js +4 -2
  3. package/dist/cjs/onchain/accounts/intents/index.js +44 -11
  4. package/dist/cjs/onchain/accounts/intents/leverage-band.js +49 -8
  5. package/dist/cjs/onchain/accounts/intents/math.js +3 -44
  6. package/dist/cjs/onchain/accounts/intents/maxBorrow.js +7 -1
  7. package/dist/cjs/onchain/accounts/intents/open-strategy.js +12 -7
  8. package/dist/cjs/onchain/accounts/intents/plan.js +4 -4
  9. package/dist/cjs/onchain/accounts/intents/realize.js +4 -3
  10. package/dist/cjs/onchain/accounts/intents/strategyLimits.js +159 -0
  11. package/dist/cjs/onchain/accounts/intents/tail.js +6 -2
  12. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +4 -0
  13. package/dist/cjs/onchain/accounts/intents/utils/index.js +1 -0
  14. package/dist/cjs/onchain/accounts/intents/utils/quotas-for-update.js +39 -0
  15. package/dist/cjs/onchain/accounts/intents/withdraw-limits.js +1 -1
  16. package/dist/cjs/onchain/accounts/quota-utils.js +9 -0
  17. package/dist/cjs/onchain/index.js +1 -0
  18. package/dist/cjs/onchain/market/oracle/PriceOracleBaseContract.js +8 -6
  19. package/dist/cjs/onchain/validation/checks/checkBorrowLimit.js +2 -3
  20. package/dist/cjs/onchain/validation/checks/checkDebtLimits.js +3 -4
  21. package/dist/cjs/onchain/validation/checks/checkQuotaLimit.js +2 -1
  22. package/dist/cjs/sdk/prepare/PrepareApi.js +3 -2
  23. package/dist/esm/dev/AccountOpener.js +1 -1
  24. package/dist/esm/dev/withdrawalUtils.js +1 -1
  25. package/dist/esm/history/trace/extractTransfers.js +1 -1
  26. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -2
  27. package/dist/esm/onchain/accounts/index.js +2 -2
  28. package/dist/esm/onchain/accounts/intents/guards.js +4 -2
  29. package/dist/esm/onchain/accounts/intents/index.js +44 -11
  30. package/dist/esm/onchain/accounts/intents/leverage-band.js +50 -9
  31. package/dist/esm/onchain/accounts/intents/math.js +5 -45
  32. package/dist/esm/onchain/accounts/intents/maxBorrow.js +7 -1
  33. package/dist/esm/onchain/accounts/intents/open-strategy.js +13 -8
  34. package/dist/esm/onchain/accounts/intents/plan.js +4 -4
  35. package/dist/esm/onchain/accounts/intents/realize.js +4 -3
  36. package/dist/esm/onchain/accounts/intents/strategyLimits.js +158 -0
  37. package/dist/esm/onchain/accounts/intents/tail.js +6 -2
  38. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +4 -0
  39. package/dist/esm/onchain/accounts/intents/utils/index.js +2 -2
  40. package/dist/esm/onchain/accounts/intents/utils/quotas-for-update.js +41 -3
  41. package/dist/esm/onchain/accounts/intents/withdraw-limits.js +1 -1
  42. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  43. package/dist/esm/onchain/accounts/quota-utils.js +9 -1
  44. package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  45. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  46. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  47. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  48. package/dist/esm/onchain/base/TokensMeta.js +3 -3
  49. package/dist/esm/onchain/core/createAddressProvider.js +1 -1
  50. package/dist/esm/onchain/index.js +2 -2
  51. package/dist/esm/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  52. package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  53. package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  54. package/dist/esm/onchain/market/oracle/PriceOracleBaseContract.js +8 -6
  55. package/dist/esm/onchain/market/pool/PoolV310Contract.js +1 -1
  56. package/dist/esm/onchain/market/rwa/createDegenNFT.js +1 -1
  57. package/dist/esm/onchain/market/zapper/IETHZapperContract.js +1 -1
  58. package/dist/esm/onchain/market/zapper/ZapperContract.js +1 -1
  59. package/dist/esm/onchain/preview/preview/previewPoolPositionOperation.js +2 -2
  60. package/dist/esm/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
  61. package/dist/esm/onchain/validation/checks/checkBorrowLimit.js +2 -3
  62. package/dist/esm/onchain/validation/checks/checkDebtLimits.js +3 -4
  63. package/dist/esm/onchain/validation/checks/checkQuotaLimit.js +2 -1
  64. package/dist/esm/sdk/prepare/PrepareApi.js +3 -2
  65. package/dist/types/model/errors/index.d.ts +2 -2
  66. package/dist/types/model/errors/operation-errors.d.ts +28 -14
  67. package/dist/types/model/index.d.ts +2 -2
  68. package/dist/types/onchain/accounts/index.d.ts +2 -2
  69. package/dist/types/onchain/accounts/intents/guards.d.ts +12 -12
  70. package/dist/types/onchain/accounts/intents/index.d.ts +2 -3
  71. package/dist/types/onchain/accounts/intents/leverage-band.d.ts +8 -6
  72. package/dist/types/onchain/accounts/intents/math.d.ts +7 -16
  73. package/dist/types/onchain/accounts/intents/plan.d.ts +2 -0
  74. package/dist/types/onchain/accounts/intents/realize.d.ts +3 -0
  75. package/dist/types/onchain/accounts/intents/strategyLimits.d.ts +33 -0
  76. package/dist/types/onchain/accounts/intents/tail.d.ts +13 -9
  77. package/dist/types/onchain/accounts/intents/utils/index.d.ts +2 -2
  78. package/dist/types/onchain/accounts/intents/utils/quotas-for-update.d.ts +15 -1
  79. package/dist/types/onchain/accounts/quota-utils.d.ts +11 -1
  80. package/dist/types/onchain/index.d.ts +2 -2
  81. package/dist/types/onchain/market/oracle/PriceOracleBaseContract.d.ts +0 -3
  82. package/dist/types/onchain/market/oracle/types.d.ts +4 -3
  83. package/dist/types/onchain/validation/checks/checkBorrowLimit.d.ts +2 -3
  84. package/dist/types/onchain/validation/checks/checkDebtLimits.d.ts +2 -3
  85. package/dist/types/onchain/validation/checks/checkQuotaLimit.d.ts +2 -2
  86. package/dist/types/sdk/prepare/PrepareApi.d.ts +1 -1
  87. package/dist/types/sdk/prepare/types.d.ts +3 -4
  88. package/package.json +1 -1
@@ -2,12 +2,13 @@ import { insufficientBalance } from "../../../model/errors/operation-errors.js";
2
2
  import "../../../model/index.js";
3
3
  import { IntentPreviewError } from "../../validation/raise.js";
4
4
  import { assertCanBorrow, assertCollateralised, assertGrowthAllowed, assertMarketOperable, assertQuotaAvailable } from "./guards.js";
5
- import { assertDebtLimits, assertLeverageAtLeastOne, debtForLeverage, openCollateralForDebtLimits } from "./math.js";
5
+ import { assertDebtLimits, assertLeverageAtLeastOne, debtForLeverage } from "./math.js";
6
6
  import { unopenedAccountSlice } from "./utils/credit-account-slice.js";
7
7
  import { collectPriceImpact } from "./utils/price-impact.js";
8
8
  import { getQuotasForUpdate } from "./utils/quotas-for-update.js";
9
9
  import { createRouterPaths } from "./utils/router-path.js";
10
10
  import "./utils/index.js";
11
+ import { strategyLimits } from "./strategyLimits.js";
11
12
  //#region src/onchain/accounts/intents/open-strategy.ts
12
13
  /**
13
14
  * Builds the state opening a leveraged position out of wallet collateral would
@@ -44,17 +45,20 @@ async function buildOpenStrategyState(props) {
44
45
  creditFacade: suite.creditFacade.address,
45
46
  underlying
46
47
  });
47
- const getCollateralLimits = () => openCollateralForDebtLimits({
48
+ const options = leftoverBalances.length || existing?.tokens.some((t) => t.balance > 0n) ? void 0 : strategyLimits({
49
+ type: "OPEN",
48
50
  suite,
49
51
  collateral,
50
- leverage
52
+ leverage,
53
+ targetToken,
54
+ quotaReserve
51
55
  });
52
56
  assertDebtLimits(sdk, debt, suite.creditFacade, underlying, {
57
+ ...options,
53
58
  allowZero: false,
54
- maxBorrowAmount: suite.maxBorrowAmount(),
55
- getCollateralLimits
59
+ maxBorrowAmount: suite.maxBorrowAmount()
56
60
  });
57
- assertCanBorrow(sdk, suite, debt, { getCollateralLimits });
61
+ assertCanBorrow(sdk, suite, debt, options);
58
62
  const paths = createRouterPaths({
59
63
  sdk,
60
64
  creditAccount: account,
@@ -123,9 +127,10 @@ async function buildOpenStrategyState(props) {
123
127
  suite,
124
128
  market,
125
129
  before: [],
126
- after: averageAssets
130
+ after: averageAssets,
131
+ limits: options
127
132
  });
128
- assertQuotaAvailable(sdk, market, averageQuota);
133
+ assertQuotaAvailable(sdk, market, averageQuota, options);
129
134
  const projection = reached ?? settle();
130
135
  assertCollateralised(projection.healthFactor, false);
131
136
  const priceImpact = await collectPriceImpact(leg.probe ? [leg.probe] : [], {
@@ -42,7 +42,7 @@ function planDeposit(intent, view) {
42
42
  const aU = view.price(intent.token, U, intent.amount);
43
43
  const debtDelta = intent.targetLeverage === void 0 ? proportionalDebt(view, aU) : debtForLeverage(view.collateral + aU, intent.targetLeverage) - view.debt;
44
44
  if (debtDelta < 0n) throw new IntentPreviewError(leverageOutOfRange(), `deposit: target leverage ${intent.targetLeverage} would require repaying debt`);
45
- assertDebtLimits(view.sdk, view.debt + debtDelta, view.debtLimits, U);
45
+ assertDebtLimits(view.sdk, view.debt + debtDelta, view.debtLimits, U, view.limits);
46
46
  const T = intent.positionToken ?? positionToken(view, "deposit");
47
47
  const depositStays = eq(intent.token, T);
48
48
  return [
@@ -77,7 +77,7 @@ function planRepay(intent, view) {
77
77
  }), "repay: the account owes nothing");
78
78
  const funding = everything(intent.amount) ? view.price(U, intent.token, withMargin(view.debt)) : intent.amount;
79
79
  const repaid = min(view.price(intent.token, U, funding), view.debt);
80
- assertDebtLimits(view.sdk, view.debt - repaid, view.debtLimits, view.underlying);
80
+ assertDebtLimits(view.sdk, view.debt - repaid, view.debtLimits, view.underlying, view.limits);
81
81
  return [
82
82
  add(intent.token, funding, intent.value),
83
83
  ...fundsInU ? [] : [convert(intent.token, U, funding)],
@@ -306,7 +306,7 @@ function withdrawShape(intent, view) {
306
306
  };
307
307
  }
308
308
  const dD = proportionalDebt(view, WU);
309
- assertDebtLimits(view.sdk, view.debt - dD, view.debtLimits, view.underlying);
309
+ assertDebtLimits(view.sdk, view.debt - dD, view.debtLimits, view.underlying, view.limits);
310
310
  return {
311
311
  U,
312
312
  T,
@@ -325,7 +325,7 @@ function leverageShape(intent, view) {
325
325
  assertLeverageAtLeastOne(intent.targetLeverage);
326
326
  if (view.collateral <= 0n) throw new IntentPreviewError(insufficientBalance(), "adjustLeverage: account has no collateral to lever");
327
327
  const target = debtForLeverage(view.collateral, intent.targetLeverage);
328
- assertDebtLimits(view.sdk, target, view.debtLimits, view.underlying);
328
+ assertDebtLimits(view.sdk, target, view.debtLimits, view.underlying, view.limits);
329
329
  return {
330
330
  U: view.underlying,
331
331
  delta: target - view.debt
@@ -130,7 +130,7 @@ async function realize(steps, props) {
130
130
  }));
131
131
  break;
132
132
  case "borrow":
133
- assertCanBorrow(sdk, suite, step.amount);
133
+ assertCanBorrow(sdk, suite, step.amount, props.limits);
134
134
  push(buildIncreaseDebtOperation({
135
135
  amount: step.amount,
136
136
  creditAccount,
@@ -394,10 +394,11 @@ async function realize(steps, props) {
394
394
  suite,
395
395
  market,
396
396
  before: creditAccount.tokens,
397
- after: projected.assets
397
+ after: projected.assets,
398
+ limits: props.limits
398
399
  });
399
400
  if (!cleared && quotas.quotaIncrease.length + quotas.quotaDecrease.length > 0) {
400
- assertQuotaAvailable(sdk, market, quotas.quotaIncrease);
401
+ assertQuotaAvailable(sdk, market, quotas.quotaIncrease, props.limits);
401
402
  push(buildQuotaUpdateOperation({
402
403
  update: quotas,
403
404
  creditAccount,
@@ -0,0 +1,158 @@
1
+ import { BigIntMath } from "../../utils/bigint-math.js";
2
+ import { LEVERAGE_DECIMALS, MAX_UINT256 } from "../../constants/math.js";
3
+ import "../../constants/index.js";
4
+ import { quotaIncreaseLimit } from "./utils/quotas-for-update.js";
5
+ //#region src/onchain/accounts/intents/strategyLimits.ts
6
+ /** Independent input bounds supplied to debt, liquidity and quota errors. */
7
+ function strategyLimits(props) {
8
+ const { suite, quotaReserve } = props;
9
+ const { market } = suite;
10
+ const { priceOracle: oracle } = market;
11
+ switch (props.type) {
12
+ case "OPEN": {
13
+ const { collateral, leverage, targetToken } = props;
14
+ if (collateral.length !== 1 || leverage <= 100n) return {};
15
+ const [{ token }] = collateral;
16
+ const minDebt = suite.creditFacade.minDebt;
17
+ const maxDebt = suite.maxBorrowAmount().amount.value;
18
+ if (maxDebt < minDebt) return {};
19
+ const minCollateralForDebt = (debt) => {
20
+ const collateralUnderlying = BigIntMath.ceilDiv(debt * LEVERAGE_DECIMALS, leverage - LEVERAGE_DECIMALS);
21
+ const result = oracle.safeConvert(market.pool.underlying, token, collateralUnderlying - 1n);
22
+ if (result.error) return void 0;
23
+ const valuation = oracle.safeConvert(token, market.pool.underlying, result.value);
24
+ if (valuation.error) return void 0;
25
+ const collateral = result.value + (valuation.value < collateralUnderlying ? 1n : 0n);
26
+ const checked = oracle.safeConvert(token, market.pool.underlying, collateral);
27
+ return checked.error || checked.value < collateralUnderlying ? void 0 : collateral;
28
+ };
29
+ if (oracle.safeConvert(token, market.pool.underlying, 1n).error) return {};
30
+ const minCollateral = minCollateralForDebt(BigIntMath.max(minDebt, 1n));
31
+ const excessCollateral = minCollateralForDebt(maxDebt + 1n);
32
+ if (minCollateral === void 0 || excessCollateral === void 0 || minCollateral > 115792089237316195423570985008687907853269984665640564039457584007913129639935n) return {};
33
+ const maxCollateral = BigIntMath.min(MAX_UINT256, excessCollateral - 1n);
34
+ let maxCollateralByQuota;
35
+ if (!market.isUnderlyingLike(targetToken) && !market.pool.pqk.hasActiveQuota(targetToken)) maxCollateralByQuota = 0n;
36
+ else {
37
+ const quotaResult = quotaIncreaseLimit({
38
+ suite,
39
+ token: targetToken,
40
+ balance: 0n,
41
+ initialQuotas: [],
42
+ quotaReserve
43
+ });
44
+ if (!quotaResult.error && quotaResult.value !== void 0) {
45
+ const excessUnderlying = BigIntMath.ceilDiv((BigIntMath.max(quotaResult.value, 0n) + 1n) * LEVERAGE_DECIMALS, leverage);
46
+ const result = oracle.safeConvert(market.pool.underlying, token, excessUnderlying - 1n);
47
+ if (!result.error) {
48
+ const valuation = oracle.safeConvert(token, market.pool.underlying, result.value);
49
+ if (!valuation.error) {
50
+ const collateral = result.value - (valuation.value >= excessUnderlying ? 1n : 0n);
51
+ maxCollateralByQuota = BigIntMath.min(MAX_UINT256, BigIntMath.max(collateral, 0n));
52
+ }
53
+ }
54
+ }
55
+ }
56
+ return {
57
+ collateralLimits: minCollateral <= maxCollateral ? {
58
+ min: oracle.toTokenAmount(token, minCollateral),
59
+ max: oracle.toTokenAmount(token, maxCollateral)
60
+ } : void 0,
61
+ quotaLimits: maxCollateralByQuota === void 0 ? void 0 : { collateralMax: oracle.toTokenAmount(token, maxCollateralByQuota) }
62
+ };
63
+ }
64
+ case "DEPOSIT": {
65
+ const { view, token, positionToken, initialQuotas, targetLeverage } = props;
66
+ if (targetLeverage !== void 0 || view.collateral <= 0n) return {};
67
+ const minDebt = BigIntMath.max(view.debt, suite.creditFacade.minDebt);
68
+ const maxDebt = BigIntMath.min(suite.creditFacade.maxDebt, view.debt + suite.maxBorrowAmount().amount.value);
69
+ const minCollateralForDebt = (debt) => {
70
+ if (debt <= view.debt) return 0n;
71
+ if (view.debt === 0n) return void 0;
72
+ const collateralUnderlying = BigIntMath.ceilDiv((debt - view.debt) * view.collateral, view.debt);
73
+ const result = oracle.safeConvert(view.underlying, token, collateralUnderlying - 1n);
74
+ if (result.error) return void 0;
75
+ const valuation = oracle.safeConvert(token, view.underlying, result.value);
76
+ if (valuation.error) return void 0;
77
+ const collateral = result.value + (valuation.value < collateralUnderlying ? 1n : 0n);
78
+ const checked = oracle.safeConvert(token, view.underlying, collateral);
79
+ return checked.error || checked.value < collateralUnderlying ? void 0 : collateral;
80
+ };
81
+ const debtFloorCollateral = minCollateralForDebt(minDebt);
82
+ const minCollateral = debtFloorCollateral === void 0 ? void 0 : BigIntMath.max(1n, debtFloorCollateral);
83
+ const excessCollateral = debtFloorCollateral === void 0 ? void 0 : minCollateralForDebt(maxDebt + 1n);
84
+ const maxCollateral = excessCollateral === void 0 ? MAX_UINT256 : BigIntMath.min(MAX_UINT256, excessCollateral - 1n);
85
+ const position = positionToken ?? view.fattest([view.underlying]);
86
+ let maxCollateralByQuota;
87
+ if (position) {
88
+ if (!market.isUnderlyingLike(position) && !market.pool.pqk.hasActiveQuota(position)) maxCollateralByQuota = 0n;
89
+ else {
90
+ const quotaResult = quotaIncreaseLimit({
91
+ suite,
92
+ token: position,
93
+ balance: view.balanceOf(position),
94
+ initialQuotas,
95
+ quotaReserve,
96
+ rwaAsset: view.rwaAsset
97
+ });
98
+ maxCollateralByQuota = MAX_UINT256;
99
+ if (!quotaResult.error && quotaResult.value !== void 0) {
100
+ const excessUnderlying = BigIntMath.ceilDiv((quotaResult.value + 1n) * view.collateral, view.collateral + view.debt);
101
+ const result = oracle.safeConvert(view.underlying, token, BigIntMath.max(excessUnderlying - 1n, 0n));
102
+ maxCollateralByQuota = void 0;
103
+ if (!result.error) {
104
+ const valuation = oracle.safeConvert(token, view.underlying, result.value);
105
+ if (!valuation.error) {
106
+ const collateral = result.value - (valuation.value >= excessUnderlying ? 1n : 0n);
107
+ maxCollateralByQuota = BigIntMath.min(MAX_UINT256, BigIntMath.max(collateral, 0n));
108
+ }
109
+ }
110
+ }
111
+ }
112
+ }
113
+ return {
114
+ collateralLimits: minCollateral !== void 0 && minCollateral <= maxCollateral ? {
115
+ min: oracle.toTokenAmount(token, minCollateral),
116
+ max: oracle.toTokenAmount(token, maxCollateral)
117
+ } : void 0,
118
+ quotaLimits: maxCollateralByQuota === void 0 ? void 0 : { collateralMax: oracle.toTokenAmount(token, maxCollateralByQuota) }
119
+ };
120
+ }
121
+ case "ADJUST_LEVERAGE": {
122
+ const { view, token, initialQuotas, targetLeverage, maxLeverage = MAX_UINT256 } = props;
123
+ if (view.collateral <= 0n || targetLeverage < 100n) return {};
124
+ const maxDebt = BigIntMath.min(suite.creditFacade.maxDebt, view.debt + suite.maxBorrowAmount().amount.value);
125
+ const minLeverage = BigIntMath.max(LEVERAGE_DECIMALS + 1n, LEVERAGE_DECIMALS + BigIntMath.ceilDiv(suite.creditFacade.minDebt * LEVERAGE_DECIMALS, view.collateral));
126
+ const debtMaxLeverage = BigIntMath.min(maxLeverage, LEVERAGE_DECIMALS + BigIntMath.ceilDiv((maxDebt + 1n) * LEVERAGE_DECIMALS, view.collateral) - 1n);
127
+ const position = token ?? view.fattest([view.underlying]);
128
+ let maxLeverageByQuota;
129
+ if (position) {
130
+ if (!market.isUnderlyingLike(position) && !market.pool.pqk.hasActiveQuota(position)) maxLeverageByQuota = LEVERAGE_DECIMALS;
131
+ else {
132
+ const quotaResult = quotaIncreaseLimit({
133
+ suite,
134
+ token: position,
135
+ balance: view.balanceOf(position),
136
+ initialQuotas,
137
+ quotaReserve,
138
+ rwaAsset: view.rwaAsset
139
+ });
140
+ maxLeverageByQuota = maxLeverage;
141
+ if (!quotaResult.error && quotaResult.value !== void 0) {
142
+ const quotaMaxDebt = view.debt + quotaResult.value;
143
+ maxLeverageByQuota = BigIntMath.min(maxLeverage, LEVERAGE_DECIMALS + BigIntMath.ceilDiv((quotaMaxDebt + 1n) * LEVERAGE_DECIMALS, view.collateral) - 1n);
144
+ }
145
+ }
146
+ }
147
+ return {
148
+ leverageLimits: minLeverage <= debtMaxLeverage ? {
149
+ min: minLeverage,
150
+ max: debtMaxLeverage
151
+ } : void 0,
152
+ quotaLimits: maxLeverageByQuota === void 0 ? void 0 : { leverageMax: maxLeverageByQuota }
153
+ };
154
+ }
155
+ }
156
+ }
157
+ //#endregion
158
+ export { strategyLimits };
@@ -5,9 +5,9 @@ import { toTokenAmount } from "../../validation/helpers/token.js";
5
5
  import { IntentPreviewError } from "../../validation/raise.js";
6
6
  import { toTargetDecimals } from "./utils/common.js";
7
7
  import { createOraclePaths } from "./utils/router-path.js";
8
+ import { accountView } from "./view.js";
8
9
  import { planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw } from "./plan.js";
9
10
  import { instantOutput } from "./operations.js";
10
- import { accountView } from "./view.js";
11
11
  import { realize } from "./realize.js";
12
12
  //#region src/onchain/accounts/intents/tail.ts
13
13
  /**
@@ -168,13 +168,17 @@ async function projectTail(args) {
168
168
  const { steps } = planTail({
169
169
  intent: delayed.record,
170
170
  claimable: projectedClaimable(request, queued.token, queued.amount, claim),
171
- view: accountView(next, sdk)
171
+ view: {
172
+ ...accountView(next, sdk),
173
+ limits: args.limits
174
+ }
172
175
  });
173
176
  const { state, operations } = await realize(steps, {
174
177
  creditAccount: next,
175
178
  sdk,
176
179
  slippage: 0,
177
180
  quotaReserve,
181
+ limits: args.limits,
178
182
  paths: createOraclePaths({
179
183
  sdk,
180
184
  creditAccount: next
@@ -148,6 +148,10 @@ function buildMockSdk(args) {
148
148
  });
149
149
  const market = {
150
150
  toUnderlyingAmount,
151
+ isUnderlyingLike: (token) => {
152
+ const address = token.toLowerCase();
153
+ return address === args.underlying.toLowerCase() || address === args.rwaAssets?.[args.underlying.toLowerCase()]?.toLowerCase();
154
+ },
151
155
  /** {@inheritDoc MarketSuite.curator} */
152
156
  curator: MOCK_CURATOR,
153
157
  /** {@inheritDoc MarketSuite.underlying} */
@@ -6,6 +6,6 @@ import { calcBorrowedAmountPlusInterestAndFees } from "./borrowed-amount-plus-in
6
6
  import { fetchCreditAccountSlice, toCreditAccountSlice, unopenedAccountSlice } from "./credit-account-slice.js";
7
7
  import { OperationLedger } from "./ledger.js";
8
8
  import { collectPriceImpact, lossRate, startProbe } from "./price-impact.js";
9
- import { clearedQuotas, getQuotasForUpdate, quotasAfterUpdate, withDirectTransferQuota } from "./quotas-for-update.js";
9
+ import { clearedQuotas, getQuotasForUpdate, quotaIncreaseLimit, quotasAfterUpdate, withDirectTransferQuota } from "./quotas-for-update.js";
10
10
  import { createOraclePaths, createRouterPaths } from "./router-path.js";
11
- export { OperationLedger, adjustStateToSnapshot, assembleOperationCalls, calcBorrowedAmountPlusInterestAndFees, clearedQuotas, collectPriceImpact, createOraclePaths, createRouterPaths, eq, fetchCreditAccountSlice, getQuotasForUpdate, isPhantomToken, isRedemptionPhantomToken, lossRate, pickFattestNonPhantomToken, quotasAfterUpdate, rankAccountTokens, resolveCreditManager, startProbe, toCreditAccountSlice, toRouterCaSlice, toTargetDecimals, unopenedAccountSlice, withDirectTransferQuota };
11
+ export { OperationLedger, adjustStateToSnapshot, assembleOperationCalls, calcBorrowedAmountPlusInterestAndFees, clearedQuotas, collectPriceImpact, createOraclePaths, createRouterPaths, eq, fetchCreditAccountSlice, getQuotasForUpdate, isPhantomToken, isRedemptionPhantomToken, lossRate, pickFattestNonPhantomToken, quotaIncreaseLimit, quotasAfterUpdate, rankAccountTokens, resolveCreditManager, startProbe, toCreditAccountSlice, toRouterCaSlice, toTargetDecimals, unopenedAccountSlice, withDirectTransferQuota };
@@ -1,6 +1,8 @@
1
- import { MIN_INT96 } from "../../../constants/math.js";
1
+ import { BigIntMath } from "../../../utils/bigint-math.js";
2
+ import { MAX_UINT256, MIN_INT96 } from "../../../constants/math.js";
2
3
  import { TypedObjectUtils } from "../../../utils/mappers.js";
3
- import { DIRECT_TRANSFERS_QUOTA, calcQuotaUpdate } from "../../quota-utils.js";
4
+ import "../../../constants/index.js";
5
+ import { DIRECT_TRANSFERS_QUOTA, calcQuotaUpdate, maxAmountForQuota, roundUpQuota } from "../../quota-utils.js";
4
6
  //#region src/onchain/accounts/intents/utils/quotas-for-update.ts
5
7
  function getQuotasForUpdate({ assetsBefore, assetsAfter, initialQuotas, quotaReserve = 0, liquidationThresholds: liquidationThresholdsMap, quotas: quotasMap, maxDebt, underlyingToken, convert }) {
6
8
  const underlyingTokenLc = underlyingToken.toLowerCase();
@@ -194,5 +196,41 @@ function constructAssetRecord(a) {
194
196
  return acc;
195
197
  }, {});
196
198
  }
199
+ /** Largest additional underlying amount whose purchase fits this token's quota. */
200
+ function quotaIncreaseLimit({ suite, token, balance, initialQuotas, quotaReserve = 0, rwaAsset }) {
201
+ const { market } = suite;
202
+ if (market.isUnderlyingLike(token)) return { value: void 0 };
203
+ const oracle = market.priceOracle;
204
+ const purchaseResult = oracle.safeConvert(market.pool.underlying, token, MAX_UINT256);
205
+ if (purchaseResult.error) return purchaseResult;
206
+ const valuationResult = oracle.safeConvert(token, market.pool.underlying, MAX_UINT256);
207
+ if (valuationResult.error) return valuationResult;
208
+ if (purchaseResult.value === 0n || valuationResult.value === 0n) return { value: void 0 };
209
+ const maxQuotaValue = maxAmountForQuota({
210
+ available: market.pool.pqk.quotaAvailable(token),
211
+ initialQuota: initialQuotas.find((q) => q.token.toLowerCase() === token.toLowerCase())?.quota ?? 0n,
212
+ totalInitialQuota: initialQuotas.reduce((sum, q) => sum + roundUpQuota(q.quota), 0n),
213
+ maxDebt: suite.creditFacade.maxDebt,
214
+ lt: BigInt(suite.creditManager.liquidationThresholds.get(token) ?? 0),
215
+ quotaReserve: BigInt(quotaReserve)
216
+ });
217
+ if (maxQuotaValue === void 0) return { value: void 0 };
218
+ const quotaBalanceResult = oracle.safeConvert(market.pool.underlying, token, maxQuotaValue);
219
+ if (quotaBalanceResult.error) return quotaBalanceResult;
220
+ const quotaValueResult = oracle.safeConvert(token, market.pool.underlying, quotaBalanceResult.value);
221
+ if (quotaValueResult.error) return quotaValueResult;
222
+ const availableTokenIncrease = quotaBalanceResult.value - (quotaValueResult.value > maxQuotaValue ? 1n : 0n) - balance;
223
+ const excessTokenIncrease = BigIntMath.max(availableTokenIncrease, 0n) + 1n;
224
+ if (rwaAsset?.toLowerCase() === token.toLowerCase()) {
225
+ const underlyingScale = 10n ** BigInt(suite.sdk.tokensMeta.decimals(market.pool.underlying));
226
+ const tokenScale = 10n ** BigInt(suite.sdk.tokensMeta.decimals(token));
227
+ return { value: BigIntMath.ceilDiv(excessTokenIncrease * underlyingScale, tokenScale) - 1n };
228
+ }
229
+ const increaseResult = oracle.safeConvert(token, market.pool.underlying, excessTokenIncrease - 1n);
230
+ if (increaseResult.error) return increaseResult;
231
+ const purchaseValue = oracle.safeConvert(market.pool.underlying, token, increaseResult.value);
232
+ if (purchaseValue.error) return purchaseValue;
233
+ return { value: increaseResult.value - (purchaseValue.value >= excessTokenIncrease ? 1n : 0n) };
234
+ }
197
235
  //#endregion
198
- export { clearedQuotas, getQuotasForUpdate, quotasAfterUpdate, withDirectTransferQuota };
236
+ export { clearedQuotas, getQuotasForUpdate, quotaIncreaseLimit, quotasAfterUpdate, withDirectTransferQuota };
@@ -4,8 +4,8 @@ import "../../validation/helpers/health-factor-limits.js";
4
4
  import "../../validation/index.js";
5
5
  import { eq } from "./utils/common.js";
6
6
  import { maxProportionalWithdrawal } from "./math.js";
7
- import { collateralValuation } from "./collateral-valuation.js";
8
7
  import { accountView } from "./view.js";
8
+ import { collateralValuation } from "./collateral-valuation.js";
9
9
  //#region src/onchain/accounts/intents/withdraw-limits.ts
10
10
  /**
11
11
  * Every limit a `WITHDRAW` answers to, in underlying units.
@@ -1,3 +1,4 @@
1
+ import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
1
2
  import { AddressSet } from "../../utils/AddressSet.js";
2
3
  import { bytes32ToString } from "../../utils/bytes32ToString.js";
3
4
  import { ADDRESS_0X0 } from "../../constants/addresses.js";
@@ -19,7 +20,6 @@ import { SecuritizeLiquidatorContract } from "../../market/rwa/securitize/Securi
19
20
  import "../../market/rwa/securitize/index.js";
20
21
  import "../../market/index.js";
21
22
  import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./constants.js";
22
- import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
23
23
  import { skipLiquidatableAccount } from "./skipLiquidatableAccount.js";
24
24
  //#region src/onchain/accounts/liquidations/LiquidationsService.ts
25
25
  /**
@@ -42,6 +42,14 @@ function calcRecommendedQuota({ amount, debt, lt, quotaReserve }) {
42
42
  function calcDefaultQuota({ amount, lt, quotaReserve }) {
43
43
  return roundUpQuota(amount * lt / PERCENTAGE_FACTOR * (PERCENTAGE_FACTOR + quotaReserve) / PERCENTAGE_FACTOR);
44
44
  }
45
+ /** Inverse of default quota rounding, including the account-wide increase cap. */
46
+ function maxAmountForQuota({ available, initialQuota, totalInitialQuota, maxDebt, lt, quotaReserve }) {
47
+ const increaseCap = roundUpQuota(BigIntMath.max(roundUpQuota(maxDebt * 2n) - totalInitialQuota, 0n));
48
+ if (lt === 0n || increaseCap <= available) return void 0;
49
+ const desired = roundUpQuota(initialQuota) + roundUpQuota(available) + PERCENTAGE_FACTOR - 1n;
50
+ const base = BigIntMath.ceilDiv((desired + 1n) * PERCENTAGE_FACTOR, PERCENTAGE_FACTOR + quotaReserve) - 1n;
51
+ return BigIntMath.ceilDiv((base + 1n) * PERCENTAGE_FACTOR, lt) - 1n;
52
+ }
45
53
  /**
46
54
  * Produces desired quota state and explicit increase/decrease actions.
47
55
  *
@@ -142,4 +150,4 @@ function getSingleQuotaChange(token, unsafeMaxQuotaIncrease, props) {
142
150
  };
143
151
  }
144
152
  //#endregion
145
- export { DIRECT_TRANSFERS_QUOTA, calcDefaultQuota, calcQuotaUpdate, calcRecommendedQuota, roundUpQuota };
153
+ export { DIRECT_TRANSFERS_QUOTA, calcDefaultQuota, calcQuotaUpdate, calcRecommendedQuota, maxAmountForQuota, roundUpQuota };
@@ -1,9 +1,9 @@
1
+ import { iRedemptionLoggerV310Abi } from "../../../abi/iRedemptionLoggerV310.js";
1
2
  import { BaseContract } from "../../base/BaseContract.js";
2
3
  import "../../base/index.js";
3
4
  import { sdkErr, sdkOk } from "../../../model/result.js";
4
5
  import "../../../model/index.js";
5
6
  import { decodeDelayedIntent } from "./intent-codec.js";
6
- import { iRedemptionLoggerV310Abi } from "../../../abi/iRedemptionLoggerV310.js";
7
7
  //#region src/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.ts
8
8
  const abi = iRedemptionLoggerV310Abi;
9
9
  /**
@@ -1,5 +1,5 @@
1
- import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
2
1
  import { iWithdrawalCompressorV310Abi } from "../../../abi/IWithdrawalCompressorV310.js";
2
+ import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
3
3
  //#region src/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.ts
4
4
  const abi = iWithdrawalCompressorV310Abi;
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
2
1
  import { iWithdrawalCompressorV311Abi } from "../../../abi/IWithdrawalCompressorV311.js";
2
+ import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
3
3
  //#region src/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.ts
4
4
  const abi = iWithdrawalCompressorV311Abi;
5
5
  /**
@@ -1,6 +1,6 @@
1
+ import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
1
2
  import { encodeDelayedIntent } from "./intent-codec.js";
2
3
  import { AbstractWithdrawalCompressorContract, iCreditAccountAbi, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal } from "./AbstractWithdrawalCompressorContract.js";
3
- import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
4
4
  import { toWithdrawalStatus } from "./types.js";
5
5
  //#region src/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.ts
6
6
  const abi = iWithdrawalCompressorV313Abi;
@@ -1,12 +1,12 @@
1
+ import { iExpirableAbi } from "../../abi/iExpirable.js";
2
+ import { iStateSerializerAbi } from "../../abi/iStateSerializer.js";
3
+ import { iVersionAbi } from "../../abi/iVersion.js";
1
4
  import { AddressMap } from "../utils/AddressMap.js";
2
5
  import { AddressSet } from "../utils/AddressSet.js";
3
6
  import { bytes32ToString } from "../utils/bytes32ToString.js";
4
7
  import { getAssetType } from "../chain/chains.js";
5
8
  import { formatBN } from "../utils/formatter.js";
6
9
  import "../utils/index.js";
7
- import { iExpirableAbi } from "../../abi/iExpirable.js";
8
- import { iStateSerializerAbi } from "../../abi/iStateSerializer.js";
9
- import { iVersionAbi } from "../../abi/iVersion.js";
10
10
  import { SdkRWADataNotLoadedError } from "../core/errors.js";
11
11
  import { executeMulticallBatches } from "../utils/viem/executeMulticallBatches.js";
12
12
  //#region src/onchain/base/TokensMeta.ts
@@ -1,8 +1,8 @@
1
+ import { iVersionAbi } from "../../abi/iVersion.js";
1
2
  import "../constants/address-provider.js";
2
3
  import { isV310 } from "../constants/versions.js";
3
4
  import "../constants/index.js";
4
5
  import { hexEq } from "../utils/hex.js";
5
- import { iVersionAbi } from "../../abi/iVersion.js";
6
6
  import { AddressProviderV310Contract } from "./AddressProviderV310Contract.js";
7
7
  //#region src/onchain/core/createAddressProvider.ts
8
8
  const OVERRIDE_ADDRESSES = {};
@@ -242,7 +242,7 @@ import { raise } from "./validation/raise.js";
242
242
  import "./validation/index.js";
243
243
  import { isPhantomToken } from "./accounts/intents/utils/pick-token.js";
244
244
  import { fetchCreditAccountSlice, toCreditAccountSlice } from "./accounts/intents/utils/credit-account-slice.js";
245
- import { DIRECT_TRANSFERS_QUOTA, calcDefaultQuota, calcQuotaUpdate, calcRecommendedQuota, roundUpQuota } from "./accounts/quota-utils.js";
245
+ import { DIRECT_TRANSFERS_QUOTA, calcDefaultQuota, calcQuotaUpdate, calcRecommendedQuota, maxAmountForQuota, roundUpQuota } from "./accounts/quota-utils.js";
246
246
  import { CreditAccountOperationsService } from "./accounts/intents/index.js";
247
247
  import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./accounts/liquidations/constants.js";
248
248
  import { LiquidationsService } from "./accounts/liquidations/LiquidationsService.js";
@@ -305,4 +305,4 @@ import { replayMulticall } from "./preview/preview/replayMulticall.js";
305
305
  import { previewOperation } from "./preview/preview/previewOperation.js";
306
306
  import "./preview/index.js";
307
307
  import "./types/index.js";
308
- export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AccountMigratorAdapterContract, AdapterType, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, CamelotV3AdapterContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, ConstantPriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountState, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, CreditSuiteStrategy, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DEGEN_NFT_MIDAS, DEGEN_NFT_SECURITIZE, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DIRECT_TRANSFERS_QUOTA, DUST_THRESHOLD, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, EXECUTE_BYTES_SELECTOR, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LidoV1AdapterContract, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_INT96, MIN_SAFE_HEALTH_FACTOR_FORM, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasDegenNFT, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NON_STRATEGY_PHANTOM_TOKEN_TYPES, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PeripheryCompressorV310Contract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegistry, PriceOracleV310Contract, PriceUpdatesCache, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_COMPRESSOR_ADDRESS, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeDegenNFT, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UpdatablePriceFeedRegistry, UpshiftVaultAdapterContract, VERSION_RANGE_310, VelodromeV2RouterAdapterContract, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, amountOf, assetsMap, attachOptionsSchema, botPermissionsToString, bpsToRay, buildDelayedStrategyPositionOperationPreview, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkAccountQuotas, checkBorrowLimit, checkCollateralFunding, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkCreditOperation, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkHealthFactors, checkIncreaseDebt, checkIncreaseQuota, checkLeverage, checkLiquidation, checkLiquidationEligibility, checkLiquidationFunding, checkLiquidatorEligible, checkMarket, checkMarketExpired, checkMidasAccountGreenlist, checkObtained, checkOperation, checkPoolFunding, checkPoolLiquidity, checkPoolOperation, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkRWAOpenRequirements, checkRWAOpening, checkReservePriceLimited, checkSimulation, checkWallet, checkWalletAllowance, checkWalletBalance, childLogger, classifyCloseOrRepay, classifyCurveOperation, classifyInnerOperations, collateralPriceInUnderlying, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectDelayedClaim, detectDelayedOperation, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateClaimableAt, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, filterDust, filterDustUSD, findCallTo, findCallWithInput, findCuratorMarketConfigurator, findExecuteBytes, fmtBinaryMask, fnSigToName, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAccountTargetCollateral, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getAssetType, getCastTraceArgs, getChain, getCuratorName, getDirectTransferToken, getFunctionSignature, getLegacyStrategyTarget, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, hasAdapterDeployParamsAbi, healthFactorBps, hexEq, hydrateAddressProvider, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, iCreditAccountAbi, iCurvePoolAbi, iCurvePoolStableNGAbi, iCurvePool_2Abi, iCurvePool_3Abi, iCurvePool_4Abi, iCurveV1StableNgAdapterAbi, iCurveV1_2AssetsAdapterAbi, iCurveV1_3AssetsAdapterAbi, iCurveV1_4AssetsAdapterAbi, iDaiUsdsAbi, iDaiUsdsAdapterAbi, iERC4626Abi, iERC4626ReferralAbi, iFluidDexAbi, iFluidDexAdapterAbi, iInfinifiGatewayAbi, iInfinifiGatewayAdapterAbi, iInfinifiUnwindingGatewayAbi, iInfinifiUnwindingGatewayAdapterAbi, iKelpLRTDepositPoolGatewayAbi, iKelpLRTWithdrawalManagerGatewayAbi, iKelpLrtDepositPoolAdapterAbi, iKelpLrtDepositPoolGatewayAbi, iKelpLrtWithdrawalManagerAdapterAbi, iKelpLrtWithdrawalManagerGatewayAbi, iLidoV1AdapterAbi, iMellow4626VaultAdapterAbi, iMellowClaimerAbi, iMellowClaimerAdapterAbi, iMellowWrapperAbi, iMellowWrapperAdapterAbi, iMidasGatewayAdapterV311Abi, iMidasGatewayV311Abi, iMidasIssuanceVaultAdapterV310Abi, iMidasIssuanceVaultV310Abi, iMidasRedemptionVaultAdapterV310Abi, iMidasRedemptionVaultGatewayV310Abi, iPendleRouterAbi, iPendleRouterAdapterAbi, iSecuritizeOnRampAbi, iSecuritizeOnRampAdapterV310Abi, iSecuritizeRedemptionGatewayAdapterV311Abi, iSecuritizeRedemptionGatewayV311Abi, iStakingRewardsAbi, iStakingRewardsAdapterAbi, iTraderJoeRouterAbi, iTraderJoeRouterAdapterAbi, iUniswapV2AdapterAbi, iUniswapV2Router02Abi, iUniswapV3Abi, iUniswapV3AdapterAbi, iUniswapV4AdapterAbi, iUniswapV4GatewayAbi, iUpshiftVaultAdapterAbi, iUpshiftVaultGatewayAbi, iVelodromeV2RouterAbi, iVelodromeV2RouterAdapterAbi, isCloseOrRepay, isDust, isLPPriceFeed, isPhantomToken, isPoolOperation, isPublicNetwork, isRWAFactory, isRWAOperation, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, makeReplayState, mellowDvvAdapterAbi, midasGreenlistsAccount, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parsePosNegAmount, parseRWAFactoryOperationCalldata, percentFmt, pickStrategyTargetCollateral, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, raise, rayToBps, rayToNumber, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent, resolveProtocolCall, retry, rewardsFromTransfers, roundUpQuota, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, soleNonUnderlyingCollateral, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, updatableDependencies, usdToNumber, watchBlocksAsync };
308
+ export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AccountMigratorAdapterContract, AdapterType, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, CamelotV3AdapterContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, ConstantPriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountState, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, CreditSuiteStrategy, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DEGEN_NFT_MIDAS, DEGEN_NFT_SECURITIZE, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DIRECT_TRANSFERS_QUOTA, DUST_THRESHOLD, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, EXECUTE_BYTES_SELECTOR, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LidoV1AdapterContract, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_INT96, MIN_SAFE_HEALTH_FACTOR_FORM, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasDegenNFT, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NON_STRATEGY_PHANTOM_TOKEN_TYPES, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PeripheryCompressorV310Contract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegistry, PriceOracleV310Contract, PriceUpdatesCache, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_COMPRESSOR_ADDRESS, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeDegenNFT, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UpdatablePriceFeedRegistry, UpshiftVaultAdapterContract, VERSION_RANGE_310, VelodromeV2RouterAdapterContract, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, amountOf, assetsMap, attachOptionsSchema, botPermissionsToString, bpsToRay, buildDelayedStrategyPositionOperationPreview, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkAccountQuotas, checkBorrowLimit, checkCollateralFunding, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkCreditOperation, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkHealthFactors, checkIncreaseDebt, checkIncreaseQuota, checkLeverage, checkLiquidation, checkLiquidationEligibility, checkLiquidationFunding, checkLiquidatorEligible, checkMarket, checkMarketExpired, checkMidasAccountGreenlist, checkObtained, checkOperation, checkPoolFunding, checkPoolLiquidity, checkPoolOperation, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkRWAOpenRequirements, checkRWAOpening, checkReservePriceLimited, checkSimulation, checkWallet, checkWalletAllowance, checkWalletBalance, childLogger, classifyCloseOrRepay, classifyCurveOperation, classifyInnerOperations, collateralPriceInUnderlying, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectDelayedClaim, detectDelayedOperation, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateClaimableAt, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, filterDust, filterDustUSD, findCallTo, findCallWithInput, findCuratorMarketConfigurator, findExecuteBytes, fmtBinaryMask, fnSigToName, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAccountTargetCollateral, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getAssetType, getCastTraceArgs, getChain, getCuratorName, getDirectTransferToken, getFunctionSignature, getLegacyStrategyTarget, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, hasAdapterDeployParamsAbi, healthFactorBps, hexEq, hydrateAddressProvider, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, iCreditAccountAbi, iCurvePoolAbi, iCurvePoolStableNGAbi, iCurvePool_2Abi, iCurvePool_3Abi, iCurvePool_4Abi, iCurveV1StableNgAdapterAbi, iCurveV1_2AssetsAdapterAbi, iCurveV1_3AssetsAdapterAbi, iCurveV1_4AssetsAdapterAbi, iDaiUsdsAbi, iDaiUsdsAdapterAbi, iERC4626Abi, iERC4626ReferralAbi, iFluidDexAbi, iFluidDexAdapterAbi, iInfinifiGatewayAbi, iInfinifiGatewayAdapterAbi, iInfinifiUnwindingGatewayAbi, iInfinifiUnwindingGatewayAdapterAbi, iKelpLRTDepositPoolGatewayAbi, iKelpLRTWithdrawalManagerGatewayAbi, iKelpLrtDepositPoolAdapterAbi, iKelpLrtDepositPoolGatewayAbi, iKelpLrtWithdrawalManagerAdapterAbi, iKelpLrtWithdrawalManagerGatewayAbi, iLidoV1AdapterAbi, iMellow4626VaultAdapterAbi, iMellowClaimerAbi, iMellowClaimerAdapterAbi, iMellowWrapperAbi, iMellowWrapperAdapterAbi, iMidasGatewayAdapterV311Abi, iMidasGatewayV311Abi, iMidasIssuanceVaultAdapterV310Abi, iMidasIssuanceVaultV310Abi, iMidasRedemptionVaultAdapterV310Abi, iMidasRedemptionVaultGatewayV310Abi, iPendleRouterAbi, iPendleRouterAdapterAbi, iSecuritizeOnRampAbi, iSecuritizeOnRampAdapterV310Abi, iSecuritizeRedemptionGatewayAdapterV311Abi, iSecuritizeRedemptionGatewayV311Abi, iStakingRewardsAbi, iStakingRewardsAdapterAbi, iTraderJoeRouterAbi, iTraderJoeRouterAdapterAbi, iUniswapV2AdapterAbi, iUniswapV2Router02Abi, iUniswapV3Abi, iUniswapV3AdapterAbi, iUniswapV4AdapterAbi, iUniswapV4GatewayAbi, iUpshiftVaultAdapterAbi, iUpshiftVaultGatewayAbi, iVelodromeV2RouterAbi, iVelodromeV2RouterAdapterAbi, isCloseOrRepay, isDust, isLPPriceFeed, isPhantomToken, isPoolOperation, isPublicNetwork, isRWAFactory, isRWAOperation, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, makeReplayState, maxAmountForQuota, mellowDvvAdapterAbi, midasGreenlistsAccount, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parsePosNegAmount, parseRWAFactoryOperationCalldata, percentFmt, pickStrategyTargetCollateral, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, raise, rayToBps, rayToNumber, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent, resolveProtocolCall, retry, rewardsFromTransfers, roundUpQuota, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, soleNonUnderlyingCollateral, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, updatableDependencies, usdToNumber, watchBlocksAsync };
@@ -1,5 +1,5 @@
1
- import { AbstractAdapterContract } from "./AbstractAdapter.js";
2
1
  import { accountMigratorAbi } from "../../../../abi/AccountMigrator.js";
2
+ import { AbstractAdapterContract } from "./AbstractAdapter.js";
3
3
  //#region src/onchain/market/adapters/contracts/AccountMigratorAdapterContract.ts
4
4
  const abi = accountMigratorAbi;
5
5
  const protocolAbi = accountMigratorAbi;
@@ -1,6 +1,6 @@
1
+ import { ierc4626AdapterAbi } from "../../../../abi/ierc4626Adapter.js";
1
2
  import { MissingSerializedParamsError } from "../../../base/errors.js";
2
3
  import "../../../base/index.js";
3
- import { ierc4626AdapterAbi } from "../../../../abi/ierc4626Adapter.js";
4
4
  import { iERC4626Abi } from "../abi/targetContractAbi.js";
5
5
  import { fnSigToName, swapFromTransfers } from "../transferHelpers.js";
6
6
  import { AbstractAdapterContract } from "./AbstractAdapter.js";
@@ -1,7 +1,7 @@
1
+ import { iPausableAbi } from "../../../abi/iPausable.js";
1
2
  import { iCreditFacadeMulticallV310Abi, iCreditFacadeV310Abi } from "../../../abi/310/generated.js";
2
3
  import { BaseContract } from "../../base/BaseContract.js";
3
4
  import "../../base/index.js";
4
- import { iPausableAbi } from "../../../abi/iPausable.js";
5
5
  //#region src/onchain/market/credit/CreditFacadeV310BaseContract.ts
6
6
  const abi = [
7
7
  ...iCreditFacadeV310Abi,
@@ -112,6 +112,9 @@ var PriceOracleBaseContract = class extends BaseContract {
112
112
  * {@inheritDoc IPriceOracleContract.convert}
113
113
  **/
114
114
  convert(from, to, amount, reserve = false) {
115
+ return this.#convert(from, to, amount, reserve, false);
116
+ }
117
+ #convert(from, to, amount, reserve, roundUp) {
115
118
  if (isAddressEqual(from, to)) return amount;
116
119
  const fromToken = this.#priceableToken(from);
117
120
  const toToken = this.#priceableToken(to);
@@ -119,7 +122,9 @@ var PriceOracleBaseContract = class extends BaseContract {
119
122
  const fromScale = 10n ** BigInt(this.tokensMeta.decimals(fromToken));
120
123
  const toPrice = reserve ? this.reservePrice(toToken) : this.mainPrice(toToken);
121
124
  const toScale = 10n ** BigInt(this.tokensMeta.decimals(toToken));
122
- return amount * fromPrice * toScale / (toPrice * fromScale);
125
+ const numerator = amount * fromPrice * toScale;
126
+ const denominator = toPrice * fromScale;
127
+ return roundUp ? BigIntMath.ceilDiv(numerator, denominator) : numerator / denominator;
123
128
  }
124
129
  /**
125
130
  * {@inheritDoc IPriceOracleContract.convertToUSD}
@@ -140,15 +145,12 @@ var PriceOracleBaseContract = class extends BaseContract {
140
145
  const price = reserve ? this.reservePrice(token) : this.mainPrice(token);
141
146
  return amount * 10n ** BigInt(this.tokensMeta.decimals(token)) / price;
142
147
  }
143
- /**
144
- * {@inheritDoc IPriceOracleContract.safeConvert}
145
- **/
146
148
  safeConvert(from, to, amount) {
147
149
  try {
148
- return { value: this.convert(from, to, amount) };
150
+ return { value: this.#convert(from, to, amount, false, true) };
149
151
  } catch {
150
152
  try {
151
- return { value: this.convert(from, to, amount, true) };
153
+ return { value: this.#convert(from, to, amount, true, true) };
152
154
  } catch {
153
155
  return safeValue(0n, unpriceableTokenError(from));
154
156
  }