@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
@@ -155,3 +155,4 @@ exports.tokenSchema = require_model_primitives_schema.tokenSchema;
155
155
  exports.tolerance = require_model_compare_schema.tolerance;
156
156
  exports.txCallSchema = require_model_primitives_schema.txCallSchema;
157
157
  exports.underlyingTokenSchema = require_model_primitives_schema.underlyingTokenSchema;
158
+ exports.withdrawalOutputAmountSchema = require_model_withdrawals_schema.withdrawalOutputAmountSchema;
@@ -5,12 +5,16 @@ const require_model_delayed_intent_schema = require("./delayed-intent.schema.js"
5
5
  let zod_v4 = require("zod/v4");
6
6
  //#region src/model/withdrawals.schema.ts
7
7
  /**
8
+ * {@link WithdrawalOutputAmount}
9
+ **/
10
+ const withdrawalOutputAmountSchema = require_model_primitives_schema.tokenAmountSchema.extend({ isDelayed: zod_v4.z.boolean() });
11
+ /**
8
12
  * {@link PositionClaimableWithdrawal}
9
13
  **/
10
14
  const positionClaimableWithdrawalSchema = zod_v4.z.object({
11
15
  sourceToken: require_model_primitives_schema.tokenSchema,
12
16
  withdrawalPhantomToken: require_model_primitives_schema.tokenAmountSchema,
13
- outputs: zod_v4.z.array(require_model_primitives_schema.tokenAmountSchema),
17
+ outputs: zod_v4.z.array(withdrawalOutputAmountSchema),
14
18
  claimCall: require_model_primitives_schema.txCallSchema,
15
19
  redeemer: require_onchain_utils_zod.ZodAddress().optional(),
16
20
  intent: require_model_delayed_intent_schema.delayedIntentSchema.optional()
@@ -21,7 +25,7 @@ const positionClaimableWithdrawalSchema = zod_v4.z.object({
21
25
  const positionPendingWithdrawalSchema = zod_v4.z.object({
22
26
  sourceToken: require_model_primitives_schema.tokenSchema,
23
27
  withdrawalPhantomToken: require_model_primitives_schema.tokenSchema,
24
- expectedOutputs: zod_v4.z.array(require_model_primitives_schema.tokenAmountSchema),
28
+ expectedOutputs: zod_v4.z.array(withdrawalOutputAmountSchema),
25
29
  claimableAt: require_model_primitives_schema.timestampSchema,
26
30
  redeemer: require_onchain_utils_zod.ZodAddress().optional(),
27
31
  intent: require_model_delayed_intent_schema.delayedIntentSchema.optional()
@@ -37,3 +41,4 @@ const positionWithdrawalsSchema = zod_v4.z.object({
37
41
  exports.positionClaimableWithdrawalSchema = positionClaimableWithdrawalSchema;
38
42
  exports.positionPendingWithdrawalSchema = positionPendingWithdrawalSchema;
39
43
  exports.positionWithdrawalsSchema = positionWithdrawalsSchema;
44
+ exports.withdrawalOutputAmountSchema = withdrawalOutputAmountSchema;
@@ -46,21 +46,27 @@ var CreditAccountOperationsService = class extends require_onchain_base_SDKConst
46
46
  }));
47
47
  }
48
48
  /**
49
- * Largest `WITHDRAW` amount (in underlying) the account can take out while
50
- * keeping leverage and staying inside the facade's debt band — the ceiling a
51
- * withdraw form should offer. Taking everything out is the same intent with
52
- * `MAX_UINT256` for an amount, and needs none of this arithmetic.
49
+ * Both ends of what a `WITHDRAW` can take out, in underlying: the largest
50
+ * partial withdrawal that keeps leverage and stays inside the facade's debt
51
+ * band, and the net value an exit hands over. They are reported together
52
+ * because a withdraw form needs both the range it may offer, and the one
53
+ * amount past it that is allowed — and because the distance between them is
54
+ * the account's own, not a constant a caller could assume.
53
55
  *
54
56
  * Takes no target health factor, unlike {@link maxWithdrawCollateral}: a
55
57
  * proportional withdrawal leaves the factor where it found it, and the
56
58
  * facade's `minDebt` is what bounds it.
57
59
  *
58
60
  * @param props - Account slice and the SDK holding its market
59
- * @returns Amount in underlying units; `0n` when nothing can leave
61
+ * @returns The two ceilings, see {@link WithdrawCeilings} for the gap between
62
+ * them
60
63
  */
61
64
  maxWithdraw(props) {
62
65
  const view = require_onchain_accounts_intents_view.accountView(props.creditAccount, props.sdk);
63
- return require_onchain_accounts_intents_math.maxProportionalWithdrawal(view, view.band);
66
+ return {
67
+ partial: require_onchain_accounts_intents_math.maxProportionalWithdrawal(view, view.band),
68
+ exit: view.collateral > 0n ? view.collateral : 0n
69
+ };
64
70
  }
65
71
  /**
66
72
  * Debt a `REPAY` would have to cover to settle the account, in underlying
@@ -230,17 +236,36 @@ var CreditAccountOperationsService = class extends require_onchain_base_SDKConst
230
236
  * whole tail: the tokens land on the account and only their quota has to
231
237
  * catch up.
232
238
  *
239
+ * A claim that brought only part of what the request queued — a legacy Mellow
240
+ * multivault, which pays out what it holds liquid and re-queues the rest — is
241
+ * served in proportion, and what it did not settle comes back as `remainder`:
242
+ * the withdrawal still in flight and the intent to finish it with.
243
+ *
233
244
  * @param props - The recorded intent, the account slice as it stands now, and
234
245
  * the matured claimable
235
- * @returns Shaped exactly like {@link startIntent}'s result, so both halves of
236
- * an operation are consumed the same way
246
+ * @returns Shaped exactly like {@link startIntent}'s result with the remainder
247
+ * beside it, so both halves of an operation are consumed the same way
237
248
  */
238
249
  async finishIntent(props) {
239
- return plain(await this.#preview(props, () => require_onchain_accounts_intents_tail.planTail({
240
- intent: props.intent,
241
- claimable: props.claimable,
242
- view: require_onchain_accounts_intents_view.accountView(props.creditAccount, props.sdk)
243
- })));
250
+ let remainder;
251
+ const result = await this.#preview(props, () => {
252
+ const tail = require_onchain_accounts_intents_tail.planTail({
253
+ intent: props.intent,
254
+ claimable: props.claimable,
255
+ view: require_onchain_accounts_intents_view.accountView(props.creditAccount, props.sdk)
256
+ });
257
+ remainder = tail.remainder;
258
+ return tail.steps;
259
+ });
260
+ if (!result.ok) return result;
261
+ const { operations, state, calls } = result;
262
+ return {
263
+ ok: true,
264
+ operations,
265
+ state,
266
+ calls,
267
+ remainder
268
+ };
244
269
  }
