@gearbox-protocol/sdk 16.0.0-next.45 → 16.0.0-next.47

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 (71) hide show
  1. package/dist/cjs/model/index.js +1 -0
  2. package/dist/cjs/model/withdrawals.schema.js +7 -2
  3. package/dist/cjs/onchain/accounts/intents/index.js +38 -13
  4. package/dist/cjs/onchain/accounts/intents/tail.js +112 -5
  5. package/dist/cjs/onchain/index.js +0 -2
  6. package/dist/cjs/onchain/market/MarketSuite.js +9 -1
  7. package/dist/cjs/onchain/market/credit/CreditSuite.js +1 -2
  8. package/dist/cjs/onchain/market/pool/PoolV310Contract.js +25 -0
  9. package/dist/cjs/onchain/pools/PoolService.js +5 -40
  10. package/dist/cjs/onchain/pools/index.js +0 -2
  11. package/dist/cjs/onchain/positions/PositionsService.js +8 -2
  12. package/dist/cjs/preview/preview/previewPoolPositionOperation.js +31 -12
  13. package/dist/cjs/preview/simulate/index.js +1 -1
  14. package/dist/cjs/preview/simulate/simulateOperation.js +1 -1
  15. package/dist/cjs/preview/simulate/simulatePoolOperation.js +2 -0
  16. package/dist/cjs/sdk/prepare/PrepareApi.js +132 -82
  17. package/dist/esm/dev/AccountOpener.js +1 -1
  18. package/dist/esm/dev/withdrawalUtils.js +1 -1
  19. package/dist/esm/model/index.js +2 -2
  20. package/dist/esm/model/withdrawals.schema.js +7 -3
  21. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -2
  22. package/dist/esm/onchain/accounts/intents/index.js +38 -13
  23. package/dist/esm/onchain/accounts/intents/tail.js +112 -5
  24. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  25. package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  26. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  27. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  28. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  29. package/dist/esm/onchain/base/TokensMeta.js +3 -3
  30. package/dist/esm/onchain/core/createAddressProvider.js +1 -1
  31. package/dist/esm/onchain/index.js +2 -2
  32. package/dist/esm/onchain/market/MarketSuite.js +9 -1
  33. package/dist/esm/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  34. package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  35. package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  36. package/dist/esm/onchain/market/credit/CreditSuite.js +1 -2
  37. package/dist/esm/onchain/market/pool/PoolV310Contract.js +26 -1
  38. package/dist/esm/onchain/market/zapper/IETHZapperContract.js +1 -1
  39. package/dist/esm/onchain/market/zapper/ZapperContract.js +1 -1
  40. package/dist/esm/onchain/pools/PoolService.js +7 -40
  41. package/dist/esm/onchain/pools/index.js +2 -2
  42. package/dist/esm/onchain/positions/PositionsService.js +8 -2
  43. package/dist/esm/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
  44. package/dist/esm/preview/preview/previewPoolPositionOperation.js +33 -14
  45. package/dist/esm/preview/simulate/index.js +1 -1
  46. package/dist/esm/preview/simulate/simulateOperation.js +1 -1
  47. package/dist/esm/preview/simulate/simulatePoolOperation.js +2 -2
  48. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  49. package/dist/esm/sdk/prepare/PrepareApi.js +132 -82
  50. package/dist/types/model/index.d.ts +3 -3
  51. package/dist/types/model/positions.d.ts +4 -1
  52. package/dist/types/model/previews.d.ts +28 -12
  53. package/dist/types/model/withdrawals.d.ts +24 -5
  54. package/dist/types/model/withdrawals.schema.d.ts +21 -1
  55. package/dist/types/onchain/accounts/index.d.ts +2 -2
  56. package/dist/types/onchain/accounts/intents/index.d.ts +19 -11
  57. package/dist/types/onchain/accounts/intents/tail.d.ts +13 -3
  58. package/dist/types/onchain/accounts/intents/types.d.ts +74 -1
  59. package/dist/types/onchain/index.d.ts +3 -3
  60. package/dist/types/onchain/market/MarketSuite.d.ts +6 -0
  61. package/dist/types/onchain/market/pool/PoolV310Contract.d.ts +12 -0
  62. package/dist/types/onchain/market/pool/types.d.ts +18 -0
  63. package/dist/types/onchain/pools/PoolService.d.ts +1 -19
  64. package/dist/types/onchain/pools/index.d.ts +2 -2
  65. package/dist/types/preview/simulate/simulatePoolOperation.d.ts +18 -1
  66. package/dist/types/preview/simulate/types.d.ts +12 -4
  67. package/dist/types/sdk/index.d.ts +3 -3
  68. package/dist/types/sdk/prepare/PrepareApi.d.ts +8 -7
  69. package/dist/types/sdk/prepare/index.d.ts +3 -3
  70. package/dist/types/sdk/prepare/types.d.ts +87 -28
  71. package/package.json +1 -1
