@gearbox-protocol/sdk 16.3.1 → 16.3.2-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/cjs/model/errors/index.js +1 -0
  2. package/dist/cjs/model/errors/operation-errors.js +9 -0
  3. package/dist/cjs/model/index.js +1 -0
  4. package/dist/cjs/onchain/accounts/intents/collateral-money.js +41 -0
  5. package/dist/cjs/onchain/accounts/intents/guards.js +15 -3
  6. package/dist/cjs/onchain/accounts/intents/index.js +21 -18
  7. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +12 -38
  8. package/dist/cjs/onchain/accounts/intents/realize.js +10 -2
  9. package/dist/cjs/onchain/accounts/intents/tail.js +1 -1
  10. package/dist/cjs/onchain/accounts/intents/withdraw-limits.js +97 -0
  11. package/dist/cjs/onchain/index.js +2 -0
  12. package/dist/cjs/onchain/market/adapters/abi/conctructorAbi.js +1 -1
  13. package/dist/cjs/onchain/validation/checks/checkReservePriceLimited.js +30 -0
  14. package/dist/cjs/onchain/validation/checks/index.js +2 -0
  15. package/dist/cjs/onchain/validation/index.js +2 -0
  16. package/dist/cjs/sdk/prepare/PrepareApi.js +3 -2
  17. package/dist/esm/dev/AccountOpener.js +1 -1
  18. package/dist/esm/dev/withdrawalUtils.js +1 -1
  19. package/dist/esm/history/trace/extractTransfers.js +1 -1
  20. package/dist/esm/model/errors/index.js +2 -2
  21. package/dist/esm/model/errors/operation-errors.js +9 -1
  22. package/dist/esm/model/index.js +2 -2
  23. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -2
  24. package/dist/esm/onchain/accounts/intents/collateral-money.js +40 -0
  25. package/dist/esm/onchain/accounts/intents/guards.js +15 -3
  26. package/dist/esm/onchain/accounts/intents/index.js +21 -18
  27. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +12 -38
  28. package/dist/esm/onchain/accounts/intents/realize.js +10 -2
  29. package/dist/esm/onchain/accounts/intents/tail.js +1 -1
  30. package/dist/esm/onchain/accounts/intents/withdraw-limits.js +95 -0
  31. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  32. package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  33. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  34. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  35. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  36. package/dist/esm/onchain/base/TokensMeta.js +3 -3
  37. package/dist/esm/onchain/core/createAddressProvider.js +1 -1
  38. package/dist/esm/onchain/index.js +2 -1
  39. package/dist/esm/onchain/market/adapters/abi/conctructorAbi.js +1 -1
  40. package/dist/esm/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  41. package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  42. package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  43. package/dist/esm/onchain/market/pool/PoolV310Contract.js +1 -1
  44. package/dist/esm/onchain/market/rwa/createDegenNFT.js +1 -1
  45. package/dist/esm/onchain/market/zapper/IETHZapperContract.js +1 -1
  46. package/dist/esm/onchain/market/zapper/ZapperContract.js +1 -1
  47. package/dist/esm/onchain/preview/preview/previewPoolPositionOperation.js +2 -2
  48. package/dist/esm/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
  49. package/dist/esm/onchain/validation/checks/checkReservePriceLimited.js +29 -0
  50. package/dist/esm/onchain/validation/checks/index.js +2 -1
  51. package/dist/esm/onchain/validation/index.js +2 -1
  52. package/dist/esm/sdk/prepare/PrepareApi.js +3 -2
  53. package/dist/types/model/errors/index.d.ts +2 -2
  54. package/dist/types/model/errors/operation-errors.d.ts +41 -1
  55. package/dist/types/model/index.d.ts +2 -2
  56. package/dist/types/onchain/accounts/intents/collateral-money.d.ts +42 -0
  57. package/dist/types/onchain/accounts/intents/guards.d.ts +18 -2
  58. package/dist/types/onchain/accounts/intents/index.d.ts +23 -14
  59. package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +3 -8
  60. package/dist/types/onchain/accounts/intents/types.d.ts +26 -4
  61. package/dist/types/onchain/accounts/intents/withdraw-limits.d.ts +80 -0
  62. package/dist/types/onchain/index.d.ts +2 -1
  63. package/dist/types/onchain/validation/checks/checkReservePriceLimited.d.ts +31 -0
  64. package/dist/types/onchain/validation/checks/index.d.ts +2 -1
  65. package/dist/types/onchain/validation/index.d.ts +2 -1
  66. package/dist/types/onchain/validation/raise.d.ts +2 -2
  67. package/dist/types/sdk/prepare/PrepareApi.d.ts +1 -1
  68. package/dist/types/sdk/prepare/types.d.ts +23 -16
  69. package/package.json +1 -1
