nocturne-midnight 0.1.0

Rust SDK for Morpho Midnight offers, execution, simulation, verification, and position management.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! ABI-encode the `take` / `cancelRoot` calls and the `EcrecoverRatifier` ratifier data.
//!
//! Byte-for-byte mirror of Solidity `abi.encode` / `abi.encodeCall`: 32-byte words, with
//! dynamic values (`bytes`, arrays, tuples containing dynamic members) laid out as an offset
//! in the head and their contents appended to the tail. Parity is asserted in `tests/codec.rs`
//! against constants produced by `fixtures/GenCodec.t.sol` run against the Midnight contracts.

use crate::{Address, Market, Offer, Sig, Word, U256};

// ---- 4-byte function selectors, baked from `fixtures/GenCodec.t.sol` ----

/// `Midnight.take(Offer,bytes,uint256,address,address,address,bytes)` selector.
pub const TAKE_SELECTOR: [u8; 4] = [0x6a, 0x14, 0xc9, 0xef];
/// `EcrecoverRatifier.cancelRoot(address,bytes32)` selector.
pub const CANCEL_ROOT_SELECTOR: [u8; 4] = [0xbb, 0x1f, 0x12, 0xaa];
/// `SetterRatifier.setIsRootRatified(address,bytes32,bool)` selector (`cast sig`-derived and
/// cross-checked against a production ratification transaction on Base).
pub const SET_IS_ROOT_RATIFIED_SELECTOR: [u8; 4] = [0x2f, 0xd0, 0xe4, 0x5d];
/// `Midnight.supplyCollateral(Market,uint256,uint256,address)` selector.
pub const SUPPLY_COLLATERAL_SELECTOR: [u8; 4] = [0x32, 0x29, 0x2d, 0x96];
/// `Midnight.withdraw(Market,uint256,address,address)` selector.
pub const WITHDRAW_SELECTOR: [u8; 4] = [0xa6, 0xdb, 0x17, 0x50];
/// `Midnight.setIsAuthorized(address,bool,address)` selector.
pub const SET_IS_AUTHORIZED_SELECTOR: [u8; 4] = [0xb7, 0x82, 0x12, 0xab];
/// `IERC20.approve(address,uint256)` selector.
pub const ERC20_APPROVE_SELECTOR: [u8; 4] = [0x09, 0x5e, 0xa7, 0xb3];
/// `MidnightBundlesV1.midnightBundlesV1RepayAndWithdrawCollateral(...)` selector.
pub const BUNDLE_REPAY_WITHDRAW_SELECTOR: [u8; 4] = [0x7f, 0x19, 0xab, 0xac];

// `IMidnightBundlesV1` fill-function selectors, derived with `cast sig` from the vendored
// interface (morpho-apps `IMidnightBundles.sol`); the BuyWithAssetsTarget selector is also
// cross-checked against production calldata and the openchain signature database.

/// `midnightBundlesV1BuyWithUnitsTargetAndWithdrawCollateral(...)` selector.
pub const BUNDLE_BUY_UNITS_SELECTOR: [u8; 4] = [0xff, 0xb4, 0x58, 0x4e];
/// `midnightBundlesV1SupplyCollateralAndSellWithUnitsTarget(...)` selector.
pub const BUNDLE_SELL_UNITS_SELECTOR: [u8; 4] = [0xb7, 0x07, 0xc6, 0x08];
/// `midnightBundlesV1BuyWithAssetsTargetAndWithdrawCollateral(...)` selector.
pub const BUNDLE_BUY_ASSETS_SELECTOR: [u8; 4] = [0xa8, 0x5d, 0x52, 0xe5];
/// `midnightBundlesV1SupplyCollateralAndSellWithAssetsTarget(...)` selector.
pub const BUNDLE_SELL_ASSETS_SELECTOR: [u8; 4] = [0x2f, 0xbc, 0x23, 0xf8];

// ---- word packing helpers ----

#[inline]
fn addr_word(a: &Address) -> Word {
    let mut w = [0u8; 32];
    w[12..].copy_from_slice(a);
    w
}

