@morpho-org/morpho-sdk 7.0.0 → 8.1.0
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.
- package/MIGRATION-v6-to-v7.md +6 -0
- package/MIGRATION-v7-to-v8.md +290 -0
- package/README.md +11 -6
- package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
- package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
- package/lib/cjs/actions/midnight/cancelAndMake.d.ts +17 -71
- package/lib/cjs/actions/midnight/cancelAndMake.js +41 -29
- package/lib/cjs/actions/midnight/redeem.d.ts +8 -1
- package/lib/cjs/actions/midnight/redeem.js +18 -1
- package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
- package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +24 -2
- package/lib/cjs/actions/midnight/supplyCollateral.d.ts +1 -0
- package/lib/cjs/actions/midnight/supplyCollateral.js +3 -0
- package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
- package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +49 -14
- package/lib/cjs/actions/midnight/takeBorrow.d.ts +18 -5
- package/lib/cjs/actions/midnight/takeBorrow.js +44 -12
- package/lib/cjs/actions/midnight/takeLend.d.ts +10 -5
- package/lib/cjs/actions/midnight/takeLend.js +27 -9
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +51 -27
- package/lib/cjs/actions/midnight/takeWithdraw.d.ts +14 -5
- package/lib/cjs/actions/midnight/takeWithdraw.js +40 -9
- package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
- package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +11 -6
- package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
- package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +17 -6
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
- package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
- package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
- package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
- package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
- package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
- package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
- package/lib/cjs/actions/requirements/validateClientChainId.d.ts +26 -0
- package/lib/cjs/actions/requirements/validateClientChainId.js +34 -0
- package/lib/cjs/blue/errors.d.ts +1 -1
- package/lib/cjs/blue/errors.js +3 -1
- package/lib/cjs/blue/types.d.ts +1 -1
- package/lib/cjs/blue/utils.d.ts +1 -1
- package/lib/cjs/blue/utils.js +5 -1
- package/lib/cjs/entities/blue/blue.d.ts +109 -27
- package/lib/cjs/entities/blue/blue.js +103 -28
- package/lib/cjs/entities/index.d.ts +1 -1
- package/lib/cjs/entities/midnight/deadline.d.ts +15 -0
- package/lib/cjs/entities/midnight/deadline.js +24 -0
- package/lib/cjs/entities/midnight/midnight.d.ts +432 -74
- package/lib/cjs/entities/midnight/midnight.js +869 -188
- package/lib/cjs/entities/midnight/publication.d.ts +134 -0
- package/lib/cjs/entities/midnight/publication.js +404 -0
- package/lib/cjs/entities/midnight/types.d.ts +26 -5
- package/lib/cjs/entities/requirements/assertContractCode.d.ts +49 -0
- package/lib/cjs/entities/requirements/assertContractCode.js +79 -0
- package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
- package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +45 -18
- package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
- package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.js +5 -2
- package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
- package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
- package/lib/cjs/entities/vaultV1/vaultV1.d.ts +63 -11
- package/lib/cjs/entities/vaultV1/vaultV1.js +83 -49
- package/lib/cjs/entities/vaultV2/vaultV2.d.ts +54 -12
- package/lib/cjs/entities/vaultV2/vaultV2.js +86 -55
- package/lib/cjs/errors.d.ts +1 -1
- package/lib/cjs/errors.js +4 -2
- package/lib/cjs/helpers/constant.d.ts +5 -0
- package/lib/cjs/helpers/constant.js +6 -1
- package/lib/cjs/helpers/index.d.ts +1 -1
- package/lib/cjs/helpers/index.js +2 -1
- package/lib/cjs/helpers/validate.d.ts +163 -8
- package/lib/cjs/helpers/validate.js +179 -8
- package/lib/cjs/helpers/validateMidnightBounds.d.ts +47 -0
- package/lib/cjs/helpers/validateMidnightBounds.js +79 -0
- package/lib/cjs/helpers/validateMidnightPublication.d.ts +12 -0
- package/lib/cjs/helpers/validateMidnightPublication.js +144 -0
- package/lib/cjs/helpers/validateMidnightReceiver.d.ts +29 -0
- package/lib/cjs/helpers/validateMidnightReceiver.js +84 -0
- package/lib/cjs/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
- package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +231 -0
- package/lib/cjs/index.d.ts +1 -0
- package/lib/cjs/index.js +3 -0
- package/lib/cjs/types/action.d.ts +102 -1
- package/lib/cjs/types/action.js +102 -1
- package/lib/cjs/types/error.d.ts +197 -4
- package/lib/cjs/types/error.js +265 -5
- package/lib/cjs/types/index.d.ts +1 -0
- package/lib/cjs/types/index.js +1 -0
- package/lib/cjs/types/midnightCancelAndMake.d.ts +70 -0
- package/lib/cjs/types/midnightCancelAndMake.js +2 -0
- package/lib/cjs/types/midnightPublicationError.d.ts +332 -0
- package/lib/cjs/types/midnightPublicationError.js +376 -0
- package/lib/cjs/types.d.ts +1 -1
- package/lib/cjs/utils.d.ts +2 -1
- package/lib/cjs/utils.js +8 -2
- package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
- package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
- package/lib/esm/actions/midnight/cancelAndMake.d.ts +17 -71
- package/lib/esm/actions/midnight/cancelAndMake.js +42 -30
- package/lib/esm/actions/midnight/redeem.d.ts +8 -1
- package/lib/esm/actions/midnight/redeem.js +18 -1
- package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
- package/lib/esm/actions/midnight/repayWithdrawCollateral.js +24 -2
- package/lib/esm/actions/midnight/supplyCollateral.d.ts +1 -0
- package/lib/esm/actions/midnight/supplyCollateral.js +3 -0
- package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
- package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +52 -17
- package/lib/esm/actions/midnight/takeBorrow.d.ts +18 -5
- package/lib/esm/actions/midnight/takeBorrow.js +47 -15
- package/lib/esm/actions/midnight/takeLend.d.ts +10 -5
- package/lib/esm/actions/midnight/takeLend.js +27 -9
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +52 -28
- package/lib/esm/actions/midnight/takeWithdraw.d.ts +14 -5
- package/lib/esm/actions/midnight/takeWithdraw.js +41 -10
- package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
- package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +13 -8
- package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
- package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
- package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
- package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +17 -6
- package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
- package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
- package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
- package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
- package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
- package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
- package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
- package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
- package/lib/esm/actions/requirements/validateClientChainId.d.ts +26 -0
- package/lib/esm/actions/requirements/validateClientChainId.js +30 -0
- package/lib/esm/blue/errors.d.ts +1 -1
- package/lib/esm/blue/errors.js +1 -1
- package/lib/esm/blue/types.d.ts +1 -1
- package/lib/esm/blue/utils.d.ts +1 -1
- package/lib/esm/blue/utils.js +1 -1
- package/lib/esm/entities/blue/blue.d.ts +109 -27
- package/lib/esm/entities/blue/blue.js +104 -29
- package/lib/esm/entities/index.d.ts +1 -1
- package/lib/esm/entities/midnight/deadline.d.ts +15 -0
- package/lib/esm/entities/midnight/deadline.js +20 -0
- package/lib/esm/entities/midnight/midnight.d.ts +432 -74
- package/lib/esm/entities/midnight/midnight.js +870 -189
- package/lib/esm/entities/midnight/publication.d.ts +134 -0
- package/lib/esm/entities/midnight/publication.js +397 -0
- package/lib/esm/entities/midnight/types.d.ts +26 -5
- package/lib/esm/entities/requirements/assertContractCode.d.ts +49 -0
- package/lib/esm/entities/requirements/assertContractCode.js +74 -0
- package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
- package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +47 -20
- package/lib/esm/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
- package/lib/esm/entities/requirements/getUnusedPermit2Nonce.js +5 -2
- package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
- package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
- package/lib/esm/entities/vaultV1/vaultV1.d.ts +63 -11
- package/lib/esm/entities/vaultV1/vaultV1.js +85 -51
- package/lib/esm/entities/vaultV2/vaultV2.d.ts +54 -12
- package/lib/esm/entities/vaultV2/vaultV2.js +88 -57
- package/lib/esm/errors.d.ts +1 -1
- package/lib/esm/errors.js +1 -1
- package/lib/esm/helpers/constant.d.ts +5 -0
- package/lib/esm/helpers/constant.js +5 -0
- package/lib/esm/helpers/index.d.ts +1 -1
- package/lib/esm/helpers/index.js +1 -1
- package/lib/esm/helpers/validate.d.ts +163 -8
- package/lib/esm/helpers/validate.js +177 -7
- package/lib/esm/helpers/validateMidnightBounds.d.ts +47 -0
- package/lib/esm/helpers/validateMidnightBounds.js +72 -0
- package/lib/esm/helpers/validateMidnightPublication.d.ts +12 -0
- package/lib/esm/helpers/validateMidnightPublication.js +139 -0
- package/lib/esm/helpers/validateMidnightReceiver.d.ts +29 -0
- package/lib/esm/helpers/validateMidnightReceiver.js +80 -0
- package/lib/esm/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
- package/lib/esm/helpers/validateMidnightTakeFeasibility.js +226 -0
- package/lib/esm/index.d.ts +1 -0
- package/lib/esm/index.js +1 -0
- package/lib/esm/types/action.d.ts +102 -1
- package/lib/esm/types/action.js +102 -1
- package/lib/esm/types/error.d.ts +197 -4
- package/lib/esm/types/error.js +253 -2
- package/lib/esm/types/index.d.ts +1 -0
- package/lib/esm/types/index.js +1 -0
- package/lib/esm/types/midnightCancelAndMake.d.ts +70 -0
- package/lib/esm/types/midnightCancelAndMake.js +1 -0
- package/lib/esm/types/midnightPublicationError.d.ts +332 -0
- package/lib/esm/types/midnightPublicationError.js +359 -0
- package/lib/esm/types.d.ts +1 -1
- package/lib/esm/utils.d.ts +2 -1
- package/lib/esm/utils.js +2 -1
- package/package.json +10 -10
|
@@ -2,21 +2,32 @@ import { MarketUtils as BlueMarketUtils, MathLib, UnsupportedMarketIrmError, } f
|
|
|
2
2
|
import { fetchMarket as fetchBlueMarket } from "@morpho-org/blue-sdk-viem";
|
|
3
3
|
import { fetchAccrualPosition, fetchMarket, MarketParams, MarketUtils, Payload, PriceRatifierV1, RateRatifierV1, Tree, } from "@morpho-org/midnight-sdk";
|
|
4
4
|
import { _try, getChainAddress, Time } from "@morpho-org/morpho-ts";
|
|
5
|
-
import { isAddressEqual } from "viem";
|
|
5
|
+
import { isAddress, isAddressEqual, maxUint256, zeroAddress, } from "viem";
|
|
6
6
|
import { midnightCancelAndMake, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, midnightTakeRepayWithdrawCollateral, midnightTakeWithdraw, } from "../../actions/midnight/index.js";
|
|
7
7
|
import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, } from "../../actions/requirements/index.js";
|
|
8
|
+
import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
|
|
8
9
|
import { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "../../helpers/callback.js";
|
|
9
10
|
import { MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS } from "../../helpers/constant.js";
|
|
10
|
-
import { validateChainId } from "../../helpers/index.js";
|
|
11
|
+
import { getMidnightMaxSafeDebt, validateChainId, } from "../../helpers/index.js";
|
|
12
|
+
import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
|
|
11
13
|
import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
|
|
14
|
+
import { validateMidnightTakeFeasibility } from "../../helpers/validateMidnightTakeFeasibility.js";
|
|
12
15
|
import { validateOfferSides } from "../../helpers/validateOfferSides.js";
|
|
13
|
-
import { AccrualPositionUserMismatchError,
|
|
14
|
-
|
|
16
|
+
import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, EmptyBlueParkingMarketError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
|
|
17
|
+
import { validateMidnightDeadline } from "./deadline.js";
|
|
18
|
+
import { fetchMidnightMakerOfferStates, offerMarketParams, validateMidnightMakerOfferCallbacks, validateMidnightMakerOfferStates, } from "./publication.js";
|
|
19
|
+
const validatePositionBinding = (params) => {
|
|
20
|
+
if (params.positionData.marketId !== params.marketData.id) {
|
|
21
|
+
throw new MarketIdMismatchError(params.positionData.marketId, params.marketData.id);
|
|
22
|
+
}
|
|
23
|
+
if (!isAddressEqual(params.positionData.user, params.accountAddress)) {
|
|
24
|
+
throw new AccrualPositionUserMismatchError(params.positionData.user, params.accountAddress);
|
|
25
|
+
}
|
|
26
|
+
};
|
|
15
27
|
const validateTakeDeadlineWindow = (deadline) => {
|
|
16
28
|
const now = Time.timestamp();
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}
|
|
29
|
+
// Throws when the deadline is at or before now.
|
|
30
|
+
validateMidnightDeadline(deadline, now);
|
|
20
31
|
const maxDeadline = now + MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
|
|
21
32
|
if (deadline > maxDeadline) {
|
|
22
33
|
throw new MidnightTakeDeadlineTooFarError({ deadline, maxDeadline });
|
|
@@ -36,6 +47,98 @@ const rejectReduceOnlyOffers = (offers) => {
|
|
|
36
47
|
throw new MidnightOfferReduceOnlyError({ index });
|
|
37
48
|
});
|
|
38
49
|
};
|
|
50
|
+
const getOffersDataInternal = async ({ client, chainId, params, marketCreationTime = "expiry", }) => {
|
|
51
|
+
validateChainId(client.viemClient.chain?.id, chainId);
|
|
52
|
+
const tree = Tree.from(params.offers);
|
|
53
|
+
const midnight = getChainAddress(chainId, "midnight");
|
|
54
|
+
tree.offers.forEach((offer, index) => {
|
|
55
|
+
if (!isAddressEqual(offer.maker, params.accountAddress)) {
|
|
56
|
+
throw new MidnightOfferMakerMismatchError({
|
|
57
|
+
index,
|
|
58
|
+
expectedMaker: params.accountAddress,
|
|
59
|
+
actualMaker: offer.maker,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
if (offer.continuousFeeCap !== 0n) {
|
|
63
|
+
throw new MidnightOfferContinuousFeeCapError({
|
|
64
|
+
index,
|
|
65
|
+
continuousFeeCap: offer.continuousFeeCap,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
if (!offer.buy &&
|
|
69
|
+
!isAddressEqual(offer.receiverIfMakerIsSeller, offer.maker)) {
|
|
70
|
+
throw new MidnightOfferSellerReceiverMismatchError({
|
|
71
|
+
index,
|
|
72
|
+
expectedReceiver: offer.maker,
|
|
73
|
+
actualReceiver: offer.receiverIfMakerIsSeller,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
const market = offerMarketParams(offer);
|
|
77
|
+
if (market.chainId !== BigInt(chainId)) {
|
|
78
|
+
throw new MidnightOfferMarketChainMismatchError({
|
|
79
|
+
index,
|
|
80
|
+
expectedChainId: chainId,
|
|
81
|
+
actualChainId: market.chainId,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
if (!isAddressEqual(market.midnight, midnight)) {
|
|
85
|
+
throw new MidnightOfferMarketAddressMismatchError({
|
|
86
|
+
index,
|
|
87
|
+
expectedMidnight: midnight,
|
|
88
|
+
actualMidnight: market.midnight,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
const ratifierType = tree.type;
|
|
93
|
+
const ratifier = getChainAddress(chainId, ratifierType === "priceV1" ? "priceRatifierV1" : "rateRatifierV1");
|
|
94
|
+
tree.offers.forEach((offer, index) => {
|
|
95
|
+
if (!isAddressEqual(offer.ratifier, ratifier)) {
|
|
96
|
+
throw new MidnightOfferRatifierMismatchError({
|
|
97
|
+
index,
|
|
98
|
+
expectedRatifier: ratifier,
|
|
99
|
+
actualRatifier: offer.ratifier,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
const { states, now } = await fetchMidnightMakerOfferStates({
|
|
104
|
+
client: client.viemClient,
|
|
105
|
+
chainId,
|
|
106
|
+
tree,
|
|
107
|
+
});
|
|
108
|
+
validateMidnightMakerOfferStates({
|
|
109
|
+
tree,
|
|
110
|
+
states,
|
|
111
|
+
now,
|
|
112
|
+
marketCreationTime,
|
|
113
|
+
});
|
|
114
|
+
const groups = [];
|
|
115
|
+
const seenGroups = new Set();
|
|
116
|
+
for (const offer of tree.offers) {
|
|
117
|
+
const group = offer.group;
|
|
118
|
+
const key = group.toLowerCase();
|
|
119
|
+
if (!seenGroups.has(key)) {
|
|
120
|
+
seenGroups.add(key);
|
|
121
|
+
groups.push(group);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (params.validation !== false) {
|
|
125
|
+
await tree.mempoolValidate({
|
|
126
|
+
...params.validation,
|
|
127
|
+
chainId,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
const items = tree.type === "priceV1"
|
|
131
|
+
? PriceRatifierV1.ratify({ tree })
|
|
132
|
+
: RateRatifierV1.ratify({ tree });
|
|
133
|
+
return {
|
|
134
|
+
accountAddress: params.accountAddress,
|
|
135
|
+
groups,
|
|
136
|
+
tree,
|
|
137
|
+
ratifierType,
|
|
138
|
+
ratifier,
|
|
139
|
+
payload: await Payload.encode(items),
|
|
140
|
+
};
|
|
141
|
+
};
|
|
39
142
|
const validateMarketData = (market, chainId) => {
|
|
40
143
|
// Reject snapshots from another chain deployment before exposing requirements.
|
|
41
144
|
validateMidnightMarket({ market, chainId });
|
|
@@ -78,7 +181,8 @@ export class MorphoMidnight {
|
|
|
78
181
|
* @param marketId - Market id to fetch.
|
|
79
182
|
* @param parameters - Optional block, account, and state-override parameters forwarded to every read.
|
|
80
183
|
* @returns The market parameters and current onchain market state.
|
|
81
|
-
* @throws {ChainIdMismatchError} when the client chain
|
|
184
|
+
* @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, another chain than this entity's.
|
|
185
|
+
* @throws {viem.BaseError} when the `eth_chainId` request or a state read fails.
|
|
82
186
|
* @example
|
|
83
187
|
* ```ts
|
|
84
188
|
* const midnight = client.morpho.midnight(8453);
|
|
@@ -88,7 +192,7 @@ export class MorphoMidnight {
|
|
|
88
192
|
* ```
|
|
89
193
|
*/
|
|
90
194
|
async getMarketData(marketId, parameters) {
|
|
91
|
-
|
|
195
|
+
await validateClientChainId(this.client.viemClient, this.chainId);
|
|
92
196
|
return await fetchMarket(this.client.viemClient, {
|
|
93
197
|
...parameters,
|
|
94
198
|
marketId,
|
|
@@ -105,7 +209,8 @@ export class MorphoMidnight {
|
|
|
105
209
|
* @param params.accountAddress - Position owner address.
|
|
106
210
|
* @param params.parameters - Optional block, account, and state-override parameters forwarded to every read.
|
|
107
211
|
* @returns The account's position paired with the fetched market.
|
|
108
|
-
* @throws {ChainIdMismatchError} when the client chain
|
|
212
|
+
* @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, another chain than this entity's.
|
|
213
|
+
* @throws {viem.BaseError} when the `eth_chainId` request or a state read fails.
|
|
109
214
|
* @example
|
|
110
215
|
* ```ts
|
|
111
216
|
* const positionData = await midnight.getPositionData({
|
|
@@ -116,7 +221,7 @@ export class MorphoMidnight {
|
|
|
116
221
|
* ```
|
|
117
222
|
*/
|
|
118
223
|
async getPositionData(params) {
|
|
119
|
-
|
|
224
|
+
await validateClientChainId(this.client.viemClient, this.chainId);
|
|
120
225
|
return fetchAccrualPosition(this.client.viemClient, {
|
|
121
226
|
...params.parameters,
|
|
122
227
|
deployless: this.client.options.supportDeployless,
|
|
@@ -125,16 +230,21 @@ export class MorphoMidnight {
|
|
|
125
230
|
});
|
|
126
231
|
}
|
|
127
232
|
/**
|
|
128
|
-
*
|
|
233
|
+
* Checks the RPC chain and reads Midnight state at one pinned block, then rejects unfillable offers
|
|
234
|
+
* before calling the mempool API unless `validation: false` skips that call. Reads market state,
|
|
235
|
+
* group consumption, maker credit and debt,
|
|
236
|
+
* plus the default continuous fee, LLTV and liquidation-cursor enablement, and oracle code for
|
|
237
|
+
* uncreated markets.
|
|
129
238
|
*
|
|
130
239
|
* @param params - Maker account, PriceRatifierV1 or RateRatifierV1 tree input, and optional API validation controls.
|
|
131
240
|
* @param params.accountAddress - Maker expected on every offer.
|
|
132
241
|
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
133
|
-
* @param params.validation -
|
|
242
|
+
* @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
|
|
134
243
|
* @returns Prepared tree, groups, ratifier, and encoded payload used by maker flows.
|
|
135
|
-
* @throws {ChainIdMismatchError} when the client chain
|
|
244
|
+
* @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, another chain than this entity's.
|
|
136
245
|
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
137
|
-
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
246
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
247
|
+
* (not thrown when `validation` is `false`).
|
|
138
248
|
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
139
249
|
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
140
250
|
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
@@ -142,6 +252,20 @@ export class MorphoMidnight {
|
|
|
142
252
|
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
143
253
|
* @throws {UnknownAddressError} when the chain has no deployment for the tree's V1 ratifier.
|
|
144
254
|
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
255
|
+
* @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
|
|
256
|
+
* @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
|
|
257
|
+
* @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
|
|
258
|
+
* @throws {MidnightOfferGroupConsumedError} when an offer group has no remaining capacity.
|
|
259
|
+
* @throws {MidnightOfferTickSpacingError} when an offer tick is not accessible in its market.
|
|
260
|
+
* @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} when the market fee exceeds an offer's cap.
|
|
261
|
+
* @throws {MidnightOfferZeroPriceSellError} when a sell offer has a zero tick.
|
|
262
|
+
* @throws {MidnightOfferRateBoundUnreachableError} when a Rate V1 offer cannot satisfy its bound.
|
|
263
|
+
* @throws {MidnightOfferNoDebtError} when a reduce-only buy is submitted without maker debt.
|
|
264
|
+
* @throws {MidnightOfferNoCreditError} when a reduce-only sell is submitted without maker credit.
|
|
265
|
+
* @throws {MidnightMarketMaturityTooFarError} when an uncreated market's maturity is more than 100 years after the offer's expiry.
|
|
266
|
+
* @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
|
|
267
|
+
* @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
|
|
268
|
+
* @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
|
|
145
269
|
* @example
|
|
146
270
|
* ```ts
|
|
147
271
|
* const offersData = await midnight.getOffersData({
|
|
@@ -151,87 +275,18 @@ export class MorphoMidnight {
|
|
|
151
275
|
* ```
|
|
152
276
|
*/
|
|
153
277
|
async getOffersData(params) {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const midnight = getChainAddress(this.chainId, "midnight");
|
|
157
|
-
tree.offers.forEach((offer, index) => {
|
|
158
|
-
if (!isAddressEqual(offer.maker, params.accountAddress)) {
|
|
159
|
-
throw new MidnightOfferMakerMismatchError({
|
|
160
|
-
index,
|
|
161
|
-
expectedMaker: params.accountAddress,
|
|
162
|
-
actualMaker: offer.maker,
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
if (offer.continuousFeeCap !== 0n) {
|
|
166
|
-
throw new MidnightOfferContinuousFeeCapError({
|
|
167
|
-
index,
|
|
168
|
-
continuousFeeCap: offer.continuousFeeCap,
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
if (!offer.buy &&
|
|
172
|
-
!isAddressEqual(offer.receiverIfMakerIsSeller, offer.maker)) {
|
|
173
|
-
throw new MidnightOfferSellerReceiverMismatchError({
|
|
174
|
-
index,
|
|
175
|
-
expectedReceiver: offer.maker,
|
|
176
|
-
actualReceiver: offer.receiverIfMakerIsSeller,
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
const market = offerMarketParams(offer);
|
|
180
|
-
if (market.chainId !== BigInt(this.chainId)) {
|
|
181
|
-
throw new MidnightOfferMarketChainMismatchError({
|
|
182
|
-
index,
|
|
183
|
-
expectedChainId: this.chainId,
|
|
184
|
-
actualChainId: market.chainId,
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
if (!isAddressEqual(market.midnight, midnight)) {
|
|
188
|
-
throw new MidnightOfferMarketAddressMismatchError({
|
|
189
|
-
index,
|
|
190
|
-
expectedMidnight: midnight,
|
|
191
|
-
actualMidnight: market.midnight,
|
|
192
|
-
});
|
|
193
|
-
}
|
|
194
|
-
});
|
|
195
|
-
const ratifierType = tree.type;
|
|
196
|
-
const ratifier = getChainAddress(this.chainId, ratifierType === "priceV1" ? "priceRatifierV1" : "rateRatifierV1");
|
|
197
|
-
tree.offers.forEach((offer, index) => {
|
|
198
|
-
if (!isAddressEqual(offer.ratifier, ratifier)) {
|
|
199
|
-
throw new MidnightOfferRatifierMismatchError({
|
|
200
|
-
index,
|
|
201
|
-
expectedRatifier: ratifier,
|
|
202
|
-
actualRatifier: offer.ratifier,
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
});
|
|
206
|
-
const groups = [];
|
|
207
|
-
const seenGroups = new Set();
|
|
208
|
-
for (const offer of tree.offers) {
|
|
209
|
-
const group = offer.group;
|
|
210
|
-
const key = group.toLowerCase();
|
|
211
|
-
if (!seenGroups.has(key)) {
|
|
212
|
-
seenGroups.add(key);
|
|
213
|
-
groups.push(group);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
await tree.mempoolValidate({
|
|
217
|
-
...params.validation,
|
|
278
|
+
return getOffersDataInternal({
|
|
279
|
+
client: this.client,
|
|
218
280
|
chainId: this.chainId,
|
|
281
|
+
params,
|
|
219
282
|
});
|
|
220
|
-
const items = tree.type === "priceV1"
|
|
221
|
-
? PriceRatifierV1.ratify({ tree })
|
|
222
|
-
: RateRatifierV1.ratify({ tree });
|
|
223
|
-
return {
|
|
224
|
-
accountAddress: params.accountAddress,
|
|
225
|
-
groups,
|
|
226
|
-
tree,
|
|
227
|
-
ratifierType,
|
|
228
|
-
ratifier,
|
|
229
|
-
payload: await Payload.encode(items),
|
|
230
|
-
};
|
|
231
283
|
}
|
|
232
284
|
/**
|
|
233
285
|
* Prepares a `MidnightBundlesV2` buy that lends into borrow-side offers for `accountAddress`.
|
|
234
286
|
*
|
|
287
|
+
* On an assets target, sell offers whose tick is out of range or whose buyer price is zero or
|
|
288
|
+
* above one are dropped from the transaction because one of them would revert the whole bundle.
|
|
289
|
+
*
|
|
235
290
|
* @param params - Lender, market snapshot, buy target, offers, fee cap, deadline, and optional referral fee.
|
|
236
291
|
* @param params.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
|
|
237
292
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
@@ -249,15 +304,20 @@ export class MorphoMidnight {
|
|
|
249
304
|
* @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
|
|
250
305
|
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
251
306
|
* @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
|
|
252
|
-
* @throws {ChainIdMismatchError} when client or market data targets another chain
|
|
307
|
+
* @throws {ChainIdMismatchError} when client or market data targets another chain, or from
|
|
308
|
+
* `getRequirements()` when the RPC reports another chain via `eth_chainId`.
|
|
309
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
310
|
+
* RPC read fails.
|
|
253
311
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
254
312
|
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
255
|
-
* @throws {InputExceedsMaxError} when
|
|
256
|
-
*
|
|
257
|
-
*
|
|
313
|
+
* @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`, when
|
|
314
|
+
* `target.maxBuyerAssets` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a
|
|
315
|
+
* higher ceiling gives no slippage protection), when `maxContinuousFee` exceeds `uint256`, or
|
|
316
|
+
* when `nativeAmount` exceeds the maximum wNative amount this call can pull.
|
|
258
317
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
259
318
|
* @throws {NonPositiveInputError} when the target amount, `minUnits` or `maxBuyerAssets` is not positive.
|
|
260
|
-
* @throws {NegativeInputError} when
|
|
319
|
+
* @throws {NegativeInputError} when a takeable offer cap, `maxContinuousFee`,
|
|
320
|
+
* `referralFeePct` or `nativeAmount` is negative.
|
|
261
321
|
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
262
322
|
* @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
|
|
263
323
|
* @throws {UnboundedMidnightTakeInputError} when `target.units` or
|
|
@@ -268,7 +328,17 @@ export class MorphoMidnight {
|
|
|
268
328
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
269
329
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
270
330
|
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
331
|
+
* @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
|
|
271
332
|
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
333
|
+
* @throws {MidnightContinuousFeeAboveMaxError} when `maxContinuousFee` is below the market's
|
|
334
|
+
* current continuous fee.
|
|
335
|
+
* @throws {MidnightTakeableOffersNotFillableError} when every takeable offer is expired, not yet
|
|
336
|
+
* started, self-made, capped below the market fee or otherwise dead.
|
|
337
|
+
* @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
|
|
338
|
+
* its bounds cannot hold at any fill, or a buy assets target's `minUnits` exceeds the live
|
|
339
|
+
* offers plus the fallback.
|
|
340
|
+
* @throws {MidnightContractReceiverError} when `referralFeeRecipient` is a Midnight protocol
|
|
341
|
+
* contract or a market token contract with a positive referral fee.
|
|
272
342
|
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
|
|
273
343
|
* @example
|
|
274
344
|
* ```ts
|
|
@@ -286,7 +356,7 @@ export class MorphoMidnight {
|
|
|
286
356
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
287
357
|
validateTakeDeadlineWindow(params.deadline);
|
|
288
358
|
const market = params.marketData.params;
|
|
289
|
-
const
|
|
359
|
+
const rawParams = {
|
|
290
360
|
chainId: this.chainId,
|
|
291
361
|
market,
|
|
292
362
|
target: params.target,
|
|
@@ -297,7 +367,23 @@ export class MorphoMidnight {
|
|
|
297
367
|
referralFeePct: params.referralFeePct,
|
|
298
368
|
referralFeeRecipient: params.referralFeeRecipient,
|
|
299
369
|
metadata: this.client.options.metadata,
|
|
370
|
+
};
|
|
371
|
+
let tx = midnightTakeLend(rawParams);
|
|
372
|
+
const takeableOffers = validateMidnightTakeFeasibility({
|
|
373
|
+
side: "buy",
|
|
374
|
+
takeableOffers: params.takeableOffers,
|
|
375
|
+
accountAddress: params.accountAddress,
|
|
376
|
+
marketData: params.marketData,
|
|
377
|
+
now: Time.timestamp(),
|
|
378
|
+
deadline: params.deadline,
|
|
379
|
+
referralFeePct: tx.action.args.referralFeePct,
|
|
380
|
+
fallbackUnits: 0n,
|
|
381
|
+
target: params.target,
|
|
382
|
+
maxContinuousFee: params.maxContinuousFee,
|
|
300
383
|
});
|
|
384
|
+
if (takeableOffers !== params.takeableOffers) {
|
|
385
|
+
tx = midnightTakeLend({ ...rawParams, takeableOffers });
|
|
386
|
+
}
|
|
301
387
|
const pulledAssets = params.target.type === "assets"
|
|
302
388
|
? params.target.assets
|
|
303
389
|
: params.target.maxBuyerAssets;
|
|
@@ -324,39 +410,85 @@ export class MorphoMidnight {
|
|
|
324
410
|
* The bundle first withdraws as much of the sender's existing credit as the target and market
|
|
325
411
|
* liquidity allow, then fills the rest from offers.
|
|
326
412
|
*
|
|
413
|
+
* Buy offers whose tick is out of range, whose price is zero, or whose price stays below the
|
|
414
|
+
* settlement fee until `deadline` (at or below it on an assets target) are dropped from the transaction because one of them would
|
|
415
|
+
* revert the whole bundle.
|
|
416
|
+
*
|
|
327
417
|
* @param params - Borrower, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
|
|
328
418
|
* @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
|
|
329
419
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
420
|
+
* @param params.positionData - Owner-bound position snapshot returned by `getPositionData`. The
|
|
421
|
+
* `DEFAULT_LLTV_BUFFER` check is only as current as this snapshot and `collateralPrices`: it
|
|
422
|
+
* does not see transactions mined or prices moved since, so two transactions built from one
|
|
423
|
+
* snapshot can together end inside the buffer. Midnight still rejects any position above
|
|
424
|
+
* LLTV onchain. Midnight debt and collateral do not accrue, so the check needs no accrual.
|
|
425
|
+
* @param params.collateralPrices - Values from `price()` on each
|
|
426
|
+
* `marketData.params.collateralParams[i].oracle`, indexed like `positionData.collateral` and
|
|
427
|
+
* scaled by `ORACLE_PRICE_SCALE`. A price is required for every held or supplied collateral
|
|
428
|
+
* index, because debt after a borrow is always positive.
|
|
330
429
|
* @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
|
|
331
430
|
* @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
|
|
431
|
+
* Midnight protocol and market token contracts are rejected.
|
|
332
432
|
* @param params.takeableOffers - Lend-side offers returned by the Midnight API.
|
|
333
433
|
* @param params.deadline - Bounded bundle execution deadline timestamp.
|
|
334
434
|
* @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
|
|
335
435
|
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
336
436
|
* @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
|
|
337
|
-
* @throws {ChainIdMismatchError} when client or market data targets another chain
|
|
437
|
+
* @throws {ChainIdMismatchError} when client or market data targets another chain, or from
|
|
438
|
+
* `getRequirements()` when the RPC reports another chain via `eth_chainId`.
|
|
439
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
440
|
+
* RPC read fails.
|
|
338
441
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
339
442
|
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
340
|
-
* @throws {InputExceedsMaxError} when
|
|
341
|
-
*
|
|
443
|
+
* @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`, or when
|
|
444
|
+
* `target.maxUnits` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a higher
|
|
445
|
+
* ceiling gives no slippage protection).
|
|
342
446
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
343
447
|
* @throws {NonPositiveInputError} when the target amount, `maxUnits` or `minSellerAssets` is not positive.
|
|
344
|
-
* @throws {NegativeInputError} when `referralFeePct` is negative.
|
|
448
|
+
* @throws {NegativeInputError} when a takeable offer cap or `referralFeePct` is negative.
|
|
345
449
|
* @throws {UnboundedMidnightTakeInputError} when `target.units` or
|
|
346
450
|
* `target.maxUnits` is `maxUint256`.
|
|
347
451
|
* @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
|
|
452
|
+
* @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
|
|
453
|
+
* market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
|
|
348
454
|
* @throws {ExpiredDeadlineError} when `deadline` has expired.
|
|
349
455
|
* @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
|
|
350
456
|
* @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
|
|
351
457
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
352
458
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
459
|
+
* @throws {AccrualPositionUserMismatchError} when `positionData.user` differs from `accountAddress`.
|
|
460
|
+
* @throws {MarketIdMismatchError} when `positionData.marketId` differs from `marketData.id`.
|
|
461
|
+
* @throws {UnknownCollateralIndexError} when held collateral uses an unconfigured index.
|
|
462
|
+
* @throws {MissingMarketPriceError} when a held collateral index has no supplied price.
|
|
463
|
+
* @throws {BorrowExceedsSafeLtvError} when the post-borrow debt exceeds buffered collateral capacity.
|
|
353
464
|
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
465
|
+
* @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
|
|
354
466
|
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
467
|
+
* @throws {MidnightTakeableOffersNotFillableError} when every takeable offer is expired, not yet
|
|
468
|
+
* started, self-made, capped below the market fee or otherwise dead, and no credit withdrawal can fill instead,
|
|
469
|
+
* or when every offer is dropped for an out-of-range tick, a zero price, or a price below the
|
|
470
|
+
* settlement fee until `deadline` (at or below it on an assets target), even with a credit
|
|
471
|
+
* withdrawal.
|
|
472
|
+
* @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
|
|
473
|
+
* its bounds cannot hold at any fill.
|
|
355
474
|
* @example
|
|
356
475
|
* ```ts
|
|
476
|
+
* import { blueOracleAbi } from "@morpho-org/morpho-sdk/abis";
|
|
477
|
+
*
|
|
478
|
+
* const collateralPrices = await Promise.all(
|
|
479
|
+
* marketData.params.collateralParams.map(({ oracle }) =>
|
|
480
|
+
* client.readContract({
|
|
481
|
+
* address: oracle,
|
|
482
|
+
* abi: blueOracleAbi,
|
|
483
|
+
* functionName: "price",
|
|
484
|
+
* }),
|
|
485
|
+
* ),
|
|
486
|
+
* );
|
|
357
487
|
* const output = midnight.takeBorrow({
|
|
358
488
|
* accountAddress: borrower,
|
|
359
489
|
* marketData,
|
|
490
|
+
* positionData,
|
|
491
|
+
* collateralPrices,
|
|
360
492
|
* target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
|
|
361
493
|
* takeableOffers: quote.data.takeableOffers,
|
|
362
494
|
* deadline: Time.timestamp() + 600n,
|
|
@@ -366,7 +498,7 @@ export class MorphoMidnight {
|
|
|
366
498
|
takeBorrow(params) {
|
|
367
499
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
368
500
|
validateTakeDeadlineWindow(params.deadline);
|
|
369
|
-
const
|
|
501
|
+
const rawParams = {
|
|
370
502
|
chainId: this.chainId,
|
|
371
503
|
market: params.marketData.params,
|
|
372
504
|
target: params.target,
|
|
@@ -376,7 +508,45 @@ export class MorphoMidnight {
|
|
|
376
508
|
referralFeePct: params.referralFeePct,
|
|
377
509
|
referralFeeRecipient: params.referralFeeRecipient,
|
|
378
510
|
metadata: this.client.options.metadata,
|
|
511
|
+
};
|
|
512
|
+
let tx = midnightTakeBorrow(rawParams);
|
|
513
|
+
validatePositionBinding({
|
|
514
|
+
positionData: params.positionData,
|
|
515
|
+
accountAddress: params.accountAddress,
|
|
516
|
+
marketData: params.marketData,
|
|
379
517
|
});
|
|
518
|
+
const requestedUnits = params.target.type === "units"
|
|
519
|
+
? params.target.units
|
|
520
|
+
: params.target.maxUnits;
|
|
521
|
+
const postDebt = params.positionData.debt + requestedUnits;
|
|
522
|
+
if (postDebt > 0n) {
|
|
523
|
+
const maxSafeDebt = getMidnightMaxSafeDebt({
|
|
524
|
+
market: params.marketData,
|
|
525
|
+
collateral: params.positionData.collateral,
|
|
526
|
+
collateralPrices: params.collateralPrices,
|
|
527
|
+
});
|
|
528
|
+
if (postDebt > maxSafeDebt) {
|
|
529
|
+
throw new BorrowExceedsSafeLtvError(requestedUnits, MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
const now = Time.timestamp();
|
|
533
|
+
const takeableOffers = validateMidnightTakeFeasibility({
|
|
534
|
+
side: "sell",
|
|
535
|
+
takeableOffers: params.takeableOffers,
|
|
536
|
+
accountAddress: params.accountAddress,
|
|
537
|
+
marketData: params.marketData,
|
|
538
|
+
now,
|
|
539
|
+
deadline: params.deadline,
|
|
540
|
+
referralFeePct: tx.action.args.referralFeePct,
|
|
541
|
+
// Credit is withdrawn first, up to the market's withdrawable liquidity.
|
|
542
|
+
fallbackUnits: MathLib.min(params.positionData.credit, params.marketData.withdrawable),
|
|
543
|
+
credit: params.positionData.credit,
|
|
544
|
+
target: params.target,
|
|
545
|
+
increasesDebt: true,
|
|
546
|
+
});
|
|
547
|
+
if (takeableOffers !== params.takeableOffers) {
|
|
548
|
+
tx = midnightTakeBorrow({ ...rawParams, takeableOffers });
|
|
549
|
+
}
|
|
380
550
|
return {
|
|
381
551
|
getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
|
|
382
552
|
buildTx: () => tx,
|
|
@@ -389,33 +559,53 @@ export class MorphoMidnight {
|
|
|
389
559
|
* the rest to lend-side offers. `reduceOnly` is always set, so it never opens debt. Use `redeem`
|
|
390
560
|
* for a direct redemption without offers.
|
|
391
561
|
*
|
|
562
|
+
* Buy offers whose tick is out of range, whose price is zero, or whose price stays below the
|
|
563
|
+
* settlement fee until `deadline` (at or below it on an assets target) are dropped from the transaction because one of them would
|
|
564
|
+
* revert the whole bundle.
|
|
565
|
+
*
|
|
392
566
|
* @param params - Lender, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
|
|
393
567
|
* @param params.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
|
|
394
568
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
395
569
|
* @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
|
|
396
570
|
* @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
|
|
571
|
+
* Midnight protocol and market token contracts are rejected.
|
|
397
572
|
* @param params.takeableOffers - Lend-side offers returned by the Midnight API.
|
|
398
573
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
399
574
|
* @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
|
|
400
575
|
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
401
576
|
* @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
|
|
402
|
-
* @throws {ChainIdMismatchError} when client or market data targets another chain
|
|
577
|
+
* @throws {ChainIdMismatchError} when client or market data targets another chain, or from
|
|
578
|
+
* `getRequirements()` when the RPC reports another chain via `eth_chainId`.
|
|
579
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
580
|
+
* RPC read fails.
|
|
403
581
|
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
404
582
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
405
|
-
* @throws {InputExceedsMaxError} when
|
|
406
|
-
*
|
|
583
|
+
* @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`, or when
|
|
584
|
+
* `target.maxUnits` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a higher
|
|
585
|
+
* ceiling gives no slippage protection).
|
|
407
586
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
408
587
|
* @throws {NonPositiveInputError} when the target amount, `maxUnits` or `minSellerAssets` is
|
|
409
588
|
* not positive.
|
|
410
|
-
* @throws {NegativeInputError} when `referralFeePct` is negative.
|
|
589
|
+
* @throws {NegativeInputError} when a takeable offer cap or `referralFeePct` is negative.
|
|
411
590
|
* @throws {UnboundedMidnightTakeInputError} when `target.units` or `target.maxUnits` is `maxUint256`.
|
|
591
|
+
* @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
|
|
592
|
+
* @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
|
|
593
|
+
* market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
|
|
412
594
|
* @throws {ExpiredDeadlineError} when `deadline` has expired.
|
|
413
595
|
* @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
|
|
414
596
|
* @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
|
|
415
597
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
416
598
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
417
599
|
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
600
|
+
* @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
|
|
418
601
|
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
602
|
+
* @throws {MidnightTakeableOffersNotFillableError} when every takeable offer is expired, not yet
|
|
603
|
+
* started, self-made, capped below the market fee or otherwise dead, and no credit withdrawal can fill instead,
|
|
604
|
+
* or when every offer is dropped for an out-of-range tick, a zero price, or a price below the
|
|
605
|
+
* settlement fee until `deadline` (at or below it on an assets target), even with a credit
|
|
606
|
+
* withdrawal.
|
|
607
|
+
* @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
|
|
608
|
+
* its bounds cannot hold at any fill.
|
|
419
609
|
* @example
|
|
420
610
|
* ```ts
|
|
421
611
|
* const output = midnight.takeWithdraw({
|
|
@@ -430,7 +620,7 @@ export class MorphoMidnight {
|
|
|
430
620
|
takeWithdraw(params) {
|
|
431
621
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
432
622
|
validateTakeDeadlineWindow(params.deadline);
|
|
433
|
-
const
|
|
623
|
+
const rawParams = {
|
|
434
624
|
chainId: this.chainId,
|
|
435
625
|
market: params.marketData.params,
|
|
436
626
|
target: params.target,
|
|
@@ -440,7 +630,24 @@ export class MorphoMidnight {
|
|
|
440
630
|
referralFeePct: params.referralFeePct,
|
|
441
631
|
referralFeeRecipient: params.referralFeeRecipient,
|
|
442
632
|
metadata: this.client.options.metadata,
|
|
633
|
+
};
|
|
634
|
+
let tx = midnightTakeWithdraw(rawParams);
|
|
635
|
+
const takeableOffers = validateMidnightTakeFeasibility({
|
|
636
|
+
side: "sell",
|
|
637
|
+
takeableOffers: params.takeableOffers,
|
|
638
|
+
accountAddress: params.accountAddress,
|
|
639
|
+
marketData: params.marketData,
|
|
640
|
+
now: Time.timestamp(),
|
|
641
|
+
deadline: params.deadline,
|
|
642
|
+
referralFeePct: tx.action.args.referralFeePct,
|
|
643
|
+
// The bundle redeems credit first, up to the market's withdrawable liquidity.
|
|
644
|
+
fallbackUnits: params.marketData.withdrawable,
|
|
645
|
+
target: params.target,
|
|
646
|
+
increasesDebt: false,
|
|
443
647
|
});
|
|
648
|
+
if (takeableOffers !== params.takeableOffers) {
|
|
649
|
+
tx = midnightTakeWithdraw({ ...rawParams, takeableOffers });
|
|
650
|
+
}
|
|
444
651
|
return {
|
|
445
652
|
getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
|
|
446
653
|
buildTx: () => tx,
|
|
@@ -452,9 +659,22 @@ export class MorphoMidnight {
|
|
|
452
659
|
*
|
|
453
660
|
* Like `takeBorrow`, the sender's existing credit is withdrawn before offers are taken.
|
|
454
661
|
*
|
|
662
|
+
* Buy offers whose tick is out of range, whose price is zero, or whose price stays below the
|
|
663
|
+
* settlement fee until `deadline` (at or below it on an assets target) are dropped from the transaction because one of them would
|
|
664
|
+
* revert the whole bundle.
|
|
665
|
+
*
|
|
455
666
|
* @param params - Borrower, market snapshot, collateral supplies, sell target, offers, deadline, receiver, and optional referral fee.
|
|
456
667
|
* @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
|
|
457
668
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
669
|
+
* @param params.positionData - Owner-bound position snapshot returned by `getPositionData`. The
|
|
670
|
+
* `DEFAULT_LLTV_BUFFER` check is only as current as this snapshot and `collateralPrices`: it
|
|
671
|
+
* does not see transactions mined or prices moved since, so two transactions built from one
|
|
672
|
+
* snapshot can together end inside the buffer. Midnight still rejects any position above
|
|
673
|
+
* LLTV onchain. Midnight debt and collateral do not accrue, so the check needs no accrual.
|
|
674
|
+
* @param params.collateralPrices - Values from `price()` on each
|
|
675
|
+
* `marketData.params.collateralParams[i].oracle`, indexed like `positionData.collateral` and
|
|
676
|
+
* scaled by `ORACLE_PRICE_SCALE`. A price is required for every held or supplied collateral
|
|
677
|
+
* index, because debt after a borrow is always positive.
|
|
458
678
|
* @param params.collateralSupplies - Collateral index and assets per supply; must not be empty.
|
|
459
679
|
* @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
|
|
460
680
|
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
@@ -463,40 +683,62 @@ export class MorphoMidnight {
|
|
|
463
683
|
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
464
684
|
* required for the full pulled amount.
|
|
465
685
|
* @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
|
|
686
|
+
* Midnight protocol and market token contracts are rejected.
|
|
466
687
|
* @param params.takeableOffers - Lend-side offers returned by the Midnight API.
|
|
467
688
|
* @param params.deadline - Bounded bundle execution deadline timestamp.
|
|
468
689
|
* @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
|
|
469
690
|
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
470
691
|
* @returns Lazy collateral approvals and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
|
|
471
|
-
* @throws {ChainIdMismatchError} when client or market data targets another chain
|
|
692
|
+
* @throws {ChainIdMismatchError} when client or market data targets another chain, or from
|
|
693
|
+
* `getRequirements()` when the RPC reports another chain via `eth_chainId`.
|
|
694
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
695
|
+
* RPC read fails.
|
|
472
696
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
473
697
|
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
474
|
-
* @throws {InputExceedsMaxError} when a
|
|
475
|
-
* `
|
|
698
|
+
* @throws {InputExceedsMaxError} when a collateral supply amount, per-index sum, target amount,
|
|
699
|
+
* or offer cap exceeds `uint128`, or when `target.maxUnits` exceeds `uint128` (an SDK cap: the
|
|
700
|
+
* bundle accepts `uint256`, but a higher ceiling gives no slippage protection), or when
|
|
476
701
|
* `nativeAmount` exceeds the maximum wNative collateral amount this call can pull.
|
|
477
702
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
478
703
|
* @throws {EmptyMidnightCollateralSuppliesError} when no collateral supply is provided.
|
|
479
704
|
* @throws {UnknownCollateralIndexError} when a collateral index is not configured.
|
|
705
|
+
* @throws {AccrualPositionUserMismatchError} when `positionData.user` differs from `accountAddress`.
|
|
706
|
+
* @throws {MarketIdMismatchError} when `positionData.marketId` differs from `marketData.id`.
|
|
707
|
+
* @throws {MissingMarketPriceError} when a held collateral index has no supplied price.
|
|
708
|
+
* @throws {BorrowExceedsSafeLtvError} when the post-borrow debt exceeds buffered collateral capacity.
|
|
480
709
|
* @throws {NonPositiveInputError} when a supply amount, the target amount, `maxUnits` or `minSellerAssets` is not positive.
|
|
481
|
-
* @throws {NegativeInputError} when `referralFeePct` or `nativeAmount`
|
|
710
|
+
* @throws {NegativeInputError} when a takeable offer cap, `referralFeePct` or `nativeAmount`
|
|
711
|
+
* is negative.
|
|
482
712
|
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
483
713
|
* @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
|
|
484
714
|
* @throws {UnboundedMidnightTakeInputError} when `target.units` or
|
|
485
715
|
* `target.maxUnits` is `maxUint256`.
|
|
486
716
|
* @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
|
|
717
|
+
* @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
|
|
718
|
+
* market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
|
|
487
719
|
* @throws {ExpiredDeadlineError} when `deadline` has expired.
|
|
488
720
|
* @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
|
|
489
721
|
* @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
|
|
490
722
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
491
723
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
492
724
|
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
725
|
+
* @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
|
|
493
726
|
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
727
|
+
* @throws {MidnightTakeableOffersNotFillableError} when every takeable offer is expired, not yet
|
|
728
|
+
* started, self-made, capped below the market fee or otherwise dead, and no credit withdrawal can fill instead,
|
|
729
|
+
* or when every offer is dropped for an out-of-range tick, a zero price, or a price below the
|
|
730
|
+
* settlement fee until `deadline` (at or below it on an assets target), even with a credit
|
|
731
|
+
* withdrawal.
|
|
732
|
+
* @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
|
|
733
|
+
* its bounds cannot hold at any fill.
|
|
494
734
|
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
|
|
495
735
|
* @example
|
|
496
736
|
* ```ts
|
|
497
737
|
* const output = midnight.supplyCollateralTakeBorrow({
|
|
498
738
|
* accountAddress: borrower,
|
|
499
739
|
* marketData,
|
|
740
|
+
* positionData,
|
|
741
|
+
* collateralPrices,
|
|
500
742
|
* collateralSupplies: [{ collateralIndex: 0n, assets: 2_000_000n }],
|
|
501
743
|
* target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
|
|
502
744
|
* takeableOffers: quote.data.takeableOffers,
|
|
@@ -508,7 +750,7 @@ export class MorphoMidnight {
|
|
|
508
750
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
509
751
|
validateTakeDeadlineWindow(params.deadline);
|
|
510
752
|
const market = params.marketData.params;
|
|
511
|
-
const
|
|
753
|
+
const rawParams = {
|
|
512
754
|
chainId: this.chainId,
|
|
513
755
|
market,
|
|
514
756
|
collateralSupplies: params.collateralSupplies,
|
|
@@ -520,7 +762,52 @@ export class MorphoMidnight {
|
|
|
520
762
|
referralFeePct: params.referralFeePct,
|
|
521
763
|
referralFeeRecipient: params.referralFeeRecipient,
|
|
522
764
|
metadata: this.client.options.metadata,
|
|
765
|
+
};
|
|
766
|
+
let tx = midnightSupplyCollateralTakeBorrow(rawParams);
|
|
767
|
+
validatePositionBinding({
|
|
768
|
+
positionData: params.positionData,
|
|
769
|
+
accountAddress: params.accountAddress,
|
|
770
|
+
marketData: params.marketData,
|
|
771
|
+
});
|
|
772
|
+
const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
|
|
773
|
+
for (const { collateralIndex, assets } of params.collateralSupplies) {
|
|
774
|
+
// Reject unconfigured collateral indexes before updating postCollateral.
|
|
775
|
+
MarketUtils.getCollateralByIndex(market, collateralIndex);
|
|
776
|
+
const index = Number(collateralIndex);
|
|
777
|
+
postCollateral[index] = (postCollateral[index] ?? 0n) + assets;
|
|
778
|
+
}
|
|
779
|
+
const requestedUnits = params.target.type === "units"
|
|
780
|
+
? params.target.units
|
|
781
|
+
: params.target.maxUnits;
|
|
782
|
+
const postDebt = params.positionData.debt + requestedUnits;
|
|
783
|
+
if (postDebt > 0n) {
|
|
784
|
+
const maxSafeDebt = getMidnightMaxSafeDebt({
|
|
785
|
+
market: params.marketData,
|
|
786
|
+
collateral: postCollateral,
|
|
787
|
+
collateralPrices: params.collateralPrices,
|
|
788
|
+
});
|
|
789
|
+
if (postDebt > maxSafeDebt) {
|
|
790
|
+
throw new BorrowExceedsSafeLtvError(requestedUnits, MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
const now = Time.timestamp();
|
|
794
|
+
const takeableOffers = validateMidnightTakeFeasibility({
|
|
795
|
+
side: "sell",
|
|
796
|
+
takeableOffers: params.takeableOffers,
|
|
797
|
+
accountAddress: params.accountAddress,
|
|
798
|
+
marketData: params.marketData,
|
|
799
|
+
now,
|
|
800
|
+
deadline: params.deadline,
|
|
801
|
+
referralFeePct: tx.action.args.referralFeePct,
|
|
802
|
+
// Credit is withdrawn first, up to the market's withdrawable liquidity.
|
|
803
|
+
fallbackUnits: MathLib.min(params.positionData.credit, params.marketData.withdrawable),
|
|
804
|
+
credit: params.positionData.credit,
|
|
805
|
+
target: params.target,
|
|
806
|
+
increasesDebt: true,
|
|
523
807
|
});
|
|
808
|
+
if (takeableOffers !== params.takeableOffers) {
|
|
809
|
+
tx = midnightSupplyCollateralTakeBorrow({ ...rawParams, takeableOffers });
|
|
810
|
+
}
|
|
524
811
|
// Sum per token so a token supplied at several indices gets one approval.
|
|
525
812
|
const collateralAmounts = new Map();
|
|
526
813
|
for (const { collateralIndex, assets } of tx.action.args
|
|
@@ -551,9 +838,22 @@ export class MorphoMidnight {
|
|
|
551
838
|
*
|
|
552
839
|
* `reduceOnly` is always set, so the buy never opens a lender position.
|
|
553
840
|
*
|
|
841
|
+
* On an assets target, sell offers whose tick is out of range or whose buyer price is zero or
|
|
842
|
+
* above one are dropped from the transaction because one of them would revert the whole bundle.
|
|
843
|
+
*
|
|
554
844
|
* @param params - Borrower, market snapshot, buy target, offers, repay fallback, withdrawals, fee cap, deadline and optional referral fee.
|
|
555
845
|
* @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
|
|
556
846
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
847
|
+
* @param params.positionData - Owner-bound position snapshot returned by `getPositionData`. The
|
|
848
|
+
* `DEFAULT_LLTV_BUFFER` check is only as current as this snapshot and `collateralPrices`: it
|
|
849
|
+
* does not see transactions mined or prices moved since, so two transactions built from one
|
|
850
|
+
* snapshot can together end inside the buffer. Midnight still rejects any position above
|
|
851
|
+
* LLTV onchain. Midnight debt and collateral do not accrue, so the check needs no accrual.
|
|
852
|
+
* @param params.collateralPrices - Values from `price()` on each
|
|
853
|
+
* `marketData.params.collateralParams[i].oracle`, indexed like `positionData.collateral` and
|
|
854
|
+
* scaled by `ORACLE_PRICE_SCALE`. An empty array is safe only when
|
|
855
|
+
* `collateralWithdrawals` is empty or the conservative post-operation debt is zero: a units
|
|
856
|
+
* `target` covering `positionData.debt`, or an assets target whose `minUnits` covers it.
|
|
557
857
|
* @param params.target - `{ type: "assets", assets, minUnits }` or `{ type: "units", units, maxBuyerAssets }`; `units: maxUint256` targets the sender's whole debt, capped by `maxBuyerAssets` (must be finite; `units: maxUint256` already selects the whole debt).
|
|
558
858
|
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
559
859
|
* chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
|
|
@@ -563,7 +863,9 @@ export class MorphoMidnight {
|
|
|
563
863
|
* @param params.takeableOffers - Borrow-side offers returned by the Midnight API.
|
|
564
864
|
* @param params.repayEnabled - Whether the unfilled remainder is repaid directly to Midnight.
|
|
565
865
|
* @param params.collateralWithdrawals - Optional collateral withdrawals; `maxUint256` assets withdraws the whole balance.
|
|
566
|
-
* @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress
|
|
866
|
+
* @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`,
|
|
867
|
+
* must be non-zero and not a Midnight protocol or market token contract when
|
|
868
|
+
* `collateralWithdrawals` is non-empty, and is unused otherwise.
|
|
567
869
|
* @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
|
|
568
870
|
* onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
|
|
569
871
|
* is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
|
|
@@ -572,33 +874,60 @@ export class MorphoMidnight {
|
|
|
572
874
|
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
573
875
|
* @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
|
|
574
876
|
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
575
|
-
* @throws {ChainIdMismatchError} when client or market data targets another chain
|
|
877
|
+
* @throws {ChainIdMismatchError} when client or market data targets another chain, or from
|
|
878
|
+
* `getRequirements()` when the RPC reports another chain via `eth_chainId`.
|
|
879
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
880
|
+
* RPC read fails.
|
|
576
881
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
577
882
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
578
883
|
* @throws {NonPositiveInputError} when the target amount, `minUnits`, `maxBuyerAssets` or a
|
|
579
884
|
* withdrawal amount is not positive.
|
|
580
|
-
* @throws {NegativeInputError} when `maxContinuousFee`, `referralFeePct`
|
|
581
|
-
*
|
|
582
|
-
*
|
|
583
|
-
* `
|
|
584
|
-
*
|
|
585
|
-
*
|
|
885
|
+
* @throws {NegativeInputError} when a takeable offer cap, `maxContinuousFee`, `referralFeePct`
|
|
886
|
+
* or `nativeAmount` is negative.
|
|
887
|
+
* @throws {InputExceedsMaxError} when a finite target amount, collateral withdrawal amount, or
|
|
888
|
+
* offer cap exceeds `uint128`; when `target.maxBuyerAssets` exceeds `uint128` (an SDK cap: the
|
|
889
|
+
* bundle accepts `uint256`, but a higher ceiling gives no slippage protection); when
|
|
890
|
+
* `maxContinuousFee` exceeds `uint256`; or when `nativeAmount` exceeds the maximum wNative
|
|
891
|
+
* amount this call can pull, including zero for a withdraw-only call.
|
|
586
892
|
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
587
893
|
* @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
|
|
588
894
|
* @throws {UnknownCollateralIndexError} when a withdrawal targets a collateral index not configured on the market.
|
|
895
|
+
* @throws {AccrualPositionUserMismatchError} when `positionData.user` differs from `accountAddress`.
|
|
896
|
+
* @throws {MarketIdMismatchError} when `positionData.marketId` differs from `marketData.id`.
|
|
897
|
+
* @throws {WithdrawExceedsCollateralError} when a withdrawal exceeds the position's collateral.
|
|
898
|
+
* @throws {MissingMarketPriceError} when a held collateral index has no supplied price.
|
|
899
|
+
* @throws {WithdrawMakesPositionUnhealthyError} when the withdrawal exceeds buffered collateral capacity.
|
|
589
900
|
* @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
|
|
590
901
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
591
902
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
592
903
|
* @throws {ExpiredDeadlineError} when `deadline` has expired.
|
|
593
904
|
* @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
|
|
594
905
|
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
906
|
+
* @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
|
|
595
907
|
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
908
|
+
* @throws {MidnightContinuousFeeAboveMaxError} when `maxContinuousFee` is below the market's
|
|
909
|
+
* current continuous fee.
|
|
910
|
+
* @throws {MidnightRepayExceedsDebtError} when a reduce-only repay target exceeds the position's debt.
|
|
911
|
+
* @throws {MidnightTakeableOffersNotFillableError} when every takeable offer is expired, not yet
|
|
912
|
+
* started, self-made, capped below the market fee or otherwise dead, and `repayEnabled` is false,
|
|
913
|
+
* or when every offer on an assets target has an out-of-range tick or a zero or above-par buyer
|
|
914
|
+
* price, even with `repayEnabled`.
|
|
915
|
+
* @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
|
|
916
|
+
* its bounds cannot hold at any fill, or a buy assets target's `minUnits` exceeds the live
|
|
917
|
+
* offers plus the fallback.
|
|
918
|
+
* @throws {MidnightZeroReceiverError} when collateral is withdrawn to the zero address. Thrown
|
|
919
|
+
* during this method call, before the lazy output is returned.
|
|
920
|
+
* @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
|
|
921
|
+
* contract or a market token contract, or when `referralFeeRecipient` is either with a
|
|
922
|
+
* positive referral fee.
|
|
596
923
|
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
|
|
597
924
|
* @example
|
|
598
925
|
* ```ts
|
|
599
926
|
* const output = midnight.takeRepayWithdrawCollateral({
|
|
600
927
|
* accountAddress: borrower,
|
|
601
928
|
* marketData,
|
|
929
|
+
* positionData,
|
|
930
|
+
* collateralPrices,
|
|
602
931
|
* target: { type: "units", units: 1_000_000n, maxBuyerAssets: 990_000n },
|
|
603
932
|
* takeableOffers: quote.data.takeableOffers,
|
|
604
933
|
* repayEnabled: true,
|
|
@@ -612,7 +941,7 @@ export class MorphoMidnight {
|
|
|
612
941
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
613
942
|
validateTakeDeadlineWindow(params.deadline);
|
|
614
943
|
const market = params.marketData.params;
|
|
615
|
-
const
|
|
944
|
+
const rawParams = {
|
|
616
945
|
chainId: this.chainId,
|
|
617
946
|
market,
|
|
618
947
|
target: params.target,
|
|
@@ -626,7 +955,72 @@ export class MorphoMidnight {
|
|
|
626
955
|
referralFeePct: params.referralFeePct,
|
|
627
956
|
referralFeeRecipient: params.referralFeeRecipient,
|
|
628
957
|
metadata: this.client.options.metadata,
|
|
958
|
+
};
|
|
959
|
+
let tx = midnightTakeRepayWithdrawCollateral(rawParams);
|
|
960
|
+
validatePositionBinding({
|
|
961
|
+
positionData: params.positionData,
|
|
962
|
+
accountAddress: params.accountAddress,
|
|
963
|
+
marketData: params.marketData,
|
|
629
964
|
});
|
|
965
|
+
const collateralWithdrawals = params.collateralWithdrawals ?? [];
|
|
966
|
+
const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
|
|
967
|
+
let withdrawAmount = 0n;
|
|
968
|
+
for (const withdrawal of collateralWithdrawals) {
|
|
969
|
+
// Reject unconfigured collateral indexes before updating postCollateral.
|
|
970
|
+
MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
|
|
971
|
+
const index = Number(withdrawal.collateralIndex);
|
|
972
|
+
const available = postCollateral[index] ?? 0n;
|
|
973
|
+
const amount = withdrawal.assets === maxUint256 ? available : withdrawal.assets;
|
|
974
|
+
if (amount > available) {
|
|
975
|
+
throw new WithdrawExceedsCollateralError({
|
|
976
|
+
withdrawAmount: amount,
|
|
977
|
+
available,
|
|
978
|
+
market: params.marketData.id,
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
postCollateral[index] = available - amount;
|
|
982
|
+
withdrawAmount += amount;
|
|
983
|
+
}
|
|
984
|
+
const debtReduction = params.target.type === "units"
|
|
985
|
+
? params.target.units
|
|
986
|
+
: params.target.minUnits;
|
|
987
|
+
const postDebt = debtReduction >= params.positionData.debt
|
|
988
|
+
? 0n
|
|
989
|
+
: params.positionData.debt - debtReduction;
|
|
990
|
+
if (collateralWithdrawals.length > 0 && postDebt > 0n) {
|
|
991
|
+
const maxSafeDebt = getMidnightMaxSafeDebt({
|
|
992
|
+
market: params.marketData,
|
|
993
|
+
collateral: postCollateral,
|
|
994
|
+
collateralPrices: params.collateralPrices,
|
|
995
|
+
});
|
|
996
|
+
if (postDebt > maxSafeDebt) {
|
|
997
|
+
throw new WithdrawMakesPositionUnhealthyError({
|
|
998
|
+
withdrawAmount,
|
|
999
|
+
borrowAssets: postDebt,
|
|
1000
|
+
maxSafeBorrow: maxSafeDebt,
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
const takeableOffers = validateMidnightTakeFeasibility({
|
|
1005
|
+
side: "buy",
|
|
1006
|
+
takeableOffers: params.takeableOffers,
|
|
1007
|
+
accountAddress: params.accountAddress,
|
|
1008
|
+
marketData: params.marketData,
|
|
1009
|
+
now: Time.timestamp(),
|
|
1010
|
+
deadline: params.deadline,
|
|
1011
|
+
referralFeePct: tx.action.args.referralFeePct,
|
|
1012
|
+
// With repayEnabled the bundle repays the unfilled debt directly, at par.
|
|
1013
|
+
fallbackUnits: params.repayEnabled ? params.positionData.debt : 0n,
|
|
1014
|
+
target: params.target,
|
|
1015
|
+
maxContinuousFee: params.maxContinuousFee,
|
|
1016
|
+
debt: params.positionData.debt,
|
|
1017
|
+
});
|
|
1018
|
+
if (takeableOffers !== params.takeableOffers) {
|
|
1019
|
+
tx = midnightTakeRepayWithdrawCollateral({
|
|
1020
|
+
...rawParams,
|
|
1021
|
+
takeableOffers,
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
630
1024
|
const pulledAssets = params.target.type === "assets"
|
|
631
1025
|
? params.target.assets
|
|
632
1026
|
: params.target.maxBuyerAssets;
|
|
@@ -657,9 +1051,13 @@ export class MorphoMidnight {
|
|
|
657
1051
|
* @param params.reservedCollateralAssets - Existing collateral reserved by other open maker groups.
|
|
658
1052
|
* @param params.collateralIndex - Optional collateral index; defaults to `0n`.
|
|
659
1053
|
* @returns Lazy token-approval requirements and a synchronous transaction builder.
|
|
660
|
-
* @throws {ChainIdMismatchError} when client or market data targets another chain
|
|
1054
|
+
* @throws {ChainIdMismatchError} when client or market data targets another chain, or from
|
|
1055
|
+
* `getRequirements()` when the RPC reports another chain via `eth_chainId`.
|
|
1056
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
1057
|
+
* RPC read fails.
|
|
661
1058
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
662
1059
|
* @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
|
|
1060
|
+
* @throws {InputExceedsMaxError} when `collateralAssets` exceeds `uint128`.
|
|
663
1061
|
* @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
|
|
664
1062
|
* @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
|
|
665
1063
|
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled collateral assets.
|
|
@@ -676,6 +1074,7 @@ export class MorphoMidnight {
|
|
|
676
1074
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
677
1075
|
validateMarketData(params.marketData, this.chainId);
|
|
678
1076
|
assertPositiveAmount("collateralAssets", params.collateralAssets);
|
|
1077
|
+
validateMidnightUint128Field("collateralAssets", params.collateralAssets);
|
|
679
1078
|
assertNonNegativeAmount("reservedCollateralAssets", params.reservedCollateralAssets ?? 0n);
|
|
680
1079
|
const market = params.marketData;
|
|
681
1080
|
const collateralIndex = params.collateralIndex ?? 0n;
|
|
@@ -704,29 +1103,33 @@ export class MorphoMidnight {
|
|
|
704
1103
|
/**
|
|
705
1104
|
* Prepares an atomic lend-offer publication or repost through `MidnightBundlesV2`.
|
|
706
1105
|
*
|
|
1106
|
+
* A partially consumed offer group remains publishable with its shared remaining cap reduced.
|
|
707
1107
|
* One transaction cancels `cancellations` under their consumption ceilings, activates the
|
|
708
1108
|
* PriceRatifierV1 or RateRatifierV1 root, and publishes its payload. Pass no cancellations
|
|
709
|
-
* for a new publication. Calls the Midnight mempool validation API while preparing the tree
|
|
1109
|
+
* for a new publication. Calls the Midnight mempool validation API while preparing the tree;
|
|
1110
|
+
* `validation: false` skips that call.
|
|
710
1111
|
*
|
|
711
1112
|
* @param params - Maker, lend-side offers, loan reserve, cancellations, and deadline.
|
|
712
1113
|
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
713
1114
|
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
714
1115
|
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
715
1116
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
716
|
-
* @param params.validation -
|
|
1117
|
+
* @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
|
|
717
1118
|
* @param params.loanToken - Loan token shared by every offer market.
|
|
718
1119
|
* @param params.loanAssets - New loan reserve assigned to the published groups.
|
|
719
1120
|
* @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
|
|
720
1121
|
* @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
|
|
721
|
-
* @throws {ChainIdMismatchError} when the client
|
|
1122
|
+
* @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
|
|
1123
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
1124
|
+
* RPC read fails.
|
|
722
1125
|
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
723
1126
|
* @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
|
|
724
1127
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
|
|
725
1128
|
* @throws {NonPositiveInputError} when `loanAssets` is non-positive.
|
|
726
1129
|
* @throws {NegativeInputError} when `reservedLoanAssets` or a `maxConsumed` ceiling is negative.
|
|
727
|
-
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
728
1130
|
* @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128` or `deadline` exceeds `uint256`.
|
|
729
|
-
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1131
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1132
|
+
* (not thrown when `validation` is `false`).
|
|
730
1133
|
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
731
1134
|
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
732
1135
|
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
@@ -734,10 +1137,24 @@ export class MorphoMidnight {
|
|
|
734
1137
|
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
735
1138
|
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
736
1139
|
* @throws {MidnightOfferSideMismatchError} when an offer is not lend-side.
|
|
1140
|
+
* @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
|
|
737
1141
|
* @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer uses another loan token.
|
|
738
1142
|
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
1143
|
+
* @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
|
|
739
1144
|
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
1145
|
+
* @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
|
|
1146
|
+
* @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
|
|
1147
|
+
* @throws {MidnightOfferGroupConsumedError} when an offer group has no remaining capacity.
|
|
1148
|
+
* @throws {MidnightOfferTickSpacingError} when an offer tick is not accessible in its market.
|
|
1149
|
+
* @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} when the market fee exceeds an offer's cap.
|
|
1150
|
+
* @throws {MidnightOfferRateBoundUnreachableError} when a Rate V1 offer cannot satisfy its bound.
|
|
1151
|
+
* @throws {MidnightMarketMaturityTooFarError} when an uncreated market's maturity is more than 100 years after the offer's expiry.
|
|
1152
|
+
* @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
|
|
1153
|
+
* @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
|
|
1154
|
+
* @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
|
|
1155
|
+
* @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
|
|
740
1156
|
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
|
|
1157
|
+
* @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
|
|
741
1158
|
* @example
|
|
742
1159
|
* ```ts
|
|
743
1160
|
* const output = await midnight.makeLend({
|
|
@@ -752,6 +1169,8 @@ export class MorphoMidnight {
|
|
|
752
1169
|
*/
|
|
753
1170
|
async makeLend(params) {
|
|
754
1171
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
1172
|
+
// Fails before any API read or build when the deadline has already passed.
|
|
1173
|
+
validateMidnightDeadline(params.deadline);
|
|
755
1174
|
const tree = Tree.from(params.offers);
|
|
756
1175
|
rejectReduceOnlyOffers(tree.offers);
|
|
757
1176
|
return this.prepareLendOffers({ ...params, offers: tree });
|
|
@@ -761,23 +1180,26 @@ export class MorphoMidnight {
|
|
|
761
1180
|
*
|
|
762
1181
|
* One transaction cancels `cancellations` under their consumption ceilings, activates the
|
|
763
1182
|
* PriceRatifierV1 or RateRatifierV1 root, and publishes its payload. Pass no cancellations for
|
|
764
|
-
* a new publication. Calls the Midnight mempool validation API while preparing the tree
|
|
1183
|
+
* a new publication. Calls the Midnight mempool validation API while preparing the tree;
|
|
1184
|
+
* `validation: false` skips that call.
|
|
765
1185
|
*
|
|
766
1186
|
* @param params - Maker, borrow-side offers, cancellations, and deadline.
|
|
767
1187
|
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
768
1188
|
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
769
1189
|
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
770
1190
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
771
|
-
* @param params.validation -
|
|
1191
|
+
* @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
|
|
772
1192
|
* @returns Prepared group metadata, lazy authorization requirements, and a synchronous transaction builder.
|
|
773
|
-
* @throws {ChainIdMismatchError} when the client chain
|
|
1193
|
+
* @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
|
|
1194
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
1195
|
+
* RPC read fails.
|
|
774
1196
|
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
775
1197
|
* @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
|
|
776
1198
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
|
|
777
1199
|
* @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
|
|
778
|
-
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
779
1200
|
* @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128` or `deadline` exceeds `uint256`.
|
|
780
|
-
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1201
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1202
|
+
* (not thrown when `validation` is `false`).
|
|
781
1203
|
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
782
1204
|
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
783
1205
|
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
@@ -785,8 +1207,23 @@ export class MorphoMidnight {
|
|
|
785
1207
|
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
786
1208
|
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
787
1209
|
* @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
|
|
1210
|
+
* @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
|
|
1211
|
+
* @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
|
|
1212
|
+
* @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
|
|
1213
|
+
* @throws {MidnightOfferGroupConsumedError} when an offer group has no remaining capacity.
|
|
1214
|
+
* @throws {MidnightOfferTickSpacingError} when an offer tick is not accessible in its market.
|
|
1215
|
+
* @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} when the market fee exceeds an offer's cap.
|
|
1216
|
+
* @throws {MidnightOfferZeroPriceSellError} when a sell offer has a zero tick.
|
|
1217
|
+
* @throws {MidnightOfferRateBoundUnreachableError} when a Rate V1 offer cannot satisfy its bound.
|
|
1218
|
+
* @throws {MidnightMarketMaturityTooFarError} when an uncreated market's maturity is more than 100 years after the offer's expiry.
|
|
1219
|
+
* @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
|
|
1220
|
+
* @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
|
|
1221
|
+
* @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
|
|
1222
|
+
* @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
|
|
788
1223
|
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
1224
|
+
* @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
|
|
789
1225
|
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
1226
|
+
* @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
|
|
790
1227
|
* @example
|
|
791
1228
|
* ```ts
|
|
792
1229
|
* const output = await midnight.makeBorrow({
|
|
@@ -798,6 +1235,8 @@ export class MorphoMidnight {
|
|
|
798
1235
|
*/
|
|
799
1236
|
async makeBorrow(params) {
|
|
800
1237
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
1238
|
+
// Fails before any API read or build when the deadline has already passed.
|
|
1239
|
+
validateMidnightDeadline(params.deadline);
|
|
801
1240
|
const tree = Tree.from(params.offers);
|
|
802
1241
|
rejectReduceOnlyOffers(tree.offers);
|
|
803
1242
|
return this.prepareBorrowOffers({ ...params, offers: tree });
|
|
@@ -808,8 +1247,14 @@ export class MorphoMidnight {
|
|
|
808
1247
|
async prepareLendOffers(params) {
|
|
809
1248
|
assertPositiveAmount("loanAssets", params.loanAssets);
|
|
810
1249
|
assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
|
|
811
|
-
const
|
|
812
|
-
validateOfferSides(
|
|
1250
|
+
const tree = Tree.from(params.offers);
|
|
1251
|
+
validateOfferSides(tree.offers, true);
|
|
1252
|
+
validateMidnightMakerOfferCallbacks(tree.offers);
|
|
1253
|
+
const data = await getOffersDataInternal({
|
|
1254
|
+
client: this.client,
|
|
1255
|
+
chainId: this.chainId,
|
|
1256
|
+
params: { ...params, offers: tree },
|
|
1257
|
+
});
|
|
813
1258
|
data.tree.offers.forEach((offer, index) => {
|
|
814
1259
|
const market = offerMarketParams(offer);
|
|
815
1260
|
if (!isAddressEqual(market.loanToken, params.loanToken)) {
|
|
@@ -866,17 +1311,21 @@ export class MorphoMidnight {
|
|
|
866
1311
|
* to `abi.encode(blueMarket)`. The contract does not check supply share-price slippage, so
|
|
867
1312
|
* `blueMarket` must be protected against supply-share-price inflation; this method rejects
|
|
868
1313
|
* Blue markets with no supply shares and parked amounts that would mint zero shares. Calls the
|
|
869
|
-
* Midnight mempool validation API while preparing the tree
|
|
1314
|
+
* Midnight mempool validation API while preparing the tree; `validation: false` skips that call.
|
|
1315
|
+
* Computes the callback's CREATE2 address from the chain's
|
|
870
1316
|
* `midnightBlueBuyCallbackFactory`, `accountAddress` and `callbackSalt`, and fetches the Morpho Blue market,
|
|
871
1317
|
* accruing interest to the current time before previewing parked shares (markets whose
|
|
872
1318
|
* IRM the SDK cannot accrue are previewed on their last-updated state).
|
|
1319
|
+
* The caller is responsible for trusting the Blue market's oracle and IRM. If Blue liquidity is
|
|
1320
|
+
* drained, callback offers cannot fill until liquidity returns. `assetsToPark` may underfund the
|
|
1321
|
+
* offers; top-ups are allowed.
|
|
873
1322
|
*
|
|
874
1323
|
* @param params - Maker, lend-side offers, Blue market, parked assets, cancellations, and deadline.
|
|
875
1324
|
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
876
1325
|
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
877
1326
|
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
878
1327
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
879
|
-
* @param params.validation -
|
|
1328
|
+
* @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
|
|
880
1329
|
* @param params.blueMarket - Morpho Blue market the parked assets are supplied to.
|
|
881
1330
|
* @param params.assetsToPark - Loan assets supplied to `blueMarket` for the maker's callback.
|
|
882
1331
|
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
@@ -884,19 +1333,23 @@ export class MorphoMidnight {
|
|
|
884
1333
|
* the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
|
|
885
1334
|
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
886
1335
|
* required for the full pulled amount.
|
|
887
|
-
* @param params.callbackSalt - Salt selecting the maker's callback;
|
|
1336
|
+
* @param params.callbackSalt - Salt selecting the maker's callback; must be exactly 32 bytes of hex.
|
|
888
1337
|
* @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
|
|
889
|
-
* @throws {ChainIdMismatchError} when the client
|
|
1338
|
+
* @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
|
|
1339
|
+
* another chain than `this.chainId`.
|
|
1340
|
+
* @throws {viem.BaseError} when the `eth_chainId` request, a Blue market RPC read, or a
|
|
1341
|
+
* requirement RPC read fails.
|
|
890
1342
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2`, `midnightBlueBuyCallbackFactory`, `midnight`, `blue` or V1 ratifier deployment.
|
|
891
1343
|
* @throws {NonPositiveInputError} when `assetsToPark` is non-positive.
|
|
1344
|
+
* @throws {InputExceedsMaxError} when `assetsToPark` exceeds `uint128`.
|
|
892
1345
|
* @throws {NegativeInputError} when a `maxConsumed` ceiling or `nativeAmount` is negative.
|
|
893
|
-
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
894
1346
|
* @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128`, `deadline` exceeds
|
|
895
1347
|
* `uint256`, or `nativeAmount` exceeds `assetsToPark` when `blueMarket.loanToken` is wNative.
|
|
896
1348
|
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
897
1349
|
* @throws {NativeAmountOnNonWNativeAssetError} when `blueMarket.loanToken` is not wNative.
|
|
898
1350
|
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
899
|
-
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1351
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1352
|
+
* (not thrown when `validation` is `false`).
|
|
900
1353
|
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
901
1354
|
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
902
1355
|
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
@@ -908,11 +1361,24 @@ export class MorphoMidnight {
|
|
|
908
1361
|
* @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer's loan token differs from `blueMarket`'s.
|
|
909
1362
|
* @throws {MidnightOfferCallbackMismatchError} when an offer does not use the maker's derived callback.
|
|
910
1363
|
* @throws {MidnightOfferCallbackDataMismatchError} when an offer's callback data is not `abi.encode(blueMarket)`.
|
|
1364
|
+
* @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
|
|
1365
|
+
* @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
|
|
1366
|
+
* @throws {MidnightOfferGroupConsumedError} when an offer group has no remaining capacity.
|
|
1367
|
+
* @throws {MidnightOfferTickSpacingError} when an offer tick is not accessible in its market.
|
|
1368
|
+
* @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} when the market fee exceeds an offer's cap.
|
|
1369
|
+
* @throws {MidnightOfferRateBoundUnreachableError} when a Rate V1 offer cannot satisfy its bound.
|
|
1370
|
+
* @throws {MidnightMarketMaturityTooFarError} when an uncreated market's maturity is more than 100 years after the offer's expiry.
|
|
1371
|
+
* @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
|
|
1372
|
+
* @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
|
|
1373
|
+
* @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
|
|
1374
|
+
* @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
|
|
911
1375
|
* @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
|
|
912
1376
|
* @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price.
|
|
913
1377
|
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
1378
|
+
* @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
|
|
914
1379
|
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
915
1380
|
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `assetsToPark`.
|
|
1381
|
+
* @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
|
|
916
1382
|
* @example
|
|
917
1383
|
* ```ts
|
|
918
1384
|
* const callback = getMidnightBlueBuyCallbackAddress({ chainId, owner: maker, salt: callbackSalt });
|
|
@@ -931,8 +1397,14 @@ export class MorphoMidnight {
|
|
|
931
1397
|
* ```
|
|
932
1398
|
*/
|
|
933
1399
|
async supplyBlueMakeLend(params) {
|
|
934
|
-
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
935
1400
|
assertPositiveAmount("assetsToPark", params.assetsToPark);
|
|
1401
|
+
validateMidnightUint128Field("assetsToPark", params.assetsToPark);
|
|
1402
|
+
const tree = Tree.from(params.offers);
|
|
1403
|
+
validateOfferSides(tree.offers, true);
|
|
1404
|
+
rejectReduceOnlyOffers(tree.offers);
|
|
1405
|
+
await validateClientChainId(this.client.viemClient, this.chainId);
|
|
1406
|
+
// Fails before any API read or build when the deadline has already passed.
|
|
1407
|
+
validateMidnightDeadline(params.deadline);
|
|
936
1408
|
const { callbackSalt } = params;
|
|
937
1409
|
const blueMarketId = BlueMarketUtils.getMarketId(params.blueMarket);
|
|
938
1410
|
const callback = getMidnightBlueBuyCallbackAddress({
|
|
@@ -941,7 +1413,11 @@ export class MorphoMidnight {
|
|
|
941
1413
|
salt: callbackSalt,
|
|
942
1414
|
});
|
|
943
1415
|
const [data, fetched] = await Promise.all([
|
|
944
|
-
|
|
1416
|
+
getOffersDataInternal({
|
|
1417
|
+
client: this.client,
|
|
1418
|
+
chainId: this.chainId,
|
|
1419
|
+
params: { ...params, offers: tree },
|
|
1420
|
+
}),
|
|
945
1421
|
fetchBlueMarket(blueMarketId, this.client.viemClient, {
|
|
946
1422
|
deployless: this.client.options.supportDeployless,
|
|
947
1423
|
}),
|
|
@@ -956,8 +1432,6 @@ export class MorphoMidnight {
|
|
|
956
1432
|
assets: params.assetsToPark,
|
|
957
1433
|
});
|
|
958
1434
|
}
|
|
959
|
-
validateOfferSides(data.tree.offers, true);
|
|
960
|
-
rejectReduceOnlyOffers(data.tree.offers);
|
|
961
1435
|
const callbackData = getMidnightBlueBuyCallbackData(params.blueMarket);
|
|
962
1436
|
data.tree.offers.forEach((offer, index) => {
|
|
963
1437
|
const offerMarket = offerMarketParams(offer);
|
|
@@ -1025,8 +1499,14 @@ export class MorphoMidnight {
|
|
|
1025
1499
|
* Prepares borrow-side offers for publication.
|
|
1026
1500
|
*/
|
|
1027
1501
|
async prepareBorrowOffers(params) {
|
|
1028
|
-
const
|
|
1029
|
-
validateOfferSides(
|
|
1502
|
+
const tree = Tree.from(params.offers);
|
|
1503
|
+
validateOfferSides(tree.offers, false);
|
|
1504
|
+
validateMidnightMakerOfferCallbacks(tree.offers);
|
|
1505
|
+
const data = await getOffersDataInternal({
|
|
1506
|
+
client: this.client,
|
|
1507
|
+
chainId: this.chainId,
|
|
1508
|
+
params: { ...params, offers: tree },
|
|
1509
|
+
});
|
|
1030
1510
|
const tx = midnightCancelAndMake({
|
|
1031
1511
|
chainId: this.chainId,
|
|
1032
1512
|
cancellations: params.cancellations ?? [],
|
|
@@ -1053,6 +1533,7 @@ export class MorphoMidnight {
|
|
|
1053
1533
|
* Shares the borrow-side publication and requirement handling of {@link MorphoMidnight.makeBorrow}.
|
|
1054
1534
|
* No tokens are pulled during publication and no token approval is required.
|
|
1055
1535
|
* Execution waits for a taker; publication does not close the position or withdraw collateral.
|
|
1536
|
+
* A partially consumed offer group remains publishable with its shared remaining cap reduced.
|
|
1056
1537
|
* Every offer must already have `buy = false` and `reduceOnly = true`.
|
|
1057
1538
|
* The supplied tree, group caps and prices are preserved; no separate root signature is needed.
|
|
1058
1539
|
*
|
|
@@ -1061,12 +1542,15 @@ export class MorphoMidnight {
|
|
|
1061
1542
|
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
1062
1543
|
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
1063
1544
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
1064
|
-
* @param params.validation -
|
|
1545
|
+
* @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
|
|
1065
1546
|
* @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
|
|
1066
|
-
* @throws {ChainIdMismatchError} when the client chain
|
|
1547
|
+
* @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
|
|
1548
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
1549
|
+
* RPC read fails.
|
|
1067
1550
|
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
1068
1551
|
* @throws {MidnightOfferSideMismatchError} when an offer is not a sell offer (`buy = false`).
|
|
1069
1552
|
* @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
|
|
1553
|
+
* @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
|
|
1070
1554
|
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
1071
1555
|
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
1072
1556
|
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
@@ -1074,12 +1558,27 @@ export class MorphoMidnight {
|
|
|
1074
1558
|
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
1075
1559
|
* @throws {UnknownAddressError} when the chain has no V1 ratifier or `midnightBundlesV2` deployment.
|
|
1076
1560
|
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
1077
|
-
* @throws {
|
|
1078
|
-
* @throws {
|
|
1561
|
+
* @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
|
|
1562
|
+
* @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
|
|
1563
|
+
* @throws {MidnightOfferGroupConsumedError} when an offer group has no remaining capacity.
|
|
1564
|
+
* @throws {MidnightOfferTickSpacingError} when an offer tick is not accessible in its market.
|
|
1565
|
+
* @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} when the market fee exceeds an offer's cap.
|
|
1566
|
+
* @throws {MidnightOfferZeroPriceSellError} when a sell offer has a zero tick.
|
|
1567
|
+
* @throws {MidnightOfferRateBoundUnreachableError} when a Rate V1 offer cannot satisfy its bound.
|
|
1568
|
+
* @throws {MidnightOfferNoCreditError} when a reduce-only sell is submitted without maker credit.
|
|
1569
|
+
* @throws {MidnightMarketMaturityTooFarError} when an uncreated market's maturity is more than 100 years after the offer's expiry.
|
|
1570
|
+
* @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
|
|
1571
|
+
* @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
|
|
1572
|
+
* @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
|
|
1573
|
+
* @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
|
|
1574
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1575
|
+
* (not thrown when `validation` is `false`).
|
|
1079
1576
|
* @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
|
|
1080
1577
|
* @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
|
|
1578
|
+
* @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
|
|
1081
1579
|
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
1082
1580
|
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
1581
|
+
* @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
|
|
1083
1582
|
* @example
|
|
1084
1583
|
* ```ts
|
|
1085
1584
|
* const output = await midnight.makeWithdraw({
|
|
@@ -1093,6 +1592,8 @@ export class MorphoMidnight {
|
|
|
1093
1592
|
*/
|
|
1094
1593
|
async makeWithdraw(params) {
|
|
1095
1594
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
1595
|
+
// Fails before any API read or build when the deadline has already passed.
|
|
1596
|
+
validateMidnightDeadline(params.deadline);
|
|
1096
1597
|
const tree = Tree.from(params.offers);
|
|
1097
1598
|
// Reject the wrong exit intent before calling the mempool validation API.
|
|
1098
1599
|
validateOfferSides(tree.offers, false);
|
|
@@ -1108,6 +1609,9 @@ export class MorphoMidnight {
|
|
|
1108
1609
|
* Shares the lend-side publication and requirement handling of {@link MorphoMidnight.makeLend}.
|
|
1109
1610
|
* Loan assets are pulled by Midnight when the offers fill, not during publication.
|
|
1110
1611
|
* The loan reserve uses the same approval sizing as `makeLend`.
|
|
1612
|
+
* A partially consumed offer group remains publishable with its shared remaining cap reduced.
|
|
1613
|
+
* No repay offer can be live after market maturity; late borrowers should repay directly with
|
|
1614
|
+
* {@link MorphoMidnight.repayWithdrawCollateral}.
|
|
1111
1615
|
* Execution waits for a taker; publication does not close the position or withdraw collateral.
|
|
1112
1616
|
* Every offer must already have `buy = true` and `reduceOnly = true`.
|
|
1113
1617
|
* The supplied tree, group caps and prices are preserved; no separate root signature is needed.
|
|
@@ -1117,16 +1621,19 @@ export class MorphoMidnight {
|
|
|
1117
1621
|
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
1118
1622
|
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
1119
1623
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
1120
|
-
* @param params.validation -
|
|
1624
|
+
* @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
|
|
1121
1625
|
* @param params.loanToken - Loan token shared by every offer market.
|
|
1122
1626
|
* @param params.loanAssets - New loan reserve assigned to the published groups.
|
|
1123
1627
|
* @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
|
|
1124
1628
|
* @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
|
|
1125
|
-
* @throws {ChainIdMismatchError} when the client
|
|
1629
|
+
* @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
|
|
1630
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
1631
|
+
* RPC read fails.
|
|
1126
1632
|
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
1127
1633
|
* @throws {MidnightOfferSideMismatchError} when an offer is not a buy offer (`buy = true`).
|
|
1128
1634
|
* @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
|
|
1129
|
-
* @throws {
|
|
1635
|
+
* @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
|
|
1636
|
+
* @throws {NonPositiveInputError} when `loanAssets` is not positive.
|
|
1130
1637
|
* @throws {NegativeInputError} when `reservedLoanAssets` or a `maxConsumed` ceiling is negative.
|
|
1131
1638
|
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
1132
1639
|
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
@@ -1135,12 +1642,27 @@ export class MorphoMidnight {
|
|
|
1135
1642
|
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
1136
1643
|
* @throws {UnknownAddressError} when the chain has no V1 ratifier or `midnightBundlesV2` deployment.
|
|
1137
1644
|
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
1138
|
-
* @throws {
|
|
1645
|
+
* @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
|
|
1646
|
+
* @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
|
|
1647
|
+
* @throws {MidnightOfferGroupConsumedError} when an offer group has no remaining capacity.
|
|
1648
|
+
* @throws {MidnightOfferTickSpacingError} when an offer tick is not accessible in its market.
|
|
1649
|
+
* @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} when the market fee exceeds an offer's cap.
|
|
1650
|
+
* @throws {MidnightOfferRateBoundUnreachableError} when a Rate V1 offer cannot satisfy its bound.
|
|
1651
|
+
* @throws {MidnightOfferNoDebtError} when a reduce-only buy is submitted without maker debt.
|
|
1652
|
+
* @throws {MidnightMarketMaturityTooFarError} when an uncreated market's maturity is more than 100 years after the offer's expiry.
|
|
1653
|
+
* @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
|
|
1654
|
+
* @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
|
|
1655
|
+
* @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
|
|
1656
|
+
* @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
|
|
1657
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1658
|
+
* (not thrown when `validation` is `false`).
|
|
1139
1659
|
* @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer uses another loan token.
|
|
1140
1660
|
* @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
|
|
1661
|
+
* @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
|
|
1141
1662
|
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
1142
1663
|
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
1143
1664
|
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
|
|
1665
|
+
* @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
|
|
1144
1666
|
* @example
|
|
1145
1667
|
* ```ts
|
|
1146
1668
|
* const output = await midnight.makeRepay({
|
|
@@ -1156,6 +1678,8 @@ export class MorphoMidnight {
|
|
|
1156
1678
|
*/
|
|
1157
1679
|
async makeRepay(params) {
|
|
1158
1680
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
1681
|
+
// Fails before any API read or build when the deadline has already passed.
|
|
1682
|
+
validateMidnightDeadline(params.deadline);
|
|
1159
1683
|
const tree = Tree.from(params.offers);
|
|
1160
1684
|
// Reject the wrong exit intent before calling the mempool validation API.
|
|
1161
1685
|
validateOfferSides(tree.offers, true);
|
|
@@ -1172,14 +1696,14 @@ export class MorphoMidnight {
|
|
|
1172
1696
|
* One transaction cancels `cancellations` under their consumption ceilings, pulls and supplies
|
|
1173
1697
|
* required `collateral`, activates the PriceRatifierV1 or RateRatifierV1 root, and publishes its
|
|
1174
1698
|
* payload. Pass no cancellations for a new publication. Calls the Midnight mempool validation
|
|
1175
|
-
* API while preparing the tree.
|
|
1699
|
+
* API while preparing the tree; `validation: false` skips that call.
|
|
1176
1700
|
*
|
|
1177
1701
|
* @param params - Maker, borrow-side offers, required collateral, cancellations, and deadline.
|
|
1178
1702
|
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
1179
1703
|
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
1180
1704
|
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
1181
1705
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
1182
|
-
* @param params.validation -
|
|
1706
|
+
* @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
|
|
1183
1707
|
* @param params.collateral - Required market and collateral supplies; every offer must target that market.
|
|
1184
1708
|
* @param params.collateral.market - Midnight market receiving the collateral; every offer must target it.
|
|
1185
1709
|
* @param params.collateral.supplies - Collateral index and assets per supply; must not be empty.
|
|
@@ -1189,19 +1713,21 @@ export class MorphoMidnight {
|
|
|
1189
1713
|
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
1190
1714
|
* required for the full pulled amount.
|
|
1191
1715
|
* @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
|
|
1192
|
-
* @throws {ChainIdMismatchError} when the client chain
|
|
1716
|
+
* @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
|
|
1717
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
1718
|
+
* RPC read fails.
|
|
1193
1719
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
|
|
1194
1720
|
* @throws {UnknownCollateralIndexError} when a collateral index is not configured.
|
|
1195
1721
|
* @throws {NonPositiveInputError} when a collateral supply amount is non-positive.
|
|
1196
1722
|
* @throws {NegativeInputError} when a `maxConsumed` ceiling or `nativeAmount` is negative.
|
|
1197
|
-
* @throws {
|
|
1198
|
-
*
|
|
1199
|
-
* collateral
|
|
1200
|
-
* collateral amount this call can pull.
|
|
1723
|
+
* @throws {InputExceedsMaxError} when a `maxConsumed` ceiling, a collateral supply amount or a
|
|
1724
|
+
* per-index sum exceeds `uint128`, `deadline` exceeds `uint256`, or `nativeAmount` exceeds the
|
|
1725
|
+
* maximum wNative collateral amount this call can pull.
|
|
1201
1726
|
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
1202
1727
|
* @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
|
|
1203
1728
|
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
1204
|
-
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1729
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
|
|
1730
|
+
* (not thrown when `validation` is `false`).
|
|
1205
1731
|
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
1206
1732
|
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
1207
1733
|
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
@@ -1209,12 +1735,27 @@ export class MorphoMidnight {
|
|
|
1209
1735
|
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
1210
1736
|
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
1211
1737
|
* @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
|
|
1738
|
+
* @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
|
|
1212
1739
|
* @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
|
|
1740
|
+
* @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
|
|
1741
|
+
* @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
|
|
1742
|
+
* @throws {MidnightOfferGroupConsumedError} when an offer group has no remaining capacity.
|
|
1743
|
+
* @throws {MidnightOfferTickSpacingError} when an offer tick is not accessible in its market.
|
|
1744
|
+
* @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} when the market fee exceeds an offer's cap.
|
|
1745
|
+
* @throws {MidnightOfferZeroPriceSellError} when a sell offer has a zero tick.
|
|
1746
|
+
* @throws {MidnightOfferRateBoundUnreachableError} when a Rate V1 offer cannot satisfy its bound.
|
|
1747
|
+
* @throws {MidnightMarketMaturityTooFarError} when an uncreated market's maturity is more than 100 years after the pinned block timestamp.
|
|
1748
|
+
* @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
|
|
1749
|
+
* @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
|
|
1750
|
+
* @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
|
|
1751
|
+
* @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
|
|
1213
1752
|
* @throws {MarketIdMismatchError} when an offer targets another market than `collateral.market`, including a `collateral.market` on another chain or Midnight deployment.
|
|
1214
1753
|
* @throws {EmptyMidnightCollateralSuppliesError} when a collateral market has no collateral supplies.
|
|
1215
1754
|
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
1755
|
+
* @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
|
|
1216
1756
|
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
1217
1757
|
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
|
|
1758
|
+
* @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
|
|
1218
1759
|
* @example
|
|
1219
1760
|
* ```ts
|
|
1220
1761
|
* const output = await midnight.supplyCollateralMakeBorrow({
|
|
@@ -1230,12 +1771,21 @@ export class MorphoMidnight {
|
|
|
1230
1771
|
*/
|
|
1231
1772
|
async supplyCollateralMakeBorrow(params) {
|
|
1232
1773
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
1774
|
+
// Fails before any API read or build when the deadline has already passed.
|
|
1775
|
+
validateMidnightDeadline(params.deadline);
|
|
1233
1776
|
const market = params.collateral.market instanceof MarketParams
|
|
1234
1777
|
? params.collateral.market
|
|
1235
1778
|
: MarketParams.from(params.collateral.market);
|
|
1236
|
-
const
|
|
1237
|
-
validateOfferSides(
|
|
1238
|
-
|
|
1779
|
+
const tree = Tree.from(params.offers);
|
|
1780
|
+
validateOfferSides(tree.offers, false);
|
|
1781
|
+
validateMidnightMakerOfferCallbacks(tree.offers);
|
|
1782
|
+
rejectReduceOnlyOffers(tree.offers);
|
|
1783
|
+
const data = await getOffersDataInternal({
|
|
1784
|
+
client: this.client,
|
|
1785
|
+
chainId: this.chainId,
|
|
1786
|
+
params: { ...params, offers: tree },
|
|
1787
|
+
marketCreationTime: "now",
|
|
1788
|
+
});
|
|
1239
1789
|
const marketId = MarketUtils.toId(market);
|
|
1240
1790
|
for (const offer of data.tree.offers) {
|
|
1241
1791
|
const offerMarketId = MarketUtils.toId(offer.market);
|
|
@@ -1294,17 +1844,33 @@ export class MorphoMidnight {
|
|
|
1294
1844
|
*
|
|
1295
1845
|
* @param params - Position owner, accrued position, optional unit amount, and receiver.
|
|
1296
1846
|
* @param params.accountAddress - Position owner whose credit is redeemed.
|
|
1297
|
-
* @param params.positionData -
|
|
1847
|
+
* @param params.positionData - Owner-bound position snapshot returned by `getPositionData`.
|
|
1298
1848
|
* @param params.receiver - Optional credit receiver; defaults to the position owner.
|
|
1849
|
+
* Midnight protocol and market token contracts are rejected.
|
|
1299
1850
|
* @param params.units - Optional credit units to redeem; defaults to the position face value.
|
|
1851
|
+
* Credit is checked after applying the realized losses and continuous fees that Midnight
|
|
1852
|
+
* charges before a withdrawal, accrued up to now. Fees keep accruing until maturity, so `units` close to the accrued
|
|
1853
|
+
* credit can still revert when the transaction lands later. The default face value does not
|
|
1854
|
+
* shrink with time, but before maturity on a market with a continuous fee it is not a full
|
|
1855
|
+
* exit: `withdraw` cuts the pending fee in proportion to the units withdrawn, so some credit
|
|
1856
|
+
* is left. Redeem again after maturity to empty the position.
|
|
1300
1857
|
* @returns No requirements and a synchronous redemption transaction builder.
|
|
1301
1858
|
* @throws {ChainIdMismatchError} when the position market targets another chain.
|
|
1302
1859
|
* @throws {MidnightMarketAddressMismatchError} when the position market targets another Midnight deployment.
|
|
1303
1860
|
* @throws {MissingAccrualPositionError} when no position snapshot is supplied.
|
|
1304
1861
|
* @throws {AccrualPositionUserMismatchError} when the position snapshot belongs to another account.
|
|
1305
1862
|
* @throws {NoMidnightCreditToRedeemError} when the selected unit amount is non-positive.
|
|
1306
|
-
* @throws {MidnightRedeemExceedsCreditError} when the selected amount exceeds
|
|
1863
|
+
* @throws {MidnightRedeemExceedsCreditError} when the selected amount exceeds the accrued
|
|
1864
|
+
* position credit.
|
|
1865
|
+
* @throws {InvalidMidnightPositionLossFactorError} when the market loss factor is below the
|
|
1866
|
+
* position's `lastLossFactor`, which `getPositionData` snapshots never are.
|
|
1867
|
+
* @throws {InvalidMidnightPositionAccrualStateError} when the snapshot's credit, pending fee or
|
|
1868
|
+
* loss factor are inconsistent, which `getPositionData` snapshots never are.
|
|
1869
|
+
* @throws {InputExceedsMaxError} when the selected units exceed `uint128`.
|
|
1307
1870
|
* @throws {InsufficientMidnightWithdrawableLiquidityError} when market liquidity cannot cover the redemption.
|
|
1871
|
+
* @throws {MidnightZeroReceiverError} when `receiver` resolves to the zero address.
|
|
1872
|
+
* @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
|
|
1873
|
+
* market token contract.
|
|
1308
1874
|
* @example
|
|
1309
1875
|
* ```ts
|
|
1310
1876
|
* const output = midnight.redeem({
|
|
@@ -1325,17 +1891,21 @@ export class MorphoMidnight {
|
|
|
1325
1891
|
}
|
|
1326
1892
|
const market = params.positionData.market;
|
|
1327
1893
|
validateMarketData(market, this.chainId);
|
|
1328
|
-
|
|
1894
|
+
// Apply realized losses and continuous fees the way `Midnight._updatePosition` does before a
|
|
1895
|
+
// withdrawal; never accrue to before the snapshot's `lastAccrual`.
|
|
1896
|
+
const accrued = params.positionData.accrueInterest(MathLib.max(Time.timestamp(), params.positionData.lastAccrual));
|
|
1897
|
+
const units = params.units ?? accrued.faceValue;
|
|
1329
1898
|
if (params.units !== undefined && units <= 0n) {
|
|
1330
1899
|
throw new NonPositiveInputError("units", units);
|
|
1331
1900
|
}
|
|
1332
1901
|
if (units <= 0n)
|
|
1333
1902
|
throw new NoMidnightCreditToRedeemError(market.id);
|
|
1334
|
-
|
|
1903
|
+
validateMidnightUint128Field("units", units);
|
|
1904
|
+
if (accrued.credit < units) {
|
|
1335
1905
|
throw new MidnightRedeemExceedsCreditError({
|
|
1336
1906
|
market: market.id,
|
|
1337
1907
|
units,
|
|
1338
|
-
credit:
|
|
1908
|
+
credit: accrued.credit,
|
|
1339
1909
|
});
|
|
1340
1910
|
}
|
|
1341
1911
|
if (market.withdrawable < units) {
|
|
@@ -1345,18 +1915,18 @@ export class MorphoMidnight {
|
|
|
1345
1915
|
withdrawable: market.withdrawable,
|
|
1346
1916
|
});
|
|
1347
1917
|
}
|
|
1918
|
+
// Build eagerly so the receiver guard throws on this call like the other flows.
|
|
1919
|
+
const tx = midnightRedeem({
|
|
1920
|
+
chainId: this.chainId,
|
|
1921
|
+
market: market.params,
|
|
1922
|
+
units,
|
|
1923
|
+
onBehalf: params.accountAddress,
|
|
1924
|
+
receiver: params.receiver,
|
|
1925
|
+
metadata: this.client.options.metadata,
|
|
1926
|
+
});
|
|
1348
1927
|
return {
|
|
1349
|
-
getRequirements: async () =>
|
|
1350
|
-
|
|
1351
|
-
},
|
|
1352
|
-
buildTx: () => midnightRedeem({
|
|
1353
|
-
chainId: this.chainId,
|
|
1354
|
-
market: market.params,
|
|
1355
|
-
units,
|
|
1356
|
-
onBehalf: params.accountAddress,
|
|
1357
|
-
receiver: params.receiver,
|
|
1358
|
-
metadata: this.client.options.metadata,
|
|
1359
|
-
}),
|
|
1928
|
+
getRequirements: async () => [],
|
|
1929
|
+
buildTx: () => tx,
|
|
1360
1930
|
};
|
|
1361
1931
|
}
|
|
1362
1932
|
/**
|
|
@@ -1365,6 +1935,16 @@ export class MorphoMidnight {
|
|
|
1365
1935
|
* @param params - Account, market snapshot, `repay` mode, collateral withdrawals, optional collateral receiver, and deadline.
|
|
1366
1936
|
* @param params.accountAddress - Position owner and transaction sender.
|
|
1367
1937
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
1938
|
+
* @param params.positionData - Owner-bound position snapshot returned by `getPositionData`. The
|
|
1939
|
+
* `DEFAULT_LLTV_BUFFER` check is only as current as this snapshot and `collateralPrices`: it
|
|
1940
|
+
* does not see transactions mined or prices moved since, so two transactions built from one
|
|
1941
|
+
* snapshot can together end inside the buffer. Midnight still rejects any position above
|
|
1942
|
+
* LLTV onchain. Midnight debt and collateral do not accrue, so the check needs no accrual.
|
|
1943
|
+
* @param params.collateralPrices - Values from `price()` on each
|
|
1944
|
+
* `marketData.params.collateralParams[i].oracle`, indexed like `positionData.collateral` and
|
|
1945
|
+
* scaled by `ORACLE_PRICE_SCALE`. An empty array is safe only when
|
|
1946
|
+
* `collateralWithdrawals` is empty or the conservative post-operation debt is zero: a `full`
|
|
1947
|
+
* repay, or `repay.assets` covering `positionData.debt`.
|
|
1368
1948
|
* @param params.repay - `{ type: "assets", assets }` (`0n` to only withdraw) or `{ type: "full", maxBuyerAssets }`; a loan-token approval to `MidnightBundlesV2` is required when the allowance is below the pulled amount — unlimited (`maxUint256`) by default, or `approvalAmount` when passed to `getRequirements()` — and any unused part is refunded.
|
|
1369
1949
|
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
1370
1950
|
* chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
|
|
@@ -1372,13 +1952,25 @@ export class MorphoMidnight {
|
|
|
1372
1952
|
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
1373
1953
|
* required for the full pulled amount.
|
|
1374
1954
|
* @param params.collateralWithdrawals - Optional withdrawals; `assets: maxUint256` withdraws the full balance.
|
|
1375
|
-
* @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress
|
|
1376
|
-
*
|
|
1955
|
+
* @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`,
|
|
1956
|
+
* must be non-zero and not a Midnight protocol or market token contract when
|
|
1957
|
+
* `collateralWithdrawals` is non-empty, and is unused otherwise.
|
|
1958
|
+
* @param params.deadline - Bundle execution deadline timestamp. Unlike taker builders,
|
|
1959
|
+
* `maxUint256` is accepted because no offers are filled; the pull remains bounded by
|
|
1960
|
+
* `repay.assets` or `repay.maxBuyerAssets`.
|
|
1377
1961
|
* @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
|
|
1378
|
-
* @throws {ChainIdMismatchError} when client or market data targets another chain
|
|
1962
|
+
* @throws {ChainIdMismatchError} when client or market data targets another chain, or from
|
|
1963
|
+
* `getRequirements()` when the RPC reports another chain via `eth_chainId`.
|
|
1964
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
1965
|
+
* RPC read fails.
|
|
1379
1966
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
1967
|
+
* @throws {AccrualPositionUserMismatchError} when `positionData.user` differs from `accountAddress`.
|
|
1968
|
+
* @throws {MarketIdMismatchError} when `positionData.marketId` differs from `marketData.id`.
|
|
1969
|
+
* @throws {WithdrawExceedsCollateralError} when a withdrawal exceeds the position's collateral.
|
|
1970
|
+
* @throws {MissingMarketPriceError} when a held collateral index has no supplied price.
|
|
1971
|
+
* @throws {WithdrawMakesPositionUnhealthyError} when the withdrawal exceeds buffered collateral capacity.
|
|
1380
1972
|
* @throws {NegativeInputError} when `repay.assets` or `nativeAmount` is negative.
|
|
1381
|
-
* @throws {NonPositiveInputError} when nothing is repaid or withdrawn, a withdrawal amount is zero, `repay.maxBuyerAssets` is zero
|
|
1973
|
+
* @throws {NonPositiveInputError} when nothing is repaid or withdrawn, a withdrawal amount is zero, or `repay.maxBuyerAssets` is zero.
|
|
1382
1974
|
* @throws {InputExceedsMaxError} when `repay.assets` or `repay.maxBuyerAssets` is at least
|
|
1383
1975
|
* `maxUint256`, a withdrawal amount or `deadline` exceeds uint256, or `nativeAmount` exceeds
|
|
1384
1976
|
* the maximum wNative amount this call can pull, including zero for a withdraw-only call.
|
|
@@ -1386,13 +1978,23 @@ export class MorphoMidnight {
|
|
|
1386
1978
|
* @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
|
|
1387
1979
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
1388
1980
|
* @throws {UnknownCollateralIndexError} when a withdrawal selects an unconfigured collateral.
|
|
1981
|
+
* @throws {MidnightRepayExceedsDebtError} when `repay.assets` exceeds the position's debt.
|
|
1982
|
+
* @throws {MidnightTakeTargetUnreachableError} when a full repay's `repay.maxBuyerAssets` is below
|
|
1983
|
+
* the position's debt.
|
|
1984
|
+
* @throws {MidnightZeroReceiverError} when collateral is withdrawn to the zero address. Thrown
|
|
1985
|
+
* during this method call, before the lazy output is returned.
|
|
1986
|
+
* @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
|
|
1987
|
+
* contract or a market token contract.
|
|
1389
1988
|
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
|
|
1989
|
+
* @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
|
|
1390
1990
|
* @example
|
|
1391
1991
|
* ```ts
|
|
1392
1992
|
* // Close the position: repay all debt, withdraw all collateral.
|
|
1393
1993
|
* const output = midnight.repayWithdrawCollateral({
|
|
1394
1994
|
* accountAddress: borrower,
|
|
1395
1995
|
* marketData,
|
|
1996
|
+
* positionData,
|
|
1997
|
+
* collateralPrices,
|
|
1396
1998
|
* repay: { type: "full", maxBuyerAssets: 1_010_000n },
|
|
1397
1999
|
* collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
|
|
1398
2000
|
* deadline: maxUint256,
|
|
@@ -1401,6 +2003,8 @@ export class MorphoMidnight {
|
|
|
1401
2003
|
*/
|
|
1402
2004
|
repayWithdrawCollateral(params) {
|
|
1403
2005
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
2006
|
+
// Fails before any API read or build when the deadline has already passed.
|
|
2007
|
+
validateMidnightDeadline(params.deadline);
|
|
1404
2008
|
const market = params.marketData.params;
|
|
1405
2009
|
const tx = midnightRepayWithdrawCollateral({
|
|
1406
2010
|
chainId: this.chainId,
|
|
@@ -1412,6 +2016,66 @@ export class MorphoMidnight {
|
|
|
1412
2016
|
deadline: params.deadline,
|
|
1413
2017
|
metadata: this.client.options.metadata,
|
|
1414
2018
|
});
|
|
2019
|
+
validatePositionBinding({
|
|
2020
|
+
positionData: params.positionData,
|
|
2021
|
+
accountAddress: params.accountAddress,
|
|
2022
|
+
marketData: params.marketData,
|
|
2023
|
+
});
|
|
2024
|
+
const collateralWithdrawals = params.collateralWithdrawals ?? [];
|
|
2025
|
+
const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
|
|
2026
|
+
let withdrawAmount = 0n;
|
|
2027
|
+
for (const withdrawal of collateralWithdrawals) {
|
|
2028
|
+
// Reject unconfigured collateral indexes before updating postCollateral.
|
|
2029
|
+
MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
|
|
2030
|
+
const index = Number(withdrawal.collateralIndex);
|
|
2031
|
+
const available = postCollateral[index] ?? 0n;
|
|
2032
|
+
const amount = withdrawal.assets === maxUint256 ? available : withdrawal.assets;
|
|
2033
|
+
if (amount > available) {
|
|
2034
|
+
throw new WithdrawExceedsCollateralError({
|
|
2035
|
+
withdrawAmount: amount,
|
|
2036
|
+
available,
|
|
2037
|
+
market: params.marketData.id,
|
|
2038
|
+
});
|
|
2039
|
+
}
|
|
2040
|
+
postCollateral[index] = available - amount;
|
|
2041
|
+
withdrawAmount += amount;
|
|
2042
|
+
}
|
|
2043
|
+
// The bundle must fill the whole assets target and the direct repay is capped at the debt, so a repay above it reverts `OutOfOffers()`.
|
|
2044
|
+
if (params.repay.type === "assets" &&
|
|
2045
|
+
params.repay.assets > params.positionData.debt) {
|
|
2046
|
+
throw new MidnightRepayExceedsDebtError({
|
|
2047
|
+
field: "repay.assets",
|
|
2048
|
+
value: params.repay.assets,
|
|
2049
|
+
debt: params.positionData.debt,
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
if (params.repay.type === "full" &&
|
|
2053
|
+
params.repay.maxBuyerAssets < params.positionData.debt) {
|
|
2054
|
+
throw new MidnightTakeTargetUnreachableError({
|
|
2055
|
+
field: "repay.maxBuyerAssets",
|
|
2056
|
+
value: params.repay.maxBuyerAssets,
|
|
2057
|
+
limit: params.positionData.debt,
|
|
2058
|
+
});
|
|
2059
|
+
}
|
|
2060
|
+
const postDebt = params.repay.type === "full"
|
|
2061
|
+
? 0n
|
|
2062
|
+
: params.positionData.debt > params.repay.assets
|
|
2063
|
+
? params.positionData.debt - params.repay.assets
|
|
2064
|
+
: 0n;
|
|
2065
|
+
if (collateralWithdrawals.length > 0 && postDebt > 0n) {
|
|
2066
|
+
const maxSafeDebt = getMidnightMaxSafeDebt({
|
|
2067
|
+
market: params.marketData,
|
|
2068
|
+
collateral: postCollateral,
|
|
2069
|
+
collateralPrices: params.collateralPrices,
|
|
2070
|
+
});
|
|
2071
|
+
if (postDebt > maxSafeDebt) {
|
|
2072
|
+
throw new WithdrawMakesPositionUnhealthyError({
|
|
2073
|
+
withdrawAmount,
|
|
2074
|
+
borrowAssets: postDebt,
|
|
2075
|
+
maxSafeBorrow: maxSafeDebt,
|
|
2076
|
+
});
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
1415
2079
|
const pulledAssets = params.repay.type === "assets"
|
|
1416
2080
|
? params.repay.assets
|
|
1417
2081
|
: params.repay.maxBuyerAssets;
|
|
@@ -1441,21 +2105,31 @@ export class MorphoMidnight {
|
|
|
1441
2105
|
* `maxConsumed` ceiling, so fills landing before execution never leave a partial cancel.
|
|
1442
2106
|
*
|
|
1443
2107
|
* @param params - Maker account, groups with consumption ceilings, and deadline.
|
|
1444
|
-
* @param params.accountAddress - Maker that must send the transaction
|
|
1445
|
-
*
|
|
2108
|
+
* @param params.accountAddress - Maker that must send the transaction. It is used only to check
|
|
2109
|
+
* the maker's Midnight authorization of `MidnightBundlesV2`; the bundle cancels the groups of
|
|
2110
|
+
* `msg.sender`. A transaction sent from another account that has also authorized
|
|
2111
|
+
* `MidnightBundlesV2` does not revert: it cancels that account's groups and leaves the maker's
|
|
2112
|
+
* offers fillable.
|
|
1446
2113
|
* @param params.cancellations - Offer groups and the largest consumption accepted for each.
|
|
1447
2114
|
* To cancel unconditionally, set `maxConsumed` to `maxUint128`; the contract treats
|
|
1448
2115
|
* `type(uint128).max` as no limit.
|
|
2116
|
+
* Cancellation is per group: it does not unratify roots or revoke
|
|
2117
|
+
* `MidnightBundlesV2` or ratifier authorization.
|
|
1449
2118
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
1450
2119
|
* @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
|
|
1451
|
-
* @throws {ChainIdMismatchError} when the client targets another chain
|
|
2120
|
+
* @throws {ChainIdMismatchError} when the client targets another chain, or from
|
|
2121
|
+
* `getRequirements()` when the RPC reports another chain via `eth_chainId`.
|
|
2122
|
+
* @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
|
|
2123
|
+
* RPC read fails.
|
|
1452
2124
|
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
1453
2125
|
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
1454
2126
|
* @throws {EmptyMidnightGroupCancellationsError} when no groups are provided.
|
|
2127
|
+
* @throws {MidnightInvalidAccountAddressError} when `accountAddress` is malformed or zero.
|
|
2128
|
+
* @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
|
|
1455
2129
|
* @throws {DuplicateMidnightGroupCancellationError} when a group appears more than once.
|
|
1456
|
-
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
1457
2130
|
* @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
|
|
1458
2131
|
* @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
|
|
2132
|
+
* @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
|
|
1459
2133
|
* @example
|
|
1460
2134
|
* ```ts
|
|
1461
2135
|
* import { morphoViemExtension } from "@morpho-org/morpho-sdk";
|
|
@@ -1477,6 +2151,13 @@ export class MorphoMidnight {
|
|
|
1477
2151
|
*/
|
|
1478
2152
|
cancelOffers(params) {
|
|
1479
2153
|
validateChainId(this.client.viemClient.chain?.id, this.chainId);
|
|
2154
|
+
const { accountAddress } = params;
|
|
2155
|
+
if (!isAddress(accountAddress) ||
|
|
2156
|
+
isAddressEqual(accountAddress, zeroAddress)) {
|
|
2157
|
+
throw new MidnightInvalidAccountAddressError(accountAddress);
|
|
2158
|
+
}
|
|
2159
|
+
// Fails before any API read or build when the deadline has already passed.
|
|
2160
|
+
validateMidnightDeadline(params.deadline);
|
|
1480
2161
|
const tx = midnightCancelAndMake({
|
|
1481
2162
|
chainId: this.chainId,
|
|
1482
2163
|
cancellations: params.cancellations,
|
|
@@ -1484,7 +2165,7 @@ export class MorphoMidnight {
|
|
|
1484
2165
|
metadata: this.client.options.metadata,
|
|
1485
2166
|
});
|
|
1486
2167
|
return {
|
|
1487
|
-
getRequirements: () => this.getBundlesV2AuthorizationRequirements(
|
|
2168
|
+
getRequirements: () => this.getBundlesV2AuthorizationRequirements(accountAddress),
|
|
1488
2169
|
buildTx: () => tx,
|
|
1489
2170
|
};
|
|
1490
2171
|
}
|