@gearbox-protocol/sdk 16.0.0-next.12 → 16.0.0-next.13

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 (49) hide show
  1. package/dist/cjs/model/index.js +2 -1
  2. package/dist/cjs/model/positions.js +6 -0
  3. package/dist/cjs/model/positions.schema.js +2 -1
  4. package/dist/cjs/model/previews.js +4 -3
  5. package/dist/cjs/onchain/market/adapters/contracts/AbstractAdapter.js +14 -0
  6. package/dist/cjs/onchain/market/adapters/contracts/ERC4626AdapterContract.js +54 -0
  7. package/dist/cjs/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +13 -0
  8. package/dist/cjs/onchain/positions/PositionsService.js +20 -17
  9. package/dist/cjs/preview/preview/replayInnerOperations.js +10 -25
  10. package/dist/esm/dev/AccountOpener.js +1 -1
  11. package/dist/esm/dev/withdrawalUtils.js +1 -1
  12. package/dist/esm/model/index.js +3 -3
  13. package/dist/esm/model/positions.js +6 -1
  14. package/dist/esm/model/positions.schema.js +2 -1
  15. package/dist/esm/model/previews.js +4 -3
  16. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -2
  17. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  18. package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  19. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  20. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  21. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  22. package/dist/esm/onchain/base/TokensMeta.js +3 -3
  23. package/dist/esm/onchain/chain/detectNetwork.js +1 -1
  24. package/dist/esm/onchain/core/createAddressProvider.js +1 -1
  25. package/dist/esm/onchain/market/adapters/contracts/AbstractAdapter.js +14 -0
  26. package/dist/esm/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  27. package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +56 -2
  28. package/dist/esm/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +14 -1
  29. package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  30. package/dist/esm/onchain/market/pool/PoolV310Contract.js +1 -1
  31. package/dist/esm/onchain/market/zapper/IETHZapperContract.js +1 -1
  32. package/dist/esm/onchain/market/zapper/ZapperContract.js +1 -1
  33. package/dist/esm/onchain/pools/PoolService.js +1 -1
  34. package/dist/esm/onchain/positions/PositionsService.js +21 -18
  35. package/dist/esm/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
  36. package/dist/esm/preview/preview/replayInnerOperations.js +11 -26
  37. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  38. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  39. package/dist/types/model/index.d.ts +3 -3
  40. package/dist/types/model/positions.d.ts +13 -1
  41. package/dist/types/model/positions.schema.d.ts +2 -0
  42. package/dist/types/model/previews.d.ts +4 -3
  43. package/dist/types/onchain/market/adapters/contracts/AbstractAdapter.d.ts +12 -0
  44. package/dist/types/onchain/market/adapters/contracts/ERC4626AdapterContract.d.ts +8 -1
  45. package/dist/types/onchain/market/adapters/contracts/MidasGatewayAdapterContract.d.ts +7 -0
  46. package/package.json +1 -1
  47. package/dist/cjs/preview/preview/applyRWAWrapUnwrap.js +0 -67
  48. package/dist/esm/preview/preview/applyRWAWrapUnwrap.js +0 -66
  49. package/dist/types/preview/preview/applyRWAWrapUnwrap.d.ts +0 -17
@@ -5,10 +5,14 @@ import "../abi/adapters/index.js";
5
5
  import { iMidasGatewayV311Abi } from "../abi/midas/iMidasGatewayV311.js";
6
6
  import "../abi/index.js";
7
7
  import { AbstractAdapterContract } from "./AbstractAdapter.js";
8
- import { decodeAbiParameters, decodeFunctionData, isAddressEqual, zeroAddress } from "viem";
8
+ import { decodeAbiParameters, decodeFunctionData, encodeFunctionData, isAddressEqual, zeroAddress } from "viem";
9
9
  //#region src/onchain/market/adapters/contracts/MidasGatewayAdapterContract.ts
10
10
  const abi = iMidasGatewayAdapterV311Abi;
11
11
  const protocolAbi = iMidasGatewayV311Abi;
