@morpho-org/morpho-sdk 10.3.0 → 10.4.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/README.md +172 -8
- package/lib/cjs/actions/midnight/redeem.d.ts +20 -3
- package/lib/cjs/actions/midnight/redeem.js +58 -1
- package/lib/cjs/actions/midnight/supplyCollateralWithNative.d.ts +24 -1
- package/lib/cjs/actions/midnight/supplyCollateralWithNative.js +41 -0
- package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +16 -2
- package/lib/cjs/actions/midnight/withdrawCollateral.js +26 -1
- package/lib/cjs/helpers/callback.d.ts +3 -2
- package/lib/cjs/helpers/callback.js +4 -20
- package/lib/cjs/helpers/computeMidnightPostWithdrawalCollateral.d.ts +17 -0
- package/lib/cjs/helpers/computeMidnightPostWithdrawalCollateral.js +30 -0
- package/lib/cjs/helpers/parseMidnightMaker.d.ts +21 -0
- package/lib/cjs/helpers/parseMidnightMaker.js +41 -1
- package/lib/cjs/helpers/validate.d.ts +49 -1
- package/lib/cjs/helpers/validate.js +87 -1
- package/lib/cjs/helpers/validateMidnightPublication.d.ts +10 -0
- package/lib/cjs/helpers/validateMidnightPublication.js +18 -1
- package/lib/cjs/helpers/validateMidnightTakeableOfferFields.d.ts +28 -0
- package/lib/cjs/helpers/validateMidnightTakeableOfferFields.js +85 -0
- package/lib/cjs/index.d.ts +2 -2
- package/lib/cjs/index.js +23 -1
- package/lib/cjs/midnight/utils.d.ts +1 -1
- package/lib/cjs/midnight/utils.js +2 -1
- package/lib/cjs/transactionPlan/blue/withdrawBuyCallback.d.ts +101 -0
- package/lib/cjs/transactionPlan/blue/withdrawBuyCallback.js +264 -0
- package/lib/cjs/transactionPlan/error.d.ts +27 -0
- package/lib/cjs/transactionPlan/error.js +30 -1
- package/lib/cjs/transactionPlan/index.d.ts +40 -1
- package/lib/cjs/transactionPlan/index.js +46 -5
- package/lib/cjs/transactionPlan/midnight/authorization.d.ts +15 -0
- package/lib/cjs/transactionPlan/midnight/authorization.js +45 -0
- package/lib/cjs/transactionPlan/midnight/cancelOffers.d.ts +80 -0
- package/lib/cjs/transactionPlan/midnight/cancelOffers.js +125 -0
- package/lib/cjs/transactionPlan/midnight/makeBorrow.d.ts +104 -0
- package/lib/cjs/transactionPlan/midnight/makeBorrow.js +126 -0
- package/lib/cjs/transactionPlan/midnight/makeLend.d.ts +140 -0
- package/lib/cjs/transactionPlan/midnight/makeLend.js +176 -0
- package/lib/cjs/transactionPlan/midnight/makeRepay.d.ts +118 -0
- package/lib/cjs/transactionPlan/midnight/makeRepay.js +118 -0
- package/lib/cjs/transactionPlan/midnight/makeWithdraw.d.ts +104 -0
- package/lib/cjs/transactionPlan/midnight/makeWithdraw.js +126 -0
- package/lib/cjs/transactionPlan/midnight/makerPublication.d.ts +55 -0
- package/lib/cjs/transactionPlan/midnight/makerPublication.js +315 -0
- package/lib/cjs/transactionPlan/midnight/market.d.ts +49 -0
- package/lib/cjs/transactionPlan/midnight/market.js +120 -0
- package/lib/cjs/transactionPlan/midnight/prepare.d.ts +244 -0
- package/lib/cjs/transactionPlan/midnight/prepare.js +547 -0
- package/lib/cjs/transactionPlan/midnight/publicationState.d.ts +24 -0
- package/lib/cjs/transactionPlan/midnight/publicationState.js +50 -0
- package/lib/cjs/transactionPlan/midnight/redeem.d.ts +102 -0
- package/lib/cjs/transactionPlan/midnight/redeem.js +170 -0
- package/lib/cjs/transactionPlan/midnight/reduceOnlySellFeasibility.d.ts +25 -0
- package/lib/cjs/transactionPlan/midnight/reduceOnlySellFeasibility.js +51 -0
- package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.d.ts +162 -0
- package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.js +328 -0
- package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.d.ts +155 -0
- package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.js +199 -0
- package/lib/cjs/transactionPlan/midnight/supplyCollateral.d.ts +96 -0
- package/lib/cjs/transactionPlan/midnight/supplyCollateral.js +190 -0
- package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.d.ts +112 -0
- package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.js +221 -0
- package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +129 -0
- package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.js +179 -0
- package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.d.ts +115 -0
- package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.js +259 -0
- package/lib/cjs/transactionPlan/midnight/takeBorrow.d.ts +304 -0
- package/lib/cjs/transactionPlan/midnight/takeBorrow.js +545 -0
- package/lib/cjs/transactionPlan/midnight/takeLend.d.ts +99 -0
- package/lib/cjs/transactionPlan/midnight/takeLend.js +263 -0
- package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +175 -0
- package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.js +440 -0
- package/lib/cjs/transactionPlan/midnight/takeWithdraw.d.ts +139 -0
- package/lib/cjs/transactionPlan/midnight/takeWithdraw.js +240 -0
- package/lib/cjs/transactionPlan/midnight/validation.d.ts +22 -0
- package/lib/cjs/transactionPlan/midnight/validation.js +158 -0
- package/lib/cjs/transactionPlan/midnight/withdrawCollateral.d.ts +130 -0
- package/lib/cjs/transactionPlan/midnight/withdrawCollateral.js +228 -0
- package/lib/cjs/transactionPlan/midnight/withdrawCollateralBatch.d.ts +142 -0
- package/lib/cjs/transactionPlan/midnight/withdrawCollateralBatch.js +232 -0
- package/lib/cjs/transactionPlan/plan.d.ts +48 -14
- package/lib/cjs/transactionPlan/plan.js +103 -18
- package/lib/cjs/transactionPlan/requirements.d.ts +7 -4
- package/lib/cjs/transactionPlan/requirements.js +2 -2
- package/lib/cjs/transactionPlan/serde.d.ts +13 -2
- package/lib/cjs/transactionPlan/serde.js +68 -21
- package/lib/cjs/transactionPlan/types.d.ts +147 -0
- package/lib/cjs/transactionPlan/validateActions.d.ts +3 -1
- package/lib/cjs/transactionPlan/validateActions.js +31 -3
- package/lib/cjs/transactionPlan/validation.d.ts +1 -1
- package/lib/cjs/transactionPlan/validation.js +37 -1
- package/lib/cjs/types/error.d.ts +2 -0
- package/lib/cjs/types/error.js +2 -0
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/esm/actions/midnight/redeem.d.ts +20 -3
- package/lib/esm/actions/midnight/redeem.js +56 -0
- package/lib/esm/actions/midnight/supplyCollateralWithNative.d.ts +24 -1
- package/lib/esm/actions/midnight/supplyCollateralWithNative.js +40 -0
- package/lib/esm/actions/midnight/withdrawCollateral.d.ts +16 -2
- package/lib/esm/actions/midnight/withdrawCollateral.js +25 -1
- package/lib/esm/helpers/callback.d.ts +3 -2
- package/lib/esm/helpers/callback.js +5 -21
- package/lib/esm/helpers/computeMidnightPostWithdrawalCollateral.d.ts +17 -0
- package/lib/esm/helpers/computeMidnightPostWithdrawalCollateral.js +27 -0
- package/lib/esm/helpers/parseMidnightMaker.d.ts +21 -0
- package/lib/esm/helpers/parseMidnightMaker.js +40 -1
- package/lib/esm/helpers/validate.d.ts +49 -1
- package/lib/esm/helpers/validate.js +84 -1
- package/lib/esm/helpers/validateMidnightPublication.d.ts +10 -0
- package/lib/esm/helpers/validateMidnightPublication.js +16 -0
- package/lib/esm/helpers/validateMidnightTakeableOfferFields.d.ts +28 -0
- package/lib/esm/helpers/validateMidnightTakeableOfferFields.js +81 -0
- package/lib/esm/index.d.ts +2 -2
- package/lib/esm/index.js +1 -1
- package/lib/esm/midnight/utils.d.ts +1 -1
- package/lib/esm/midnight/utils.js +1 -1
- package/lib/esm/transactionPlan/blue/withdrawBuyCallback.d.ts +101 -0
- package/lib/esm/transactionPlan/blue/withdrawBuyCallback.js +259 -0
- package/lib/esm/transactionPlan/error.d.ts +27 -0
- package/lib/esm/transactionPlan/error.js +28 -0
- package/lib/esm/transactionPlan/index.d.ts +40 -1
- package/lib/esm/transactionPlan/index.js +20 -1
- package/lib/esm/transactionPlan/midnight/authorization.d.ts +15 -0
- package/lib/esm/transactionPlan/midnight/authorization.js +40 -0
- package/lib/esm/transactionPlan/midnight/cancelOffers.d.ts +80 -0
- package/lib/esm/transactionPlan/midnight/cancelOffers.js +120 -0
- package/lib/esm/transactionPlan/midnight/makeBorrow.d.ts +104 -0
- package/lib/esm/transactionPlan/midnight/makeBorrow.js +123 -0
- package/lib/esm/transactionPlan/midnight/makeLend.d.ts +140 -0
- package/lib/esm/transactionPlan/midnight/makeLend.js +172 -0
- package/lib/esm/transactionPlan/midnight/makeRepay.d.ts +118 -0
- package/lib/esm/transactionPlan/midnight/makeRepay.js +115 -0
- package/lib/esm/transactionPlan/midnight/makeWithdraw.d.ts +104 -0
- package/lib/esm/transactionPlan/midnight/makeWithdraw.js +123 -0
- package/lib/esm/transactionPlan/midnight/makerPublication.d.ts +55 -0
- package/lib/esm/transactionPlan/midnight/makerPublication.js +310 -0
- package/lib/esm/transactionPlan/midnight/market.d.ts +49 -0
- package/lib/esm/transactionPlan/midnight/market.js +112 -0
- package/lib/esm/transactionPlan/midnight/prepare.d.ts +244 -0
- package/lib/esm/transactionPlan/midnight/prepare.js +536 -0
- package/lib/esm/transactionPlan/midnight/publicationState.d.ts +24 -0
- package/lib/esm/transactionPlan/midnight/publicationState.js +47 -0
- package/lib/esm/transactionPlan/midnight/redeem.d.ts +102 -0
- package/lib/esm/transactionPlan/midnight/redeem.js +165 -0
- package/lib/esm/transactionPlan/midnight/reduceOnlySellFeasibility.d.ts +25 -0
- package/lib/esm/transactionPlan/midnight/reduceOnlySellFeasibility.js +47 -0
- package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.d.ts +162 -0
- package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.js +323 -0
- package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.d.ts +155 -0
- package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.js +196 -0
- package/lib/esm/transactionPlan/midnight/supplyCollateral.d.ts +96 -0
- package/lib/esm/transactionPlan/midnight/supplyCollateral.js +185 -0
- package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.d.ts +112 -0
- package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.js +216 -0
- package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +129 -0
- package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.js +176 -0
- package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.d.ts +115 -0
- package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.js +254 -0
- package/lib/esm/transactionPlan/midnight/takeBorrow.d.ts +304 -0
- package/lib/esm/transactionPlan/midnight/takeBorrow.js +539 -0
- package/lib/esm/transactionPlan/midnight/takeLend.d.ts +99 -0
- package/lib/esm/transactionPlan/midnight/takeLend.js +258 -0
- package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +175 -0
- package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.js +435 -0
- package/lib/esm/transactionPlan/midnight/takeWithdraw.d.ts +139 -0
- package/lib/esm/transactionPlan/midnight/takeWithdraw.js +236 -0
- package/lib/esm/transactionPlan/midnight/validation.d.ts +22 -0
- package/lib/esm/transactionPlan/midnight/validation.js +151 -0
- package/lib/esm/transactionPlan/midnight/withdrawCollateral.d.ts +130 -0
- package/lib/esm/transactionPlan/midnight/withdrawCollateral.js +223 -0
- package/lib/esm/transactionPlan/midnight/withdrawCollateralBatch.d.ts +142 -0
- package/lib/esm/transactionPlan/midnight/withdrawCollateralBatch.js +227 -0
- package/lib/esm/transactionPlan/plan.d.ts +48 -14
- package/lib/esm/transactionPlan/plan.js +99 -14
- package/lib/esm/transactionPlan/requirements.d.ts +7 -4
- package/lib/esm/transactionPlan/requirements.js +2 -2
- package/lib/esm/transactionPlan/serde.d.ts +13 -2
- package/lib/esm/transactionPlan/serde.js +49 -2
- package/lib/esm/transactionPlan/types.d.ts +147 -0
- package/lib/esm/transactionPlan/validateActions.d.ts +3 -1
- package/lib/esm/transactionPlan/validateActions.js +31 -3
- package/lib/esm/transactionPlan/validation.d.ts +1 -1
- package/lib/esm/transactionPlan/validation.js +38 -2
- package/lib/esm/types/error.d.ts +2 -0
- package/lib/esm/types/error.js +2 -0
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { deepFreeze, getChainAddress, Time } from "@morpho-org/morpho-ts";
|
|
2
|
+
import { midnightTakeRepayWithdrawCollateral, parseMidnightTakeRepayWithdrawCollateral, } from "../../actions/midnight/takeRepayWithdrawCollateral.js";
|
|
3
|
+
import { createChainCheck } from "../../actions/requirements/chainCheck.js";
|
|
4
|
+
import { assertRegistryTargetsHaveCode } from "../../entities/requirements/assertContractCode.js";
|
|
5
|
+
import { computeMidnightPostWithdrawalCollateral } from "../../helpers/computeMidnightPostWithdrawalCollateral.js";
|
|
6
|
+
import { MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS } from "../../helpers/constant.js";
|
|
7
|
+
import { validateMidnightPositionBinding } from "../../helpers/parseMidnight.js";
|
|
8
|
+
import { validateMidnightWithdrawHealth, validateReferenceTime, } from "../../helpers/validate.js";
|
|
9
|
+
import { validateMidnightTakeableOfferFields } from "../../helpers/validateMidnightTakeableOfferFields.js";
|
|
10
|
+
import { validateMidnightTakeFeasibility } from "../../helpers/validateMidnightTakeFeasibility.js";
|
|
11
|
+
import { InvalidBigIntInputError, MidnightTakeDeadlineTooFarError, } from "../../types/error.js";
|
|
12
|
+
import { InvalidTransactionPlanError } from "../error.js";
|
|
13
|
+
import { resolveIntent } from "../intent.js";
|
|
14
|
+
import { getTokenRequirements } from "../requirements.js";
|
|
15
|
+
import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
|
|
16
|
+
import { prepareMidnightBundleAuthorization, validateSignaturelessMidnightAction, } from "./authorization.js";
|
|
17
|
+
import { storedFills, storedMarketTuple, validateCollateralIndexTypes, validateStoredCollateralOrder, } from "./market.js";
|
|
18
|
+
import { validateMidnightTargetAmountTypes, validateStoredMidnightFills, validateStoredMidnightMarket, } from "./validation.js";
|
|
19
|
+
const actionId = "midnightTakeRepayWithdrawCollateral";
|
|
20
|
+
/**
|
|
21
|
+
* Checks a Midnight repayment through borrow offers and its collateral withdrawals
|
|
22
|
+
* against the position snapshot: each withdrawal against the remaining collateral, then, when
|
|
23
|
+
* collateral is withdrawn, the debt left after the target's guaranteed reduction (`units`, or
|
|
24
|
+
* `minUnits` for an assets target) against the remaining collateral's buffered capacity. Runs the
|
|
25
|
+
* same checks as the entity's inline ones; callers parse the withdrawals first.
|
|
26
|
+
* @throws {WithdrawExceedsCollateralError} If a withdrawal exceeds the remaining collateral.
|
|
27
|
+
* @throws {MissingMarketPriceError} If remaining collateral has no price for the health check.
|
|
28
|
+
* @throws {WithdrawMakesPositionUnhealthyError} If the remaining debt exceeds buffered capacity.
|
|
29
|
+
*/
|
|
30
|
+
const validateTakeRepayWithdrawCollateralPosition = (params) => {
|
|
31
|
+
const { marketData, positionData, target, collateralWithdrawals } = params;
|
|
32
|
+
const { postCollateral, withdrawAmount } = computeMidnightPostWithdrawalCollateral({
|
|
33
|
+
market: marketData.params,
|
|
34
|
+
marketId: marketData.id,
|
|
35
|
+
collateral: positionData.collateral,
|
|
36
|
+
withdrawals: collateralWithdrawals,
|
|
37
|
+
});
|
|
38
|
+
if (collateralWithdrawals.length === 0) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const debtReduction = target.type === "units" ? target.units : target.minUnits;
|
|
42
|
+
validateMidnightWithdrawHealth({
|
|
43
|
+
market: marketData,
|
|
44
|
+
collateral: postCollateral,
|
|
45
|
+
collateralPrices: params.collateralPrices,
|
|
46
|
+
debt: debtReduction >= positionData.debt
|
|
47
|
+
? 0n
|
|
48
|
+
: positionData.debt - debtReduction,
|
|
49
|
+
withdrawAmount,
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Prepares a reduce-only buy on MidnightBundlesV2. The bundle fills borrow offers,
|
|
54
|
+
* repays the unfilled remainder at par if enabled, then withdraws collateral.
|
|
55
|
+
* The collateral receiver defaults to the submitting account. Validates inputs with the same
|
|
56
|
+
* parse-once constructor, position binding, buffered post-withdrawal health check and fill
|
|
57
|
+
* feasibility check as the entity `takeRepayWithdrawCollateral`, including its buy-budget bound:
|
|
58
|
+
* a units target's `maxBuyerAssets` must cover the units at the cheapest live price, and an
|
|
59
|
+
* assets target has no budget check. Offers whose price conversion fails throughout the plan
|
|
60
|
+
* window are dropped from the stored fills; an offer that converts only at a later fee can still
|
|
61
|
+
* revert the bundle if sent earlier. Preparation does not see live cancellations either, so
|
|
62
|
+
* simulate before sending to catch these price-conversion reverts and cancelled or consumed
|
|
63
|
+
* offers. Native funding still requires allowance for the full
|
|
64
|
+
* wrapped-native pull.
|
|
65
|
+
* @param client - Viem client used to check the chain and deployments and read prerequisites.
|
|
66
|
+
* @param params - Borrower, snapshots, buy target, quote, optional withdrawals and intent.
|
|
67
|
+
* @param params.chainId - Chain containing the market and MidnightBundlesV2.
|
|
68
|
+
* @param params.account - Non-zero borrower whose debt is repaid; it funds the repayment and sends the plan.
|
|
69
|
+
* @param params.marketData - Hydrated market snapshot used for fill feasibility and collateral capacity.
|
|
70
|
+
* @param params.positionData - Borrower's position snapshot for the same market.
|
|
71
|
+
* @param params.collateralPrices - Oracle prices indexed by market collateral, scaled by `ORACLE_PRICE_SCALE`.
|
|
72
|
+
* @param params.takeableOffers - ABI-ready borrow offers from the caller's quote, in fill order.
|
|
73
|
+
* @param params.target.type - `"assets"` to pay exact loan assets, or `"units"` to buy exact units.
|
|
74
|
+
* @param params.target.assets - Loan assets paid on an assets target, referral fee included.
|
|
75
|
+
* @param params.target.minUnits - Unit floor on an assets target.
|
|
76
|
+
* @param params.target.units - Exact units bought on a units target; `maxUint256` targets the account's whole debt.
|
|
77
|
+
* @param params.target.maxBuyerAssets - Loan-asset cap pulled on a units target, referral fee included; the unused remainder is returned.
|
|
78
|
+
* @param params.repayEnabled - Whether the bundle repays the unfilled remainder directly to Midnight.
|
|
79
|
+
* @param params.maxContinuousFee - Largest market continuous fee accepted when taking offers; pass `maxUint256` for no cap.
|
|
80
|
+
* @param params.nativeAmount - Optional native ETH in wei for a wrapped-native loan, capped by the pull.
|
|
81
|
+
* @param params.collateralWithdrawals - Optional withdrawals after the repayment; defaults to none. Each
|
|
82
|
+
* `collateralIndex` indexes `marketData.params.collateralParams`, and `assets` is in that token's base units;
|
|
83
|
+
* `maxUint256` withdraws the account's whole balance of that collateral.
|
|
84
|
+
* @param params.collateralReceiver - Optional recipient of withdrawn collateral; defaults to `account`.
|
|
85
|
+
* @param params.referralFee.bps - Optional referral fee in integer basis points, at most 10%.
|
|
86
|
+
* @param params.referralFee.recipient - Recipient required for a positive referral fee.
|
|
87
|
+
* @param params.now - Reference Unix timestamp in seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
|
|
88
|
+
* @param params.expiresAt - Onchain deadline in Unix seconds; defaults to, and may not exceed, one hour after `now`.
|
|
89
|
+
* @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
|
|
90
|
+
* @returns A frozen plan with any needed approval and standalone authorization, without signatures.
|
|
91
|
+
* @throws {InvalidBigIntInputError} when a supplied non-null `now`, `maxContinuousFee`, a target amount, or a withdrawal's collateral index or amount is not a bigint; checked before any request.
|
|
92
|
+
* @throws {ZeroAccountError} when the sender is the zero address.
|
|
93
|
+
* @throws {InvalidTransactionPlanError} when the sender address, attribution length, target discriminator or `repayEnabled` flag is invalid.
|
|
94
|
+
* @throws {InvalidMidnightNativeAmountTypeError} when `nativeAmount` is supplied as a non-bigint.
|
|
95
|
+
* @throws {NonIntegerInputError} when expiry or referral fee basis points are not safe integers.
|
|
96
|
+
* @throws {NonPositiveInputError} when expiry, a target amount or bound, or a withdrawal amount is nonpositive.
|
|
97
|
+
* @throws {ExpiredDeadlineError} when expiry is at or before the reference timestamp.
|
|
98
|
+
* @throws {NegativeInputError} when the referral fee, offer cap, continuous fee cap or native amount is negative.
|
|
99
|
+
* @throws {InputExceedsMaxError} when referral fee basis points exceed 1,000 (10%), an amount or cap exceeds its
|
|
100
|
+
* bound, or native funding exceeds the pull.
|
|
101
|
+
* @throws {InvalidCalldataOriginError} when attribution bytes are empty or malformed.
|
|
102
|
+
* @throws {MidnightTakeDeadlineTooFarError} when expiry is more than one hour away.
|
|
103
|
+
* @throws {ChainIdMismatchError} when the market, configured client or transport is on another chain.
|
|
104
|
+
* @throws {UnsupportedChainIdError} when the chain is not registered.
|
|
105
|
+
* @throws {UnknownAddressError} when a required Midnight deployment is not registered on the chain.
|
|
106
|
+
* @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
|
|
107
|
+
* @throws {InvalidMarketParameterError} when the market configuration is invalid.
|
|
108
|
+
* @throws {UnknownCollateralIndexError} when a withdrawal targets an unconfigured collateral index.
|
|
109
|
+
* @throws {MidnightCalldataEncodingError} when an address is malformed or calldata cannot be encoded.
|
|
110
|
+
* @throws {MidnightZeroReceiverError} when withdrawn collateral is sent to the zero address.
|
|
111
|
+
* @throws {MidnightContractReceiverError} when withdrawn collateral or a positive referral fee is sent to a blocked contract.
|
|
112
|
+
* @throws {EmptyMidnightTakeableOffersError} when the quote is empty.
|
|
113
|
+
* @throws {MidnightOfferSideMismatchError} when an offer is not a borrow offer.
|
|
114
|
+
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer trades another market.
|
|
115
|
+
* @throws {MidnightTakeableOfferZeroSellerReceiverError} when an offer sends seller proceeds to the zero address.
|
|
116
|
+
* @throws {UnboundedMidnightTakeInputError} when the bundle deadline is `maxUint256`.
|
|
117
|
+
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
|
|
118
|
+
* @throws {ChainWNativeMissingError} when native funding is requested without a registered wrapped-native token.
|
|
119
|
+
* @throws {NativeAmountOnNonWNativeAssetError} when native funding is requested for a different loan token.
|
|
120
|
+
* @throws {MarketIdMismatchError} when the position belongs to another market.
|
|
121
|
+
* @throws {AccrualPositionUserMismatchError} when another account owns the position.
|
|
122
|
+
* @throws {WithdrawExceedsCollateralError} when withdrawals exceed the collateral balance.
|
|
123
|
+
* @throws {MissingMarketPriceError} when the health check needs a missing oracle price.
|
|
124
|
+
* @throws {WithdrawMakesPositionUnhealthyError} when remaining debt exceeds buffered collateral capacity.
|
|
125
|
+
* @throws {MidnightContinuousFeeAboveMaxError} when the market's continuous fee exceeds the caller's cap.
|
|
126
|
+
* @throws {MidnightRepayExceedsDebtError} when the target exceeds the snapshot debt.
|
|
127
|
+
* @throws {MidnightTakeableOffersNotFillableError} when the supplied offers cannot be used.
|
|
128
|
+
* @throws {MidnightTakeTargetUnreachableError} when the target cannot be met within its bounds.
|
|
129
|
+
* @throws {viem.BaseError} when a chain, bytecode, allowance or authorization read fails.
|
|
130
|
+
* @throws {MissingContractCodeError} when a registered Midnight target has no code.
|
|
131
|
+
* @example
|
|
132
|
+
* ```ts
|
|
133
|
+
* import {
|
|
134
|
+
* buildTransactions,
|
|
135
|
+
* prepareMidnightTakeRepayWithdrawCollateral,
|
|
136
|
+
* type MidnightTakeRepayWithdrawCollateralPlanParams,
|
|
137
|
+
* } from "@morpho-org/morpho-sdk";
|
|
138
|
+
* import { blueOracleAbi } from "@morpho-org/morpho-sdk/abis";
|
|
139
|
+
* import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
|
|
140
|
+
* import { MidnightApi } from "@morpho-org/morpho-sdk/midnight-api";
|
|
141
|
+
*
|
|
142
|
+
* type SnapshotParams = Parameters<typeof fetchMidnightAccrualPosition>[1];
|
|
143
|
+
* type PublicClient = Parameters<typeof fetchMidnightAccrualPosition>[0] & {
|
|
144
|
+
* getBlock(): Promise<{ number: bigint; timestamp: bigint }>;
|
|
145
|
+
* readContract(params: {
|
|
146
|
+
* address: SnapshotParams["user"];
|
|
147
|
+
* abi: typeof blueOracleAbi;
|
|
148
|
+
* functionName: "price";
|
|
149
|
+
* blockNumber: bigint;
|
|
150
|
+
* }): Promise<bigint>;
|
|
151
|
+
* };
|
|
152
|
+
*
|
|
153
|
+
* async function prepareRepayment(
|
|
154
|
+
* client: PublicClient,
|
|
155
|
+
* marketId: SnapshotParams["marketId"],
|
|
156
|
+
* params: Pick<MidnightTakeRepayWithdrawCollateralPlanParams,
|
|
157
|
+
* "chainId" | "account" | "maxContinuousFee" | "collateralWithdrawals">,
|
|
158
|
+
* assets: bigint,
|
|
159
|
+
* minUnits: bigint,
|
|
160
|
+
* ) {
|
|
161
|
+
* const block = await client.getBlock();
|
|
162
|
+
* const positionData = await fetchMidnightAccrualPosition(client, {
|
|
163
|
+
* marketId, user: params.account, blockNumber: block.number,
|
|
164
|
+
* });
|
|
165
|
+
* const marketData = positionData.market;
|
|
166
|
+
* const collateralPrices = await Promise.all(
|
|
167
|
+
* marketData.params.collateralParams.map(({ oracle }) =>
|
|
168
|
+
* client.readContract({
|
|
169
|
+
* address: oracle, abi: blueOracleAbi, functionName: "price", blockNumber: block.number,
|
|
170
|
+
* }),
|
|
171
|
+
* ),
|
|
172
|
+
* );
|
|
173
|
+
* const quote = await new MidnightApi().fetchBookQuote({
|
|
174
|
+
* marketId, side: "asks", assets, taker: params.account,
|
|
175
|
+
* });
|
|
176
|
+
* const plan = await prepareMidnightTakeRepayWithdrawCollateral(client, {
|
|
177
|
+
* ...params, marketData, positionData, collateralPrices, now: block.timestamp,
|
|
178
|
+
* target: { type: "assets", assets, minUnits },
|
|
179
|
+
* takeableOffers: quote.data.takeableOffers,
|
|
180
|
+
* repayEnabled: true,
|
|
181
|
+
* });
|
|
182
|
+
* // Simulate, then send in order from plan.account on plan.chainId.
|
|
183
|
+
* return buildTransactions(plan);
|
|
184
|
+
* }
|
|
185
|
+
* ```
|
|
186
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
187
|
+
*/
|
|
188
|
+
export async function prepareMidnightTakeRepayWithdrawCollateral(client, params) {
|
|
189
|
+
const { chainId, account, marketData, positionData, target, nativeAmount } = params;
|
|
190
|
+
const now = params.now ?? Time.timestamp();
|
|
191
|
+
// Reject a non-bigint clock before the bigint deadline sum can throw a generic TypeError.
|
|
192
|
+
validateReferenceTime(now);
|
|
193
|
+
const maxDeadline = now + MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
|
|
194
|
+
const intent = resolveIntent({ ...params, expiresAt: params.expiresAt ?? Number(maxDeadline) }, now);
|
|
195
|
+
if (intent.deadline > maxDeadline) {
|
|
196
|
+
throw new MidnightTakeDeadlineTooFarError({
|
|
197
|
+
deadline: intent.deadline,
|
|
198
|
+
maxDeadline,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
const { type } = getPlanObject(target, "$.target");
|
|
202
|
+
if (type !== "assets" && type !== "units") {
|
|
203
|
+
throw invalidTargetType("$.target");
|
|
204
|
+
}
|
|
205
|
+
validatePlanField(params.repayEnabled, {
|
|
206
|
+
path: "$.repayEnabled",
|
|
207
|
+
type: "boolean",
|
|
208
|
+
});
|
|
209
|
+
if (typeof params.maxContinuousFee !== "bigint") {
|
|
210
|
+
throw new InvalidBigIntInputError("maxContinuousFee", params.maxContinuousFee);
|
|
211
|
+
}
|
|
212
|
+
validateMidnightTargetAmountTypes(target, target.type === "assets"
|
|
213
|
+
? ["assets", "minUnits"]
|
|
214
|
+
: ["units", "maxBuyerAssets"]);
|
|
215
|
+
const collateralWithdrawals = params.collateralWithdrawals ?? [];
|
|
216
|
+
validateCollateralIndexTypes("collateralWithdrawals", collateralWithdrawals);
|
|
217
|
+
for (const [index, { assets }] of collateralWithdrawals.entries()) {
|
|
218
|
+
if (typeof assets !== "bigint") {
|
|
219
|
+
throw new InvalidBigIntInputError(`collateralWithdrawals[${index}].assets`, assets);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const parsed = parseMidnightTakeRepayWithdrawCollateral({
|
|
223
|
+
chainId,
|
|
224
|
+
market: marketData.params,
|
|
225
|
+
target,
|
|
226
|
+
takeableOffers: params.takeableOffers,
|
|
227
|
+
repayEnabled: params.repayEnabled,
|
|
228
|
+
nativeAmount,
|
|
229
|
+
collateralWithdrawals,
|
|
230
|
+
collateralReceiver: params.collateralReceiver ?? account,
|
|
231
|
+
maxContinuousFee: params.maxContinuousFee,
|
|
232
|
+
deadline: intent.deadline,
|
|
233
|
+
referralFeePct: intent.referralFeePct,
|
|
234
|
+
referralFeeRecipient: intent.referralFeeRecipient,
|
|
235
|
+
});
|
|
236
|
+
validateMidnightTakeableOfferFields(parsed.takeableOffers);
|
|
237
|
+
const bundle = getChainAddress(chainId, "midnightBundlesV2");
|
|
238
|
+
validateMidnightPositionBinding({
|
|
239
|
+
positionData,
|
|
240
|
+
accountAddress: account,
|
|
241
|
+
marketData,
|
|
242
|
+
});
|
|
243
|
+
validateTakeRepayWithdrawCollateralPosition({
|
|
244
|
+
marketData,
|
|
245
|
+
positionData,
|
|
246
|
+
collateralPrices: params.collateralPrices,
|
|
247
|
+
target: parsed.target,
|
|
248
|
+
collateralWithdrawals: parsed.collateralWithdrawals,
|
|
249
|
+
});
|
|
250
|
+
const takeableOffers = validateMidnightTakeFeasibility({
|
|
251
|
+
side: "buy",
|
|
252
|
+
takeableOffers: parsed.takeableOffers,
|
|
253
|
+
accountAddress: account,
|
|
254
|
+
marketData,
|
|
255
|
+
now,
|
|
256
|
+
deadline: parsed.deadline,
|
|
257
|
+
referralFeePct: parsed.referralFeePct,
|
|
258
|
+
fallbackUnits: parsed.repayEnabled ? positionData.debt : 0n,
|
|
259
|
+
target: parsed.target,
|
|
260
|
+
maxContinuousFee: parsed.maxContinuousFee,
|
|
261
|
+
debt: positionData.debt,
|
|
262
|
+
});
|
|
263
|
+
await assertDeployments(client, chainId);
|
|
264
|
+
const [{ approvals }, authorization] = await Promise.all([
|
|
265
|
+
getTokenRequirements(client, {
|
|
266
|
+
chainId,
|
|
267
|
+
token: parsed.market.loanToken,
|
|
268
|
+
owner: account,
|
|
269
|
+
spender: bundle,
|
|
270
|
+
amount: parsed.target.type === "assets"
|
|
271
|
+
? parsed.target.assets
|
|
272
|
+
: parsed.target.maxBuyerAssets,
|
|
273
|
+
approvalId: (index) => `${actionId}:approval:${index}`,
|
|
274
|
+
}),
|
|
275
|
+
prepareMidnightBundleAuthorization(client, { chainId, account }),
|
|
276
|
+
]);
|
|
277
|
+
return deepFreeze({
|
|
278
|
+
version: 2,
|
|
279
|
+
chainId,
|
|
280
|
+
account,
|
|
281
|
+
expiresAt: intent.expiresAt,
|
|
282
|
+
...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
|
|
283
|
+
steps: [
|
|
284
|
+
...approvals,
|
|
285
|
+
...(authorization === undefined ? [] : [authorization]),
|
|
286
|
+
{
|
|
287
|
+
id: actionId,
|
|
288
|
+
label: "Repay Midnight debt through offers",
|
|
289
|
+
action: {
|
|
290
|
+
type: actionId,
|
|
291
|
+
inputs: {
|
|
292
|
+
chainId,
|
|
293
|
+
account,
|
|
294
|
+
market: parsed.market,
|
|
295
|
+
target: parsed.target,
|
|
296
|
+
takeableOffers,
|
|
297
|
+
repayEnabled: parsed.repayEnabled,
|
|
298
|
+
collateralWithdrawals: parsed.collateralWithdrawals,
|
|
299
|
+
collateralReceiver: parsed.collateralReceiver,
|
|
300
|
+
maxContinuousFee: parsed.maxContinuousFee,
|
|
301
|
+
...(nativeAmount !== undefined && {
|
|
302
|
+
nativeAssets: parsed.nativeFunding.value,
|
|
303
|
+
}),
|
|
304
|
+
deadline: parsed.deadline,
|
|
305
|
+
referralFeePct: parsed.referralFeePct,
|
|
306
|
+
referralFeeRecipient: parsed.referralFeeRecipient,
|
|
307
|
+
},
|
|
308
|
+
},
|
|
309
|
+
},
|
|
310
|
+
],
|
|
311
|
+
signatureRequests: [],
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
async function assertDeployments(client, chainId) {
|
|
315
|
+
const chainCheck = createChainCheck(client, chainId);
|
|
316
|
+
await chainCheck();
|
|
317
|
+
// Check deployments before allowance or authorization reads can fail decoding empty data.
|
|
318
|
+
await assertRegistryTargetsHaveCode(client, chainId, [
|
|
319
|
+
{
|
|
320
|
+
role: "midnightBundlesV2",
|
|
321
|
+
address: getChainAddress(chainId, "midnightBundlesV2"),
|
|
322
|
+
},
|
|
323
|
+
{ role: "midnight", address: getChainAddress(chainId, "midnight") },
|
|
324
|
+
], chainCheck);
|
|
325
|
+
}
|
|
326
|
+
function invalidTargetType(path) {
|
|
327
|
+
return new InvalidTransactionPlanError({
|
|
328
|
+
path: `${path}.type`,
|
|
329
|
+
reason: "expected assets or units",
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
function storedParams(inputs) {
|
|
333
|
+
return {
|
|
334
|
+
chainId: inputs.chainId,
|
|
335
|
+
market: storedMarketTuple(inputs.market),
|
|
336
|
+
target: inputs.target,
|
|
337
|
+
takeableOffers: storedFills(inputs.takeableOffers),
|
|
338
|
+
repayEnabled: inputs.repayEnabled,
|
|
339
|
+
collateralWithdrawals: inputs.collateralWithdrawals.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
|
|
340
|
+
collateralReceiver: inputs.collateralReceiver,
|
|
341
|
+
maxContinuousFee: inputs.maxContinuousFee,
|
|
342
|
+
deadline: inputs.deadline,
|
|
343
|
+
referralFeePct: inputs.referralFeePct,
|
|
344
|
+
referralFeeRecipient: inputs.referralFeeRecipient,
|
|
345
|
+
nativeAmount: inputs.nativeAssets,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* @internal Encodes the prepared buy and withdrawals from persisted fields alone.
|
|
350
|
+
* @throws {InvalidTransactionPlanError} If the market's collateral tokens are not in strictly
|
|
351
|
+
* ascending address order, or the target is not an object whose type is `assets` or `units`.
|
|
352
|
+
*/
|
|
353
|
+
export function buildMidnightTakeRepayWithdrawCollateral({ inputs, }) {
|
|
354
|
+
const { type } = getPlanObject(inputs.target, "$.inputs.target");
|
|
355
|
+
if (type !== "assets" && type !== "units") {
|
|
356
|
+
throw invalidTargetType("$.inputs.target");
|
|
357
|
+
}
|
|
358
|
+
validateStoredCollateralOrder(inputs.market.collateralParams, "$.inputs.market.collateralParams");
|
|
359
|
+
return midnightTakeRepayWithdrawCollateral(storedParams(inputs));
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* @internal Validates a stored reduce-only buy recipe without fetching any state: the field
|
|
363
|
+
* shapes and collateral order, then the action's clock-free parse checks on the stored inputs.
|
|
364
|
+
*/
|
|
365
|
+
export function validateMidnightTakeRepayWithdrawCollateralPlanAction(action, path) {
|
|
366
|
+
const inputsPath = `${path}.inputs`;
|
|
367
|
+
const inputs = getPlanObject(action.inputs, inputsPath);
|
|
368
|
+
validatePlanFields(inputs, {
|
|
369
|
+
path: inputsPath,
|
|
370
|
+
fields: {
|
|
371
|
+
repayEnabled: "boolean",
|
|
372
|
+
collateralReceiver: "address",
|
|
373
|
+
maxContinuousFee: "uint256 bigint",
|
|
374
|
+
deadline: "uint256 bigint",
|
|
375
|
+
referralFeePct: "uint256 bigint",
|
|
376
|
+
referralFeeRecipient: "address",
|
|
377
|
+
...(inputs.nativeAssets !== undefined && {
|
|
378
|
+
nativeAssets: "uint256 bigint",
|
|
379
|
+
}),
|
|
380
|
+
},
|
|
381
|
+
});
|
|
382
|
+
const targetPath = `${inputsPath}.target`;
|
|
383
|
+
const target = getPlanObject(inputs.target, targetPath);
|
|
384
|
+
switch (target.type) {
|
|
385
|
+
case "assets":
|
|
386
|
+
validatePlanFields(target, {
|
|
387
|
+
path: targetPath,
|
|
388
|
+
fields: { assets: "uint256 bigint", minUnits: "uint256 bigint" },
|
|
389
|
+
});
|
|
390
|
+
break;
|
|
391
|
+
case "units":
|
|
392
|
+
validatePlanFields(target, {
|
|
393
|
+
path: targetPath,
|
|
394
|
+
fields: { units: "uint256 bigint", maxBuyerAssets: "uint256 bigint" },
|
|
395
|
+
});
|
|
396
|
+
break;
|
|
397
|
+
default:
|
|
398
|
+
throw invalidTargetType(targetPath);
|
|
399
|
+
}
|
|
400
|
+
const withdrawalsPath = `${inputsPath}.collateralWithdrawals`;
|
|
401
|
+
if (!Array.isArray(inputs.collateralWithdrawals)) {
|
|
402
|
+
throw new InvalidTransactionPlanError({
|
|
403
|
+
path: withdrawalsPath,
|
|
404
|
+
reason: "expected an array",
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
for (const [index, item] of inputs.collateralWithdrawals.entries()) {
|
|
408
|
+
const itemPath = `${withdrawalsPath}[${index}]`;
|
|
409
|
+
validatePlanFields(getPlanObject(item, itemPath), {
|
|
410
|
+
path: itemPath,
|
|
411
|
+
fields: { collateralIndex: "uint256 bigint", assets: "uint256 bigint" },
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
const chainId = inputs.chainId; // Checked by the parse dispatcher.
|
|
415
|
+
validateStoredMidnightMarket(inputs.market, {
|
|
416
|
+
path: `${inputsPath}.market`,
|
|
417
|
+
chainId,
|
|
418
|
+
});
|
|
419
|
+
validateStoredCollateralOrder(inputs.market.collateralParams, `${inputsPath}.market.collateralParams`);
|
|
420
|
+
validateStoredMidnightFills(inputs.takeableOffers, {
|
|
421
|
+
path: `${inputsPath}.takeableOffers`,
|
|
422
|
+
chainId,
|
|
423
|
+
});
|
|
424
|
+
validateSignaturelessMidnightAction(action, path);
|
|
425
|
+
try {
|
|
426
|
+
parseMidnightTakeRepayWithdrawCollateral(storedParams(action.inputs));
|
|
427
|
+
}
|
|
428
|
+
catch (cause) {
|
|
429
|
+
throw new InvalidTransactionPlanError({
|
|
430
|
+
path: inputsPath,
|
|
431
|
+
reason: "expected a valid Midnight repayment through borrow offers",
|
|
432
|
+
cause,
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { AccrualPosition, type Market } from "@morpho-org/midnight-sdk";
|
|
2
|
+
import type { Address, Client } from "viem";
|
|
3
|
+
import { type MidnightTakeWithdrawParams } from "../../actions/midnight/takeWithdraw.js";
|
|
4
|
+
import { type IntentParams } from "../intent.js";
|
|
5
|
+
import type { Action, TransactionPlan } from "../types.js";
|
|
6
|
+
/**
|
|
7
|
+
* Inputs for withdrawing the account's Midnight credit using caller-selected lend offers.
|
|
8
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
9
|
+
*/
|
|
10
|
+
export interface MidnightTakeWithdrawPlanParams extends Omit<IntentParams, "supportSignature" | "deployless">, Pick<MidnightTakeWithdrawParams, "target" | "takeableOffers"> {
|
|
11
|
+
/** Market snapshot used to assess liquidity and fill feasibility. */
|
|
12
|
+
readonly marketData: Market;
|
|
13
|
+
/** Owner-bound position snapshot for the same market, read at the same block. */
|
|
14
|
+
readonly positionData: AccrualPosition;
|
|
15
|
+
/** Recipient of the withdrawn loan assets; defaults to account. */
|
|
16
|
+
readonly receiver?: Address;
|
|
17
|
+
/** Reference timestamp in seconds; defaults to the device clock. */
|
|
18
|
+
readonly now?: bigint;
|
|
19
|
+
/** Unix seconds; defaults to one hour after the reference timestamp. */
|
|
20
|
+
readonly expiresAt?: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Prepares a reduce-only Midnight withdrawal that redeems available credit at par
|
|
24
|
+
* before selling the rest of the target into lend offers. It cannot open debt.
|
|
25
|
+
* Validates inputs with the same parse-once constructor and fill feasibility check as the
|
|
26
|
+
* entity `takeWithdraw`, checks every taken offer field, binds the position to the account and
|
|
27
|
+
* market, and caps fills at the
|
|
28
|
+
* position's credit accrued to the reference timestamp against `marketData`, the snapshot that
|
|
29
|
+
* caps withdrawable credit. It then reads the registry targets'
|
|
30
|
+
* bytecode and the bundle authorization. On an assets target, offers that would revert the
|
|
31
|
+
* whole bundle are dropped from the stored fills. Like the entity check, fill feasibility counts
|
|
32
|
+
* units at par and does not price discounted bids after settlement fees, so a plan can pass
|
|
33
|
+
* preparation and still revert onchain; the onchain bounds keep funds safe. Simulate before sending.
|
|
34
|
+
* @param client - Viem client used to verify chain, deployments and authorization.
|
|
35
|
+
* @param params - Account, market and position snapshots, fills and intent.
|
|
36
|
+
* @param params.chainId - Chain containing the market and MidnightBundlesV2.
|
|
37
|
+
* @param params.account - Non-zero position owner that sends the plan; its credit is withdrawn.
|
|
38
|
+
* @param params.marketData - Market snapshot used to assess liquidity and fill feasibility.
|
|
39
|
+
* @param params.positionData - Owner-bound position snapshot for the same market, read at the same block.
|
|
40
|
+
* @param params.takeableOffers - ABI-ready lend offers from the caller's quote, in fill order.
|
|
41
|
+
* @param params.target.type - `"assets"` to receive loan assets, or `"units"` to sell exact credit units.
|
|
42
|
+
* @param params.target.assets - Exact loan assets paid to the receiver on an assets target; any referral fee is sold on top.
|
|
43
|
+
* @param params.target.maxUnits - Unit cap on an assets target.
|
|
44
|
+
* @param params.target.units - Exact credit units to sell on a units target.
|
|
45
|
+
* @param params.target.minSellerAssets - Loan-asset floor on a units target.
|
|
46
|
+
* @param params.receiver - Optional recipient of the withdrawn loan assets; defaults to `account`.
|
|
47
|
+
* @param params.referralFee.bps - Optional referral fee in integer basis points, at most 10%.
|
|
48
|
+
* @param params.referralFee.recipient - Recipient required for a positive referral fee.
|
|
49
|
+
* @param params.now - Reference Unix timestamp in seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
|
|
50
|
+
* @param params.expiresAt - Onchain deadline in Unix seconds; defaults to, and may not exceed, one hour after `now`.
|
|
51
|
+
* @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
|
|
52
|
+
* @returns A frozen plan with a standalone authorization step if needed and no signature requests.
|
|
53
|
+
* @throws {InvalidBigIntInputError} If a supplied non-null `now` or a target amount is not a
|
|
54
|
+
* bigint; checked before any request.
|
|
55
|
+
* @throws {ZeroAccountError} If `account` is the zero address.
|
|
56
|
+
* @throws {NonIntegerInputError} If `expiresAt` or `referralFee.bps` is not a safe integer.
|
|
57
|
+
* @throws {NonPositiveInputError} If `expiresAt`, the target amount, `maxUnits` or
|
|
58
|
+
* `minSellerAssets` is not positive.
|
|
59
|
+
* @throws {ExpiredDeadlineError} If expiry is at or before the reference timestamp.
|
|
60
|
+
* @throws {NegativeInputError} If `referralFee.bps` or an offer cap is negative.
|
|
61
|
+
* @throws {InputExceedsMaxError} If `referralFee.bps` exceeds 1,000 (10%), or a target amount or
|
|
62
|
+
* offer cap exceeds uint128.
|
|
63
|
+
* @throws {InvalidCalldataOriginError} If `calldataOrigin` is empty, malformed or has an odd number of hex digits.
|
|
64
|
+
* @throws {MidnightTakeDeadlineTooFarError} If expiry is more than one hour away.
|
|
65
|
+
* @throws {InvalidTransactionPlanError} If `account` is malformed or the target type is neither assets nor units.
|
|
66
|
+
* @throws {ChainIdMismatchError} If the client, transport or market is on a different chain.
|
|
67
|
+
* @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
|
|
68
|
+
* @throws {InvalidMarketParameterError} If the market tuple has invalid parameters.
|
|
69
|
+
* @throws {EmptyMidnightTakeableOffersError} If no offers are supplied.
|
|
70
|
+
* @throws {MidnightOfferSideMismatchError} If an offer is not a lend offer.
|
|
71
|
+
* @throws {MidnightTakeableOfferMarketMismatchError} If an offer trades another market.
|
|
72
|
+
* @throws {MidnightCalldataEncodingError} If an address or offer field cannot be ABI-encoded.
|
|
73
|
+
* @throws {MidnightZeroReceiverError} If the receiver is the zero address.
|
|
74
|
+
* @throws {MidnightContractReceiverError} If the receiver, or the referral fee recipient of a
|
|
75
|
+
* positive fee, is a Midnight protocol or market token contract.
|
|
76
|
+
* @throws {UnboundedMidnightTakeInputError} If `target.units` or `target.maxUnits` is `maxUint256`.
|
|
77
|
+
* @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no recipient.
|
|
78
|
+
* @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
|
|
79
|
+
* @throws {UnknownAddressError} If the chain has no `midnightBundlesV2` deployment.
|
|
80
|
+
* @throws {MarketIdMismatchError} If the position belongs to another market.
|
|
81
|
+
* @throws {AccrualPositionUserMismatchError} If the position is not owned by the account.
|
|
82
|
+
* @throws {InvalidPositionLossFactorError} If the position's loss factor is ahead of its market's.
|
|
83
|
+
* @throws {InvalidPositionAccrualStateError} If the position's credit and fee snapshot cannot be accrued.
|
|
84
|
+
* @throws {MidnightTakeableOffersNotFillableError} If the supplied offers cannot be used.
|
|
85
|
+
* @throws {MidnightTakeCreditInsufficientError} If the target needs more units than the
|
|
86
|
+
* position's accrued credit.
|
|
87
|
+
* @throws {MidnightTakeTargetUnreachableError} With field `target.maxUnits` if `maxUnits` cannot
|
|
88
|
+
* cover the requested assets, or `target.minSellerAssets` if the units cannot yield it; change the
|
|
89
|
+
* target instead of re-quoting. With field `takeableOffers` if the credit covers the target but
|
|
90
|
+
* the offers plus withdrawable liquidity cannot fill it.
|
|
91
|
+
* @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
|
|
92
|
+
* @throws {viem.BaseError} If an `eth_chainId` request or the authorization read fails.
|
|
93
|
+
* @example
|
|
94
|
+
* ```ts
|
|
95
|
+
* import { buildTransactions, prepareMidnightTakeWithdraw, type TransactionPlan } from "@morpho-org/morpho-sdk";
|
|
96
|
+
* import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
|
|
97
|
+
* import { MidnightApi } from "@morpho-org/morpho-sdk/midnight-api";
|
|
98
|
+
* import { type Address, type Hash, createPublicClient, http } from "viem";
|
|
99
|
+
* import { base } from "viem/chains";
|
|
100
|
+
*
|
|
101
|
+
* async function prepareWithdrawal(account: Address, marketId: Hash) {
|
|
102
|
+
* const client = createPublicClient({ chain: base, transport: http() });
|
|
103
|
+
* const block = await client.getBlock();
|
|
104
|
+
* const positionData = await fetchMidnightAccrualPosition(client, {
|
|
105
|
+
* marketId,
|
|
106
|
+
* user: account,
|
|
107
|
+
* blockNumber: block.number,
|
|
108
|
+
* });
|
|
109
|
+
* const marketData = positionData.market;
|
|
110
|
+
* const assets = 1_000_000n;
|
|
111
|
+
* const maxUnits = 1_100_000n;
|
|
112
|
+
* // Quote the unit ceiling: fees come out of the proceeds, so fills sized to the net
|
|
113
|
+
* // assets could not deliver them.
|
|
114
|
+
* const quote = await new MidnightApi().fetchBookQuote({
|
|
115
|
+
* marketId,
|
|
116
|
+
* side: "bids",
|
|
117
|
+
* units: maxUnits,
|
|
118
|
+
* taker: account,
|
|
119
|
+
* });
|
|
120
|
+
* const plan: TransactionPlan = await prepareMidnightTakeWithdraw(client, {
|
|
121
|
+
* chainId: base.id,
|
|
122
|
+
* account,
|
|
123
|
+
* marketData,
|
|
124
|
+
* positionData,
|
|
125
|
+
* now: block.timestamp,
|
|
126
|
+
* target: { type: "assets", assets, maxUnits },
|
|
127
|
+
* takeableOffers: quote.data.takeableOffers,
|
|
128
|
+
* });
|
|
129
|
+
* // Simulate, then send in order from plan.account on plan.chainId.
|
|
130
|
+
* return buildTransactions(plan);
|
|
131
|
+
* }
|
|
132
|
+
* ```
|
|
133
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
134
|
+
*/
|
|
135
|
+
export declare function prepareMidnightTakeWithdraw(client: Client, params: MidnightTakeWithdrawPlanParams): Promise<TransactionPlan>;
|
|
136
|
+
/** @internal Encodes the prepared credit withdrawal from persisted inputs without state reads. */
|
|
137
|
+
export declare function buildMidnightTakeWithdraw({ inputs: { chainId, market, target, receiver, takeableOffers, deadline, referralFeePct, referralFeeRecipient, }, }: Extract<Action, {
|
|
138
|
+
type: "midnightTakeWithdraw";
|
|
139
|
+
}>): Readonly<import("../../index.js").Transaction<import("../../index.js").MidnightTakeWithdrawAction>>;
|