Skip to main content

hypercall_client/
rfq_v2_signing.rs

1//! EIP-712 signing for every RFQ V2 action.
2//!
3//! The [`crate::rfq_v2`] transport methods take complete signed requests.
4//! This module builds those requests. Each action has a pure message builder
5//! (`rfq_v2_*_message`) that returns the exact EIP-712 struct the server
6//! verifies, and a [`HypercallWallet`] method that signs it under the
7//! Hypercall domain (name `Hypercall`, version `1`, the wallet's chain ID,
8//! zero verifying contract) and returns the wire request.
9//!
10//! A remote signer that cannot use [`HypercallWallet`] signs
11//! [`rfq_v2_signing_hash`] of the same message and wraps the 65-byte result
12//! in [`hypercall_sdk_types::RfqV2Signature`].
13//!
14//! | Action | Message | Signer |
15//! | --- | --- | --- |
16//! | Create RFQ | [`AuthorizeRfqV2`] | Taker |
17//! | Firm quote | [`AuthorizeRfqQuoteV2`] | Maker |
18//! | Indicative quote | [`PublishRfqIndicativeQuoteV2`] | Maker |
19//! | Firm-up request | [`RequestFirmRfqQuoteV2`] | Taker |
20//! | Decline | [`DeclineRfqV2`] | Maker |
21//! | Execute or sweep | [`ExecuteRfqV2`] | Taker |
22//! | Cancel RFQ, withdraw quote | [`InvalidateRfqV2`] | Taker, maker |
23//! | Bulk withdrawal | [`BulkWithdrawRfqV2`] | Maker |
24//! | Cancel schedule | [`ScheduleRfqQuoteCancelV2`] | Maker |
25//! | Replace RFQ or quote | [`ReplaceRfqV2`] | Taker, maker |
26//!
27//! These builders check only what changes the signed bytes or makes them
28//! ambiguous. Economic policy (fill grids, deadlines, routing limits) is
29//! the server's to enforce, and it answers a violation with a 4xx.
30//!
31//! ```rust,no_run
32//! use hypercall_client::rfq_v2_signing::RfqV2ActionAuth;
33//! use hypercall_client::{HypercallClient, HypercallWallet};
34//! use uuid::Uuid;
35//!
36//! # async fn example(rfq_id: Uuid, quote_id: Uuid) -> hypercall_client::Result<()> {
37//! let client = HypercallClient::new("https://api.hypercall.xyz");
38//! let wallet = HypercallWallet::from_private_key("0xYOUR_PRIVATE_KEY", 999)?;
39//! let now = client.server_now_ms().await?;
40//! // Execute one package against a firm quote, with no builder fee.
41//! let execution = wallet
42//!     .sign_rfq_v2_execution(rfq_id, quote_id, 1_000_000, 0, RfqV2ActionAuth::new(now + 30_000, now))
43//!     .await?;
44//! client.execute_rfq_v2(rfq_id, &execution).await?;
45//! # Ok(())
46//! # }
47//! ```
48
49use alloy::{
50    primitives::{keccak256, Address, FixedBytes, B256, U256},
51    sol,
52    sol_types::{Eip712Domain, SolStruct},
53};
54use uuid::Uuid;
55
56use hypercall_sdk_types::{
57    CreateRfqV2Request, DeclineRfqV2Request, PublishRfqV2FirmQuoteRequest,
58    PublishRfqV2IndicativeQuoteRequest, RequestRfqV2FirmQuoteRequest, RfqV2BulkWithdrawalRequest,
59    RfqV2BulkWithdrawalScope, RfqV2Digest, RfqV2ExecutionMode, RfqV2ExecutionRequest,
60    RfqV2FeeLimits, RfqV2FillPolicy, RfqV2FirmQuoteTerms, RfqV2IndicativeQuoteTerms,
61    RfqV2InvalidationRequest, RfqV2PackageLeg, RfqV2PricedLeg, RfqV2QuotePolicy,
62    RfqV2QuoteReplacement, RfqV2ReplacementRequest, RfqV2Routing, RfqV2ScheduledQuoteCancelRequest,
63    RfqV2Side, RfqV2SweepAllocation, RfqV2SweepRequest, RfqV2TakerIdentity, RfqV2Terms,
64    RfqV2WithdrawalPolicy, WalletAddress,
65};
66
67use crate::{ClientError, HypercallWallet, Result};
68
69/// Most quotes one execution or sweep may name.
70pub const MAX_RFQ_V2_EXECUTION_ALLOCATIONS: usize = 1024;
71/// Most exact quote targets one bulk withdrawal may name.
72pub const MAX_RFQ_V2_BULK_WITHDRAWAL_QUOTES: usize = 64;
73
74sol! {
75    // Every struct below must match the RFQ service's EIP-712 types exactly:
76    // field names, order and widths are all part of the type hash.
77
78    #[derive(Debug, PartialEq, Eq)]
79    struct RfqV2SigningLeg {
80        bytes32 instrumentId;
81        uint8 takerSide;
82        uint128 quantityMicrosPerUnit;
83    }
84
85    #[derive(Debug, PartialEq, Eq)]
86    struct RfqV2SigningFeeLimits {
87        uint128 perExecutionMicros;
88        uint128 cumulativeMicros;
89    }
90
91    /// Immutable taker terms. Its struct hash is the parent commitment every
92    /// quote signs as `rfqTermsCommitment`.
93    #[derive(Debug, PartialEq, Eq)]
94    struct RfqV2SigningTerms {
95        bytes16 rfqId;
96        address takerAccount;
97        RfqV2SigningLeg[] legs;
98        uint128 targetUnits;
99        uint8 fillPolicy;
100        uint128 minimumUnits;
101        uint128 stepUnits;
102        uint8 executionMode;
103        bool autoMakerReceivesPremium;
104        uint128 autoPremiumLimitMicros;
105        uint8 quotePolicy;
106        uint8 takerIdentity;
107        uint8 routingMode;
108        address[] selectedMakers;
109        uint64 quoteDeadlineMs;
110        uint64 expiresAtMs;
111        RfqV2SigningFeeLimits feeLimits;
112        address builder;
113        bytes32 privateTermsBlinding;
114    }
115
116    /// Taker authorization to admit one RFQ.
117    #[derive(Debug, PartialEq, Eq)]
118    struct AuthorizeRfqV2 {
119        RfqV2SigningTerms terms;
120        uint64 nonce;
121    }
122
123    #[derive(Debug, PartialEq, Eq)]
124    struct RfqV2SigningPriceLeg {
125        bytes32 instrumentId;
126        uint128 priceMicros;
127    }
128
129    #[derive(Debug, PartialEq, Eq)]
130    struct RfqFirmQuoteV2SigningTerms {
131        bytes16 quoteId;
132        bytes16 rfqId;
133        bytes32 rfqTermsCommitment;
134        address makerAccount;
135        uint64 makerGeneration;
136        uint64 rfqGeneration;
137        RfqV2SigningPriceLeg[] pricedLegs;
138        uint128 referenceQuantity;
139        bool makerReceivesReferencePremium;
140        uint128 referencePremiumMicros;
141        uint128 capacity;
142        uint8 fillPolicy;
143        uint128 minimumUnits;
144        uint128 stepUnits;
145        uint8 withdrawalPolicy;
146        RfqV2SigningFeeLimits feeLimits;
147        uint64 expiresAtMs;
148        bytes32 protectionScope;
149        bool hasSourceIndicativeQuote;
150        bytes16 sourceIndicativeQuoteId;
151    }
152
153    /// Maker authorization to admit one executable quote.
154    #[derive(Debug, PartialEq, Eq)]
155    struct AuthorizeRfqQuoteV2 {
156        RfqFirmQuoteV2SigningTerms terms;
157        uint64 nonce;
158    }
159
160    #[derive(Debug, PartialEq, Eq)]
161    struct RfqIndicativeQuoteV2SigningTerms {
162        bytes16 quoteId;
163        bytes16 rfqId;
164        bytes32 rfqTermsCommitment;
165        address makerAccount;
166        RfqV2SigningPriceLeg[] pricedLegs;
167        uint128 referenceQuantity;
168        bool makerReceivesReferencePremium;
169        uint128 referencePremiumMicros;
170        uint128 indicatedCapacity;
171        uint64 expiresAtMs;
172    }
173
174    /// Non-executable maker price discovery. The quote ID is the replay key,
175    /// so there is no nonce.
176    #[derive(Debug, PartialEq, Eq)]
177    struct PublishRfqIndicativeQuoteV2 {
178        RfqIndicativeQuoteV2SigningTerms terms;
179    }
180
181    /// One ordered allocation. Order is signed: a sweep fills in this order.
182    #[derive(Debug, PartialEq, Eq)]
183    struct RfqV2ExecutionAllocation {
184        bytes16 quoteId;
185        uint128 packageUnits;
186    }
187
188    /// Taker authorization for one execution or an atomic sweep.
189    #[derive(Debug, PartialEq, Eq)]
190    struct ExecuteRfqV2 {
191        bytes16 rfqId;
192        bytes16 operationId;
193        RfqV2ExecutionAllocation[] allocations;
194        uint128 maxFeeMicros;
195        uint64 expiresAtMs;
196        uint64 nonce;
197    }
198
199    /// One parent cancellation or quote withdrawal.
200    #[derive(Debug, PartialEq, Eq)]
201    struct InvalidateRfqV2 {
202        bytes16 rfqId;
203        bytes16 quoteId;
204        uint8 scope;
205        uint8 reason;
206        bytes16 operationId;
207        uint64 expiresAtMs;
208        uint64 nonce;
209    }
210
211    #[derive(Debug, PartialEq, Eq)]
212    struct RfqV2BulkWithdrawalTarget {
213        bytes16 rfqId;
214        bytes16 quoteId;
215    }
216
217    /// One maker action over exact quote IDs, one RFQ, or all open quotes.
218    #[derive(Debug, PartialEq, Eq)]
219    struct BulkWithdrawRfqV2 {
220        address makerAccount;
221        uint8 scope;
222        bytes16 rfqId;
223        RfqV2BulkWithdrawalTarget[] targets;
224        bytes16 operationId;
225        uint64 expiresAtMs;
226        uint64 nonce;
227    }
228
229    /// Renew or remove the maker's account-wide quote cancel deadline.
230    /// `cancelAtMs` zero removes it.
231    #[derive(Debug, PartialEq, Eq)]
232    struct ScheduleRfqQuoteCancelV2 {
233        bytes16 operationId;
234        address makerAccount;
235        uint64 cancelAtMs;
236        uint64 expiresAtMs;
237        uint64 nonce;
238    }
239
240    /// Atomic replacement of an RFQ or a quote by a newly signed successor.
241    #[derive(Debug, PartialEq, Eq)]
242    struct ReplaceRfqV2 {
243        bytes16 rfqId;
244        bytes16 oldObjectId;
245        bytes16 newObjectId;
246        uint8 scope;
247        bytes16 operationId;
248        uint64 expiresAtMs;
249        uint64 nonce;
250    }
251
252    /// Taker asks the maker of one indicative quote for firm terms.
253    #[derive(Debug, PartialEq, Eq)]
254    struct RequestFirmRfqQuoteV2 {
255        bytes16 operationId;
256        bytes16 rfqId;
257        bytes16 indicativeQuoteId;
258        uint128 requestedUnits;
259        uint64 expiresAtMs;
260        uint64 nonce;
261    }
262
263    /// A routed maker declines to quote one RFQ.
264    #[derive(Debug, PartialEq, Eq)]
265    struct DeclineRfqV2 {
266        bytes16 rfqId;
267        address makerAccount;
268        bytes16 operationId;
269        uint64 expiresAtMs;
270        uint64 nonce;
271    }
272}
273
274/// The signed fields every RFQ V2 lifecycle action carries besides its
275/// subject: a fresh UUIDv7 operation ID, the signature expiry, and a nonce.
276///
277/// Reuse an operation ID only to resend the identical signed request.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub struct RfqV2ActionAuth {
280    pub operation_id: Uuid,
281    pub expires_at_ms: u64,
282    pub nonce: u64,
283}
284
285impl RfqV2ActionAuth {
286    /// Mint a fresh UUIDv7 operation ID for a new action.
287    pub fn new(expires_at_ms: u64, nonce: u64) -> Self {
288        Self {
289            operation_id: Uuid::now_v7(),
290            expires_at_ms,
291            nonce,
292        }
293    }
294}
295
296/// What an [`InvalidateRfqV2`] retires.
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298pub enum RfqV2InvalidationTarget {
299    /// The taker cancels its RFQ.
300    CancelRfq { rfq_id: Uuid },
301    /// The maker withdraws one of its quotes.
302    WithdrawQuote { rfq_id: Uuid, quote_id: Uuid },
303}
304
305/// What a [`ReplaceRfqV2`] retires in favour of its successor.
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
307pub enum RfqV2ReplacementTarget {
308    Rfq { rfq_id: Uuid },
309    Quote { rfq_id: Uuid, quote_id: Uuid },
310}
311
312/// The EIP-712 domain RFQ V2 messages are signed under.
313pub fn rfq_v2_domain(chain_id: u64) -> Eip712Domain {
314    Eip712Domain {
315        name: Some("Hypercall".into()),
316        version: Some("1".into()),
317        chain_id: Some(alloy::primitives::U256::from(chain_id)),
318        verifying_contract: Some(Address::ZERO),
319        salt: None,
320    }
321}
322
323/// The digest a signer signs for `message` on `chain_id`.
324pub fn rfq_v2_signing_hash<T: SolStruct>(message: &T, chain_id: u64) -> B256 {
325    message.eip712_signing_hash(&rfq_v2_domain(chain_id))
326}
327
328/// Signed instrument identity: `keccak256("instrument" ‖ symbol)`.
329pub fn rfq_v2_instrument_id(symbol: &str) -> B256 {
330    let mut preimage = Vec::with_capacity(10 + symbol.len());
331    preimage.extend_from_slice(b"instrument");
332    preimage.extend_from_slice(symbol.as_bytes());
333    keccak256(preimage)
334}
335
336/// The commitment quotes sign as `rfq_terms_commitment`. The server returns
337/// the same value as `terms_commitment` when the RFQ is created; a maker that
338/// cannot see the full terms reads it from the RFQ instead.
339#[expect(
340    clippy::result_large_err,
341    reason = "public client methods preserve the established unboxed ClientError contract"
342)]
343pub fn rfq_v2_terms_commitment(terms: &RfqV2Terms) -> Result<RfqV2Digest> {
344    Ok(RfqV2Digest(
345        rfq_v2_signing_terms(terms)?.eip712_hash_struct(),
346    ))
347}
348
349/// The taker message for `POST /private/rfqs`.
350#[expect(
351    clippy::result_large_err,
352    reason = "public client methods preserve the established unboxed ClientError contract"
353)]
354pub fn rfq_v2_create_message(terms: &RfqV2Terms, nonce: u64) -> Result<AuthorizeRfqV2> {
355    Ok(AuthorizeRfqV2 {
356        terms: rfq_v2_signing_terms(terms)?,
357        nonce,
358    })
359}
360
361/// The maker message for a firm quote.
362pub fn rfq_v2_firm_quote_message(terms: &RfqV2FirmQuoteTerms, nonce: u64) -> AuthorizeRfqQuoteV2 {
363    let (fill_policy, minimum_units, step_units) = fill_policy_fields(terms.fill_policy);
364    AuthorizeRfqQuoteV2 {
365        terms: RfqFirmQuoteV2SigningTerms {
366            quoteId: uuid_bytes(terms.id),
367            rfqId: uuid_bytes(terms.rfq_id),
368            rfqTermsCommitment: terms.rfq_terms_commitment.0,
369            makerAccount: terms.maker_account.inner(),
370            makerGeneration: terms.maker_generation,
371            rfqGeneration: terms.rfq_generation,
372            pricedLegs: priced_legs(&terms.priced_legs),
373            referenceQuantity: terms.reference_quantity,
374            makerReceivesReferencePremium: terms.maker_receives_reference_premium,
375            referencePremiumMicros: terms.reference_premium_micros,
376            capacity: terms.capacity,
377            fillPolicy: fill_policy,
378            minimumUnits: minimum_units,
379            stepUnits: step_units,
380            withdrawalPolicy: match terms.withdrawal_policy {
381                RfqV2WithdrawalPolicy::NotPermitted => 0,
382                RfqV2WithdrawalPolicy::Permitted => 1,
383            },
384            feeLimits: fee_limits(terms.fee_limits),
385            expiresAtMs: terms.expires_at_ms,
386            protectionScope: terms.protection_scope.map_or(B256::ZERO, |scope| scope.0),
387            hasSourceIndicativeQuote: terms.source_indicative_quote_id.is_some(),
388            sourceIndicativeQuoteId: terms
389                .source_indicative_quote_id
390                .map_or(FixedBytes::ZERO, uuid_bytes),
391        },
392        nonce,
393    }
394}
395
396/// The maker message for an indicative quote.
397pub fn rfq_v2_indicative_quote_message(
398    terms: &RfqV2IndicativeQuoteTerms,
399) -> PublishRfqIndicativeQuoteV2 {
400    PublishRfqIndicativeQuoteV2 {
401        terms: RfqIndicativeQuoteV2SigningTerms {
402            quoteId: uuid_bytes(terms.id),
403            rfqId: uuid_bytes(terms.rfq_id),
404            rfqTermsCommitment: terms.rfq_terms_commitment.0,
405            makerAccount: terms.maker_account.inner(),
406            pricedLegs: priced_legs(&terms.priced_legs),
407            referenceQuantity: terms.reference_quantity,
408            makerReceivesReferencePremium: terms.maker_receives_reference_premium,
409            referencePremiumMicros: terms.reference_premium_micros,
410            indicatedCapacity: terms.indicated_capacity,
411            expiresAtMs: terms.expires_at_ms,
412        },
413    }
414}
415
416/// The taker message asking the maker of `indicative_quote_id` for firm terms.
417pub fn rfq_v2_firm_up_message(
418    rfq_id: Uuid,
419    indicative_quote_id: Uuid,
420    requested_units: u128,
421    auth: RfqV2ActionAuth,
422) -> RequestFirmRfqQuoteV2 {
423    RequestFirmRfqQuoteV2 {
424        operationId: uuid_bytes(auth.operation_id),
425        rfqId: uuid_bytes(rfq_id),
426        indicativeQuoteId: uuid_bytes(indicative_quote_id),
427        requestedUnits: requested_units,
428        expiresAtMs: auth.expires_at_ms,
429        nonce: auth.nonce,
430    }
431}
432
433/// The maker message declining to quote `rfq_id`.
434pub fn rfq_v2_decline_message(
435    rfq_id: Uuid,
436    maker_account: WalletAddress,
437    auth: RfqV2ActionAuth,
438) -> DeclineRfqV2 {
439    DeclineRfqV2 {
440        rfqId: uuid_bytes(rfq_id),
441        makerAccount: maker_account.inner(),
442        operationId: uuid_bytes(auth.operation_id),
443        expiresAtMs: auth.expires_at_ms,
444        nonce: auth.nonce,
445    }
446}
447
448/// The taker message for one execution (one allocation) or a sweep.
449///
450/// Refuses an empty list, more than [`MAX_RFQ_V2_EXECUTION_ALLOCATIONS`]
451/// allocations, and a repeated quote ID, as the server does.
452#[expect(
453    clippy::result_large_err,
454    reason = "public client methods preserve the established unboxed ClientError contract"
455)]
456pub fn rfq_v2_execution_message(
457    rfq_id: Uuid,
458    allocations: &[RfqV2SweepAllocation],
459    max_fee_micros: u128,
460    auth: RfqV2ActionAuth,
461) -> Result<ExecuteRfqV2> {
462    if allocations.is_empty() {
463        return Err(invalid("RFQ V2 execution requires at least one allocation"));
464    }
465    if allocations.len() > MAX_RFQ_V2_EXECUTION_ALLOCATIONS {
466        return Err(invalid(format!(
467            "RFQ V2 execution names {} quotes, maximum is {MAX_RFQ_V2_EXECUTION_ALLOCATIONS}",
468            allocations.len()
469        )));
470    }
471    let mut seen = std::collections::HashSet::with_capacity(allocations.len());
472    if let Some(repeat) = allocations
473        .iter()
474        .find(|allocation| !seen.insert(allocation.quote_id))
475    {
476        return Err(invalid(format!(
477            "RFQ V2 execution repeats quote {}",
478            repeat.quote_id
479        )));
480    }
481    Ok(ExecuteRfqV2 {
482        rfqId: uuid_bytes(rfq_id),
483        operationId: uuid_bytes(auth.operation_id),
484        allocations: allocations
485            .iter()
486            .map(|allocation| RfqV2ExecutionAllocation {
487                quoteId: uuid_bytes(allocation.quote_id),
488                packageUnits: allocation.package_units,
489            })
490            .collect(),
491        maxFeeMicros: max_fee_micros,
492        expiresAtMs: auth.expires_at_ms,
493        nonce: auth.nonce,
494    })
495}
496
497/// The message cancelling an RFQ (taker) or withdrawing a quote (maker).
498pub fn rfq_v2_invalidation_message(
499    target: RfqV2InvalidationTarget,
500    auth: RfqV2ActionAuth,
501) -> InvalidateRfqV2 {
502    // Scope and reason are signed so a withdrawal cannot be replayed as a
503    // cancellation. Reason 2 (replaced) is signed only through ReplaceRfqV2.
504    let (rfq_id, quote_id, scope, reason) = match target {
505        RfqV2InvalidationTarget::CancelRfq { rfq_id } => (rfq_id, FixedBytes::ZERO, 0, 0),
506        RfqV2InvalidationTarget::WithdrawQuote { rfq_id, quote_id } => {
507            (rfq_id, uuid_bytes(quote_id), 1, 1)
508        }
509    };
510    InvalidateRfqV2 {
511        rfqId: uuid_bytes(rfq_id),
512        quoteId: quote_id,
513        scope,
514        reason,
515        operationId: uuid_bytes(auth.operation_id),
516        expiresAtMs: auth.expires_at_ms,
517        nonce: auth.nonce,
518    }
519}
520
521/// The maker message withdrawing a set of its quotes atomically.
522///
523/// Refuses an empty or oversized exact-ID list, a nil or repeated target, and
524/// a nil RFQ ID, as the server does.
525#[expect(
526    clippy::result_large_err,
527    reason = "public client methods preserve the established unboxed ClientError contract"
528)]
529pub fn rfq_v2_bulk_withdrawal_message(
530    maker_account: WalletAddress,
531    scope: &RfqV2BulkWithdrawalScope,
532    auth: RfqV2ActionAuth,
533) -> Result<BulkWithdrawRfqV2> {
534    let (scope_tag, rfq_id, targets) = match scope {
535        RfqV2BulkWithdrawalScope::QuoteIds { quote_ids } => {
536            if quote_ids.is_empty() {
537                return Err(invalid(
538                    "RFQ V2 bulk withdrawal requires at least one quote",
539                ));
540            }
541            if quote_ids.len() > MAX_RFQ_V2_BULK_WITHDRAWAL_QUOTES {
542                return Err(invalid(format!(
543                    "RFQ V2 bulk withdrawal names {} quotes, maximum is {MAX_RFQ_V2_BULK_WITHDRAWAL_QUOTES}",
544                    quote_ids.len()
545                )));
546            }
547            let mut seen = std::collections::HashSet::with_capacity(quote_ids.len());
548            if quote_ids.iter().any(|target| {
549                target.rfq_id.is_nil()
550                    || target.quote_id.is_nil()
551                    || !seen.insert((target.rfq_id, target.quote_id))
552            }) {
553                return Err(invalid(
554                    "RFQ V2 bulk withdrawal contains a nil or repeated quote",
555                ));
556            }
557            let targets = quote_ids
558                .iter()
559                .map(|target| RfqV2BulkWithdrawalTarget {
560                    rfqId: uuid_bytes(target.rfq_id),
561                    quoteId: uuid_bytes(target.quote_id),
562                })
563                .collect();
564            (0, FixedBytes::ZERO, targets)
565        }
566        RfqV2BulkWithdrawalScope::Rfq { rfq_id } => {
567            if rfq_id.is_nil() {
568                return Err(invalid("RFQ V2 bulk withdrawal names the nil RFQ"));
569            }
570            (1, uuid_bytes(*rfq_id), Vec::new())
571        }
572        RfqV2BulkWithdrawalScope::AllOpen => (2, FixedBytes::ZERO, Vec::new()),
573    };
574    Ok(BulkWithdrawRfqV2 {
575        makerAccount: maker_account.inner(),
576        scope: scope_tag,
577        rfqId: rfq_id,
578        targets,
579        operationId: uuid_bytes(auth.operation_id),
580        expiresAtMs: auth.expires_at_ms,
581        nonce: auth.nonce,
582    })
583}
584
585/// The maker message setting (`Some`) or removing (`None`) its account-wide
586/// quote cancel deadline. `Some(0)` is refused: zero is the removal encoding.
587#[expect(
588    clippy::result_large_err,
589    reason = "public client methods preserve the established unboxed ClientError contract"
590)]
591pub fn rfq_v2_quote_cancel_schedule_message(
592    maker_account: WalletAddress,
593    cancel_at_ms: Option<u64>,
594    auth: RfqV2ActionAuth,
595) -> Result<ScheduleRfqQuoteCancelV2> {
596    if cancel_at_ms == Some(0) {
597        return Err(invalid(
598            "RFQ V2 quote cancel deadline must be nonzero; pass None to remove it",
599        ));
600    }
601    Ok(ScheduleRfqQuoteCancelV2 {
602        operationId: uuid_bytes(auth.operation_id),
603        makerAccount: maker_account.inner(),
604        cancelAtMs: cancel_at_ms.unwrap_or(0),
605        expiresAtMs: auth.expires_at_ms,
606        nonce: auth.nonce,
607    })
608}
609
610/// The message retiring `target` in favour of `successor_id`, the ID inside
611/// the replacement's own signed terms.
612pub fn rfq_v2_replacement_message(
613    target: RfqV2ReplacementTarget,
614    successor_id: Uuid,
615    auth: RfqV2ActionAuth,
616) -> ReplaceRfqV2 {
617    let (rfq_id, old_object_id, scope) = match target {
618        RfqV2ReplacementTarget::Rfq { rfq_id } => (rfq_id, rfq_id, 0),
619        RfqV2ReplacementTarget::Quote { rfq_id, quote_id } => (rfq_id, quote_id, 1),
620    };
621    ReplaceRfqV2 {
622        rfqId: uuid_bytes(rfq_id),
623        oldObjectId: uuid_bytes(old_object_id),
624        newObjectId: uuid_bytes(successor_id),
625        scope,
626        operationId: uuid_bytes(auth.operation_id),
627        expiresAtMs: auth.expires_at_ms,
628        nonce: auth.nonce,
629    }
630}
631
632/// The reference premium a quote must sign for `reference_quantity` package
633/// units at `priced_legs`, as `(maker_receives_reference_premium,
634/// reference_premium_micros)`.
635///
636/// The server recomputes this from the parent's legs and refuses a quote
637/// whose signed premium differs. A taker buy leg pays the maker and a taker
638/// sell leg pays the taker; a zero net premium is `(false, 0)`. Pass the
639/// parent's fill `step` for partial-fill policies (`None` for
640/// `full_size_once`): the premium of one step must also be a whole number of
641/// micros.
642#[expect(
643    clippy::result_large_err,
644    reason = "public client methods preserve the established unboxed ClientError contract"
645)]
646pub fn rfq_v2_reference_premium(
647    parent_legs: &[RfqV2PackageLeg],
648    priced_legs: &[RfqV2PricedLeg],
649    reference_quantity: u128,
650    fill_step: Option<u128>,
651) -> Result<(bool, u128)> {
652    if parent_legs.len() != priced_legs.len() {
653        return Err(invalid(format!(
654            "RFQ V2 quote prices {} legs, the RFQ has {}",
655            priced_legs.len(),
656            parent_legs.len()
657        )));
658    }
659    if reference_quantity == 0 {
660        return Err(invalid("RFQ V2 reference quantity must be nonzero"));
661    }
662    let overflow = || invalid("RFQ V2 reference premium overflows");
663    let mut maker_receives = U256::ZERO;
664    let mut taker_receives = U256::ZERO;
665    for (leg, priced) in parent_legs.iter().zip(priced_legs) {
666        if leg.instrument != priced.instrument {
667            return Err(invalid(format!(
668                "RFQ V2 quote prices {} where the RFQ has {}",
669                priced.instrument, leg.instrument
670            )));
671        }
672        let scaled = U256::from(priced.price_micros)
673            .checked_mul(U256::from(leg.quantity_micros_per_unit))
674            .and_then(|value| value.checked_mul(U256::from(reference_quantity)))
675            .ok_or_else(overflow)?;
676        let side_total = match leg.taker_side {
677            RfqV2Side::Buy => &mut maker_receives,
678            RfqV2Side::Sell => &mut taker_receives,
679        };
680        *side_total = side_total.checked_add(scaled).ok_or_else(overflow)?;
681    }
682    let (receives, scaled) = if maker_receives > taker_receives {
683        (true, maker_receives - taker_receives)
684    } else {
685        (false, taker_receives - maker_receives)
686    };
687    // Prices and quantities are both micros, so the product carries 1e12.
688    let denominator = U256::from(1_000_000_u64) * U256::from(1_000_000_u64);
689    if let Some(step) = fill_step {
690        let per_unit = scaled / U256::from(reference_quantity);
691        let per_step = per_unit
692            .checked_mul(U256::from(step))
693            .ok_or_else(overflow)?;
694        if per_step % denominator != U256::ZERO {
695            return Err(invalid(
696                "RFQ V2 premium for one fill step is not a whole number of micros",
697            ));
698        }
699    }
700    if scaled % denominator != U256::ZERO {
701        return Err(invalid(
702            "RFQ V2 reference premium is not a whole number of micros",
703        ));
704    }
705    let premium = u128::try_from(scaled / denominator).map_err(|_| overflow())?;
706    Ok((receives, premium))
707}
708
709impl HypercallWallet {
710    /// Sign RFQ terms for [`crate::HypercallClient::create_rfq_v2`].
711    pub async fn sign_create_rfq_v2(
712        &self,
713        terms: RfqV2Terms,
714        nonce: u64,
715    ) -> Result<CreateRfqV2Request> {
716        let message = rfq_v2_create_message(&terms, nonce)?;
717        let signature = self.sign_rfq_v2_typed_data(&message, "RFQ V2").await?;
718        Ok(CreateRfqV2Request {
719            terms,
720            nonce,
721            signature,
722        })
723    }
724
725    /// Sign a firm quote for
726    /// [`crate::HypercallClient::publish_rfq_v2_firm_quote`].
727    pub async fn sign_rfq_v2_firm_quote(
728        &self,
729        terms: RfqV2FirmQuoteTerms,
730        nonce: u64,
731    ) -> Result<PublishRfqV2FirmQuoteRequest> {
732        let message = rfq_v2_firm_quote_message(&terms, nonce);
733        let signature = self
734            .sign_rfq_v2_typed_data(&message, "RFQ V2 firm quote")
735            .await?;
736        Ok(PublishRfqV2FirmQuoteRequest {
737            terms,
738            nonce,
739            signature,
740        })
741    }
742
743    /// Sign an indicative quote for
744    /// [`crate::HypercallClient::publish_rfq_v2_indicative_quote`].
745    pub async fn sign_rfq_v2_indicative_quote(
746        &self,
747        terms: RfqV2IndicativeQuoteTerms,
748    ) -> Result<PublishRfqV2IndicativeQuoteRequest> {
749        let message = rfq_v2_indicative_quote_message(&terms);
750        let signature = self
751            .sign_rfq_v2_typed_data(&message, "RFQ V2 indicative quote")
752            .await?;
753        Ok(PublishRfqV2IndicativeQuoteRequest { terms, signature })
754    }
755
756    /// Sign a firm-up request for
757    /// [`crate::HypercallClient::request_rfq_v2_firm_quote`].
758    pub async fn sign_rfq_v2_firm_up(
759        &self,
760        rfq_id: Uuid,
761        indicative_quote_id: Uuid,
762        requested_units: u128,
763        auth: RfqV2ActionAuth,
764    ) -> Result<RequestRfqV2FirmQuoteRequest> {
765        let message = rfq_v2_firm_up_message(rfq_id, indicative_quote_id, requested_units, auth);
766        let signature = self
767            .sign_rfq_v2_typed_data(&message, "RFQ V2 firm-up request")
768            .await?;
769        Ok(RequestRfqV2FirmQuoteRequest {
770            operation_id: auth.operation_id,
771            requested_units,
772            expires_at_ms: auth.expires_at_ms,
773            nonce: auth.nonce,
774            signature,
775        })
776    }
777
778    /// Sign a maker decline for [`crate::HypercallClient::decline_rfq_v2`].
779    pub async fn sign_rfq_v2_decline(
780        &self,
781        rfq_id: Uuid,
782        maker_account: WalletAddress,
783        auth: RfqV2ActionAuth,
784    ) -> Result<DeclineRfqV2Request> {
785        let message = rfq_v2_decline_message(rfq_id, maker_account, auth);
786        let signature = self
787            .sign_rfq_v2_typed_data(&message, "RFQ V2 decline")
788            .await?;
789        Ok(DeclineRfqV2Request {
790            operation_id: auth.operation_id,
791            maker_account,
792            expires_at_ms: auth.expires_at_ms,
793            nonce: auth.nonce,
794            signature,
795        })
796    }
797
798    /// Sign one execution against one firm quote for
799    /// [`crate::HypercallClient::execute_rfq_v2`].
800    pub async fn sign_rfq_v2_execution(
801        &self,
802        rfq_id: Uuid,
803        quote_id: Uuid,
804        package_units: u128,
805        max_fee_micros: u128,
806        auth: RfqV2ActionAuth,
807    ) -> Result<RfqV2ExecutionRequest> {
808        let allocation = RfqV2SweepAllocation {
809            quote_id,
810            package_units,
811        };
812        let message = rfq_v2_execution_message(rfq_id, &[allocation], max_fee_micros, auth)?;
813        let signature = self
814            .sign_rfq_v2_typed_data(&message, "RFQ V2 execution")
815            .await?;
816        Ok(RfqV2ExecutionRequest {
817            operation_id: auth.operation_id,
818            quote_id,
819            package_units,
820            max_fee_micros,
821            expires_at_ms: auth.expires_at_ms,
822            nonce: auth.nonce,
823            signature,
824        })
825    }
826
827    /// Sign an ordered, atomic sweep for
828    /// [`crate::HypercallClient::sweep_rfq_v2`].
829    pub async fn sign_rfq_v2_sweep(
830        &self,
831        rfq_id: Uuid,
832        allocations: Vec<RfqV2SweepAllocation>,
833        max_fee_micros: u128,
834        auth: RfqV2ActionAuth,
835    ) -> Result<RfqV2SweepRequest> {
836        let message = rfq_v2_execution_message(rfq_id, &allocations, max_fee_micros, auth)?;
837        let signature = self
838            .sign_rfq_v2_typed_data(&message, "RFQ V2 sweep")
839            .await?;
840        Ok(RfqV2SweepRequest {
841            operation_id: auth.operation_id,
842            allocations,
843            max_fee_micros,
844            expires_at_ms: auth.expires_at_ms,
845            nonce: auth.nonce,
846            signature,
847        })
848    }
849
850    /// Sign a taker cancel for [`crate::HypercallClient::cancel_rfq_v2`] or a
851    /// maker withdrawal for [`crate::HypercallClient::withdraw_rfq_v2_quote`].
852    pub async fn sign_rfq_v2_invalidation(
853        &self,
854        target: RfqV2InvalidationTarget,
855        auth: RfqV2ActionAuth,
856    ) -> Result<RfqV2InvalidationRequest> {
857        let message = rfq_v2_invalidation_message(target, auth);
858        let signature = self
859            .sign_rfq_v2_typed_data(&message, "RFQ V2 invalidation")
860            .await?;
861        Ok(RfqV2InvalidationRequest {
862            operation_id: auth.operation_id,
863            expires_at_ms: auth.expires_at_ms,
864            nonce: auth.nonce,
865            signature,
866        })
867    }
868
869    /// Sign a bulk withdrawal for
870    /// [`crate::HypercallClient::withdraw_rfq_v2_quotes`].
871    pub async fn sign_rfq_v2_bulk_withdrawal(
872        &self,
873        maker_account: WalletAddress,
874        scope: RfqV2BulkWithdrawalScope,
875        auth: RfqV2ActionAuth,
876    ) -> Result<RfqV2BulkWithdrawalRequest> {
877        let message = rfq_v2_bulk_withdrawal_message(maker_account, &scope, auth)?;
878        let signature = self
879            .sign_rfq_v2_typed_data(&message, "RFQ V2 bulk withdrawal")
880            .await?;
881        Ok(RfqV2BulkWithdrawalRequest {
882            operation_id: auth.operation_id,
883            maker_account,
884            scope,
885            expires_at_ms: auth.expires_at_ms,
886            nonce: auth.nonce,
887            signature,
888        })
889    }
890
891    /// Sign the maker dead-man switch for
892    /// [`crate::HypercallClient::schedule_rfq_v2_quote_cancel`]. `None`
893    /// removes the schedule.
894    pub async fn sign_rfq_v2_quote_cancel_schedule(
895        &self,
896        maker_account: WalletAddress,
897        cancel_at_ms: Option<u64>,
898        auth: RfqV2ActionAuth,
899    ) -> Result<RfqV2ScheduledQuoteCancelRequest> {
900        let message = rfq_v2_quote_cancel_schedule_message(maker_account, cancel_at_ms, auth)?;
901        let signature = self
902            .sign_rfq_v2_typed_data(&message, "RFQ V2 quote cancel schedule")
903            .await?;
904        Ok(RfqV2ScheduledQuoteCancelRequest {
905            operation_id: auth.operation_id,
906            maker_account,
907            cancel_at_ms,
908            expires_at_ms: auth.expires_at_ms,
909            nonce: auth.nonce,
910            signature,
911        })
912    }
913
914    /// Sign the replacement of `rfq_id` by an already signed successor RFQ,
915    /// for [`crate::HypercallClient::replace_rfq_v2`].
916    pub async fn sign_rfq_v2_replacement(
917        &self,
918        rfq_id: Uuid,
919        replacement: CreateRfqV2Request,
920        auth: RfqV2ActionAuth,
921    ) -> Result<RfqV2ReplacementRequest<CreateRfqV2Request>> {
922        let message = rfq_v2_replacement_message(
923            RfqV2ReplacementTarget::Rfq { rfq_id },
924            replacement.terms.id,
925            auth,
926        );
927        let signature = self
928            .sign_rfq_v2_typed_data(&message, "RFQ V2 replacement")
929            .await?;
930        Ok(RfqV2ReplacementRequest {
931            operation_id: auth.operation_id,
932            replacement,
933            expires_at_ms: auth.expires_at_ms,
934            nonce: auth.nonce,
935            signature,
936        })
937    }
938
939    /// Sign the replacement of quote `quote_id` by an already signed
940    /// successor quote, for [`crate::HypercallClient::replace_rfq_v2_quote`].
941    pub async fn sign_rfq_v2_quote_replacement(
942        &self,
943        rfq_id: Uuid,
944        quote_id: Uuid,
945        replacement: RfqV2QuoteReplacement,
946        auth: RfqV2ActionAuth,
947    ) -> Result<RfqV2ReplacementRequest<RfqV2QuoteReplacement>> {
948        let successor_id = match &replacement {
949            RfqV2QuoteReplacement::Indicative(quote) => quote.terms.id,
950            RfqV2QuoteReplacement::Firm(quote) => quote.terms.id,
951        };
952        let message = rfq_v2_replacement_message(
953            RfqV2ReplacementTarget::Quote { rfq_id, quote_id },
954            successor_id,
955            auth,
956        );
957        let signature = self
958            .sign_rfq_v2_typed_data(&message, "RFQ V2 quote replacement")
959            .await?;
960        Ok(RfqV2ReplacementRequest {
961            operation_id: auth.operation_id,
962            replacement,
963            expires_at_ms: auth.expires_at_ms,
964            nonce: auth.nonce,
965            signature,
966        })
967    }
968}
969
970#[expect(
971    clippy::result_large_err,
972    reason = "public client methods preserve the established unboxed ClientError contract"
973)]
974fn rfq_v2_signing_terms(terms: &RfqV2Terms) -> Result<RfqV2SigningTerms> {
975    let (fill_policy, minimum_units, step_units) = fill_policy_fields(terms.fill_policy);
976    let (routing_mode, selected_makers) = match &terms.routing {
977        RfqV2Routing::AllEligible => (0, Vec::new()),
978        RfqV2Routing::SelectedMakers { makers } => {
979            // The server signs the canonical (sorted, unique) set. Build it
980            // with `RfqV2Routing::selected_makers` rather than by hand.
981            if makers.windows(2).any(|pair| pair[0] >= pair[1]) {
982                return Err(invalid(
983                    "RFQ V2 selected makers must be sorted ascending without duplicates; \
984                     build them with RfqV2Routing::selected_makers",
985                ));
986            }
987            (1, makers.iter().map(|maker| maker.inner()).collect())
988        }
989    };
990    let (auto_maker_receives_premium, auto_premium_limit_micros) =
991        match (terms.execution_mode, terms.auto_execution_limit) {
992            (RfqV2ExecutionMode::Manual, None) => (false, 0),
993            (RfqV2ExecutionMode::Auto, Some(limit)) => {
994                (limit.maker_receives_premium, limit.premium_micros)
995            }
996            (RfqV2ExecutionMode::Manual, Some(_)) => {
997                return Err(invalid(
998                    "RFQ V2 manual execution must not carry an auto_execution_limit",
999                ))
1000            }
1001            (RfqV2ExecutionMode::Auto, None) => {
1002                return Err(invalid(
1003                    "RFQ V2 auto execution requires an auto_execution_limit",
1004                ))
1005            }
1006        };
1007    Ok(RfqV2SigningTerms {
1008        rfqId: uuid_bytes(terms.id),
1009        takerAccount: terms.taker_account.inner(),
1010        legs: terms
1011            .legs
1012            .iter()
1013            .map(|leg| RfqV2SigningLeg {
1014                instrumentId: rfq_v2_instrument_id(&leg.instrument),
1015                takerSide: match leg.taker_side {
1016                    RfqV2Side::Buy => 0,
1017                    RfqV2Side::Sell => 1,
1018                },
1019                quantityMicrosPerUnit: leg.quantity_micros_per_unit,
1020            })
1021            .collect(),
1022        targetUnits: terms.target,
1023        fillPolicy: fill_policy,
1024        minimumUnits: minimum_units,
1025        stepUnits: step_units,
1026        executionMode: match terms.execution_mode {
1027            RfqV2ExecutionMode::Manual => 0,
1028            RfqV2ExecutionMode::Auto => 1,
1029        },
1030        autoMakerReceivesPremium: auto_maker_receives_premium,
1031        autoPremiumLimitMicros: auto_premium_limit_micros,
1032        quotePolicy: match terms.quote_policy {
1033            RfqV2QuotePolicy::FirmOnly => 0,
1034            RfqV2QuotePolicy::IndicativeAllowed => 1,
1035        },
1036        takerIdentity: match terms.taker_identity {
1037            RfqV2TakerIdentity::Anonymous => 0,
1038            RfqV2TakerIdentity::Disclosed => 1,
1039        },
1040        routingMode: routing_mode,
1041        selectedMakers: selected_makers,
1042        quoteDeadlineMs: terms.quote_deadline_ms,
1043        expiresAtMs: terms.expires_at_ms,
1044        feeLimits: fee_limits(terms.fee_limits),
1045        builder: terms
1046            .builder
1047            .map_or(Address::ZERO, |builder| builder.recipient.inner()),
1048        privateTermsBlinding: terms.private_terms_blinding.0,
1049    })
1050}
1051
1052fn fill_policy_fields(policy: RfqV2FillPolicy) -> (u8, u128, u128) {
1053    match policy {
1054        RfqV2FillPolicy::FullSizeOnce => (0, 0, 0),
1055        RfqV2FillPolicy::OneSmallerPackage { minimum, step } => (1, minimum, step),
1056        RfqV2FillPolicy::RepeatedPartial { minimum, step } => (2, minimum, step),
1057    }
1058}
1059
1060fn fee_limits(limits: RfqV2FeeLimits) -> RfqV2SigningFeeLimits {
1061    RfqV2SigningFeeLimits {
1062        perExecutionMicros: limits.per_execution,
1063        cumulativeMicros: limits.cumulative,
1064    }
1065}
1066
1067fn priced_legs(legs: &[RfqV2PricedLeg]) -> Vec<RfqV2SigningPriceLeg> {
1068    legs.iter()
1069        .map(|leg| RfqV2SigningPriceLeg {
1070            instrumentId: rfq_v2_instrument_id(&leg.instrument),
1071            priceMicros: leg.price_micros,
1072        })
1073        .collect()
1074}
1075
1076fn uuid_bytes(id: Uuid) -> FixedBytes<16> {
1077    FixedBytes::from(*id.as_bytes())
1078}
1079
1080fn invalid(message: impl Into<String>) -> ClientError {
1081    ClientError::InvalidInput(message.into())
1082}
1083
1084#[cfg(test)]
1085#[path = "rfq_v2_signing_test.rs"]
1086mod tests;