cowprotocol-primitives 0.1.1-alpha.1

Primitive CoW Protocol chain, domain, order, and contract types.
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! On-chain ABI bindings for the contracts integrators most often need when
//! interacting with CoW Protocol.
//!
//! The bindings here are pure type definitions, generated by
//! [`alloy_sol_types::sol!`]. They do not pull in `alloy-contract` or any
//! `Provider` plumbing: callers who want to actually dispatch transactions
//! bring their own `alloy_contract::CallBuilder` (or equivalent) and feed it
//! the call structs exposed below. Tests and off-chain tooling that only need
//! to encode calldata, decode return data or compute selectors can use these
//! types directly.
//!
//! ## What this module exposes
//!
//! - [`GPv2Settlement`]: the `setPreSignature` entry
//!   points used to authorise pre-signed orders, the `settle` entry point
//!   solvers call to clear a batch, the typed `GPv2Order.Data` and
//!   `GPv2Trade.Data` structs, and the on-chain events the contract emits
//!   (`Trade`, `Interaction`, `Settlement`, `OrderInvalidated`,
//!   `PreSignature`). The events let off-chain indexers and MEV tooling
//!   parse settlement transactions without re-deriving the topic hashes.
//! - [`ERC20`]: the subset of the ERC-20 ABI integrators reach for when
//!   approving the vault relayer, checking balances or decimals, and pushing
//!   simple transfers.
//! - [`WETH9`]: `deposit()` and `withdraw(uint256)` on top of the ERC-20
//!   API, for wrapping and unwrapping the chain's native gas token.
//! - [`CoWSwapEthFlow`] and [`EthFlowOrderData`]: the native-token sell
//!   periphery contract and its order struct, including create/invalidate
//!   calls and refund events.
//! - [`GPV2_SETTLEMENT`] and [`GPV2_VAULT_RELAYER`]: the two singleton
//!   addresses that share a deployment across every chain CoW Protocol
//!   supports (CREATE2 with the same salt and bytecode).
//!
//! ## Canonical sources
//!
//! - `GPv2Settlement` and `GPv2Order.Data`:
//!   [`cowprotocol/contracts`](https://github.com/cowprotocol/contracts/blob/main/src/contracts/GPv2Settlement.sol)
//!   and
//!   [`GPv2Order.sol`](https://github.com/cowprotocol/contracts/blob/main/src/contracts/libraries/GPv2Order.sol).
//! - Deployment addresses: cow-docs reference (`cow-protocol/reference/contracts/core.mdx`).
//! - `ERC20`: the EIP-20 specification (<https://eips.ethereum.org/EIPS/eip-20>).
//! - `WETH9`: the canonical
//!   [WETH9 source](https://etherscan.io/address/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2#code).
//!
//! ## A note on `GPv2Order.Data` field types
//!
//! `kind`, `sellTokenBalance` and `buyTokenBalance` are `bytes32` markers in
//! the on-chain Solidity struct, even though the EIP-712 type string hashes
//! them as `string`. The signing-side view lives in the signing crate's
//! `order::eip712::Order` and is routed through
//! [`alloy_sol_types::SolStruct`]. The bindings here mirror the on-chain
//! layout: callers that need the EIP-712 view should use the signing
//! crate's `OrderData` instead.

use alloy_primitives::{Address, B256, address, b256};
use alloy_sol_types::sol;

/// Deployment address of the `GPv2Settlement` singleton.
///
/// Identical on every chain CoW Protocol supports thanks to a CREATE2
/// deployment that uses the same salt and bytecode everywhere. Source:
/// `cow-protocol/reference/contracts/core.mdx`.
pub const GPV2_SETTLEMENT: Address = address!("9008D19f58AAbD9eD0D60971565AA8510560ab41");

/// Deployment address of the `GPv2VaultRelayer` singleton, the contract that
/// pulls sell-token allowances on the settlement contract's behalf. This is
/// the spender ERC-20 `approve` calls should target, not the settlement
/// contract itself.
///
/// Identical on every chain CoW Protocol supports. Source:
/// `cow-protocol/reference/contracts/core.mdx`.
pub const GPV2_VAULT_RELAYER: Address = address!("C92E8bdf79f0507f65a392b0ab4667716BFE0110");

