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