@@ -1,5 +1,3 @@
1
- import { iBaseRewardPoolAbi } from "../../abi/iBaseRewardPool.js";
2
- import { ierc4626AdapterAbi } from "../../abi/ierc4626Adapter.js";
3
1
  import { AP_REWARDS_COMPRESSOR } from "../constants/address-provider.js";
4
2
  import { ADDRESS_0X0 } from "../constants/addresses.js";
5
3
  import { MAX_UINT256 } from "../constants/math.js";
@@ -10,6 +8,8 @@ import "../base/index.js";
10
8
  import { AccountBotsService } from "./bots/AccountBotsService.js";
11
9
  import "./bots/index.js";
12
10
  import { rewardsCompressorAbi } from "../../abi/compressors/rewardsCompressor.js";
11
+ import { iBaseRewardPoolAbi } from "../../abi/iBaseRewardPool.js";
12
+ import { ierc4626AdapterAbi } from "../../abi/ierc4626Adapter.js";
13
13
  import { expectedBalanceDeltas } from "../market/credit/expectedBalanceDeltas.js";
14
14
  import "../market/index.js";
15
15
  import { CreditAccountCompressor } from "./credit-account-compressor/CreditAccountCompressor.js";
@@ -0,0 +1,40 @@
1
+ import { BigIntMath } from "../../utils/bigint-math.js";
2
+ import { PERCENTAGE_FACTOR } from "../../constants/math.js";
3
+ import "../../utils/index.js";
4
+ import { eq } from "./utils/common.js";
5
+ //#region src/onchain/accounts/intents/collateral-money.ts
6
+ /** {@inheritDoc CollateralMoney} */
7
+ function collateralMoney(creditAccount, sdk) {
8
+ const { market, creditManager } = sdk.marketRegister.findCreditManager(creditAccount.creditManager);
9
+ const { priceOracle } = market;
10
+ const { pqk } = market.pool;
11
+ const underlying = market.pool.underlying;
12
+ const masked = creditAccount.enabledTokensMask !== 0n;
13
+ const mainUsd = (token, amount) => {
14
+ try {
15
+ return priceOracle.convertToUSD(token, amount);
16
+ } catch {
17
+ return;
18
+ }
19
+ };
20
+ const lt = (token) => BigInt(creditManager.liquidationThresholds.get(token) ?? 0);
21
+ const checkedUsd = (holding) => eq(holding.token, underlying) ? mainUsd(holding.token, holding.balance) ?? 0n : priceOracle.safeConvertMinUSD(holding.token, holding.balance).value;
22
+ /** A quota is underlying-denominated, and a closed market backs nothing. */
23
+ const quotaMoney = (holding) => pqk.hasActiveQuota(holding.token) ? (mainUsd(underlying, holding.quota) ?? 0n) * PERCENTAGE_FACTOR : 0n;
24
+ const weigh = (holding) => {
25
+ const weighted = checkedUsd(holding) * lt(holding.token);
26
+ if (holding.quota === 0n) return weighted;
27
+ return BigIntMath.min(quotaMoney(holding), weighted);
28
+ };
29
+ return {
30
+ underlying,
31
+ counts: (holding) => holding.balance > 10n && (!masked || (holding.mask & creditAccount.enabledTokensMask) !== 0n),
32
+ weigh,
33
+ quotaMoney,
34
+ mainUsd,
35
+ checkedUsd,
36
+ lt
37
+ };
38
+ }
39
+ //#endregion
40
+ export { collateralMoney };
@@ -6,6 +6,7 @@ import { checkCreditManagerPaused } from "../../validation/checks/checkCreditMan
6
6
  import { checkForbiddenToken } from "../../validation/checks/checkForbiddenToken.js";
7
7
  import { checkMarketExpired } from "../../validation/checks/checkMarketExpired.js";
8
8
  import { checkQuotaLimit } from "../../validation/checks/checkQuotaLimit.js";
9
+ import { checkReservePriceLimited } from "../../validation/checks/checkReservePriceLimited.js";
9
10
  import { raise } from "../../validation/raise.js";
10
11
  import "../../validation/index.js";
11
12
  import { eq } from "./utils/common.js";