/// `GPv2Order.TYPE_HASH`: the EIP-712 type hash of the order struct,
/// `keccak256("Order(address sellToken,...)")`. The on-chain value
/// hard-coded in `GPv2Order.sol`, also passed to `safeSignature` when
/// assembling a ComposableCoW EIP-1271 blob (see
/// [`crate::composable::safe_handler_signature`]). Locked against the
/// derived `eip712_type_hash` by the test in `crate::order`.
pub const GPV2_ORDER_TYPE_HASH: B256 =
    b256!("d5a25ba2e97094ad7d83dc28a6572da797d6b3e7fc6663bd93efb789fc17e489");

sol! {
    /// The 12-field on-chain order struct verified by `GPv2Settlement`.
    ///
    /// Mirrors `GPv2Order.Data` from
    /// [`GPv2Order.sol`](https://github.com/cowprotocol/contracts/blob/main/src/contracts/libraries/GPv2Order.sol):
    ///
    /// ```solidity
    /// struct Data {
    ///     IERC20 sellToken;
    ///     IERC20 buyToken;
    ///     address receiver;
    ///     uint256 sellAmount;
    ///     uint256 buyAmount;
    ///     uint32 validTo;
    ///     bytes32 appData;
    ///     uint256 feeAmount;
    ///     bytes32 kind;
    ///     bool partiallyFillable;
    ///     bytes32 sellTokenBalance;
    ///     bytes32 buyTokenBalance;
    /// }
    /// ```
    ///
    /// `kind`, `sellTokenBalance` and `buyTokenBalance` are `bytes32` here
    /// (matching the storage layout) even though the EIP-712 hash treats them
    /// as `string`. The signing-side typed-data view lives in
    /// `crate::order::eip712::Order` and is fed to
    /// [`alloy_sol_types::SolStruct::eip712_hash_struct`].
    #[derive(Debug)]
    struct GPv2OrderData {
        address sellToken;
        address buyToken;
        address receiver;
        uint256 sellAmount;
        uint256 buyAmount;
        uint32 validTo;
        bytes32 appData;
        uint256 feeAmount;
        bytes32 kind;
        bool partiallyFillable;
        bytes32 sellTokenBalance;
        bytes32 buyTokenBalance;
    }

    /// One element of the `trades` array passed into
    /// [`GPv2Settlement::settle`]. Mirrors `GPv2Trade.Data`:
    ///
    /// ```solidity
    /// struct Data {
    ///     uint256 sellTokenIndex;
    ///     uint256 buyTokenIndex;
    ///     address receiver;
    ///     uint256 sellAmount;
    ///     uint256 buyAmount;
    ///     uint32 validTo;
    ///     bytes32 appData;
    ///     uint256 feeAmount;
    ///     uint256 flags;
    ///     uint256 executedAmount;
    ///     bytes signature;
    /// }
    /// ```
    ///
    /// The `tokens` array at the settlement level is indexed by
    /// `sellTokenIndex` / `buyTokenIndex`; the per-trade
    /// `(sellAmount, buyAmount, feeAmount, executedAmount)` are the
    /// solver-reported amounts at clearing.
    #[derive(Debug)]
    struct GPv2TradeData {
        uint256 sellTokenIndex;
        uint256 buyTokenIndex;
        address receiver;
        uint256 sellAmount;
        uint256 buyAmount;
        uint32 validTo;
        bytes32 appData;
        uint256 feeAmount;
        uint256 flags;
        uint256 executedAmount;
        bytes signature;
    }

    /// One interaction step in [`GPv2Settlement::settle`]'s
    /// `interactions` payload. Mirrors `GPv2Interaction.Data`:
    ///
    /// ```solidity
    /// struct Data {
    ///     address target;
    ///     uint256 value;
    ///     bytes callData;
    /// }
    /// ```
    #[derive(Debug)]
    struct GPv2InteractionData {
        address target;
        uint256 value;
        bytes callData;
    }

    /// Subset of the `GPv2Settlement` ABI integrators most often reach for,
    /// plus the events the contract emits.
    ///
    /// Source:
    /// [`GPv2Settlement.sol`](https://github.com/cowprotocol/contracts/blob/main/src/contracts/GPv2Settlement.sol)
    /// and
    /// [`GPv2Signing.sol`](https://github.com/cowprotocol/contracts/blob/main/src/contracts/mixins/GPv2Signing.sol)
    /// for [`PreSignature`].
    #[derive(Debug)]
    interface GPv2Settlement {
        // --- events ---

        /// Emitted for each executed trade in a settlement batch. Solvers
        /// emit one per settled order.
        event Trade(
            address indexed owner,
            address sellToken,
            address buyToken,
            uint256 sellAmount,
            uint256 buyAmount,
            uint256 feeAmount,
            bytes orderUid
        );

        /// Emitted for each interaction executed during settlement. Only
        /// the first four bytes of the call's selector are recorded, for
        /// gas efficiency; full calldata is recoverable from the settlement
        /// transaction's input.
        event Interaction(address indexed target, uint256 value, bytes4 selector);

        /// Emitted once per settlement transaction, with the solver that
        /// submitted it.
        event Settlement(address indexed solver);

        /// Emitted when an owner invalidates a previously signed order.
        event OrderInvalidated(address indexed owner, bytes orderUid);

        /// Emitted by `GPv2Signing.setPreSignature` whenever a pre-signature
        /// is set or revoked. Carried on the settlement contract address.
        event PreSignature(address indexed owner, bytes orderUid, bool signed);

        // --- functions ---

        /// Settle a batch of orders. Callable only by whitelisted solvers.
        ///
        /// `tokens` is the unique token set referenced by the trades;
        /// `clearingPrices` is the matching price vector (one per token).
        /// `trades` lists the orders being filled; `interactions` is the
        /// three-stage list of pre / intra / post-settlement calls solvers
        /// schedule against external contracts.
        function settle(
            address[] tokens,
            uint256[] clearingPrices,
            GPv2TradeData[] trades,
            GPv2InteractionData[][3] interactions
        ) external;

        /// Toggle the pre-signature flag for `orderUid`.
        ///
        /// When `signed` is true the settlement contract accepts the order as
        /// if it had been signed by the order owner via
        /// [`crate::SigningScheme::PreSign`]; passing false revokes a
        /// previously set pre-signature.
        function setPreSignature(bytes orderUid, bool signed) external;
    }

    /// The subset of the ERC-20 ABI integrators most often need.
    ///
    /// Reference: [EIP-20](https://eips.ethereum.org/EIPS/eip-20).
    #[derive(Debug)]
    interface ERC20 {
        /// Authorise `spender` to move up to `amount` of the caller's balance.
        function approve(address spender, uint256 amount) external returns (bool);

        /// Remaining amount `spender` may still pull from `owner`.
        function allowance(address owner, address spender) external view returns (uint256);

        /// Token balance held by `owner`.
        function balanceOf(address owner) external view returns (uint256);

        /// Move `amount` from the caller to `to`.
        function transfer(address to, uint256 amount) external returns (bool);

        /// Token's display decimals.
        function decimals() external view returns (uint8);
    }

    /// The two non-ERC-20 entry points on canonical
    /// [WETH9](https://etherscan.io/address/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2#code).
    /// The ERC-20 functions (`approve`, `balanceOf`, etc.) are exposed
    /// through [`ERC20`].
    #[derive(Debug)]
    interface WETH9 {
        /// Wrap `msg.value` of the chain's native gas token into WETH credited
        /// to the caller.
        function deposit() external payable;

        /// Burn `wad` WETH from the caller and pay out the equivalent in the
        /// chain's native gas token.
        function withdraw(uint256 wad) external;
    }

    /// The on-chain `EthFlowOrder.Data` struct passed to
    /// [`CoWSwapEthFlow::createOrder`].
    ///
    /// Mirrors `EthFlowOrder.Data` from
    /// [`EthFlowOrder.sol`](https://github.com/cowprotocol/ethflowcontract/blob/main/src/libraries/EthFlowOrder.sol).
    #[derive(Debug, Eq, PartialEq)]
    struct EthFlowOrderData {
        address buyToken;
        address receiver;
        uint256 sellAmount;
        uint256 buyAmount;
        bytes32 appData;
        uint256 feeAmount;
        uint32 validTo;
        bool partiallyFillable;
        int64 quoteId;
    }

    /// `CoWSwapEthFlow`, the native-token sell periphery contract.
    ///
    /// Source:
    /// [`CoWSwapEthFlow.sol`](https://github.com/cowprotocol/ethflowcontract/blob/main/src/CoWSwapEthFlow.sol)
    /// and
    /// [`ICoWSwapEthFlow.sol`](https://github.com/cowprotocol/ethflowcontract/blob/main/src/interfaces/ICoWSwapEthFlow.sol).
    #[derive(Debug)]
    interface CoWSwapEthFlow {
        // --- events ---

        /// Emitted when an expired or otherwise non-tradable EthFlow
        /// order is invalidated and its unfilled native token is refunded.
        event OrderRefund(bytes orderUid, address indexed refunder);

        // --- errors ---

        /// An order with the same settlement hash already exists.
        error OrderIsAlreadyOwned(bytes32 orderHash);
        /// The EthFlow order is expired at creation time.
        error OrderIsAlreadyExpired();
        /// `msg.value` does not equal `sellAmount + feeAmount`.
        error IncorrectEthAmount();
        /// EthFlow rejects zero-amount sells.
        error NotAllowedZeroSellAmount();
        /// EthFlow rejects `address(0)` receivers because the contract owns
        /// the settlement order.
        error ReceiverMustBeSet();
        /// Caller is not allowed to invalidate this order.
        error NotAllowedToInvalidateOrder(bytes32 orderHash);
        /// Native-token refund transfer failed.
        error EthTransferFailed();

        // --- writes ---

        /// Create and broadcast an EthFlow order.
        function createOrder(EthFlowOrderData order) external payable returns (bytes32 orderHash);

        /// Invalidate multiple orders, ignoring entries that cannot be
        /// invalidated by the caller.
        function invalidateOrdersIgnoringNotAllowed(EthFlowOrderData[] orderArray) external;

        /// Invalidate one EthFlow order and refund any unfilled native token.
        function invalidateOrder(EthFlowOrderData order) external;

        /// Wrap the contract's whole native-token balance.
        function wrapAll() external;

        /// Wrap `amount` native token into the chain's wrapped native token.
        function wrap(uint256 amount) external;

        /// Unwrap `amount` wrapped native token into native token.
        function unwrap(uint256 amount) external;

        // --- views ---

        /// EIP-1271 signature check used by settlement.
        function isValidSignature(bytes32 orderHash, bytes signature) external view returns (bytes4 magicValue);

        /// Settlement contract configured at construction.
        function cowSwapSettlement() external view returns (address);

        /// Wrapped native token configured at construction.
        function wrappedNativeToken() external view returns (address);

        /// Stored owner and user-facing expiry for an EthFlow order hash.
        function orders(bytes32 orderHash) external view returns (address owner, uint32 validTo);
    }

    /// On-chain signature scheme variants accepted by
    /// [`CoWSwapOnchainOrders`]. Mirrors the `OnchainSigningScheme`
    /// Solidity enum at
    /// [`CoWSwapOnchainOrders.sol`](https://github.com/cowprotocol/ethflowcontract/blob/main/src/mixins/CoWSwapOnchainOrders.sol).
    #[derive(Debug, Eq, PartialEq)]
    enum OnchainSigningScheme {
        /// EIP-1271 contract signature (the placer is a contract that
        /// implements `isValidSignature`).
        Eip1271,
        /// Pre-signature recorded on the settlement contract via
        /// `GPv2Signing::setPreSignature`.
        PreSign,
    }

    /// Signature payload accompanying an on-chain order placement.
    /// Mirrors `CoWSwapOnchainOrders.OnchainSignature`.
    #[derive(Debug, Eq, PartialEq)]
    struct OnchainSignature {
        OnchainSigningScheme scheme;
        bytes data;
    }

    /// Events emitted by `CoWSwapOnchainOrders`, the mixin every ETH-flow
    /// or contract-placed-order entry point inherits. Off-chain indexers
    /// watch [`OrderPlacement`] to learn that a new on-chain order has
    /// been registered and [`OrderInvalidation`] to mark it cancelled.
    ///
    /// Source:
    /// [`CoWSwapOnchainOrders.sol`](https://github.com/cowprotocol/ethflowcontract/blob/main/src/mixins/CoWSwapOnchainOrders.sol).
    #[derive(Debug)]
    interface CoWSwapOnchainOrders {
        /// Emitted when a contract registers a new on-chain order. The
        /// embedded `GPv2OrderData` is the exact 12-field payload the
        /// settlement contract will verify; `signature` carries the
        /// scheme (`PreSign` or `EIP-1271`) and any contract-specific
        /// payload; `data` is opaque metadata the contract chose to
        /// publish (e.g. ETH-flow's refund pointer).
        event OrderPlacement(
            address indexed sender,
            GPv2OrderData order,
            OnchainSignature signature,
            bytes data
        );

        /// Emitted when a previously placed on-chain order is
        /// invalidated, either by the placer or by an authorised
        /// invalidator. The body is the 56-byte order UID.
        ///
        /// Note the naming overlap with [`GPv2Settlement::OrderInvalidated`]:
        /// the two events live on different contracts (the settlement
        /// singleton vs the ETH-flow / on-chain-orders mixin) and have
        /// different topic hashes. Indexers should match on
        /// `log.topics[0]` against the canonical signature hash of the
        /// event they actually care about.
        event OrderInvalidation(bytes orderUid);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy_primitives::{Bytes, keccak256};
    use alloy_sol_types::{SolCall, SolError, SolEvent};

    /// `GPv2Settlement::setPreSignature(bytes,bool)` must encode to the same
    /// 4-byte selector as `keccak256("setPreSignature(bytes,bool)")[..4]`.
    /// This is what relayers and solvers match against when decoding
    /// settlement-bound transactions.
    #[test]
    fn set_pre_signature_selector_matches_keccak() {
        let expected = &keccak256("setPreSignature(bytes,bool)")[..4];
        assert_eq!(&GPv2Settlement::setPreSignatureCall::SELECTOR, expected);
    }

    /// Encoding `setPreSignature((uid, true))` must round-trip back to the
    /// same `(uid, true)` and start with the canonical selector. This locks
    /// the call's wire format against accidental field reordering.
    #[test]
    fn set_pre_signature_call_round_trips() {
        let uid = Bytes::from(vec![0xab; 56]);
        let call = GPv2Settlement::setPreSignatureCall {
            orderUid: uid.clone(),
            signed: true,
        };
        let encoded = call.abi_encode();
        assert_eq!(
            &encoded[..4],
            &GPv2Settlement::setPreSignatureCall::SELECTOR
        );
        let decoded = GPv2Settlement::setPreSignatureCall::abi_decode(&encoded).unwrap();
        assert_eq!(decoded.orderUid, uid);
        assert!(decoded.signed);
    }

    /// `ERC20::approve(address,uint256)` must encode to the well-known
    /// `0x095ea7b3` selector that every block explorer recognises.
    #[test]
    fn erc20_approve_selector_matches_keccak() {
        let expected = &keccak256("approve(address,uint256)")[..4];
        assert_eq!(&ERC20::approveCall::SELECTOR, expected);
        assert_eq!(ERC20::approveCall::SELECTOR, [0x09, 0x5e, 0xa7, 0xb3]);
    }

    /// `WETH9::deposit()` must encode to the well-known `0xd0e30db0`
    /// selector used by every WETH wrapper in the wild.
    #[test]
    fn weth9_deposit_selector_matches_keccak() {
        let expected = &keccak256("deposit()")[..4];
        assert_eq!(&WETH9::depositCall::SELECTOR, expected);
        assert_eq!(WETH9::depositCall::SELECTOR, [0xd0, 0xe3, 0x0d, 0xb0]);
    }

    /// `settle(address[],uint256[],GPv2TradeData[],GPv2InteractionData[][3])`
    /// must compute to the canonical 4-byte selector `0x13d79a0b` that
    /// solvers and block explorers match against. Locks the typed Rust
    /// signature against the on-chain ABI.
    #[test]
    fn settle_selector_matches_keccak() {
        let expected = &keccak256(
            "settle(address[],uint256[],(uint256,uint256,address,uint256,uint256,uint32,bytes32,uint256,uint256,uint256,bytes)[],(address,uint256,bytes)[][3])",
        )[..4];
        assert_eq!(&GPv2Settlement::settleCall::SELECTOR, expected);
        assert_eq!(
            GPv2Settlement::settleCall::SELECTOR,
            [0x13, 0xd7, 0x9a, 0x0b]
        );
    }

    /// The five `GPv2Settlement` event topic hashes must match the
    /// canonical `keccak256(signature)` values, so off-chain indexers
    /// matching `log.topics[0]` against this Rust constant pick up every
    /// settlement event without drift.
    #[test]
    fn settlement_event_topic_hashes_match_keccak() {
        // Trade(address,address,address,uint256,uint256,uint256,bytes)
        assert_eq!(
            GPv2Settlement::Trade::SIGNATURE_HASH,
            keccak256("Trade(address,address,address,uint256,uint256,uint256,bytes)")
        );
        // Interaction(address,uint256,bytes4)
        assert_eq!(
            GPv2Settlement::Interaction::SIGNATURE_HASH,
            keccak256("Interaction(address,uint256,bytes4)")
        );
        // Settlement(address)
        assert_eq!(
            GPv2Settlement::Settlement::SIGNATURE_HASH,
            keccak256("Settlement(address)")
        );
        // OrderInvalidated(address,bytes)
        assert_eq!(
            GPv2Settlement::OrderInvalidated::SIGNATURE_HASH,
            keccak256("OrderInvalidated(address,bytes)")
        );
        // PreSignature(address,bytes,bool)
        assert_eq!(
            GPv2Settlement::PreSignature::SIGNATURE_HASH,
            keccak256("PreSignature(address,bytes,bool)")
        );
    }

    /// `GPv2Settlement::Trade` log round-trips: encode the data segment,
    /// decode it back, and verify every non-indexed field. The indexed
    /// `owner` rides in `topics[1]` so it is verified separately by
    /// callers that decode logs end-to-end.
    #[test]
    fn trade_event_data_round_trips() {
        let event = GPv2Settlement::Trade {
            owner: address!("70997970C51812dc3A010C7d01b50e0d17dc79C8"),
            sellToken: address!("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
            buyToken: address!("6B175474E89094C44Da98b954EedeAC495271d0F"),
            sellAmount: alloy_primitives::U256::from(1_000_000u64),
            buyAmount: alloy_primitives::U256::from(999_000_000_000_000_000u128),
            feeAmount: alloy_primitives::U256::from(123u64),
            orderUid: Bytes::from(vec![0xab; 56]),
        };
        let data = event.encode_data();
        let decoded = GPv2Settlement::Trade::abi_decode_data(&data).unwrap();
        // abi_decode_data returns a tuple of the non-indexed fields, in
        // declaration order: (sellToken, buyToken, sellAmount, buyAmount,
        // feeAmount, orderUid).
        assert_eq!(decoded.0, event.sellToken);
        assert_eq!(decoded.1, event.buyToken);
        assert_eq!(decoded.2, event.sellAmount);
        assert_eq!(decoded.3, event.buyAmount);
        assert_eq!(decoded.4, event.feeAmount);
        assert_eq!(decoded.5, event.orderUid);
    }

    /// Lock the `CoWSwapOnchainOrders` event topic hashes against the
    /// canonical Solidity signatures so off-chain indexers matching
    /// `log.topics[0]` against these Rust constants pick up every emitted
    /// event from the ETH-flow and on-chain-orders mixin.
    #[test]
    fn cowswap_onchain_orders_event_topic_hashes_match_keccak() {
        assert_eq!(
            CoWSwapOnchainOrders::OrderPlacement::SIGNATURE_HASH,
            keccak256(
                "OrderPlacement(address,(address,address,address,uint256,uint256,\
                 uint32,bytes32,uint256,bytes32,bool,bytes32,bytes32),(uint8,bytes),bytes)"
            )
        );
        assert_eq!(
            CoWSwapOnchainOrders::OrderInvalidation::SIGNATURE_HASH,
            keccak256("OrderInvalidation(bytes)")
        );
    }

    #[test]
    fn cowswap_eth_flow_selectors_match_keccak() {
        let order = "(address,address,uint256,uint256,bytes32,uint256,uint32,bool,int64)";
        let cases: &[(&[u8; 4], String)] = &[
            (
                &CoWSwapEthFlow::createOrderCall::SELECTOR,
                format!("createOrder({order})"),
            ),
            (
                &CoWSwapEthFlow::invalidateOrderCall::SELECTOR,
                format!("invalidateOrder({order})"),
            ),
            (
                &CoWSwapEthFlow::invalidateOrdersIgnoringNotAllowedCall::SELECTOR,
                format!("invalidateOrdersIgnoringNotAllowed({order}[])"),
            ),
            (
                &CoWSwapEthFlow::wrapAllCall::SELECTOR,
                "wrapAll()".to_string(),
            ),
            (
                &CoWSwapEthFlow::wrapCall::SELECTOR,
                "wrap(uint256)".to_string(),
            ),
            (
                &CoWSwapEthFlow::unwrapCall::SELECTOR,
                "unwrap(uint256)".to_string(),
            ),
            (
                &CoWSwapEthFlow::isValidSignatureCall::SELECTOR,
                "isValidSignature(bytes32,bytes)".to_string(),
            ),
        ];

        for (selector, signature) in cases {
            assert_eq!(
                selector.as_slice(),
                &keccak256(signature.as_bytes())[..4],
                "selector for {signature}",
            );
        }
    }

    #[test]
    fn cowswap_eth_flow_error_selectors_match_keccak() {
        let cases: &[(&[u8; 4], &[u8])] = &[
            (
                &CoWSwapEthFlow::OrderIsAlreadyOwned::SELECTOR,
                b"OrderIsAlreadyOwned(bytes32)",
            ),
            (
                &CoWSwapEthFlow::OrderIsAlreadyExpired::SELECTOR,
                b"OrderIsAlreadyExpired()",
            ),
            (
                &CoWSwapEthFlow::IncorrectEthAmount::SELECTOR,
                b"IncorrectEthAmount()",
            ),
            (
                &CoWSwapEthFlow::NotAllowedZeroSellAmount::SELECTOR,
                b"NotAllowedZeroSellAmount()",
            ),
            (
                &CoWSwapEthFlow::ReceiverMustBeSet::SELECTOR,
                b"ReceiverMustBeSet()",
            ),
            (
                &CoWSwapEthFlow::NotAllowedToInvalidateOrder::SELECTOR,
                b"NotAllowedToInvalidateOrder(bytes32)",
            ),
            (
                &CoWSwapEthFlow::EthTransferFailed::SELECTOR,
                b"EthTransferFailed()",
            ),
        ];

        for (selector, signature) in cases {
            assert_eq!(
                selector.as_slice(),
                &keccak256(signature)[..4],
                "selector for {}",
                std::str::from_utf8(signature).unwrap(),
            );
        }
    }

    #[test]
    fn cowswap_eth_flow_create_order_call_round_trips() {
        let order = EthFlowOrderData {
            buyToken: address!("6B175474E89094C44Da98b954EedeAC495271d0F"),
            receiver: address!("DeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF"),
            sellAmount: alloy_primitives::U256::from(1_000_000_u64),
            buyAmount: alloy_primitives::U256::from(999_000_u64),
            appData: B256::repeat_byte(0xab),
            feeAmount: alloy_primitives::U256::from(12_345_u64),
            validTo: 1_700_000_000,
            partiallyFillable: false,
            quoteId: 42,
        };
        let call = CoWSwapEthFlow::createOrderCall {
            order: order.clone(),
        };

        let encoded = call.abi_encode();
        assert_eq!(&encoded[..4], &CoWSwapEthFlow::createOrderCall::SELECTOR);
        let decoded = CoWSwapEthFlow::createOrderCall::abi_decode(&encoded).unwrap();
        assert_eq!(decoded.order, order);
    }

    #[test]
    fn cowswap_eth_flow_event_topic_hashes_match_keccak() {
        assert_eq!(
            CoWSwapEthFlow::OrderRefund::SIGNATURE_HASH,
            keccak256("OrderRefund(bytes,address)")
        );
    }

    /// Pin the GPv2 deployment hex literals so a copy-paste regression
    /// on the constants (e.g. relayer overwriting settlement) breaks the
    /// build instead of silently shipping orders to the wrong contract.
    #[test]
    fn deployment_addresses_match_canonical_hex_literals() {
        assert_eq!(
            GPV2_SETTLEMENT,
            address!("9008D19f58AAbD9eD0D60971565AA8510560ab41")
        );
        assert_eq!(
            GPV2_VAULT_RELAYER,
            address!("C92E8bdf79f0507f65a392b0ab4667716BFE0110")
        );
        assert_ne!(GPV2_SETTLEMENT, GPV2_VAULT_RELAYER);
    }
}