245
270
  /**
246
271
  * Previews opening a brand-new leveraged position.
@@ -1,5 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_onchain_validation_refusal = require("../../validation/refusal.js");
3
+ const require_onchain_validation_token = require("../../validation/token.js");
4
+ const require_onchain_accounts_intents_utils_common = require("./utils/common.js");
3
5
  const require_onchain_accounts_intents_utils_router_path = require("./utils/router-path.js");
4
6
  const require_onchain_accounts_intents_plan = require("./plan.js");
5
7
  const require_onchain_accounts_intents_operations = require("./operations.js");
@@ -13,6 +15,10 @@ const require_onchain_accounts_intents_view = require("./view.js");
13
15
  * Shared by the two callers that need it and must not disagree — the tail as
14
16
  * it is previewed days later against the account that really exists, and the
15
17
  * tail as it is projected the moment the request is made.
18
+ *
19
+ * A claim that brought only part of what was queued is served in proportion,
20
+ * see {@link partialTail}: the intent's payout and its repayment are cut to the
21
+ * share that arrived, and the rest of both is handed to the next claim.
16
22
  */
17
23
  function planTail(args) {
18
24
  const { intent, claimable, view } = args;
@@ -21,17 +27,118 @@ function planTail(args) {
21
27
  if (!output) throw new require_onchain_validation_refusal.IntentPreviewError("insufficientSourceBalance", void 0, "finishIntent: the claim credits nothing to spend");
22
28
  return output;
23
29
  };
30
+ const queued = claimable.outputs.find((o) => o.isDelayed && o.amount > 0n);
31
+ if (queued) return partialTail({
32
+ intent,
33
+ claimable,
34
+ queued,
35
+ view
36
+ });
24
37
  switch (intent.type) {
25
- case "WITHDRAW_COLLATERAL": return require_onchain_accounts_intents_plan.planFinishWithdraw(intent, claimable, claimed(), view);
26
- case "DECREASE_LEVERAGE": return require_onchain_accounts_intents_plan.planFinishDecreaseLeverage(claimable, claimed(), view);
27
- case "CLOSE_ACCOUNT": return require_onchain_accounts_intents_plan.planFinishCloseAccount(intent, claimable, claimed(), view);
38
+ case "WITHDRAW_COLLATERAL": return whole(require_onchain_accounts_intents_plan.planFinishWithdraw(intent, claimable, claimed(), view));
39
+ case "DECREASE_LEVERAGE": return whole(require_onchain_accounts_intents_plan.planFinishDecreaseLeverage(claimable, claimed(), view));
40
+ case "CLOSE_ACCOUNT": return whole(require_onchain_accounts_intents_plan.planFinishCloseAccount(intent, claimable, claimed(), view));
28
41
  case "ADD_COLLATERAL":
29
42
  case "INCREASE_LEVERAGE":
30
43
  case "DEPOSIT":
31
- case "DEPOSIT_AND_INCREASE_LEVERAGE": return require_onchain_accounts_intents_plan.planFinishClaimOnly(claimable);
44
+ case "DEPOSIT_AND_INCREASE_LEVERAGE": return whole(require_onchain_accounts_intents_plan.planFinishClaimOnly(claimable));
32
45
  default: throw new Error(`${intent.type} - not implemented`);
33
46
  }
34
47
  }
