@morpho-org/calldata-verifier 0.2.0 → 0.3.1-next.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 +8 -4
- package/lib/cjs/blue.js +8 -9
- package/lib/cjs/midnight.d.ts +47 -0
- package/lib/cjs/midnight.js +6 -2
- package/lib/cjs/midnightMakers.d.ts +17 -0
- package/lib/cjs/midnightMakers.js +383 -0
- package/lib/cjs/midnightOffers.d.ts +0 -5
- package/lib/cjs/midnightOffers.js +0 -7
- package/lib/cjs/verifyCalldata.js +2 -0
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/esm/blue.js +8 -9
- package/lib/esm/midnight.d.ts +47 -0
- package/lib/esm/midnight.js +6 -4
- package/lib/esm/midnightMakers.d.ts +17 -0
- package/lib/esm/midnightMakers.js +380 -0
- package/lib/esm/midnightOffers.d.ts +0 -5
- package/lib/esm/midnightOffers.js +1 -8
- package/lib/esm/verifyCalldata.js +2 -0
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -19,13 +19,14 @@ Use [`@morpho-org/evm-simulation`](../evm-simulation) for execution-dependent ch
|
|
|
19
19
|
- Whether the caller-supplied Vault `asset` matches the actual `vault.asset()`. Read `vault.asset()` at the pinned block and compare it with `asset`. For deposits and standard withdrawals or redemptions, typed-input simulation can establish an exact match if you pass a canonical ERC-20 address as the token override (`assetPaid` for deposits, `assetReceived` for exits). Simulation also accepts `ethAddress` for a vault whose asset is the chain's wrapped-native token, so use the pinned read if your source might supply a native alias. Force withdrawals, force redemptions, and in-kind redemptions do not support typed inputs; use the pinned read for those. Quote-only limits can accept a token override without comparing it with `vault.asset()`.
|
|
20
20
|
- Whether existing onchain allowances suffice and whether a call succeeds or reverts.
|
|
21
21
|
- Blue ERC-20 repay by shares or for all debt: before signing, compare the decoded `maxRepayAssets`, which is `args[3]` of the verified `blueBundlesV1RepayAndWithdrawCollateral` call, against an independently chosen funding cap. Apply this check whenever that call's `value` is zero, including for requests that allowed native funding, because such requests don't have to use it. Simulating net spend does not bound the upfront pull because unused funds can be refunded.
|
|
22
|
-
- Blue public-allocator reallocations: the verifier checks zero penalty, the destination market and loan token, positive
|
|
22
|
+
- Blue public-allocator reallocations: the verifier checks each leg in calldata order for zero penalty, the destination market and loan token, a positive amount, and nonzero vault and destination adapter addresses. Market-funded legs require a nonzero source adapter and may revisit a route. Idle-funded legs require a zero source adapter and must be unique per vault and destination adapter. Adapter eligibility, whether a reallocation is needed, and whether its source and amount are appropriate require onchain checks.
|
|
23
23
|
- Blue embedded Morpho authorizations: the verifier checks signature structure. The bundle supplies the transaction sender and its own address as the authorizer and authorized spender; signature validity, nonce and expiry are execution checks.
|
|
24
24
|
- Midnight full direct repays, and units-target lends, market repays and `midnight.take_lend` takes: compare the decoded `maxBuyerAssets` against an independently chosen upfront funding cap before signing. For full direct repays, this applies to ERC-20, native, and auto funding: when ETH is sent, the bundle wraps it to the signer's balance and then pulls the encoded `maxBuyerAssets` from that wrapped-native balance. `max_native_assets` caps only the ETH sent, not the token pull. For the units-target cases, you can instead set a `max_assets` guard to enforce the upfront funding cap. Simulation's `assetsPaid` measures net spend after refunds, not the upfront pull.
|
|
25
25
|
- Midnight buy bundles for lend, market repay, and `midnight.take_lend`: the verifier does not bound the encoded `maxContinuousFee`. Compare it with an independently chosen ceiling. To check the market's actual fee against that ceiling, read Midnight's `continuousFee(marketId)` at the simulation block or use a simulation `assertBefore` view call.
|
|
26
26
|
- Midnight fill prices under a `slippage` guard: the secondary bound and offer ticks depend on the onchain price. Check the resulting fill price in simulation.
|
|
27
27
|
- Midnight borrow takes withdraw available existing credit first and may succeed without filling the requested offer. If a fill is required, verify it in simulation.
|
|
28
|
-
- Midnight
|
|
28
|
+
- Midnight take ratification: for takes, the verifier does not check roots, proofs, or ratifier data. Midnight checks ratification at execution.
|
|
29
|
+
- Midnight maker state: whether offer markets exist, their tick spacing, whether the published group is already consumed or cancelled, and existing allowances. Midnight checks these at execution or when offers are taken.
|
|
29
30
|
|
|
30
31
|
## Usage
|
|
31
32
|
|
|
@@ -53,7 +54,7 @@ For Blue and Midnight, pass the market ID as `market` and the chain separately a
|
|
|
53
54
|
|
|
54
55
|
- Submit only the verified calls, in order, from `account` on `chain_id`. Calldata does not identify the signer or the network; some Vault calls pay the caller directly.
|
|
55
56
|
- For `amount.unit: "all"`, the owner and every recipient (including any referral recipient) must be `account`. The verifier does not compare a concrete share or asset amount, so a withdrawal may return less than the full balance.
|
|
56
|
-
- An approval's spender must match the main call's target. A positive approval included in the response must cover the encoded pull where the amount is available: at least the encoded assets on Vault deposits, or at least the encoded shares on share-unit and `"all"` Vault withdrawals. An unlimited approval is accepted. A zero reset must immediately precede a positive approval for the same token and spender.
|
|
57
|
+
- An approval's spender must match the main call's target, except where an action's section names another spender (Midnight maker lend and repay approve Midnight core). A positive approval included in the response must cover the encoded pull where the amount is available: at least the encoded assets on Vault deposits, or at least the encoded shares on share-unit and `"all"` Vault withdrawals. An unlimited approval is accepted. A zero reset must immediately precede a positive approval for the same token and spender.
|
|
57
58
|
- Nonzero native value must be authorized by the request's `funding.max_native_assets`. The verifier does not require a native-capable request to use native funds.
|
|
58
59
|
- Blue reallocations with a nonzero penalty are rejected.
|
|
59
60
|
- Midnight accepts `slippage` or no guard, and checks explicit `min_units`/`max_assets` on buys and `max_units`/`min_assets` on sells and direct withdrawals. Unknown and wrong-side guards throw `CalldataUnsupportedError`.
|
|
@@ -96,4 +97,7 @@ Verification stays synchronous and throws `CalldataProofError` if the signature,
|
|
|
96
97
|
|
|
97
98
|
- For takes, pass `group` from the original path and `market_id` from the request. Group IDs are scoped to a maker: without `maker`, the group alone does not identify the offer, and the verifier only checks that all fills use one maker. Takes without a caller-known market ID or with a reduce-only maker fill throw `CalldataUnsupportedError`. Use an explicit amount guard to enforce a minimum or maximum on the other side of the trade.
|
|
98
99
|
- Funding withdrawals must pay `account` from the original `funding_address` and `funding_market`. The request has no amount: the verifier checks for a positive share withdrawal, not that it empties the position.
|
|
99
|
-
-
|
|
100
|
+
- `midnight.make_lend`, `make_borrow`, `make_repay` and `make_withdraw` must call `MidnightBundlesV2.midnightBundlesV2CancelAndMake` with the chain's `priceRatifierV1` or `rateRatifierV1` for `offers.type`, no delegated root signature, no cancellations, a nonzero deadline, and no Blue parking unless `make_lend` is funded from a variable-rate market. The verifier decompresses the published payload, rebuilds the offer tree from it, and requires its root to equal the activated root, so the payload is exactly the set of offers the call activates. A payload with an attribution suffix is rejected. Decoding stops at the number of request entries, so a payload with extra offers is rejected before its items are ABI-decoded.
|
|
101
|
+
- Each published offer must match the request entry at the same index: `account` as maker, the entry's `market_id` on the intended chain and Midnight deployment, `starts_at` and `expires_at`, the entry's `tick` when given, and for rate offers a ratified rate equal to `rate_wad`. On rate offers only `rate_wad` is binding: the root commits to the rate, not the tick, so a request `tick` is only compared with the published payload. Use price offers when the exact tick matters. Lend and repay offers buy; borrow and withdraw offers sell and pay `account`. Lend and borrow cap `maxAssets` at `amount`, except variable-rate funded lend, whose offers carry an unbounded `maxAssets` (`2^128 - 1`) because the parked Blue position bounds what the callback can fund; repay and withdraw are reduce-only and cap `maxUnits` at `amount`. Offers carry no taker restriction or continuous-fee cap and, except on variable-rate funded lend, no callback, and share the group derived from their leaves.
|
|
102
|
+
- Lend and repay may include an approval of the offers' loan token to Midnight, at least `amount` for lend. `make_borrow` with `collateral_supplies` must supply exactly that collateral on the offers' market, with native value up to the wrapped-native collateral amount and `funding.max_native_assets`; without it, the call must encode no collateral and no value.
|
|
103
|
+
- `make_lend` with `funding_source.type: "variable_rate_market"` must park exactly `amount` on the Blue market whose id is `funding_source.market_id` and whose loan token is the offers' loan token. The callback salt must be the group id of the callback-free offers the backend builds first: the published offers with their callback cleared and `maxAssets` set back to `amount`. Every offer must name the maker's `BlueBuyCallback` (the CREATE2 address the chain's `midnightBlueBuyCallbackFactory` derives for `account` and that salt) with `abi.encode(blueMarket)` as callback data. The loan-token approval names `MidnightBundlesV2`, not Midnight, and covers at least `amount`: the bundle wraps the native value for the maker and still pulls the full parked amount. Native value is accepted only on a wrapped-native loan token, up to `amount` and `funding.max_native_assets`. Whether the Blue market exists is left to EVM simulation. Any other `funding_source.type` throws `CalldataUnsupportedError`.
|
package/lib/cjs/blue.js
CHANGED
|
@@ -61,28 +61,27 @@ function requireMarket(params, { chainId, selector, call, field = "market", }) {
|
|
|
61
61
|
}
|
|
62
62
|
function requireReallocations(entries, { params, call }) {
|
|
63
63
|
const expected = marketId(params);
|
|
64
|
-
const
|
|
64
|
+
const idleDestinations = new Set();
|
|
65
65
|
for (const entry of entries) {
|
|
66
|
-
const source = marketId(entry.sourceMarketParams);
|
|
67
66
|
const destination = `${entry.vault}:${entry.adapter}`;
|
|
68
|
-
const route = entry.fromIdle
|
|
69
|
-
? destination
|
|
70
|
-
: `${destination}:${entry.sourceAdapter}:${source}`;
|
|
71
67
|
if (entry.penalty !== 0n) {
|
|
72
68
|
throw new errors_js_1.CalldataFeeError("reallocations.penalty", call.id);
|
|
73
69
|
}
|
|
74
70
|
if (entry.assets === 0n ||
|
|
75
|
-
used.has(route) ||
|
|
76
71
|
(0, checks_js_1.sameAddress)(entry.vault, viem_1.zeroAddress) ||
|
|
77
72
|
(0, checks_js_1.sameAddress)(entry.adapter, viem_1.zeroAddress) ||
|
|
78
73
|
marketId(entry.marketParams) !== expected ||
|
|
79
74
|
!(0, checks_js_1.sameAddress)(entry.sourceMarketParams.loanToken, params.loanToken) ||
|
|
80
75
|
(entry.fromIdle
|
|
81
|
-
? !(0, checks_js_1.sameAddress)(entry.sourceAdapter, viem_1.zeroAddress)
|
|
82
|
-
|
|
76
|
+
? !(0, checks_js_1.sameAddress)(entry.sourceAdapter, viem_1.zeroAddress) ||
|
|
77
|
+
idleDestinations.has(destination)
|
|
78
|
+
: (0, checks_js_1.sameAddress)(entry.sourceAdapter, viem_1.zeroAddress) ||
|
|
79
|
+
marketId(entry.sourceMarketParams) === expected)) {
|
|
83
80
|
throw new errors_js_1.CalldataCallError("reallocations", call.id);
|
|
84
81
|
}
|
|
85
|
-
|
|
82
|
+
if (entry.fromIdle) {
|
|
83
|
+
idleDestinations.add(destination);
|
|
84
|
+
}
|
|
86
85
|
}
|
|
87
86
|
}
|
|
88
87
|
function requirePositionAmount(amount, { assets, shares, call, }) {
|
package/lib/cjs/midnight.d.ts
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
|
+
import { midnightBundlesV2Abi } from "@morpho-org/midnight-sdk";
|
|
1
2
|
import type { ChainAddresses } from "@morpho-org/morpho-ts";
|
|
3
|
+
import { type Address } from "viem";
|
|
4
|
+
import { decode } from "./checks.js";
|
|
2
5
|
import type { CalldataCall, DecodedCalldataCall, MidnightMarketIntent, MidnightTakeIntent } from "./types.js";
|
|
3
6
|
type Intent = MidnightMarketIntent | MidnightTakeIntent;
|
|
7
|
+
type BundleCall = ReturnType<typeof decode<typeof midnightBundlesV2Abi>>;
|
|
8
|
+
type Transfer = {
|
|
9
|
+
readonly collateralIndex: bigint;
|
|
10
|
+
readonly assets: bigint;
|
|
11
|
+
};
|
|
12
|
+
type TokenPull = {
|
|
13
|
+
readonly token: Address;
|
|
14
|
+
readonly assets: bigint;
|
|
15
|
+
readonly spender?: Address;
|
|
16
|
+
};
|
|
17
|
+
type RequestedTransfer = {
|
|
18
|
+
readonly collateral: {
|
|
19
|
+
readonly address: Address;
|
|
20
|
+
};
|
|
21
|
+
readonly amount: {
|
|
22
|
+
readonly unit: "all";
|
|
23
|
+
} | {
|
|
24
|
+
readonly unit: "assets";
|
|
25
|
+
readonly value: string;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
type Market = Extract<BundleCall, {
|
|
29
|
+
functionName: "midnightBundlesV2BuyWithAssetsTargetAndWithdrawCollateral";
|
|
30
|
+
}>["args"][0];
|
|
31
|
+
/** @internal */
|
|
32
|
+
export declare function checkCollateral(transfers: readonly Transfer[], { requested, market, call, withdrawal, }: {
|
|
33
|
+
requested: readonly RequestedTransfer[];
|
|
34
|
+
market: Market;
|
|
35
|
+
call: CalldataCall;
|
|
36
|
+
withdrawal?: "core" | "bundle";
|
|
37
|
+
}): {
|
|
38
|
+
token: `0x${string}`;
|
|
39
|
+
assets: bigint;
|
|
40
|
+
}[];
|
|
41
|
+
/** @internal */
|
|
42
|
+
export declare function checkPrerequisites(calls: readonly CalldataCall[], { intent, chain, call: main, pulls, allowAuthorization, }: {
|
|
43
|
+
readonly intent: {
|
|
44
|
+
readonly account: Address;
|
|
45
|
+
};
|
|
46
|
+
readonly chain: ChainAddresses;
|
|
47
|
+
readonly call: CalldataCall;
|
|
48
|
+
readonly pulls: readonly TokenPull[];
|
|
49
|
+
readonly allowAuthorization: boolean;
|
|
50
|
+
}): DecodedCalldataCall[];
|
|
4
51
|
declare function verifyMidnight(intent: Intent, { calls, chain, }: {
|
|
5
52
|
readonly calls: readonly CalldataCall[];
|
|
6
53
|
readonly chain: ChainAddresses;
|
package/lib/cjs/midnight.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.midnightRules = void 0;
|
|
4
|
+
exports.checkCollateral = checkCollateral;
|
|
5
|
+
exports.checkPrerequisites = checkPrerequisites;
|
|
4
6
|
const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
|
|
5
7
|
const viem_1 = require("viem");
|
|
6
8
|
const checks_js_1 = require("./checks.js");
|
|
@@ -46,6 +48,7 @@ function assetsMatch(assets, { requested, withdrawal, call, }) {
|
|
|
46
48
|
field: "collateral.amount",
|
|
47
49
|
});
|
|
48
50
|
}
|
|
51
|
+
/** @internal */
|
|
49
52
|
function checkCollateral(transfers, { requested, market, call, withdrawal, }) {
|
|
50
53
|
if (!Array.isArray(requested) || transfers.length !== requested.length) {
|
|
51
54
|
throw new errors_js_1.CalldataCallError("collateral", call.id);
|
|
@@ -69,6 +72,7 @@ function noValue(call) {
|
|
|
69
72
|
field: "value",
|
|
70
73
|
});
|
|
71
74
|
}
|
|
75
|
+
/** @internal */
|
|
72
76
|
function checkPrerequisites(calls, { intent, chain, call: main, pulls, allowAuthorization, }) {
|
|
73
77
|
let authorized = false;
|
|
74
78
|
const approved = new Map();
|
|
@@ -98,9 +102,9 @@ function checkPrerequisites(calls, { intent, chain, call: main, pulls, allowAuth
|
|
|
98
102
|
if (pull == null) {
|
|
99
103
|
throw new errors_js_1.CalldataTargetError("approval.token", call.id);
|
|
100
104
|
}
|
|
101
|
-
const { token, assets } = pull;
|
|
105
|
+
const { token, assets, spender = main.to } = pull;
|
|
102
106
|
const verified = (0, checks_js_1.approval)(call, {
|
|
103
|
-
spender
|
|
107
|
+
spender,
|
|
104
108
|
token,
|
|
105
109
|
minAmount: assets,
|
|
106
110
|
allowReset: (0, checks_js_1.sameAddress)(calls[index + 1]?.to, token),
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ChainAddresses } from "@morpho-org/morpho-ts";
|
|
2
|
+
import type { CalldataCall, DecodedCalldataCall, MidnightOfferManagementIntent } from "./types.js";
|
|
3
|
+
type MakeIntent = Extract<MidnightOfferManagementIntent, {
|
|
4
|
+
readonly offers: unknown;
|
|
5
|
+
}>;
|
|
6
|
+
declare function verifyMake(intent: MakeIntent, { calls, chain, }: {
|
|
7
|
+
readonly calls: readonly CalldataCall[];
|
|
8
|
+
readonly chain: ChainAddresses;
|
|
9
|
+
}): readonly DecodedCalldataCall[];
|
|
10
|
+
/** @internal */
|
|
11
|
+
export declare const midnightMakerRules: {
|
|
12
|
+
"midnight.make_borrow": typeof verifyMake;
|
|
13
|
+
"midnight.make_lend": typeof verifyMake;
|
|
14
|
+
"midnight.make_repay": typeof verifyMake;
|
|
15
|
+
"midnight.make_withdraw": typeof verifyMake;
|
|
16
|
+
};
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.midnightMakerRules = void 0;
|
|
4
|
+
const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
|
|
5
|
+
const abis_1 = require("@morpho-org/morpho-ts/abis");
|
|
6
|
+
const fflate_1 = require("fflate");
|
|
7
|
+
const viem_1 = require("viem");
|
|
8
|
+
const checks_js_1 = require("./checks.js");
|
|
9
|
+
const errors_js_1 = require("./errors.js");
|
|
10
|
+
const midnight_js_1 = require("./midnight.js");
|
|
11
|
+
const sides = {
|
|
12
|
+
"midnight.make_lend": { buy: true, reduceOnly: false, unit: "assets" },
|
|
13
|
+
"midnight.make_borrow": { buy: false, reduceOnly: false, unit: "assets" },
|
|
14
|
+
"midnight.make_repay": { buy: true, reduceOnly: true, unit: "units" },
|
|
15
|
+
"midnight.make_withdraw": { buy: false, reduceOnly: true, unit: "units" },
|
|
16
|
+
};
|
|
17
|
+
const GUNZIP_SLICE_BYTES = 1_024;
|
|
18
|
+
function gunzip(compressed, maxBytes) {
|
|
19
|
+
const chunks = [];
|
|
20
|
+
let length = 0;
|
|
21
|
+
const stream = new fflate_1.Gunzip((chunk) => {
|
|
22
|
+
length += chunk.length;
|
|
23
|
+
if (length > maxBytes) {
|
|
24
|
+
throw new RangeError(`gzip output exceeds ${maxBytes} bytes`);
|
|
25
|
+
}
|
|
26
|
+
chunks.push(chunk);
|
|
27
|
+
});
|
|
28
|
+
// fflate inflates a whole push before reporting output, so small slices bound the work done past the cap.
|
|
29
|
+
for (let offset = 0; offset < compressed.length; offset += GUNZIP_SLICE_BYTES) {
|
|
30
|
+
const end = offset + GUNZIP_SLICE_BYTES;
|
|
31
|
+
stream.push(compressed.subarray(offset, end), end >= compressed.length);
|
|
32
|
+
}
|
|
33
|
+
const output = new Uint8Array(length);
|
|
34
|
+
let offset = 0;
|
|
35
|
+
for (const chunk of chunks) {
|
|
36
|
+
output.set(chunk, offset);
|
|
37
|
+
offset += chunk.length;
|
|
38
|
+
}
|
|
39
|
+
return output;
|
|
40
|
+
}
|
|
41
|
+
function decodePayload(payload, { call, maxItems }) {
|
|
42
|
+
try {
|
|
43
|
+
const bytes = (0, viem_1.hexToBytes)(payload);
|
|
44
|
+
// The API never appends an attribution suffix after the gzip stream.
|
|
45
|
+
if (bytes.length !== 5 + new DataView(bytes.buffer).getUint32(1)) {
|
|
46
|
+
throw new errors_js_1.CalldataDecodeError("payload", call.id);
|
|
47
|
+
}
|
|
48
|
+
return midnight_sdk_1.Payload.decodeSync(payload, { gunzip, maxItems });
|
|
49
|
+
}
|
|
50
|
+
catch (cause) {
|
|
51
|
+
if (cause instanceof errors_js_1.CalldataDecodeError) {
|
|
52
|
+
throw cause;
|
|
53
|
+
}
|
|
54
|
+
throw new errors_js_1.CalldataDecodeError("payload", { callId: call.id, cause });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function rebuildTree(items, { intent, call }) {
|
|
58
|
+
try {
|
|
59
|
+
if (intent.offers.type === "rate") {
|
|
60
|
+
const entries = items.map(({ offer, ratifierData }) => ({
|
|
61
|
+
offer,
|
|
62
|
+
...midnight_sdk_1.RateRatifierV1.decodeRatifierData(ratifierData),
|
|
63
|
+
}));
|
|
64
|
+
const tree = midnight_sdk_1.Tree.create({ type: "rateV1", entries });
|
|
65
|
+
return {
|
|
66
|
+
leaves: entries.map(({ offer, rate, allowedTaker }) => ({
|
|
67
|
+
offer: midnight_sdk_1.OfferUtils.toStruct({ offer }),
|
|
68
|
+
rate,
|
|
69
|
+
allowedTaker,
|
|
70
|
+
})),
|
|
71
|
+
root: tree.root,
|
|
72
|
+
group: midnight_sdk_1.RateRatifierV1.groupId(entries),
|
|
73
|
+
items: midnight_sdk_1.RateRatifierV1.ratify({ tree }),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
const entries = items.map(({ offer, ratifierData }) => ({
|
|
77
|
+
offer,
|
|
78
|
+
...midnight_sdk_1.PriceRatifierV1.decodeRatifierData(ratifierData),
|
|
79
|
+
}));
|
|
80
|
+
const tree = midnight_sdk_1.Tree.create({ type: "priceV1", entries });
|
|
81
|
+
return {
|
|
82
|
+
leaves: entries.map(({ offer, allowedTaker }) => ({
|
|
83
|
+
offer: midnight_sdk_1.OfferUtils.toStruct({ offer }),
|
|
84
|
+
allowedTaker,
|
|
85
|
+
})),
|
|
86
|
+
root: tree.root,
|
|
87
|
+
group: midnight_sdk_1.PriceRatifierV1.groupId(entries),
|
|
88
|
+
items: midnight_sdk_1.PriceRatifierV1.ratify({ tree }),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
catch (cause) {
|
|
92
|
+
throw new errors_js_1.CalldataCallError("payload", { callId: call.id, cause });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function marketId(market, call) {
|
|
96
|
+
try {
|
|
97
|
+
const sorted = market.collateralParams.every((collateral, index) => index === 0 ||
|
|
98
|
+
midnight_sdk_1.MarketUtils.compareCollateralTokens(market.collateralParams[index - 1], collateral) < 0);
|
|
99
|
+
if (sorted) {
|
|
100
|
+
return midnight_sdk_1.MarketUtils.toId(market);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch (cause) {
|
|
104
|
+
throw new errors_js_1.CalldataTargetError("market", { callId: call.id, cause });
|
|
105
|
+
}
|
|
106
|
+
throw new errors_js_1.CalldataTargetError("market", call.id);
|
|
107
|
+
}
|
|
108
|
+
function checkOffer({ offer, rate }, { entry, ratifier, cap, context: { intent, chain, call, blue }, }) {
|
|
109
|
+
const { buy, reduceOnly, unit } = sides[intent.action];
|
|
110
|
+
if (offer.market.chainId !== BigInt(intent.chain_id) ||
|
|
111
|
+
!(0, checks_js_1.sameAddress)(offer.market.midnight, chain.midnight) ||
|
|
112
|
+
!(0, checks_js_1.sameHex)(marketId(offer.market, call), entry.market_id)) {
|
|
113
|
+
throw new errors_js_1.CalldataTargetError("offers.market_id", call.id);
|
|
114
|
+
}
|
|
115
|
+
(0, checks_js_1.requireAccount)(offer.maker, {
|
|
116
|
+
expected: intent.account,
|
|
117
|
+
field: "offers.maker",
|
|
118
|
+
call,
|
|
119
|
+
});
|
|
120
|
+
(0, checks_js_1.requireAccount)(offer.receiverIfMakerIsSeller, {
|
|
121
|
+
expected: buy ? viem_1.zeroAddress : intent.account,
|
|
122
|
+
field: "offers.receiver",
|
|
123
|
+
call,
|
|
124
|
+
});
|
|
125
|
+
if (offer.buy !== buy ||
|
|
126
|
+
offer.reduceOnly !== reduceOnly ||
|
|
127
|
+
!(0, checks_js_1.sameAddress)(offer.ratifier, ratifier) ||
|
|
128
|
+
!(0, checks_js_1.sameAddress)(offer.callback, blue?.callback ?? viem_1.zeroAddress) ||
|
|
129
|
+
!(0, checks_js_1.sameHex)(offer.callbackData, blue?.callbackData ?? "0x") ||
|
|
130
|
+
offer.continuousFeeCap !== 0n) {
|
|
131
|
+
throw new errors_js_1.CalldataCallError("offers", call.id);
|
|
132
|
+
}
|
|
133
|
+
if (offer.start !==
|
|
134
|
+
(0, checks_js_1.uint)(String(entry.starts_at), { field: "offers.starts_at", call }) ||
|
|
135
|
+
offer.expiry !==
|
|
136
|
+
(0, checks_js_1.uint)(String(entry.expires_at), { field: "offers.expires_at", call })) {
|
|
137
|
+
throw new errors_js_1.CalldataAmountError("offers.expires_at", call.id);
|
|
138
|
+
}
|
|
139
|
+
if ((intent.offers.type === "price" || entry.tick != null) &&
|
|
140
|
+
offer.tick !== (0, checks_js_1.uint)(entry.tick ?? "", { field: "offers.tick", call })) {
|
|
141
|
+
throw new errors_js_1.CalldataAmountError("offers.tick", call.id);
|
|
142
|
+
}
|
|
143
|
+
if (intent.offers.type === "rate" &&
|
|
144
|
+
rate !==
|
|
145
|
+
(0, checks_js_1.uint)(("rate_wad" in entry ? entry.rate_wad : undefined) ?? "", {
|
|
146
|
+
field: "offers.rate_wad",
|
|
147
|
+
call,
|
|
148
|
+
})) {
|
|
149
|
+
throw new errors_js_1.CalldataAmountError("offers.rate_wad", call.id);
|
|
150
|
+
}
|
|
151
|
+
(0, checks_js_1.requireAmount)(unit === "assets" ? offer.maxAssets : offer.maxUnits, {
|
|
152
|
+
expected: blue == null ? cap : viem_1.maxUint128,
|
|
153
|
+
field: "amount",
|
|
154
|
+
call,
|
|
155
|
+
});
|
|
156
|
+
(0, checks_js_1.requireAmount)(unit === "assets" ? offer.maxUnits : offer.maxAssets, {
|
|
157
|
+
expected: 0n,
|
|
158
|
+
field: "amount",
|
|
159
|
+
call,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
function checkOffers(args, context) {
|
|
163
|
+
const { intent, chain, call, cap } = context;
|
|
164
|
+
const [, , , , , ratifier, root, , , , , , , , payload] = args;
|
|
165
|
+
const { offers } = intent;
|
|
166
|
+
const expectedRatifier = offers?.type === "rate" || offers?.type === "price"
|
|
167
|
+
? { rate: chain.rateRatifierV1, price: chain.priceRatifierV1 }[offers.type]
|
|
168
|
+
: undefined;
|
|
169
|
+
if (expectedRatifier == null || !(0, checks_js_1.sameAddress)(ratifier, expectedRatifier)) {
|
|
170
|
+
throw new errors_js_1.CalldataTargetError("ratifier", call.id);
|
|
171
|
+
}
|
|
172
|
+
if (!Array.isArray(offers.entries) ||
|
|
173
|
+
offers.entries.length === 0 ||
|
|
174
|
+
Array.from(offers.entries).some((entry) => typeof entry !== "object" || entry == null)) {
|
|
175
|
+
throw new errors_js_1.CalldataCallError("offers.entries", call.id);
|
|
176
|
+
}
|
|
177
|
+
const items = decodePayload(payload, {
|
|
178
|
+
call,
|
|
179
|
+
maxItems: offers.entries.length,
|
|
180
|
+
});
|
|
181
|
+
if (items.length !== offers.entries.length) {
|
|
182
|
+
throw new errors_js_1.CalldataCallError("offers.entries", call.id);
|
|
183
|
+
}
|
|
184
|
+
const { blue } = context;
|
|
185
|
+
if (blue != null &&
|
|
186
|
+
!(0, checks_js_1.sameHex)(blue.salt, midnight_sdk_1.GroupUtils.hash(items.map(({ offer }) => ({
|
|
187
|
+
...offer,
|
|
188
|
+
maxAssets: cap,
|
|
189
|
+
callback: viem_1.zeroAddress,
|
|
190
|
+
callbackData: "0x",
|
|
191
|
+
}))))) {
|
|
192
|
+
throw new errors_js_1.CalldataCallError("callback_salt", call.id);
|
|
193
|
+
}
|
|
194
|
+
const tree = rebuildTree(items, context);
|
|
195
|
+
if (!(0, checks_js_1.sameHex)(tree.root, root) ||
|
|
196
|
+
tree.items.some(({ ratifierData }, index) => !(0, checks_js_1.sameHex)(ratifierData, items[index]?.ratifierData))) {
|
|
197
|
+
throw new errors_js_1.CalldataCallError("root", call.id);
|
|
198
|
+
}
|
|
199
|
+
const entries = offers.entries;
|
|
200
|
+
tree.leaves.forEach((leaf, index) => {
|
|
201
|
+
if (!(0, checks_js_1.sameAddress)(leaf.allowedTaker, viem_1.zeroAddress)) {
|
|
202
|
+
throw new errors_js_1.CalldataCallError("offers.allowed_taker", call.id);
|
|
203
|
+
}
|
|
204
|
+
checkOffer(leaf, {
|
|
205
|
+
entry: entries[index],
|
|
206
|
+
ratifier: expectedRatifier,
|
|
207
|
+
cap,
|
|
208
|
+
context,
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
if (tree.leaves.some(({ offer }) => !(0, checks_js_1.sameHex)(offer.group, tree.group))) {
|
|
212
|
+
throw new errors_js_1.CalldataCallError("offers.group", call.id);
|
|
213
|
+
}
|
|
214
|
+
return tree.leaves.map(({ offer }) => offer);
|
|
215
|
+
}
|
|
216
|
+
function checkEnvelope(args, { call }) {
|
|
217
|
+
const [, , , , , , , height, nonce, signatureDeadline, v, r, s, groupsToCancel, , deadline,] = args;
|
|
218
|
+
if (height !== 0n ||
|
|
219
|
+
nonce !== 0n ||
|
|
220
|
+
signatureDeadline !== 0n ||
|
|
221
|
+
v !== 0 ||
|
|
222
|
+
!(0, checks_js_1.sameHex)(r, viem_1.zeroHash) ||
|
|
223
|
+
!(0, checks_js_1.sameHex)(s, viem_1.zeroHash)) {
|
|
224
|
+
throw new errors_js_1.CalldataCallError("root_signature", call.id);
|
|
225
|
+
}
|
|
226
|
+
if (groupsToCancel.length !== 0) {
|
|
227
|
+
throw new errors_js_1.CalldataCallError("cancellations", call.id);
|
|
228
|
+
}
|
|
229
|
+
if (deadline === 0n) {
|
|
230
|
+
throw new errors_js_1.CalldataAmountError("deadline", call.id);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
function checkBlueFunding(args, { intent, call, cap }) {
|
|
234
|
+
const [market, assets, salt] = args;
|
|
235
|
+
const source = intent.action === "midnight.make_lend" ? intent.funding_source : undefined;
|
|
236
|
+
if (source != null &&
|
|
237
|
+
!["wallet", "variable_rate_market"].includes(source.type)) {
|
|
238
|
+
throw new errors_js_1.CalldataUnsupportedError("funding_source", call.id);
|
|
239
|
+
}
|
|
240
|
+
if (intent.action !== "midnight.make_lend" ||
|
|
241
|
+
intent.funding_source?.type !== "variable_rate_market") {
|
|
242
|
+
if (!(0, checks_js_1.sameAddress)(market.loanToken, viem_1.zeroAddress) ||
|
|
243
|
+
!(0, checks_js_1.sameAddress)(market.collateralToken, viem_1.zeroAddress) ||
|
|
244
|
+
!(0, checks_js_1.sameAddress)(market.oracle, viem_1.zeroAddress) ||
|
|
245
|
+
!(0, checks_js_1.sameAddress)(market.irm, viem_1.zeroAddress) ||
|
|
246
|
+
market.lltv !== 0n ||
|
|
247
|
+
assets !== 0n ||
|
|
248
|
+
!(0, checks_js_1.sameHex)(salt, viem_1.zeroHash)) {
|
|
249
|
+
throw new errors_js_1.CalldataCallError("funding_source", call.id);
|
|
250
|
+
}
|
|
251
|
+
return undefined;
|
|
252
|
+
}
|
|
253
|
+
const callbackData = (0, viem_1.encodeAbiParameters)([abis_1.marketParamsAbi], [market]);
|
|
254
|
+
if (!(0, checks_js_1.sameHex)((0, viem_1.keccak256)(callbackData), intent.funding_source.market_id)) {
|
|
255
|
+
throw new errors_js_1.CalldataTargetError("funding_source.market_id", call.id);
|
|
256
|
+
}
|
|
257
|
+
if (cap === 0n || cap > viem_1.maxUint128) {
|
|
258
|
+
throw new errors_js_1.CalldataAmountError("amount", call.id);
|
|
259
|
+
}
|
|
260
|
+
(0, checks_js_1.requireAmount)(assets, {
|
|
261
|
+
expected: cap,
|
|
262
|
+
field: "amount",
|
|
263
|
+
call,
|
|
264
|
+
});
|
|
265
|
+
return {
|
|
266
|
+
funding: intent.funding,
|
|
267
|
+
loanToken: market.loanToken,
|
|
268
|
+
assets,
|
|
269
|
+
salt,
|
|
270
|
+
callback: (0, midnight_sdk_1.getBlueBuyCallbackAddress)({
|
|
271
|
+
chainId: intent.chain_id,
|
|
272
|
+
owner: intent.account,
|
|
273
|
+
salt,
|
|
274
|
+
}),
|
|
275
|
+
callbackData,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
function checkCollateralSupplies(args, { offers, context }) {
|
|
279
|
+
const { intent, chain, call, blue } = context;
|
|
280
|
+
const [, , , market, supplies, , , , , , , , , , , , wrappedNative] = args;
|
|
281
|
+
const value = (0, checks_js_1.uint)(call.value, { field: "value", call });
|
|
282
|
+
const { requested, funding } = intent.action === "midnight.make_borrow"
|
|
283
|
+
? { requested: intent.collateral_supplies, funding: intent.funding }
|
|
284
|
+
: { requested: undefined, funding: undefined };
|
|
285
|
+
if (requested == null) {
|
|
286
|
+
if (market.chainId !== 0n ||
|
|
287
|
+
!(0, checks_js_1.sameAddress)(market.midnight, viem_1.zeroAddress) ||
|
|
288
|
+
!(0, checks_js_1.sameAddress)(market.loanToken, viem_1.zeroAddress) ||
|
|
289
|
+
market.collateralParams.length !== 0 ||
|
|
290
|
+
market.maturity !== 0n ||
|
|
291
|
+
market.rcfThreshold !== 0n ||
|
|
292
|
+
!(0, checks_js_1.sameAddress)(market.enterGate, viem_1.zeroAddress) ||
|
|
293
|
+
!(0, checks_js_1.sameAddress)(market.liquidatorGate, viem_1.zeroAddress) ||
|
|
294
|
+
supplies.length !== 0 ||
|
|
295
|
+
(blue == null &&
|
|
296
|
+
(value !== 0n || !(0, checks_js_1.sameAddress)(wrappedNative, viem_1.zeroAddress)))) {
|
|
297
|
+
throw new errors_js_1.CalldataCallError("collateral_supplies", call.id);
|
|
298
|
+
}
|
|
299
|
+
if (blue == null ||
|
|
300
|
+
(value === 0n && (0, checks_js_1.sameAddress)(wrappedNative, viem_1.zeroAddress))) {
|
|
301
|
+
return [];
|
|
302
|
+
}
|
|
303
|
+
if (value === 0n ||
|
|
304
|
+
!(0, checks_js_1.sameAddress)(blue.loanToken, chain.wNative) ||
|
|
305
|
+
!(0, checks_js_1.sameAddress)(wrappedNative, chain.wNative) ||
|
|
306
|
+
value > blue.assets) {
|
|
307
|
+
throw new errors_js_1.CalldataAmountError("value", call.id);
|
|
308
|
+
}
|
|
309
|
+
(0, checks_js_1.requireNativeBudget)(value, { funding: blue.funding, call });
|
|
310
|
+
return [];
|
|
311
|
+
}
|
|
312
|
+
const collateralMarketId = marketId(market, call);
|
|
313
|
+
if (market.chainId !== BigInt(intent.chain_id) ||
|
|
314
|
+
!(0, checks_js_1.sameAddress)(market.midnight, chain.midnight) ||
|
|
315
|
+
offers.some((offer) => !(0, checks_js_1.sameHex)(marketId(offer.market, call), collateralMarketId))) {
|
|
316
|
+
throw new errors_js_1.CalldataTargetError("market", call.id);
|
|
317
|
+
}
|
|
318
|
+
const collateral = (0, midnight_js_1.checkCollateral)(supplies, { requested, market, call });
|
|
319
|
+
if (value === 0n && (0, checks_js_1.sameAddress)(wrappedNative, viem_1.zeroAddress)) {
|
|
320
|
+
return collateral;
|
|
321
|
+
}
|
|
322
|
+
const nativeCap = collateral.find(({ token }) => (0, checks_js_1.sameAddress)(token, chain.wNative))?.assets ??
|
|
323
|
+
0n;
|
|
324
|
+
if (value === 0n ||
|
|
325
|
+
!(0, checks_js_1.sameAddress)(wrappedNative, chain.wNative) ||
|
|
326
|
+
value > nativeCap) {
|
|
327
|
+
throw new errors_js_1.CalldataAmountError("value", call.id);
|
|
328
|
+
}
|
|
329
|
+
(0, checks_js_1.requireNativeBudget)(value, { funding, call });
|
|
330
|
+
return collateral;
|
|
331
|
+
}
|
|
332
|
+
function loanTokenPulls(offers, { intent, chain, call, cap, blue }) {
|
|
333
|
+
if (!sides[intent.action].buy) {
|
|
334
|
+
return [];
|
|
335
|
+
}
|
|
336
|
+
const token = offers[0].market.loanToken;
|
|
337
|
+
if (blue != null && !(0, checks_js_1.sameAddress)(blue.loanToken, token)) {
|
|
338
|
+
throw new errors_js_1.CalldataTargetError("funding_source.market_id", call.id);
|
|
339
|
+
}
|
|
340
|
+
return [
|
|
341
|
+
{
|
|
342
|
+
token,
|
|
343
|
+
spender: blue == null ? chain.midnight : chain.midnightBundlesV2,
|
|
344
|
+
assets: intent.action === "midnight.make_lend" ? cap : 0n,
|
|
345
|
+
},
|
|
346
|
+
];
|
|
347
|
+
}
|
|
348
|
+
function verifyMake(intent, { calls, chain, }) {
|
|
349
|
+
const call = (0, checks_js_1.mainCall)(calls, Number.MAX_SAFE_INTEGER);
|
|
350
|
+
(0, checks_js_1.requireTarget)(call, chain.midnightBundlesV2);
|
|
351
|
+
const decoded = (0, checks_js_1.decode)(call, { abi: midnight_sdk_1.midnightBundlesV2Abi });
|
|
352
|
+
if (decoded.functionName !== "midnightBundlesV2CancelAndMake") {
|
|
353
|
+
throw new errors_js_1.CalldataCallError("function", call.id);
|
|
354
|
+
}
|
|
355
|
+
if (intent.amount?.unit !== sides[intent.action].unit) {
|
|
356
|
+
throw new errors_js_1.CalldataAmountError("amount.unit", call.id);
|
|
357
|
+
}
|
|
358
|
+
const base = {
|
|
359
|
+
intent,
|
|
360
|
+
chain,
|
|
361
|
+
call,
|
|
362
|
+
cap: (0, checks_js_1.uint)(intent.amount.value, { field: "amount", call }),
|
|
363
|
+
};
|
|
364
|
+
const context = { ...base, blue: checkBlueFunding(decoded.args, base) };
|
|
365
|
+
checkEnvelope(decoded.args, context);
|
|
366
|
+
const offers = checkOffers(decoded.args, context);
|
|
367
|
+
const collateral = checkCollateralSupplies(decoded.args, { offers, context });
|
|
368
|
+
return [
|
|
369
|
+
...(0, midnight_js_1.checkPrerequisites)(calls.slice(0, -1), {
|
|
370
|
+
...context,
|
|
371
|
+
pulls: [...collateral, ...loanTokenPulls(offers, context)],
|
|
372
|
+
allowAuthorization: true,
|
|
373
|
+
}),
|
|
374
|
+
(0, checks_js_1.checked)(call, decoded),
|
|
375
|
+
];
|
|
376
|
+
}
|
|
377
|
+
/** @internal */
|
|
378
|
+
exports.midnightMakerRules = {
|
|
379
|
+
"midnight.make_borrow": verifyMake,
|
|
380
|
+
"midnight.make_lend": verifyMake,
|
|
381
|
+
"midnight.make_repay": verifyMake,
|
|
382
|
+
"midnight.make_withdraw": verifyMake,
|
|
383
|
+
};
|
|
@@ -10,14 +10,9 @@ declare function cancel(intent: Extract<MidnightOfferManagementIntent, {
|
|
|
10
10
|
declare function withdrawFunding(intent: Extract<MidnightOfferManagementIntent, {
|
|
11
11
|
action: "midnight.withdraw_funding";
|
|
12
12
|
}>, context: Context): import("./types.js").DecodedCalldataCall[];
|
|
13
|
-
declare function unsupported(intent: MidnightOfferManagementIntent, { calls }: Context): never;
|
|
14
13
|
/** @internal */
|
|
15
14
|
export declare const midnightOfferRules: {
|
|
16
15
|
"midnight.cancel_offers": typeof cancel;
|
|
17
16
|
"midnight.withdraw_funding": typeof withdrawFunding;
|
|
18
|
-
"midnight.make_borrow": typeof unsupported;
|
|
19
|
-
"midnight.make_lend": typeof unsupported;
|
|
20
|
-
"midnight.make_repay": typeof unsupported;
|
|
21
|
-
"midnight.make_withdraw": typeof unsupported;
|
|
22
17
|
};
|
|
23
18
|
export {};
|
|
@@ -94,15 +94,8 @@ function withdrawFunding(intent, context) {
|
|
|
94
94
|
}
|
|
95
95
|
return [(0, checks_js_1.checked)(call, decoded)];
|
|
96
96
|
}
|
|
97
|
-
function unsupported(intent, { calls }) {
|
|
98
|
-
throw new errors_js_1.CalldataUnsupportedError(intent.action, calls[0]?.id);
|
|
99
|
-
}
|
|
100
97
|
/** @internal */
|
|
101
98
|
exports.midnightOfferRules = {
|
|
102
99
|
"midnight.cancel_offers": cancel,
|
|
103
100
|
"midnight.withdraw_funding": withdrawFunding,
|
|
104
|
-
"midnight.make_borrow": unsupported,
|
|
105
|
-
"midnight.make_lend": unsupported,
|
|
106
|
-
"midnight.make_repay": unsupported,
|
|
107
|
-
"midnight.make_withdraw": unsupported,
|
|
108
101
|
};
|
|
@@ -8,6 +8,7 @@ const blue_js_1 = require("./blue.js");
|
|
|
8
8
|
const checks_js_1 = require("./checks.js");
|
|
9
9
|
const errors_js_1 = require("./errors.js");
|
|
10
10
|
const midnight_js_1 = require("./midnight.js");
|
|
11
|
+
const midnightMakers_js_1 = require("./midnightMakers.js");
|
|
11
12
|
const midnightOffers_js_1 = require("./midnightOffers.js");
|
|
12
13
|
const vault_js_1 = require("./vault.js");
|
|
13
14
|
const rules = {
|
|
@@ -15,6 +16,7 @@ const rules = {
|
|
|
15
16
|
...blue_js_1.blueRules,
|
|
16
17
|
...midnight_js_1.midnightRules,
|
|
17
18
|
...midnightOffers_js_1.midnightOfferRules,
|
|
19
|
+
...midnightMakers_js_1.midnightMakerRules,
|
|
18
20
|
};
|
|
19
21
|
/**
|
|
20
22
|
* Statically checks Actions API calldata against the original request before signing; does not simulate execution.
|
package/lib/cjs/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Installed @morpho-org/calldata-verifier package version. */
|
|
2
|
-
export declare const version = "0.
|
|
2
|
+
export declare const version = "0.3.1-next.0";
|
package/lib/cjs/version.js
CHANGED
package/lib/esm/blue.js
CHANGED
|
@@ -58,28 +58,27 @@ function requireMarket(params, { chainId, selector, call, field = "market", }) {
|
|
|
58
58
|
}
|
|
59
59
|
function requireReallocations(entries, { params, call }) {
|
|
60
60
|
const expected = marketId(params);
|
|
61
|
-
const
|
|
61
|
+
const idleDestinations = new Set();
|
|
62
62
|
for (const entry of entries) {
|
|
63
|
-
const source = marketId(entry.sourceMarketParams);
|
|
64
63
|
const destination = `${entry.vault}:${entry.adapter}`;
|
|
65
|
-
const route = entry.fromIdle
|
|
66
|
-
? destination
|
|
67
|
-
: `${destination}:${entry.sourceAdapter}:${source}`;
|
|
68
64
|
if (entry.penalty !== 0n) {
|
|
69
65
|
throw new CalldataFeeError("reallocations.penalty", call.id);
|
|
70
66
|
}
|
|
71
67
|
if (entry.assets === 0n ||
|
|
72
|
-
used.has(route) ||
|
|
73
68
|
sameAddress(entry.vault, zeroAddress) ||
|
|
74
69
|
sameAddress(entry.adapter, zeroAddress) ||
|
|
75
70
|
marketId(entry.marketParams) !== expected ||
|
|
76
71
|
!sameAddress(entry.sourceMarketParams.loanToken, params.loanToken) ||
|
|
77
72
|
(entry.fromIdle
|
|
78
|
-
? !sameAddress(entry.sourceAdapter, zeroAddress)
|
|
79
|
-
|
|
73
|
+
? !sameAddress(entry.sourceAdapter, zeroAddress) ||
|
|
74
|
+
idleDestinations.has(destination)
|
|
75
|
+
: sameAddress(entry.sourceAdapter, zeroAddress) ||
|
|
76
|
+
marketId(entry.sourceMarketParams) === expected)) {
|
|
80
77
|
throw new CalldataCallError("reallocations", call.id);
|
|
81
78
|
}
|
|
82
|
-
|
|
79
|
+
if (entry.fromIdle) {
|
|
80
|
+
idleDestinations.add(destination);
|
|
81
|
+
}
|
|
83
82
|
}
|
|
84
83
|
}
|
|
85
84
|
function requirePositionAmount(amount, { assets, shares, call, }) {
|
package/lib/esm/midnight.d.ts
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
|
+
import { midnightBundlesV2Abi } from "@morpho-org/midnight-sdk";
|
|
1
2
|
import type { ChainAddresses } from "@morpho-org/morpho-ts";
|
|
3
|
+
import { type Address } from "viem";
|
|
4
|
+
import { decode } from "./checks.js";
|
|
2
5
|
import type { CalldataCall, DecodedCalldataCall, MidnightMarketIntent, MidnightTakeIntent } from "./types.js";
|
|
3
6
|
type Intent = MidnightMarketIntent | MidnightTakeIntent;
|
|
7
|
+
type BundleCall = ReturnType<typeof decode<typeof midnightBundlesV2Abi>>;
|
|
8
|
+
type Transfer = {
|
|
9
|
+
readonly collateralIndex: bigint;
|
|
10
|
+
readonly assets: bigint;
|
|
11
|
+
};
|
|
12
|
+
type TokenPull = {
|
|
13
|
+
readonly token: Address;
|
|
14
|
+
readonly assets: bigint;
|
|
15
|
+
readonly spender?: Address;
|
|
16
|
+
};
|
|
17
|
+
type RequestedTransfer = {
|
|
18
|
+
readonly collateral: {
|
|
19
|
+
readonly address: Address;
|
|
20
|
+
};
|
|
21
|
+
readonly amount: {
|
|
22
|
+
readonly unit: "all";
|
|
23
|
+
} | {
|
|
24
|
+
readonly unit: "assets";
|
|
25
|
+
readonly value: string;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
type Market = Extract<BundleCall, {
|
|
29
|
+
functionName: "midnightBundlesV2BuyWithAssetsTargetAndWithdrawCollateral";
|
|
30
|
+
}>["args"][0];
|
|
31
|
+
/** @internal */
|
|
32
|
+
export declare function checkCollateral(transfers: readonly Transfer[], { requested, market, call, withdrawal, }: {
|
|
33
|
+
requested: readonly RequestedTransfer[];
|
|
34
|
+
market: Market;
|
|
35
|
+
call: CalldataCall;
|
|
36
|
+
withdrawal?: "core" | "bundle";
|
|
37
|
+
}): {
|
|
38
|
+
token: `0x${string}`;
|
|
39
|
+
assets: bigint;
|
|
40
|
+
}[];
|
|
41
|
+
/** @internal */
|
|
42
|
+
export declare function checkPrerequisites(calls: readonly CalldataCall[], { intent, chain, call: main, pulls, allowAuthorization, }: {
|
|
43
|
+
readonly intent: {
|
|
44
|
+
readonly account: Address;
|
|
45
|
+
};
|
|
46
|
+
readonly chain: ChainAddresses;
|
|
47
|
+
readonly call: CalldataCall;
|
|
48
|
+
readonly pulls: readonly TokenPull[];
|
|
49
|
+
readonly allowAuthorization: boolean;
|
|
50
|
+
}): DecodedCalldataCall[];
|
|
4
51
|
declare function verifyMidnight(intent: Intent, { calls, chain, }: {
|
|
5
52
|
readonly calls: readonly CalldataCall[];
|
|
6
53
|
readonly chain: ChainAddresses;
|
package/lib/esm/midnight.js
CHANGED
|
@@ -43,7 +43,8 @@ function assetsMatch(assets, { requested, withdrawal, call, }) {
|
|
|
43
43
|
field: "collateral.amount",
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
|
-
|
|
46
|
+
/** @internal */
|
|
47
|
+
export function checkCollateral(transfers, { requested, market, call, withdrawal, }) {
|
|
47
48
|
if (!Array.isArray(requested) || transfers.length !== requested.length) {
|
|
48
49
|
throw new CalldataCallError("collateral", call.id);
|
|
49
50
|
}
|
|
@@ -66,7 +67,8 @@ function noValue(call) {
|
|
|
66
67
|
field: "value",
|
|
67
68
|
});
|
|
68
69
|
}
|
|
69
|
-
|
|
70
|
+
/** @internal */
|
|
71
|
+
export function checkPrerequisites(calls, { intent, chain, call: main, pulls, allowAuthorization, }) {
|
|
70
72
|
let authorized = false;
|
|
71
73
|
const approved = new Map();
|
|
72
74
|
return calls.map((call, index) => {
|
|
@@ -95,9 +97,9 @@ function checkPrerequisites(calls, { intent, chain, call: main, pulls, allowAuth
|
|
|
95
97
|
if (pull == null) {
|
|
96
98
|
throw new CalldataTargetError("approval.token", call.id);
|
|
97
99
|
}
|
|
98
|
-
const { token, assets } = pull;
|
|
100
|
+
const { token, assets, spender = main.to } = pull;
|
|
99
101
|
const verified = approval(call, {
|
|
100
|
-
spender
|
|
102
|
+
spender,
|
|
101
103
|
token,
|
|
102
104
|
minAmount: assets,
|
|
103
105
|
allowReset: sameAddress(calls[index + 1]?.to, token),
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ChainAddresses } from "@morpho-org/morpho-ts";
|
|
2
|
+
import type { CalldataCall, DecodedCalldataCall, MidnightOfferManagementIntent } from "./types.js";
|
|
3
|
+
type MakeIntent = Extract<MidnightOfferManagementIntent, {
|
|
4
|
+
readonly offers: unknown;
|
|
5
|
+
}>;
|
|
6
|
+
declare function verifyMake(intent: MakeIntent, { calls, chain, }: {
|
|
7
|
+
readonly calls: readonly CalldataCall[];
|
|
8
|
+
readonly chain: ChainAddresses;
|
|
9
|
+
}): readonly DecodedCalldataCall[];
|
|
10
|
+
/** @internal */
|
|
11
|
+
export declare const midnightMakerRules: {
|
|
12
|
+
"midnight.make_borrow": typeof verifyMake;
|
|
13
|
+
"midnight.make_lend": typeof verifyMake;
|
|
14
|
+
"midnight.make_repay": typeof verifyMake;
|
|
15
|
+
"midnight.make_withdraw": typeof verifyMake;
|
|
16
|
+
};
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { GroupUtils, getBlueBuyCallbackAddress, MarketUtils, midnightBundlesV2Abi, OfferUtils, Payload, PriceRatifierV1, RateRatifierV1, Tree, } from "@morpho-org/midnight-sdk";
|
|
2
|
+
import { marketParamsAbi } from "@morpho-org/morpho-ts/abis";
|
|
3
|
+
import { Gunzip } from "fflate";
|
|
4
|
+
import { encodeAbiParameters, hexToBytes, keccak256, maxUint128, zeroAddress, zeroHash, } from "viem";
|
|
5
|
+
import { checked, decode, mainCall, requireAccount, requireAmount, requireNativeBudget, requireTarget, sameAddress, sameHex, uint, } from "./checks.js";
|
|
6
|
+
import { CalldataAmountError, CalldataCallError, CalldataDecodeError, CalldataTargetError, CalldataUnsupportedError, } from "./errors.js";
|
|
7
|
+
import { checkCollateral, checkPrerequisites } from "./midnight.js";
|
|
8
|
+
const sides = {
|
|
9
|
+
"midnight.make_lend": { buy: true, reduceOnly: false, unit: "assets" },
|
|
10
|
+
"midnight.make_borrow": { buy: false, reduceOnly: false, unit: "assets" },
|
|
11
|
+
"midnight.make_repay": { buy: true, reduceOnly: true, unit: "units" },
|
|
12
|
+
"midnight.make_withdraw": { buy: false, reduceOnly: true, unit: "units" },
|
|
13
|
+
};
|
|
14
|
+
const GUNZIP_SLICE_BYTES = 1_024;
|
|
15
|
+
function gunzip(compressed, maxBytes) {
|
|
16
|
+
const chunks = [];
|
|
17
|
+
let length = 0;
|
|
18
|
+
const stream = new Gunzip((chunk) => {
|
|
19
|
+
length += chunk.length;
|
|
20
|
+
if (length > maxBytes) {
|
|
21
|
+
throw new RangeError(`gzip output exceeds ${maxBytes} bytes`);
|
|
22
|
+
}
|
|
23
|
+
chunks.push(chunk);
|
|
24
|
+
});
|
|
25
|
+
// fflate inflates a whole push before reporting output, so small slices bound the work done past the cap.
|
|
26
|
+
for (let offset = 0; offset < compressed.length; offset += GUNZIP_SLICE_BYTES) {
|
|
27
|
+
const end = offset + GUNZIP_SLICE_BYTES;
|
|
28
|
+
stream.push(compressed.subarray(offset, end), end >= compressed.length);
|
|
29
|
+
}
|
|
30
|
+
const output = new Uint8Array(length);
|
|
31
|
+
let offset = 0;
|
|
32
|
+
for (const chunk of chunks) {
|
|
33
|
+
output.set(chunk, offset);
|
|
34
|
+
offset += chunk.length;
|
|
35
|
+
}
|
|
36
|
+
return output;
|
|
37
|
+
}
|
|
38
|
+
function decodePayload(payload, { call, maxItems }) {
|
|
39
|
+
try {
|
|
40
|
+
const bytes = hexToBytes(payload);
|
|
41
|
+
// The API never appends an attribution suffix after the gzip stream.
|
|
42
|
+
if (bytes.length !== 5 + new DataView(bytes.buffer).getUint32(1)) {
|
|
43
|
+
throw new CalldataDecodeError("payload", call.id);
|
|
44
|
+
}
|
|
45
|
+
return Payload.decodeSync(payload, { gunzip, maxItems });
|
|
46
|
+
}
|
|
47
|
+
catch (cause) {
|
|
48
|
+
if (cause instanceof CalldataDecodeError) {
|
|
49
|
+
throw cause;
|
|
50
|
+
}
|
|
51
|
+
throw new CalldataDecodeError("payload", { callId: call.id, cause });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function rebuildTree(items, { intent, call }) {
|
|
55
|
+
try {
|
|
56
|
+
if (intent.offers.type === "rate") {
|
|
57
|
+
const entries = items.map(({ offer, ratifierData }) => ({
|
|
58
|
+
offer,
|
|
59
|
+
...RateRatifierV1.decodeRatifierData(ratifierData),
|
|
60
|
+
}));
|
|
61
|
+
const tree = Tree.create({ type: "rateV1", entries });
|
|
62
|
+
return {
|
|
63
|
+
leaves: entries.map(({ offer, rate, allowedTaker }) => ({
|
|
64
|
+
offer: OfferUtils.toStruct({ offer }),
|
|
65
|
+
rate,
|
|
66
|
+
allowedTaker,
|
|
67
|
+
})),
|
|
68
|
+
root: tree.root,
|
|
69
|
+
group: RateRatifierV1.groupId(entries),
|
|
70
|
+
items: RateRatifierV1.ratify({ tree }),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const entries = items.map(({ offer, ratifierData }) => ({
|
|
74
|
+
offer,
|
|
75
|
+
...PriceRatifierV1.decodeRatifierData(ratifierData),
|
|
76
|
+
}));
|
|
77
|
+
const tree = Tree.create({ type: "priceV1", entries });
|
|
78
|
+
return {
|
|
79
|
+
leaves: entries.map(({ offer, allowedTaker }) => ({
|
|
80
|
+
offer: OfferUtils.toStruct({ offer }),
|
|
81
|
+
allowedTaker,
|
|
82
|
+
})),
|
|
83
|
+
root: tree.root,
|
|
84
|
+
group: PriceRatifierV1.groupId(entries),
|
|
85
|
+
items: PriceRatifierV1.ratify({ tree }),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
catch (cause) {
|
|
89
|
+
throw new CalldataCallError("payload", { callId: call.id, cause });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function marketId(market, call) {
|
|
93
|
+
try {
|
|
94
|
+
const sorted = market.collateralParams.every((collateral, index) => index === 0 ||
|
|
95
|
+
MarketUtils.compareCollateralTokens(market.collateralParams[index - 1], collateral) < 0);
|
|
96
|
+
if (sorted) {
|
|
97
|
+
return MarketUtils.toId(market);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
catch (cause) {
|
|
101
|
+
throw new CalldataTargetError("market", { callId: call.id, cause });
|
|
102
|
+
}
|
|
103
|
+
throw new CalldataTargetError("market", call.id);
|
|
104
|
+
}
|
|
105
|
+
function checkOffer({ offer, rate }, { entry, ratifier, cap, context: { intent, chain, call, blue }, }) {
|
|
106
|
+
const { buy, reduceOnly, unit } = sides[intent.action];
|
|
107
|
+
if (offer.market.chainId !== BigInt(intent.chain_id) ||
|
|
108
|
+
!sameAddress(offer.market.midnight, chain.midnight) ||
|
|
109
|
+
!sameHex(marketId(offer.market, call), entry.market_id)) {
|
|
110
|
+
throw new CalldataTargetError("offers.market_id", call.id);
|
|
111
|
+
}
|
|
112
|
+
requireAccount(offer.maker, {
|
|
113
|
+
expected: intent.account,
|
|
114
|
+
field: "offers.maker",
|
|
115
|
+
call,
|
|
116
|
+
});
|
|
117
|
+
requireAccount(offer.receiverIfMakerIsSeller, {
|
|
118
|
+
expected: buy ? zeroAddress : intent.account,
|
|
119
|
+
field: "offers.receiver",
|
|
120
|
+
call,
|
|
121
|
+
});
|
|
122
|
+
if (offer.buy !== buy ||
|
|
123
|
+
offer.reduceOnly !== reduceOnly ||
|
|
124
|
+
!sameAddress(offer.ratifier, ratifier) ||
|
|
125
|
+
!sameAddress(offer.callback, blue?.callback ?? zeroAddress) ||
|
|
126
|
+
!sameHex(offer.callbackData, blue?.callbackData ?? "0x") ||
|
|
127
|
+
offer.continuousFeeCap !== 0n) {
|
|
128
|
+
throw new CalldataCallError("offers", call.id);
|
|
129
|
+
}
|
|
130
|
+
if (offer.start !==
|
|
131
|
+
uint(String(entry.starts_at), { field: "offers.starts_at", call }) ||
|
|
132
|
+
offer.expiry !==
|
|
133
|
+
uint(String(entry.expires_at), { field: "offers.expires_at", call })) {
|
|
134
|
+
throw new CalldataAmountError("offers.expires_at", call.id);
|
|
135
|
+
}
|
|
136
|
+
if ((intent.offers.type === "price" || entry.tick != null) &&
|
|
137
|
+
offer.tick !== uint(entry.tick ?? "", { field: "offers.tick", call })) {
|
|
138
|
+
throw new CalldataAmountError("offers.tick", call.id);
|
|
139
|
+
}
|
|
140
|
+
if (intent.offers.type === "rate" &&
|
|
141
|
+
rate !==
|
|
142
|
+
uint(("rate_wad" in entry ? entry.rate_wad : undefined) ?? "", {
|
|
143
|
+
field: "offers.rate_wad",
|
|
144
|
+
call,
|
|
145
|
+
})) {
|
|
146
|
+
throw new CalldataAmountError("offers.rate_wad", call.id);
|
|
147
|
+
}
|
|
148
|
+
requireAmount(unit === "assets" ? offer.maxAssets : offer.maxUnits, {
|
|
149
|
+
expected: blue == null ? cap : maxUint128,
|
|
150
|
+
field: "amount",
|
|
151
|
+
call,
|
|
152
|
+
});
|
|
153
|
+
requireAmount(unit === "assets" ? offer.maxUnits : offer.maxAssets, {
|
|
154
|
+
expected: 0n,
|
|
155
|
+
field: "amount",
|
|
156
|
+
call,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
function checkOffers(args, context) {
|
|
160
|
+
const { intent, chain, call, cap } = context;
|
|
161
|
+
const [, , , , , ratifier, root, , , , , , , , payload] = args;
|
|
162
|
+
const { offers } = intent;
|
|
163
|
+
const expectedRatifier = offers?.type === "rate" || offers?.type === "price"
|
|
164
|
+
? { rate: chain.rateRatifierV1, price: chain.priceRatifierV1 }[offers.type]
|
|
165
|
+
: undefined;
|
|
166
|
+
if (expectedRatifier == null || !sameAddress(ratifier, expectedRatifier)) {
|
|
167
|
+
throw new CalldataTargetError("ratifier", call.id);
|
|
168
|
+
}
|
|
169
|
+
if (!Array.isArray(offers.entries) ||
|
|
170
|
+
offers.entries.length === 0 ||
|
|
171
|
+
Array.from(offers.entries).some((entry) => typeof entry !== "object" || entry == null)) {
|
|
172
|
+
throw new CalldataCallError("offers.entries", call.id);
|
|
173
|
+
}
|
|
174
|
+
const items = decodePayload(payload, {
|
|
175
|
+
call,
|
|
176
|
+
maxItems: offers.entries.length,
|
|
177
|
+
});
|
|
178
|
+
if (items.length !== offers.entries.length) {
|
|
179
|
+
throw new CalldataCallError("offers.entries", call.id);
|
|
180
|
+
}
|
|
181
|
+
const { blue } = context;
|
|
182
|
+
if (blue != null &&
|
|
183
|
+
!sameHex(blue.salt, GroupUtils.hash(items.map(({ offer }) => ({
|
|
184
|
+
...offer,
|
|
185
|
+
maxAssets: cap,
|
|
186
|
+
callback: zeroAddress,
|
|
187
|
+
callbackData: "0x",
|
|
188
|
+
}))))) {
|
|
189
|
+
throw new CalldataCallError("callback_salt", call.id);
|
|
190
|
+
}
|
|
191
|
+
const tree = rebuildTree(items, context);
|
|
192
|
+
if (!sameHex(tree.root, root) ||
|
|
193
|
+
tree.items.some(({ ratifierData }, index) => !sameHex(ratifierData, items[index]?.ratifierData))) {
|
|
194
|
+
throw new CalldataCallError("root", call.id);
|
|
195
|
+
}
|
|
196
|
+
const entries = offers.entries;
|
|
197
|
+
tree.leaves.forEach((leaf, index) => {
|
|
198
|
+
if (!sameAddress(leaf.allowedTaker, zeroAddress)) {
|
|
199
|
+
throw new CalldataCallError("offers.allowed_taker", call.id);
|
|
200
|
+
}
|
|
201
|
+
checkOffer(leaf, {
|
|
202
|
+
entry: entries[index],
|
|
203
|
+
ratifier: expectedRatifier,
|
|
204
|
+
cap,
|
|
205
|
+
context,
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
if (tree.leaves.some(({ offer }) => !sameHex(offer.group, tree.group))) {
|
|
209
|
+
throw new CalldataCallError("offers.group", call.id);
|
|
210
|
+
}
|
|
211
|
+
return tree.leaves.map(({ offer }) => offer);
|
|
212
|
+
}
|
|
213
|
+
function checkEnvelope(args, { call }) {
|
|
214
|
+
const [, , , , , , , height, nonce, signatureDeadline, v, r, s, groupsToCancel, , deadline,] = args;
|
|
215
|
+
if (height !== 0n ||
|
|
216
|
+
nonce !== 0n ||
|
|
217
|
+
signatureDeadline !== 0n ||
|
|
218
|
+
v !== 0 ||
|
|
219
|
+
!sameHex(r, zeroHash) ||
|
|
220
|
+
!sameHex(s, zeroHash)) {
|
|
221
|
+
throw new CalldataCallError("root_signature", call.id);
|
|
222
|
+
}
|
|
223
|
+
if (groupsToCancel.length !== 0) {
|
|
224
|
+
throw new CalldataCallError("cancellations", call.id);
|
|
225
|
+
}
|
|
226
|
+
if (deadline === 0n) {
|
|
227
|
+
throw new CalldataAmountError("deadline", call.id);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
function checkBlueFunding(args, { intent, call, cap }) {
|
|
231
|
+
const [market, assets, salt] = args;
|
|
232
|
+
const source = intent.action === "midnight.make_lend" ? intent.funding_source : undefined;
|
|
233
|
+
if (source != null &&
|
|
234
|
+
!["wallet", "variable_rate_market"].includes(source.type)) {
|
|
235
|
+
throw new CalldataUnsupportedError("funding_source", call.id);
|
|
236
|
+
}
|
|
237
|
+
if (intent.action !== "midnight.make_lend" ||
|
|
238
|
+
intent.funding_source?.type !== "variable_rate_market") {
|
|
239
|
+
if (!sameAddress(market.loanToken, zeroAddress) ||
|
|
240
|
+
!sameAddress(market.collateralToken, zeroAddress) ||
|
|
241
|
+
!sameAddress(market.oracle, zeroAddress) ||
|
|
242
|
+
!sameAddress(market.irm, zeroAddress) ||
|
|
243
|
+
market.lltv !== 0n ||
|
|
244
|
+
assets !== 0n ||
|
|
245
|
+
!sameHex(salt, zeroHash)) {
|
|
246
|
+
throw new CalldataCallError("funding_source", call.id);
|
|
247
|
+
}
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
const callbackData = encodeAbiParameters([marketParamsAbi], [market]);
|
|
251
|
+
if (!sameHex(keccak256(callbackData), intent.funding_source.market_id)) {
|
|
252
|
+
throw new CalldataTargetError("funding_source.market_id", call.id);
|
|
253
|
+
}
|
|
254
|
+
if (cap === 0n || cap > maxUint128) {
|
|
255
|
+
throw new CalldataAmountError("amount", call.id);
|
|
256
|
+
}
|
|
257
|
+
requireAmount(assets, {
|
|
258
|
+
expected: cap,
|
|
259
|
+
field: "amount",
|
|
260
|
+
call,
|
|
261
|
+
});
|
|
262
|
+
return {
|
|
263
|
+
funding: intent.funding,
|
|
264
|
+
loanToken: market.loanToken,
|
|
265
|
+
assets,
|
|
266
|
+
salt,
|
|
267
|
+
callback: getBlueBuyCallbackAddress({
|
|
268
|
+
chainId: intent.chain_id,
|
|
269
|
+
owner: intent.account,
|
|
270
|
+
salt,
|
|
271
|
+
}),
|
|
272
|
+
callbackData,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function checkCollateralSupplies(args, { offers, context }) {
|
|
276
|
+
const { intent, chain, call, blue } = context;
|
|
277
|
+
const [, , , market, supplies, , , , , , , , , , , , wrappedNative] = args;
|
|
278
|
+
const value = uint(call.value, { field: "value", call });
|
|
279
|
+
const { requested, funding } = intent.action === "midnight.make_borrow"
|
|
280
|
+
? { requested: intent.collateral_supplies, funding: intent.funding }
|
|
281
|
+
: { requested: undefined, funding: undefined };
|
|
282
|
+
if (requested == null) {
|
|
283
|
+
if (market.chainId !== 0n ||
|
|
284
|
+
!sameAddress(market.midnight, zeroAddress) ||
|
|
285
|
+
!sameAddress(market.loanToken, zeroAddress) ||
|
|
286
|
+
market.collateralParams.length !== 0 ||
|
|
287
|
+
market.maturity !== 0n ||
|
|
288
|
+
market.rcfThreshold !== 0n ||
|
|
289
|
+
!sameAddress(market.enterGate, zeroAddress) ||
|
|
290
|
+
!sameAddress(market.liquidatorGate, zeroAddress) ||
|
|
291
|
+
supplies.length !== 0 ||
|
|
292
|
+
(blue == null &&
|
|
293
|
+
(value !== 0n || !sameAddress(wrappedNative, zeroAddress)))) {
|
|
294
|
+
throw new CalldataCallError("collateral_supplies", call.id);
|
|
295
|
+
}
|
|
296
|
+
if (blue == null ||
|
|
297
|
+
(value === 0n && sameAddress(wrappedNative, zeroAddress))) {
|
|
298
|
+
return [];
|
|
299
|
+
}
|
|
300
|
+
if (value === 0n ||
|
|
301
|
+
!sameAddress(blue.loanToken, chain.wNative) ||
|
|
302
|
+
!sameAddress(wrappedNative, chain.wNative) ||
|
|
303
|
+
value > blue.assets) {
|
|
304
|
+
throw new CalldataAmountError("value", call.id);
|
|
305
|
+
}
|
|
306
|
+
requireNativeBudget(value, { funding: blue.funding, call });
|
|
307
|
+
return [];
|
|
308
|
+
}
|
|
309
|
+
const collateralMarketId = marketId(market, call);
|
|
310
|
+
if (market.chainId !== BigInt(intent.chain_id) ||
|
|
311
|
+
!sameAddress(market.midnight, chain.midnight) ||
|
|
312
|
+
offers.some((offer) => !sameHex(marketId(offer.market, call), collateralMarketId))) {
|
|
313
|
+
throw new CalldataTargetError("market", call.id);
|
|
314
|
+
}
|
|
315
|
+
const collateral = checkCollateral(supplies, { requested, market, call });
|
|
316
|
+
if (value === 0n && sameAddress(wrappedNative, zeroAddress)) {
|
|
317
|
+
return collateral;
|
|
318
|
+
}
|
|
319
|
+
const nativeCap = collateral.find(({ token }) => sameAddress(token, chain.wNative))?.assets ??
|
|
320
|
+
0n;
|
|
321
|
+
if (value === 0n ||
|
|
322
|
+
!sameAddress(wrappedNative, chain.wNative) ||
|
|
323
|
+
value > nativeCap) {
|
|
324
|
+
throw new CalldataAmountError("value", call.id);
|
|
325
|
+
}
|
|
326
|
+
requireNativeBudget(value, { funding, call });
|
|
327
|
+
return collateral;
|
|
328
|
+
}
|
|
329
|
+
function loanTokenPulls(offers, { intent, chain, call, cap, blue }) {
|
|
330
|
+
if (!sides[intent.action].buy) {
|
|
331
|
+
return [];
|
|
332
|
+
}
|
|
333
|
+
const token = offers[0].market.loanToken;
|
|
334
|
+
if (blue != null && !sameAddress(blue.loanToken, token)) {
|
|
335
|
+
throw new CalldataTargetError("funding_source.market_id", call.id);
|
|
336
|
+
}
|
|
337
|
+
return [
|
|
338
|
+
{
|
|
339
|
+
token,
|
|
340
|
+
spender: blue == null ? chain.midnight : chain.midnightBundlesV2,
|
|
341
|
+
assets: intent.action === "midnight.make_lend" ? cap : 0n,
|
|
342
|
+
},
|
|
343
|
+
];
|
|
344
|
+
}
|
|
345
|
+
function verifyMake(intent, { calls, chain, }) {
|
|
346
|
+
const call = mainCall(calls, Number.MAX_SAFE_INTEGER);
|
|
347
|
+
requireTarget(call, chain.midnightBundlesV2);
|
|
348
|
+
const decoded = decode(call, { abi: midnightBundlesV2Abi });
|
|
349
|
+
if (decoded.functionName !== "midnightBundlesV2CancelAndMake") {
|
|
350
|
+
throw new CalldataCallError("function", call.id);
|
|
351
|
+
}
|
|
352
|
+
if (intent.amount?.unit !== sides[intent.action].unit) {
|
|
353
|
+
throw new CalldataAmountError("amount.unit", call.id);
|
|
354
|
+
}
|
|
355
|
+
const base = {
|
|
356
|
+
intent,
|
|
357
|
+
chain,
|
|
358
|
+
call,
|
|
359
|
+
cap: uint(intent.amount.value, { field: "amount", call }),
|
|
360
|
+
};
|
|
361
|
+
const context = { ...base, blue: checkBlueFunding(decoded.args, base) };
|
|
362
|
+
checkEnvelope(decoded.args, context);
|
|
363
|
+
const offers = checkOffers(decoded.args, context);
|
|
364
|
+
const collateral = checkCollateralSupplies(decoded.args, { offers, context });
|
|
365
|
+
return [
|
|
366
|
+
...checkPrerequisites(calls.slice(0, -1), {
|
|
367
|
+
...context,
|
|
368
|
+
pulls: [...collateral, ...loanTokenPulls(offers, context)],
|
|
369
|
+
allowAuthorization: true,
|
|
370
|
+
}),
|
|
371
|
+
checked(call, decoded),
|
|
372
|
+
];
|
|
373
|
+
}
|
|
374
|
+
/** @internal */
|
|
375
|
+
export const midnightMakerRules = {
|
|
376
|
+
"midnight.make_borrow": verifyMake,
|
|
377
|
+
"midnight.make_lend": verifyMake,
|
|
378
|
+
"midnight.make_repay": verifyMake,
|
|
379
|
+
"midnight.make_withdraw": verifyMake,
|
|
380
|
+
};
|
|
@@ -10,14 +10,9 @@ declare function cancel(intent: Extract<MidnightOfferManagementIntent, {
|
|
|
10
10
|
declare function withdrawFunding(intent: Extract<MidnightOfferManagementIntent, {
|
|
11
11
|
action: "midnight.withdraw_funding";
|
|
12
12
|
}>, context: Context): import("./types.js").DecodedCalldataCall[];
|
|
13
|
-
declare function unsupported(intent: MidnightOfferManagementIntent, { calls }: Context): never;
|
|
14
13
|
/** @internal */
|
|
15
14
|
export declare const midnightOfferRules: {
|
|
16
15
|
"midnight.cancel_offers": typeof cancel;
|
|
17
16
|
"midnight.withdraw_funding": typeof withdrawFunding;
|
|
18
|
-
"midnight.make_borrow": typeof unsupported;
|
|
19
|
-
"midnight.make_lend": typeof unsupported;
|
|
20
|
-
"midnight.make_repay": typeof unsupported;
|
|
21
|
-
"midnight.make_withdraw": typeof unsupported;
|
|
22
17
|
};
|
|
23
18
|
export {};
|
|
@@ -3,7 +3,7 @@ import { midnightAbi } from "@morpho-org/midnight-sdk";
|
|
|
3
3
|
import { marketParamsAbi } from "@morpho-org/morpho-ts/abis";
|
|
4
4
|
import { encodeAbiParameters, keccak256, maxUint128, zeroAddress } from "viem";
|
|
5
5
|
import { checked, decode, innerCall, isCallAddress, mainCall, requireAccount, requireAmount, requireTarget, sameAddress, sameHex, uint, } from "./checks.js";
|
|
6
|
-
import { CalldataAmountError, CalldataCallError, CalldataTargetError,
|
|
6
|
+
import { CalldataAmountError, CalldataCallError, CalldataTargetError, } from "./errors.js";
|
|
7
7
|
function singleCall({ calls }) {
|
|
8
8
|
const call = mainCall(calls, 1);
|
|
9
9
|
requireAmount(uint(call.value, { field: "value", call }), {
|
|
@@ -91,15 +91,8 @@ function withdrawFunding(intent, context) {
|
|
|
91
91
|
}
|
|
92
92
|
return [checked(call, decoded)];
|
|
93
93
|
}
|
|
94
|
-
function unsupported(intent, { calls }) {
|
|
95
|
-
throw new CalldataUnsupportedError(intent.action, calls[0]?.id);
|
|
96
|
-
}
|
|
97
94
|
/** @internal */
|
|
98
95
|
export const midnightOfferRules = {
|
|
99
96
|
"midnight.cancel_offers": cancel,
|
|
100
97
|
"midnight.withdraw_funding": withdrawFunding,
|
|
101
|
-
"midnight.make_borrow": unsupported,
|
|
102
|
-
"midnight.make_lend": unsupported,
|
|
103
|
-
"midnight.make_repay": unsupported,
|
|
104
|
-
"midnight.make_withdraw": unsupported,
|
|
105
98
|
};
|
|
@@ -5,6 +5,7 @@ import { blueRules } from "./blue.js";
|
|
|
5
5
|
import { isCallAddress, sameAddress } from "./checks.js";
|
|
6
6
|
import { CalldataCallError, CalldataChainError, CalldataFeeError, CalldataRecipientError, CalldataTargetError, } from "./errors.js";
|
|
7
7
|
import { midnightRules } from "./midnight.js";
|
|
8
|
+
import { midnightMakerRules } from "./midnightMakers.js";
|
|
8
9
|
import { midnightOfferRules } from "./midnightOffers.js";
|
|
9
10
|
import { vaultRules } from "./vault.js";
|
|
10
11
|
const rules = {
|
|
@@ -12,6 +13,7 @@ const rules = {
|
|
|
12
13
|
...blueRules,
|
|
13
14
|
...midnightRules,
|
|
14
15
|
...midnightOfferRules,
|
|
16
|
+
...midnightMakerRules,
|
|
15
17
|
};
|
|
16
18
|
/**
|
|
17
19
|
* Statically checks Actions API calldata against the original request before signing; does not simulate execution.
|
package/lib/esm/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Installed @morpho-org/calldata-verifier package version. */
|
|
2
|
-
export declare const version = "0.
|
|
2
|
+
export declare const version = "0.3.1-next.0";
|
package/lib/esm/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@morpho-org/calldata-verifier",
|
|
3
3
|
"description": "Verify Morpho action calldata locally before signing.",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.1-next.0",
|
|
5
5
|
"author": "Morpho Association <contact@morpho.org>",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -27,11 +27,12 @@
|
|
|
27
27
|
"build:esm": "tsc --build tsconfig.build.esm.json && echo '{\"type\":\"module\"}' > lib/esm/package.json"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@morpho-org/blue-sdk-viem": "^7.
|
|
31
|
-
"@morpho-org/midnight-sdk": "^2.
|
|
32
|
-
"@morpho-org/morpho-sdk": "^10.
|
|
33
|
-
"@morpho-org/morpho-ts": "^4.
|
|
34
|
-
"@noble/curves": "1.9.1"
|
|
30
|
+
"@morpho-org/blue-sdk-viem": "^7.7.0-next.0",
|
|
31
|
+
"@morpho-org/midnight-sdk": "^2.11.0-next.0",
|
|
32
|
+
"@morpho-org/morpho-sdk": "^10.5.0-next.0",
|
|
33
|
+
"@morpho-org/morpho-ts": "^4.6.0-next.1",
|
|
34
|
+
"@noble/curves": "1.9.1",
|
|
35
|
+
"fflate": "0.8.3"
|
|
35
36
|
},
|
|
36
37
|
"peerDependencies": {
|
|
37
38
|
"viem": "^2.9.2"
|