#[inline]
fn bool_word(b: bool) -> Word {
    let mut w = [0u8; 32];
    w[31] = b as u8;
    w
}

#[inline]
fn u128_word(x: u128) -> Word {
    let mut w = [0u8; 32];
    w[16..].copy_from_slice(&x.to_be_bytes());
    w
}

#[inline]
fn usize_word(x: usize) -> Word {
    let mut w = [0u8; 32];
    w[24..].copy_from_slice(&(x as u64).to_be_bytes());
    w
}

// ---- ABI value model ----

/// A minimal ABI value tree, enough to encode the Midnight `take` / ratifier types.
enum Value {
    /// A single pre-padded 32-byte word (uint256, bytes32, address, bool, uint128, ...).
    Word(Word),
    /// Dynamic `bytes` / `string`.
    Bytes(Vec<u8>),
    /// A dynamic-length array; each element carries its own `Value`.
    Array(Vec<Value>),
    /// A tuple / struct; dynamic iff any component is dynamic.
    Tuple(Vec<Value>),
}

impl Value {
    fn is_dynamic(&self) -> bool {
        match self {
            Value::Word(_) => false,
            Value::Bytes(_) | Value::Array(_) => true,
            Value::Tuple(items) => items.iter().any(Value::is_dynamic),
        }
    }

    /// Size in bytes of the inline (head) encoding - only defined for static values.
    fn static_size(&self) -> usize {
        match self {
            Value::Word(_) => 32,
            Value::Tuple(items) => items.iter().map(Value::static_size).sum(),
            Value::Bytes(_) | Value::Array(_) => {
                unreachable!("static_size on a dynamic value")
            }
        }
    }

    /// Full encoding of this value when it stands on its own (in a tail slot).
    fn encode(&self) -> Vec<u8> {
        match self {
            Value::Word(w) => w.to_vec(),
            Value::Bytes(b) => {
                let mut out = usize_word(b.len()).to_vec();
                out.extend_from_slice(b);
                let rem = b.len() % 32;
                if rem != 0 {
                    out.extend(std::iter::repeat(0u8).take(32 - rem));
                }
                out
            }
            Value::Array(items) => {
                let mut out = usize_word(items.len()).to_vec();
                out.extend(encode_sequence(items));
                out
            }
            Value::Tuple(items) => encode_sequence(items),
        }
    }
}

/// Encode a sequence of values with the standard head/tail split (this is exactly what
/// `abi.encode(a, b, c, ...)` does, and also how a dynamic tuple encodes its components).
fn encode_sequence(values: &[Value]) -> Vec<u8> {
    let head_size: usize = values
        .iter()
        .map(|v| if v.is_dynamic() { 32 } else { v.static_size() })
        .sum();

    let mut head = Vec::with_capacity(head_size);
    let mut tail = Vec::new();
    for v in values {
        if v.is_dynamic() {
            let offset = head_size + tail.len();
            head.extend_from_slice(&usize_word(offset));
            tail.extend(v.encode());
        } else {
            head.extend(v.encode());
        }
    }
    head.extend(tail);
    head
}

// ---- Offer / Market as ABI values ----

fn collateral_params_value(cp: &crate::CollateralParams) -> Value {
    Value::Tuple(vec![
        Value::Word(addr_word(&cp.token)),
        Value::Word(cp.lltv),
        Value::Word(cp.liquidation_cursor),
        Value::Word(addr_word(&cp.oracle)),
    ])
}

fn market_value(m: &crate::Market) -> Value {
    Value::Tuple(vec![
        Value::Word(m.chain_id),
        Value::Word(addr_word(&m.midnight)),
        Value::Word(addr_word(&m.loan_token)),
        Value::Array(
            m.collateral_params
                .iter()
                .map(collateral_params_value)
                .collect(),
        ),
        Value::Word(m.maturity),
        Value::Word(m.rcf_threshold),
        Value::Word(addr_word(&m.enter_gate)),
        Value::Word(addr_word(&m.liquidator_gate)),
    ])
}

