@morpho-org/morpho-sdk 6.0.0-next.0 → 6.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/MIGRATION-v5-to-v6.md +206 -3
  2. package/README.md +81 -41
  3. package/lib/cjs/abis.d.ts +210 -0
  4. package/lib/cjs/abis.js +142 -2
  5. package/lib/cjs/actions/blue/borrow.d.ts +1 -1
  6. package/lib/cjs/actions/blue/borrow.js +1 -1
  7. package/lib/cjs/actions/blue/common.d.ts +6 -19
  8. package/lib/cjs/actions/blue/common.js +25 -138
  9. package/lib/cjs/actions/blue/refinance.d.ts +1 -1
  10. package/lib/cjs/actions/blue/refinance.js +1 -1
  11. package/lib/cjs/actions/blue/repay.d.ts +3 -3
  12. package/lib/cjs/actions/blue/repay.js +1 -1
  13. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +3 -3
  14. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +1 -1
  15. package/lib/cjs/actions/blue/supply.d.ts +3 -3
  16. package/lib/cjs/actions/blue/supply.js +1 -1
  17. package/lib/cjs/actions/blue/supplyCollateral.d.ts +3 -3
  18. package/lib/cjs/actions/blue/supplyCollateral.js +1 -1
  19. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +3 -3
  20. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +1 -1
  21. package/lib/cjs/actions/blue/withdraw.d.ts +1 -1
  22. package/lib/cjs/actions/blue/withdraw.js +1 -1
  23. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +1 -1
  24. package/lib/cjs/actions/blue/withdrawCollateral.js +1 -1
  25. package/lib/cjs/actions/bundles/common.d.ts +200 -0
  26. package/lib/cjs/actions/bundles/common.js +469 -0
  27. package/lib/cjs/actions/bundles/index.d.ts +3 -0
  28. package/lib/cjs/actions/bundles/index.js +23 -0
  29. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +76 -0
  30. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +125 -0
  31. package/lib/cjs/actions/index.d.ts +1 -0
  32. package/lib/cjs/actions/index.js +1 -0
  33. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +2 -2
  34. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +2 -2
  35. package/lib/cjs/actions/midnight/takeBorrow.d.ts +2 -2
  36. package/lib/cjs/actions/midnight/takeBorrow.js +2 -2
  37. package/lib/cjs/actions/midnight/takeLend.d.ts +2 -2
  38. package/lib/cjs/actions/midnight/takeLend.js +2 -2
  39. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +1 -1
  40. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.js +1 -1
  41. package/lib/cjs/actions/requirements/blue/index.d.ts +0 -1
  42. package/lib/cjs/actions/requirements/blue/index.js +0 -1
  43. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -1
  44. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  45. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +2 -1
  46. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +3 -3
  47. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +10 -4
  48. package/lib/{esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts → cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts} +12 -12
  49. package/lib/cjs/actions/requirements/encode/{encodeErc20Permit2TransferFrom.js → encodeErc20Permit2SignatureTransfer.js} +13 -13
  50. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -4
  51. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +6 -5
  52. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -1
  53. package/lib/cjs/actions/requirements/encode/index.js +1 -1
  54. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +4 -3
  55. package/lib/cjs/actions/requirements/getRequirementsApproval.js +4 -3
  56. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +2 -2
  57. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +22 -30
  58. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +18 -66
  59. package/lib/cjs/actions/vaultV1/deposit.d.ts +73 -57
  60. package/lib/cjs/actions/vaultV1/deposit.js +110 -109
  61. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +43 -66
  62. package/lib/cjs/actions/vaultV1/migrateToV2.js +91 -104
  63. package/lib/cjs/actions/vaultV1/redeem.d.ts +30 -23
  64. package/lib/cjs/actions/vaultV1/redeem.js +56 -33
  65. package/lib/cjs/actions/vaultV1/withdraw.d.ts +58 -24
  66. package/lib/cjs/actions/vaultV1/withdraw.js +86 -34
  67. package/lib/cjs/actions/vaultV2/deposit.d.ts +74 -57
  68. package/lib/cjs/actions/vaultV2/deposit.js +111 -109
  69. package/lib/cjs/actions/vaultV2/redeem.d.ts +30 -24
  70. package/lib/cjs/actions/vaultV2/redeem.js +56 -34
  71. package/lib/cjs/actions/vaultV2/withdraw.d.ts +58 -25
  72. package/lib/cjs/actions/vaultV2/withdraw.js +86 -35
  73. package/lib/cjs/entities/blue/blue.d.ts +19 -19
  74. package/lib/cjs/entities/blue/blue.js +3 -1
  75. package/lib/cjs/entities/index.d.ts +1 -0
  76. package/lib/cjs/entities/index.js +15 -0
  77. package/lib/cjs/entities/midnight/midnight.d.ts +2 -2
  78. package/lib/cjs/{actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts → entities/requirements/getBundlesTokenRequirements.d.ts} +21 -14
  79. package/lib/cjs/{actions/requirements/blue/getBlueBundlesV1TokenRequirements.js → entities/requirements/getBundlesTokenRequirements.js} +61 -65
  80. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +28 -0
  81. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +74 -0
  82. package/lib/cjs/entities/requirements/index.d.ts +1 -0
  83. package/lib/cjs/entities/requirements/index.js +17 -0
  84. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +348 -98
  85. package/lib/cjs/entities/vaultV1/vaultV1.js +322 -120
  86. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +221 -68
  87. package/lib/cjs/entities/vaultV2/vaultV2.js +219 -77
  88. package/lib/cjs/helpers/index.d.ts +2 -1
  89. package/lib/cjs/helpers/index.js +5 -1
  90. package/lib/cjs/helpers/referralFee.d.ts +21 -0
  91. package/lib/cjs/helpers/referralFee.js +35 -0
  92. package/lib/cjs/helpers/slippage.d.ts +90 -1
  93. package/lib/cjs/helpers/slippage.js +123 -0
  94. package/lib/cjs/helpers/validate.d.ts +2 -0
  95. package/lib/cjs/helpers/validate.js +12 -1
  96. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  97. package/lib/cjs/helpers/validateRequirementSpender.js +1 -0
  98. package/lib/cjs/index.d.ts +1 -0
  99. package/lib/cjs/index.js +1 -0
  100. package/lib/cjs/types/action.d.ts +179 -70
  101. package/lib/cjs/types/action.js +12 -12
  102. package/lib/cjs/types/error.d.ts +62 -14
  103. package/lib/cjs/types/error.js +88 -22
  104. package/lib/esm/abis.d.ts +210 -0
  105. package/lib/esm/abis.js +140 -0
  106. package/lib/esm/actions/blue/borrow.d.ts +1 -1
  107. package/lib/esm/actions/blue/borrow.js +1 -1
  108. package/lib/esm/actions/blue/common.d.ts +6 -19
  109. package/lib/esm/actions/blue/common.js +27 -140
  110. package/lib/esm/actions/blue/refinance.d.ts +1 -1
  111. package/lib/esm/actions/blue/refinance.js +1 -1
  112. package/lib/esm/actions/blue/repay.d.ts +3 -3
  113. package/lib/esm/actions/blue/repay.js +1 -1
  114. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +3 -3
  115. package/lib/esm/actions/blue/repayWithdrawCollateral.js +1 -1
  116. package/lib/esm/actions/blue/supply.d.ts +3 -3
  117. package/lib/esm/actions/blue/supply.js +1 -1
  118. package/lib/esm/actions/blue/supplyCollateral.d.ts +3 -3
  119. package/lib/esm/actions/blue/supplyCollateral.js +1 -1
  120. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +3 -3
  121. package/lib/esm/actions/blue/supplyCollateralBorrow.js +1 -1
  122. package/lib/esm/actions/blue/withdraw.d.ts +1 -1
  123. package/lib/esm/actions/blue/withdraw.js +1 -1
  124. package/lib/esm/actions/blue/withdrawCollateral.d.ts +1 -1
  125. package/lib/esm/actions/blue/withdrawCollateral.js +1 -1
  126. package/lib/esm/actions/bundles/common.d.ts +200 -0
  127. package/lib/esm/actions/bundles/common.js +457 -0
  128. package/lib/esm/actions/bundles/index.d.ts +3 -0
  129. package/lib/esm/actions/bundles/index.js +2 -0
  130. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +76 -0
  131. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +121 -0
  132. package/lib/esm/actions/index.d.ts +1 -0
  133. package/lib/esm/actions/index.js +1 -0
  134. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +2 -2
  135. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +2 -2
  136. package/lib/esm/actions/midnight/takeBorrow.d.ts +2 -2
  137. package/lib/esm/actions/midnight/takeBorrow.js +2 -2
  138. package/lib/esm/actions/midnight/takeLend.d.ts +2 -2
  139. package/lib/esm/actions/midnight/takeLend.js +2 -2
  140. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +1 -1
  141. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.js +1 -1
  142. package/lib/esm/actions/requirements/blue/index.d.ts +0 -1
  143. package/lib/esm/actions/requirements/blue/index.js +0 -1
  144. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -1
  145. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  146. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +2 -1
  147. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +3 -3
  148. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +10 -4
  149. package/lib/{cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts → esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts} +12 -12
  150. package/lib/esm/actions/requirements/encode/{encodeErc20Permit2TransferFrom.js → encodeErc20Permit2SignatureTransfer.js} +11 -11
  151. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -4
  152. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +6 -5
  153. package/lib/esm/actions/requirements/encode/index.d.ts +1 -1
  154. package/lib/esm/actions/requirements/encode/index.js +1 -1
  155. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +4 -3
  156. package/lib/esm/actions/requirements/getRequirementsApproval.js +4 -3
  157. package/lib/esm/actions/signatures/getTokenRequirementActions.js +3 -3
  158. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +22 -30
  159. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +19 -67
  160. package/lib/esm/actions/vaultV1/deposit.d.ts +73 -57
  161. package/lib/esm/actions/vaultV1/deposit.js +112 -111
  162. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +43 -66
  163. package/lib/esm/actions/vaultV1/migrateToV2.js +93 -106
  164. package/lib/esm/actions/vaultV1/redeem.d.ts +30 -23
  165. package/lib/esm/actions/vaultV1/redeem.js +56 -33
  166. package/lib/esm/actions/vaultV1/withdraw.d.ts +58 -24
  167. package/lib/esm/actions/vaultV1/withdraw.js +86 -34
  168. package/lib/esm/actions/vaultV2/deposit.d.ts +74 -57
  169. package/lib/esm/actions/vaultV2/deposit.js +113 -111
  170. package/lib/esm/actions/vaultV2/redeem.d.ts +30 -24
  171. package/lib/esm/actions/vaultV2/redeem.js +56 -34
  172. package/lib/esm/actions/vaultV2/withdraw.d.ts +58 -25
  173. package/lib/esm/actions/vaultV2/withdraw.js +86 -35
  174. package/lib/esm/entities/blue/blue.d.ts +19 -19
  175. package/lib/esm/entities/blue/blue.js +4 -2
  176. package/lib/esm/entities/index.d.ts +1 -0
  177. package/lib/esm/entities/index.js +1 -0
  178. package/lib/esm/entities/midnight/midnight.d.ts +2 -2
  179. package/lib/esm/{actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts → entities/requirements/getBundlesTokenRequirements.d.ts} +21 -14
  180. package/lib/esm/{actions/requirements/blue/getBlueBundlesV1TokenRequirements.js → entities/requirements/getBundlesTokenRequirements.js} +51 -55
  181. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +28 -0
  182. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +70 -0
  183. package/lib/esm/entities/requirements/index.d.ts +1 -0
  184. package/lib/esm/entities/requirements/index.js +1 -0
  185. package/lib/esm/entities/vaultV1/vaultV1.d.ts +348 -98
  186. package/lib/esm/entities/vaultV1/vaultV1.js +326 -124
  187. package/lib/esm/entities/vaultV2/vaultV2.d.ts +221 -68
  188. package/lib/esm/entities/vaultV2/vaultV2.js +222 -80
  189. package/lib/esm/helpers/index.d.ts +2 -1
  190. package/lib/esm/helpers/index.js +2 -1
  191. package/lib/esm/helpers/referralFee.d.ts +21 -0
  192. package/lib/esm/helpers/referralFee.js +31 -0
  193. package/lib/esm/helpers/slippage.d.ts +90 -1
  194. package/lib/esm/helpers/slippage.js +122 -2
  195. package/lib/esm/helpers/validate.d.ts +2 -0
  196. package/lib/esm/helpers/validate.js +11 -1
  197. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  198. package/lib/esm/helpers/validateRequirementSpender.js +1 -0
  199. package/lib/esm/index.d.ts +1 -0
  200. package/lib/esm/index.js +1 -0
  201. package/lib/esm/types/action.d.ts +179 -70
  202. package/lib/esm/types/action.js +11 -11
  203. package/lib/esm/types/error.d.ts +62 -14
  204. package/lib/esm/types/error.js +80 -16
  205. package/package.json +3 -3