48
+ const whole = (steps) => ({
49
+ steps,
50
+ remainder: void 0
51
+ });
52
+ /**
53
+ * The tail of a claim that settled only part of the withdrawal it matured.
54
+ *
55
+ * Only a legacy Mellow multivault answers one this way — it pays out what its
56
+ * subvaults hold liquid and queues the rest — and the engine cannot finish an
57
+ * intent it has been given a fraction of the funds for. So the fraction is what
58
+ * it serves: the payout and the repayment are cut in the proportion that
59
+ * arrived, which keeps the withdrawal at the fixed leverage it was asked for
60
+ * instead of paying the wallet out first and deleveraging a claim later, and
61
+ * the untouched half of each is carried to the next claim by the remainder.
62
+ *
63
+ * Two intents cannot be served in part at all. An exit sells the account whole,
64
+ * and it cannot while a withdrawal is in flight — the phantom is neither
65
+ * sellable nor transferable — so a partial claim only repays what it brought
66
+ * and the account is emptied by the claim that brings the last of it. A claim
67
+ * that credited nothing at all leaves nothing to spend, so it is taken alone:
68
+ * it is still worth sending, since it is what moves the queue.
69
+ */
70
+ function partialTail(args) {
71
+ const { intent, claimable, queued, view } = args;
72
+ const inFlight = require_onchain_validation_token.toTokenAmount(view.sdk, queued.token, queued.amount);
73
+ const claimed = require_onchain_accounts_intents_operations.instantOutput(claimable.outputs);
74
+ if (!claimed) return {
75
+ steps: require_onchain_accounts_intents_plan.planFinishClaimOnly(claimable),
76
+ remainder: {
77
+ inFlight,
78
+ intent
79
+ }
80
+ };
81
+ switch (intent.type) {
82
+ case "WITHDRAW_COLLATERAL": {
83
+ const served = arrivedShare(claimed, queued, view.sdk);
84
+ const withdrawAmount = part(intent.withdrawAmount, served);
85
+ const debtRepaid = part(intent.debtRepaid, served);
86
+ return {
87
+ steps: require_onchain_accounts_intents_plan.planFinishWithdraw({
88
+ ...intent,
89
+ withdrawAmount,
90
+ debtRepaid
91
+ }, claimable, claimed, view),
92
+ remainder: {
93
+ inFlight,
94
+ intent: {
95
+ ...intent,
96
+ withdrawAmount: intent.withdrawAmount - withdrawAmount,
97
+ debtRepaid: intent.debtRepaid - debtRepaid
98
+ }
99
+ }
100
+ };
101
+ }
102
+ case "DECREASE_LEVERAGE":
103
+ case "CLOSE_ACCOUNT": return {
104
+ steps: require_onchain_accounts_intents_plan.planFinishDecreaseLeverage(claimable, claimed, view),
105
+ remainder: {
106
+ inFlight,
107
+ intent
108
+ }
109
+ };
110
+ case "ADD_COLLATERAL":
111
+ case "INCREASE_LEVERAGE":
112
+ case "DEPOSIT":
113
+ case "DEPOSIT_AND_INCREASE_LEVERAGE": return {
114
+ steps: require_onchain_accounts_intents_plan.planFinishClaimOnly(claimable),
115
+ remainder: {
116
+ inFlight,
117
+ intent
118
+ }
119
+ };
120
+ default: throw new Error(`${intent.type} - not implemented`);
121
+ }
122
+ }
123
+ /**
124
+ * How much of the redemption this claim was: what it credited, over that plus
125
+ * what it left queued.
126
+ *
127
+ * The phantom stands for its payout one for one — the same reading the request
128
+ * side takes when it names the claim it expects — so only the decimals of the
129
+ * two have to be reconciled before they can be added up.
130
+ */
131
+ function arrivedShare(claimed, queued, sdk) {
132
+ const rest = require_onchain_accounts_intents_utils_common.toTargetDecimals(queued.amount, queued.token, claimed.token, sdk);
133
+ return {
134
+ got: claimed.amount,
135
+ of: claimed.amount + rest
136
+ };
137
+ }
138
+ /** A share of an amount, rounded down: a tail never promises more than it has. */
139
+ function part(amount, share) {
140
+ return share.of > 0n ? amount * share.got / share.of : 0n;
141
+ }
35
142
  /**
36
143
  * Where a delayed intent ends up, worked out at the moment it is started.
37
144
  *
@@ -56,7 +163,7 @@ async function projectTail(args) {
56
163
  const queued = request.outputs.find((o) => o.isDelayed);
57
164
  if (!queued || !claim) throw new require_onchain_validation_refusal.IntentPreviewError("noRecordedIntent", void 0, "projectTail: the request queued nothing to claim");
58
165
  const next = sliceAfter(creditAccount, delayed.afterRequest);
59
- const steps = planTail({
166
+ const { steps } = planTail({
60
167
  intent: delayed.record,
61
168
  claimable: projectedClaimable(request, queued.token, queued.amount, claim),
62
169
  view: require_onchain_accounts_intents_view.accountView(next, sdk)
@@ -704,8 +704,6 @@ exports.toCreditAccountSlice = require_onchain_accounts_intents_utils_credit_acc
704
704
  exports.toNetTransfers = require_onchain_market_adapters_transferHelpers.toNetTransfers;
705
705
  exports.toPendingWithdrawal = require_onchain_accounts_withdrawal_compressor_AbstractWithdrawalCompressorContract.toPendingWithdrawal;
706
706
  exports.toRequestableWithdrawal = require_onchain_accounts_withdrawal_compressor_AbstractWithdrawalCompressorContract.toRequestableWithdrawal;
707
- exports.toShares = require_onchain_pools_PoolService.toShares;
708
- exports.toSharesUp = require_onchain_pools_PoolService.toSharesUp;
709
707
  exports.toSignificant = require_onchain_utils_formatter.toSignificant;
710
708
  exports.toToken = require_onchain_validation_token.toToken;
711
709
  exports.toTokenAmount = require_onchain_validation_token.toTokenAmount;
@@ -128,6 +128,14 @@ var MarketSuite = class extends require_onchain_base_SDKConstruct.SDKConstruct {
128
128
  };
129
129
  }
130
130
  /**
131
+ * Whether `token` is this market's pool underlying or the asset it wraps
132
+ * (dcUSDC or USDC on an RWA pool). Amounts in either unit are 1:1 with the
133
+ * figure {@link toUnderlyingAmount} reports.
134
+ */
135
+ isUnderlyingLike(token) {
136
+ return (0, viem.isAddressEqual)(token, this.underlying) || (0, viem.isAddressEqual)(token, this.unwrappedUnderlying);
137
+ }
138
+ /**
131
139
  * Prices a figure already denominated in this market's underlying — a debt,
132
140
  * a TVL, a payout — as the read model reports one.
133
141
  *
@@ -166,7 +174,7 @@ var MarketSuite = class extends require_onchain_base_SDKConstruct.SDKConstruct {
166
174
  seen.upsert(this.unwrappedUnderlying, this.underlyingToken);
167
175
  for (const zapper of this.sdk.marketRegister.poolZappers(this.pool.pool.address)) {
168
176
  const tokenIn = zapper.tokenIn.addr;
169
- if ((0, viem.isAddressEqual)(tokenIn, this.pool.underlying) || (0, viem.isAddressEqual)(tokenIn, this.unwrappedUnderlying)) continue;
177
+ if (this.isUnderlyingLike(tokenIn)) continue;
170
178
  seen.upsert(tokenIn, this.tokensMeta.mustGetToken(tokenIn));
171
179
  }
172
180
  return seen.values();
@@ -392,8 +392,7 @@ var CreditSuite = class extends require_onchain_base_SDKConstruct.SDKConstruct {
392
392
  */