fn offer_value(o: &Offer) -> Value {
    Value::Tuple(vec![
        market_value(&o.market),
        Value::Word(bool_word(o.buy)),
        Value::Word(addr_word(&o.maker)),
        Value::Word(o.start),
        Value::Word(o.expiry),
        Value::Word(o.tick),
        Value::Word(o.group),
        Value::Word(addr_word(&o.callback)),
        Value::Bytes(o.callback_data.clone()),
        Value::Word(addr_word(&o.receiver_if_maker_is_seller)),
        Value::Word(addr_word(&o.ratifier)),
        Value::Word(bool_word(o.reduce_only)),
        Value::Word(u128_word(o.max_units)),
        Value::Word(u128_word(o.max_assets)),
        Value::Word(o.continuous_fee_cap),
    ])
}

// ---- public encoders ----

/// Standard ABI encoding of a single `Market` tuple.
///
/// This is the payload stored by Midnight's SSTORE2 market-params pointer. The collateral order
/// is preserved; callers that need the canonical protocol representation should pass a
/// [`canonical_market`](crate::canonical_market).
pub fn encode_market_params(market: &crate::Market) -> Vec<u8> {
    encode_sequence(&[market_value(market)])
}

fn selector_call(selector: [u8; 4], args: &[Value]) -> Vec<u8> {
    let encoded = encode_sequence(args);
    let mut out = Vec::with_capacity(4 + encoded.len());
    out.extend_from_slice(&selector);
    out.extend(encoded);
    out
}

/// `abi.encode(Signature{uint8 v, bytes32 r, bytes32 s}, bytes32 root, uint256 leafIndex,
/// bytes32[] proof)` - the `ratifierData` consumed by `EcrecoverRatifier.isRatified`.
///
/// `Signature` is a fully static tuple, so it is inlined as three head words (`v` padded, `r`,
/// `s`); `root` and `leafIndex` are static words; `proof` is a dynamic array (offset in the head,
/// length + elements in the tail).
pub fn encode_ratifier_data(sig: &Sig, root: &Word, leaf_index: usize, proof: &[Word]) -> Vec<u8> {
    let signature = Value::Tuple(vec![
        Value::Word(usize_word(sig.v as usize)),
        Value::Word(sig.r),
        Value::Word(sig.s),
    ]);
    let proof_arr = Value::Array(proof.iter().map(|w| Value::Word(*w)).collect());
    encode_sequence(&[
        signature,
        Value::Word(*root),
        Value::Word(usize_word(leaf_index)),
        proof_arr,
    ])
}

/// `abi.encode(bytes32 root, uint256 leafIndex, bytes32[] proof)` - the `ratifierData`
/// consumed by `SetterRatifier.isRatified`. Carries no signature: the maker ratifies the root
/// on-chain via `setIsRootRatified` instead.
pub fn encode_setter_ratifier_data(root: &Word, leaf_index: usize, proof: &[Word]) -> Vec<u8> {
    encode_sequence(&[
        Value::Word(*root),
        Value::Word(usize_word(leaf_index)),
        Value::Array(proof.iter().map(|w| Value::Word(*w)).collect()),
    ])
}

/// `Midnight.take.selector ++ abi.encode(offer, ratifierData, units, taker,
/// receiverIfTakerIsSeller, takerCallback, takerCallbackData)`.
#[allow(clippy::too_many_arguments)]
pub fn encode_take_calldata(
    offer: &Offer,
    ratifier_data: &[u8],
    units: U256,
    taker: &Address,
    receiver_if_taker_is_seller: &Address,
    taker_callback: &Address,
    taker_callback_data: &[u8],
) -> Vec<u8> {
    let args = encode_sequence(&[
        offer_value(offer),
        Value::Bytes(ratifier_data.to_vec()),
        Value::Word(units.to_be_bytes::<32>()),
        Value::Word(addr_word(taker)),
        Value::Word(addr_word(receiver_if_taker_is_seller)),
        Value::Word(addr_word(taker_callback)),
        Value::Bytes(taker_callback_data.to_vec()),
    ]);
    let mut out = Vec::with_capacity(4 + args.len());
    out.extend_from_slice(&TAKE_SELECTOR);
    out.extend(args);
    out
}