@@ -3,9 +3,13 @@ import { erc2612Abi, fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
3
  import { getChainAddress, Time } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual } from "viem";
5
5
  import { multicall } from "viem/actions";
6
- import { encodeErc20Approval, encodeVaultSharesPermit, getGeneralAdapterRequirements, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2InKindRedeem, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
7
- import { validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
8
- import { AdapterNotPartOfVaultError, ChainIdMismatchError, ChainWNativeMissingError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemRequiresSingleAdapterError, InKindRedeemZeroDeallocationError, InsufficientBlueBalanceForInKindRedeemError, NativeAmountOnNonWNativeVaultError, NegativeInputError, NonPositiveInputError, selectRequirementSignatures, UnsupportedInKindAdapterError, VaultAddressMismatchError, } from "../../types/index.js";
6
+ import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundlesFunding, selectBundlesSharesRequirementSignature, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
7
+ import { encodeErc20Approval, encodeVaultSharesPermit, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2InKindRedeem, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
8
+ import { computeVaultMaxShareAllowance, computeVaultMaxSharePrice, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
9
+ import { validateNativeVaultAsset, validateUint256Field, } from "../../helpers/validate.js";
10
+ import { AdapterNotPartOfVaultError, ChainIdMismatchError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemRequiresSingleAdapterError, InKindRedeemZeroDeallocationError, InsufficientBlueBalanceForInKindRedeemError, isRequirementSignature, NonPositiveInputError, selectRequirementSignatures, UnsupportedInKindAdapterError, VaultAddressMismatchError, } from "../../types/index.js";
11
+ import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
12
+ import { getBundlesTokenRequirements } from "../requirements/index.js";
9
13
  export class MorphoVaultV2 {
10
14
  client;
11
15
  vault;
@@ -27,104 +31,242 @@ export class MorphoVaultV2 {
27
31
  deployless: this.client.options.supportDeployless,
28
32
  });
29
33
  }
30
- deposit({ amount = 0n, userAddress, vaultData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
34
+ /** {@inheritDoc VaultV2Actions.deposit} */
35
+ deposit(params) {
36
+ const { userAddress, vaultData } = params;
37
+ const { asset: vaultAsset } = vaultData;
31
38
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
32
39
  if (!isAddressEqual(vaultData.address, this.vault)) {
33
40
  throw new VaultAddressMismatchError(this.vault, vaultData.address);
34
41
  }
35
- if (amount < 0n) {
36
- throw new NegativeInputError("amount", amount);
37
- }
38
- if (nativeAmount && nativeAmount < 0n) {
39
- throw new NegativeInputError("nativeAmount", nativeAmount);
40
- }
41
- let wNative;
42
- if (nativeAmount) {
43
- ({ wNative } = getChainAddresses(this.chainId));
44
- if (!wNative) {
45
- throw new ChainWNativeMissingError(this.chainId);
46
- }
47
- }
48
- validateSlippageTolerance(slippageTolerance);
49
- if (nativeAmount && wNative) {
50
- if (!isAddressEqual(vaultData.asset, wNative)) {
51
- throw new NativeAmountOnNonWNativeVaultError(vaultData.asset, wNative);
52
- }
53
- }
54
- const totalAssets = amount + (nativeAmount ?? 0n);
55
- if (totalAssets === 0n) {
56
- throw new NonPositiveInputError("totalAssets", totalAssets);
57
- }
58
- // Accrue interest forward to bound the on-chain share price at execution.
59
- // Mirrors blue repay's 2h forward-accrual buffer.
60
- const accrualTimestamp = MathLib.max(Time.timestamp(), vaultData.lastUpdate) + Time.s.from.h(2n);
61
- const { vault: accruedVault } = vaultData.accrueInterest(accrualTimestamp);
62
- const shares = accruedVault.toShares(totalAssets);
63
- if (shares <= 0n) {
64
- throw new NonPositiveInputError("shares", shares);
42
+ const createdAt = Time.timestamp();
43
+ const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
44
+ if (deadline <= createdAt)
45
+ throw new ExpiredDeadlineError(deadline, createdAt);
46
+ const common = normalizeBundlesCommonParams({
47
+ deadline,
48
+ referralFeePct: params.referralFeePct,
49
+ referralFeeRecipient: params.referralFeeRecipient,
50
+ });
51
+ const funding = resolveBundlesFunding(params);
52
+ // Reject overflow before share-price math or native-only prerequisite resolution.
53
+ validateUint256Field(funding.value > 0n ? "nativeAmount" : "amount", funding.assets);
54
+ if (funding.value > 0n) {
55
+ // The native path must target the chain's registered wrapped-native asset.
56
+ validateNativeVaultAsset(this.chainId, vaultAsset);
65
57
  }
66
- const maxSharePrice = MathLib.min(MathLib.mulDivUp(totalAssets, MathLib.wToRay(MathLib.WAD + slippageTolerance), shares), MathLib.RAY * 100n);
67
- return {
68
- getRequirements: (params) => getGeneralAdapterRequirements(this.client.viemClient, {
69
- address: vaultData.asset,
70
- chainId: this.chainId,
71
- supportSignature: this.client.options.supportSignature,
72
- supportDeployless: this.client.options.supportDeployless,
73
- useSimplePermit: params?.useSimplePermit,
74
- args: {
75
- amount,
76
- from: userAddress,
77
- },
78
- }),
58
+ const referralFeeAssets = getBundlesReferralFeeAssets(funding.assets, common.referralFeePct);
59
+ const maxSharePrice = computeVaultMaxSharePrice({
60
+ vaultData,
61
+ deadline,
62
+ assets: funding.assets - referralFeeAssets,
63
+ slippageTolerance: params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE,
64
+ });
65
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
66
+ let pendingRequirements;
67
+ let expectedRequirement;
68
+ return Object.freeze({
69
+ getRequirements: async (requirementOptions) => {
70
+ const now = Time.timestamp();
71
+ if (deadline <= now)
72
+ throw new ExpiredDeadlineError(deadline, now);
73
+ if (pendingRequirements != null)
74
+ return await pendingRequirements;
75
+ // Memoize the in-flight promise, not just its result: concurrent callers
76
+ // requesting different routes would otherwise both resolve requirements and
77
+ // the slower one would overwrite `expectedRequirement`, making `buildTx()`
78
+ // reject the signature returned by the other call.
79
+ const pending = (async () => {
80
+ const requirements = funding.value > 0n
81
+ ? []
82
+ : await getBundlesTokenRequirements(this.client.viemClient, {
83
+ token: vaultAsset,
84
+ spender,
85
+ amount: funding.assets,
86
+ owner: userAddress,
87
+ chainId: this.chainId,
88
+ deadline,
89
+ supportSignature: this.client.options.supportSignature,
90
+ supportDeployless: this.client.options.supportDeployless,
91
+ useSimplePermit: requirementOptions?.useSimplePermit,
92
+ permit2Nonce: requirementOptions?.permit2Nonce,
93
+ });
94
+ const signatureRequirement = requirements.find(isRequirementSignature);
95
+ expectedRequirement =
96
+ signatureRequirement?.action.type === "permit" ||
97
+ signatureRequirement?.action.type === "permit2SignatureTransfer"
98
+ ? signatureRequirement.action
99
+ : undefined;
100
+ return requirements;
101
+ })();
102
+ pendingRequirements = pending;
103
+ try {
104
+ return await pending;
105
+ }
106
+ finally {
107
+ // Later calls must re-read live allowances/nonces and honor their own options.
108
+ if (pendingRequirements === pending)
109
+ pendingRequirements = undefined;
110
+ }
111
+ },
79
112
  buildTx: (signatures) => {
80
- const { permit } = selectRequirementSignatures(signatures, {
81
- permit: true,
82
- });
113
+ const requirementSignature = selectBundlesTokenRequirementSignature(signatures, expectedRequirement);
83
114
  return vaultV2Deposit({
84
115
  vault: {
85
116
  chainId: this.chainId,
86
117
  address: this.vault,
87
- asset: vaultData.asset,
118
+ asset: vaultAsset,
88
119
  },
89
120
  args: {
90
- amount,
121
+ ...(funding.value > 0n
122
+ ? { nativeAmount: funding.assets }
123
+ : { amount: funding.assets }),
91
124
  maxSharePrice,
92
- recipient: userAddress,
93
- requirementSignature: permit,
94
- nativeAmount,
125
+ userAddress,
126
+ requirementSignature,
127
+ referralFeePct: common.referralFeePct,
128
+ referralFeeRecipient: common.referralFeeRecipient,
129
+ deadline,
95
130
  },
96
131
  metadata: this.client.options.metadata,
97
132
  });
98
133
  },
99
- };
134
+ });
100
135
  }
101
- withdraw({ amount, userAddress }) {
136
+ withdraw(params) {
137
+ const { amount, userAddress } = params;
102
138
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
103
- return {
104
- buildTx: () => vaultV2Withdraw({
105
- vault: { address: this.vault },
106
- args: {
107
- amount,
108
- recipient: userAddress,
109
- onBehalf: userAddress,
110
- },
111
- metadata: this.client.options.metadata,
112
- }),
113
- };
139
+ if (amount <= 0n)
140
+ throw new NonPositiveInputError("amount", amount);
141
+ // Reject values outside the ABI range before resolving any requirements.
142
+ validateUint256Field("amount", amount);
143
+ const createdAt = Time.timestamp();
144
+ const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
145
+ if (deadline <= createdAt)
146
+ throw new ExpiredDeadlineError(deadline, createdAt);
147
+ const common = normalizeBundlesCommonParams({
148
+ deadline,
149
+ referralFeePct: params.referralFeePct,
150
+ referralFeeRecipient: params.referralFeeRecipient,
151
+ });
152
+ const slippageTolerance = params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE;
153
+ validateSlippageTolerance(slippageTolerance);
154
+ // Fail eagerly if VaultBundlesV1 is unavailable; only validation is needed here.
155
+ getChainAddress(this.chainId, "bundles.vaultBundlesV1");
156
+ let requiredShareAllowance;
157
+ let vaultSnapshot;
158
+ let expectedRequirement;
159
+ return Object.freeze({
160
+ getRequirements: async () => {
161
+ const now = Time.timestamp();
162
+ if (deadline <= now)
163
+ throw new ExpiredDeadlineError(deadline, now);
164
+ // Re-read the live share allowance on every call instead of caching the resolved
165
+ // requirements: the allowance is the sole cap on the burn, so a caller that executed the
166
+ // returned approval must see it satisfied on the next call, and an allowance revoked or
167
+ // raised afterwards must resurface as an outstanding requirement. Only the vault snapshot
168
+ // and the cap derived from it are pinned, so re-reading cannot move the cap this handle
169
+ // already committed to; the snapshot is used for immutable identity and permit-domain
170
+ // fields only.
171
+ const vaultData = (vaultSnapshot ??= await this.getData());
172
+ requiredShareAllowance ??= computeVaultMaxShareAllowance({
173
+ vaultData,
174
+ deadline,
175
+ assets: amount,
176
+ slippageTolerance,
177
+ });
178
+ const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
179
+ vaultData,
180
+ version: "vaultV2",
181
+ owner: userAddress,
182
+ chainId: this.chainId,
183
+ requiredShareAllowance,
184
+ deadline,
185
+ supportSignature: this.client.options.supportSignature,
186
+ });
187
+ const signatureRequirement = requirements.find(isRequirementSignature);
188
+ if (signatureRequirement?.action.type === "permit") {
189
+ expectedRequirement = signatureRequirement.action;
190
+ }
191
+ return requirements;
192
+ },
193
+ buildTx: (signatures) => {
194
+ const permit = selectBundlesSharesRequirementSignature(signatures, {
195
+ requiredShareAllowance,
196
+ expectedRequirement,
197
+ });
198
+ return vaultV2Withdraw({
199
+ vault: { chainId: this.chainId, address: this.vault },
200
+ args: {
201
+ amount,
202
+ userAddress,
203
+ requirementSignature: permit,
204
+ referralFeePct: common.referralFeePct,
205
+ referralFeeRecipient: common.referralFeeRecipient,
206
+ deadline,
207
+ },
208
+ metadata: this.client.options.metadata,
209
+ });
210
+ },
211
+ });
114
212
  }
115
- redeem({ shares, userAddress }) {
213
+ /** {@inheritDoc VaultV2Actions.redeem} */
214
+ redeem(params) {
116
215
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
117
- return {
118
- buildTx: () => vaultV2Redeem({
119
- vault: { address: this.vault },
120
- args: {
121
- shares,
122
- recipient: userAddress,
123
- onBehalf: userAddress,
124
- },
125
- metadata: this.client.options.metadata,
126
- }),
127
- };
216
+ const { shares, userAddress } = params;
217
+ if (shares <= 0n)
218
+ throw new NonPositiveInputError("shares", shares);
219
+ const createdAt = Time.timestamp();
220
+ const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
221
+ if (deadline <= createdAt)
222
+ throw new ExpiredDeadlineError(deadline, createdAt);
223
+ const common = normalizeBundlesCommonParams({
224
+ deadline,
225
+ referralFeePct: params.referralFeePct,
226
+ referralFeeRecipient: params.referralFeeRecipient,
227
+ });
228
+ getChainAddress(this.chainId, "bundles.vaultBundlesV1");
229
+ let expectedRequirement;
230
+ return Object.freeze({
231
+ getRequirements: async () => {
232
+ const now = Time.timestamp();
233
+ if (deadline <= now)
234
+ throw new ExpiredDeadlineError(deadline, now);
235
+ const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
236
+ vaultData: await this.getData(),
237
+ version: "vaultV2",
238
+ owner: userAddress,
239
+ chainId: this.chainId,
240
+ requiredShareAllowance: shares,
241
+ deadline,
242
+ supportSignature: this.client.options.supportSignature,
243
+ });
244
+ const signatureRequirement = requirements.find(isRequirementSignature);
245
+ expectedRequirement =
246
+ signatureRequirement?.action.type === "permit"
247
+ ? signatureRequirement.action
248
+ : undefined;
249
+ return requirements;
250
+ },
251
+ buildTx: (signatures) => {
252
+ const permit = selectBundlesSharesRequirementSignature(signatures, {
253
+ requiredShareAllowance: shares,
254
+ expectedRequirement,
255
+ });
256
+ return vaultV2Redeem({
257
+ vault: { chainId: this.chainId, address: this.vault },
258
+ args: {
259
+ shares,
260
+ userAddress,
261
+ requirementSignature: permit,
262
+ referralFeePct: common.referralFeePct,
263
+ referralFeeRecipient: common.referralFeeRecipient,
264
+ deadline,
265
+ },
266
+ metadata: this.client.options.metadata,
267
+ });
268
+ },
269
+ });
128
270
  }
129
271
  /** {@inheritDoc VaultV2Actions.inKindRedeem} */
130
272
  inKindRedeem({ amount, marketParamsList, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, }) {
@@ -2,8 +2,9 @@ export { computeReallocations, computeVaultV1Reallocations, } from "./computeVau
2
2
  export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
3
3
  export { addTransactionMetadata } from "./metadata.js";
4
4
  export { type PreviewVaultV2InKindRedeemParams, previewVaultV2InKindRedeem, type VaultV2InKindRedeemMarketPreview, } from "./previewVaultV2InKindRedeem.js";
5
+ export { grossFromNetAssets } from "./referralFee.js";
5
6
  export { signAndVerifyTypedData } from "./signAndVerifyTypedData.js";
6
- export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, } from "./slippage.js";
7
+ export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, computeVaultMaxShareAllowance, computeVaultMaxSharePrice, } from "./slippage.js";
7
8
  export { validateAccrualPosition, validateChainId, validateMidnightMarketChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
8
9
  export { validateOfferSides } from "./validateOfferSides.js";
9
10
  export { type RequirementSpenderKey, validateRequirementSpender, } from "./validateRequirementSpender.js";
@@ -2,8 +2,9 @@ export { computeReallocations, computeVaultV1Reallocations, } from "./computeVau
2
2
  export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
3
3
  export { addTransactionMetadata } from "./metadata.js";
4
4
  export { previewVaultV2InKindRedeem, } from "./previewVaultV2InKindRedeem.js";
5
+ export { grossFromNetAssets } from "./referralFee.js";
5
6
  export { signAndVerifyTypedData } from "./signAndVerifyTypedData.js";
6
- export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, } from "./slippage.js";
7
+ export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, computeVaultMaxShareAllowance, computeVaultMaxSharePrice, } from "./slippage.js";
7
8
  export { validateAccrualPosition, validateChainId, validateMidnightMarketChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
8
9
  export { validateOfferSides } from "./validateOfferSides.js";
9
10
  export { validateRequirementSpender, } from "./validateRequirementSpender.js";
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Computes the gross amount whose post-referral-fee proceeds equal `netAssets` exactly.
3
+ *
4
+ * @param params - Net target and WAD-scaled referral fee.
5
+ * @param params.netAssets - Required proceeds after the fee, in the asset's smallest unit.
6
+ * @param params.referralFeePct - Referral fee fraction scaled by WAD (`1e18`); must be below WAD.
7
+ * @returns The gross asset amount to pass to a bundles entrypoint.
8
+ * @throws {NegativeInputError} when `netAssets` or `referralFeePct` is negative.
9
+ * @throws {ReferralFeePctExceededError} when `referralFeePct >= WAD`.
10
+ * @example
11
+ * ```ts
12
+ * import { grossFromNetAssets } from "@morpho-org/morpho-sdk";
13
+ *
14
+ * const gross = grossFromNetAssets({ netAssets: 990n, referralFeePct: 10_000000000000000n });
15
+ * // gross satisfies bigint
16
+ * ```
17
+ */
18
+ export declare const grossFromNetAssets: (params: {
19
+ readonly netAssets: bigint;
20
+ readonly referralFeePct: bigint;
21
+ }) => bigint;
@@ -0,0 +1,31 @@
1
+ import { MathLib } from "@morpho-org/blue-sdk";
2
+ import { NegativeInputError, ReferralFeePctExceededError, } from "../types/index.js";
3
+ /**
4
+ * Computes the gross amount whose post-referral-fee proceeds equal `netAssets` exactly.
5
+ *
6
+ * @param params - Net target and WAD-scaled referral fee.
7
+ * @param params.netAssets - Required proceeds after the fee, in the asset's smallest unit.
8
+ * @param params.referralFeePct - Referral fee fraction scaled by WAD (`1e18`); must be below WAD.
9
+ * @returns The gross asset amount to pass to a bundles entrypoint.
10
+ * @throws {NegativeInputError} when `netAssets` or `referralFeePct` is negative.
11
+ * @throws {ReferralFeePctExceededError} when `referralFeePct >= WAD`.
12
+ * @example
13
+ * ```ts
14
+ * import { grossFromNetAssets } from "@morpho-org/morpho-sdk";
15
+ *
16
+ * const gross = grossFromNetAssets({ netAssets: 990n, referralFeePct: 10_000000000000000n });
17
+ * // gross satisfies bigint
18
+ * ```
19
+ */
20
+ export const grossFromNetAssets = (params) => {
21
+ if (params.netAssets < 0n) {
22
+ throw new NegativeInputError("netAssets", params.netAssets);
23
+ }
24
+ if (params.referralFeePct < 0n) {
25
+ throw new NegativeInputError("referralFeePct", params.referralFeePct);
26
+ }
27
+ if (params.referralFeePct >= MathLib.WAD) {
28
+ throw new ReferralFeePctExceededError(params.referralFeePct);
29
+ }
30
+ return MathLib.mulDivDown(params.netAssets, MathLib.WAD, MathLib.WAD - params.referralFeePct);
31
+ };
@@ -1,4 +1,4 @@
1
- import { type Market } from "@morpho-org/blue-sdk";
1
+ import { type AccrualVault, AccrualVaultV2, type Market } from "@morpho-org/blue-sdk";
2
2
  /**
3
3
  * Computes the minimum borrow share price (in RAY, 1e27) for slippage protection.
4
4
  *
@@ -101,3 +101,92 @@ export declare function computeMinWithdrawSharePrice(params: {
101
101
  market: Market;
102
102
  slippageTolerance: bigint;
103
103
  }): bigint;
104
+ /**
105
+ * Computes the RAY-scaled maximum share price for a VaultBundlesV1 deposit leg.
106
+ *
107
+ * Previews shares on both the supplied Vault V1 or Vault V2 snapshot and its deadline-accrued
108
+ * counterpart, dividing by the smaller of the two so the bound covers the highest price the
109
+ * bundle may execute at. Shares are previewed rounding down, mirroring the ERC-4626 `deposit()`
110
+ * shares the on-chain `maxSharePrice` check divides by.
111
+ *
112
+ * @param params - Vault snapshot, bundles execution deadline, net assets, and slippage.
113
+ * @param params.vaultData - Hydrated Vault V1 `AccrualVault` or Vault V2 `AccrualVaultV2` snapshot.
114
+ * @param params.deadline - Bundle execution deadline as a Unix timestamp in seconds, used for accrual.
115
+ * @param params.assets - Net assets deposited after referral fees, in the underlying token's smallest unit.
116
+ * @param params.slippageTolerance - Accepted share-price increase as a WAD-scaled fraction (`1e18` = 100%).
117
+ * @returns The capped maximum share price enforced by VaultBundlesV1.
118
+ * @throws {NonPositiveInputError} when `assets` or the previewed shares are not positive.
119
+ * @throws {NegativeInputError} when `slippageTolerance` is negative.
120
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
121
+ * @example
122
+ * ```ts
123
+ * import { fetchAccrualVault } from "@morpho-org/blue-sdk-viem";
124
+ * import { computeVaultMaxSharePrice } from "@morpho-org/morpho-sdk";
125
+ * import { createPublicClient, http } from "viem";
126
+ * import { mainnet } from "viem/chains";
127
+ *
128
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
129
+ * const vaultData = await fetchAccrualVault(
130
+ * "0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB",
131
+ * client,
132
+ * );
133
+ * const { timestamp } = await client.getBlock();
134
+ * const maxSharePrice = computeVaultMaxSharePrice({
135
+ * vaultData,
136
+ * deadline: timestamp + 7_200n,
137
+ * assets: 1_000_000n,
138
+ * slippageTolerance: 500_000_000_000_000n,
139
+ * });
140
+ * // maxSharePrice satisfies bigint
141
+ * ```
142
+ */
143
+ export declare const computeVaultMaxSharePrice: (params: {
144
+ readonly vaultData: AccrualVault | AccrualVaultV2;
145
+ readonly deadline: bigint;
146
+ readonly assets: bigint;
147
+ readonly slippageTolerance: bigint;
148
+ }) => bigint;
149
+ /**
150
+ * Computes the exact vault-share authorization cap for an asset-denominated exit.
151
+ *
152
+ * The cap covers both the current and deadline-accrued preview. Vault V2 and MetaMorpho 1.0 divide
153
+ * by `1 - slippageTolerance`, rounding up, to cover a share-price decline before inclusion;
154
+ * MetaMorpho 1.1's `lostAssets` clamp keeps that preview upper-bounded without widening it.
155
+ *
156
+ * @param params - Vault snapshot, execution deadline, asset amount, and WAD-scaled slippage.
157
+ * @param params.vaultData - Hydrated Vault V1 `AccrualVault` or Vault V2 `AccrualVaultV2` snapshot.
158
+ * @param params.deadline - Bundle execution deadline as a Unix timestamp in seconds, used for accrual.
159
+ * @param params.assets - Assets withdrawn from the vault, in the underlying token's smallest unit.
160
+ * @param params.slippageTolerance - Accepted share-price decline as a WAD-scaled fraction (`1e18` = 100%).
161
+ * @returns The maximum shares the prepared operation may burn.
162
+ * @throws {NonPositiveInputError} when `assets` or the computed share cap is not positive.
163
+ * @throws {NegativeInputError} when `slippageTolerance` is negative.
164
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
165
+ * @example
166
+ * ```ts
167
+ * import { fetchAccrualVault } from "@morpho-org/blue-sdk-viem";
168
+ * import { computeVaultMaxShareAllowance } from "@morpho-org/morpho-sdk";
169
+ * import { createPublicClient, http } from "viem";
170
+ * import { mainnet } from "viem/chains";
171
+ *
172
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
173
+ * const vaultData = await fetchAccrualVault(
174
+ * "0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB",
175
+ * client,
176
+ * );
177
+ * const { timestamp } = await client.getBlock();
178
+ * const shares = computeVaultMaxShareAllowance({
179
+ * vaultData,
180
+ * deadline: timestamp + 7_200n,
181
+ * assets: 1_000_000n,
182
+ * slippageTolerance: 500_000_000_000_000n,
183
+ * });
184
+ * // shares is the exact allowance or permit value for the prepared exit.
185
+ * ```
186
+ */
187
+ export declare const computeVaultMaxShareAllowance: (params: {
188
+ readonly vaultData: AccrualVault | AccrualVaultV2;
189
+ readonly deadline: bigint;
190
+ readonly assets: bigint;
191
+ readonly slippageTolerance: bigint;
192
+ }) => bigint;
@@ -1,6 +1,7 @@
1
- import { MathLib } from "@morpho-org/blue-sdk";
2
- import { ExcessiveSlippageToleranceError, ShareDivideByZeroError, } from "../types/index.js";
1
+ import { AccrualVaultV2, MathLib, } from "@morpho-org/blue-sdk";
2
+ import { ExcessiveSlippageToleranceError, NonPositiveInputError, ShareDivideByZeroError, } from "../types/index.js";
3
3
  import { MAX_ABSOLUTE_SHARE_PRICE } from "./constant.js";
4
+ import { validateSlippageTolerance } from "./validate.js";
4
5
  /**
5
6
  * Computes the minimum borrow share price (in RAY, 1e27) for slippage protection.
6
7
  *
@@ -147,3 +148,122 @@ export function computeMinWithdrawSharePrice(params) {
147
148
  }
148
149
  return MathLib.mulDivDown(assets, MathLib.wToRay(MathLib.WAD - slippageTolerance), shares);
149
150
  }
151
+ /**
152
+ * Computes the RAY-scaled maximum share price for a VaultBundlesV1 deposit leg.
153
+ *
154
+ * Previews shares on both the supplied Vault V1 or Vault V2 snapshot and its deadline-accrued
155
+ * counterpart, dividing by the smaller of the two so the bound covers the highest price the
156
+ * bundle may execute at. Shares are previewed rounding down, mirroring the ERC-4626 `deposit()`
157
+ * shares the on-chain `maxSharePrice` check divides by.
158
+ *
159
+ * @param params - Vault snapshot, bundles execution deadline, net assets, and slippage.
160
+ * @param params.vaultData - Hydrated Vault V1 `AccrualVault` or Vault V2 `AccrualVaultV2` snapshot.
161
+ * @param params.deadline - Bundle execution deadline as a Unix timestamp in seconds, used for accrual.
162
+ * @param params.assets - Net assets deposited after referral fees, in the underlying token's smallest unit.
163
+ * @param params.slippageTolerance - Accepted share-price increase as a WAD-scaled fraction (`1e18` = 100%).
164
+ * @returns The capped maximum share price enforced by VaultBundlesV1.
165
+ * @throws {NonPositiveInputError} when `assets` or the previewed shares are not positive.
166
+ * @throws {NegativeInputError} when `slippageTolerance` is negative.
167
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
168
+ * @example
169
+ * ```ts
170
+ * import { fetchAccrualVault } from "@morpho-org/blue-sdk-viem";
171
+ * import { computeVaultMaxSharePrice } from "@morpho-org/morpho-sdk";
172
+ * import { createPublicClient, http } from "viem";
173
+ * import { mainnet } from "viem/chains";
174
+ *
175
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
176
+ * const vaultData = await fetchAccrualVault(
177
+ * "0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB",
178
+ * client,
179
+ * );
180
+ * const { timestamp } = await client.getBlock();
181
+ * const maxSharePrice = computeVaultMaxSharePrice({
182
+ * vaultData,
183
+ * deadline: timestamp + 7_200n,
184
+ * assets: 1_000_000n,
185
+ * slippageTolerance: 500_000_000_000_000n,
186
+ * });
187
+ * // maxSharePrice satisfies bigint
188
+ * ```
189
+ */
190
+ export const computeVaultMaxSharePrice = (params) => {
191
+ if (params.assets <= 0n) {
192
+ throw new NonPositiveInputError("assets", params.assets);
193
+ }
194
+ validateSlippageTolerance(params.slippageTolerance);
195
+ const accrualTimestamp = params.vaultData instanceof AccrualVaultV2
196
+ ? MathLib.max(params.deadline, params.vaultData.lastUpdate)
197
+ : params.deadline;
198
+ const accruedVault = params.vaultData instanceof AccrualVaultV2
199
+ ? params.vaultData.accrueInterest(accrualTimestamp).vault
200
+ : params.vaultData.accrueInterest(accrualTimestamp);
201
+ // The deadline snapshot is not necessarily the highest price over `[now, deadline]`: Vault V2
202
+ // charges its management fee regardless of yield, minting shares against an unchanged
203
+ // `_totalAssets`, so an idle vault's price *declines*. Bound at the maximum price across both
204
+ // endpoints — the minimum previewed shares — mirroring the `max(current, accrued)` shares the
205
+ // sibling `computeVaultMaxShareAllowance` authorizes.
206
+ const shares = MathLib.min(params.vaultData.toShares(params.assets, "Down"), accruedVault.toShares(params.assets, "Down"));
207
+ if (shares <= 0n) {
208
+ throw new NonPositiveInputError("shares", shares);
209
+ }
210
+ return MathLib.min(MathLib.mulDivUp(params.assets, MathLib.wToRay(MathLib.WAD + params.slippageTolerance), shares), MAX_ABSOLUTE_SHARE_PRICE);
211
+ };
212
+ /**
213
+ * Computes the exact vault-share authorization cap for an asset-denominated exit.
214
+ *
215
+ * The cap covers both the current and deadline-accrued preview. Vault V2 and MetaMorpho 1.0 divide
216
+ * by `1 - slippageTolerance`, rounding up, to cover a share-price decline before inclusion;
217
+ * MetaMorpho 1.1's `lostAssets` clamp keeps that preview upper-bounded without widening it.
218
+ *
219
+ * @param params - Vault snapshot, execution deadline, asset amount, and WAD-scaled slippage.
220
+ * @param params.vaultData - Hydrated Vault V1 `AccrualVault` or Vault V2 `AccrualVaultV2` snapshot.
221
+ * @param params.deadline - Bundle execution deadline as a Unix timestamp in seconds, used for accrual.
222
+ * @param params.assets - Assets withdrawn from the vault, in the underlying token's smallest unit.
223
+ * @param params.slippageTolerance - Accepted share-price decline as a WAD-scaled fraction (`1e18` = 100%).
224
+ * @returns The maximum shares the prepared operation may burn.
225
+ * @throws {NonPositiveInputError} when `assets` or the computed share cap is not positive.
226
+ * @throws {NegativeInputError} when `slippageTolerance` is negative.
227
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
228
+ * @example
229
+ * ```ts
230
+ * import { fetchAccrualVault } from "@morpho-org/blue-sdk-viem";
231
+ * import { computeVaultMaxShareAllowance } from "@morpho-org/morpho-sdk";
232
+ * import { createPublicClient, http } from "viem";
233
+ * import { mainnet } from "viem/chains";
234
+ *
235
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
236
+ * const vaultData = await fetchAccrualVault(
237
+ * "0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB",
238
+ * client,
239
+ * );
240
+ * const { timestamp } = await client.getBlock();
241
+ * const shares = computeVaultMaxShareAllowance({
242
+ * vaultData,
243
+ * deadline: timestamp + 7_200n,
244
+ * assets: 1_000_000n,
245
+ * slippageTolerance: 500_000_000_000_000n,
246
+ * });
247
+ * // shares is the exact allowance or permit value for the prepared exit.
248
+ * ```
249
+ */
250
+ export const computeVaultMaxShareAllowance = (params) => {
251
+ if (params.assets <= 0n) {
252
+ throw new NonPositiveInputError("assets", params.assets);
253
+ }
254
+ validateSlippageTolerance(params.slippageTolerance);
255
+ const isVaultV2 = params.vaultData instanceof AccrualVaultV2;
256
+ const accruedVault = isVaultV2
257
+ ? params.vaultData.accrueInterest(MathLib.max(params.deadline, params.vaultData.lastUpdate)).vault
258
+ : params.vaultData.accrueInterest(params.deadline);
259
+ const previewedShares = MathLib.max(params.vaultData.toShares(params.assets, "Up"), accruedVault.toShares(params.assets, "Up"));
260
+ if (previewedShares <= 0n) {
261
+ throw new NonPositiveInputError("shares", previewedShares);
262
+ }
263
+ const needsLossBuffer = isVaultV2 ||
264
+ !("lostAssets" in params.vaultData) ||
265
+ params.vaultData.lostAssets == null;
266
+ return needsLossBuffer
267
+ ? MathLib.wDivUp(previewedShares, MathLib.WAD - params.slippageTolerance)
268
+ : previewedShares;
269
+ };