393
393
  #allowedDepositTokens(targetCollateral) {
394
394
  const unwrappedUnderlying = this.market.unwrappedUnderlying;
395
- const contractUnderlying = this.underlying;
396
- const skip = (token) => (0, viem.isAddressEqual)(token, unwrappedUnderlying) || (0, viem.isAddressEqual)(token, contractUnderlying) || (0, viem.isAddressEqual)(token, targetCollateral);
395
+ const skip = (token) => this.market.isUnderlyingLike(token) || (0, viem.isAddressEqual)(token, targetCollateral);
397
396
  return [
398
397
  unwrappedUnderlying,
399
398
  targetCollateral,
@@ -51,6 +51,31 @@ var PoolV310Contract = class extends require_onchain_base_BaseContract.BaseContr
51
51
  return this.totalSupply * this.dieselRate / require_onchain_constants_math.RAY;
52
52
  }
53
53
  /**
54
+ * {@inheritDoc IPoolContract.getShareBalance}
55
+ */
56
+ async getShareBalance(wallet, blockNumber) {
57
+ return this.client.readContract({
58
+ address: this.address,
59
+ abi: this.abi,
60
+ functionName: "balanceOf",
61
+ args: [wallet],
62
+ blockNumber
63
+ });
64
+ }
65
+ /**
66
+ * {@inheritDoc IPoolContract.sharesToUnderlying}
67
+ */
68
+ sharesToUnderlying(shares) {
69
+ return this.dieselRate === 0n ? shares : shares * this.dieselRate / require_onchain_constants_math.RAY;
70
+ }
71
+ /**
72
+ * {@inheritDoc IPoolContract.underlyingToShares}
73
+ */
74
+ underlyingToShares(underlying, roundUp = false) {
75
+ if (this.dieselRate === 0n) return underlying;
76
+ return roundUp ? (underlying * require_onchain_constants_math.RAY + this.dieselRate - 1n) / this.dieselRate : underlying * require_onchain_constants_math.RAY / this.dieselRate;
77
+ }
78
+ /**
54
79
  * {@inheritDoc IPoolContract.unwrappedUnderlying}
55
80
  */