/// `IMidnightBundles` fill calldata: the kind's selector ++ its ABI-encoded arguments - the
/// inverse of [`decode_bundle_calldata`](crate::decode_bundle_calldata).
///
/// The wrapper argument order per kind mirrors `IMidnightBundlesV1`: buy variants carry a
/// `TokenPermit`, `OfferFill[]`, `CollateralWithdrawal[]`, and a collateral receiver; sell
/// variants a receiver, `CollateralSupply[]`, then `OfferFill[]`. Both end with
/// (referralFeePct, referralFeeRecipient, maxContinuousFee, deadline).
pub fn encode_bundle_calldata(b: &crate::BundleCall) -> Vec<u8> {
    let fills = Value::Array(
        b.fills
            .iter()
            .map(|f| {
                Value::Tuple(vec![
                    offer_value(&f.offer),
                    Value::Bytes(f.ratifier_data_raw.clone()),
                    Value::Word(f.units.to_be_bytes::<32>()),
                ])
            })
            .collect(),
    );
    let tail = [
        Value::Word(b.referral_fee_pct.to_be_bytes::<32>()),
        Value::Word(addr_word(&b.referral_fee_recipient)),
        Value::Word(b.max_continuous_fee.to_be_bytes::<32>()),
        Value::Word(b.deadline.to_be_bytes::<32>()),
    ];
    let common = [
        Value::Word(b.target.to_be_bytes::<32>()),
        Value::Word(b.limit.to_be_bytes::<32>()),
        Value::Word(addr_word(&b.taker)),
        Value::Word(bool_word(b.reduce_only)),
    ];
    let permit_value = |p: &crate::TokenPermit| {
        Value::Tuple(vec![
            Value::Word(usize_word(p.kind as usize)),
            Value::Bytes(p.data.clone()),
        ])
    };

    let mut args: Vec<Value> = common.into();
    match &b.side {
        crate::BundleSide::Buy {
            loan_token_permit,
            collateral_withdrawals,
            collateral_receiver,
        } => {
            args.push(permit_value(loan_token_permit));
            args.push(fills);
            args.push(Value::Array(
                collateral_withdrawals
                    .iter()
                    .map(|w| {
                        Value::Tuple(vec![
                            Value::Word(w.collateral_index.to_be_bytes::<32>()),
                            Value::Word(w.assets.to_be_bytes::<32>()),
                        ])
                    })
                    .collect(),
            ));
            args.push(Value::Word(addr_word(collateral_receiver)));
        }
        crate::BundleSide::Sell {
            receiver,
            collateral_supplies,
        } => {
            args.push(Value::Word(addr_word(receiver)));
            args.push(Value::Array(
                collateral_supplies
                    .iter()
                    .map(|s| {
                        Value::Tuple(vec![
                            Value::Word(s.collateral_index.to_be_bytes::<32>()),
                            Value::Word(s.assets.to_be_bytes::<32>()),
                            permit_value(&s.permit),
                        ])
                    })
                    .collect(),
            ));
            args.push(fills);
        }
    }
    args.extend(tail);

    let encoded = encode_sequence(&args);
    let mut out = Vec::with_capacity(4 + encoded.len());
    out.extend_from_slice(&b.kind.selector());
    out.extend(encoded);
    out
}

/// Encode `Midnight.supplyCollateral(market, collateralIndex, assets, onBehalf)`.
pub fn encode_supply_collateral_calldata(
    market: &Market,
    collateral_index: U256,
    assets: U256,
    on_behalf: &Address,
) -> Vec<u8> {
    selector_call(
        SUPPLY_COLLATERAL_SELECTOR,
        &[
            market_value(market),
            Value::Word(collateral_index.to_be_bytes::<32>()),
            Value::Word(assets.to_be_bytes::<32>()),
            Value::Word(addr_word(on_behalf)),
        ],
    )
}