@@ -59,7 +59,7 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
59
59
  }));
60
60
  const creditAccount = await slice(sdk, position.creditAccount);
61
61
  if (!creditAccount) return require_model_result.sdkErr(require_sdk_prepare_errors.creditAccountNotFound(position.creditAccount));
62
- return planned(await service(sdk).finishIntent({
62
+ return finalized(await service(sdk).finishIntent({
63
63
  intent,
64
64
  claimable: toClaimableWithdrawal(params.claimable),
65
65
  creditAccount,
@@ -74,94 +74,106 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
74
74
  /**
75
75
  * {@inheritDoc IOpportunitiesPrepare.deposit}
76
76
  **/
77
- deposit(pool, params) {
78
- const chain = this.sdk.chain(pool.chainId);
79
- const { marketRegister, pools } = chain;
80
- const tokenIn = params.tokenIn ?? marketRegister.findByPool(pool.pool).pool.underlying;
81
- const tokenOut = lpRoute(params.tokenOut, () => pools.getDepositTokensOut(pool.pool, tokenIn));
82
- if (!tokenOut) return unroutable(chain, tokenIn, void 0);
83
- const state = pools.simulateDeposit({
84
- pool: pool.pool,
85
- amount: params.amount,
86
- tokenIn,
87
- tokenOut
88
- });
89
- const call = pools.addLiquidity({
90
- collateral: {
91
- token: state.tokenIn.token.address,
92
- balance: state.tokenIn.value
93
- },
94
- pool: pool.pool,
95
- wallet: params.wallet,
96
- meta: pools.getDepositMetadata(pool.pool, tokenIn, tokenOut)
97
- });
98
- if (!call) return unroutable(chain, tokenIn, tokenOut);
99
- return require_model_result.sdkOk({
100
- operations: [],
101
- state,
102
- calls: call.calls,
103
- ...stateBlock(chain)
104
- });
77
+ async deposit(pool, params) {
78
+ try {
79
+ const chain = await this.#chain(pool.chainId);
80
+ const { marketRegister, pools } = chain;
81
+ const tokenIn = params.tokenIn ?? marketRegister.findByPool(pool.pool).pool.underlying;
82
+ const tokenOut = lpRoute(params.tokenOut, () => pools.getDepositTokensOut(pool.pool, tokenIn));
83
+ if (!tokenOut) return unroutable(chain, tokenIn, void 0);
84
+ const state = pools.simulateDeposit({
85
+ pool: pool.pool,
86
+ amount: params.amount,
87
+ tokenIn,
88
+ tokenOut
89
+ });
90
+ const call = pools.addLiquidity({
91
+ collateral: {
92
+ token: state.tokenIn.token.address,
93
+ balance: state.tokenIn.value
94
+ },
95
+ pool: pool.pool,
96
+ wallet: params.wallet,
97
+ meta: pools.getDepositMetadata(pool.pool, tokenIn, tokenOut)
98
+ });
99
+ if (!call) return unroutable(chain, tokenIn, tokenOut);
100
+ return require_model_result.sdkOk({
101
+ operations: [],
102
+ state: await lpState(chain, pool.pool, params.wallet, state, { mints: state.tokenOut.value }),
103
+ calls: call.calls,
104
+ ...stateBlock(chain)
105
+ });
106
+ } catch (e) {
107
+ return require_model_result.sdkErr(require_sdk_prepare_errors.unexpectedFailure(e));
108
+ }
105
109
  }
106
110
  /**
107
111
  * {@inheritDoc IOpportunitiesPrepare.withdraw}
108
112
  **/
109
- withdraw(pool, params) {
110
- const chain = this.sdk.chain(pool.chainId);
111
- const { pools } = chain;
112
- const tokenIn = params.tokenIn ?? pool.pool;
113
- const tokenOut = lpRoute(params.tokenOut, () => pools.getWithdrawalTokensOut(pool.pool, tokenIn));
114
- if (!tokenOut) return unroutable(chain, tokenIn, void 0);
115
- const state = pools.simulateWithdraw({
116
- pool: pool.pool,
117
- amount: params.amount,
118
- tokenIn,
119
- tokenOut
120
- });
121
- const { calls } = pools.removeLiquidity({
122
- pool: pool.pool,
123
- amount: params.amount,
124
- wallet: params.wallet,
125
- permit: void 0,
126
- meta: pools.getWithdrawalMetadata(pool.pool, tokenIn, tokenOut),
127
- mode: "withdraw"
128
- });
129
- return require_model_result.sdkOk({
130
- operations: [],
131
- state,
132
- calls,
133
- ...stateBlock(chain)
134
- });
113
+ async withdraw(pool, params) {
114
+ try {
115
+ const chain = await this.#chain(pool.chainId);
116
+ const { pools } = chain;
117
+ const tokenIn = params.tokenIn ?? pool.pool;
118
+ const tokenOut = lpRoute(params.tokenOut, () => pools.getWithdrawalTokensOut(pool.pool, tokenIn));
119
+ if (!tokenOut) return unroutable(chain, tokenIn, void 0);
120
+ const state = pools.simulateWithdraw({
121
+ pool: pool.pool,
122
+ amount: params.amount,
123
+ tokenIn,
124
+ tokenOut
125
+ });
126
+ const { calls } = pools.removeLiquidity({
127
+ pool: pool.pool,
128
+ amount: params.amount,
129
+ wallet: params.wallet,
130
+ permit: void 0,
131
+ meta: pools.getWithdrawalMetadata(pool.pool, tokenIn, tokenOut),
132
+ mode: "withdraw"
133
+ });
134
+ return require_model_result.sdkOk({
135
+ operations: [],
136
+ state: await lpState(chain, pool.pool, params.wallet, state, { burns: state.tokenIn.value }),
137
+ calls,
138
+ ...stateBlock(chain)
139
+ });
140
+ } catch (e) {
141
+ return require_model_result.sdkErr(require_sdk_prepare_errors.unexpectedFailure(e));
142
+ }
135
143
  }
136
144
  /**
137
145
  * {@inheritDoc IOpportunitiesPrepare.redeem}
138
146
  **/
139
- redeem(pool, params) {
140
- const chain = this.sdk.chain(pool.chainId);
141
- const { pools } = chain;
142
- const tokenIn = params.tokenIn ?? pool.pool;
143
- const tokenOut = lpRoute(params.tokenOut, () => pools.getWithdrawalTokensOut(pool.pool, tokenIn));
144
- if (!tokenOut) return unroutable(chain, tokenIn, void 0);
145
- const state = pools.simulateRedeem({
146
- pool: pool.pool,
147
- amount: params.amount,
148
- tokenIn,
149
- tokenOut
150
- });
151
- const { calls } = pools.removeLiquidity({
152
- pool: pool.pool,
153
- amount: params.amount,
154
- wallet: params.wallet,
155
- permit: void 0,
156
- meta: pools.getWithdrawalMetadata(pool.pool, tokenIn, tokenOut),
157
- mode: "redeem"
158
- });
159
- return require_model_result.sdkOk({
160
- operations: [],
161
- state,
162
- calls,
163
- ...stateBlock(chain)
164
- });
147
+ async redeem(pool, params) {
148
+ try {
149
+ const chain = await this.#chain(pool.chainId);
150
+ const { pools } = chain;
151
+ const tokenIn = params.tokenIn ?? pool.pool;
152
+ const tokenOut = lpRoute(params.tokenOut, () => pools.getWithdrawalTokensOut(pool.pool, tokenIn));
153
+ if (!tokenOut) return unroutable(chain, tokenIn, void 0);
154
+ const state = pools.simulateRedeem({
155
+ pool: pool.pool,
156
+ amount: params.amount,
157
+ tokenIn,
158
+ tokenOut
159
+ });
160
+ const { calls } = pools.removeLiquidity({
161
+ pool: pool.pool,
162
+ amount: params.amount,
163
+ wallet: params.wallet,
164
+ permit: void 0,
165
+ meta: pools.getWithdrawalMetadata(pool.pool, tokenIn, tokenOut),
166
+ mode: "redeem"
167
+ });
168
+ return require_model_result.sdkOk({
169
+ operations: [],
170
+ state: await lpState(chain, pool.pool, params.wallet, state, { burns: state.tokenIn.value }),
171
+ calls,
172
+ ...stateBlock(chain)
173
+ });
174
+ } catch (e) {
175
+ return require_model_result.sdkErr(require_sdk_prepare_errors.unexpectedFailure(e));
176
+ }
165
177
  }
166
178
  /**
167
179
  * {@inheritDoc IOpportunitiesPrepare.openNewStrategy}
@@ -413,7 +425,7 @@ function toClaimableWithdrawal(claimable) {
413
425
  outputs: claimable.outputs.map((o) => ({
414
426
  token: o.token.address,
415
427
  amount: o.value,
416
- isDelayed: false
428
+ isDelayed: o.isDelayed
417
429
  })),
418
430
  claimCalls: [{
419
431
  target: claimable.claimCall.to,
@@ -470,6 +482,23 @@ function planned(result, at) {
470
482
  }
471
483
  /**
472
484
  * {@inheritDoc planned}
485
+ *
486
+ * A tail carries one thing the other results do not: whether the claim it was
487
+ * built on finished the withdrawal, or left part of it queued for another one.
488
+ **/
489
+ function finalized(result, at) {
490
+ if (!result.ok) return refusal(result);
491
+ const { operations, state, calls, remainder } = result;
492
+ return require_model_result.sdkOk({
493
+ operations,
494
+ state,
495
+ calls,
496
+ remainder,
497
+ ...at
498
+ });
499
+ }
500
+ /**
501
+ * {@inheritDoc planned}
473
502
  **/
474
503
  function opened(result, at) {
475
504
  return result.ok ? require_model_result.sdkOk({
@@ -512,6 +541,27 @@ function routed(result, at) {
512
541
  });
513
542
  }
514
543
  /**
544
+ * The pool's own numbers as the namespace reports them: the trade the service
545
+ * priced, the market it belongs to, and where the wallet's position lands.
546
+ *
547
+ * The position is measured in shares and converted once, rather than added up
548
+ * in underlying, so the figure is exactly what a later
549
+ * `sdk.positions.list()` will report — the same balance through the same rate.
550
+ * A withdrawal larger than the position floors at nothing: the transaction
551
+ * would revert long before it got there, and a negative holding is not a thing
552
+ * a screen can show.
553
+ **/
554
+ async function lpState(sdk, pool, wallet, simulation, moved) {
555
+ const market = sdk.marketRegister.findByPool(pool);
556
+ const poolContract = market.pool.pool;
557
+ const after = await poolContract.getShareBalance(wallet) + (moved.mints ?? -moved.burns);
558
+ return {
559
+ ...simulation,
560
+ curator: market.curator,
561
+ netValue: market.toUnderlyingAmount(poolContract.sharesToUnderlying(after > 0n ? after : 0n))
562
+ };
563
+ }
564
+ /**
515
565
  * A pool route the market does not offer, as the refusal a caller reads.
516
566
  *
517
567
  * `to` is absent where {@link lpRoute} found no output to name at all, which
@@ -1,5 +1,5 @@
1
- import { ierc20Abi } from "../abi/iERC20.js";
2
1
  import { iCreditFacadeV310Abi } from "../abi/310/generated.js";
2
+ import { ierc20Abi } from "../abi/iERC20.js";
3
3
  import { AddressMap } from "../onchain/utils/AddressMap.js";
4
4
  import { AddressSet } from "../onchain/utils/AddressSet.js";
5
5
  import { AssetsMap } from "../onchain/utils/AssetsMap.js";
@@ -1,6 +1,6 @@
1
- import { iWithdrawalCompressorV313Abi } from "../abi/IWithdrawalCompressorV313.js";
2
1
  import { getNetworkType } from "../onchain/chain/chains.js";
3
2
  import { getWithdrawalCompressorAddress } from "../onchain/accounts/withdrawal-compressor/addresses.js";
3
+ import { iWithdrawalCompressorV313Abi } from "../abi/IWithdrawalCompressorV313.js";
4
4
  import "../onchain/index.js";
5
5
  import { iMidasDataFeedAbi, iMidasRedemptionVaultAbi, midasGatewayAbi, midasRedeemerAbi, midasRedemptionVaultPhantomTokenAbi, securitizeRedeemerAbi, securitizeRedemptionGatewayAbi, securitizeRedemptionPhantomTokenAbi } from "./withdrawalAbi.js";
6
6
  import { erc20Abi, hexToString, parseAbi, parseEther } from "viem";
@@ -22,5 +22,5 @@ import "./response.js";
22
22
  import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourceSchema, responseMetadataSchema, responseSchema } from "./response.schema.js";
23
23
  import { isSDKError, sdkErr, sdkOk } from "./result.js";
24
24
  import "./withdrawals.js";
25
- import { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema } from "./withdrawals.schema.js";
26
- export { CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL, FILTER_ALL, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, amountSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, isSDKError, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema };
25
+ import { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema, withdrawalOutputAmountSchema } from "./withdrawals.schema.js";
26
+ export { CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL, FILTER_ALL, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, amountSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, isSDKError, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema, withdrawalOutputAmountSchema };
@@ -4,12 +4,16 @@ import { delayedIntentSchema } from "./delayed-intent.schema.js";
4
4
  import { z } from "zod/v4";
5
5
  //#region src/model/withdrawals.schema.ts
6
6
  /**
7
+ * {@link WithdrawalOutputAmount}
8
+ **/
9
+ const withdrawalOutputAmountSchema = tokenAmountSchema.extend({ isDelayed: z.boolean() });
10
+ /**
7
11
  * {@link PositionClaimableWithdrawal}
8
12
  **/
9
13
  const positionClaimableWithdrawalSchema = z.object({
10
14
  sourceToken: tokenSchema,
11
15
  withdrawalPhantomToken: tokenAmountSchema,
12
- outputs: z.array(tokenAmountSchema),
16
+ outputs: z.array(withdrawalOutputAmountSchema),
13
17
  claimCall: txCallSchema,
14
18
  redeemer: ZodAddress().optional(),
15
19
  intent: delayedIntentSchema.optional()
@@ -20,7 +24,7 @@ const positionClaimableWithdrawalSchema = z.object({
20
24
  const positionPendingWithdrawalSchema = z.object({
21
25
  sourceToken: tokenSchema,
22
26
  withdrawalPhantomToken: tokenSchema,
23
- expectedOutputs: z.array(tokenAmountSchema),
27
+ expectedOutputs: z.array(withdrawalOutputAmountSchema),
24
28
  claimableAt: timestampSchema,
25
29
  redeemer: ZodAddress().optional(),
26
30
  intent: delayedIntentSchema.optional()
@@ -33,4 +37,4 @@ const positionWithdrawalsSchema = z.object({
33
37
  pending: z.array(positionPendingWithdrawalSchema)
34
38
  });
35
39
  //#endregion
36
- export { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema };
40
+ export { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema, withdrawalOutputAmountSchema };
@@ -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";
@@ -45,21 +45,27 @@ var CreditAccountOperationsService = class extends SDKConstruct {
45
45
  }));
46
46
  }
47
47
  /**
48
- * Largest `WITHDRAW` amount (in underlying) the account can take out while
49
- * keeping leverage and staying inside the facade's debt band — the ceiling a
50
- * withdraw form should offer. Taking everything out is the same intent with
51
- * `MAX_UINT256` for an amount, and needs none of this arithmetic.
48
+ * Both ends of what a `WITHDRAW` can take out, in underlying: the largest
49
+ * partial withdrawal that keeps leverage and stays inside the facade's debt
50
+ * band, and the net value an exit hands over. They are reported together
51
+ * because a withdraw form needs both the range it may offer, and the one
52
+ * amount past it that is allowed — and because the distance between them is
53
+ * the account's own, not a constant a caller could assume.
52
54
  *
53
55
  * Takes no target health factor, unlike {@link maxWithdrawCollateral}: a
54
56
  * proportional withdrawal leaves the factor where it found it, and the
55
57
  * facade's `minDebt` is what bounds it.
56
58
  *
57
59
  * @param props - Account slice and the SDK holding its market
58
- * @returns Amount in underlying units; `0n` when nothing can leave
60
+ * @returns The two ceilings, see {@link WithdrawCeilings} for the gap between
61
+ * them
59
62
  */
60
63
  maxWithdraw(props) {
61
64
  const view = accountView(props.creditAccount, props.sdk);
62
- return maxProportionalWithdrawal(view, view.band);
65
+ return {
66
+ partial: maxProportionalWithdrawal(view, view.band),
67
+ exit: view.collateral > 0n ? view.collateral : 0n
68
+ };
63
69
  }
64
70
  /**
65
71
  * Debt a `REPAY` would have to cover to settle the account, in underlying
@@ -229,17 +235,36 @@ var CreditAccountOperationsService = class extends SDKConstruct {
229
235
  * whole tail: the tokens land on the account and only their quota has to
230
236
  * catch up.
231
237
  *
238
+ * A claim that brought only part of what the request queued — a legacy Mellow
239
+ * multivault, which pays out what it holds liquid and re-queues the rest — is
240
+ * served in proportion, and what it did not settle comes back as `remainder`:
241
+ * the withdrawal still in flight and the intent to finish it with.
242
+ *
232
243
  * @param props - The recorded intent, the account slice as it stands now, and
233
244
  * the matured claimable
234
- * @returns Shaped exactly like {@link startIntent}'s result, so both halves of
235
- * an operation are consumed the same way
245
+ * @returns Shaped exactly like {@link startIntent}'s result with the remainder
246
+ * beside it, so both halves of an operation are consumed the same way
236
247
  */
237
248
  async finishIntent(props) {
238
- return plain(await this.#preview(props, () => planTail({
239
- intent: props.intent,
240
- claimable: props.claimable,
241
- view: accountView(props.creditAccount, props.sdk)
242
- })));
249
+ let remainder;
250
+ const result = await this.#preview(props, () => {
251
+ const tail = planTail({
252
+ intent: props.intent,
253
+ claimable: props.claimable,
254
+ view: accountView(props.creditAccount, props.sdk)
255
+ });
256
+ remainder = tail.remainder;
257
+ return tail.steps;
258
+ });
259
+ if (!result.ok) return result;
260
+ const { operations, state, calls } = result;
261
+ return {
262
+ ok: true,
263
+ operations,
264
+ state,
265
+ calls,
266
+ remainder
267
+ };
243
268
  }
244
269
  /**
245
270
  * Previews opening a brand-new leveraged position.
@@ -1,4 +1,6 @@
1
1
  import { IntentPreviewError } from "../../validation/refusal.js";
2
+ import { toTokenAmount } from "../../validation/token.js";
3
+ import { toTargetDecimals } from "./utils/common.js";
2
4
  import { createOraclePaths } from "./utils/router-path.js";
3
5
  import { planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw } from "./plan.js";
4
6
  import { instantOutput } from "./operations.js";
@@ -12,6 +14,10 @@ import { accountView } from "./view.js";
12
14
  * Shared by the two callers that need it and must not disagree — the tail as
13
15
  * it is previewed days later against the account that really exists, and the
14
16
  * tail as it is projected the moment the request is made.
17
+ *
18
+ * A claim that brought only part of what was queued is served in proportion,
19
+ * see {@link partialTail}: the intent's payout and its repayment are cut to the
20
+ * share that arrived, and the rest of both is handed to the next claim.
15
21
  */
16
22
  function planTail(args) {
17
23
  const { intent, claimable, view } = args;
@@ -20,17 +26,118 @@ function planTail(args) {
20
26
  if (!output) throw new IntentPreviewError("insufficientSourceBalance", void 0, "finishIntent: the claim credits nothing to spend");
21
27
  return output;
22
28
  };
29
+ const queued = claimable.outputs.find((o) => o.isDelayed && o.amount > 0n);
30
+ if (queued) return partialTail({
31
+ intent,
32
+ claimable,
33
+ queued,
34
+ view
35
+ });
23
36
  switch (intent.type) {
24
- case "WITHDRAW_COLLATERAL": return planFinishWithdraw(intent, claimable, claimed(), view);
25
- case "DECREASE_LEVERAGE": return planFinishDecreaseLeverage(claimable, claimed(), view);
26
- case "CLOSE_ACCOUNT": return planFinishCloseAccount(intent, claimable, claimed(), view);
37
+ case "WITHDRAW_COLLATERAL": return whole(planFinishWithdraw(intent, claimable, claimed(), view));
38
+ case "DECREASE_LEVERAGE": return whole(planFinishDecreaseLeverage(claimable, claimed(), view));
39
+ case "CLOSE_ACCOUNT": return whole(planFinishCloseAccount(intent, claimable, claimed(), view));
27
40
  case "ADD_COLLATERAL":
28
41
  case "INCREASE_LEVERAGE":
29
42
  case "DEPOSIT":
30
- case "DEPOSIT_AND_INCREASE_LEVERAGE": return planFinishClaimOnly(claimable);
43
+ case "DEPOSIT_AND_INCREASE_LEVERAGE": return whole(planFinishClaimOnly(claimable));
31
44
  default: throw new Error(`${intent.type} - not implemented`);
32
45
  }
33
46
  }
47
+ const whole = (steps) => ({
48
+ steps,
49
+ remainder: void 0
50
+ });
51
+ /**
52
+ * The tail of a claim that settled only part of the withdrawal it matured.
53
+ *
54
+ * Only a legacy Mellow multivault answers one this way — it pays out what its
55
+ * subvaults hold liquid and queues the rest — and the engine cannot finish an
56
+ * intent it has been given a fraction of the funds for. So the fraction is what
57
+ * it serves: the payout and the repayment are cut in the proportion that
58
+ * arrived, which keeps the withdrawal at the fixed leverage it was asked for
59
+ * instead of paying the wallet out first and deleveraging a claim later, and
60
+ * the untouched half of each is carried to the next claim by the remainder.
61
+ *
62
+ * Two intents cannot be served in part at all. An exit sells the account whole,
63
+ * and it cannot while a withdrawal is in flight — the phantom is neither
64
+ * sellable nor transferable — so a partial claim only repays what it brought
65
+ * and the account is emptied by the claim that brings the last of it. A claim
66
+ * that credited nothing at all leaves nothing to spend, so it is taken alone:
67
+ * it is still worth sending, since it is what moves the queue.
68
+ */
69
+ function partialTail(args) {
70
+ const { intent, claimable, queued, view } = args;
71
+ const inFlight = toTokenAmount(view.sdk, queued.token, queued.amount);
72
+ const claimed = instantOutput(claimable.outputs);
73
+ if (!claimed) return {
74
+ steps: planFinishClaimOnly(claimable),
75
+ remainder: {
76
+ inFlight,
77
+ intent
78
+ }
79
+ };
80
+ switch (intent.type) {
81
+ case "WITHDRAW_COLLATERAL": {
82
+ const served = arrivedShare(claimed, queued, view.sdk);
83
+ const withdrawAmount = part(intent.withdrawAmount, served);
84
+ const debtRepaid = part(intent.debtRepaid, served);
85
+ return {
86
+ steps: planFinishWithdraw({
87
+ ...intent,
88
+ withdrawAmount,
89
+ debtRepaid
90
+ }, claimable, claimed, view),
91
+ remainder: {
92
+ inFlight,
93
+ intent: {
94
+ ...intent,
95
+ withdrawAmount: intent.withdrawAmount - withdrawAmount,
96
+ debtRepaid: intent.debtRepaid - debtRepaid
97
+ }
98
+ }
99
+ };
100
+ }
101
+ case "DECREASE_LEVERAGE":
102
+ case "CLOSE_ACCOUNT": return {
103
+ steps: planFinishDecreaseLeverage(claimable, claimed, view),
104
+ remainder: {
105
+ inFlight,
106
+ intent
107
+ }
108
+ };
109
+ case "ADD_COLLATERAL":
110
+ case "INCREASE_LEVERAGE":
111
+ case "DEPOSIT":
112
+ case "DEPOSIT_AND_INCREASE_LEVERAGE": return {
113
+ steps: planFinishClaimOnly(claimable),
114
+ remainder: {
115
+ inFlight,
116
+ intent
117
+ }
118
+ };
119
+ default: throw new Error(`${intent.type} - not implemented`);
120
+ }
121
+ }
122
+ /**
123
+ * How much of the redemption this claim was: what it credited, over that plus
124
+ * what it left queued.
125
+ *
126
+ * The phantom stands for its payout one for one — the same reading the request
127
+ * side takes when it names the claim it expects — so only the decimals of the
128
+ * two have to be reconciled before they can be added up.
129
+ */
130
+ function arrivedShare(claimed, queued, sdk) {
131
+ const rest = toTargetDecimals(queued.amount, queued.token, claimed.token, sdk);
132
+ return {
133
+ got: claimed.amount,
134
+ of: claimed.amount + rest
135
+ };
136
+ }
137
+ /** A share of an amount, rounded down: a tail never promises more than it has. */
138
+ function part(amount, share) {
139
+ return share.of > 0n ? amount * share.got / share.of : 0n;
140
+ }
34
141
  /**
35
142
  * Where a delayed intent ends up, worked out at the moment it is started.
36
143
  *
@@ -55,7 +162,7 @@ async function projectTail(args) {
55
162
  const queued = request.outputs.find((o) => o.isDelayed);
56
163
  if (!queued || !claim) throw new IntentPreviewError("noRecordedIntent", void 0, "projectTail: the request queued nothing to claim");
57
164
  const next = sliceAfter(creditAccount, delayed.afterRequest);
58
- const steps = planTail({
165
+ const { steps } = planTail({
59
166
  intent: delayed.record,
60
167
  claimable: projectedClaimable(request, queued.token, queued.amount, claim),
61
168
  view: accountView(next, sdk)
@@ -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: {