@@ -111,13 +112,24 @@ function assertGrowthAllowed(args) {
111
112
  * whose reserve feed the SDK cannot read keeps its main price, so a plan can
112
113
  * still be refused on-chain after passing here.
113
114
  */
114
- function assertCollateralised(healthFactorBps, safePrices) {
115
+ function assertCollateralised(healthFactorBps, safePrices, atSafePrices) {
115
116
  const healthFactorThreshold = MIN_HEALTH_FACTOR_FACADE;
116
- raise(checkCollateralised({
117
+ const errors = checkCollateralised({
117
118
  healthFactor: healthFactorBps,
118
119
  healthFactorThreshold,
119
120
  safePrices
120
- }), `the account would end at a health factor of ${healthFactorBps}, below ${healthFactorThreshold}`);
121
+ });
122
+ if (errors.length === 0) return;
123
+ if (safePrices && atSafePrices) {
124
+ const { atMainPrices, withdrawable } = atSafePrices();
125
+ raise(checkReservePriceLimited({
126
+ healthFactor: healthFactorBps,
127
+ atMainPrices,
128
+ healthFactorThreshold,
129
+ withdrawable
130
+ }), `the account covers its debt at ${atMainPrices} on the main feed and only ${healthFactorBps} at the reserve one, below ${healthFactorThreshold}`);
131
+ }
132
+ raise(errors, `the account would end at a health factor of ${healthFactorBps}, below ${healthFactorThreshold}`);
121
133
  }
122
134
  /**
123
135
  * A quota can only be raised as far as the market still has room for: past the
@@ -8,13 +8,13 @@ import "../../validation/index.js";
8
8
  import { isPhantomToken } from "./utils/pick-token.js";
9
9
  import { assertMarketOperable } from "./guards.js";
10
10
  import { calcLeverageBand } from "./leverage-band.js";
11
- import { maxProportionalWithdrawal } from "./math.js";
12
11
  import { maxWithdrawCollateral } from "./maxWithdrawCollateral.js";
13
12
  import { fetchCreditAccountSlice, toCreditAccountSlice } from "./utils/credit-account-slice.js";
14
13
  import { buildOpenStrategyState } from "./open-strategy.js";
15
14
  import { planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planDeposit, planRepay, planWithdraw, planWithdrawAsset, planWithdrawDelayed } from "./plan.js";
16
- import { realize } from "./realize.js";
17
15
  import { accountView } from "./view.js";
16
+ import { withdrawLimits } from "./withdraw-limits.js";
17
+ import { realize } from "./realize.js";
18
18
  import { planTail, projectTail } from "./tail.js";
19
19
  //#region src/onchain/accounts/intents/index.ts
20
20
  /**
@@ -50,26 +50,29 @@ var CreditAccountOperationsService = class extends SDKConstruct {
50
50
  }
51
51
  /**
52
52
  * Both ends of what a `WITHDRAW` can take out, in underlying: the largest
53
- * partial withdrawal that keeps leverage and stays inside the facade's
54
- * `debtLimits`, and the net value an exit hands over. They are reported together
55
- * because a withdraw form needs both — the range it may offer, and the one
56
- * amount past it that is allowed — and because the distance between them is
57
- * the account's own, not a constant a caller could assume.
53
+ * partial withdrawal that keeps leverage, and the net value an exit hands
54
+ * over. They are reported together because a withdraw form needs both — the
55
+ * range it may offer, and the one amount past it that is allowed — and
56
+ * because the distance between them is the account's own, not a constant a
57
+ * caller could assume.
58
58
  *
59
- * Takes no target health factor, unlike {@link maxWithdrawCollateral}: a
60
- * proportional withdrawal leaves the factor where it found it, and the
61
- * facade's `minDebt` is what bounds it.
59
+ * Two rules bound the partial end and both are reported: the facade's
60
+ * `debtLimits` as `partial`, and the safe-price collateral check on top of
61
+ * it as `safePartial`. The second is the one to offer — see
62
+ * {@link WithdrawCeilings}.
62
63
  *
63
- * @param props - Account slice and the SDK holding its market
64
- * @returns The two ceilings, see {@link WithdrawCeilings} for the gap between
65
- * them
64
+ * Takes no target health factor, unlike {@link maxWithdrawCollateral}. A
65
+ * proportional withdrawal leaves the factor where it found it, so there is
66
+ * no room to choose: what these answer to is the facade's own threshold,
67
+ * which is also what {@link startIntent} refuses against.
68
+ *
69
+ * @param props - Account slice, the SDK holding its market, and optionally
70
+ * the collateral the withdrawal would be funded from
71
+ * @returns The three limits, see {@link WithdrawCeilings} for the gap
72
+ * between them
66
73
  */
67
74
  maxWithdraw(props) {
68
- const view = accountView(props.creditAccount, props.sdk);
69
- return {
70
- partial: maxProportionalWithdrawal(view, view.debtLimits),
71
- exit: view.collateral > 0n ? view.collateral : 0n
72
- };
75
+ return withdrawLimits(props);
73
76
  }
74
77
  /**
75
78
  * Debt a `REPAY` would have to cover to settle the account, in underlying
@@ -1,21 +1,17 @@
1
1
  import { BigIntMath } from "../../utils/bigint-math.js";
2
- import { PERCENTAGE_FACTOR } from "../../constants/math.js";
2
+ import "../../constants/math.js";
3
3
  import "../../utils/index.js";
4
4
  import { eq } from "./utils/common.js";
5
+ import { collateralMoney } from "./collateral-money.js";
5
6
  //#region src/onchain/accounts/intents/maxWithdrawCollateral.ts
6
7
  /**
7
8
  * Largest amount of one collateral the account can withdraw while its health
8
9
  * factor stays at or above `targetHF`.
9
10
  *
10
11
  * This is the collateral check solved for one balance, and it counts what that
11
- * check counts: a holding backed by a quota contributes the lesser of the
12
- * quota and its threshold-weighted value, an unquoted one — the underlying —
13
- * its weighted value alone, and dust or a disabled balance nothing at all.
14
- * Collateral is valued at the protocol safe price (`min` of the two feeds,
15
- * 0 when there is no reserve), the way the facade values a call that hands
16
- * funds over; the underlying is exempt and is valued at the main feed, as
17
- * `CreditManagerV3._safeConvertToUSD` does. The debt is valued at the main
18
- * feed, as the check does. Zero debt frees the whole balance.
12
+ * check counts — see {@link collateralMoney} for the valuation, safe prices
13
+ * included. The debt is valued at the main feed, as the check does. Zero debt
14
+ * frees the whole balance.
19
15
  *
20
16
  * Rounding always favours the account, so the answer clears the check rather
21
17
  * than landing a wei short of it.
@@ -26,49 +22,27 @@ import { eq } from "./utils/common.js";
26
22
  **/
27
23
  function maxWithdrawCollateral(props) {
28
24
  const { creditAccount, sdk, token, targetHF } = props;
29
- const { market, creditManager } = sdk.marketRegister.findCreditManager(creditAccount.creditManager);
30
- const { priceOracle } = market;
31
- const { pqk } = market.pool;
32
- const underlying = market.pool.underlying;
33
25
  const target = creditAccount.tokens.find((t) => eq(t.token, token));
34
26
  if (!target || target.balance <= 10n) return 0n;
35
27
  if (creditAccount.totalDebt === 0n) return target.balance;
36
- const masked = creditAccount.enabledTokensMask !== 0n;
37
- const counts = (t) => t.balance > 10n && (!masked || (t.mask & creditAccount.enabledTokensMask) !== 0n);
38
- /** What a holding backs, in the check's units: USD × PERCENTAGE_FACTOR. */
39
- const weigh = (t) => {
40
- const lt = BigInt(creditManager.liquidationThresholds.get(t.token) ?? 0);
41
- const weighted = (eq(t.token, underlying) ? usd(priceOracle, t.token, t.balance) ?? 0n : priceOracle.safeConvertMinUSD(t.token, t.balance).value) * lt;
42
- if (t.quota === 0n) return weighted;
43
- return BigIntMath.min(quotaUsd(t) * PERCENTAGE_FACTOR, weighted);
44
- };
45
- /** A quota is underlying-denominated, and a closed market backs nothing. */
46
- const quotaUsd = (t) => pqk.hasActiveQuota(t.token) ? usd(priceOracle, underlying, t.quota) ?? 0n : 0n;
28
+ const money = collateralMoney(creditAccount, sdk);
47
29
  let otherMoney = 0n;
48
30
  for (const t of creditAccount.tokens) {
49
- if (eq(t.token, token) || !counts(t)) continue;
50
- otherMoney += weigh(t);
31
+ if (eq(t.token, token) || !money.counts(t)) continue;
32
+ otherMoney += money.weigh(t);
51
33
  }
52
- const borrowed = usd(priceOracle, underlying, creditAccount.totalDebt);
34
+ const borrowed = money.mainUsd(money.underlying, creditAccount.totalDebt);
53
35
  if (borrowed === void 0 || borrowed <= 0n) return 0n;
54
36
  const required = borrowed * targetHF;
55
37
  if (required <= otherMoney) return target.balance;
56
38
  const shortfall = required - otherMoney;
57
- if (target.quota > 0n && quotaUsd(target) * 10000n < shortfall) return 0n;
58
- const targetLt = BigInt(creditManager.liquidationThresholds.get(target.token) ?? 0);
59
- const targetUsd = eq(target.token, underlying) ? usd(priceOracle, target.token, target.balance) ?? 0n : priceOracle.safeConvertMinUSD(target.token, target.balance).value;
39
+ if (target.quota > 0n && money.quotaMoney(target) < shortfall) return 0n;
40
+ const targetLt = money.lt(target.token);
41
+ const targetUsd = money.checkedUsd(target);
60
42
  if (targetLt === 0n || targetUsd === 0n) return 0n;
61
43
  const keptUsd = BigIntMath.ceilDiv(shortfall, targetLt);
62
44
  const kept = BigIntMath.ceilDiv(target.balance * keptUsd, targetUsd);
63
45
  return kept >= target.balance ? 0n : target.balance - kept;
64
46
  }
65
- /** USD value at the main feed, or `undefined` when the token has no price. */
66
- function usd(oracle, token, amount) {
67
- try {
68
- return oracle.convertToUSD(token, amount);
69
- } catch {
70
- return;
71
- }
72
- }
73
47
  //#endregion
74
48
  export { maxWithdrawCollateral };
@@ -11,6 +11,7 @@ import { collectPriceImpact } from "./utils/price-impact.js";
11
11
  import { clearedQuotas, getQuotasForUpdate, quotasAfterUpdate } from "./utils/quotas-for-update.js";
12
12
  import { createRouterPaths } from "./utils/router-path.js";
13
13
  import { buildAddCollateralOperation, buildClaimDelayedWithdrawalOperation, buildCloseSwapOperation, buildDecreaseDebtOperation, buildIncreaseDebtOperation, buildQuotaUpdateOperation, buildStartDelayedWithdrawalOperation, buildSwapOperation, buildUnwrapRwaCollateralOperation, buildWithdrawCollateralOperation, buildWrapRwaCollateralOperation, instantOutput } from "./operations.js";
14
+ import { withdrawLimits } from "./withdraw-limits.js";
14
15
  //#region src/onchain/accounts/intents/realize.ts
15
16
  /**
16
17
  * Turns a plan into operations: the one place that talks to the router, knows
@@ -319,11 +320,18 @@ async function realize(steps, props) {
319
320
  totalValue: projected.totalValue
320
321
  };
321
322
  const projection = sdk.positions.projection(snapshot, { availableLiquidityChange: creditAccount.totalDebt - debt });
322
- assertCollateralised(sdk.positions.healthFactor({
323
+ const settled = {
323
324
  ...snapshot,
324
325
  assets,
325
326
  totalValue: floor.totalValue
326
- }, { safePrices: withdrawsCollateral }), withdrawsCollateral);
327
+ };
328
+ assertCollateralised(sdk.positions.healthFactor(settled, { safePrices: withdrawsCollateral }), withdrawsCollateral, () => ({
329
+ atMainPrices: sdk.positions.healthFactor(settled, { safePrices: false }),
330
+ withdrawable: toTokenAmount(sdk, underlying, withdrawLimits({
331
+ creditAccount,
332
+ sdk
333
+ }).safePartial)
334
+ }));
327
335
  const priceImpact = await collectPriceImpact(probes, {
328
336
  totalValue: projected.totalValue,
329
337
  netValue: projected.totalValue - debt,
@@ -7,8 +7,8 @@ import { toTargetDecimals } from "./utils/common.js";
7
7
  import { createOraclePaths } from "./utils/router-path.js";
8
8
  import { planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw } from "./plan.js";
9
9
  import { instantOutput } from "./operations.js";
10
- import { realize } from "./realize.js";
11
10
  import { accountView } from "./view.js";
11
+ import { realize } from "./realize.js";
12
12
  //#region src/onchain/accounts/intents/tail.ts
13
13
  /**
14
14
  * The second half of a delayed intent: the claim, then whatever the intent
@@ -0,0 +1,95 @@
1
+ import { BigIntMath } from "../../utils/bigint-math.js";
2
+ import "../../utils/index.js";
3
+ import { MIN_HEALTH_FACTOR_FACADE } from "../../validation/helpers/health-factor-limits.js";
4
+ import "../../validation/index.js";
5
+ import { eq } from "./utils/common.js";
6
+ import { collateralMoney } from "./collateral-money.js";
7
+ import { maxProportionalWithdrawal } from "./math.js";
8
+ import { accountView } from "./view.js";
9
+ //#region src/onchain/accounts/intents/withdraw-limits.ts
10
+ /**
11
+ * Every limit a `WITHDRAW` answers to, in underlying units.
12
+ *
13
+ * The one place they are assembled, so the figure a form is offered and the
14
+ * figure the collateral guard names when it turns a withdrawal down cannot
15
+ * drift apart: `CreditAccountOperationsService` reports this, and the guard
16
+ * quotes it back.
17
+ *
18
+ * @param props - Account slice, the SDK holding its market, and optionally the
19
+ * collateral the withdrawal would be funded from
20
+ * @returns The three limits, see {@link WithdrawCeilings}
21
+ **/
22
+ function withdrawLimits(props) {
23
+ const { creditAccount, sdk } = props;
24
+ const view = accountView(creditAccount, sdk);
25
+ const partial = maxProportionalWithdrawal(view, view.debtLimits);
26
+ const safe = maxSafeWithdrawal({
27
+ ...props,
28
+ targetHF: BigInt(MIN_HEALTH_FACTOR_FACADE)
29
+ });
30
+ return {
31
+ partial,
32
+ safePartial: BigIntMath.min(partial, safe),
33
+ exit: view.collateral > 0n ? view.collateral : 0n
34
+ };
35
+ }
36
+ /**
37
+ * Largest proportional withdrawal the safe-price collateral check still clears,
38
+ * in underlying units.
39
+ *
40
+ * A withdrawal hands funds over, so the facade weighs the account it leaves
41
+ * behind at safe prices rather than main ones — see {@link collateralMoney}.
42
+ * That is a second limit on top of the facade's `debtLimits`, and the two are
43
+ * independent: a caller wanting the amount a form may actually offer takes the
44
+ * lesser of this and `maxProportionalWithdrawal`.
45
+ *
46
+ * The arithmetic is the check solved for the amount. Taking `W` out at fixed
47
+ * leverage repays `dD = D·W/C`, so `W·TVL/C` of value is sold out of the source
48
+ * token; each dollar of that sale costs the check the source's threshold times
49
+ * its safe-to-main price ratio, while the repayment relieves `targetHF` per
50
+ * dollar of debt. Both terms are linear in `W`, which is why one division
51
+ * answers instead of a search — and why the answer is exact rather than a
52
+ * bound, as long as the plan really does fund itself from `sourceToken`.
53
+ *
54
+ * Two consequences worth stating, because they surprise:
55
+ *
56
+ * - An account whose collateral is entirely a token the reserve feed marks
57
+ * down cannot withdraw at all once it is under the threshold. A proportional
58
+ * withdrawal scales collateral and debt together, so it leaves the safe-price
59
+ * factor exactly where it found it — no amount climbs back over.
60
+ * - Leaving entirely is never refused for this reason: the exit settles the
61
+ * debt instead of shrinking it, and a check with no debt to divide by has
62
+ * nothing to refuse.
63
+ *
64
+ * @returns Amount in underlying units. The account's net value when safe prices
65
+ * do not limit the withdrawal at all, so the caller's `min` is a no-op; `0n`
66
+ * when the account already sits below `targetHF` at safe prices, and only the
67
+ * exit is left
68
+ **/
69
+ function maxSafeWithdrawal(props) {
70
+ const { creditAccount, sdk, targetHF } = props;
71
+ const view = accountView(creditAccount, sdk);
72
+ if (view.collateral <= 0n) return 0n;
73
+ if (view.debt === 0n) return view.collateral;
74
+ const money = collateralMoney(creditAccount, sdk);
75
+ const source = props.sourceToken ?? view.fattest();
76
+ const holding = source === void 0 ? void 0 : creditAccount.tokens.find((t) => eq(t.token, source));
77
+ if (!holding) return view.collateral;
78
+ let total = 0n;
79
+ for (const t of creditAccount.tokens) if (money.counts(t)) total += money.weigh(t);
80
+ const debtUsd = money.mainUsd(money.underlying, view.debt);
81
+ if (debtUsd === void 0 || debtUsd <= 0n) return view.collateral;
82
+ const slack = total - debtUsd * targetHF;
83
+ if (slack < 0n) return 0n;
84
+ const sourceMainUsd = money.mainUsd(holding.token, holding.balance);
85
+ if (sourceMainUsd === void 0 || sourceMainUsd <= 0n) return view.collateral;
86
+ const sourceRate = money.lt(holding.token) * money.checkedUsd(holding);
87
+ const tvlUsd = money.mainUsd(money.underlying, view.collateral + view.debt);
88
+ if (tvlUsd === void 0) return view.collateral;
89
+ const drain = sourceRate * tvlUsd - targetHF * debtUsd * sourceMainUsd;
90
+ if (drain <= 0n) return view.collateral;
91
+ const limit = view.collateral * slack * sourceMainUsd / drain;
92
+ return limit < view.collateral ? limit : view.collateral;
93
+ }
94
+ //#endregion
95
+ export { maxSafeWithdrawal, withdrawLimits };
@@ -1,4 +1,3 @@
1
- import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
2
1
  import { AddressSet } from "../../utils/AddressSet.js";
3
2
  import { bytes32ToString } from "../../utils/bytes32ToString.js";
4
3
  import { ADDRESS_0X0 } from "../../constants/addresses.js";
@@ -20,6 +19,7 @@ import { SecuritizeLiquidatorContract } from "../../market/rwa/securitize/Securi
20
19
  import "../../market/rwa/securitize/index.js";
21
20
  import "../../market/index.js";
22
21
  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
  /**
@@ -1,9 +1,9 @@
1
- import { iRedemptionLoggerV310Abi } from "../../../abi/iRedemptionLoggerV310.js";
2
1
  import { BaseContract } from "../../base/BaseContract.js";
3
2
  import "../../base/index.js";
4
3
  import { sdkErr, sdkOk } from "../../../model/result.js";
5
4
  import "../../../model/index.js";
6
5
  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 { iWithdrawalCompressorV310Abi } from "../../../abi/IWithdrawalCompressorV310.js";
2
1
  import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
2
+ import { iWithdrawalCompressorV310Abi } from "../../../abi/IWithdrawalCompressorV310.js";
3
3
  //#region src/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.ts
4
4
  const abi = iWithdrawalCompressorV310Abi;
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { iWithdrawalCompressorV311Abi } from "../../../abi/IWithdrawalCompressorV311.js";
2
1
  import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
2
+ import { iWithdrawalCompressorV311Abi } from "../../../abi/IWithdrawalCompressorV311.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";
2
1
  import { encodeDelayedIntent } from "./intent-codec.js";
3
2
  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";
4
1
  import { AddressMap } from "../utils/AddressMap.js";
5
2
  import { AddressSet } from "../utils/AddressSet.js";
6
3
  import { bytes32ToString } from "../utils/bytes32ToString.js";
7
4
  import { getAssetType } from "../chain/chains.js";
8
5
  import { formatBN } from "../utils/formatter.js";
9
6
  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";
2
1
  import { AP_MARKET_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR } from "../constants/address-provider.js";
3
2
  import { isV310 } from "../constants/versions.js";
4
3
  import "../constants/index.js";
5
4
  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 = { Mainnet: {
@@ -212,6 +212,7 @@ import { checkPoolPaused } from "./validation/checks/checkPoolPaused.js";
212
212
  import { checkPoolSunset } from "./validation/checks/checkPoolSunset.js";
213
213
  import { checkQuotaCount } from "./validation/checks/checkQuotaCount.js";
214
214
  import { checkQuotaLimit } from "./validation/checks/checkQuotaLimit.js";
215
+ import { checkReservePriceLimited } from "./validation/checks/checkReservePriceLimited.js";
215
216
  import { checkAccountQuotas } from "./validation/bundles/checkAccountQuotas.js";
216
217
  import { checkWalletAllowance } from "./validation/bundles/checkWalletAllowance.js";
217
218
  import { checkWalletBalance } from "./validation/bundles/checkWalletBalance.js";
@@ -298,4 +299,4 @@ import { replayMulticall } from "./preview/preview/replayMulticall.js";
298
299
  import { previewOperation } from "./preview/preview/previewOperation.js";
299
300
  import "./preview/index.js";
300
301
  import "./types/index.js";
301
- 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_RWA_COMPRESSOR, 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, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountState, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DEGEN_NFT_MIDAS, DEGEN_NFT_SECURITIZE, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, 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, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, 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, 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, checkObtained, checkOperation, checkPoolFunding, checkPoolLiquidity, checkPoolOperation, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkRWAOpenRequirements, checkRWAOpening, 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, fetchRedstonePayloads, 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, 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, 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, usdToNumber, watchBlocksAsync };
302
+ 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_RWA_COMPRESSOR, 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, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountState, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DEGEN_NFT_MIDAS, DEGEN_NFT_SECURITIZE, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, 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, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, 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, 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, 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, fetchRedstonePayloads, 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, 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, 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, usdToNumber, watchBlocksAsync };
@@ -19,7 +19,7 @@ const adapterConstructorAbi = {
19
19
  ["INFINIFI_GATEWAY"]: { 310: BASIC_ADAPTER_ABI },
20
20
  ["LIDO_V1"]: { 310: BASIC_ADAPTER_ABI },
21
21
  ["LIDO_WSTETH_V1"]: { 310: BASIC_ADAPTER_ABI },
22
- ["MIDAS_GATEWAY"]: { 311: REFERER_ID_ADAPTER_ABI },
22
+ ["MIDAS_GATEWAY"]: { 311: BASIC_ADAPTER_ABI },
23
23
  ["MIDAS_REDEMPTION_VAULT"]: {
24
24
  310: BASIC_ADAPTER_ABI,
25
25
  311: BASIC_ADAPTER_ABI
@@ -1,5 +1,5 @@
1
- import { accountMigratorAbi } from "../../../../abi/AccountMigrator.js";
2
1
  import { AbstractAdapterContract } from "./AbstractAdapter.js";
2
+ import { accountMigratorAbi } from "../../../../abi/AccountMigrator.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";
2
1
  import { MissingSerializedParamsError } from "../../../base/errors.js";
3
2
  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";
2
1
  import { iCreditFacadeMulticallV310Abi, iCreditFacadeV310Abi } from "../../../abi/310/generated.js";
3
2
  import { BaseContract } from "../../base/BaseContract.js";
4
3
  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,
@@ -1,4 +1,3 @@
1
- import { iPausableAbi } from "../../../abi/iPausable.js";
2
1
  import { iPoolV310Abi } from "../../../abi/310/generated.js";
3
2
  import { AddressMap } from "../../utils/AddressMap.js";
4
3
  import { RAY } from "../../constants/math.js";
@@ -8,6 +7,7 @@ import "../../utils/index.js";
8
7
  import { SdkRWADataNotLoadedError } from "../../core/errors.js";
9
8
  import { BaseContract } from "../../base/BaseContract.js";
10
9
  import "../../base/index.js";
10
+ import { iPausableAbi } from "../../../abi/iPausable.js";
11
11
  //#region src/onchain/market/pool/PoolV310Contract.ts
12
12
  const abi = [...iPoolV310Abi, ...iPausableAbi];
13
13
  var PoolV310Contract = class extends BaseContract {
@@ -1,6 +1,6 @@
1
- import { iVersionAbi } from "../../../abi/iVersion.js";
2
1
  import { bytes32ToString } from "../../utils/bytes32ToString.js";
3
2
  import "../../utils/index.js";
3
+ import { iVersionAbi } from "../../../abi/iVersion.js";
4
4
  import { iMidasDegenNFTAbi } from "../../../abi/rwa/iMidasDegenNFT.js";
5
5
  import { DEGEN_NFT_MIDAS } from "./midas/constants.js";
6
6
  import { MidasDegenNFT } from "./midas/MidasDegenNFT.js";
@@ -1,5 +1,5 @@
1
- import { iethZapperAbi } from "../../../abi/iETHZapper.js";
2
1
  import { ZapperContract } from "./ZapperContract.js";
2
+ import { iethZapperAbi } from "../../../abi/iETHZapper.js";
3
3
  //#region src/onchain/market/zapper/IETHZapperContract.ts
4
4
  const abi = iethZapperAbi;
5
5
  var IETHZapperContract = class extends ZapperContract {
@@ -1,8 +1,8 @@
1
- import { iZapperAbi } from "../../../abi/iZapper.js";
2
1
  import { BaseContract } from "../../base/BaseContract.js";
3
2
  import "../../base/index.js";
4
3
  import { sdkErr, sdkOk } from "../../../model/result.js";
5
4
  import "../../../model/index.js";
5
+ import { iZapperAbi } from "../../../abi/iZapper.js";
6
6
  //#region src/onchain/market/zapper/ZapperContract.ts
7
7
  /**
8
8
  * Base contract for every Gearbox zapper. Specialized zappers (e.g.
@@ -1,8 +1,8 @@
1
- import { ierc20Abi } from "../../../abi/iERC20.js";
2
- import { iZapperAbi } from "../../../abi/iZapper.js";
3
1
  import { iPoolV310Abi } from "../../../abi/310/generated.js";
2
+ import { ierc20Abi } from "../../../abi/iERC20.js";
4
3
  import { sdkErr, sdkOk } from "../../../model/result.js";
5
4
  import "../../../model/index.js";
5
+ import { iZapperAbi } from "../../../abi/iZapper.js";
6
6
  //#region src/onchain/preview/preview/previewPoolPositionOperation.ts
7
7
  function previewRead(operation) {
8
8
  switch (operation.operation) {
@@ -1,6 +1,6 @@
1
1
  import { errorAbis } from "../../../abi/errors.js";
2
- import { iUpdatablePriceFeedAbi } from "../../../abi/iUpdatablePriceFeed.js";
3
2
  import { generateCastTraceCall } from "./cast.js";
3
+ import { iUpdatablePriceFeedAbi } from "../../../abi/iUpdatablePriceFeed.js";
4
4
  import { simulateMulticall } from "./simulateMulticall.js";
5
5
  import { BaseError, CallExecutionError, ContractFunctionRevertedError, decodeFunctionData, decodeFunctionResult, encodeFunctionData, parseAbi } from "viem";
6
6
  import { getAction, parseAccount } from "viem/utils";