/// Encode `Midnight.withdraw(market, units, onBehalf, receiver)` for credit redemption.
pub fn encode_withdraw_calldata(
    market: &Market,
    units: U256,
    on_behalf: &Address,
    receiver: &Address,
) -> Vec<u8> {
    selector_call(
        WITHDRAW_SELECTOR,
        &[
            market_value(market),
            Value::Word(units.to_be_bytes::<32>()),
            Value::Word(addr_word(on_behalf)),
            Value::Word(addr_word(receiver)),
        ],
    )
}

/// Encode `Midnight.setIsAuthorized(authorized, newIsAuthorized, onBehalf)`.
pub fn encode_set_is_authorized_calldata(
    authorized: &Address,
    is_authorized: bool,
    on_behalf: &Address,
) -> Vec<u8> {
    selector_call(
        SET_IS_AUTHORIZED_SELECTOR,
        &[
            Value::Word(addr_word(authorized)),
            Value::Word(bool_word(is_authorized)),
            Value::Word(addr_word(on_behalf)),
        ],
    )
}

/// Encode the standard ERC-20 `approve(spender, amount)` call.
pub fn encode_erc20_approve_calldata(spender: &Address, amount: U256) -> Vec<u8> {
    selector_call(
        ERC20_APPROVE_SELECTOR,
        &[
            Value::Word(addr_word(spender)),
            Value::Word(amount.to_be_bytes::<32>()),
        ],
    )
}

/// Encode the fixed MidnightBundles V1 repay-and-withdraw workflow.
#[allow(clippy::too_many_arguments)]
pub fn encode_repay_withdraw_collateral_calldata(
    market: &Market,
    repay_assets: U256,
    on_behalf: &Address,
    loan_token_permit: &crate::TokenPermit,
    collateral_withdrawals: &[crate::CollateralWithdrawal],
    collateral_receiver: &Address,
    referral_fee_pct: U256,
    referral_fee_recipient: &Address,
    deadline: U256,
) -> Vec<u8> {
    let permit = Value::Tuple(vec![
        Value::Word(usize_word(loan_token_permit.kind as usize)),
        Value::Bytes(loan_token_permit.data.clone()),
    ]);
    let withdrawals = Value::Array(
        collateral_withdrawals
            .iter()
            .map(|withdrawal| {
                Value::Tuple(vec![
                    Value::Word(withdrawal.collateral_index.to_be_bytes::<32>()),
                    Value::Word(withdrawal.assets.to_be_bytes::<32>()),
                ])
            })
            .collect(),
    );
    selector_call(
        BUNDLE_REPAY_WITHDRAW_SELECTOR,
        &[
            market_value(market),
            Value::Word(repay_assets.to_be_bytes::<32>()),
            Value::Word(addr_word(on_behalf)),
            permit,
            withdrawals,
            Value::Word(addr_word(collateral_receiver)),
            Value::Word(referral_fee_pct.to_be_bytes::<32>()),
            Value::Word(addr_word(referral_fee_recipient)),
            Value::Word(deadline.to_be_bytes::<32>()),
        ],
    )
}

/// `EcrecoverRatifier.cancelRoot.selector ++ abi.encode(maker, root)`.
pub fn encode_cancel_root_calldata(maker: &Address, root: &Word) -> Vec<u8> {
    let args = encode_sequence(&[Value::Word(addr_word(maker)), Value::Word(*root)]);
    let mut out = Vec::with_capacity(4 + args.len());
    out.extend_from_slice(&CANCEL_ROOT_SELECTOR);
    out.extend(args);
    out
}

/// `SetterRatifier.setIsRootRatified.selector ++ abi.encode(maker, root, newIsRootRatified)` -
/// the transaction a maker confirms to (un)ratify a whole offer tree on-chain.
pub fn encode_set_is_root_ratified_calldata(
    maker: &Address,
    root: &Word,
    ratified: bool,
) -> Vec<u8> {
    let args = encode_sequence(&[
        Value::Word(addr_word(maker)),
        Value::Word(*root),
        Value::Word(bool_word(ratified)),
    ]);
    let mut out = Vec::with_capacity(4 + args.len());
    out.extend_from_slice(&SET_IS_ROOT_RATIFIED_SELECTOR);
    out.extend(args);
    out
}