@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,216 @@
|
|
|
1
|
+
import { MAX_COLLATERALS_PER_BORROWER, MarketUtils, } from "@morpho-org/midnight-sdk";
|
|
2
|
+
import { deepFreeze, getChainAddress, Time } from "@morpho-org/morpho-ts";
|
|
3
|
+
import { parseMidnightSupplyCollateralBatchPreparation } from "../../actions/midnight/parseCollateralBatch.js";
|
|
4
|
+
import { midnightSupplyCollateralBatch } from "../../actions/midnight/supplyCollateralBatch.js";
|
|
5
|
+
import { createChainCheck } from "../../actions/requirements/chainCheck.js";
|
|
6
|
+
import { assertRegistryTargetsHaveCode } from "../../entities/requirements/assertContractCode.js";
|
|
7
|
+
import { validateReferenceTime } from "../../helpers/validate.js";
|
|
8
|
+
import { InputExceedsMaxError, } from "../../types/index.js";
|
|
9
|
+
import { InvalidTransactionPlanError } from "../error.js";
|
|
10
|
+
import { resolveIntent } from "../intent.js";
|
|
11
|
+
import { getTokenRequirements } from "../requirements.js";
|
|
12
|
+
import { getPlanObject, validatePlanFields } from "../validation.js";
|
|
13
|
+
import { validateSignaturelessMidnightAction } from "./authorization.js";
|
|
14
|
+
import { storedMarketTuple, validateCollateralTransferInputs, validateStoredCollateralOrder, } from "./market.js";
|
|
15
|
+
import { validateStoredMidnightMarket } from "./validation.js";
|
|
16
|
+
const actionId = "midnightSupplyCollateralBatch";
|
|
17
|
+
/**
|
|
18
|
+
* Prepares ordered collateral supplies in one direct Midnight core multicall, even for one entry.
|
|
19
|
+
* Inputs go through `parseMidnightSupplyCollateralBatchPreparation`, the parse-once constructor
|
|
20
|
+
* the entity `supplyCollateralBatch` uses, in the same order: account, market, a nonempty list
|
|
21
|
+
* with unique indexes, then each entry's amount and index. Duplicate indexes are rejected, unlike
|
|
22
|
+
* bundle flows which sum them. Midnight pulls every token from the account, so for each collateral
|
|
23
|
+
* token whose allowance is below that token's total the plan adds the ERC-20 approval steps that
|
|
24
|
+
* token's rules require, as the entity does: usually one unlimited approval to Midnight core, but
|
|
25
|
+
* possibly a reset to zero first or a capped amount. No authorization or signature is needed, and expiry is checked
|
|
26
|
+
* during preparation only; it is not an onchain deadline. Midnight keeps at most 16 collaterals per
|
|
27
|
+
* borrower, so a longer list is rejected before any request. The plan reads no balances, and the
|
|
28
|
+
* approvals are separate transactions that stay in place when an underfunded entry reverts the
|
|
29
|
+
* multicall, so simulate every step together before asking for the first approval. Unlike the
|
|
30
|
+
* entity, the allowance check keeps no `reservedCollateralAssets` reserve, so the supply can
|
|
31
|
+
* consume an allowance another operation relies on.
|
|
32
|
+
* @param client - Viem client used to check the network and the Midnight core deployment and read allowances.
|
|
33
|
+
* @param params - Market, ordered supplies and the sending account.
|
|
34
|
+
* @param params.chainId - EIP-155 chain ID of the market and submitting client.
|
|
35
|
+
* @param params.account - Nonzero account that sends the multicall and receives the collateral.
|
|
36
|
+
* @param params.market - Market configuration on the target chain.
|
|
37
|
+
* @param params.collateralSupplies - Nonempty ordered supplies, one per collateral index.
|
|
38
|
+
* @param params.now - Reference Unix timestamp in seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
|
|
39
|
+
* @param params.expiresAt - Plan expiry in Unix seconds; defaults to two hours after `now`. Midnight does not enforce it onchain.
|
|
40
|
+
* @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
|
|
41
|
+
* @returns A frozen plan whose approval steps, if any, precede the multicall step; send them in order from `params.account`.
|
|
42
|
+
* @throws {InvalidBigIntInputError} If a supplied non-null `now`, or a supply's `collateralIndex` or `assets`, is not a bigint; checked before any request.
|
|
43
|
+
* @throws {ZeroAccountError} If the account is the zero address.
|
|
44
|
+
* @throws {NonIntegerInputError} If expiry is not a safe integer.
|
|
45
|
+
* @throws {ExpiredDeadlineError} If expiry is at or before the reference time.
|
|
46
|
+
* @throws {InvalidCalldataOriginError} If attribution bytes are empty or malformed.
|
|
47
|
+
* @throws {InvalidTransactionPlanError} If the account is malformed, attribution exceeds 1 MiB, the supplies are not an array, or an entry is not an object.
|
|
48
|
+
* @throws {ChainIdMismatchError} If the market, client or RPC targets another chain.
|
|
49
|
+
* @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
|
|
50
|
+
* @throws {InvalidMarketParameterError} If the market configuration is invalid.
|
|
51
|
+
* @throws {EmptyMidnightCollateralSuppliesError} If the list is empty.
|
|
52
|
+
* @throws {DuplicateMidnightCollateralIndexError} If an index repeats.
|
|
53
|
+
* @throws {NonPositiveInputError} If expiry or an amount is not positive.
|
|
54
|
+
* @throws {InputExceedsMaxError} If an amount exceeds uint128, or the list has more than `MAX_COLLATERALS_PER_BORROWER` (16) entries.
|
|
55
|
+
* @throws {UnknownCollateralIndexError} If an index is not configured on the market.
|
|
56
|
+
* @throws {MidnightCalldataEncodingError} If a market field cannot be ABI-encoded.
|
|
57
|
+
* @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
|
|
58
|
+
* @throws {UnknownAddressError} If Midnight core is not registered on the chain.
|
|
59
|
+
* @throws {MissingContractCodeError} If the registered Midnight core has no deployed code.
|
|
60
|
+
* @throws {viem.BaseError} If the chain ID, bytecode or allowance read fails.
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* import {
|
|
64
|
+
* buildTransactions,
|
|
65
|
+
* prepareMidnightSupplyCollateralBatch,
|
|
66
|
+
* type TransactionPlan,
|
|
67
|
+
* } from "@morpho-org/morpho-sdk";
|
|
68
|
+
* import { fetchMidnightMarketParams } from "@morpho-org/morpho-sdk/fetch";
|
|
69
|
+
* import { type Address, type Hash, createPublicClient, http } from "viem";
|
|
70
|
+
* import { base } from "viem/chains";
|
|
71
|
+
*
|
|
72
|
+
* async function prepareCollateralBatch(account: Address, marketId: Hash) {
|
|
73
|
+
* const client = createPublicClient({ chain: base, transport: http() });
|
|
74
|
+
* const market = await fetchMidnightMarketParams(client, { marketId });
|
|
75
|
+
* const plan: TransactionPlan = await prepareMidnightSupplyCollateralBatch(client, {
|
|
76
|
+
* chainId: base.id,
|
|
77
|
+
* account,
|
|
78
|
+
* market,
|
|
79
|
+
* collateralSupplies: [
|
|
80
|
+
* { collateralIndex: 0n, assets: 1_000_000n },
|
|
81
|
+
* { collateralIndex: 1n, assets: 2_000_000n },
|
|
82
|
+
* ],
|
|
83
|
+
* });
|
|
84
|
+
* // plan.steps: any approvals to Midnight core, then "midnightSupplyCollateralBatch".
|
|
85
|
+
* return buildTransactions(plan);
|
|
86
|
+
* }
|
|
87
|
+
* ```
|
|
88
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
89
|
+
*/
|
|
90
|
+
export async function prepareMidnightSupplyCollateralBatch(client, params) {
|
|
91
|
+
const { account, chainId, market } = params;
|
|
92
|
+
const now = params.now ?? Time.timestamp();
|
|
93
|
+
validateReferenceTime(now);
|
|
94
|
+
const { expiresAt, calldataOrigin } = resolveIntent({
|
|
95
|
+
account,
|
|
96
|
+
chainId,
|
|
97
|
+
expiresAt: params.expiresAt,
|
|
98
|
+
calldataOrigin: params.calldataOrigin,
|
|
99
|
+
}, now);
|
|
100
|
+
const { collateralSupplies } = params;
|
|
101
|
+
validateCollateralTransferInputs("collateralSupplies", collateralSupplies);
|
|
102
|
+
// Every supplied index becomes active, and core rejects a 17th active collateral after the approvals.
|
|
103
|
+
if (BigInt(collateralSupplies.length) > MAX_COLLATERALS_PER_BORROWER) {
|
|
104
|
+
throw new InputExceedsMaxError({
|
|
105
|
+
field: "collateralSupplies.length",
|
|
106
|
+
value: BigInt(collateralSupplies.length),
|
|
107
|
+
max: MAX_COLLATERALS_PER_BORROWER,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
const parsed = parseMidnightSupplyCollateralBatchPreparation({
|
|
111
|
+
chainId,
|
|
112
|
+
market,
|
|
113
|
+
accountAddress: account,
|
|
114
|
+
// Forward only the declared fields: an entity entry's reservedCollateralAssets would raise the approval threshold.
|
|
115
|
+
collateralSupplies: collateralSupplies.map(({ collateralIndex, assets }) => ({
|
|
116
|
+
collateralIndex,
|
|
117
|
+
assets,
|
|
118
|
+
})),
|
|
119
|
+
});
|
|
120
|
+
// Narrows the type only: resolveIntent has already rejected the zero account.
|
|
121
|
+
if ("error" in parsed) {
|
|
122
|
+
throw parsed.error;
|
|
123
|
+
}
|
|
124
|
+
if ("error" in parsed.action) {
|
|
125
|
+
throw parsed.action.error;
|
|
126
|
+
}
|
|
127
|
+
// Store the tuple the parse step checked, not one read again after the awaits below.
|
|
128
|
+
const marketStruct = MarketUtils.toStruct(market);
|
|
129
|
+
const spender = getChainAddress(chainId, "midnight");
|
|
130
|
+
const chainCheck = createChainCheck(client, chainId);
|
|
131
|
+
await chainCheck();
|
|
132
|
+
// A code-less core would accept the multicall as a silent no-op and keep the allowances.
|
|
133
|
+
await assertRegistryTargetsHaveCode(client, chainId, [{ role: "midnight", address: spender }], chainCheck);
|
|
134
|
+
const prerequisites = await Promise.all(parsed.approvals.map(({ token, amount }, tokenIndex) => getTokenRequirements(client, {
|
|
135
|
+
chainId,
|
|
136
|
+
owner: account,
|
|
137
|
+
token,
|
|
138
|
+
spender,
|
|
139
|
+
amount,
|
|
140
|
+
approvalId: (index) => `${actionId}:approval:${tokenIndex}:${index}`,
|
|
141
|
+
})));
|
|
142
|
+
return deepFreeze({
|
|
143
|
+
version: 2,
|
|
144
|
+
chainId,
|
|
145
|
+
account,
|
|
146
|
+
expiresAt,
|
|
147
|
+
...(calldataOrigin && { calldataOrigin }),
|
|
148
|
+
steps: [
|
|
149
|
+
...prerequisites.flatMap(({ approvals }) => approvals),
|
|
150
|
+
{
|
|
151
|
+
id: actionId,
|
|
152
|
+
label: "Supply Midnight collateral batch",
|
|
153
|
+
action: {
|
|
154
|
+
type: actionId,
|
|
155
|
+
inputs: {
|
|
156
|
+
account,
|
|
157
|
+
chainId,
|
|
158
|
+
market: marketStruct,
|
|
159
|
+
collateralSupplies: parsed.action.collateralSupplies.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
],
|
|
164
|
+
signatureRequests: [],
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/** @internal Encodes the stored direct collateral supply batch. */
|
|
168
|
+
export function buildMidnightSupplyCollateralBatch({ inputs, }) {
|
|
169
|
+
const { account, chainId, market, collateralSupplies } = inputs;
|
|
170
|
+
// A directly built step skips restore, so check each entry's shape and index type here.
|
|
171
|
+
validateCollateralTransferInputs("inputs.collateralSupplies", collateralSupplies);
|
|
172
|
+
validateStoredCollateralOrder(market.collateralParams, "$.inputs.market.collateralParams");
|
|
173
|
+
return midnightSupplyCollateralBatch({
|
|
174
|
+
chainId,
|
|
175
|
+
market: storedMarketTuple(market),
|
|
176
|
+
collateralSupplies,
|
|
177
|
+
onBehalf: account,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
/** @internal Validates the stored Midnight collateral supply batch without RPC. */
|
|
181
|
+
export function validateMidnightSupplyCollateralBatchPlanAction(action, path) {
|
|
182
|
+
const inputsPath = `${path}.inputs`;
|
|
183
|
+
const inputs = getPlanObject(action.inputs, inputsPath);
|
|
184
|
+
const marketPath = `${inputsPath}.market`;
|
|
185
|
+
const market = getPlanObject(inputs.market, marketPath);
|
|
186
|
+
// Validate the tuple before reading its collateral tokens.
|
|
187
|
+
validateStoredMidnightMarket(market, {
|
|
188
|
+
path: marketPath,
|
|
189
|
+
chainId: inputs.chainId,
|
|
190
|
+
});
|
|
191
|
+
const collaterals = market.collateralParams;
|
|
192
|
+
validateStoredCollateralOrder(collaterals, `${marketPath}.collateralParams`);
|
|
193
|
+
const suppliesPath = `${inputsPath}.collateralSupplies`;
|
|
194
|
+
if (!Array.isArray(inputs.collateralSupplies)) {
|
|
195
|
+
throw new InvalidTransactionPlanError({
|
|
196
|
+
path: suppliesPath,
|
|
197
|
+
reason: "expected an array",
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
for (const [index, supply] of inputs.collateralSupplies.entries()) {
|
|
201
|
+
const itemPath = `${suppliesPath}[${index}]`;
|
|
202
|
+
const item = getPlanObject(supply, itemPath);
|
|
203
|
+
validatePlanFields(item, {
|
|
204
|
+
path: itemPath,
|
|
205
|
+
fields: { collateralIndex: "uint256 bigint", assets: "uint128 bigint" },
|
|
206
|
+
});
|
|
207
|
+
if (item.collateralIndex >= BigInt(collaterals.length)) {
|
|
208
|
+
throw new InvalidTransactionPlanError({
|
|
209
|
+
path: `${itemPath}.collateralIndex`,
|
|
210
|
+
reason: "expected an index configured in the market",
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Midnight never consumes a signature reference.
|
|
215
|
+
validateSignaturelessMidnightAction(action, path);
|
|
216
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import type { Client } from "viem";
|
|
2
|
+
import type { MidnightMakeBorrowCollateral } from "../../types/midnightCancelAndMake.js";
|
|
3
|
+
import type { TransactionPlan } from "../types.js";
|
|
4
|
+
import { type MidnightMakerPublicationPlanParams } from "./makerPublication.js";
|
|
5
|
+
/**
|
|
6
|
+
* Inputs for atomically supplying collateral and publishing resting Midnight borrow offers.
|
|
7
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
8
|
+
*/
|
|
9
|
+
export interface MidnightSupplyCollateralMakeBorrowPlanParams extends MidnightMakerPublicationPlanParams {
|
|
10
|
+
/**
|
|
11
|
+
* Market shared by all offers, with one positive supply per selected collateral index.
|
|
12
|
+
* Indexes are zero-based positions in ascending collateral token address order.
|
|
13
|
+
*/
|
|
14
|
+
readonly collateral: MidnightMakeBorrowCollateral;
|
|
15
|
+
/** Native ETH in wei, capped by the wrapped-native collateral pull. */
|
|
16
|
+
readonly nativeAmount?: bigint;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Prepares one MidnightBundlesV2 call to supply collateral, optionally cancel groups, and
|
|
20
|
+
* activate the maker's Price V1 or Rate V1 offer root without filling an offer or creating debt.
|
|
21
|
+
* Per-token allowance to the bundle is checked against the full pull, even when native ETH funds
|
|
22
|
+
* some wrapped collateral; when it falls short, the plan approves `maxUint256` (capped per token
|
|
23
|
+
* by the SDK), and unused allowance remains after publication. Operator grants remain until
|
|
24
|
+
* revoked; a standalone bundle grant can remain even if publication fails. No signature is requested.
|
|
25
|
+
* Builds the offer tree and checks the offer-capped `expiresAt` first, then validates the
|
|
26
|
+
* publication with the entity `supplyCollateralMakeBorrow` checks through a plan-side
|
|
27
|
+
* constructor, with the market, collateral and native funding checks before any state read. So an
|
|
28
|
+
* input with several errors can fail on another error here than in the entity. The chain and the bundle, Midnight and ratifier code are checked
|
|
29
|
+
* once, right before the first publication-state read. Approvals are checked per
|
|
30
|
+
* token like the entity's `getRequirements()`, summing supplies that pull the same token.
|
|
31
|
+
*
|
|
32
|
+
* @param client - Plain viem client used to validate deployments, offers and prerequisites.
|
|
33
|
+
* @param params - Maker, collateral supplies and the maker's offer tree or tree creation request.
|
|
34
|
+
* @param params.chainId - Chain containing Midnight, MidnightBundlesV2 and the selected ratifier.
|
|
35
|
+
* @param params.account - Non-zero maker that supplies the collateral, names itself on every offer and sends the plan.
|
|
36
|
+
* @param params.offers - Caller-supplied sell-offer tree, or a PriceRatifierV1 or RateRatifierV1 tree creation request.
|
|
37
|
+
* @param params.validation - Optional mempool API request controls; `false` skips the API call.
|
|
38
|
+
* @param params.cancellations - Optional groups and consumed ceilings to cancel atomically with publication; must not overlap the new tree.
|
|
39
|
+
* Omitting it cancels nothing (an untyped JavaScript `null` does too).
|
|
40
|
+
* @param params.collateral.market - Market shared by every offer.
|
|
41
|
+
* @param params.collateral.supplies - Positive collateral supplies; each `collateralIndex` is a zero-based position in ascending collateral token address order, and `assets` is in that token's base units. Entries may repeat an index; their amounts are summed for that token's allowance check.
|
|
42
|
+
* @param params.nativeAmount - Optional native ETH in wei, capped by the wrapped-native collateral pull.
|
|
43
|
+
* @param params.now - Reference Unix timestamp in seconds for plan expiry; omitting it uses the device clock (an untyped JavaScript `null` does too).
|
|
44
|
+
* @param params.expiresAt - Unix seconds. The default is the earlier of now + 2 hours and the first offer expiry minus one second.
|
|
45
|
+
* @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
|
|
46
|
+
* @returns A frozen plan that builds offline from saved steps and opaque offer payload bytes.
|
|
47
|
+
* @throws {InvalidBigIntInputError} If a supplied non-null `now`, a cancellation ceiling, or a collateral
|
|
48
|
+
* index or amount is not a bigint; checked before any request.
|
|
49
|
+
* @throws {ZeroAccountError} If the submitting account is zero.
|
|
50
|
+
* @throws {InvalidTransactionPlanError} If the account is not an address, calldata origin exceeds 1 MiB,
|
|
51
|
+
* or a supplied non-null `cancellations` is not an array or has a non-object entry; checked
|
|
52
|
+
* before any request.
|
|
53
|
+
* @throws {InvalidCalldataOriginError} If the supplied calldata origin is not nonempty, even-length hex.
|
|
54
|
+
* @throws {NonIntegerInputError} If `expiresAt` is not a safe integer.
|
|
55
|
+
* @throws {InvalidMarketParameterError} If the supplied collateral market parameters are invalid.
|
|
56
|
+
* @throws {InvalidTreeError} If the offer tree is empty or invalid.
|
|
57
|
+
* @throws {InvalidTreeHeightError} If the tree exceeds the maximum height.
|
|
58
|
+
* @throws {InvalidMidnightOfferGroupError} If a tree request uses an invalid explicit group.
|
|
59
|
+
* @throws {InvalidMidnightRateRatifierV1RateError} If a Rate V1 request has a negative leaf rate.
|
|
60
|
+
* @throws {InvalidMidnightRateRatifierV1TickError} If a Rate V1 request uses a tick below its minimum.
|
|
61
|
+
* @throws {MidnightOfferMakerMismatchError} If any offer names another maker.
|
|
62
|
+
* @throws {MidnightOfferSideMismatchError} If any offer is a buy offer.
|
|
63
|
+
* @throws {MidnightOfferCallbackNotSupportedError} If an offer names a callback.
|
|
64
|
+
* @throws {MidnightOfferReduceOnlyError} If an offer is reduce-only.
|
|
65
|
+
* @throws {MidnightOfferSellerReceiverMismatchError} If an offer names another proceeds receiver.
|
|
66
|
+
* @throws {MidnightOfferContinuousFeeCapError} If an offer sets a nonzero continuous fee cap.
|
|
67
|
+
* @throws {InvalidMidnightHexInputError} If a cancellation group is not bytes32.
|
|
68
|
+
* @throws {DuplicateMidnightGroupCancellationError} If a cancellation group appears twice.
|
|
69
|
+
* @throws {MidnightReplacementGroupCancelledError} If a cancellation group is also in the new tree.
|
|
70
|
+
* @throws {ExpiredDeadlineError} If the resolved deadline is at or before the reference time or
|
|
71
|
+
* pinned block timestamp, or an offer has expired by the reference time but not at the pinned
|
|
72
|
+
* block; this skips API validation.
|
|
73
|
+
* @throws {MidnightOfferExpiredError} If an offer is already expired at the pinned block timestamp.
|
|
74
|
+
* @throws {MidnightOfferExpiryAfterMaturityError} If an offer expiry exceeds its market maturity.
|
|
75
|
+
* @throws {MidnightOfferGroupConsumedError} If an offer group has no capacity remaining.
|
|
76
|
+
* @throws {MidnightOfferTickSpacingError} If an offer tick is not accessible in its market.
|
|
77
|
+
* @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} If the market fee exceeds an offer's cap.
|
|
78
|
+
* @throws {MidnightOfferZeroPriceSellError} If a sell offer has a zero tick.
|
|
79
|
+
* @throws {MidnightOfferRateBoundUnreachableError} If a Rate V1 offer cannot satisfy its rate bound.
|
|
80
|
+
* @throws {MidnightMarketMaturityTooFarError} If an uncreated market matures more than 100 years after the pinned block timestamp.
|
|
81
|
+
* @throws {MidnightMarketLltvNotEnabledError} If an uncreated market uses a disabled LLTV.
|
|
82
|
+
* @throws {MidnightMarketLiquidationCursorNotEnabledError} If an uncreated market uses a disabled liquidation cursor.
|
|
83
|
+
* @throws {MidnightMarketOracleWithoutCodeError} If an uncreated market's oracle has no code.
|
|
84
|
+
* @throws {MidnightOfferMarketChainMismatchError} If an offer's market uses another chain.
|
|
85
|
+
* @throws {MidnightOfferMarketAddressMismatchError} If an offer's market names another Midnight deployment.
|
|
86
|
+
* @throws {MidnightOfferRatifierMismatchError} If an offer names the wrong ratifier for its tree.
|
|
87
|
+
* @throws {MidnightPayloadDecodeError} If the offers cannot be encoded in the publication payload,
|
|
88
|
+
* including when the encoded payload exceeds its size limit; split the offer tree.
|
|
89
|
+
* @throws {MidnightMempoolValidationError} If optional mempool validation rejects the tree.
|
|
90
|
+
* @throws {MidnightApiError} If API validation returns a non-2xx response.
|
|
91
|
+
* @throws {InvalidMidnightApiResponseError} If the API returns malformed successful validation data.
|
|
92
|
+
* @throws {MarketIdMismatchError} If an offer bound to this chain and Midnight deployment targets another market than `collateral.market`.
|
|
93
|
+
* @throws {EmptyMidnightCollateralSuppliesError} If no collateral supply is specified.
|
|
94
|
+
* @throws {UnknownCollateralIndexError} If a collateral index is not configured in the supplied market.
|
|
95
|
+
* @throws {NonPositiveInputError} If a collateral amount or explicit expiry is not positive.
|
|
96
|
+
* @throws {NegativeInputError} If native funding or a cancellation ceiling is negative.
|
|
97
|
+
* @throws {InputExceedsMaxError} If a supply, per-index sum or cancellation ceiling exceeds uint128, native funding exceeds the wrapped-native pull, or explicit expiry reaches the first offer expiry while every offer is still live at the reference time.
|
|
98
|
+
* @throws {InvalidMidnightNativeAmountTypeError} If `nativeAmount` is not a bigint.
|
|
99
|
+
* @throws {ChainWNativeMissingError} If native funding is requested on a chain without registered wrapped native.
|
|
100
|
+
* @throws {NativeAmountOnNonWNativeAssetError} If native funding is requested without a wrapped-native pull.
|
|
101
|
+
* @throws {MidnightCalldataEncodingError} If the offer tree, collateral market or bundle input cannot be ABI-encoded.
|
|
102
|
+
* @throws {ChainIdMismatchError} If the configured or transport chain differs from `chainId`.
|
|
103
|
+
* @throws {UnsupportedChainIdError} If the chain has no address registry.
|
|
104
|
+
* @throws {UnknownAddressError} If Midnight, the bundle or the selected ratifier is not registered on the chain.
|
|
105
|
+
* @throws {MissingContractCodeError} If a registered write target has no code.
|
|
106
|
+
* @throws {viem.BaseError} If a chain, deployment, offer-state, allowance or authorization read fails.
|
|
107
|
+
* @example
|
|
108
|
+
* ```ts
|
|
109
|
+
* import { buildTransactions, prepareMidnightSupplyCollateralMakeBorrow } from "@morpho-org/morpho-sdk";
|
|
110
|
+
* import { type Offer, Tree } from "@morpho-org/morpho-sdk/midnight/entities";
|
|
111
|
+
* import { type Address, createPublicClient, http } from "viem";
|
|
112
|
+
* import { base } from "viem/chains";
|
|
113
|
+
*
|
|
114
|
+
* async function buildBorrowPublication(first: Offer, rest: readonly Offer[], maker: Address) {
|
|
115
|
+
* const client = createPublicClient({ chain: base, transport: http() });
|
|
116
|
+
* // The maker constructs same-market sell offers naming the Base PriceRatifierV1.
|
|
117
|
+
* const offers = Tree.create({ type: "priceV1", entries: [first, ...rest].map(offer => ({ offer })) });
|
|
118
|
+
* const plan = await prepareMidnightSupplyCollateralMakeBorrow(client, {
|
|
119
|
+
* chainId: base.id, account: maker, offers,
|
|
120
|
+
* collateral: { market: first.market, supplies: [{ collateralIndex: 0n, assets: 1_000_000n }] },
|
|
121
|
+
* now: (await client.getBlock()).timestamp,
|
|
122
|
+
* });
|
|
123
|
+
* // Simulate and send the steps in order from maker.
|
|
124
|
+
* return buildTransactions(plan);
|
|
125
|
+
* }
|
|
126
|
+
* ```
|
|
127
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
128
|
+
*/
|
|
129
|
+
export declare function prepareMidnightSupplyCollateralMakeBorrow(client: Client, params: MidnightSupplyCollateralMakeBorrowPlanParams): Promise<TransactionPlan>;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
|
|
2
|
+
import { parseMidnightApprovalRequirements } from "../../actions/requirements/midnight/getMidnightApprovalRequirements.js";
|
|
3
|
+
import { getTokenRequirements } from "../requirements.js";
|
|
4
|
+
import { prepareMidnightBundleAuthorization } from "./authorization.js";
|
|
5
|
+
import { prepareMidnightMakerPublication, } from "./makerPublication.js";
|
|
6
|
+
import { parseSupplyCollateralMakeBorrowParams } from "./prepare.js";
|
|
7
|
+
const actionId = "midnightSupplyCollateralMakeBorrow";
|
|
8
|
+
/**
|
|
9
|
+
* Prepares one MidnightBundlesV2 call to supply collateral, optionally cancel groups, and
|
|
10
|
+
* activate the maker's Price V1 or Rate V1 offer root without filling an offer or creating debt.
|
|
11
|
+
* Per-token allowance to the bundle is checked against the full pull, even when native ETH funds
|
|
12
|
+
* some wrapped collateral; when it falls short, the plan approves `maxUint256` (capped per token
|
|
13
|
+
* by the SDK), and unused allowance remains after publication. Operator grants remain until
|
|
14
|
+
* revoked; a standalone bundle grant can remain even if publication fails. No signature is requested.
|
|
15
|
+
* Builds the offer tree and checks the offer-capped `expiresAt` first, then validates the
|
|
16
|
+
* publication with the entity `supplyCollateralMakeBorrow` checks through a plan-side
|
|
17
|
+
* constructor, with the market, collateral and native funding checks before any state read. So an
|
|
18
|
+
* input with several errors can fail on another error here than in the entity. The chain and the bundle, Midnight and ratifier code are checked
|
|
19
|
+
* once, right before the first publication-state read. Approvals are checked per
|
|
20
|
+
* token like the entity's `getRequirements()`, summing supplies that pull the same token.
|
|
21
|
+
*
|
|
22
|
+
* @param client - Plain viem client used to validate deployments, offers and prerequisites.
|
|
23
|
+
* @param params - Maker, collateral supplies and the maker's offer tree or tree creation request.
|
|
24
|
+
* @param params.chainId - Chain containing Midnight, MidnightBundlesV2 and the selected ratifier.
|
|
25
|
+
* @param params.account - Non-zero maker that supplies the collateral, names itself on every offer and sends the plan.
|
|
26
|
+
* @param params.offers - Caller-supplied sell-offer tree, or a PriceRatifierV1 or RateRatifierV1 tree creation request.
|
|
27
|
+
* @param params.validation - Optional mempool API request controls; `false` skips the API call.
|
|
28
|
+
* @param params.cancellations - Optional groups and consumed ceilings to cancel atomically with publication; must not overlap the new tree.
|
|
29
|
+
* Omitting it cancels nothing (an untyped JavaScript `null` does too).
|
|
30
|
+
* @param params.collateral.market - Market shared by every offer.
|
|
31
|
+
* @param params.collateral.supplies - Positive collateral supplies; each `collateralIndex` is a zero-based position in ascending collateral token address order, and `assets` is in that token's base units. Entries may repeat an index; their amounts are summed for that token's allowance check.
|
|
32
|
+
* @param params.nativeAmount - Optional native ETH in wei, capped by the wrapped-native collateral pull.
|
|
33
|
+
* @param params.now - Reference Unix timestamp in seconds for plan expiry; omitting it uses the device clock (an untyped JavaScript `null` does too).
|
|
34
|
+
* @param params.expiresAt - Unix seconds. The default is the earlier of now + 2 hours and the first offer expiry minus one second.
|
|
35
|
+
* @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
|
|
36
|
+
* @returns A frozen plan that builds offline from saved steps and opaque offer payload bytes.
|
|
37
|
+
* @throws {InvalidBigIntInputError} If a supplied non-null `now`, a cancellation ceiling, or a collateral
|
|
38
|
+
* index or amount is not a bigint; checked before any request.
|
|
39
|
+
* @throws {ZeroAccountError} If the submitting account is zero.
|
|
40
|
+
* @throws {InvalidTransactionPlanError} If the account is not an address, calldata origin exceeds 1 MiB,
|
|
41
|
+
* or a supplied non-null `cancellations` is not an array or has a non-object entry; checked
|
|
42
|
+
* before any request.
|
|
43
|
+
* @throws {InvalidCalldataOriginError} If the supplied calldata origin is not nonempty, even-length hex.
|
|
44
|
+
* @throws {NonIntegerInputError} If `expiresAt` is not a safe integer.
|
|
45
|
+
* @throws {InvalidMarketParameterError} If the supplied collateral market parameters are invalid.
|
|
46
|
+
* @throws {InvalidTreeError} If the offer tree is empty or invalid.
|
|
47
|
+
* @throws {InvalidTreeHeightError} If the tree exceeds the maximum height.
|
|
48
|
+
* @throws {InvalidMidnightOfferGroupError} If a tree request uses an invalid explicit group.
|
|
49
|
+
* @throws {InvalidMidnightRateRatifierV1RateError} If a Rate V1 request has a negative leaf rate.
|
|
50
|
+
* @throws {InvalidMidnightRateRatifierV1TickError} If a Rate V1 request uses a tick below its minimum.
|
|
51
|
+
* @throws {MidnightOfferMakerMismatchError} If any offer names another maker.
|
|
52
|
+
* @throws {MidnightOfferSideMismatchError} If any offer is a buy offer.
|
|
53
|
+
* @throws {MidnightOfferCallbackNotSupportedError} If an offer names a callback.
|
|
54
|
+
* @throws {MidnightOfferReduceOnlyError} If an offer is reduce-only.
|
|
55
|
+
* @throws {MidnightOfferSellerReceiverMismatchError} If an offer names another proceeds receiver.
|
|
56
|
+
* @throws {MidnightOfferContinuousFeeCapError} If an offer sets a nonzero continuous fee cap.
|
|
57
|
+
* @throws {InvalidMidnightHexInputError} If a cancellation group is not bytes32.
|
|
58
|
+
* @throws {DuplicateMidnightGroupCancellationError} If a cancellation group appears twice.
|
|
59
|
+
* @throws {MidnightReplacementGroupCancelledError} If a cancellation group is also in the new tree.
|
|
60
|
+
* @throws {ExpiredDeadlineError} If the resolved deadline is at or before the reference time or
|
|
61
|
+
* pinned block timestamp, or an offer has expired by the reference time but not at the pinned
|
|
62
|
+
* block; this skips API validation.
|
|
63
|
+
* @throws {MidnightOfferExpiredError} If an offer is already expired at the pinned block timestamp.
|
|
64
|
+
* @throws {MidnightOfferExpiryAfterMaturityError} If an offer expiry exceeds its market maturity.
|
|
65
|
+
* @throws {MidnightOfferGroupConsumedError} If an offer group has no capacity remaining.
|
|
66
|
+
* @throws {MidnightOfferTickSpacingError} If an offer tick is not accessible in its market.
|
|
67
|
+
* @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} If the market fee exceeds an offer's cap.
|
|
68
|
+
* @throws {MidnightOfferZeroPriceSellError} If a sell offer has a zero tick.
|
|
69
|
+
* @throws {MidnightOfferRateBoundUnreachableError} If a Rate V1 offer cannot satisfy its rate bound.
|
|
70
|
+
* @throws {MidnightMarketMaturityTooFarError} If an uncreated market matures more than 100 years after the pinned block timestamp.
|
|
71
|
+
* @throws {MidnightMarketLltvNotEnabledError} If an uncreated market uses a disabled LLTV.
|
|
72
|
+
* @throws {MidnightMarketLiquidationCursorNotEnabledError} If an uncreated market uses a disabled liquidation cursor.
|
|
73
|
+
* @throws {MidnightMarketOracleWithoutCodeError} If an uncreated market's oracle has no code.
|
|
74
|
+
* @throws {MidnightOfferMarketChainMismatchError} If an offer's market uses another chain.
|
|
75
|
+
* @throws {MidnightOfferMarketAddressMismatchError} If an offer's market names another Midnight deployment.
|
|
76
|
+
* @throws {MidnightOfferRatifierMismatchError} If an offer names the wrong ratifier for its tree.
|
|
77
|
+
* @throws {MidnightPayloadDecodeError} If the offers cannot be encoded in the publication payload,
|
|
78
|
+
* including when the encoded payload exceeds its size limit; split the offer tree.
|
|
79
|
+
* @throws {MidnightMempoolValidationError} If optional mempool validation rejects the tree.
|
|
80
|
+
* @throws {MidnightApiError} If API validation returns a non-2xx response.
|
|
81
|
+
* @throws {InvalidMidnightApiResponseError} If the API returns malformed successful validation data.
|
|
82
|
+
* @throws {MarketIdMismatchError} If an offer bound to this chain and Midnight deployment targets another market than `collateral.market`.
|
|
83
|
+
* @throws {EmptyMidnightCollateralSuppliesError} If no collateral supply is specified.
|
|
84
|
+
* @throws {UnknownCollateralIndexError} If a collateral index is not configured in the supplied market.
|
|
85
|
+
* @throws {NonPositiveInputError} If a collateral amount or explicit expiry is not positive.
|
|
86
|
+
* @throws {NegativeInputError} If native funding or a cancellation ceiling is negative.
|
|
87
|
+
* @throws {InputExceedsMaxError} If a supply, per-index sum or cancellation ceiling exceeds uint128, native funding exceeds the wrapped-native pull, or explicit expiry reaches the first offer expiry while every offer is still live at the reference time.
|
|
88
|
+
* @throws {InvalidMidnightNativeAmountTypeError} If `nativeAmount` is not a bigint.
|
|
89
|
+
* @throws {ChainWNativeMissingError} If native funding is requested on a chain without registered wrapped native.
|
|
90
|
+
* @throws {NativeAmountOnNonWNativeAssetError} If native funding is requested without a wrapped-native pull.
|
|
91
|
+
* @throws {MidnightCalldataEncodingError} If the offer tree, collateral market or bundle input cannot be ABI-encoded.
|
|
92
|
+
* @throws {ChainIdMismatchError} If the configured or transport chain differs from `chainId`.
|
|
93
|
+
* @throws {UnsupportedChainIdError} If the chain has no address registry.
|
|
94
|
+
* @throws {UnknownAddressError} If Midnight, the bundle or the selected ratifier is not registered on the chain.
|
|
95
|
+
* @throws {MissingContractCodeError} If a registered write target has no code.
|
|
96
|
+
* @throws {viem.BaseError} If a chain, deployment, offer-state, allowance or authorization read fails.
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* import { buildTransactions, prepareMidnightSupplyCollateralMakeBorrow } from "@morpho-org/morpho-sdk";
|
|
100
|
+
* import { type Offer, Tree } from "@morpho-org/morpho-sdk/midnight/entities";
|
|
101
|
+
* import { type Address, createPublicClient, http } from "viem";
|
|
102
|
+
* import { base } from "viem/chains";
|
|
103
|
+
*
|
|
104
|
+
* async function buildBorrowPublication(first: Offer, rest: readonly Offer[], maker: Address) {
|
|
105
|
+
* const client = createPublicClient({ chain: base, transport: http() });
|
|
106
|
+
* // The maker constructs same-market sell offers naming the Base PriceRatifierV1.
|
|
107
|
+
* const offers = Tree.create({ type: "priceV1", entries: [first, ...rest].map(offer => ({ offer })) });
|
|
108
|
+
* const plan = await prepareMidnightSupplyCollateralMakeBorrow(client, {
|
|
109
|
+
* chainId: base.id, account: maker, offers,
|
|
110
|
+
* collateral: { market: first.market, supplies: [{ collateralIndex: 0n, assets: 1_000_000n }] },
|
|
111
|
+
* now: (await client.getBlock()).timestamp,
|
|
112
|
+
* });
|
|
113
|
+
* // Simulate and send the steps in order from maker.
|
|
114
|
+
* return buildTransactions(plan);
|
|
115
|
+
* }
|
|
116
|
+
* ```
|
|
117
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
118
|
+
*/
|
|
119
|
+
export async function prepareMidnightSupplyCollateralMakeBorrow(client, params) {
|
|
120
|
+
const { chainId, account, collateral, nativeAmount } = params;
|
|
121
|
+
const { parsed, inputs, calldataOrigin } = await prepareMidnightMakerPublication(client, {
|
|
122
|
+
params,
|
|
123
|
+
parse: (raw, context) => parseSupplyCollateralMakeBorrowParams({ ...raw, collateral, nativeAmount }, context),
|
|
124
|
+
});
|
|
125
|
+
const spender = getChainAddress(chainId, "midnightBundlesV2");
|
|
126
|
+
const pulls = new Map();
|
|
127
|
+
for (const { token, assets } of parsed.action.collateralPulls) {
|
|
128
|
+
pulls.set(token, (pulls.get(token) ?? 0n) + assets);
|
|
129
|
+
}
|
|
130
|
+
const [prerequisites, authorization] = await Promise.all([
|
|
131
|
+
Promise.all([...pulls].map(([token, amount], tokenIndex) => {
|
|
132
|
+
// Validation only; the entity checks the same per-token bound in getRequirements().
|
|
133
|
+
parseMidnightApprovalRequirements({
|
|
134
|
+
viemClient: client,
|
|
135
|
+
chainId,
|
|
136
|
+
token,
|
|
137
|
+
owner: account,
|
|
138
|
+
spender,
|
|
139
|
+
amount,
|
|
140
|
+
});
|
|
141
|
+
return getTokenRequirements(client, {
|
|
142
|
+
chainId,
|
|
143
|
+
owner: account,
|
|
144
|
+
token,
|
|
145
|
+
spender,
|
|
146
|
+
amount,
|
|
147
|
+
approvalId: (index) => `${actionId}:approval:${tokenIndex}:${index}`,
|
|
148
|
+
});
|
|
149
|
+
})),
|
|
150
|
+
prepareMidnightBundleAuthorization(client, { chainId, account }),
|
|
151
|
+
]);
|
|
152
|
+
return deepFreeze({
|
|
153
|
+
version: 2,
|
|
154
|
+
chainId,
|
|
155
|
+
account,
|
|
156
|
+
expiresAt: Number(inputs.deadline),
|
|
157
|
+
...(calldataOrigin && { calldataOrigin }),
|
|
158
|
+
steps: [
|
|
159
|
+
...prerequisites.flatMap(({ approvals }) => approvals),
|
|
160
|
+
...(authorization === undefined ? [] : [authorization]),
|
|
161
|
+
{
|
|
162
|
+
id: actionId,
|
|
163
|
+
label: "Supply collateral and publish Midnight borrow offers",
|
|
164
|
+
action: {
|
|
165
|
+
type: actionId,
|
|
166
|
+
inputs: {
|
|
167
|
+
...inputs,
|
|
168
|
+
collateral: parsed.collateral,
|
|
169
|
+
...(nativeAmount !== undefined && { nativeAssets: nativeAmount }),
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
],
|
|
174
|
+
signatureRequests: [],
|
|
175
|
+
});
|
|
176
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { IMarketParams } from "@morpho-org/midnight-sdk";
|
|
2
|
+
import type { Client } from "viem";
|
|
3
|
+
import { type ReferenceTimestampParams } from "../../types/index.js";
|
|
4
|
+
import { type IntentParams } from "../intent.js";
|
|
5
|
+
import type { Action, TransactionPlan } from "../types.js";
|
|
6
|
+
type SupplyCollateralWithNativeAction = Extract<Action, {
|
|
7
|
+
type: "midnightSupplyCollateralWithNative";
|
|
8
|
+
}>;
|
|
9
|
+
/**
|
|
10
|
+
* Represents an intent to wrap native currency and supply it as wNative collateral to the
|
|
11
|
+
* submitting account's Midnight position through MidnightBundlesV2.
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import type { MidnightSupplyCollateralWithNativePlanParams } from "@morpho-org/morpho-sdk";
|
|
15
|
+
* const fullyNative = (params: MidnightSupplyCollateralWithNativePlanParams) =>
|
|
16
|
+
* ({ ...params, nativeAmount: params.collateralAssets });
|
|
17
|
+
* ```
|
|
18
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
19
|
+
*/
|
|
20
|
+
export interface MidnightSupplyCollateralWithNativePlanParams extends Pick<IntentParams, "chainId" | "account" | "expiresAt" | "calldataOrigin">, ReferenceTimestampParams {
|
|
21
|
+
/** Market configuration on the target chain. */
|
|
22
|
+
readonly market: IMarketParams;
|
|
23
|
+
/** Index of the registered wNative collateral in Midnight's token-address order; defaults to `0n`. */
|
|
24
|
+
readonly collateralIndex?: bigint;
|
|
25
|
+
/** Positive total collateral to supply, in wNative base units. */
|
|
26
|
+
readonly collateralAssets: bigint;
|
|
27
|
+
/** Positive native amount in wei sent as transaction value and wrapped, at most `collateralAssets`. */
|
|
28
|
+
readonly nativeAmount: bigint;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Prepares a payable MidnightBundlesV2 collateral supply that wraps native currency, with no
|
|
32
|
+
* borrow or offer. Inputs go through `parseMidnightSupplyCollateralWithNative`, which applies
|
|
33
|
+
* the checks of the `midnightSupplyCollateralWithNative` builder the entity uses, in the same
|
|
34
|
+
* order, without encoding the call. The bundle wraps `nativeAmount` into wNative for the sender
|
|
35
|
+
* and pulls `collateralAssets` from the sender, so the plan adds an ERC-20 approval to
|
|
36
|
+
* MidnightBundlesV2 for the full collateral amount when the allowance is insufficient, even with
|
|
37
|
+
* full native funding, as the entity does. It adds the standalone bundle authorization only when
|
|
38
|
+
* missing and never requests signatures. The bundle enforces the plan expiry as its deadline.
|
|
39
|
+
* The plan reads no balances: the wallet needs `collateralAssets - nativeAmount` wNative plus the
|
|
40
|
+
* native value and gas, so simulate every step together before asking for the first approval.
|
|
41
|
+
* Unlike the entity, the allowance check keeps no `reservedCollateralAssets` reserve, so the
|
|
42
|
+
* supply can consume an allowance another operation relies on.
|
|
43
|
+
* @param client - Viem client used to check the network and deployments and read prerequisites.
|
|
44
|
+
* @param params - Market, wNative collateral selection, total amount, native funding and sending account.
|
|
45
|
+
* @param params.chainId - Chain containing the market, Midnight core and MidnightBundlesV2.
|
|
46
|
+
* @param params.account - Non-zero account that sends the value and receives the collateral position.
|
|
47
|
+
* @param params.market - Market configuration on the target chain.
|
|
48
|
+
* @param params.collateralIndex - Index of the registered wNative collateral in token-address order. Defaults to `0n`.
|
|
49
|
+
* @param params.collateralAssets - Positive total collateral in wNative base units.
|
|
50
|
+
* @param params.nativeAmount - Positive native funding in wei, at most `collateralAssets`; any rest is pulled as wNative.
|
|
51
|
+
* @param params.now - Reference Unix timestamp in seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
|
|
52
|
+
* @param params.expiresAt - Bundle execution deadline in Unix seconds; defaults to two hours after `now`.
|
|
53
|
+
* @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
|
|
54
|
+
* @returns A frozen plan whose steps must be submitted in order from `params.account`.
|
|
55
|
+
* @throws {InvalidBigIntInputError} If a supplied non-null `now`, the collateral amount or the index is not a bigint; checked before any request.
|
|
56
|
+
* @throws {ZeroAccountError} If the account is the zero address.
|
|
57
|
+
* @throws {NonIntegerInputError} If expiry is not a safe integer.
|
|
58
|
+
* @throws {ExpiredDeadlineError} If expiry is at or before the reference time.
|
|
59
|
+
* @throws {InvalidCalldataOriginError} If attribution bytes are empty or malformed.
|
|
60
|
+
* @throws {InvalidTransactionPlanError} If the account is malformed or attribution exceeds 1 MiB.
|
|
61
|
+
* @throws {NonPositiveInputError} If the collateral amount, native amount or expiry is not positive.
|
|
62
|
+
* @throws {InputExceedsMaxError} If the collateral amount exceeds uint128 or the native amount exceeds the collateral amount.
|
|
63
|
+
* @throws {ChainIdMismatchError} If the market, client or RPC targets another chain.
|
|
64
|
+
* @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
|
|
65
|
+
* @throws {InvalidMarketParameterError} If the market's chain ID or collateral configuration is invalid.
|
|
66
|
+
* @throws {MidnightCalldataEncodingError} If market fields cannot be ABI-encoded.
|
|
67
|
+
* @throws {UnknownCollateralIndexError} If the index is not configured on the market.
|
|
68
|
+
* @throws {InvalidMidnightNativeAmountTypeError} If `nativeAmount` is not a bigint.
|
|
69
|
+
* @throws {NegativeInputError} If `nativeAmount` is negative.
|
|
70
|
+
* @throws {ChainWNativeMissingError} If the chain has no wrapped-native asset.
|
|
71
|
+
* @throws {NativeAmountOnNonWNativeAssetError} If the selected collateral is not wNative.
|
|
72
|
+
* @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
|
|
73
|
+
* @throws {UnknownAddressError} If Midnight core or MidnightBundlesV2 is not registered on the chain.
|
|
74
|
+
* @throws {MissingContractCodeError} If the registered bundle or Midnight core has no deployed code.
|
|
75
|
+
* @throws {viem.BaseError} If the chain ID, bytecode, allowance or authorization read fails.
|
|
76
|
+
* @example
|
|
77
|
+
* ```ts
|
|
78
|
+
* import {
|
|
79
|
+
* buildTransactions,
|
|
80
|
+
* prepareMidnightSupplyCollateralWithNative,
|
|
81
|
+
* type TransactionPlan,
|
|
82
|
+
* } from "@morpho-org/morpho-sdk";
|
|
83
|
+
* import { fetchMidnightMarketParams } from "@morpho-org/morpho-sdk/fetch";
|
|
84
|
+
* import { type Address, type Hash, createPublicClient, http } from "viem";
|
|
85
|
+
* import { base } from "viem/chains";
|
|
86
|
+
*
|
|
87
|
+
* // `collateralIndex` is the position of the chain's wNative in the market's collaterals.
|
|
88
|
+
* async function prepareNativeCollateralSupply(
|
|
89
|
+
* account: Address,
|
|
90
|
+
* marketId: Hash,
|
|
91
|
+
* collateralIndex: bigint,
|
|
92
|
+
* ) {
|
|
93
|
+
* const client = createPublicClient({ chain: base, transport: http() });
|
|
94
|
+
* const market = await fetchMidnightMarketParams(client, { marketId });
|
|
95
|
+
* const plan: TransactionPlan = await prepareMidnightSupplyCollateralWithNative(client, {
|
|
96
|
+
* chainId: base.id,
|
|
97
|
+
* account,
|
|
98
|
+
* market,
|
|
99
|
+
* collateralIndex,
|
|
100
|
+
* collateralAssets: 1_000_000_000_000_000n,
|
|
101
|
+
* nativeAmount: 1_000_000_000_000_000n,
|
|
102
|
+
* });
|
|
103
|
+
* // plan.steps: any wNative approval to MidnightBundlesV2, any bundle authorization, then
|
|
104
|
+
* // "midnightSupplyCollateralWithNative". Send them in order from plan.account on plan.chainId.
|
|
105
|
+
* return buildTransactions(plan);
|
|
106
|
+
* }
|
|
107
|
+
* ```
|
|
108
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
109
|
+
*/
|
|
110
|
+
export declare function prepareMidnightSupplyCollateralWithNative(client: Client, params: MidnightSupplyCollateralWithNativePlanParams): Promise<TransactionPlan>;
|
|
111
|
+
/** @internal Encodes only the persisted inputs; no client or clock is needed. */
|
|
112
|
+
export declare function buildMidnightSupplyCollateralWithNative({ inputs, }: SupplyCollateralWithNativeAction): Readonly<import("../../types/action.js").Transaction<import("../../types/action.js").MidnightSupplyCollateralWithNativeAction>>;
|
|
113
|
+
/** @internal Validates the stored native collateral supply recipe without RPC. */
|
|
114
|
+
export declare function validateMidnightSupplyCollateralWithNativePlanAction(action: Record<string, unknown>, path: string): void;
|
|
115
|
+
export {};
|