12
+ const receiveGreenlistCalldata = encodeFunctionData({
13
+ abi,
14
+ functionName: "receiveGreenlist"
15
+ });
12
16
  var MidasGatewayAdapterContract = class extends AbstractAdapterContract {
13
17
  #version;
14
18
  #gateway;
@@ -164,6 +168,15 @@ var MidasGatewayAdapterContract = class extends AbstractAdapterContract {
164
168
  const [redeemer] = decoded.args;
165
169
  return { redeemer };
166
170
  }
171
+ /**
172
+ * `receiveGreenlist()` is prepended by `prependMidasReceiveGreenlist`
173
+ * before the balance bracket when the multicall mints a permissioned
174
+ * mToken: it only greenlists the credit account and is balance-neutral,
175
+ * so it is legal outside a bracket and leaves balances untouched.
176
+ */
177
+ replayOutOfBracketCall(_balances, calldata) {
178
+ return calldata === receiveGreenlistCalldata;
179
+ }
167
180
  async applyBalanceChanges(balances, decoded) {
168
181
  switch (decoded.functionName) {
169
182
  case "depositInstantDiff": {
@@ -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,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,6 +1,6 @@
1
- import { iZapperAbi } from "../../../abi/iZapper.js";
2
1
  import { BaseContract } from "../../base/BaseContract.js";
3
2
  import "../../base/index.js";
3
+ import { iZapperAbi } from "../../../abi/iZapper.js";
4
4
  import { UnsupportedZapperFunctionError } from "./errors.js";
5
5
  //#region src/onchain/market/zapper/ZapperContract.ts
6
6
  /**
@@ -1,5 +1,5 @@
1
- import { ierc20Abi } from "../../abi/iERC20.js";
2
1
  import { AddressSet } from "../utils/AddressSet.js";
2
+ import { ierc20Abi } from "../../abi/iERC20.js";
3
3
  import "../constants/addresses.js";
4
4
  import { PERCENTAGE_FACTOR, RAY } from "../constants/math.js";
5
5
  import "../constants/index.js";
@@ -8,7 +8,7 @@ import "../base/index.js";
8
8
  import { bpsToRay, calcBorrowApy, calcPositionLeverage, healthFactorBps, usdToNumber } from "../market/math.js";
9
9
  import { strategyName } from "../market/strategyName.js";
10
10
  import { isFilterSet } from "../../model/filters.js";
11
- import { matchesPositionFilter } from "../../model/positions.js";
11
+ import { STRATEGY_POSITION_COLLATERAL_ERROR, matchesPositionFilter } from "../../model/positions.js";
12
12
  import "../../model/index.js";
13
13
  import { borrowRateAtUtilization, utilizationAfterLiquidityChange } from "../market/pool/math.js";
14
14
  import { calcBorrowRate } from "./calcBorrowRate.js";
@@ -63,12 +63,9 @@ var PositionsService = class extends SDKConstruct {
63
63
  **/
64
64
  async listStrategyPositions(props) {
65
65
  const { owner, includeZeroDebt, blockNumber } = props;
66
- const describable = (await this.sdk.accounts.getBorrowerCreditAccounts(owner, { includeZeroDebt }, blockNumber)).filter((ca) => {
67
- if (!ca.success) this.logger?.warn(`cannot describe position of ${this.labelAddress(ca.creditAccount)}: collateral computation failed`);
68
- return ca.success;
69
- });
70
- const withdrawals = await Promise.all(describable.map((ca) => this.#accountWithdrawals(ca, blockNumber)));
71
- return describable.map((ca, i) => this.#toStrategyPosition(ca, withdrawals[i] ?? new AddressMap()));
66
+ const accounts = await this.sdk.accounts.getBorrowerCreditAccounts(owner, { includeZeroDebt }, blockNumber);
67
+ const withdrawals = await Promise.all(accounts.map((ca) => this.#accountWithdrawals(ca, blockNumber)));
68
+ return accounts.map((ca, i) => this.#toStrategyPosition(ca, withdrawals[i] ?? new AddressMap()));
72
69
  }
73
70
  /**
74
71
  * Health factor of an account state, in basis points (`10000` = 1.0).
@@ -179,14 +176,11 @@ var PositionsService = class extends SDKConstruct {
179
176
  const token = market.underlyingToken;
180
177
  const totalDebtValue = ca.debt + ca.accruedInterest + ca.accruedFees;
181
178
  const target = getAccountTargetCollateral(ca.creditAccount, this.sdk.chainId) ?? suite.strategyTargetCollateral;
182
- const snapshot = accountSnapshotFromCreditAccountData(ca);
183
- const borrowRate = this.borrowRate(snapshot);
184
- const timeToLiquidation = this.timeToLiquidation(snapshot);
185
- const liquidationPrice = this.liquidationPrice(snapshot);
186
- const zeroDebt = ca.debt === 0n;
179
+ const priceFailed = !ca.success;
180
+ const recomputeTotals = ca.debt === 0n || priceFailed;
187
181
  const collaterals = [];
188
- let totalValue = zeroDebt ? 0n : ca.totalValue;
189
- let totalValueUSD = zeroDebt ? 0n : ca.totalValueUSD;
182
+ let totalValue = recomputeTotals ? 0n : ca.totalValue;
183
+ let totalValueUSD = recomputeTotals ? 0n : ca.totalValueUSD;
190
184
  for (const t of ca.tokens) {
191
185
  if (t.balance <= 10n) continue;
192
186
  collaterals.push({
@@ -194,13 +188,21 @@ var PositionsService = class extends SDKConstruct {
194
188
  quota: priceOracle.toTokenAmount(market.underlying, t.quota),
195
189
  withdrawals: withdrawals.get(t.token) ?? []
196
190
  });
197
- if (zeroDebt) {
191
+ if (recomputeTotals) {
198
192
  const value = priceOracle.safeConvert(t.token, market.underlying, t.balance) || 0n;
199
193
  totalValue += value;
200
194
  const usd = priceOracle.safeConvertToUSD(t.token, t.balance) || 0n;
201
195
  totalValueUSD += usd;
202
196
  }
203
197
  }
198
+ const snapshot = {
199
+ ...accountSnapshotFromCreditAccountData(ca),
200
+ totalValue
201
+ };
202
+ const borrowRate = this.borrowRate(snapshot);
203
+ const timeToLiquidation = this.timeToLiquidation(snapshot);
204
+ const liquidationPrice = this.liquidationPrice(snapshot);
205
+ const totalDebtUSD = priceFailed ? priceOracle.safeConvertToUSD(market.underlying, totalDebtValue) ?? 0n : ca.totalDebtUSD;
204
206
  return {
205
207
  kind: "strategy",
206
208
  chainId: this.sdk.chainId,
@@ -214,18 +216,19 @@ var PositionsService = class extends SDKConstruct {
214
216
  totalDebt: {
215
217
  token,
216
218
  value: totalDebtValue,
217
- valueUsd: usdToNumber(ca.totalDebtUSD)
219
+ valueUsd: usdToNumber(totalDebtUSD)
218
220
  },
219
221
  totalValue: {
220
222
  token,
221
223
  value: totalValue,
222
224
  valueUsd: usdToNumber(totalValueUSD)
223
225
  },
224
- healthFactor: healthFactorBps(ca.healthFactor),
226
+ healthFactor: priceFailed ? this.healthFactor(snapshot) : healthFactorBps(ca.healthFactor),
225
227
  borrowRate,
226
228
  timeToLiquidation,
227
229
  liquidationPrice,
228
- collaterals
230
+ collaterals,
231
+ ...priceFailed ? { error: STRATEGY_POSITION_COLLATERAL_ERROR } : {}
229
232
  };
230
233
  }
231
234
  /**
@@ -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";
@@ -1,11 +1,9 @@
1
1
  import { AssetsMap } from "../../onchain/utils/AssetsMap.js";
2
2
  import "../../onchain/constants/math.js";
3
3
  import { AbstractAdapterContract } from "../../onchain/market/adapters/contracts/AbstractAdapter.js";
4
- import { ERC4626AdapterContract } from "../../onchain/market/adapters/contracts/ERC4626AdapterContract.js";
5
- import { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP } from "../../model/previews.js";
4
+ import { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL } from "../../model/previews.js";
6
5
  import "../../model/index.js";
7
6
  import "../../onchain/index.js";
8
- import { applyRWAWrapUnwrap } from "./applyRWAWrapUnwrap.js";
9
7
  //#region src/preview/preview/replayInnerOperations.ts
10
8
  /**
11
9
  * Creates a {@link ReplayState} around the given account seed, with empty
@@ -93,26 +91,25 @@ function applyWithdrawCollateral(state, op) {
93
91
  *
94
92
  * Inside a bracket, the adapter's balance changes are previewed via
95
93
  * {@link AbstractAdapterContract.previewBalanceChanges}. Outside a bracket,
96
- * only RWA wrap/unwrap calls are allowed (see {@link applyRWAWrapUnwrap});
97
- * nothing enforces the outcome of any other out-of-bracket adapter call
98
- * on-chain, so its effect on balances cannot be previewed.
94
+ * only calls that {@link AbstractAdapterContract.replayOutOfBracketCall}
95
+ * accepts are allowed; nothing enforces the outcome of any other out-of-bracket
96
+ * adapter call on-chain, so its effect on balances cannot be previewed.
99
97
  */
100
98
  async function applyExecute(sdk, op, inBracket, balances) {
101
99
  const adapter = sdk.getContract(op.adapter);
102
100
  if (!inBracket) {
103
- if (!isRWAShare(sdk, adapter)) return {
104
- code: ERROR_ADAPTER_CALL_OUTSIDE_BRACKET,
105
- message: `call to ${op.adapter} outside of a storeExpectedBalances/compareBalances bracket`
106
- };
107
- try {
108
- applyRWAWrapUnwrap(adapter, op.calldata, balances);
109
- return;
101
+ if (adapter instanceof AbstractAdapterContract) try {
102
+ if (adapter.replayOutOfBracketCall(balances, op.calldata)) return;
110
103
  } catch (e) {
111
104
  return {
112
- code: ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP,
105
+ code: ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL,
113
106
  message: e instanceof Error ? e.message : String(e)
114
107
  };
115
108
  }
109
+ return {
110
+ code: ERROR_ADAPTER_CALL_OUTSIDE_BRACKET,
111
+ message: `call to ${op.adapter} outside of a storeExpectedBalances/compareBalances bracket`
112
+ };
116
113
  }
117
114
  if (!(adapter instanceof AbstractAdapterContract)) return {
118
115
  code: ERROR_NON_ADAPTER_CALL_IN_BRACKET,
@@ -128,17 +125,5 @@ async function applyExecute(sdk, op, inBracket, balances) {
128
125
  };
129
126
  }
130
127
  }
131
- /**
132
- * True when the ERC4626 adapter converts an RWA underlying, i.e. it is the
133
- * wrap/unwrap adapter of an RWA market rather than a regular vault strategy
134
- * adapter.
135
- */
136
- function isRWAShare(sdk, adapter) {
137
- if (adapter instanceof ERC4626AdapterContract) {
138
- const meta = sdk.tokensMeta.get(adapter.share);
139
- return !!meta && sdk.tokensMeta.isRWAUnderlying(meta);
140
- }
141
- return false;
142
- }
143
128
  //#endregion
144
129
  export { makeReplayState, replayInnerOperations };
@@ -1,5 +1,5 @@
1
- import { iZapperAbi } from "../../abi/iZapper.js";
2
1
  import { iPoolV310Abi } from "../../abi/310/generated.js";
2
+ import { iZapperAbi } from "../../abi/iZapper.js";
3
3
  import { asPreviewSimulationError } from "./errors.js";
4
4
  //#region src/preview/simulate/simulatePoolOperation.ts
5
5
  function previewRead(operation) {
@@ -1,6 +1,6 @@
1
- import { ierc20Abi } from "../../abi/iERC20.js";
2
1
  import { iCreditFacadeV310Abi } from "../../abi/310/generated.js";
3
2
  import { AddressMap } from "../../onchain/utils/AddressMap.js";
3
+ import { ierc20Abi } from "../../abi/iERC20.js";
4
4
  import "../../onchain/index.js";
5
5
  import { UnexpectedFacadeEventOrderError } from "./errors.js";
6
6
  import { getAddress, isAddressEqual, parseEventLogs } from "viem";
@@ -10,13 +10,13 @@ import { booleanParamSchema, encodeFlag, filterAllSchema, filterable } from "./f
10
10
  import { DelayedReceivedAsset, InstantReceivedAsset, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, ReceivedAsset, matchesLiquidatableAccountFilter } from "./liquidations.js";
11
11
  import { delayedReceivedAssetSchema, instantReceivedAssetSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionSchema, receivedAssetSchema } from "./liquidations.schema.js";
12
12
  import { ApyBreakdown, Opportunity, OpportunityBase, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, PointRewards, PointsProgram, PoolOpportunity, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, Rewards, StrategyOpportunity, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, TokenRewards, matchesOpportunityFilter, opportunityId, poolOpportunityId, strategyOpportunityId } from "./opportunities.js";
13
- import { BorrowRateBreakdown, PnlBreakdown, PointsProgramPnL, PointsRewardsPnL, PoolPosition, PoolPositionKey, PoolPositionRef, Position, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionTransaction, PositionTransactionKind, PositionsTotals, RewardsPnL, StrategyPosition, StrategyPositionKey, StrategyPositionRef, TokenQuotaRate, TokenRewardsPnL, liquidationPositionId, matchesPositionFilter, poolPositionId, positionId, strategyPositionId } from "./positions.js";
13
+ import { BorrowRateBreakdown, PnlBreakdown, PointsProgramPnL, PointsRewardsPnL, PoolPosition, PoolPositionKey, PoolPositionRef, Position, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionTransaction, PositionTransactionKind, PositionsTotals, RewardsPnL, STRATEGY_POSITION_COLLATERAL_ERROR, StrategyPosition, StrategyPositionKey, StrategyPositionRef, TokenQuotaRate, TokenRewardsPnL, liquidationPositionId, matchesPositionFilter, poolPositionId, positionId, strategyPositionId } from "./positions.js";
14
14
  import { Notice, NoticeKind, NoticeSubject } from "./notices.js";
15
15
  import { noticeKindSchema, noticeSchema } from "./notices.schema.js";
16
16
  import { apyBreakdownSchema, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pointRewardsSchema, pointsProgramSchema, poolOpportunityDetailSchema, poolOpportunityKeySchema, poolOpportunitySchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, rewardsSchema, strategyOpportunityDetailSchema, strategyOpportunityKeySchema, strategyOpportunitySchema, tokenRewardsSchema } from "./opportunities.schema.js";
17
17
  import { borrowRateBreakdownSchema, pnlBreakdownSchema, pointsProgramPnLSchema, pointsRewardsPnLSchema, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionKeySchema, positionKindSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionsTotalsSchema, rewardsPnLSchema, strategyPositionKeySchema, strategyPositionSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema } from "./positions.schema.js";
18
- import { AdjustCreditAccountPreview, CloseCreditAccountPreview, DelayedCreditAccountOperationPreview, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, InstantOperationPreview, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, PoolOperationPreview, PoolOperationType, PreviewOperationInput, PreviewOperationOptions, RepayCreditAccountPreview } from "./previews.js";
18
+ import { AdjustCreditAccountPreview, CloseCreditAccountPreview, DelayedCreditAccountOperationPreview, 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, InstantOperationPreview, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, PoolOperationPreview, PoolOperationType, PreviewOperationInput, PreviewOperationOptions, RepayCreditAccountPreview } from "./previews.js";
19
19
  import { amountSchema, assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, timestampSchema, tokenAmountSchema, tokenSchema, txCallSchema, underlyingTokenSchema } from "./primitives.schema.js";
20
20
  import { ChainFailed, ChainMetadata, ChainScoped, ChainSucceeded, DataResponse, DataSource, ResponseMetadata } from "./response.js";
21
21
  import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourceSchema, responseMetadataSchema, responseSchema } from "./response.schema.js";
22
- export { AdjustCreditAccountPreview, Amount, ApyBreakdown, Asset, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CloseCreditAccountPreview, CompareTag, CompareTolerance, Curator, CuratorName, DataResponse, DataSource, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedCreditAccountOperationPreview, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedWithdrawCollateralIntent, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, FILTER_ALL, FilterAll, Filterable, GridSampling, InstantOperationPreview, InstantReceivedAsset, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, Notice, NoticeKind, NoticeSubject, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationPreview, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionRef, Position, PositionChartMetric, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionTransaction, PositionTransactionKind, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, RepayCreditAccountPreview, ResponseMetadata, Rewards, RewardsPnL, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, amountSchema, apyBreakdownSchema, 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, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema };
22
+ export { AdjustCreditAccountPreview, Amount, ApyBreakdown, Asset, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CloseCreditAccountPreview, CompareTag, CompareTolerance, Curator, CuratorName, DataResponse, DataSource, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedCreditAccountOperationPreview, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedWithdrawCollateralIntent, 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, FilterAll, Filterable, GridSampling, InstantOperationPreview, InstantReceivedAsset, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, Notice, NoticeKind, NoticeSubject, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationPreview, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionRef, Position, PositionChartMetric, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionTransaction, PositionTransactionKind, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, RepayCreditAccountPreview, ResponseMetadata, Rewards, RewardsPnL, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, amountSchema, apyBreakdownSchema, 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, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema };
@@ -181,6 +181,11 @@ interface BorrowRateBreakdown {
181
181
  **/
182
182
  quotas: TokenQuotaRate[];
183
183
  }
184
+ /**
185
+ * Set on {@link StrategyPosition.error} when the account could not be fully
186
+ * valued (e.g. a dead price feed).
187
+ **/
188
+ declare const STRATEGY_POSITION_COLLATERAL_ERROR = "collateral computation failed";
184
189
  /**
185
190
  * An open credit account of a wallet.
186
191
  **/
@@ -316,6 +321,13 @@ interface StrategyPosition {
316
321
  * withdrawals.
317
322
  **/
318
323
  collaterals: PositionCollateral[];
324
+ /**
325
+ * Present when the account could not be fully valued (e.g. a dead price
326
+ * feed). Identity, balances, and debt principal are still filled; valued
327
+ * fields are best-effort. Set by either the chain compressor path or the
328
+ * backend.
329
+ **/
330
+ error?: string;
319
331
  }
320
332
  /**
321
333
  * A row of the positions list: anything a wallet holds in the protocol.
@@ -491,4 +503,4 @@ interface PositionTransaction {
491
503
  assets: TokenAmount[];
492
504
  }
493
505
  //#endregion
494
- export { BorrowRateBreakdown, PnlBreakdown, PointsProgramPnL, PointsRewardsPnL, PoolPosition, PoolPositionKey, PoolPositionRef, Position, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionTransaction, PositionTransactionKind, PositionsTotals, RewardsPnL, StrategyPosition, StrategyPositionKey, StrategyPositionRef, TokenQuotaRate, TokenRewardsPnL, liquidationPositionId, matchesPositionFilter, poolPositionId, positionId, strategyPositionId };
506
+ export { BorrowRateBreakdown, PnlBreakdown, PointsProgramPnL, PointsRewardsPnL, PoolPosition, PoolPositionKey, PoolPositionRef, Position, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionTransaction, PositionTransactionKind, PositionsTotals, RewardsPnL, STRATEGY_POSITION_COLLATERAL_ERROR, StrategyPosition, StrategyPositionKey, StrategyPositionRef, TokenQuotaRate, TokenRewardsPnL, liquidationPositionId, matchesPositionFilter, poolPositionId, positionId, strategyPositionId };
@@ -545,6 +545,7 @@ declare const strategyPositionSchema: z.ZodObject<{
545
545
  claimableAt: z.ZodOptional<z.ZodNumber>;
546
546
  }, z.core.$strip>>;
547
547
  }, z.core.$strip>>;
548
+ error: z.ZodOptional<z.ZodString>;
548
549
  }, z.core.$strip>;
549
550
  /**
550
551
  * {@link Position}
@@ -891,6 +892,7 @@ declare const positionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
891
892
  claimableAt: z.ZodOptional<z.ZodNumber>;
892
893
  }, z.core.$strip>>;
893
894
  }, z.core.$strip>>;
895
+ error: z.ZodOptional<z.ZodString>;
894
896
  }, z.core.$strip>, z.ZodObject<{
895
897
  kind: z.ZodLiteral<"liquidation">;
896
898
  name: z.ZodString;
@@ -64,9 +64,10 @@ declare const ERROR_NON_ADAPTER_CALL_IN_BRACKET = 1003;
64
64
  **/
65
65
  declare const ERROR_UNPREVIEWABLE_ADAPTER_CALL = 1004;
66
66
  /**
67
- * Out-of-bracket RWA wrap/unwrap calldata cannot be decoded
67
+ * An out-of-bracket adapter call that is allowed there (e.g. RWA wrap/unwrap)
68
+ * could not be decoded or replayed
68
69
  **/
69
- declare const ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP = 1005;
70
+ declare const ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL = 1005;
70
71
  /**
71
72
  * `msg.value` does not fit into the declared WETH collateral
72
73
  * Transactions can have arbitrary value, but the ones that we create
@@ -467,4 +468,4 @@ interface DelayedCreditAccountOperationPreview {
467
468
  */
468
469
  type OperationPreview = PoolOperationPreview | OpenCreditAccountPreview | AdjustCreditAccountPreview | CloseCreditAccountPreview | RepayCreditAccountPreview | DelayedCreditAccountOperationPreview;
469
470
  //#endregion
470
- export { AdjustCreditAccountPreview, CloseCreditAccountPreview, DelayedCreditAccountOperationPreview, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, InstantOperationPreview, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, PoolOperationPreview, PoolOperationType, PreviewOperationInput, PreviewOperationOptions, RepayCreditAccountPreview };
471
+ export { AdjustCreditAccountPreview, CloseCreditAccountPreview, DelayedCreditAccountOperationPreview, 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, InstantOperationPreview, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, PoolOperationPreview, PoolOperationType, PreviewOperationInput, PreviewOperationOptions, RepayCreditAccountPreview };
@@ -57,6 +57,18 @@ declare class AbstractAdapterContract<const abi extends Abi | readonly unknown[]
57
57
  * specific function) has no balance-changes support.
58
58
  */
59
59
  previewBalanceChanges(balances: AssetsMap, calldata: Hex): Promise<void>;
60
+ /**
61
+ * Replays this adapter call when it appears outside a
62
+ * storeExpectedBalances/compareBalances bracket, mutating `balances` in
63
+ * place, and returns `true` when the call is legal there.
64
+ *
65
+ * Base implementation returns `false`: nothing enforces the outcome of an
66
+ * out-of-bracket adapter call on-chain, so it cannot be previewed.
67
+ *
68
+ * @throws when the call is allowed outside a bracket but its calldata
69
+ * cannot be decoded
70
+ */
71
+ replayOutOfBracketCall(_balances: AssetsMap, _calldata: Hex): boolean;
60
72
  /**
61
73
  * Applies the balance changes of a decoded adapter call to the running
62
74
  * balances, mutating them in place. Overrides should express changes via
@@ -5,7 +5,7 @@ import { AbstractAdapterContract, ConcreteAdapterContractOptions } from "./Abstr
5
5
  import { OnchainSDK } from "../../../OnchainSDK.js";
6
6
  import "../../../utils/index.js";
7
7
  import "../../../base/index.js";
8
- import { Address, DecodeFunctionDataReturnType } from "viem";
8
+ import { Address, DecodeFunctionDataReturnType, Hex } from "viem";
9
9
  //#region src/onchain/market/adapters/contracts/ERC4626AdapterContract.d.ts
10
10
  declare const abi: readonly [{
11
11
  readonly type: "function";
@@ -682,6 +682,13 @@ declare class ERC4626AdapterContract extends AbstractAdapterContract<abi, protoc
682
682
  * @see https://github.com/Gearbox-protocol/charts_server/blob/master/core/operation_type_v3.go#L32-L38
683
683
  */
684
684
  classifyLegacyOperation(parsed: ParsedCallV2, transfers: Transfers): LegacyAdapterOperation;
685
+ /**
686
+ * Out-of-bracket calls are legal only on the RWA wrap/unwrap adapter (the
687
+ * share converts 1:1 with the vault asset, so no on-chain preview or
688
+ * slippage bracket is needed); a regular vault-strategy ERC4626 adapter
689
+ * keeps the base behavior and returns false.
690
+ */
691
+ replayOutOfBracketCall(balances: AssetsMap, calldata: Hex): boolean;
685
692
  protected applyBalanceChanges(balances: AssetsMap, decoded: DecodeFunctionDataReturnType<abi>): Promise<void>;
686
693
  }
687
694
  //#endregion
@@ -649,6 +649,13 @@ declare class MidasGatewayAdapterContract extends AbstractAdapterContract<abi, p
649
649
  * redemption from a redeemer contract.
650
650
  */
651
651
  parseDelayedWithdrawalClaim(calldata: Hex): DelayedWithdrawalClaim | undefined;
652
+ /**
653
+ * `receiveGreenlist()` is prepended by `prependMidasReceiveGreenlist`
654
+ * before the balance bracket when the multicall mints a permissioned
655
+ * mToken: it only greenlists the credit account and is balance-neutral,
656
+ * so it is legal outside a bracket and leaves balances untouched.
657
+ */
658
+ replayOutOfBracketCall(_balances: AssetsMap, calldata: Hex): boolean;
652
659
  protected applyBalanceChanges(balances: AssetsMap, decoded: DecodeFunctionDataReturnType<abi>): Promise<void>;
653
660
  }
654
661
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gearbox-protocol/sdk",
3
- "version": "16.0.0-next.12",
3
+ "version": "16.0.0-next.13",
4
4
  "description": "Gearbox SDK",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,67 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_abi_ierc4626Adapter = require("../../abi/ierc4626Adapter.js");
3
- let viem = require("viem");
4
- //#region src/preview/preview/applyRWAWrapUnwrap.ts
5
- /**
6
- * Maps the decoded adapter call to the conversion it performs. Diff variants
7
- * spend the running balance down to the calldata leftover, so their input
8
- * amount comes from `balances`. Returns `undefined` for functions we do not
9
- * handle (`mint`/`withdraw` are never emitted by the RWA flows).
10
- */
11
- function resolveWrapUnwrap(adapter, calldata, balances) {
12
- const decoded = (0, viem.decodeFunctionData)({
13
- abi: require_abi_ierc4626Adapter.ierc4626AdapterAbi,
14
- data: calldata
15
- });
16
- const { asset, share } = adapter;
17
- switch (decoded.functionName) {
18
- case "deposit": return {
19
- tokenIn: asset,
20
- tokenOut: share,
21
- amountIn: decoded.args[0]
22
- };
23
- case "depositDiff": {
24
- const [leftoverAmount] = decoded.args;
25
- const running = balances.getOrZero(asset);
26
- return {
27
- tokenIn: asset,
28
- tokenOut: share,
29
- amountIn: running > leftoverAmount ? running - leftoverAmount : 0n
30
- };
31
- }
32
- case "redeem": return {
33
- tokenIn: share,
34
- tokenOut: asset,
35
- amountIn: decoded.args[0]
36
- };
37
- case "redeemDiff": {
38
- const [leftoverAmount] = decoded.args;
39
- const running = balances.getOrZero(share);
40
- return {
41
- tokenIn: share,
42
- tokenOut: asset,
43
- amountIn: running > leftoverAmount ? running - leftoverAmount : 0n
44
- };
45
- }
46
- default: return;
47
- }
48
- }
49
- /**
50
- * Applies an RWA wrap/unwrap adapter call (ERC4626 `deposit`/`redeem` and
51
- * their diff variants, as emitted by `CreditAccountsServiceV310`) to the
52
- * running credit-account balances.
53
- *
54
- * RWA underlyings always convert 1-to-1 with their vault asset, so the
55
- * counterpart amount equals the input amount and no on-chain preview read is
56
- * needed.
57
- */
58
- function applyRWAWrapUnwrap(adapter, calldata, balances) {
59
- const resolved = resolveWrapUnwrap(adapter, calldata, balances);
60
- if (!resolved) return;
61
- const { tokenIn, tokenOut, amountIn } = resolved;
62
- if (amountIn === 0n) return;
63
- balances.dec(tokenIn, amountIn);
64
- balances.inc(tokenOut, amountIn);
65
- }
66
- //#endregion
67
- exports.applyRWAWrapUnwrap = applyRWAWrapUnwrap;
@@ -1,66 +0,0 @@
1
- import { ierc4626AdapterAbi } from "../../abi/ierc4626Adapter.js";
2
- import { decodeFunctionData } from "viem";
3
- //#region src/preview/preview/applyRWAWrapUnwrap.ts
4
- /**
5
- * Maps the decoded adapter call to the conversion it performs. Diff variants
6
- * spend the running balance down to the calldata leftover, so their input
7
- * amount comes from `balances`. Returns `undefined` for functions we do not
8
- * handle (`mint`/`withdraw` are never emitted by the RWA flows).
9
- */
10
- function resolveWrapUnwrap(adapter, calldata, balances) {
11
- const decoded = decodeFunctionData({
12
- abi: ierc4626AdapterAbi,
13
- data: calldata
14
- });
15
- const { asset, share } = adapter;
16
- switch (decoded.functionName) {
17
- case "deposit": return {
18
- tokenIn: asset,
19
- tokenOut: share,
20
- amountIn: decoded.args[0]
21
- };
22
- case "depositDiff": {
23
- const [leftoverAmount] = decoded.args;
24
- const running = balances.getOrZero(asset);
25
- return {
26
- tokenIn: asset,
27
- tokenOut: share,
28
- amountIn: running > leftoverAmount ? running - leftoverAmount : 0n
29
- };
30
- }
31
- case "redeem": return {
32
- tokenIn: share,
33
- tokenOut: asset,
34
- amountIn: decoded.args[0]
35
- };
36
- case "redeemDiff": {
37
- const [leftoverAmount] = decoded.args;
38
- const running = balances.getOrZero(share);
39
- return {
40
- tokenIn: share,
41
- tokenOut: asset,
42
- amountIn: running > leftoverAmount ? running - leftoverAmount : 0n
43
- };
44
- }
45
- default: return;
46
- }
47
- }
48
- /**
49
- * Applies an RWA wrap/unwrap adapter call (ERC4626 `deposit`/`redeem` and
50
- * their diff variants, as emitted by `CreditAccountsServiceV310`) to the
51
- * running credit-account balances.
52
- *
53
- * RWA underlyings always convert 1-to-1 with their vault asset, so the
54
- * counterpart amount equals the input amount and no on-chain preview read is
55
- * needed.
56
- */
57
- function applyRWAWrapUnwrap(adapter, calldata, balances) {
58
- const resolved = resolveWrapUnwrap(adapter, calldata, balances);
59
- if (!resolved) return;
60
- const { tokenIn, tokenOut, amountIn } = resolved;
61
- if (amountIn === 0n) return;
62
- balances.dec(tokenIn, amountIn);
63
- balances.inc(tokenOut, amountIn);
64
- }
65
- //#endregion
66
- export { applyRWAWrapUnwrap };
@@ -1,17 +0,0 @@
1
- import { AssetsMap } from "../../onchain/utils/AssetsMap.js";
2
- import { ERC4626AdapterContract } from "../../onchain/market/adapters/contracts/ERC4626AdapterContract.js";
3
- import "../../onchain/index.js";
4
- import { Hex } from "viem";
5
- //#region src/preview/preview/applyRWAWrapUnwrap.d.ts
6
- /**
7
- * Applies an RWA wrap/unwrap adapter call (ERC4626 `deposit`/`redeem` and
8
- * their diff variants, as emitted by `CreditAccountsServiceV310`) to the
9
- * running credit-account balances.
10
- *
11
- * RWA underlyings always convert 1-to-1 with their vault asset, so the
12
- * counterpart amount equals the input amount and no on-chain preview read is
13
- * needed.
14
- */
15
- declare function applyRWAWrapUnwrap(adapter: ERC4626AdapterContract, calldata: Hex, balances: AssetsMap): void;
16
- //#endregion
17
- export { applyRWAWrapUnwrap };