use alloy_primitives::Address;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::Instrument as _;
use super::{linked, records};
use crate::{
Error, Result, Session,
error::ErrorCode,
model::{Dex, Withdrawal, WithdrawalState},
protocol::{
checks::{
details::{self, changed, unsupported},
withdrawal::{check_margin_withdrawal, check_send, signed_at},
},
signing::Verified,
},
transport::{Call, ops},
types::{Amount, ClientId, EscrowEnvironment, MoveId, SignatureBytes, VenueId},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum WithdrawTo {
Signer,
VenueWallet(Address),
Account(Address),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WithdrawalRequest {
id: ClientId,
venue: VenueId,
amount: Amount,
to: WithdrawTo,
#[serde(default, skip_serializing_if = "Option::is_none")]
move_id: Option<MoveId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
dex: Option<Dex>,
}
impl WithdrawalRequest {
pub fn new(id: ClientId, venue: VenueId, amount: Amount, to: WithdrawTo) -> Self {
Self { id, venue, amount, to, move_id: None, dex: None }
}
#[must_use]
pub fn move_id(mut self, id: MoveId) -> Self {
self.move_id = Some(id);
self
}
#[must_use]
pub fn dex(mut self, dex: Dex) -> Self {
self.dex = Some(dex);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Context {
environment: EscrowEnvironment,
venue: VenueId,
amount: Amount,
to: WithdrawTo,
signer: Address,
#[serde(default, skip_serializing_if = "Option::is_none")]
move_id: Option<MoveId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
dex: Option<Dex>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct WithdrawalRecord {
context: Context,
typed_data: Value,
signature: SignatureBytes,
#[serde(default, skip_serializing_if = "Option::is_none")]
result: Option<Withdrawal>,
#[serde(default, skip_serializing_if = "Option::is_none")]
refused: Option<ErrorCode>,
}
#[derive(Serialize)]
struct PrepareBody<'a> {
venue: &'a VenueId,
amount: Amount,
to: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
recipient: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
dex: Option<&'a Dex>,
}
#[derive(Deserialize)]
struct Prepared {
typed_data: Value,
}
#[derive(Serialize)]
struct SubmitBody<'a> {
venue: &'a VenueId,
typed_data: &'a Value,
signature: SignatureBytes,
#[serde(skip_serializing_if = "Option::is_none")]
move_id: Option<MoveId>,
}
impl Session {
pub async fn withdraw(&self, request: &WithdrawalRequest) -> Result<Withdrawal> {
let span =
tracing::info_span!("lamarge.withdraw", id = %request.id, venue = %request.venue);
run(self, request).instrument(span).await
}
}
fn target(to: WithdrawTo) -> (&'static str, Option<Address>) {
match to {
WithdrawTo::Signer => ("signer", None),
WithdrawTo::VenueWallet(_) => ("wallet", None),
WithdrawTo::Account(recipient) => ("account", Some(recipient)),
}
}
fn validate(session: &Session, request: &WithdrawalRequest) -> Result<()> {
match (&request.venue, request.to) {
(VenueId::Hyperliquid | VenueId::Polymarket, WithdrawTo::Signer)
| (VenueId::Polymarket, WithdrawTo::VenueWallet(_))
| (VenueId::Hyperliquid | VenueId::Polymarket | VenueId::Aster, WithdrawTo::Account(_)) => {
}
(VenueId::Hyperliquid, WithdrawTo::VenueWallet(_)) => {
return Err(Error::InvalidRequest("Hyperliquid withdraws to the signer only".into()));
}
_ => return Err(unsupported(details::VENUE).into()),
}
if request.to == WithdrawTo::Account(session.address()) {
return Err(Error::InvalidRequest("a send goes to another account".into()));
}
if request.move_id.is_some() && request.to != WithdrawTo::Signer {
return Err(Error::InvalidRequest("a move's withdrawal goes to the signer".into()));
}
match (&request.dex, &request.venue) {
(None, _) | (Some(Dex::Xyz), VenueId::Hyperliquid) => {}
(Some(Dex::Xyz), _) => {
return Err(Error::InvalidRequest(
"only a Hyperliquid withdrawal or send pays from trade.xyz".into(),
));
}
(Some(Dex::Unknown(_)), _) => return Err(unsupported(details::SOURCE_DEX).into()),
}
if request.amount == Amount::ZERO {
return Err(Error::InvalidRequest("amount must be positive".into()));
}
Ok(())
}
async fn run(session: &Session, request: &WithdrawalRequest) -> Result<Withdrawal> {
validate(session, request)?;
let id = &request.id;
let signer = session.address();
let (to, recipient) = target(request.to);
let journal = session.journal();
let key = session.record_key(&format!("withdrawal:{id}"));
let _turn = journal.lock(&key).await;
let context = Context {
environment: session.escrow_environment(),
venue: request.venue.clone(),
amount: request.amount,
to: request.to,
signer,
move_id: request.move_id,
dex: request.dex.clone(),
};
let stored = records::load::<WithdrawalRecord>(journal, &key).await?;
if let Some(record) = &stored {
if record.context != context {
return Err(Error::InvalidRequest(
format!("withdrawal {id} names another withdrawal").into(),
));
}
if let Some(code) = &record.refused {
return Err(Error::WithdrawalRefused { id: id.clone(), code: code.clone() });
}
if let Some(result) = record.result.as_ref().filter(|result| is_final(&result.state)) {
return Ok(result.clone());
}
}
let destination = destination(session, request).await?;
let record = if let Some(record) = stored {
check(request, signer, destination, &record.typed_data, signed_at(&record.typed_data)?)?;
tracing::info!("submitting the saved signature");
record
} else {
let body = PrepareBody {
venue: &request.venue,
amount: request.amount,
to,
recipient,
dex: request.dex.as_ref(),
};
let call = Call::new(&ops::PREPARE_WITHDRAWAL).json(&body)?;
let prepared: Prepared = session.transport().send(call, session.auth()).await?;
let now = session.transport().now();
let verified = check(request, signer, destination, &prepared.typed_data, now)?;
let signature = session.sign(&verified).await?;
let record = WithdrawalRecord {
context,
typed_data: prepared.typed_data,
signature,
result: None,
refused: None,
};
records::save(journal, &key, &record, false).await?;
tracing::info!("withdrawal signed");
record
};
submit(session, request, &key, record).await
}
async fn destination(session: &Session, request: &WithdrawalRequest) -> Result<Address> {
let balances = session.account().balances().await?;
let row = linked(&balances, &request.venue, session.address())?;
Ok(match request.to {
WithdrawTo::Signer => session.address(),
WithdrawTo::VenueWallet(wallet) => {
let linked = row.venue_wallet.as_deref().and_then(|linked| linked.parse().ok());
if linked != Some(wallet) {
return Err(changed(details::LINKED_ACCOUNT).into());
}
wallet
}
WithdrawTo::Account(recipient) => recipient,
})
}
fn check(
request: &WithdrawalRequest,
signer: Address,
destination: Address,
typed: &Value,
at: DateTime<Utc>,
) -> Result<Verified> {
let (venue, amount, dex) = (&request.venue, request.amount, request.dex.as_ref());
let checked = match request.to {
WithdrawTo::Account(_) => check_send(typed, venue, signer, destination, amount, at, dex),
WithdrawTo::Signer | WithdrawTo::VenueWallet(_) => {
check_margin_withdrawal(typed, venue, signer, destination, amount, at, dex)
}
};
Ok(checked?)
}
async fn submit(
session: &Session,
request: &WithdrawalRequest,
key: &str,
mut record: WithdrawalRecord,
) -> Result<Withdrawal> {
let journal = session.journal();
let body = SubmitBody {
venue: &request.venue,
typed_data: &record.typed_data,
signature: record.signature,
move_id: request.move_id,
};
let call = Call::new(&ops::SUBMIT_WITHDRAWAL).json(&body)?;
match session.transport().send::<Withdrawal>(call, session.auth()).await {
Ok(result) => {
record.result = Some(result.clone());
records::save(journal, key, &record, true).await?;
tracing::info!(state = %result.state, "withdrawal submitted");
Ok(result)
}
Err(error) if refusal(&error) => {
record.refused = error.code().cloned();
records::save(journal, key, &record, true).await?;
Err(error)
}
Err(error) => Err(error),
}
}
fn is_final(state: &WithdrawalState) -> bool {
matches!(state, WithdrawalState::Relayed | WithdrawalState::Refused)
}
fn refusal(error: &Error) -> bool {
matches!(error.code(), Some(ErrorCode::VenueRejected | ErrorCode::WithdrawalExpired))
}
#[cfg(test)]
mod tests;