use std::{
collections::{HashSet, VecDeque},
fmt,
future::Future,
pin::Pin,
sync::Arc,
time::Duration,
};
use alloy_primitives::hex;
use alloy_signer::Signer;
use chrono::{DateTime, TimeDelta, Utc};
use reqwest::Url;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::{
HostError, HttpExchange, HttpRequest,
delivery::{
Backoff, Deliveries, DeliveryCore, DeliveryError, DeliveryOutcome, DeliveryRecord,
DeliveryVenue, FillSource, Refused, VenueDeliverer,
},
model::Fill,
protocol::{
self, deliveries,
lighter::{self, COLLATERAL_ROUTE, USDC_ASSET},
poseidon,
signing::SigningKey,
},
transport::Clock,
types::{Amount, FillId, VenueId},
};
const TRANSFER: u64 = 12;
const FAILED: u64 = 0;
const EXECUTED: u64 = 2;
const FINAL: u64 = 3;
const UNKNOWN_TRANSACTION: i64 = 21_500;
const SEND_MARGIN: TimeDelta = TimeDelta::seconds(60);
const REQUESTS_PER_MINUTE: usize = 50;
const READ_TIMEOUT: Duration = Duration::from_secs(10);
const SEND_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LighterConfig {
pub api: String,
pub chain_id: u64,
pub account_index: u64,
pub api_key_index: u8,
pub max_fee: u64,
}
impl LighterConfig {
pub fn new(account_index: u64, api_key_index: u8) -> Self {
Self {
api: "https://mainnet.zklighter.elliot.ai".to_owned(),
chain_id: protocol::LIGHTER_CHAIN_ID,
account_index,
api_key_index,
max_fee: 0,
}
}
#[must_use]
pub fn api(mut self, api: impl Into<String>) -> Self {
self.api = api.into();
self
}
#[must_use]
pub fn max_fee(mut self, max_fee: u64) -> Self {
self.max_fee = max_fee;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct LighterTransferParams {
pub to_account_index: u64,
pub asset_id: u16,
pub is_spot_account: bool,
pub from_is_spot_account: bool,
pub usdc_amount: u64,
pub fee: u64,
pub memo: String,
pub skip_nonce: u64,
pub nonce: u64,
pub api_key_index: u8,
pub account_index: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SignedLighterTransfer {
pub tx_type: u64,
pub tx_info: String,
pub tx_hash: String,
pub message_to_sign: Option<String>,
}
impl SignedLighterTransfer {
pub fn new(
tx_type: u64,
tx_info: String,
tx_hash: String,
message_to_sign: Option<String>,
) -> Self {
Self { tx_type, tx_info, tx_hash, message_to_sign }
}
}
pub type LighterSignerFuture<'a, T> =
Pin<Box<dyn Future<Output = Result<T, HostError>> + Send + 'a>>;
pub trait LighterSigner: Send + Sync {
fn auth_token(&self) -> LighterSignerFuture<'_, String>;
fn sign_transfer(
&self,
params: LighterTransferParams,
) -> LighterSignerFuture<'_, SignedLighterTransfer>;
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LighterDelivery {
pub fill_id: FillId,
pub tx_hash: String,
pub tx_type: u64,
pub tx_info: String,
pub nonce: u64,
pub expires_at: u64,
pub amount: Amount,
pub fee: u64,
pub to: u64,
pub attempted: bool,
pub sent: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outcome: Option<DeliveryOutcome>,
pub created_at: DateTime<Utc>,
}
impl DeliveryRecord for LighterDelivery {
fn fill_id(&self) -> FillId {
self.fill_id
}
fn outcome(&self) -> Option<DeliveryOutcome> {
self.outcome
}
}
pub struct LighterVenue {
config: LighterConfig,
signer: Arc<dyn LighterSigner>,
owner: SigningKey,
http: Arc<dyn HttpExchange>,
read_at: Backoff,
executed: HashSet<String>,
requests: VecDeque<DateTime<Utc>>,
}
impl fmt::Debug for LighterVenue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LighterVenue")
.field("config", &self.config)
.field("owner", &self.owner.address())
.finish_non_exhaustive()
}
}
pub type LighterDeliverer = VenueDeliverer<LighterVenue>;
impl LighterVenue {
pub fn new(
config: LighterConfig,
signer: impl LighterSigner + 'static,
owner: impl Signer + Send + Sync + 'static,
http: impl HttpExchange + 'static,
) -> Self {
Self {
config,
signer: Arc::new(signer),
owner: SigningKey::new(owner),
http: Arc::new(http),
read_at: Backoff::default(),
executed: HashSet::new(),
requests: VecDeque::new(),
}
}
fn spend(&mut self, now: DateTime<Utc>) -> Result<(), DeliveryError> {
while self.requests.front().is_some_and(|at| now - *at >= TimeDelta::minutes(1)) {
self.requests.pop_front();
}
if self.requests.len() >= REQUESTS_PER_MINUTE {
return Err(DeliveryError::Venue(
"Lighter request budget spent for this minute".into(),
));
}
self.requests.push_back(now);
Ok(())
}
fn url(&self, path: &str, query: &[(&str, String)]) -> Result<Url, DeliveryError> {
let mut url = Url::parse(&format!("{}/api/v1/{path}", self.config.api))
.map_err(|error| DeliveryError::Venue(format!("Lighter {path}: {error}")))?;
if !query.is_empty() {
url.query_pairs_mut().extend_pairs(query);
}
Ok(url)
}
async fn get(
&mut self,
now: DateTime<Utc>,
path: &str,
query: &[(&str, String)],
authorization: Option<&str>,
) -> Result<Map<String, Value>, DeliveryError> {
self.spend(now)?;
let url = self.url(path, query)?;
let mut headers = vec![("accept", "application/json".to_owned())];
if let Some(token) = authorization {
headers.push(("authorization", token.to_owned()));
}
let request = HttpRequest { method: "GET", url: url.into(), headers, body: None };
let answer = tokio::time::timeout(READ_TIMEOUT, self.http.send(request))
.await
.map_err(|_| DeliveryError::Venue(format!("Lighter {path}: timed out")))?
.map_err(|error| DeliveryError::Venue(format!("Lighter {path}: {error}")))?;
let status = answer.status();
let Ok(Value::Object(body)) = serde_json::from_slice::<Value>(&answer.into_body()) else {
return Err(DeliveryError::Venue(format!("Lighter {path}: HTTP {status}")));
};
if !(200..300).contains(&status) && code(&body) != Some(UNKNOWN_TRANSACTION) {
let message = body.get("message").and_then(Value::as_str).unwrap_or_default();
return Err(DeliveryError::Venue(format!("Lighter {path}: HTTP {status} {message}")));
}
Ok(body)
}
pub async fn status(
&mut self,
now: DateTime<Utc>,
tx_hash: &str,
) -> Result<Option<u64>, DeliveryError> {
let query = [("by", "hash".to_owned()), ("value", tx_hash.to_owned())];
let tx = self.get(now, "tx", &query, None).await?;
match (code(&tx), tx.get("status").and_then(Value::as_u64)) {
(Some(UNKNOWN_TRANSACTION), _) => Ok(None),
(Some(200), Some(status)) => Ok(Some(status)),
_ => Err(DeliveryError::Venue(format!("Lighter answered no status for {tx_hash}"))),
}
}
#[allow(clippy::too_many_lines, reason = "the TypeScript sign(), step by step")]
pub async fn sign(
&mut self,
fill: &Fill,
nonce: u64,
now: DateTime<Utc>,
) -> Result<LighterDelivery, DeliveryError> {
let not_lighter = || DeliveryError::Venue("Not a Lighter delivery".into());
let to: u64 = fill
.delivery_to
.as_deref()
.filter(|to| {
fill.to_venue == VenueId::Lighter
&& !to.is_empty()
&& to.bytes().all(|b| b.is_ascii_digit())
})
.and_then(|to| to.parse().ok())
.ok_or_else(not_lighter)?;
let amount = u64::try_from(fill.amount_out.get()).map_err(|_| not_lighter())?;
let token = self.signer.auth_token().await.map_err(|error| signer_failed(&error))?;
let query = [
("account_index", self.config.account_index.to_string()),
("to_account_index", to.to_string()),
("auth", token.clone()),
];
let fee = self.get(now, "transferFeeInfo", &query, Some(&token)).await?;
let usdc_fee = match fee.get("transfer_fee_usdc") {
Some(Value::Number(fee)) => fee.as_u64(),
Some(Value::String(fee)) => fee.parse().ok(),
_ => None,
}
.filter(|_| code(&fee) == Some(200))
.ok_or_else(|| DeliveryError::Venue("Unexpected Lighter transfer fee".into()))?;
if usdc_fee > self.config.max_fee {
return Err(DeliveryError::Venue(format!(
"Lighter charges this account {usdc_fee} per transfer, above max_fee"
)));
}
let memo = lighter::fill_memo(fill.id);
let params = LighterTransferParams {
to_account_index: to,
asset_id: USDC_ASSET.into(),
is_spot_account: false,
from_is_spot_account: false,
usdc_amount: amount,
fee: usdc_fee,
memo: format!("0x{}", hex::encode(memo)),
skip_nonce: 0,
nonce,
api_key_index: self.config.api_key_index,
account_index: self.config.account_index,
};
let signed =
self.signer.sign_transfer(params).await.map_err(|error| signer_failed(&error))?;
let differs = || DeliveryError::Venue("The signed transfer differs from the fill".into());
let Ok(Value::Object(mut info)) = serde_json::from_str::<Value>(&signed.tx_info) else {
return Err(differs());
};
let mut probe = info.clone();
probe.insert("L1Sig".to_owned(), Value::String(String::new()));
let read =
protocol::read_transfer_tx_info(&Value::Object(probe)).map_err(|_| differs())?.transfer;
let transfer = poseidon::message_terms(&read);
let message = lighter::transfer_message(&transfer, self.config.chain_id);
let hash = hex::encode(protocol::transfer_hash(&read, self.config.chain_id));
let reported = signed.tx_hash.strip_prefix("0x").unwrap_or(&signed.tx_hash);
let expected = signed.tx_type == TRANSFER
&& reported.eq_ignore_ascii_case(&hash)
&& read.from_route == COLLATERAL_ROUTE
&& read.to == to
&& read.from == self.config.account_index
&& read.api_key == self.config.api_key_index
&& read.amount == amount
&& read.fee == usdc_fee
&& read.asset == USDC_ASSET
&& read.to_route == COLLATERAL_ROUTE
&& read.nonce == nonce
&& read.memo == memo
&& signed.message_to_sign.as_deref() == Some(message.as_str());
if !expected {
return Err(differs());
}
let verified =
deliveries::lighter_transfer(&transfer, self.config.chain_id, self.owner.address());
let clock: Clock = Arc::new(move || now);
let signature = self.owner.sign(&verified, &clock).await?;
info.insert(
"L1Sig".to_owned(),
Value::String(format!("0x{}", hex::encode(signature.as_bytes()))),
);
Ok(LighterDelivery {
fill_id: fill.id,
tx_hash: signed.tx_hash,
tx_type: signed.tx_type,
tx_info: Value::Object(info).to_string(),
nonce,
expires_at: read.expired_at,
amount: fill.amount_out,
fee: usdc_fee,
to,
attempted: false,
sent: false,
outcome: None,
created_at: now,
})
}
async fn send(
&mut self,
now: DateTime<Utc>,
delivery: &LighterDelivery,
) -> Result<(), DeliveryError> {
let mut form = self.url("sendTx", &[])?;
form.query_pairs_mut().extend_pairs([
("tx_type", delivery.tx_type.to_string()),
("tx_info", delivery.tx_info.clone()),
("account_index", self.config.account_index.to_string()),
("api_key_index", self.config.api_key_index.to_string()),
("price_protection", "false".to_owned()),
]);
let body = form.query().unwrap_or_default().as_bytes().to_vec();
self.spend(now)?;
let headers = vec![
("content-type", "application/x-www-form-urlencoded".to_owned()),
("accept", "application/json".to_owned()),
];
let url = self.url("sendTx", &[])?.into();
let request = HttpRequest { method: "POST", url, headers, body: Some(body) };
let answer = tokio::time::timeout(SEND_TIMEOUT, self.http.send(request))
.await
.map_err(|_| DeliveryError::Venue("Lighter sendTx: timed out".into()))?
.map_err(|error| DeliveryError::Venue(format!("Lighter sendTx: {error}")))?;
let status = answer.status();
let body = match serde_json::from_slice::<Value>(&answer.into_body()) {
Ok(Value::Object(body)) => body,
_ => Map::new(),
};
if code(&body) != Some(200) {
if self.status(now, &delivery.tx_hash).await?.is_some() {
return Ok(());
}
let reason = match body.get("message").and_then(Value::as_str) {
Some(message) => format!("Lighter refused the transfer: {message}"),
None => format!("Lighter refused the transfer: HTTP {status}"),
};
if (400..500).contains(&status) && status != 429 && code(&body).is_some() {
return Err(Refused(reason).into());
}
return Err(DeliveryError::Venue(reason));
}
match body.get("tx_hash").and_then(Value::as_str) {
Some(hash) if !hash.is_empty() && hash != delivery.tx_hash => {
Err(DeliveryError::Venue("Lighter answered another transaction hash".into()))
}
_ => Ok(()),
}
}
#[allow(clippy::too_many_lines, reason = "the TypeScript settle(), step by step")]
async fn settle_one<S: FillSource>(
&mut self,
core: &mut DeliveryCore,
source: &S,
mut delivery: LighterDelivery,
fill: Option<&Fill>,
deliveries: &mut Deliveries<LighterDelivery>,
) -> Result<bool, DeliveryError> {
let id = delivery.fill_id;
let key = id.to_string();
if fill.is_none() && (delivery.attempted || delivery.sent) {
if core.report_due(&key)
&& let Some(outcome) = core.report(source, id, &delivery.tx_hash).await
{
delivery.outcome = Some(outcome);
core.record(deliveries, delivery).await?;
}
return Ok(true);
}
let reported =
fill.and_then(|fill| fill.delivery_hash.as_deref()) == Some(delivery.tx_hash.as_str());
let Some(fill) = fill.filter(|_| core.awaits(fill) && !reported) else {
delivery.outcome =
Some(if reported { DeliveryOutcome::Reported } else { DeliveryOutcome::Failed });
core.record(deliveries, delivery).await?;
tracing::info!(fill = %id, "fill no longer awaits this delivery");
return Ok(true);
};
if !core.report_due(&key) {
return Ok(true);
}
let executed = self.executed.contains(&key);
if !executed && !core.turn(&mut self.read_at, &key) {
return Ok(false);
}
let now = core.now();
let mut status =
if executed { Some(EXECUTED) } else { self.status(now, &delivery.tx_hash).await? };
if status.is_some() && !delivery.sent {
delivery.sent = true;
core.record(deliveries, delivery.clone()).await?;
}
if status.is_none() && !delivery.sent {
if fill.deliver_by.is_some_and(|by| by - now > SEND_MARGIN) {
let first = !delivery.attempted;
delivery.attempted = true;
core.record(deliveries, delivery.clone()).await?;
match self.send(now, &delivery).await {
Ok(()) => {}
Err(DeliveryError::Refused(refused)) if first => {
delivery.outcome = Some(DeliveryOutcome::Refused);
core.record(deliveries, delivery).await?;
tracing::warn!(fill = %id, %refused, "transfer refused");
return Ok(true);
}
Err(error) => return Err(error),
}
delivery.sent = true;
core.record(deliveries, delivery.clone()).await?;
tracing::info!(fill = %id, tx = %delivery.tx_hash, "transfer sent");
status = self.status(core.now(), &delivery.tx_hash).await?;
} else if !delivery.attempted {
delivery.outcome = Some(DeliveryOutcome::Dropped);
core.record(deliveries, delivery).await?;
tracing::warn!(fill = %id, "too close to the delivery deadline, transfer not sent");
return Ok(true);
}
}
if status.is_some_and(|status| (EXECUTED..=FINAL).contains(&status)) {
self.executed.insert(key.clone());
self.read_at.clear(&key);
}
if status.is_some_and(|status| status == FAILED || status > FINAL) {
delivery.outcome = Some(DeliveryOutcome::Dropped);
core.record(deliveries, delivery).await?;
tracing::warn!(fill = %id, ?status, "transfer failed");
return Ok(true);
}
if status.is_none_or(|status| status < EXECUTED) {
let expiry = i64::try_from(delivery.expires_at).unwrap_or(i64::MAX);
if core.now().timestamp_millis() > expiry.saturating_add(60_000) {
delivery.outcome = Some(DeliveryOutcome::Dropped);
core.record(deliveries, delivery).await?;
tracing::warn!(fill = %id, ?status, "transfer expired without executing");
return Ok(true);
}
return Ok(false);
}
if let Some(outcome) = core.report(source, id, &delivery.tx_hash).await {
delivery.outcome = Some(outcome);
core.record(deliveries, delivery).await?;
}
Ok(true)
}
}
impl DeliveryVenue for LighterVenue {
type Record = LighterDelivery;
fn venue(&self) -> VenueId {
VenueId::Lighter
}
fn send_margin(&self) -> TimeDelta {
SEND_MARGIN
}
async fn settle<S: FillSource>(
&mut self,
core: &mut DeliveryCore,
source: &S,
id: &str,
fill: Option<&Fill>,
deliveries: &mut Deliveries<LighterDelivery>,
) -> Result<bool, DeliveryError> {
let Some(delivery) = deliveries.get(id).cloned() else { return Ok(true) };
self.settle_one(core, source, delivery, fill, deliveries).await
}
async fn deliver<S: FillSource>(
&mut self,
core: &mut DeliveryCore,
source: &S,
due: Vec<Fill>,
deliveries: &mut Deliveries<LighterDelivery>,
) -> Result<bool, DeliveryError> {
let Some(next) = due.first() else { return Ok(true) };
let now = core.now();
let query = [
("account_index", self.config.account_index.to_string()),
("api_key_index", self.config.api_key_index.to_string()),
];
let answer = self.get(now, "nextNonce", &query, None).await?;
let remote = answer
.get("nonce")
.and_then(Value::as_u64)
.ok_or_else(|| DeliveryError::Venue("Lighter answered no nonce".into()))?;
let known = deliveries
.values()
.filter(|delivery| {
(delivery.attempted || delivery.sent)
&& !matches!(
delivery.outcome,
Some(DeliveryOutcome::Dropped | DeliveryOutcome::Refused)
)
})
.map(|delivery| delivery.nonce + 1);
let nonce = known.fold(remote, u64::max);
let delivery = self.sign(next, nonce, now).await?;
core.record(deliveries, delivery.clone()).await?;
match self.settle_one(core, source, delivery, Some(next), deliveries).await {
Ok(settled) => Ok(settled),
Err(error) => {
tracing::warn!(fill = %next.id, %error, "delivery unsettled");
Ok(false)
}
}
}
}
fn code(body: &Map<String, Value>) -> Option<i64> {
body.get("code").and_then(Value::as_i64)
}
fn signer_failed(error: &HostError) -> DeliveryError {
DeliveryError::Venue(format!("Lighter signer: {error}"))
}
#[cfg(test)]
mod tests;