56
81
  get unwrappedUnderlying() {
@@ -146,7 +146,7 @@ var PoolService = class extends require_onchain_base_SDKConstruct.SDKConstruct {
146
146
  const { zapper } = this.getDepositMetadata(poolAddr, tokenIn, tokenOut);
147
147
  return {
148
148
  tokenIn: toTokenAmount(tokenIn, amount),
149
- tokenOut: toTokenAmount(tokenOut, toShares(pool.pool, amount)),
149
+ tokenOut: toTokenAmount(tokenOut, pool.pool.underlyingToShares(amount)),
150
150
  zapper: zapper?.baseParams.addr
151
151
  };
152
152
  }
@@ -166,7 +166,7 @@ var PoolService = class extends require_onchain_base_SDKConstruct.SDKConstruct {
166
166
  });
167
167
  const { zapper } = this.getWithdrawalMetadata(poolAddr, tokenIn, tokenOut);
168
168
  return {
169
- tokenIn: toTokenAmount(tokenIn, toSharesUp(pool.pool, amount)),
169
+ tokenIn: toTokenAmount(tokenIn, pool.pool.underlyingToShares(amount * require_onchain_constants_math.PERCENTAGE_FACTOR / (require_onchain_constants_math.PERCENTAGE_FACTOR - pool.pool.withdrawFee), true)),
170
170
  tokenOut: toTokenAmount(tokenOut, amount),
171
171
  zapper: zapper?.baseParams.addr,
172
172
  availableLiquidity: payoutCeiling(market)
@@ -189,7 +189,7 @@ var PoolService = class extends require_onchain_base_SDKConstruct.SDKConstruct {
189
189
  const { zapper } = this.getWithdrawalMetadata(poolAddr, tokenIn, tokenOut);
190
190
  return {
191
191
  tokenIn: toTokenAmount(tokenIn, amount),
192
- tokenOut: toTokenAmount(tokenOut, toAssets(pool.pool, amount)),
192
+ tokenOut: toTokenAmount(tokenOut, pool.pool.sharesToUnderlying(amount) * (require_onchain_constants_math.PERCENTAGE_FACTOR - pool.pool.withdrawFee) / require_onchain_constants_math.PERCENTAGE_FACTOR),
193
193
  zapper: zapper?.baseParams.addr,
194
194
  availableLiquidity: payoutCeiling(market)
195
195
  };
@@ -221,7 +221,7 @@ var PoolService = class extends require_onchain_base_SDKConstruct.SDKConstruct {
221
221
  }
222
222
  const poolContract = this.sdk.marketRegister.findByPool(pool).pool.pool;
223
223
  if (meta.zapper instanceof require_onchain_market_zapper_IETHZapperContract.IETHZapperContract || meta.zapper instanceof require_onchain_market_zapper_IERC20ZapperContract.IERC20ZapperContract) {
224
- const shares = mode === "withdraw" ? toSharesUp(poolContract, amount) : amount;
224
+ const shares = mode === "withdraw" ? poolContract.underlyingToShares(amount * require_onchain_constants_math.PERCENTAGE_FACTOR / (require_onchain_constants_math.PERCENTAGE_FACTOR - poolContract.withdrawFee), true) : amount;
225
225
  const tx = permit ? meta.zapper.redeemWithPermit(shares, wallet, permit.deadline, permit.v, permit.r, permit.s) : meta.zapper.redeem(shares, wallet);
226
226
  return {
227
227
  tx,
@@ -415,45 +415,10 @@ var PoolService = class extends require_onchain_base_SDKConstruct.SDKConstruct {
415
415
  chainId: this.chainId,
416
416
  pool: pool.address,
417
417
  underlyingToken: market.underlyingToken,
418
- netValue: {
419
- token: this.sdk.tokensMeta.mustGetToken(market.unwrappedUnderlying),
420
- ...market.priceOracle.toAmount(market.underlying, shares * pool.dieselRate / require_onchain_constants_math.RAY)
421
- },
418
+ netValue: market.toUnderlyingAmount(pool.sharesToUnderlying(shares)),
422
419
  apy: { organicApy: require_onchain_market_math.rayToBps(pool.supplyRate) }
423
420
  };
424
421
  }
425
422
  };
426
- /**
427
- * Shares minted for `assets`, as `previewDeposit` would report them.
428
- *
429
- * Both directions convert through the diesel rate — underlying per RAY of
430
- * shares — because that is the rate the pool itself divides by, and the only
431
- * exact one the SDK holds: `totalAssets` is this rate multiplied out, so
432
- * converting back through it costs a wei on large amounts. Rounds down, as
433
- * minting does.
434
- */
435
- function toShares(pool, assets) {
436
- const { dieselRate } = pool;
437
- return dieselRate === 0n ? assets : assets * require_onchain_constants_math.RAY / dieselRate;
438
- }
439
- /**
440
- * Shares a withdrawal of `assets` burns, as `previewWithdraw` would report
441
- * them: {@link toShares} rounded the other way, since the burn has to cover
442
- * the payout the caller asked for.
443
- */
444
- function toSharesUp(pool, assets) {
445
- const { dieselRate } = pool;
446
- return dieselRate === 0n ? assets : (assets * require_onchain_constants_math.RAY + dieselRate - 1n) / dieselRate;
447
- }
448
- /**
449
- * Underlying paid out for `shares`, as `previewRedeem` would report it:
450
- * {@link toShares} run backwards, less the pool's withdrawal fee.
451
- */
452
- function toAssets(pool, shares) {
453
- const { dieselRate, withdrawFee } = pool;
454
- return (dieselRate === 0n ? shares : shares * dieselRate / require_onchain_constants_math.RAY) * (require_onchain_constants_math.PERCENTAGE_FACTOR - withdrawFee) / require_onchain_constants_math.PERCENTAGE_FACTOR;
455
- }
456
423
  //#endregion
457
424
  exports.PoolService = PoolService;
458
- exports.toShares = toShares;
459
- exports.toSharesUp = toSharesUp;
@@ -2,5 +2,3 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_onchain_pools_PoolService = require("./PoolService.js");
3
3
  require("./types.js");
4
4
  exports.PoolService = require_onchain_pools_PoolService.PoolService;
5
- exports.toShares = require_onchain_pools_PoolService.toShares;
6
- exports.toSharesUp = require_onchain_pools_PoolService.toSharesUp;
@@ -373,7 +373,10 @@ var PositionsService = class extends require_onchain_base_SDKConstruct.SDKConstr
373
373
  return {
374
374
  sourceToken: this.sdk.tokensMeta.mustGetToken(w.token),
375
375
  withdrawalPhantomToken: priceOracle.toTokenAmount(w.withdrawalPhantomToken, w.withdrawalTokenSpent),
376
- outputs: w.outputs.map((o) => priceOracle.toTokenAmount(o.token, o.amount)),
376
+ outputs: w.outputs.map((o) => ({
377
+ ...priceOracle.toTokenAmount(o.token, o.amount),
378
+ isDelayed: o.isDelayed
379
+ })),
377
380
  claimCall: this.#claimTx(w.claimCalls, w.token),
378
381
  redeemer: w.redeemer,
379
382
  intent: w.intent
@@ -383,7 +386,10 @@ var PositionsService = class extends require_onchain_base_SDKConstruct.SDKConstr
383
386
  return {
384
387
  sourceToken: this.sdk.tokensMeta.mustGetToken(w.token),
385
388
  withdrawalPhantomToken: this.sdk.tokensMeta.mustGetToken(w.withdrawalPhantomToken),
386
- expectedOutputs: w.expectedOutputs.map((o) => priceOracle.toTokenAmount(o.token, o.amount)),
389
+ expectedOutputs: w.expectedOutputs.map((o) => ({
390
+ ...priceOracle.toTokenAmount(o.token, o.amount),
391
+ isDelayed: o.isDelayed
392
+ })),
387
393
  claimableAt: Number(w.claimableAt),
388
394
  redeemer: w.redeemer,
389
395
  intent: w.intent
@@ -1,29 +1,48 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_abi_iERC20 = require("../../abi/iERC20.js");
2
3
  const require_model_result = require("../../model/result.js");
3
4
  require("../../model/index.js");
5
+ const require_preview_simulate_errors = require("../simulate/errors.js");
4
6
  const require_preview_simulate_simulatePoolOperation = require("../simulate/simulatePoolOperation.js");
5
- require("../simulate/index.js");
6
7
  //#region src/preview/preview/previewPoolPositionOperation.ts
7
8
  async function previewPoolPositionOperation(input, operation, options) {
8
- const { sdk, to, calldata } = input;
9
+ const { sdk } = input;
9
10
  const { tokenIn, tokenOut } = operation;
10
11
  const market = sdk.marketRegister.findByPool(operation.pool);
11
- const answer = await require_preview_simulate_simulatePoolOperation.simulatePoolOperation({
12
- sdk,
13
- operation,
14
- to,
15
- calldata
16
- }, options);
17
- if (require_model_result.isSDKError(answer)) return answer;
18
- const sim = answer.data;
12
+ const pool = market.pool.pool;
13
+ const holder = "owner" in operation ? operation.owner : operation.receiver;
14
+ let previewAmount;
15
+ let shares;
16
+ try {
17
+ [previewAmount, shares] = await sdk.client.multicall({
18
+ contracts: [require_preview_simulate_simulatePoolOperation.previewContract(operation), {
19
+ address: operation.pool,
20
+ abi: require_abi_iERC20.ierc20Abi,
21
+ functionName: "balanceOf",
22
+ args: [holder]
23
+ }],
24
+ allowFailure: false,
25
+ batchSize: 0,
26
+ blockNumber: options?.blockNumber
27
+ });
28
+ } catch (cause) {
29
+ const error = require_preview_simulate_errors.asPreviewSimulationError(cause, "multicall");
30
+ options?.logger?.error(error, "pool operation simulation failed");
31
+ return require_model_result.sdkErr(error);
32
+ }
33
+ const sim = require_preview_simulate_simulatePoolOperation.amountsInOut(operation, previewAmount);
34
+ const inflow = operation.operation === "Deposit" || operation.operation === "Mint";
35
+ const after = shares + (inflow ? sim.amountOut : -sim.amountIn);
19
36
  return require_model_result.sdkOk({
20
37
  operation: operation.operation,
21
38
  pool: operation.pool,
22
39
  name: sdk.tokensMeta.mustGetToken(operation.pool).name,
23
40
  underlyingToken: market.underlyingToken,
24
- shareRate: market.pool.pool.dieselRate,
41
+ shareRate: pool.dieselRate,
25
42
  tokenIn: market.priceOracle.toTokenAmount(tokenIn, sim.amountIn),
26
- tokenOut: market.priceOracle.toTokenAmount(tokenOut, sim.amountOut)
43
+ tokenOut: market.priceOracle.toTokenAmount(tokenOut, sim.amountOut),
44
+ curator: market.curator,
45
+ netValue: market.toUnderlyingAmount(pool.sharesToUnderlying(after > 0n ? after : 0n))
27
46
  });
28
47
  }
29
48
  //#endregion
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_preview_simulate_errors = require("./errors.js");
3
- const require_preview_simulate_simulateFacadeOperation = require("./simulateFacadeOperation.js");
4
3
  const require_preview_simulate_simulatePoolOperation = require("./simulatePoolOperation.js");
4
+ const require_preview_simulate_simulateFacadeOperation = require("./simulateFacadeOperation.js");
5
5
  const require_preview_simulate_simulateRWAOperation = require("./simulateRWAOperation.js");
6
6
  const require_preview_simulate_simulateOperation = require("./simulateOperation.js");
7
7
  exports.asPreviewSimulationError = require_preview_simulate_errors.asPreviewSimulationError;
@@ -3,8 +3,8 @@ const require_model_result = require("../../model/result.js");
3
3
  require("../../model/index.js");
4
4
  const require_preview_parse_types = require("../parse/types.js");
5
5
  require("../parse/index.js");
6
- const require_preview_simulate_simulateFacadeOperation = require("./simulateFacadeOperation.js");
7
6
  const require_preview_simulate_simulatePoolOperation = require("./simulatePoolOperation.js");
7
+ const require_preview_simulate_simulateFacadeOperation = require("./simulateFacadeOperation.js");
8
8
  const require_preview_simulate_simulateRWAOperation = require("./simulateRWAOperation.js");
9
9
  //#region src/preview/simulate/simulateOperation.ts
10
10
  /**
@@ -104,4 +104,6 @@ async function simulatePoolOperation(input, options = {}) {
104
104
  }
105
105
  }
106
106
  //#endregion
107
+ exports.amountsInOut = amountsInOut;
108
+ exports.previewContract = previewContract;
107
109
  exports.simulatePoolOperation = simulatePoolOperation;