lamarge 0.7.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! A maker's early refund: the taker's payment locked for a fill the maker abandoned inside its
//! venue, given back before `t2` once the escrow confirms the lock.

use alloy_primitives::{Address, B256, U256};
use alloy_sol_types::SolCall;
use serde::Serialize;
use tracing::Instrument as _;

use crate::{
    BlockTag, ChainCall, ChainReader, Error, Result, Session, deployments,
    error::TransportError,
    model::Fill,
    protocol::checks::{
        consents::{
            EscrowLock, PaymentRefundPreparation, check_refund_locks, refund_escrow,
            verified_payment_refund,
        },
        details::{self, changed, unsupported},
    },
    transport::{Call, ops},
    types::{SignatureBytes, VenueId},
};

mod escrow {
    alloy_sol_types::sol! {
        /// A maker's refund consent, as the escrow hashes it.
        struct RefundConsent {
            address payer;
            bytes32 swapId;
            uint256 deadline;
        }

        function locks(address owner, bytes32 offerId, bytes32 swapId)
            external
            view
            returns (uint256 amount, bytes32 hashlock, address recipient, uint64 refundAt, uint8 state, uint32 dex);

        function refundPaymentDigest(RefundConsent consent) external view returns (bytes32);
    }
}

#[derive(Serialize)]
struct RefundBody {
    deadline: u64,
    signature: SignatureBytes,
}

impl Session {
    /// As the maker of `fill`, abandoned inside its venue, gives the taker's locked payment back
    /// before `t2`: the consent LaMarge prepares is checked (the payment's beneficiary signs it
    /// in a pinned escrow's domain, good until `t2` at most), the escrow it names is read
    /// through `reader` before and after signing (the lock still refunds `amount_in` at `t2`,
    /// and the escrow answers the consent's digest), then the signature is submitted.
    ///
    /// # Errors
    ///
    /// - `Verification(..)` when the fill cannot be refunded early, the consent differs or the
    ///   lock no longer permits the refund: nothing is signed, or nothing submitted.
    /// - [`Error::Transport`] when `reader` cannot read the paying chain: nothing is signed.
    pub async fn refund_payment(&self, fill: &Fill, reader: &dyn ChainReader) -> Result<()> {
        let span = tracing::info_span!("lamarge.refund_payment", fill = %fill.id);
        async {
            let call = Call::new(&ops::PREPARE_PAYMENT_REFUND).segment(fill.id);
            let prepared: PaymentRefundPreparation =
                self.transport().send(call, self.auth()).await?;
            let verified = verified_payment_refund(fill, &prepared, self.transport().now())?;
            let item = prepared.to_sign.first().ok_or(changed(details::TO_SIGN))?;
            let escrow = refund_escrow(&item.typed_data, &fill.from_venue)?;
            check_escrow_locks(fill, prepared.deadline, reader, escrow).await?;
            let signature = self.sign(&verified).await?;
            check_escrow_locks(fill, prepared.deadline, reader, escrow).await?;
            let body = RefundBody { deadline: prepared.deadline, signature };
            let call = Call::new(&ops::SUBMIT_PAYMENT_REFUND).segment(fill.id).json(&body)?;
            self.transport().send::<()>(call, self.auth()).await?;
            tracing::info!("refund submitted");
            Ok(())
        }
        .instrument(span)
        .await
    }
}

/// Reads the payment lock of `fill` from `escrow`, a pinned escrow of its paying chain, at the
/// block LaMarge acts on, and requires the escrow to answer the refund consent's digest for
/// `deadline`; then checks the lock still refunds `fill.amount_in` to its payer at `t2`
/// ([`check_refund_locks`](crate::protocol::check_refund_locks)).
pub async fn check_escrow_locks(
    fill: &Fill,
    deadline: u64,
    reader: &dyn ChainReader,
    escrow: Address,
) -> Result<()> {
    let chain = deployments::chain(&fill.from_venue).ok_or(unsupported(details::VENUE))?;
    if deployments::is_venue_settled(&fill.from_venue)
        || deployments::escrow_environment(chain.id, escrow).is_none()
    {
        return Err(details::deployment(details::ESCROW).into());
    }
    // Arbitrum's escrow acts at its head, the others at finality.
    let block =
        if fill.from_venue == VenueId::Gmx { BlockTag::Latest } else { BlockTag::Finalized };
    let locks = escrow::locksCall { owner: fill.payer, offerId: B256::ZERO, swapId: fill.swap_id };
    let answer =
        read(reader, ChainCall { chain_id: chain.id, to: escrow, data: locks.abi_encode(), block })
            .await?;
    let lock = escrow::locksCall::abi_decode_returns(&answer)
        .map_err(|_| changed(details::PAYMENT_LOCK))?;
    let consent = escrow::RefundConsent {
        payer: fill.payer,
        swapId: fill.swap_id,
        deadline: U256::from(deadline),
    };
    let data = escrow::refundPaymentDigestCall { consent }.abi_encode();
    let digest =
        read(reader, ChainCall { chain_id: chain.id, to: escrow, data, block: BlockTag::Latest })
            .await?;
    if digest.len() != 32 {
        return Err(changed(details::REFUND_DIGEST).into());
    }
    let lock = EscrowLock::new(
        lock.amount,
        lock.hashlock,
        lock.recipient,
        lock.refundAt,
        lock.state,
        lock.dex,
    );
    Ok(check_refund_locks(fill, &lock)?)
}

async fn read(reader: &dyn ChainReader, call: ChainCall) -> Result<Vec<u8>> {
    reader.call(call).await.map_err(|error| Error::Transport(TransportError::caller(error)))
}

#[cfg(test)]
mod tests;