@morpho-org/morpho-sdk 6.5.0 → 7.0.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 +291 -0
- package/README.md +26 -12
- package/lib/cjs/abis.d.ts +1 -1
- package/lib/cjs/abis.js +3 -2
- package/lib/cjs/actions/bundles/common.d.ts +9 -5
- package/lib/cjs/actions/bundles/common.js +22 -13
- package/lib/cjs/actions/midnight/authorization.d.ts +3 -2
- package/lib/cjs/actions/midnight/authorization.js +3 -2
- package/lib/cjs/actions/midnight/cancelAndMake.d.ts +153 -0
- package/lib/cjs/actions/midnight/cancelAndMake.js +292 -0
- package/lib/cjs/actions/midnight/index.d.ts +3 -3
- package/lib/cjs/actions/midnight/index.js +3 -3
- package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +40 -23
- package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +105 -69
- package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +52 -27
- package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +128 -71
- package/lib/cjs/actions/midnight/takeBorrow.d.ts +40 -28
- package/lib/cjs/actions/midnight/takeBorrow.js +95 -54
- package/lib/cjs/actions/midnight/takeLend.d.ts +51 -27
- package/lib/cjs/actions/midnight/takeLend.js +111 -54
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +97 -0
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +201 -0
- package/lib/cjs/actions/midnight/takeWithdraw.d.ts +69 -0
- package/lib/cjs/actions/midnight/takeWithdraw.js +153 -0
- package/lib/cjs/actions/midnight/types.d.ts +7 -26
- package/lib/cjs/actions/midnight/types.js +0 -13
- package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
- package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -4
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +5 -5
- package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +2 -2
- package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -2
- package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +24 -8
- package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +24 -13
- package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -7
- package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +11 -7
- package/lib/cjs/actions/requirements/midnight/index.d.ts +0 -1
- package/lib/cjs/actions/requirements/midnight/index.js +0 -1
- package/lib/cjs/constants.d.ts +1 -1
- package/lib/cjs/constants.js +3 -1
- package/lib/cjs/entities/blue/blue.d.ts +10 -6
- package/lib/cjs/entities/blue/blue.js +5 -3
- package/lib/cjs/entities/index.d.ts +2 -2
- package/lib/cjs/entities/midnight/midnight.d.ts +582 -108
- package/lib/cjs/entities/midnight/midnight.js +981 -509
- package/lib/cjs/entities/midnight/types.d.ts +142 -60
- package/lib/cjs/entities/vaultV1/vaultV1.d.ts +2 -1
- package/lib/cjs/entities/vaultV1/vaultV1.js +1 -0
- package/lib/cjs/entities/vaultV2/vaultV2.d.ts +2 -1
- package/lib/cjs/entities/vaultV2/vaultV2.js +1 -0
- package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +11 -3
- package/lib/cjs/entities/vaultV2BlueReallocationData.js +119 -43
- package/lib/cjs/helpers/callback.d.ts +54 -0
- package/lib/cjs/helpers/callback.js +73 -0
- package/lib/cjs/helpers/constant.d.ts +10 -0
- package/lib/cjs/helpers/constant.js +11 -1
- package/lib/cjs/helpers/index.d.ts +3 -2
- package/lib/cjs/helpers/index.js +7 -1
- package/lib/cjs/helpers/signAndVerifyTypedData.d.ts +3 -3
- package/lib/cjs/helpers/signAndVerifyTypedData.js +3 -3
- package/lib/cjs/helpers/utilization.d.ts +13 -0
- package/lib/cjs/helpers/utilization.js +26 -1
- package/lib/cjs/helpers/validate.d.ts +43 -2
- package/lib/cjs/helpers/validate.js +60 -3
- package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +1 -1
- package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +3 -7
- package/lib/cjs/helpers/validateRequirementSpender.d.ts +3 -3
- package/lib/cjs/helpers/validateRequirementSpender.js +4 -5
- package/lib/cjs/midnight/abis.d.ts +1 -1
- package/lib/cjs/midnight/abis.js +3 -2
- package/lib/cjs/midnight/types.d.ts +1 -1
- package/lib/cjs/types/action.d.ts +117 -89
- package/lib/cjs/types/action.js +1 -19
- package/lib/cjs/types/error.d.ts +126 -40
- package/lib/cjs/types/error.js +154 -49
- package/lib/cjs/types/sharedLiquidity.d.ts +17 -0
- package/lib/esm/abis.d.ts +1 -1
- package/lib/esm/abis.js +1 -1
- package/lib/esm/actions/bundles/common.d.ts +9 -5
- package/lib/esm/actions/bundles/common.js +22 -13
- package/lib/esm/actions/midnight/authorization.d.ts +3 -2
- package/lib/esm/actions/midnight/authorization.js +3 -2
- package/lib/esm/actions/midnight/cancelAndMake.d.ts +153 -0
- package/lib/esm/actions/midnight/cancelAndMake.js +288 -0
- package/lib/esm/actions/midnight/index.d.ts +3 -3
- package/lib/esm/actions/midnight/index.js +3 -3
- package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +40 -23
- package/lib/esm/actions/midnight/repayWithdrawCollateral.js +108 -72
- package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +52 -27
- package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +131 -74
- package/lib/esm/actions/midnight/takeBorrow.d.ts +40 -28
- package/lib/esm/actions/midnight/takeBorrow.js +98 -57
- package/lib/esm/actions/midnight/takeLend.d.ts +51 -27
- package/lib/esm/actions/midnight/takeLend.js +114 -57
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +97 -0
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +197 -0
- package/lib/esm/actions/midnight/takeWithdraw.d.ts +69 -0
- package/lib/esm/actions/midnight/takeWithdraw.js +149 -0
- package/lib/esm/actions/midnight/types.d.ts +7 -26
- package/lib/esm/actions/midnight/types.js +1 -12
- package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
- package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
- package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -4
- package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +5 -5
- package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +2 -2
- package/lib/esm/actions/requirements/getRequirementsApproval.js +2 -2
- package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +24 -8
- package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +25 -14
- package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -7
- package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +11 -7
- package/lib/esm/actions/requirements/midnight/index.d.ts +0 -1
- package/lib/esm/actions/requirements/midnight/index.js +0 -1
- package/lib/esm/constants.d.ts +1 -1
- package/lib/esm/constants.js +1 -1
- package/lib/esm/entities/blue/blue.d.ts +10 -6
- package/lib/esm/entities/blue/blue.js +5 -3
- package/lib/esm/entities/index.d.ts +2 -2
- package/lib/esm/entities/midnight/midnight.d.ts +582 -108
- package/lib/esm/entities/midnight/midnight.js +987 -515
- package/lib/esm/entities/midnight/types.d.ts +142 -60
- package/lib/esm/entities/vaultV1/vaultV1.d.ts +2 -1
- package/lib/esm/entities/vaultV1/vaultV1.js +1 -0
- package/lib/esm/entities/vaultV2/vaultV2.d.ts +2 -1
- package/lib/esm/entities/vaultV2/vaultV2.js +1 -0
- package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +11 -3
- package/lib/esm/entities/vaultV2BlueReallocationData.js +120 -44
- package/lib/esm/helpers/callback.d.ts +54 -0
- package/lib/esm/helpers/callback.js +68 -0
- package/lib/esm/helpers/constant.d.ts +10 -0
- package/lib/esm/helpers/constant.js +10 -0
- package/lib/esm/helpers/index.d.ts +3 -2
- package/lib/esm/helpers/index.js +3 -2
- package/lib/esm/helpers/signAndVerifyTypedData.d.ts +3 -3
- package/lib/esm/helpers/signAndVerifyTypedData.js +3 -3
- package/lib/esm/helpers/utilization.d.ts +13 -0
- package/lib/esm/helpers/utilization.js +25 -1
- package/lib/esm/helpers/validate.d.ts +43 -2
- package/lib/esm/helpers/validate.js +58 -2
- package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +1 -1
- package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +3 -7
- package/lib/esm/helpers/validateRequirementSpender.d.ts +3 -3
- package/lib/esm/helpers/validateRequirementSpender.js +4 -5
- package/lib/esm/midnight/abis.d.ts +1 -1
- package/lib/esm/midnight/abis.js +1 -1
- package/lib/esm/midnight/types.d.ts +1 -1
- package/lib/esm/types/action.d.ts +117 -89
- package/lib/esm/types/action.js +1 -18
- package/lib/esm/types/error.d.ts +126 -40
- package/lib/esm/types/error.js +135 -38
- package/lib/esm/types/sharedLiquidity.d.ts +17 -0
- package/package.json +9 -8
- package/lib/cjs/actions/midnight/cancelOffer.d.ts +0 -38
- package/lib/cjs/actions/midnight/cancelOffer.js +0 -73
- package/lib/cjs/actions/midnight/mempoolSubmitOffers.d.ts +0 -52
- package/lib/cjs/actions/midnight/mempoolSubmitOffers.js +0 -72
- package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.d.ts +0 -40
- package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.js +0 -59
- package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +0 -42
- package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +0 -70
- package/lib/esm/actions/midnight/cancelOffer.d.ts +0 -38
- package/lib/esm/actions/midnight/cancelOffer.js +0 -69
- package/lib/esm/actions/midnight/mempoolSubmitOffers.d.ts +0 -52
- package/lib/esm/actions/midnight/mempoolSubmitOffers.js +0 -68
- package/lib/esm/actions/midnight/setterRatifierRatifyRoot.d.ts +0 -40
- package/lib/esm/actions/midnight/setterRatifierRatifyRoot.js +0 -55
- package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +0 -42
- package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +0 -66
|
@@ -1,17 +1,30 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.MorphoMidnight = void 0;
|
|
4
|
+
const blue_sdk_1 = require("@morpho-org/blue-sdk");
|
|
5
|
+
const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
|
|
4
6
|
const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
|
|
5
7
|
const morpho_ts_1 = require("@morpho-org/morpho-ts");
|
|
6
8
|
const viem_1 = require("viem");
|
|
7
9
|
const index_js_1 = require("../../actions/midnight/index.js");
|
|
8
10
|
const index_js_2 = require("../../actions/requirements/index.js");
|
|
11
|
+
const callback_js_1 = require("../../helpers/callback.js");
|
|
12
|
+
const constant_js_1 = require("../../helpers/constant.js");
|
|
9
13
|
const index_js_3 = require("../../helpers/index.js");
|
|
10
|
-
const signAndVerifyTypedData_js_1 = require("../../helpers/signAndVerifyTypedData.js");
|
|
11
14
|
const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
|
|
12
15
|
const validateOfferSides_js_1 = require("../../helpers/validateOfferSides.js");
|
|
13
|
-
const validateTakeableOffers_js_1 = require("../../helpers/validateTakeableOffers.js");
|
|
14
16
|
const index_js_4 = require("../../types/index.js");
|
|
17
|
+
const offerMarketParams = (offer) => "params" in offer.market ? offer.market.params : offer.market;
|
|
18
|
+
const validateTakeDeadlineWindow = (deadline) => {
|
|
19
|
+
const now = morpho_ts_1.Time.timestamp();
|
|
20
|
+
if (deadline <= now) {
|
|
21
|
+
throw new index_js_4.ExpiredDeadlineError(deadline, now);
|
|
22
|
+
}
|
|
23
|
+
const maxDeadline = now + constant_js_1.MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
|
|
24
|
+
if (deadline > maxDeadline) {
|
|
25
|
+
throw new index_js_4.MidnightTakeDeadlineTooFarError({ deadline, maxDeadline });
|
|
26
|
+
}
|
|
27
|
+
};
|
|
15
28
|
const assertNonNegativeAmount = (label, amount) => {
|
|
16
29
|
if (amount < 0n)
|
|
17
30
|
throw new index_js_4.NegativeInputError(label, amount);
|
|
@@ -20,6 +33,12 @@ const assertPositiveAmount = (label, amount) => {
|
|
|
20
33
|
if (amount <= 0n)
|
|
21
34
|
throw new index_js_4.NonPositiveInputError(label, amount);
|
|
22
35
|
};
|
|
36
|
+
const rejectReduceOnlyOffers = (offers) => {
|
|
37
|
+
offers.forEach((offer, index) => {
|
|
38
|
+
if (offer.reduceOnly)
|
|
39
|
+
throw new index_js_4.MidnightOfferReduceOnlyError({ index });
|
|
40
|
+
});
|
|
41
|
+
};
|
|
23
42
|
const validateMarketData = (market, chainId) => {
|
|
24
43
|
// Reject snapshots from another chain deployment before exposing requirements.
|
|
25
44
|
(0, validateMidnightMarket_js_1.validateMidnightMarket)({ market, chainId });
|
|
@@ -111,22 +130,26 @@ class MorphoMidnight {
|
|
|
111
130
|
/**
|
|
112
131
|
* Builds and validates a maker offer tree against the Midnight mempool API.
|
|
113
132
|
*
|
|
114
|
-
* @param params - Maker account,
|
|
133
|
+
* @param params - Maker account, PriceRatifierV1 or RateRatifierV1 tree input, and optional API validation controls.
|
|
115
134
|
* @param params.accountAddress - Maker expected on every offer.
|
|
116
|
-
* @param params.offers -
|
|
135
|
+
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
117
136
|
* @param params.validation - Optional Midnight mempool API request controls.
|
|
118
|
-
* @returns Prepared tree
|
|
137
|
+
* @returns Prepared tree, groups, ratifier, and encoded payload used by maker flows.
|
|
119
138
|
* @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
|
|
120
139
|
* @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.
|
|
121
141
|
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
142
|
+
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
143
|
+
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
122
144
|
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
123
145
|
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
124
|
-
* @throws {
|
|
146
|
+
* @throws {UnknownAddressError} when the chain has no deployment for the tree's V1 ratifier.
|
|
147
|
+
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
125
148
|
* @example
|
|
126
149
|
* ```ts
|
|
127
150
|
* const offersData = await midnight.getOffersData({
|
|
128
151
|
* accountAddress: maker,
|
|
129
|
-
* offers: [offer],
|
|
152
|
+
* offers: { type: "rateV1", entries: [{ offer, rate }] },
|
|
130
153
|
* });
|
|
131
154
|
* ```
|
|
132
155
|
*/
|
|
@@ -142,7 +165,21 @@ class MorphoMidnight {
|
|
|
142
165
|
actualMaker: offer.maker,
|
|
143
166
|
});
|
|
144
167
|
}
|
|
145
|
-
|
|
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);
|
|
146
183
|
if (market.chainId !== BigInt(this.chainId)) {
|
|
147
184
|
throw new index_js_4.MidnightOfferMarketChainMismatchError({
|
|
148
185
|
index,
|
|
@@ -158,25 +195,17 @@ class MorphoMidnight {
|
|
|
158
195
|
});
|
|
159
196
|
}
|
|
160
197
|
});
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
: undefined;
|
|
173
|
-
if (ratifierType == null) {
|
|
174
|
-
throw new index_js_4.UnknownMidnightRatifierError({
|
|
175
|
-
ratifier,
|
|
176
|
-
ecrecoverRatifier,
|
|
177
|
-
setterRatifier,
|
|
178
|
-
});
|
|
179
|
-
}
|
|
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
|
+
});
|
|
180
209
|
const groups = [];
|
|
181
210
|
const seenGroups = new Set();
|
|
182
211
|
for (const offer of tree.offers) {
|
|
@@ -191,260 +220,434 @@ class MorphoMidnight {
|
|
|
191
220
|
...params.validation,
|
|
192
221
|
chainId: this.chainId,
|
|
193
222
|
});
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
return {
|
|
198
|
-
accountAddress: params.accountAddress,
|
|
199
|
-
groups,
|
|
200
|
-
tree,
|
|
201
|
-
ratifierType,
|
|
202
|
-
ratifier,
|
|
203
|
-
setterPayload: await midnight_sdk_1.Payload.encode(items),
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
// Ecrecover typed-data generation validates that the created tree has one ratifier.
|
|
207
|
-
midnight_sdk_1.EcrecoverRatifierUtils.typedData({ tree, chainId: this.chainId });
|
|
223
|
+
const items = tree.type === "priceV1"
|
|
224
|
+
? midnight_sdk_1.PriceRatifierV1.ratify({ tree })
|
|
225
|
+
: midnight_sdk_1.RateRatifierV1.ratify({ tree });
|
|
208
226
|
return {
|
|
209
227
|
accountAddress: params.accountAddress,
|
|
210
228
|
groups,
|
|
211
229
|
tree,
|
|
212
230
|
ratifierType,
|
|
213
231
|
ratifier,
|
|
232
|
+
payload: await midnight_sdk_1.Payload.encode(items),
|
|
214
233
|
};
|
|
215
234
|
}
|
|
216
235
|
/**
|
|
217
|
-
* Prepares a
|
|
236
|
+
* Prepares a `MidnightBundlesV2` buy that lends into borrow-side offers for `accountAddress`.
|
|
218
237
|
*
|
|
219
|
-
* @param params - Lender, market snapshot, target
|
|
220
|
-
* @param params.accountAddress - Lender
|
|
238
|
+
* @param params - Lender, market snapshot, buy target, offers, fee cap, deadline, and optional referral fee.
|
|
239
|
+
* @param params.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
|
|
221
240
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
222
|
-
* @param params.
|
|
223
|
-
* @param params.
|
|
241
|
+
* @param params.target - `{ type: "assets", assets, minUnits }` or `{ type: "units", units, maxBuyerAssets }`.
|
|
242
|
+
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
243
|
+
* chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
|
|
244
|
+
* the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
|
|
245
|
+
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
246
|
+
* required for the full pulled amount.
|
|
224
247
|
* @param params.takeableOffers - Borrow-side offers returned by the Midnight API.
|
|
248
|
+
* @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
|
|
249
|
+
* onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
|
|
250
|
+
* is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
|
|
225
251
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
226
|
-
* @
|
|
252
|
+
* @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
|
|
253
|
+
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
254
|
+
* @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
|
|
227
255
|
* @throws {ChainIdMismatchError} when client or market data targets another chain.
|
|
256
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
257
|
+
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
258
|
+
* @throws {InputExceedsMaxError} when `target.assets`, `target.units`, `minUnits`, `maxBuyerAssets`
|
|
259
|
+
* or `maxContinuousFee` exceeds `uint256`, or `nativeAmount` exceeds the maximum
|
|
260
|
+
* wNative amount this call can pull.
|
|
228
261
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
229
|
-
* @throws {NonPositiveInputError} when `
|
|
230
|
-
* @throws {NegativeInputError} when `
|
|
262
|
+
* @throws {NonPositiveInputError} when the target amount, `minUnits` or `maxBuyerAssets` is not positive.
|
|
263
|
+
* @throws {NegativeInputError} when `maxContinuousFee`, `referralFeePct` or `nativeAmount` is negative.
|
|
264
|
+
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
265
|
+
* @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
|
|
266
|
+
* @throws {UnboundedMidnightTakeInputError} when `target.units` or
|
|
267
|
+
* `target.maxBuyerAssets` is `maxUint256`.
|
|
268
|
+
* @throws {ExpiredDeadlineError} when `deadline` has expired.
|
|
269
|
+
* @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
|
|
231
270
|
* @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
|
|
232
271
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
233
272
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
273
|
+
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
274
|
+
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
275
|
+
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
|
|
234
276
|
* @example
|
|
235
277
|
* ```ts
|
|
236
278
|
* const output = midnight.takeLend({
|
|
237
279
|
* accountAddress: lender,
|
|
238
280
|
* marketData,
|
|
239
|
-
* assets: 1_000_000n,
|
|
240
|
-
* minUnits: 900_000n,
|
|
281
|
+
* target: { type: "assets", assets: 1_000_000n, minUnits: 900_000n },
|
|
241
282
|
* takeableOffers: quote.data.takeableOffers,
|
|
242
|
-
*
|
|
283
|
+
* maxContinuousFee: maxUint256,
|
|
284
|
+
* deadline: Time.timestamp() + 600n,
|
|
243
285
|
* });
|
|
244
286
|
* ```
|
|
245
287
|
*/
|
|
246
288
|
takeLend(params) {
|
|
247
289
|
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
290
|
+
validateTakeDeadlineWindow(params.deadline);
|
|
291
|
+
const market = params.marketData.params;
|
|
292
|
+
const tx = (0, index_js_1.midnightTakeLend)({
|
|
293
|
+
chainId: this.chainId,
|
|
294
|
+
market,
|
|
295
|
+
target: params.target,
|
|
296
|
+
nativeAmount: params.nativeAmount,
|
|
255
297
|
takeableOffers: params.takeableOffers,
|
|
256
|
-
|
|
298
|
+
maxContinuousFee: params.maxContinuousFee,
|
|
299
|
+
deadline: params.deadline,
|
|
300
|
+
referralFeePct: params.referralFeePct,
|
|
301
|
+
referralFeeRecipient: params.referralFeeRecipient,
|
|
302
|
+
metadata: this.client.options.metadata,
|
|
257
303
|
});
|
|
258
|
-
const
|
|
259
|
-
|
|
304
|
+
const pulledAssets = params.target.type === "assets"
|
|
305
|
+
? params.target.assets
|
|
306
|
+
: params.target.maxBuyerAssets;
|
|
260
307
|
return {
|
|
261
|
-
getRequirements: async () => {
|
|
262
|
-
const
|
|
263
|
-
...(await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
264
|
-
viemClient: this.client.viemClient,
|
|
265
|
-
chainId: this.chainId,
|
|
266
|
-
token: market.params.loanToken,
|
|
267
|
-
owner: params.accountAddress,
|
|
268
|
-
spender: midnightBundles,
|
|
269
|
-
amount: params.assets,
|
|
270
|
-
})),
|
|
271
|
-
];
|
|
272
|
-
const authorization = await (0, index_js_2.getMidnightAuthorizationRequirement)({
|
|
308
|
+
getRequirements: async (requirementsParams) => {
|
|
309
|
+
const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
273
310
|
viemClient: this.client.viemClient,
|
|
274
311
|
chainId: this.chainId,
|
|
312
|
+
token: market.loanToken,
|
|
275
313
|
owner: params.accountAddress,
|
|
276
|
-
|
|
314
|
+
spender: tx.to,
|
|
315
|
+
amount: pulledAssets,
|
|
316
|
+
approvalAmount: requirementsParams?.approvalAmount,
|
|
277
317
|
});
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
return requirements;
|
|
318
|
+
const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
|
|
319
|
+
return [...approvals, ...authorization];
|
|
281
320
|
},
|
|
282
|
-
buildTx: () =>
|
|
283
|
-
chainId: this.chainId,
|
|
284
|
-
market: market.params,
|
|
285
|
-
assets: params.assets,
|
|
286
|
-
minUnits: params.minUnits,
|
|
287
|
-
taker: params.accountAddress,
|
|
288
|
-
takeableOffers: params.takeableOffers,
|
|
289
|
-
deadline: params.deadline,
|
|
290
|
-
metadata: this.client.options.metadata,
|
|
291
|
-
}),
|
|
321
|
+
buildTx: () => tx,
|
|
292
322
|
};
|
|
293
323
|
}
|
|
294
324
|
/**
|
|
295
|
-
* Prepares a
|
|
325
|
+
* Prepares a `MidnightBundlesV2` sell that borrows from lend-side offers for `accountAddress`.
|
|
326
|
+
*
|
|
327
|
+
* The bundle first withdraws as much of the sender's existing credit as the target and market
|
|
328
|
+
* liquidity allow, then fills the rest from offers.
|
|
296
329
|
*
|
|
297
|
-
* @param params - Borrower, market snapshot, target
|
|
298
|
-
* @param params.accountAddress - Borrower
|
|
330
|
+
* @param params - Borrower, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
|
|
331
|
+
* @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
|
|
299
332
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
300
|
-
* @param params.
|
|
301
|
-
* @param params.
|
|
333
|
+
* @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
|
|
334
|
+
* @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
|
|
302
335
|
* @param params.takeableOffers - Lend-side offers returned by the Midnight API.
|
|
303
|
-
* @param params.deadline -
|
|
304
|
-
* @
|
|
336
|
+
* @param params.deadline - Bounded bundle execution deadline timestamp.
|
|
337
|
+
* @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
|
|
338
|
+
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
339
|
+
* @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
|
|
305
340
|
* @throws {ChainIdMismatchError} when client or market data targets another chain.
|
|
341
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
342
|
+
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
343
|
+
* @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`
|
|
344
|
+
* or `target.minSellerAssets` exceeds `uint256`.
|
|
306
345
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
307
|
-
* @throws {NonPositiveInputError} when `
|
|
308
|
-
* @throws {NegativeInputError} when `
|
|
346
|
+
* @throws {NonPositiveInputError} when the target amount, `maxUnits` or `minSellerAssets` is not positive.
|
|
347
|
+
* @throws {NegativeInputError} when `referralFeePct` is negative.
|
|
348
|
+
* @throws {UnboundedMidnightTakeInputError} when `target.units` or
|
|
349
|
+
* `target.maxUnits` is `maxUint256`.
|
|
350
|
+
* @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
|
|
351
|
+
* @throws {ExpiredDeadlineError} when `deadline` has expired.
|
|
352
|
+
* @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
|
|
309
353
|
* @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
|
|
310
354
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
311
355
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
356
|
+
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
357
|
+
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
312
358
|
* @example
|
|
313
359
|
* ```ts
|
|
314
360
|
* const output = midnight.takeBorrow({
|
|
315
361
|
* accountAddress: borrower,
|
|
316
362
|
* marketData,
|
|
317
|
-
*
|
|
318
|
-
* maxUnits: 1_100_000n,
|
|
363
|
+
* target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
|
|
319
364
|
* takeableOffers: quote.data.takeableOffers,
|
|
320
|
-
* deadline:
|
|
365
|
+
* deadline: Time.timestamp() + 600n,
|
|
321
366
|
* });
|
|
322
367
|
* ```
|
|
323
368
|
*/
|
|
324
369
|
takeBorrow(params) {
|
|
325
370
|
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
assertNonNegativeAmount("deadline", params.deadline);
|
|
330
|
-
// Reject inconsistent quotes before exposing requirement reads.
|
|
331
|
-
(0, validateTakeableOffers_js_1.validateTakeableOffers)({
|
|
371
|
+
validateTakeDeadlineWindow(params.deadline);
|
|
372
|
+
const tx = (0, index_js_1.midnightTakeBorrow)({
|
|
373
|
+
chainId: this.chainId,
|
|
332
374
|
market: params.marketData.params,
|
|
375
|
+
target: params.target,
|
|
376
|
+
receiver: params.receiver ?? params.accountAddress,
|
|
333
377
|
takeableOffers: params.takeableOffers,
|
|
334
|
-
|
|
378
|
+
deadline: params.deadline,
|
|
379
|
+
referralFeePct: params.referralFeePct,
|
|
380
|
+
referralFeeRecipient: params.referralFeeRecipient,
|
|
381
|
+
metadata: this.client.options.metadata,
|
|
335
382
|
});
|
|
336
|
-
const market = params.marketData;
|
|
337
|
-
const midnightBundles = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnightBundles");
|
|
338
383
|
return {
|
|
339
|
-
getRequirements:
|
|
340
|
-
|
|
341
|
-
|
|
384
|
+
getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
|
|
385
|
+
buildTx: () => tx,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Prepares a reduce-only `MidnightBundlesV2` sell that withdraws `accountAddress`'s credit.
|
|
390
|
+
*
|
|
391
|
+
* The bundle first redeems as much credit as the target and market liquidity allow, then sells
|
|
392
|
+
* the rest to lend-side offers. `reduceOnly` is always set, so it never opens debt. Use `redeem`
|
|
393
|
+
* for a direct redemption without offers.
|
|
394
|
+
*
|
|
395
|
+
* @param params - Lender, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
|
|
396
|
+
* @param params.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
|
|
397
|
+
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
398
|
+
* @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
|
|
399
|
+
* @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
|
|
400
|
+
* @param params.takeableOffers - Lend-side offers returned by the Midnight API.
|
|
401
|
+
* @param params.deadline - Bundle execution deadline timestamp.
|
|
402
|
+
* @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
|
|
403
|
+
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
404
|
+
* @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
|
|
405
|
+
* @throws {ChainIdMismatchError} when client or market data targets another chain.
|
|
406
|
+
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
407
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
408
|
+
* @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`
|
|
409
|
+
* or `target.minSellerAssets` exceeds `uint256`.
|
|
410
|
+
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
411
|
+
* @throws {NonPositiveInputError} when the target amount, `maxUnits` or `minSellerAssets` is
|
|
412
|
+
* not positive.
|
|
413
|
+
* @throws {NegativeInputError} when `referralFeePct` is negative.
|
|
414
|
+
* @throws {UnboundedMidnightTakeInputError} when `target.units` or `target.maxUnits` is `maxUint256`.
|
|
415
|
+
* @throws {ExpiredDeadlineError} when `deadline` has expired.
|
|
416
|
+
* @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
|
|
417
|
+
* @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
|
|
418
|
+
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
419
|
+
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
420
|
+
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
421
|
+
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
422
|
+
* @example
|
|
423
|
+
* ```ts
|
|
424
|
+
* const output = midnight.takeWithdraw({
|
|
425
|
+
* accountAddress: lender,
|
|
426
|
+
* marketData,
|
|
427
|
+
* target: { type: "units", units: credit, minSellerAssets: 990_000n },
|
|
428
|
+
* takeableOffers: quote.data.takeableOffers,
|
|
429
|
+
* deadline: Time.timestamp() + 600n,
|
|
430
|
+
* });
|
|
431
|
+
* ```
|
|
432
|
+
*/
|
|
433
|
+
takeWithdraw(params) {
|
|
434
|
+
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
435
|
+
validateTakeDeadlineWindow(params.deadline);
|
|
436
|
+
const tx = (0, index_js_1.midnightTakeWithdraw)({
|
|
437
|
+
chainId: this.chainId,
|
|
438
|
+
market: params.marketData.params,
|
|
439
|
+
target: params.target,
|
|
440
|
+
receiver: params.receiver ?? params.accountAddress,
|
|
441
|
+
takeableOffers: params.takeableOffers,
|
|
442
|
+
deadline: params.deadline,
|
|
443
|
+
referralFeePct: params.referralFeePct,
|
|
444
|
+
referralFeeRecipient: params.referralFeeRecipient,
|
|
445
|
+
metadata: this.client.options.metadata,
|
|
446
|
+
});
|
|
447
|
+
return {
|
|
448
|
+
getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
|
|
449
|
+
buildTx: () => tx,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Prepares one `MidnightBundlesV2` sell that supplies collateral and borrows from lend-side
|
|
454
|
+
* offers for `accountAddress`.
|
|
455
|
+
*
|
|
456
|
+
* Like `takeBorrow`, the sender's existing credit is withdrawn before offers are taken.
|
|
457
|
+
*
|
|
458
|
+
* @param params - Borrower, market snapshot, collateral supplies, sell target, offers, deadline, receiver, and optional referral fee.
|
|
459
|
+
* @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
|
|
460
|
+
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
461
|
+
* @param params.collateralSupplies - Collateral index and assets per supply; must not be empty.
|
|
462
|
+
* @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
|
|
463
|
+
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
464
|
+
* chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
|
|
465
|
+
* the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
|
|
466
|
+
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
467
|
+
* required for the full pulled amount.
|
|
468
|
+
* @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
|
|
469
|
+
* @param params.takeableOffers - Lend-side offers returned by the Midnight API.
|
|
470
|
+
* @param params.deadline - Bounded bundle execution deadline timestamp.
|
|
471
|
+
* @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
|
|
472
|
+
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
473
|
+
* @returns Lazy collateral approvals and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
|
|
474
|
+
* @throws {ChainIdMismatchError} when client or market data targets another chain.
|
|
475
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
476
|
+
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
477
|
+
* @throws {InputExceedsMaxError} when a `collateralSupplies[].assets` amount, `target.assets`,
|
|
478
|
+
* `target.maxUnits`, `target.units` or `target.minSellerAssets` exceeds `uint256`, or
|
|
479
|
+
* `nativeAmount` exceeds the maximum wNative collateral amount this call can pull.
|
|
480
|
+
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
481
|
+
* @throws {EmptyMidnightCollateralSuppliesError} when no collateral supply is provided.
|
|
482
|
+
* @throws {UnknownCollateralIndexError} when a collateral index is not configured.
|
|
483
|
+
* @throws {NonPositiveInputError} when a supply amount, the target amount, `maxUnits` or `minSellerAssets` is not positive.
|
|
484
|
+
* @throws {NegativeInputError} when `referralFeePct` or `nativeAmount` is negative.
|
|
485
|
+
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
486
|
+
* @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
|
|
487
|
+
* @throws {UnboundedMidnightTakeInputError} when `target.units` or
|
|
488
|
+
* `target.maxUnits` is `maxUint256`.
|
|
489
|
+
* @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
|
|
490
|
+
* @throws {ExpiredDeadlineError} when `deadline` has expired.
|
|
491
|
+
* @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
|
|
492
|
+
* @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
|
|
493
|
+
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
494
|
+
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
495
|
+
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
496
|
+
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
497
|
+
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
|
|
498
|
+
* @example
|
|
499
|
+
* ```ts
|
|
500
|
+
* const output = midnight.supplyCollateralTakeBorrow({
|
|
501
|
+
* accountAddress: borrower,
|
|
502
|
+
* marketData,
|
|
503
|
+
* collateralSupplies: [{ collateralIndex: 0n, assets: 2_000_000n }],
|
|
504
|
+
* target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
|
|
505
|
+
* takeableOffers: quote.data.takeableOffers,
|
|
506
|
+
* deadline: Time.timestamp() + 600n,
|
|
507
|
+
* });
|
|
508
|
+
* ```
|
|
509
|
+
*/
|
|
510
|
+
supplyCollateralTakeBorrow(params) {
|
|
511
|
+
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
512
|
+
validateTakeDeadlineWindow(params.deadline);
|
|
513
|
+
const market = params.marketData.params;
|
|
514
|
+
const tx = (0, index_js_1.midnightSupplyCollateralTakeBorrow)({
|
|
515
|
+
chainId: this.chainId,
|
|
516
|
+
market,
|
|
517
|
+
collateralSupplies: params.collateralSupplies,
|
|
518
|
+
nativeAmount: params.nativeAmount,
|
|
519
|
+
target: params.target,
|
|
520
|
+
receiver: params.receiver ?? params.accountAddress,
|
|
521
|
+
takeableOffers: params.takeableOffers,
|
|
522
|
+
deadline: params.deadline,
|
|
523
|
+
referralFeePct: params.referralFeePct,
|
|
524
|
+
referralFeeRecipient: params.referralFeeRecipient,
|
|
525
|
+
metadata: this.client.options.metadata,
|
|
526
|
+
});
|
|
527
|
+
// Sum per token so a token supplied at several indices gets one approval.
|
|
528
|
+
const collateralAmounts = new Map();
|
|
529
|
+
for (const { collateralIndex, assets } of tx.action.args
|
|
530
|
+
.collateralSupplies) {
|
|
531
|
+
const { token } = midnight_sdk_1.MarketUtils.getCollateralByIndex(market, collateralIndex);
|
|
532
|
+
collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
|
|
533
|
+
}
|
|
534
|
+
return {
|
|
535
|
+
getRequirements: async (requirementsParams) => {
|
|
536
|
+
const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => (0, index_js_2.getMidnightApprovalRequirements)({
|
|
342
537
|
viemClient: this.client.viemClient,
|
|
343
538
|
chainId: this.chainId,
|
|
539
|
+
token,
|
|
344
540
|
owner: params.accountAddress,
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
541
|
+
spender: tx.to,
|
|
542
|
+
amount,
|
|
543
|
+
approvalAmount: requirementsParams?.approvalAmount,
|
|
544
|
+
})));
|
|
545
|
+
const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
|
|
546
|
+
return [...approvals.flat(), ...authorization];
|
|
350
547
|
},
|
|
351
|
-
buildTx: () =>
|
|
352
|
-
chainId: this.chainId,
|
|
353
|
-
market: market.params,
|
|
354
|
-
loanAssets: params.loanAssets,
|
|
355
|
-
maxUnits: params.maxUnits,
|
|
356
|
-
taker: params.accountAddress,
|
|
357
|
-
takeableOffers: params.takeableOffers,
|
|
358
|
-
deadline: params.deadline,
|
|
359
|
-
metadata: this.client.options.metadata,
|
|
360
|
-
}),
|
|
548
|
+
buildTx: () => tx,
|
|
361
549
|
};
|
|
362
550
|
}
|
|
363
551
|
/**
|
|
364
|
-
* Prepares
|
|
552
|
+
* Prepares a `MidnightBundlesV2` reduce-only buy that repays `accountAddress`'s debt by taking
|
|
553
|
+
* borrow-side offers, optionally repays the remainder directly, then withdraws collateral.
|
|
554
|
+
*
|
|
555
|
+
* `reduceOnly` is always set, so the buy never opens a lender position.
|
|
365
556
|
*
|
|
366
|
-
* @param params - Borrower, market snapshot,
|
|
367
|
-
* @param params.accountAddress - Borrower
|
|
557
|
+
* @param params - Borrower, market snapshot, buy target, offers, repay fallback, withdrawals, fee cap, deadline and optional referral fee.
|
|
558
|
+
* @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
|
|
368
559
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
369
|
-
* @param params.
|
|
370
|
-
* @param params.
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
*
|
|
560
|
+
* @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
|
+
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
562
|
+
* chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
|
|
563
|
+
* the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
|
|
564
|
+
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
565
|
+
* required for the full pulled amount.
|
|
566
|
+
* @param params.takeableOffers - Borrow-side offers returned by the Midnight API.
|
|
567
|
+
* @param params.repayEnabled - Whether the unfilled remainder is repaid directly to Midnight.
|
|
568
|
+
* @param params.collateralWithdrawals - Optional collateral withdrawals; `maxUint256` assets withdraws the whole balance.
|
|
569
|
+
* @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`.
|
|
570
|
+
* @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
|
|
571
|
+
* onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
|
|
572
|
+
* is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
|
|
374
573
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
375
|
-
* @
|
|
574
|
+
* @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
|
|
575
|
+
* @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
|
|
576
|
+
* @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
|
|
577
|
+
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
376
578
|
* @throws {ChainIdMismatchError} when client or market data targets another chain.
|
|
579
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
377
580
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
378
|
-
* @throws {NonPositiveInputError} when
|
|
379
|
-
*
|
|
380
|
-
* @throws {
|
|
581
|
+
* @throws {NonPositiveInputError} when the target amount, `minUnits`, `maxBuyerAssets` or a
|
|
582
|
+
* withdrawal amount is not positive.
|
|
583
|
+
* @throws {NegativeInputError} when `maxContinuousFee`, `referralFeePct` or `nativeAmount` is negative.
|
|
584
|
+
* @throws {InputExceedsMaxError} when `target.assets` or `target.maxBuyerAssets` is at
|
|
585
|
+
* least `maxUint256`, or a `collateralWithdrawals[].assets` amount, `target.units`,
|
|
586
|
+
* `minUnits`, `maxBuyerAssets` or `maxContinuousFee` exceeds `uint256`, or
|
|
587
|
+
* `nativeAmount` exceeds the maximum wNative amount this call can pull, including zero for a
|
|
588
|
+
* withdraw-only call.
|
|
589
|
+
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
590
|
+
* @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
|
|
591
|
+
* @throws {UnknownCollateralIndexError} when a withdrawal targets a collateral index not configured on the market.
|
|
381
592
|
* @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
|
|
382
593
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
383
594
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
|
|
595
|
+
* @throws {ExpiredDeadlineError} when `deadline` has expired.
|
|
596
|
+
* @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
|
|
597
|
+
* @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
|
|
598
|
+
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
599
|
+
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
|
|
384
600
|
* @example
|
|
385
601
|
* ```ts
|
|
386
|
-
* const output = midnight.
|
|
602
|
+
* const output = midnight.takeRepayWithdrawCollateral({
|
|
387
603
|
* accountAddress: borrower,
|
|
388
604
|
* marketData,
|
|
389
|
-
*
|
|
390
|
-
* loanAssets: 1_000_000n,
|
|
391
|
-
* maxUnits: 1_100_000n,
|
|
605
|
+
* target: { type: "units", units: 1_000_000n, maxBuyerAssets: 990_000n },
|
|
392
606
|
* takeableOffers: quote.data.takeableOffers,
|
|
393
|
-
*
|
|
607
|
+
* repayEnabled: true,
|
|
608
|
+
* collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
|
|
609
|
+
* maxContinuousFee: maxUint256,
|
|
610
|
+
* deadline: Time.timestamp() + 600n,
|
|
394
611
|
* });
|
|
395
612
|
* ```
|
|
396
613
|
*/
|
|
397
|
-
|
|
614
|
+
takeRepayWithdrawCollateral(params) {
|
|
398
615
|
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
market: params.marketData.params,
|
|
616
|
+
validateTakeDeadlineWindow(params.deadline);
|
|
617
|
+
const market = params.marketData.params;
|
|
618
|
+
const tx = (0, index_js_1.midnightTakeRepayWithdrawCollateral)({
|
|
619
|
+
chainId: this.chainId,
|
|
620
|
+
market,
|
|
621
|
+
target: params.target,
|
|
622
|
+
nativeAmount: params.nativeAmount,
|
|
407
623
|
takeableOffers: params.takeableOffers,
|
|
408
|
-
|
|
624
|
+
repayEnabled: params.repayEnabled,
|
|
625
|
+
collateralWithdrawals: params.collateralWithdrawals ?? [],
|
|
626
|
+
collateralReceiver: params.collateralReceiver ?? params.accountAddress,
|
|
627
|
+
maxContinuousFee: params.maxContinuousFee,
|
|
628
|
+
deadline: params.deadline,
|
|
629
|
+
referralFeePct: params.referralFeePct,
|
|
630
|
+
referralFeeRecipient: params.referralFeeRecipient,
|
|
631
|
+
metadata: this.client.options.metadata,
|
|
409
632
|
});
|
|
410
|
-
const
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
const collateral = market.getCollateralByIndex(collateralIndex);
|
|
633
|
+
const pulledAssets = params.target.type === "assets"
|
|
634
|
+
? params.target.assets
|
|
635
|
+
: params.target.maxBuyerAssets;
|
|
414
636
|
return {
|
|
415
|
-
getRequirements: async () => {
|
|
416
|
-
const
|
|
417
|
-
...(await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
418
|
-
viemClient: this.client.viemClient,
|
|
419
|
-
chainId: this.chainId,
|
|
420
|
-
token: collateral.token,
|
|
421
|
-
owner: params.accountAddress,
|
|
422
|
-
spender: midnightBundles,
|
|
423
|
-
amount: params.collateralAssets,
|
|
424
|
-
})),
|
|
425
|
-
];
|
|
426
|
-
const authorization = await (0, index_js_2.getMidnightAuthorizationRequirement)({
|
|
637
|
+
getRequirements: async (requirementsParams) => {
|
|
638
|
+
const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
427
639
|
viemClient: this.client.viemClient,
|
|
428
640
|
chainId: this.chainId,
|
|
641
|
+
token: market.loanToken,
|
|
429
642
|
owner: params.accountAddress,
|
|
430
|
-
|
|
643
|
+
spender: tx.to,
|
|
644
|
+
amount: pulledAssets,
|
|
645
|
+
approvalAmount: requirementsParams?.approvalAmount,
|
|
431
646
|
});
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
return requirements;
|
|
647
|
+
const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
|
|
648
|
+
return [...approvals, ...authorization];
|
|
435
649
|
},
|
|
436
|
-
buildTx: () =>
|
|
437
|
-
chainId: this.chainId,
|
|
438
|
-
market: market.params,
|
|
439
|
-
collateralAssets: params.collateralAssets,
|
|
440
|
-
loanAssets: params.loanAssets,
|
|
441
|
-
maxUnits: params.maxUnits,
|
|
442
|
-
taker: params.accountAddress,
|
|
443
|
-
collateralIndex,
|
|
444
|
-
takeableOffers: params.takeableOffers,
|
|
445
|
-
deadline: params.deadline,
|
|
446
|
-
metadata: this.client.options.metadata,
|
|
447
|
-
}),
|
|
650
|
+
buildTx: () => tx,
|
|
448
651
|
};
|
|
449
652
|
}
|
|
450
653
|
/**
|
|
@@ -462,6 +665,7 @@ class MorphoMidnight {
|
|
|
462
665
|
* @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
|
|
463
666
|
* @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
|
|
464
667
|
* @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
|
|
668
|
+
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled collateral assets.
|
|
465
669
|
* @example
|
|
466
670
|
* ```ts
|
|
467
671
|
* const output = midnight.supplyCollateral({
|
|
@@ -481,13 +685,14 @@ class MorphoMidnight {
|
|
|
481
685
|
const collateral = market.getCollateralByIndex(collateralIndex);
|
|
482
686
|
const midnight = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnight");
|
|
483
687
|
return {
|
|
484
|
-
getRequirements: async () => await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
688
|
+
getRequirements: async (requirementsParams) => await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
485
689
|
viemClient: this.client.viemClient,
|
|
486
690
|
chainId: this.chainId,
|
|
487
691
|
token: collateral.token,
|
|
488
692
|
owner: params.accountAddress,
|
|
489
693
|
spender: midnight,
|
|
490
694
|
amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
|
|
695
|
+
approvalAmount: requirementsParams?.approvalAmount,
|
|
491
696
|
}),
|
|
492
697
|
buildTx: () => (0, index_js_1.midnightSupplyCollateral)({
|
|
493
698
|
chainId: this.chainId,
|
|
@@ -500,30 +705,49 @@ class MorphoMidnight {
|
|
|
500
705
|
};
|
|
501
706
|
}
|
|
502
707
|
/**
|
|
503
|
-
*
|
|
708
|
+
* Prepares an atomic lend-offer publication or repost through `MidnightBundlesV2`.
|
|
504
709
|
*
|
|
505
|
-
*
|
|
506
|
-
*
|
|
710
|
+
* One transaction cancels `cancellations` under their consumption ceilings, activates the
|
|
711
|
+
* 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.
|
|
507
713
|
*
|
|
508
|
-
* @param params - Maker,
|
|
509
|
-
* @param params.accountAddress - Maker expected on every offer.
|
|
510
|
-
* @param params.offers -
|
|
714
|
+
* @param params - Maker, lend-side offers, loan reserve, cancellations, and deadline.
|
|
715
|
+
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
716
|
+
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
717
|
+
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
718
|
+
* @param params.deadline - Bundle execution deadline timestamp.
|
|
511
719
|
* @param params.validation - Optional Midnight mempool API request controls.
|
|
512
720
|
* @param params.loanToken - Loan token shared by every offer market.
|
|
513
|
-
* @param params.loanAssets - New loan reserve assigned to the
|
|
514
|
-
* @param params.reservedLoanAssets - Existing loan assets reserved by other open groups
|
|
515
|
-
* @returns Prepared group metadata, lazy requirements, and a synchronous
|
|
721
|
+
* @param params.loanAssets - New loan reserve assigned to the published groups.
|
|
722
|
+
* @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
|
|
723
|
+
* @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
|
|
516
724
|
* @throws {ChainIdMismatchError} when the client targets another chain.
|
|
517
|
-
* @throws {
|
|
725
|
+
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
726
|
+
* @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
|
|
727
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
|
|
518
728
|
* @throws {NonPositiveInputError} when `loanAssets` is non-positive.
|
|
519
|
-
* @throws {NegativeInputError} when `reservedLoanAssets` is negative.
|
|
729
|
+
* @throws {NegativeInputError} when `reservedLoanAssets` or a `maxConsumed` ceiling is negative.
|
|
730
|
+
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
731
|
+
* @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128` or `deadline` exceeds `uint256`.
|
|
732
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
|
|
733
|
+
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
734
|
+
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
735
|
+
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
736
|
+
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
737
|
+
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
738
|
+
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
520
739
|
* @throws {MidnightOfferSideMismatchError} when an offer is not lend-side.
|
|
521
740
|
* @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer uses another loan token.
|
|
741
|
+
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
742
|
+
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
743
|
+
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
|
|
522
744
|
* @example
|
|
523
745
|
* ```ts
|
|
524
746
|
* const output = await midnight.makeLend({
|
|
525
747
|
* accountAddress: maker,
|
|
526
|
-
* offers: [offer],
|
|
748
|
+
* offers: { type: "rateV1", entries: [{ offer, rate }] },
|
|
749
|
+
* cancellations: [{ group: previousGroup, maxConsumed: 0n }],
|
|
750
|
+
* deadline: maxUint256,
|
|
527
751
|
* loanToken,
|
|
528
752
|
* loanAssets: 1_000_000n,
|
|
529
753
|
* });
|
|
@@ -531,16 +755,66 @@ class MorphoMidnight {
|
|
|
531
755
|
*/
|
|
532
756
|
async makeLend(params) {
|
|
533
757
|
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
758
|
+
const tree = midnight_sdk_1.Tree.from(params.offers);
|
|
759
|
+
rejectReduceOnlyOffers(tree.offers);
|
|
760
|
+
return this.prepareLendOffers({ ...params, offers: tree });
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Prepares an atomic borrow-offer publication or repost through `MidnightBundlesV2`.
|
|
764
|
+
*
|
|
765
|
+
* One transaction cancels `cancellations` under their consumption ceilings, activates the
|
|
766
|
+
* 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.
|
|
768
|
+
*
|
|
769
|
+
* @param params - Maker, borrow-side offers, cancellations, and deadline.
|
|
770
|
+
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
771
|
+
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
772
|
+
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
773
|
+
* @param params.deadline - Bundle execution deadline timestamp.
|
|
774
|
+
* @param params.validation - Optional Midnight mempool API request controls.
|
|
775
|
+
* @returns Prepared group metadata, lazy authorization requirements, and a synchronous transaction builder.
|
|
776
|
+
* @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
|
|
777
|
+
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
778
|
+
* @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
|
|
779
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
|
|
780
|
+
* @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
|
|
781
|
+
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
782
|
+
* @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128` or `deadline` exceeds `uint256`.
|
|
783
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
|
|
784
|
+
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
785
|
+
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
786
|
+
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
787
|
+
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
788
|
+
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
789
|
+
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
790
|
+
* @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
|
|
791
|
+
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
792
|
+
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
793
|
+
* @example
|
|
794
|
+
* ```ts
|
|
795
|
+
* const output = await midnight.makeBorrow({
|
|
796
|
+
* accountAddress: maker,
|
|
797
|
+
* offers: { type: "rateV1", entries: [{ offer, rate }] },
|
|
798
|
+
* deadline: maxUint256,
|
|
799
|
+
* });
|
|
800
|
+
* ```
|
|
801
|
+
*/
|
|
802
|
+
async makeBorrow(params) {
|
|
803
|
+
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
804
|
+
const tree = midnight_sdk_1.Tree.from(params.offers);
|
|
805
|
+
rejectReduceOnlyOffers(tree.offers);
|
|
806
|
+
return this.prepareBorrowOffers({ ...params, offers: tree });
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Prepares lend-side offers for publication.
|
|
810
|
+
*/
|
|
811
|
+
async prepareLendOffers(params) {
|
|
534
812
|
assertPositiveAmount("loanAssets", params.loanAssets);
|
|
535
813
|
assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
|
|
536
|
-
const data = await this.getOffersData(
|
|
537
|
-
accountAddress: params.accountAddress,
|
|
538
|
-
offers: params.offers,
|
|
539
|
-
validation: params.validation,
|
|
540
|
-
});
|
|
814
|
+
const data = await this.getOffersData(params);
|
|
541
815
|
(0, validateOfferSides_js_1.validateOfferSides)(data.tree.offers, true);
|
|
542
816
|
data.tree.offers.forEach((offer, index) => {
|
|
543
|
-
const market =
|
|
817
|
+
const market = offerMarketParams(offer);
|
|
544
818
|
if (!(0, viem_1.isAddressEqual)(market.loanToken, params.loanToken)) {
|
|
545
819
|
throw new index_js_4.MidnightOfferMarketLoanTokenMismatchError({
|
|
546
820
|
index,
|
|
@@ -549,120 +823,422 @@ class MorphoMidnight {
|
|
|
549
823
|
});
|
|
550
824
|
}
|
|
551
825
|
});
|
|
826
|
+
const tx = (0, index_js_1.midnightCancelAndMake)({
|
|
827
|
+
chainId: this.chainId,
|
|
828
|
+
cancellations: params.cancellations ?? [],
|
|
829
|
+
deadline: params.deadline,
|
|
830
|
+
metadata: this.client.options.metadata,
|
|
831
|
+
publication: {
|
|
832
|
+
ratifier: data.ratifier,
|
|
833
|
+
root: data.tree.root,
|
|
834
|
+
groups: data.groups,
|
|
835
|
+
payload: data.payload,
|
|
836
|
+
},
|
|
837
|
+
});
|
|
552
838
|
const midnight = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnight");
|
|
553
839
|
return {
|
|
554
840
|
groups: data.groups,
|
|
555
841
|
root: data.tree.root,
|
|
556
842
|
ratifierType: data.ratifierType,
|
|
557
|
-
getRequirements: async () => {
|
|
558
|
-
const
|
|
559
|
-
requirements.push(...(await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
843
|
+
getRequirements: async (requirementsParams) => {
|
|
844
|
+
const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
560
845
|
viemClient: this.client.viemClient,
|
|
561
846
|
chainId: this.chainId,
|
|
562
847
|
token: params.loanToken,
|
|
563
848
|
owner: data.accountAddress,
|
|
564
849
|
spender: midnight,
|
|
565
850
|
amount: params.loanAssets + (params.reservedLoanAssets ?? 0n),
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
return requirements;
|
|
851
|
+
approvalAmount: requirementsParams?.approvalAmount,
|
|
852
|
+
});
|
|
853
|
+
const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
|
|
854
|
+
return [...approvals, ...authorization];
|
|
571
855
|
},
|
|
572
|
-
buildTx: (
|
|
573
|
-
offersData: data,
|
|
574
|
-
signatures,
|
|
575
|
-
}),
|
|
856
|
+
buildTx: () => tx,
|
|
576
857
|
};
|
|
577
858
|
}
|
|
578
859
|
/**
|
|
579
|
-
*
|
|
860
|
+
* Prepares an atomic Blue-funded lend-offer publication or repost through `MidnightBundlesV2`.
|
|
580
861
|
*
|
|
581
|
-
*
|
|
582
|
-
*
|
|
583
|
-
*
|
|
862
|
+
* One transaction cancels `cancellations` under their consumption ceilings, pulls `assetsToPark`
|
|
863
|
+
* from the maker and supplies them to `blueMarket` on Morpho Blue for the maker's
|
|
864
|
+
* `BlueBuyCallback` (created if missing), activates the PriceRatifierV1 or RateRatifierV1 root,
|
|
865
|
+
* and publishes its payload. When an offer is taken, the callback withdraws the bought assets
|
|
866
|
+
* from Blue and pays Midnight, so the maker needs no loan-token approval to Midnight.
|
|
867
|
+
*
|
|
868
|
+
* Every offer must set `callback` to the maker's derived `BlueBuyCallback` and `callbackData`
|
|
869
|
+
* to `abi.encode(blueMarket)`. The contract does not check supply share-price slippage, so
|
|
870
|
+
* `blueMarket` must be protected against supply-share-price inflation; this method rejects
|
|
871
|
+
* 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. Computes the callback's CREATE2 address from the chain's
|
|
873
|
+
* `midnightBlueBuyCallbackFactory`, `accountAddress` and `callbackSalt`, and fetches the Morpho Blue market,
|
|
874
|
+
* accruing interest to the current time before previewing parked shares (markets whose
|
|
875
|
+
* IRM the SDK cannot accrue are previewed on their last-updated state).
|
|
876
|
+
*
|
|
877
|
+
* @param params - Maker, lend-side offers, Blue market, parked assets, cancellations, and deadline.
|
|
878
|
+
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
879
|
+
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
880
|
+
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
881
|
+
* @param params.deadline - Bundle execution deadline timestamp.
|
|
584
882
|
* @param params.validation - Optional Midnight mempool API request controls.
|
|
585
|
-
* @
|
|
883
|
+
* @param params.blueMarket - Morpho Blue market the parked assets are supplied to.
|
|
884
|
+
* @param params.assetsToPark - Loan assets supplied to `blueMarket` for the maker's callback.
|
|
885
|
+
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
886
|
+
* chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
|
|
887
|
+
* the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
|
|
888
|
+
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
889
|
+
* required for the full pulled amount.
|
|
890
|
+
* @param params.callbackSalt - Salt selecting the maker's callback; the same salt reuses the same callback.
|
|
891
|
+
* @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
|
|
586
892
|
* @throws {ChainIdMismatchError} when the client targets another chain.
|
|
893
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2`, `midnightBlueBuyCallbackFactory`, `midnight`, `blue` or V1 ratifier deployment.
|
|
894
|
+
* @throws {NonPositiveInputError} when `assetsToPark` is non-positive.
|
|
895
|
+
* @throws {NegativeInputError} when a `maxConsumed` ceiling or `nativeAmount` is negative.
|
|
896
|
+
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
897
|
+
* @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128`, `deadline` exceeds
|
|
898
|
+
* `uint256`, or `nativeAmount` exceeds `assetsToPark` when `blueMarket.loanToken` is wNative.
|
|
899
|
+
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
900
|
+
* @throws {NativeAmountOnNonWNativeAssetError} when `blueMarket.loanToken` is not wNative.
|
|
901
|
+
* @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.
|
|
903
|
+
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
587
904
|
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
588
|
-
* @throws {
|
|
905
|
+
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
906
|
+
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
907
|
+
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
908
|
+
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
909
|
+
* @throws {MidnightOfferSideMismatchError} when an offer is not lend-side.
|
|
910
|
+
* @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
|
|
911
|
+
* @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer's loan token differs from `blueMarket`'s.
|
|
912
|
+
* @throws {MidnightOfferCallbackMismatchError} when an offer does not use the maker's derived callback.
|
|
913
|
+
* @throws {MidnightOfferCallbackDataMismatchError} when an offer's callback data is not `abi.encode(blueMarket)`.
|
|
914
|
+
* @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
|
|
915
|
+
* @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price.
|
|
916
|
+
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
917
|
+
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
918
|
+
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `assetsToPark`.
|
|
589
919
|
* @example
|
|
590
920
|
* ```ts
|
|
591
|
-
* const
|
|
921
|
+
* const callback = getMidnightBlueBuyCallbackAddress({ chainId, owner: maker, salt: callbackSalt });
|
|
922
|
+
* const callbackData = getMidnightBlueBuyCallbackData(blueMarket);
|
|
923
|
+
* const output = await midnight.supplyBlueMakeLend({
|
|
592
924
|
* accountAddress: maker,
|
|
593
|
-
* offers:
|
|
925
|
+
* offers: {
|
|
926
|
+
* type: "rateV1",
|
|
927
|
+
* entries: [{ offer: { ...offer, callback, callbackData }, rate }],
|
|
928
|
+
* },
|
|
929
|
+
* deadline: maxUint256,
|
|
930
|
+
* blueMarket,
|
|
931
|
+
* assetsToPark: 1_000_000n,
|
|
932
|
+
* callbackSalt,
|
|
594
933
|
* });
|
|
595
934
|
* ```
|
|
596
935
|
*/
|
|
597
|
-
async
|
|
936
|
+
async supplyBlueMakeLend(params) {
|
|
598
937
|
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
938
|
+
assertPositiveAmount("assetsToPark", params.assetsToPark);
|
|
939
|
+
const { callbackSalt } = params;
|
|
940
|
+
const blueMarketId = blue_sdk_1.MarketUtils.getMarketId(params.blueMarket);
|
|
941
|
+
const callback = (0, callback_js_1.getMidnightBlueBuyCallbackAddress)({
|
|
942
|
+
chainId: this.chainId,
|
|
943
|
+
owner: params.accountAddress,
|
|
944
|
+
salt: callbackSalt,
|
|
945
|
+
});
|
|
946
|
+
const [data, fetched] = await Promise.all([
|
|
947
|
+
this.getOffersData(params),
|
|
948
|
+
(0, blue_sdk_viem_1.fetchMarket)(blueMarketId, this.client.viemClient, {
|
|
949
|
+
deployless: this.client.options.supportDeployless,
|
|
950
|
+
}),
|
|
951
|
+
]);
|
|
952
|
+
const market = (0, morpho_ts_1._try)(() => fetched.accrueInterest(blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), fetched.lastUpdate)), blue_sdk_1.UnsupportedMarketIrmError) ?? fetched;
|
|
953
|
+
if (market.totalSupplyShares === 0n) {
|
|
954
|
+
throw new index_js_4.EmptyBlueParkingMarketError({ marketId: blueMarketId });
|
|
955
|
+
}
|
|
956
|
+
if (market.toSupplyShares(params.assetsToPark, "Down") === 0n) {
|
|
957
|
+
throw new index_js_4.ZeroBlueParkingSharesError({
|
|
958
|
+
marketId: blueMarketId,
|
|
959
|
+
assets: params.assetsToPark,
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
(0, validateOfferSides_js_1.validateOfferSides)(data.tree.offers, true);
|
|
963
|
+
rejectReduceOnlyOffers(data.tree.offers);
|
|
964
|
+
const callbackData = (0, callback_js_1.getMidnightBlueBuyCallbackData)(params.blueMarket);
|
|
965
|
+
data.tree.offers.forEach((offer, index) => {
|
|
966
|
+
const offerMarket = offerMarketParams(offer);
|
|
967
|
+
if (!(0, viem_1.isAddressEqual)(offerMarket.loanToken, params.blueMarket.loanToken)) {
|
|
968
|
+
throw new index_js_4.MidnightOfferMarketLoanTokenMismatchError({
|
|
969
|
+
index,
|
|
970
|
+
expectedLoanToken: params.blueMarket.loanToken,
|
|
971
|
+
actualLoanToken: offerMarket.loanToken,
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
if (!(0, viem_1.isAddressEqual)(offer.callback, callback)) {
|
|
975
|
+
throw new index_js_4.MidnightOfferCallbackMismatchError({
|
|
976
|
+
index,
|
|
977
|
+
expectedCallback: callback,
|
|
978
|
+
actualCallback: offer.callback,
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
if (offer.callbackData.toLowerCase() !== callbackData.toLowerCase()) {
|
|
982
|
+
throw new index_js_4.MidnightOfferCallbackDataMismatchError({
|
|
983
|
+
index,
|
|
984
|
+
expectedCallbackData: callbackData,
|
|
985
|
+
actualCallbackData: offer.callbackData,
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
});
|
|
989
|
+
const tx = (0, index_js_1.midnightCancelAndMake)({
|
|
990
|
+
chainId: this.chainId,
|
|
991
|
+
publication: {
|
|
992
|
+
ratifier: data.ratifier,
|
|
993
|
+
root: data.tree.root,
|
|
994
|
+
groups: data.groups,
|
|
995
|
+
payload: data.payload,
|
|
996
|
+
blueSupply: {
|
|
997
|
+
market: params.blueMarket,
|
|
998
|
+
assets: params.assetsToPark,
|
|
999
|
+
callbackSalt,
|
|
1000
|
+
},
|
|
1001
|
+
},
|
|
1002
|
+
nativeAmount: params.nativeAmount,
|
|
1003
|
+
cancellations: params.cancellations ?? [],
|
|
1004
|
+
deadline: params.deadline,
|
|
1005
|
+
metadata: this.client.options.metadata,
|
|
603
1006
|
});
|
|
604
|
-
(0, validateOfferSides_js_1.validateOfferSides)(data.tree.offers, false);
|
|
605
1007
|
return {
|
|
606
1008
|
groups: data.groups,
|
|
607
1009
|
root: data.tree.root,
|
|
608
1010
|
ratifierType: data.ratifierType,
|
|
609
|
-
getRequirements: async () => {
|
|
610
|
-
|
|
611
|
-
|
|
1011
|
+
getRequirements: async (requirementsParams) => {
|
|
1012
|
+
const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
1013
|
+
viemClient: this.client.viemClient,
|
|
1014
|
+
chainId: this.chainId,
|
|
1015
|
+
token: params.blueMarket.loanToken,
|
|
1016
|
+
owner: data.accountAddress,
|
|
1017
|
+
spender: (0, morpho_ts_1.getChainAddress)(this.chainId, "midnightBundlesV2"),
|
|
1018
|
+
amount: params.assetsToPark,
|
|
1019
|
+
approvalAmount: requirementsParams?.approvalAmount,
|
|
612
1020
|
});
|
|
1021
|
+
const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
|
|
1022
|
+
return [...approvals, ...authorization];
|
|
613
1023
|
},
|
|
614
|
-
buildTx: (
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
1024
|
+
buildTx: () => tx,
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Prepares borrow-side offers for publication.
|
|
1029
|
+
*/
|
|
1030
|
+
async prepareBorrowOffers(params) {
|
|
1031
|
+
const data = await this.getOffersData(params);
|
|
1032
|
+
(0, validateOfferSides_js_1.validateOfferSides)(data.tree.offers, false);
|
|
1033
|
+
const tx = (0, index_js_1.midnightCancelAndMake)({
|
|
1034
|
+
chainId: this.chainId,
|
|
1035
|
+
cancellations: params.cancellations ?? [],
|
|
1036
|
+
deadline: params.deadline,
|
|
1037
|
+
metadata: this.client.options.metadata,
|
|
1038
|
+
publication: {
|
|
1039
|
+
ratifier: data.ratifier,
|
|
1040
|
+
root: data.tree.root,
|
|
1041
|
+
groups: data.groups,
|
|
1042
|
+
payload: data.payload,
|
|
1043
|
+
},
|
|
1044
|
+
});
|
|
1045
|
+
return {
|
|
1046
|
+
groups: data.groups,
|
|
1047
|
+
root: data.tree.root,
|
|
1048
|
+
ratifierType: data.ratifierType,
|
|
1049
|
+
getRequirements: async () => this.getBundlesV2AuthorizationRequirements(data.accountAddress),
|
|
1050
|
+
buildTx: () => tx,
|
|
618
1051
|
};
|
|
619
1052
|
}
|
|
620
1053
|
/**
|
|
621
|
-
*
|
|
1054
|
+
* Publishes reduce-only sell offers for a lend limit exit through MidnightBundlesV2.
|
|
622
1055
|
*
|
|
623
|
-
*
|
|
624
|
-
*
|
|
625
|
-
*
|
|
1056
|
+
* Shares the borrow-side publication and requirement handling of {@link MorphoMidnight.makeBorrow}.
|
|
1057
|
+
* No tokens are pulled during publication and no token approval is required.
|
|
1058
|
+
* Execution waits for a taker; publication does not close the position or withdraw collateral.
|
|
1059
|
+
* Every offer must already have `buy = false` and `reduceOnly = true`.
|
|
1060
|
+
* The supplied tree, group caps and prices are preserved; no separate root signature is needed.
|
|
1061
|
+
*
|
|
1062
|
+
* @param params - Maker, reduce-only offers, optional cancellations, and deadline.
|
|
1063
|
+
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
1064
|
+
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
1065
|
+
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
1066
|
+
* @param params.deadline - Bundle execution deadline timestamp.
|
|
626
1067
|
* @param params.validation - Optional Midnight mempool API request controls.
|
|
627
|
-
* @
|
|
628
|
-
* @
|
|
629
|
-
* @
|
|
630
|
-
* @
|
|
631
|
-
* @
|
|
1068
|
+
* @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
|
|
1069
|
+
* @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
|
|
1070
|
+
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
1071
|
+
* @throws {MidnightOfferSideMismatchError} when an offer is not a sell offer (`buy = false`).
|
|
1072
|
+
* @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
|
|
1073
|
+
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
1074
|
+
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
1075
|
+
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
1076
|
+
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
1077
|
+
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
1078
|
+
* @throws {UnknownAddressError} when the chain has no V1 ratifier or `midnightBundlesV2` deployment.
|
|
1079
|
+
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
1080
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
|
|
1081
|
+
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
1082
|
+
* @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
|
|
1083
|
+
* @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
|
|
1084
|
+
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
1085
|
+
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
1086
|
+
* @example
|
|
1087
|
+
* ```ts
|
|
1088
|
+
* const output = await midnight.makeWithdraw({
|
|
1089
|
+
* accountAddress: maker,
|
|
1090
|
+
* offers: { type: "priceV1", entries: [{ offer: reduceOnlySellOffer }] },
|
|
1091
|
+
* deadline: maxUint256,
|
|
1092
|
+
* });
|
|
1093
|
+
* const requirements = await output.getRequirements();
|
|
1094
|
+
* const tx = output.buildTx();
|
|
1095
|
+
* ```
|
|
1096
|
+
*/
|
|
1097
|
+
async makeWithdraw(params) {
|
|
1098
|
+
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
1099
|
+
const tree = midnight_sdk_1.Tree.from(params.offers);
|
|
1100
|
+
// Reject the wrong exit intent before calling the mempool validation API.
|
|
1101
|
+
(0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
|
|
1102
|
+
for (const [index, offer] of tree.offers.entries()) {
|
|
1103
|
+
if (!offer.reduceOnly)
|
|
1104
|
+
throw new index_js_4.MidnightOfferNotReduceOnlyError({ index });
|
|
1105
|
+
}
|
|
1106
|
+
return this.prepareBorrowOffers({ ...params, offers: tree });
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* Publishes reduce-only buy offers for a borrow limit exit through MidnightBundlesV2.
|
|
1110
|
+
*
|
|
1111
|
+
* Shares the lend-side publication and requirement handling of {@link MorphoMidnight.makeLend}.
|
|
1112
|
+
* Loan assets are pulled by Midnight when the offers fill, not during publication.
|
|
1113
|
+
* The loan reserve uses the same approval sizing as `makeLend`.
|
|
1114
|
+
* Execution waits for a taker; publication does not close the position or withdraw collateral.
|
|
1115
|
+
* Every offer must already have `buy = true` and `reduceOnly = true`.
|
|
1116
|
+
* The supplied tree, group caps and prices are preserved; no separate root signature is needed.
|
|
1117
|
+
*
|
|
1118
|
+
* @param params - Maker, reduce-only offers, optional cancellations, loan reserve, and deadline.
|
|
1119
|
+
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
1120
|
+
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
1121
|
+
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
1122
|
+
* @param params.deadline - Bundle execution deadline timestamp.
|
|
1123
|
+
* @param params.validation - Optional Midnight mempool API request controls.
|
|
1124
|
+
* @param params.loanToken - Loan token shared by every offer market.
|
|
1125
|
+
* @param params.loanAssets - New loan reserve assigned to the published groups.
|
|
1126
|
+
* @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
|
|
1127
|
+
* @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
|
|
632
1128
|
* @throws {ChainIdMismatchError} when the client targets another chain.
|
|
633
|
-
* @throws {
|
|
634
|
-
* @throws {
|
|
635
|
-
* @throws {
|
|
636
|
-
* @throws {
|
|
1129
|
+
* @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
|
|
1130
|
+
* @throws {MidnightOfferSideMismatchError} when an offer is not a buy offer (`buy = true`).
|
|
1131
|
+
* @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
|
|
1132
|
+
* @throws {NonPositiveInputError} when `loanAssets` or `deadline` is not positive.
|
|
1133
|
+
* @throws {NegativeInputError} when `reservedLoanAssets` or a `maxConsumed` ceiling is negative.
|
|
1134
|
+
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
1135
|
+
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
1136
|
+
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
1137
|
+
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
1138
|
+
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
1139
|
+
* @throws {UnknownAddressError} when the chain has no V1 ratifier or `midnightBundlesV2` deployment.
|
|
1140
|
+
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
1141
|
+
* @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
|
|
1142
|
+
* @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer uses another loan token.
|
|
1143
|
+
* @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
|
|
1144
|
+
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
1145
|
+
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
1146
|
+
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
|
|
1147
|
+
* @example
|
|
1148
|
+
* ```ts
|
|
1149
|
+
* const output = await midnight.makeRepay({
|
|
1150
|
+
* accountAddress: maker,
|
|
1151
|
+
* offers: { type: "priceV1", entries: [{ offer: reduceOnlyBuyOffer }] },
|
|
1152
|
+
* loanToken,
|
|
1153
|
+
* loanAssets: 1_000_000n,
|
|
1154
|
+
* deadline: maxUint256,
|
|
1155
|
+
* });
|
|
1156
|
+
* const requirements = await output.getRequirements();
|
|
1157
|
+
* const tx = output.buildTx();
|
|
1158
|
+
* ```
|
|
1159
|
+
*/
|
|
1160
|
+
async makeRepay(params) {
|
|
1161
|
+
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
1162
|
+
const tree = midnight_sdk_1.Tree.from(params.offers);
|
|
1163
|
+
// Reject the wrong exit intent before calling the mempool validation API.
|
|
1164
|
+
(0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
|
|
1165
|
+
for (const [index, offer] of tree.offers.entries()) {
|
|
1166
|
+
if (!offer.reduceOnly)
|
|
1167
|
+
throw new index_js_4.MidnightOfferNotReduceOnlyError({ index });
|
|
1168
|
+
}
|
|
1169
|
+
return this.prepareLendOffers({ ...params, offers: tree });
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* Prepares an atomic borrow-offer publication or repost through `MidnightBundlesV2`,
|
|
1173
|
+
* requiring collateral before activation.
|
|
1174
|
+
*
|
|
1175
|
+
* One transaction cancels `cancellations` under their consumption ceilings, pulls and supplies
|
|
1176
|
+
* required `collateral`, activates the PriceRatifierV1 or RateRatifierV1 root, and publishes its
|
|
1177
|
+
* payload. Pass no cancellations for a new publication. Calls the Midnight mempool validation
|
|
1178
|
+
* API while preparing the tree.
|
|
1179
|
+
*
|
|
1180
|
+
* @param params - Maker, borrow-side offers, required collateral, cancellations, and deadline.
|
|
1181
|
+
* @param params.accountAddress - Maker expected on every offer; must send the transaction.
|
|
1182
|
+
* @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
|
|
1183
|
+
* @param params.cancellations - Previous groups to cancel with their consumption ceilings.
|
|
1184
|
+
* @param params.deadline - Bundle execution deadline timestamp.
|
|
1185
|
+
* @param params.validation - Optional Midnight mempool API request controls.
|
|
1186
|
+
* @param params.collateral - Required market and collateral supplies; every offer must target that market.
|
|
1187
|
+
* @param params.collateral.market - Midnight market receiving the collateral; every offer must target it.
|
|
1188
|
+
* @param params.collateral.supplies - Collateral index and assets per supply; must not be empty.
|
|
1189
|
+
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
1190
|
+
* chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
|
|
1191
|
+
* the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
|
|
1192
|
+
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
1193
|
+
* required for the full pulled amount.
|
|
1194
|
+
* @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
|
|
1195
|
+
* @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
|
|
1196
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
|
|
1197
|
+
* @throws {UnknownCollateralIndexError} when a collateral index is not configured.
|
|
1198
|
+
* @throws {NonPositiveInputError} when a collateral supply amount is non-positive.
|
|
1199
|
+
* @throws {NegativeInputError} when a `maxConsumed` ceiling or `nativeAmount` is negative.
|
|
1200
|
+
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
1201
|
+
* @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128`, `deadline` or a
|
|
1202
|
+
* collateral supply amount exceeds `uint256`, or `nativeAmount` exceeds the maximum wNative
|
|
1203
|
+
* collateral amount this call can pull.
|
|
1204
|
+
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
1205
|
+
* @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
|
|
1206
|
+
* @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.
|
|
1208
|
+
* @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
|
|
1209
|
+
* @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
|
|
1210
|
+
* @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
|
|
1211
|
+
* @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
|
|
1212
|
+
* @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
|
|
1213
|
+
* @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
|
|
637
1214
|
* @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
|
|
638
|
-
* @throws {
|
|
1215
|
+
* @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
|
|
1216
|
+
* @throws {MarketIdMismatchError} when an offer targets another market than `collateral.market`, including a `collateral.market` on another chain or Midnight deployment.
|
|
1217
|
+
* @throws {EmptyMidnightCollateralSuppliesError} when a collateral market has no collateral supplies.
|
|
1218
|
+
* @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
|
|
1219
|
+
* @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
|
|
1220
|
+
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
|
|
639
1221
|
* @example
|
|
640
1222
|
* ```ts
|
|
641
1223
|
* const output = await midnight.supplyCollateralMakeBorrow({
|
|
642
1224
|
* accountAddress: maker,
|
|
643
|
-
*
|
|
644
|
-
*
|
|
645
|
-
*
|
|
1225
|
+
* offers: { type: "rateV1", entries: [{ offer, rate }] },
|
|
1226
|
+
* collateral: {
|
|
1227
|
+
* market: marketData.params,
|
|
1228
|
+
* supplies: [{ collateralIndex: 0n, assets: 2_000_000n }],
|
|
1229
|
+
* },
|
|
1230
|
+
* deadline: maxUint256,
|
|
646
1231
|
* });
|
|
647
1232
|
* ```
|
|
648
1233
|
*/
|
|
649
1234
|
async supplyCollateralMakeBorrow(params) {
|
|
650
1235
|
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
: midnight_sdk_1.MarketParams.from(params.market);
|
|
656
|
-
// Reject markets from another chain deployment before preparing requirements.
|
|
657
|
-
(0, validateMidnightMarket_js_1.validateMidnightMarket)({ market, chainId: this.chainId });
|
|
658
|
-
const collateralIndex = params.collateralIndex ?? 0n;
|
|
659
|
-
const collateral = midnight_sdk_1.MarketUtils.getCollateralByIndex(market, collateralIndex);
|
|
660
|
-
const data = await this.getOffersData({
|
|
661
|
-
accountAddress: params.accountAddress,
|
|
662
|
-
offers: params.offers,
|
|
663
|
-
validation: params.validation,
|
|
664
|
-
});
|
|
1236
|
+
const market = params.collateral.market instanceof midnight_sdk_1.MarketParams
|
|
1237
|
+
? params.collateral.market
|
|
1238
|
+
: midnight_sdk_1.MarketParams.from(params.collateral.market);
|
|
1239
|
+
const data = await this.getOffersData(params);
|
|
665
1240
|
(0, validateOfferSides_js_1.validateOfferSides)(data.tree.offers, false);
|
|
1241
|
+
rejectReduceOnlyOffers(data.tree.offers);
|
|
666
1242
|
const marketId = midnight_sdk_1.MarketUtils.toId(market);
|
|
667
1243
|
for (const offer of data.tree.offers) {
|
|
668
1244
|
const offerMarketId = midnight_sdk_1.MarketUtils.toId(offer.market);
|
|
@@ -670,39 +1246,50 @@ class MorphoMidnight {
|
|
|
670
1246
|
throw new index_js_4.MarketIdMismatchError(offerMarketId, marketId);
|
|
671
1247
|
}
|
|
672
1248
|
}
|
|
673
|
-
const
|
|
1249
|
+
const tx = (0, index_js_1.midnightCancelAndMake)({
|
|
1250
|
+
chainId: this.chainId,
|
|
1251
|
+
nativeAmount: params.nativeAmount,
|
|
1252
|
+
cancellations: params.cancellations ?? [],
|
|
1253
|
+
deadline: params.deadline,
|
|
1254
|
+
metadata: this.client.options.metadata,
|
|
1255
|
+
publication: {
|
|
1256
|
+
ratifier: data.ratifier,
|
|
1257
|
+
root: data.tree.root,
|
|
1258
|
+
groups: data.groups,
|
|
1259
|
+
payload: data.payload,
|
|
1260
|
+
collateral: {
|
|
1261
|
+
market,
|
|
1262
|
+
supplies: params.collateral.supplies,
|
|
1263
|
+
},
|
|
1264
|
+
},
|
|
1265
|
+
});
|
|
1266
|
+
const midnightBundlesV2 = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnightBundlesV2");
|
|
1267
|
+
const collateralAmounts = new Map();
|
|
1268
|
+
for (const { collateralIndex, assets } of tx.action.args
|
|
1269
|
+
.collateralSupplies) {
|
|
1270
|
+
const { token } = midnight_sdk_1.MarketUtils.getCollateralByIndex(market, collateralIndex);
|
|
1271
|
+
collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
|
|
1272
|
+
}
|
|
674
1273
|
return {
|
|
675
1274
|
groups: data.groups,
|
|
676
1275
|
root: data.tree.root,
|
|
677
1276
|
ratifierType: data.ratifierType,
|
|
678
|
-
getRequirements: async () => {
|
|
679
|
-
const
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
collateralIndex,
|
|
692
|
-
assets: params.collateralAssets,
|
|
693
|
-
onBehalf: data.accountAddress,
|
|
694
|
-
metadata: this.client.options.metadata,
|
|
695
|
-
}),
|
|
696
|
-
...(await this.getRatifierRequirements({
|
|
697
|
-
offersData: data,
|
|
698
|
-
})),
|
|
1277
|
+
getRequirements: async (requirementsParams) => {
|
|
1278
|
+
const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => (0, index_js_2.getMidnightApprovalRequirements)({
|
|
1279
|
+
viemClient: this.client.viemClient,
|
|
1280
|
+
chainId: this.chainId,
|
|
1281
|
+
token,
|
|
1282
|
+
owner: data.accountAddress,
|
|
1283
|
+
spender: midnightBundlesV2,
|
|
1284
|
+
amount,
|
|
1285
|
+
approvalAmount: requirementsParams?.approvalAmount,
|
|
1286
|
+
})));
|
|
1287
|
+
return [
|
|
1288
|
+
...approvals.flat(),
|
|
1289
|
+
...(await this.getBundlesV2AuthorizationRequirements(data.accountAddress)),
|
|
699
1290
|
];
|
|
700
|
-
return requirements;
|
|
701
1291
|
},
|
|
702
|
-
buildTx: (
|
|
703
|
-
offersData: data,
|
|
704
|
-
signatures,
|
|
705
|
-
}),
|
|
1292
|
+
buildTx: () => tx,
|
|
706
1293
|
};
|
|
707
1294
|
}
|
|
708
1295
|
/**
|
|
@@ -762,7 +1349,9 @@ class MorphoMidnight {
|
|
|
762
1349
|
});
|
|
763
1350
|
}
|
|
764
1351
|
return {
|
|
765
|
-
getRequirements: async () =>
|
|
1352
|
+
getRequirements: async () => {
|
|
1353
|
+
return [];
|
|
1354
|
+
},
|
|
766
1355
|
buildTx: () => (0, index_js_1.midnightRedeem)({
|
|
767
1356
|
chainId: this.chainId,
|
|
768
1357
|
market: market.params,
|
|
@@ -774,259 +1363,142 @@ class MorphoMidnight {
|
|
|
774
1363
|
};
|
|
775
1364
|
}
|
|
776
1365
|
/**
|
|
777
|
-
* Prepares a
|
|
1366
|
+
* Prepares a direct `MidnightBundlesV2` repayment, collateral withdrawal, or both, for `accountAddress`.
|
|
778
1367
|
*
|
|
779
|
-
* @param params - Account, market snapshot, repay
|
|
780
|
-
* @param params.accountAddress - Position owner
|
|
1368
|
+
* @param params - Account, market snapshot, `repay` mode, collateral withdrawals, optional collateral receiver, and deadline.
|
|
1369
|
+
* @param params.accountAddress - Position owner and transaction sender.
|
|
781
1370
|
* @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
|
|
782
|
-
* @param params.
|
|
783
|
-
* @param params.
|
|
784
|
-
*
|
|
1371
|
+
* @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
|
+
* @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
|
|
1373
|
+
* chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
|
|
1374
|
+
* the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
|
|
1375
|
+
* stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
|
|
1376
|
+
* required for the full pulled amount.
|
|
1377
|
+
* @param params.collateralWithdrawals - Optional withdrawals; `assets: maxUint256` withdraws the full balance.
|
|
1378
|
+
* @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`.
|
|
785
1379
|
* @param params.deadline - Bundle execution deadline timestamp.
|
|
786
1380
|
* @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
|
|
787
1381
|
* @throws {ChainIdMismatchError} when client or market data targets another chain.
|
|
788
1382
|
* @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
|
|
789
|
-
* @throws {NegativeInputError} when
|
|
790
|
-
* @throws {NonPositiveInputError} when
|
|
791
|
-
* @throws {
|
|
1383
|
+
* @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, or `deadline` is not positive.
|
|
1385
|
+
* @throws {InputExceedsMaxError} when `repay.assets` or `repay.maxBuyerAssets` is at least
|
|
1386
|
+
* `maxUint256`, a withdrawal amount or `deadline` exceeds uint256, or `nativeAmount` exceeds
|
|
1387
|
+
* the maximum wNative amount this call can pull, including zero for a withdraw-only call.
|
|
1388
|
+
* @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
|
|
1389
|
+
* @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
|
|
1390
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
1391
|
+
* @throws {UnknownCollateralIndexError} when a withdrawal selects an unconfigured collateral.
|
|
1392
|
+
* @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
|
|
792
1393
|
* @example
|
|
793
1394
|
* ```ts
|
|
1395
|
+
* // Close the position: repay all debt, withdraw all collateral.
|
|
794
1396
|
* const output = midnight.repayWithdrawCollateral({
|
|
795
1397
|
* accountAddress: borrower,
|
|
796
1398
|
* marketData,
|
|
797
|
-
*
|
|
798
|
-
*
|
|
1399
|
+
* repay: { type: "full", maxBuyerAssets: 1_010_000n },
|
|
1400
|
+
* collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
|
|
799
1401
|
* deadline: maxUint256,
|
|
800
1402
|
* });
|
|
801
1403
|
* ```
|
|
802
1404
|
*/
|
|
803
1405
|
repayWithdrawCollateral(params) {
|
|
804
1406
|
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
assertNonNegativeAmount(`collateralWithdrawals[${index}].collateralIndex`, withdrawal.collateralIndex);
|
|
820
|
-
// Validate the configured collateral before exposing requirement reads.
|
|
821
|
-
market.getCollateralByIndex(withdrawal.collateralIndex);
|
|
822
|
-
}
|
|
823
|
-
if (params.repayAssets === 0n &&
|
|
824
|
-
collateralWithdrawals.every((withdrawal) => withdrawal.assets === 0n)) {
|
|
825
|
-
throw new index_js_4.NonPositiveInputError("repay or withdraw amount", 0n);
|
|
826
|
-
}
|
|
827
|
-
const midnightBundles = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnightBundles");
|
|
1407
|
+
const market = params.marketData.params;
|
|
1408
|
+
const tx = (0, index_js_1.midnightRepayWithdrawCollateral)({
|
|
1409
|
+
chainId: this.chainId,
|
|
1410
|
+
market,
|
|
1411
|
+
repay: params.repay,
|
|
1412
|
+
nativeAmount: params.nativeAmount,
|
|
1413
|
+
collateralWithdrawals: params.collateralWithdrawals ?? [],
|
|
1414
|
+
collateralReceiver: params.collateralReceiver ?? params.accountAddress,
|
|
1415
|
+
deadline: params.deadline,
|
|
1416
|
+
metadata: this.client.options.metadata,
|
|
1417
|
+
});
|
|
1418
|
+
const pulledAssets = params.repay.type === "assets"
|
|
1419
|
+
? params.repay.assets
|
|
1420
|
+
: params.repay.maxBuyerAssets;
|
|
828
1421
|
return {
|
|
829
|
-
getRequirements: async () => {
|
|
830
|
-
const
|
|
831
|
-
|
|
832
|
-
requirements.push(...(await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
1422
|
+
getRequirements: async (requirementsParams) => {
|
|
1423
|
+
const approvals = pulledAssets > 0n
|
|
1424
|
+
? await (0, index_js_2.getMidnightApprovalRequirements)({
|
|
833
1425
|
viemClient: this.client.viemClient,
|
|
834
1426
|
chainId: this.chainId,
|
|
835
|
-
token: market.
|
|
1427
|
+
token: market.loanToken,
|
|
836
1428
|
owner: params.accountAddress,
|
|
837
|
-
spender:
|
|
838
|
-
amount:
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
owner: params.accountAddress,
|
|
845
|
-
authorized: midnightBundles,
|
|
846
|
-
});
|
|
847
|
-
if (authorization)
|
|
848
|
-
requirements.push(authorization);
|
|
849
|
-
return requirements;
|
|
1429
|
+
spender: tx.to,
|
|
1430
|
+
amount: pulledAssets,
|
|
1431
|
+
approvalAmount: requirementsParams?.approvalAmount,
|
|
1432
|
+
})
|
|
1433
|
+
: [];
|
|
1434
|
+
const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
|
|
1435
|
+
return [...approvals, ...authorization];
|
|
850
1436
|
},
|
|
851
|
-
buildTx: () =>
|
|
852
|
-
chainId: this.chainId,
|
|
853
|
-
market: market.params,
|
|
854
|
-
repayAssets: params.repayAssets,
|
|
855
|
-
withdrawCollateralAssets: params.withdrawCollateralAssets,
|
|
856
|
-
onBehalf: params.accountAddress,
|
|
857
|
-
collateralIndex: params.collateralIndex,
|
|
858
|
-
deadline: params.deadline,
|
|
859
|
-
metadata: this.client.options.metadata,
|
|
860
|
-
}),
|
|
1437
|
+
buildTx: () => tx,
|
|
861
1438
|
};
|
|
862
1439
|
}
|
|
863
1440
|
/**
|
|
864
|
-
* Prepares
|
|
1441
|
+
* Prepares guarded cancellation of several maker offer groups through `MidnightBundlesV2`.
|
|
1442
|
+
*
|
|
1443
|
+
* The transaction reverts as a whole when any group's consumption exceeds its
|
|
1444
|
+
* `maxConsumed` ceiling, so fills landing before execution never leave a partial cancel.
|
|
865
1445
|
*
|
|
866
|
-
* @param params -
|
|
867
|
-
* @param params.
|
|
868
|
-
*
|
|
869
|
-
* @
|
|
1446
|
+
* @param params - Maker account, groups with consumption ceilings, and deadline.
|
|
1447
|
+
* @param params.accountAddress - Maker that must send the transaction; V2 cancels for `msg.sender`,
|
|
1448
|
+
* so sending from another account cancels that account's groups instead.
|
|
1449
|
+
* @param params.cancellations - Offer groups and the largest consumption accepted for each.
|
|
1450
|
+
* To cancel unconditionally, set `maxConsumed` to `maxUint128`; the contract treats
|
|
1451
|
+
* `type(uint128).max` as no limit.
|
|
1452
|
+
* @param params.deadline - Bundle execution deadline timestamp.
|
|
1453
|
+
* @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
|
|
870
1454
|
* @throws {ChainIdMismatchError} when the client targets another chain.
|
|
1455
|
+
* @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
|
|
1456
|
+
* @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
|
|
1457
|
+
* @throws {EmptyMidnightGroupCancellationsError} when no groups are provided.
|
|
1458
|
+
* @throws {DuplicateMidnightGroupCancellationError} when a group appears more than once.
|
|
1459
|
+
* @throws {NonPositiveInputError} when `deadline` is not positive.
|
|
1460
|
+
* @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
|
|
1461
|
+
* @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
|
|
871
1462
|
* @example
|
|
872
1463
|
* ```ts
|
|
873
|
-
*
|
|
874
|
-
*
|
|
1464
|
+
* import { morphoViemExtension } from "@morpho-org/morpho-sdk";
|
|
1465
|
+
* import { createPublicClient, http, maxUint256, type Address, type Hex } from "viem";
|
|
1466
|
+
* import { base } from "viem/chains";
|
|
1467
|
+
*
|
|
1468
|
+
* declare const maker: Address;
|
|
1469
|
+
* declare const group: Hex;
|
|
1470
|
+
* const client = createPublicClient({ chain: base, transport: http() }).extend(
|
|
1471
|
+
* morphoViemExtension(),
|
|
1472
|
+
* );
|
|
1473
|
+
* const midnight = client.morpho.midnight(base.id);
|
|
1474
|
+
* const output = midnight.cancelOffers({
|
|
875
1475
|
* accountAddress: maker,
|
|
1476
|
+
* cancellations: [{ group, maxConsumed: 0n }],
|
|
1477
|
+
* deadline: maxUint256,
|
|
876
1478
|
* });
|
|
877
1479
|
* ```
|
|
878
1480
|
*/
|
|
879
|
-
|
|
1481
|
+
cancelOffers(params) {
|
|
880
1482
|
(0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
|
|
1483
|
+
const tx = (0, index_js_1.midnightCancelAndMake)({
|
|
1484
|
+
chainId: this.chainId,
|
|
1485
|
+
cancellations: params.cancellations,
|
|
1486
|
+
deadline: params.deadline,
|
|
1487
|
+
metadata: this.client.options.metadata,
|
|
1488
|
+
});
|
|
881
1489
|
return {
|
|
882
|
-
getRequirements:
|
|
883
|
-
buildTx: () =>
|
|
884
|
-
chainId: this.chainId,
|
|
885
|
-
group: params.group,
|
|
886
|
-
onBehalf: params.accountAddress,
|
|
887
|
-
metadata: this.client.options.metadata,
|
|
888
|
-
}),
|
|
1490
|
+
getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
|
|
1491
|
+
buildTx: () => tx,
|
|
889
1492
|
};
|
|
890
1493
|
}
|
|
891
|
-
async
|
|
892
|
-
const data = params.offersData;
|
|
893
|
-
const requirements = [];
|
|
1494
|
+
async getBundlesV2AuthorizationRequirements(owner) {
|
|
894
1495
|
const authorization = await (0, index_js_2.getMidnightAuthorizationRequirement)({
|
|
895
1496
|
viemClient: this.client.viemClient,
|
|
896
1497
|
chainId: this.chainId,
|
|
897
|
-
owner
|
|
898
|
-
authorized:
|
|
899
|
-
});
|
|
900
|
-
if (authorization)
|
|
901
|
-
requirements.push(authorization);
|
|
902
|
-
if (data.ratifierType === "ecrecover") {
|
|
903
|
-
const chainId = this.chainId;
|
|
904
|
-
// The offer-tree EIP-712 payload is signed over the tree, not the signer, so it is fully
|
|
905
|
-
// determined at build time and stored on the action for external signing.
|
|
906
|
-
const treeTypedData = midnight_sdk_1.EcrecoverRatifierUtils.typedData({
|
|
907
|
-
tree: data.tree,
|
|
908
|
-
chainId,
|
|
909
|
-
});
|
|
910
|
-
const typedData = (0, morpho_ts_1.deepFreeze)({
|
|
911
|
-
domain: treeTypedData.domain,
|
|
912
|
-
types: treeTypedData.types,
|
|
913
|
-
primaryType: treeTypedData.primaryType,
|
|
914
|
-
message: treeTypedData.message,
|
|
915
|
-
});
|
|
916
|
-
const action = {
|
|
917
|
-
type: "midnightOfferRootSignature",
|
|
918
|
-
args: {
|
|
919
|
-
root: data.tree.root,
|
|
920
|
-
ratifier: data.ratifier,
|
|
921
|
-
offers: data.tree.offers.length,
|
|
922
|
-
},
|
|
923
|
-
typedData,
|
|
924
|
-
};
|
|
925
|
-
requirements.push({
|
|
926
|
-
action,
|
|
927
|
-
async sign(client, userAddress) {
|
|
928
|
-
const signature = await (0, signAndVerifyTypedData_js_1.signAndVerifyTypedData)({
|
|
929
|
-
client,
|
|
930
|
-
userAddress,
|
|
931
|
-
typedData,
|
|
932
|
-
});
|
|
933
|
-
// Derive the ratification payload `buildTx()` submits.
|
|
934
|
-
const items = await midnight_sdk_1.EcrecoverRatifierUtils.ratify({
|
|
935
|
-
tree: data.tree,
|
|
936
|
-
account: userAddress,
|
|
937
|
-
signature,
|
|
938
|
-
});
|
|
939
|
-
const payload = await midnight_sdk_1.Payload.encode(items);
|
|
940
|
-
return (0, morpho_ts_1.deepFreeze)({
|
|
941
|
-
args: {
|
|
942
|
-
owner: userAddress,
|
|
943
|
-
root: data.tree.root,
|
|
944
|
-
signature,
|
|
945
|
-
payload,
|
|
946
|
-
},
|
|
947
|
-
action,
|
|
948
|
-
});
|
|
949
|
-
},
|
|
950
|
-
});
|
|
951
|
-
return requirements;
|
|
952
|
-
}
|
|
953
|
-
const ratifyRoot = await (0, index_js_2.getSetterRatifierRatifyRootRequirement)({
|
|
954
|
-
viemClient: this.client.viemClient,
|
|
955
|
-
chainId: this.chainId,
|
|
956
|
-
maker: data.accountAddress,
|
|
957
|
-
root: data.tree.root,
|
|
958
|
-
});
|
|
959
|
-
if (ratifyRoot)
|
|
960
|
-
requirements.push(ratifyRoot);
|
|
961
|
-
return requirements;
|
|
962
|
-
}
|
|
963
|
-
buildSubmitOffersTx(params) {
|
|
964
|
-
const data = params.offersData;
|
|
965
|
-
const collectedSignatures = params.signatures == null
|
|
966
|
-
? undefined
|
|
967
|
-
: "action" in params.signatures
|
|
968
|
-
? [params.signatures]
|
|
969
|
-
: params.signatures;
|
|
970
|
-
let payload;
|
|
971
|
-
if (data.ratifierType === "ecrecover") {
|
|
972
|
-
const { midnightOfferRoot: signature } = (0, index_js_4.selectRequirementSignatures)(collectedSignatures, { midnightOfferRoot: true });
|
|
973
|
-
if (signature == null) {
|
|
974
|
-
throw new index_js_4.MissingMidnightOfferRootSignatureError();
|
|
975
|
-
}
|
|
976
|
-
if (!(0, viem_1.isAddressEqual)(signature.args.owner, data.accountAddress)) {
|
|
977
|
-
throw new index_js_4.MidnightOfferRootOwnerMismatchError({
|
|
978
|
-
expectedOwner: data.accountAddress,
|
|
979
|
-
actualOwner: signature.args.owner,
|
|
980
|
-
});
|
|
981
|
-
}
|
|
982
|
-
if (signature.args.root.toLowerCase() !== data.tree.root.toLowerCase()) {
|
|
983
|
-
throw new index_js_4.MidnightOfferRootMismatchError({
|
|
984
|
-
expectedRoot: data.tree.root,
|
|
985
|
-
actualRoot: signature.args.root,
|
|
986
|
-
});
|
|
987
|
-
}
|
|
988
|
-
if (signature.action.args.root.toLowerCase() !==
|
|
989
|
-
data.tree.root.toLowerCase()) {
|
|
990
|
-
throw new index_js_4.MidnightOfferRootMismatchError({
|
|
991
|
-
expectedRoot: data.tree.root,
|
|
992
|
-
actualRoot: signature.action.args.root,
|
|
993
|
-
});
|
|
994
|
-
}
|
|
995
|
-
if (!(0, viem_1.isAddressEqual)(signature.action.args.ratifier, data.ratifier)) {
|
|
996
|
-
throw new index_js_4.MidnightOfferRootRatifierMismatchError({
|
|
997
|
-
expectedRatifier: data.ratifier,
|
|
998
|
-
actualRatifier: signature.action.args.ratifier,
|
|
999
|
-
});
|
|
1000
|
-
}
|
|
1001
|
-
if (signature.action.args.offers !== data.tree.offers.length) {
|
|
1002
|
-
throw new index_js_4.MidnightOfferRootOfferCountMismatchError({
|
|
1003
|
-
expectedOffers: data.tree.offers.length,
|
|
1004
|
-
actualOffers: signature.action.args.offers,
|
|
1005
|
-
});
|
|
1006
|
-
}
|
|
1007
|
-
// The payload is carried on the signature the caller hands to buildTx, so
|
|
1008
|
-
// a prepared offer-root requirement can be signed on one instance and
|
|
1009
|
-
// submitted from another without sharing in-memory state.
|
|
1010
|
-
if (signature.args.payload == null) {
|
|
1011
|
-
throw new index_js_4.UnpreparedMidnightOfferRootSignatureError();
|
|
1012
|
-
}
|
|
1013
|
-
payload = signature.args.payload;
|
|
1014
|
-
}
|
|
1015
|
-
else {
|
|
1016
|
-
(0, index_js_4.selectRequirementSignatures)(collectedSignatures, {});
|
|
1017
|
-
payload = data.setterPayload;
|
|
1018
|
-
}
|
|
1019
|
-
return (0, index_js_1.mempoolSubmitOffers)({
|
|
1020
|
-
chainId: this.chainId,
|
|
1021
|
-
groups: data.groups,
|
|
1022
|
-
root: data.tree.root,
|
|
1023
|
-
maker: data.accountAddress,
|
|
1024
|
-
ratifier: data.ratifier,
|
|
1025
|
-
ratifierType: data.ratifierType,
|
|
1026
|
-
offers: data.tree.offers.length,
|
|
1027
|
-
payload,
|
|
1028
|
-
metadata: this.client.options.metadata,
|
|
1498
|
+
owner,
|
|
1499
|
+
authorized: (0, morpho_ts_1.getChainAddress)(this.chainId, "midnightBundlesV2"),
|
|
1029
1500
|
});
|
|
1501
|
+
return authorization ? [authorization] : [];
|
|
1030
1502
|
}
|
|
1031
1503
|
}
|
|
1032
1504
|
exports.MorphoMidnight = MorphoMidnight;
|