use alloy_dyn_abi::TypedData;
use alloy_primitives::{Address, B256, Bytes, U256, address, hex};
use alloy_sol_types::{SolCall, SolStruct};
use serde::{Deserialize, Deserializer, de};
use serde_json::Value;
use super::{
checks::details::{self, at, differs, stale, unsupported},
eip712::{self, address_text},
hyperliquid::SendAsset,
signing::Verified,
};
use crate::{
deployments,
error::VerificationError,
model::{MoveEndpoint, MoveVenue},
};
pub(crate) const DEPOSITORY: Address = address!("4cd00e387622c35bddb9b4c962c136462338bc31");
pub(crate) const HYPERLIQUID_DEPOSITORY: Address =
address!("66cf0aace1b4e562593bec10ec7868fba9932224");
pub(crate) const ROUTER: Address = address!("0729e2a4716d9f7dd17858d5d504426d228697f7");
pub(crate) const SOLVER: Address = address!("f70da97812cb96acdf810712aa562db8dfa3dbef");
pub(crate) const SOLVER_CHAIN_ID: &str = "base";
pub(crate) const GMX_ROUTER: Address = address!("3f6772b95423fc03264adf90efb8a9922b6c8c6e");
pub(crate) const GMX_VAULT: Address = address!("ceaadfaf6a8c489b250e407987877c5fdfcdbe6e");
pub(crate) const RELAY_CREDIT: Address = address!("2a9775e3e4b88b1b4f96a71bb53d2c74c25e9cae");
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Vm {
Evm,
Hyperliquid,
Lighter,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RelayEndpoint {
pub chain: &'static str,
pub chain_id: u64,
pub currency: &'static str,
pub decimals: u8,
pub units: u8,
pub vm: Vm,
}
impl RelayEndpoint {
pub(crate) fn token(&self) -> Option<Address> {
if self.vm == Vm::Evm { address_text(self.currency) } else { None }
}
}
const fn evm(
chain: &'static str,
chain_id: u64,
currency: &'static str,
decimals: u8,
) -> RelayEndpoint {
RelayEndpoint { chain, chain_id, currency, decimals, units: decimals, vm: Vm::Evm }
}
pub const WALLETS: [RelayEndpoint; 5] = [
evm("hyperevm", 999, "0xb88339cb7199b77e23db6e890353e22632ba630f", 6),
evm("polygon", 137, "0xc011a7e12a19f7b1f670d46f03b03f3342e82dfb", 6),
evm("polygon", 137, "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359", 6),
evm("arbitrum", 42161, "0xaf88d065e77c8cc2239327c5edb3a432268e5831", 6),
evm("bnb", 56, "0x55d398326f99059ff775485246999027b3197955", 18),
];
const HYPERCORE: RelayEndpoint = RelayEndpoint {
chain: "hyperliquid",
chain_id: 1337,
currency: "0x00000000000000000000000000000000",
decimals: 8,
units: 6,
vm: Vm::Hyperliquid,
};
const LIGHTER: RelayEndpoint = RelayEndpoint {
chain: "lighter",
chain_id: 3_586_256,
currency: "0",
decimals: 6,
units: 6,
vm: Vm::Lighter,
};
pub(crate) fn account(venue: &MoveVenue) -> Option<&'static RelayEndpoint> {
match venue {
MoveVenue::Hyperliquid => Some(&HYPERCORE),
MoveVenue::Lighter => Some(&LIGHTER),
MoveVenue::Polymarket => Some(&WALLETS[1]),
MoveVenue::Gmx => Some(&WALLETS[3]),
MoveVenue::Aster => Some(&WALLETS[4]),
_ => None,
}
}
pub(crate) fn account_minimum(venue: &MoveVenue) -> U256 {
ACCOUNT_MINIMUMS
.iter()
.find(|(minimum_venue, _)| minimum_venue == venue)
.map_or(U256::ZERO, |(_, minimum)| *minimum)
}
pub const ACCOUNT_MINIMUMS: [(MoveVenue, U256); 1] =
[(MoveVenue::Polymarket, U256::from_limbs([5_000_000, 0, 0, 0]))];
pub(crate) fn is_origin(venue: &MoveVenue) -> bool {
*venue == MoveVenue::Hyperliquid
}
pub(crate) fn is_call_venue(venue: &MoveVenue) -> bool {
matches!(venue, MoveVenue::Polymarket | MoveVenue::Gmx | MoveVenue::Aster)
}
pub fn relay_endpoint(
endpoint: &MoveEndpoint,
origin: bool,
) -> Result<&'static RelayEndpoint, VerificationError> {
if endpoint.venue == MoveVenue::Wallet {
return WALLETS
.iter()
.find(|wallet| {
Some(wallet.chain_id) == endpoint.chain_id && endpoint.token == wallet.token()
})
.ok_or(unsupported(details::BRIDGE_WALLET));
}
if origin && !is_origin(&endpoint.venue) {
return Err(unsupported(details::BRIDGE_ORIGIN));
}
account(&endpoint.venue).ok_or(unsupported(details::BRIDGE_VENUE))
}
fn scale(endpoint: &RelayEndpoint) -> U256 {
U256::from(10u8).pow(U256::from(endpoint.decimals - endpoint.units))
}
pub fn to_relay_units(amount: U256, endpoint: &RelayEndpoint) -> Option<U256> {
amount.checked_mul(scale(endpoint))
}
pub fn from_relay_units(amount: U256, endpoint: &RelayEndpoint) -> U256 {
amount / scale(endpoint)
}
mod typed {
alloy_sol_types::sol! {
struct Order {
string version;
string solverChainId;
address solver;
uint256 salt;
Input[] inputs;
Output output;
Fee[] fees;
}
struct Input {
InputPayment payment;
InputRefund[] refunds;
}
struct InputPayment {
string chainId;
bytes currency;
uint256 amount;
uint256 weight;
}
struct InputRefund {
string chainId;
bytes recipient;
bytes currency;
uint256 minimumAmount;
uint32 deadline;
bytes extraData;
}
struct Output {
string chainId;
OutputPayment[] payments;
uint32 deadline;
bytes[] calls;
bytes extraData;
}
struct OutputPayment {
bytes recipient;
bytes currency;
uint256 minimumAmount;
uint256 expectedAmount;
}
struct Fee {
string recipientChainId;
bytes recipient;
string currencyChainId;
bytes currency;
uint256 amount;
}
#[derive(serde::Serialize)]
struct NonceMapping {
string chainId;
address wallet;
address depositor;
bytes32 id;
uint256 nonce;
}
function approve(address spender, uint256 amount);
function depositErc20(address depositor, address currency, uint256 amount, bytes32 id);
function bridgeIn(address account, address token);
function cleanupErc20s(address[] tokens, address[] recipients, uint256[] amounts, bytes data);
function cleanupErc20sViaCall(address[] tokens, address[] tos, bytes[] datas, uint256[] amounts);
function credit(address recipient, uint256 least);
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Order {
version: String,
solver_chain_id: String,
solver: String,
#[serde(deserialize_with = "uint")]
salt: U256,
inputs: Vec<Input>,
output: Output,
fees: Vec<Fee>,
}
#[derive(Debug, Deserialize)]
struct Input {
payment: InputPayment,
refunds: Vec<Refund>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct InputPayment {
chain_id: String,
currency: String,
#[serde(deserialize_with = "uint")]
amount: U256,
#[serde(deserialize_with = "uint")]
weight: U256,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Refund {
chain_id: String,
recipient: String,
currency: String,
#[serde(deserialize_with = "uint")]
minimum_amount: U256,
#[serde(deserialize_with = "uint")]
deadline: U256,
extra_data: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Output {
chain_id: String,
payments: Vec<Payment>,
#[serde(deserialize_with = "uint")]
deadline: U256,
calls: Vec<String>,
extra_data: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Payment {
recipient: String,
currency: String,
#[serde(deserialize_with = "uint")]
minimum_amount: U256,
#[serde(deserialize_with = "uint")]
expected_amount: U256,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Fee {
recipient_chain_id: String,
recipient: String,
currency_chain_id: String,
currency: String,
#[serde(deserialize_with = "uint")]
amount: U256,
}
fn uint<'de, D: Deserializer<'de>>(deserializer: D) -> Result<U256, D::Error> {
let parsed = match Value::deserialize(deserializer)? {
Value::Number(number) => number.as_u64().map(U256::from),
Value::String(text) => match text.strip_prefix("0x") {
Some(digits) if (1..=64).contains(&digits.len()) => {
U256::from_str_radix(digits, 16).ok()
}
Some(_) => None,
None => decimal(&text),
},
_ => None,
};
parsed.ok_or_else(|| de::Error::custom("invalid integer"))
}
fn decimal(text: &str) -> Option<U256> {
let digits = (1..=78).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit());
if digits { U256::from_str_radix(text, 10).ok() } else { None }
}
fn bytes(text: &str) -> Option<Bytes> {
let digits = text.strip_prefix("0x")?;
if digits.len() % 2 != 0 { None } else { hex::decode(digits).ok().map(Bytes::from) }
}
fn bytes_on(chain: &str, text: &str) -> Option<Bytes> {
if chain == LIGHTER.chain {
let index = u128::try_from(decimal(text)?).ok()?;
Some(Bytes::copy_from_slice(&index.to_be_bytes()))
} else {
bytes(text)
}
}
impl Order {
fn read(value: &Value) -> Result<Self, VerificationError> {
Self::deserialize(value).map_err(|_| differs(details::BRIDGE_ORDER))
}
fn id(&self) -> Option<B256> {
let deadline = |value: U256| u32::try_from(value).ok();
let inputs = self
.inputs
.iter()
.map(|input| {
let payment = &input.payment;
let refunds = input
.refunds
.iter()
.map(|refund| {
Some(typed::InputRefund {
chainId: refund.chain_id.clone(),
recipient: bytes_on(&refund.chain_id, &refund.recipient)?,
currency: bytes_on(&refund.chain_id, &refund.currency)?,
minimumAmount: refund.minimum_amount,
deadline: deadline(refund.deadline)?,
extraData: bytes(&refund.extra_data)?,
})
})
.collect::<Option<_>>()?;
Some(typed::Input {
payment: typed::InputPayment {
chainId: payment.chain_id.clone(),
currency: bytes_on(&payment.chain_id, &payment.currency)?,
amount: payment.amount,
weight: payment.weight,
},
refunds,
})
})
.collect::<Option<_>>()?;
let output = &self.output;
let payments = output
.payments
.iter()
.map(|payment| {
Some(typed::OutputPayment {
recipient: bytes_on(&output.chain_id, &payment.recipient)?,
currency: bytes_on(&output.chain_id, &payment.currency)?,
minimumAmount: payment.minimum_amount,
expectedAmount: payment.expected_amount,
})
})
.collect::<Option<_>>()?;
let fees = self
.fees
.iter()
.map(|fee| {
Some(typed::Fee {
recipientChainId: fee.recipient_chain_id.clone(),
recipient: bytes(&fee.recipient)?,
currencyChainId: fee.currency_chain_id.clone(),
currency: bytes(&fee.currency)?,
amount: fee.amount,
})
})
.collect::<Option<_>>()?;
let order = typed::Order {
version: self.version.clone(),
solverChainId: self.solver_chain_id.clone(),
solver: address_text(&self.solver)?,
salt: self.salt,
inputs,
output: typed::Output {
chainId: output.chain_id.clone(),
payments,
deadline: deadline(output.deadline)?,
calls: output.calls.iter().map(|call| bytes(call)).collect::<Option<_>>()?,
extraData: bytes(&output.extra_data)?,
},
fees,
};
Some(order.eip712_hash_struct())
}
}
pub fn relay_order_id(order: &Value) -> Result<B256, VerificationError> {
Order::read(order)?.id().ok_or(differs(details::BRIDGE_ORDER))
}
fn canonical_extra(chain: &str) -> Bytes {
if chain == HYPERCORE.chain || chain == LIGHTER.chain {
Bytes::new()
} else {
Bytes::copy_from_slice(ROUTER.into_word().as_slice())
}
}
fn call(to: Address, data: &[u8]) -> Bytes {
let word = |n: usize| U256::from(n).to_be_bytes::<32>();
let mut out = Vec::with_capacity(160 + data.len().next_multiple_of(32));
out.extend_from_slice(to.into_word().as_slice());
for n in [0x60, 0, 0x20, data.len()] {
out.extend_from_slice(&word(n));
}
out.extend_from_slice(data);
out.resize(160 + data.len().next_multiple_of(32), 0);
out.into()
}
pub fn destination_calls(venue: &MoveVenue, recipient: Address, least: U256) -> Option<Vec<Bytes>> {
if least.is_zero() {
return None;
}
let token = account(venue)?.token()?;
let sweep_to = |to| {
typed::cleanupErc20sCall {
tokens: vec![token],
recipients: vec![to],
amounts: vec![U256::ZERO],
data: Bytes::new(),
}
.abi_encode()
};
let mut calls = match venue {
MoveVenue::Gmx => vec![
call(ROUTER, &sweep_to(GMX_VAULT)),
call(GMX_ROUTER, &typed::bridgeInCall { account: recipient, token }.abi_encode()),
],
MoveVenue::Polymarket | MoveVenue::Aster => {
let credit = typed::creditCall { recipient, least }.abi_encode();
let deposit = typed::cleanupErc20sViaCallCall {
tokens: vec![token],
tos: vec![RELAY_CREDIT],
datas: vec![credit.into()],
amounts: vec![U256::ZERO],
};
vec![call(ROUTER, &deposit.abi_encode())]
}
_ => return None,
};
calls.push(call(ROUTER, &sweep_to(recipient)));
Some(calls)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Recipient {
Address(Address),
Lighter(u64),
}
impl Recipient {
fn is(self, value: &str, endpoint: &RelayEndpoint) -> bool {
match (self, endpoint.vm) {
(Self::Lighter(index), Vm::Lighter) => {
value.bytes().all(|b| b.is_ascii_digit()) && value == index.to_string()
}
(Self::Address(address), Vm::Evm | Vm::Hyperliquid) => {
address_text(value) == Some(address)
}
_ => false,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Expectation<'a> {
pub(crate) from: &'a MoveEndpoint,
pub(crate) to: &'a MoveEndpoint,
pub(crate) payer: Address,
pub(crate) recipient: Recipient,
pub(crate) amount_in: U256,
pub(crate) min_out: U256,
pub(crate) credit: Option<U256>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Checked {
pub(crate) id: B256,
pub(crate) deadline: u32,
}
fn ensure(ok: bool, detail: &'static str) -> Result<(), VerificationError> {
if ok { Ok(()) } else { Err(differs(detail)) }
}
fn same_text(value: &str, pinned: &str) -> bool {
value.eq_ignore_ascii_case(pinned)
}
pub(crate) fn check_bridge_order(
order: &Value,
expect: &Expectation<'_>,
now: i64,
) -> Result<Checked, VerificationError> {
let origin = relay_endpoint(expect.from, true)?;
let destination = relay_endpoint(expect.to, false)?;
let order = Order::read(order)?;
ensure(order.version == "v1", details::ORDER_VERSION)?;
ensure(
order.solver_chain_id == SOLVER_CHAIN_ID && address_text(&order.solver) == Some(SOLVER),
details::ORDER_SOLVER,
)?;
ensure(order.fees.is_empty(), details::ORDER_FEES)?;
let [input] = order.inputs.as_slice() else { return Err(differs(details::ORDER_INPUTS)) };
let payment = &input.payment;
ensure(
payment.chain_id == origin.chain && same_text(&payment.currency, origin.currency),
details::ORDER_INPUT,
)?;
ensure(
Some(payment.amount) == to_relay_units(expect.amount_in, origin)
&& payment.weight == U256::from(1u8),
details::ORDER_AMOUNT,
)?;
let chains = [origin.chain, destination.chain, HYPERCORE.chain];
for (index, refund) in input.refunds.iter().enumerate() {
let to_payer = refund.chain_id != LIGHTER.chain
&& address_text(&refund.recipient) == Some(expect.payer);
let to_recipient = refund.chain_id == destination.chain
&& expect.recipient.is(&refund.recipient, destination);
let checks = ensure(
chains.contains(&refund.chain_id.as_str()) && (to_payer || to_recipient),
details::ORDER_REFUND,
)
.and_then(|()| {
ensure(
bytes(&refund.extra_data) == Some(canonical_extra(&refund.chain_id)),
details::ORDER_REFUND_EXTRA,
)
});
checks.map_err(|error| at(error, index))?;
}
let output = &order.output;
ensure(output.chain_id == destination.chain, details::ORDER_OUTPUT_CHAIN)?;
ensure(
bytes(&output.extra_data) == Some(canonical_extra(&output.chain_id)),
details::ORDER_OUTPUT_EXTRA,
)?;
let deadline = u32::try_from(output.deadline).map_err(|_| differs(details::ORDER_DEADLINE))?;
if i64::from(deadline) <= now {
return Err(stale(details::ORDER_DEADLINE));
}
let [paid] = output.payments.as_slice() else {
return Err(differs(details::ORDER_PAYMENTS));
};
ensure(same_text(&paid.currency, destination.currency), details::ORDER_CURRENCY)?;
let minimum = from_relay_units(paid.minimum_amount, destination);
ensure(minimum >= expect.min_out, details::ORDER_MINIMUM)?;
let calls: Option<Vec<Bytes>> = output.calls.iter().map(|call| bytes(call)).collect();
if is_call_venue(&expect.to.venue) {
let credit = expect.credit.ok_or(differs(details::ACCOUNT_CREDIT))?;
ensure(credit >= expect.min_out && minimum >= credit, details::ACCOUNT_CREDIT)?;
ensure(address_text(&paid.recipient) == Some(ROUTER), details::ORDER_RECIPIENT)?;
let Recipient::Address(recipient) = expect.recipient else {
return Err(differs(details::ORDER_RECIPIENT));
};
let expected = destination_calls(&expect.to.venue, recipient, credit);
ensure(calls.is_some() && calls == expected, details::ORDER_CALLS)?;
} else {
ensure(calls.is_some_and(|calls| calls.is_empty()), details::ORDER_CALLS)?;
ensure(expect.recipient.is(&paid.recipient, destination), details::ORDER_RECIPIENT)?;
}
let id = order.id().ok_or(differs(details::BRIDGE_ORDER))?;
Ok(Checked { id, deadline })
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Transactions {
pub chain_id: u64,
pub token: Address,
pub approve: Bytes,
pub deposit: Bytes,
}
pub fn bridge_transactions(
id: B256,
origin: &RelayEndpoint,
payer: Address,
amount: U256,
) -> Option<Transactions> {
let token = origin.token()?;
Some(Transactions {
chain_id: origin.chain_id,
token,
approve: typed::approveCall { spender: DEPOSITORY, amount }.abi_encode().into(),
deposit: typed::depositErc20Call { depositor: payer, currency: token, amount, id }
.abi_encode()
.into(),
})
}
pub fn part_floor(part: U256, min_out: U256, amount_in: U256) -> Option<U256> {
if amount_in.is_zero() {
return None;
}
Some(part.checked_mul(min_out)?.div_ceil(amount_in))
}
pub fn check_bridge_nonce(nonce: u64, now_ms: i64) -> Result<u64, VerificationError> {
let nonce_ms = i64::try_from(nonce).map_err(|_| differs(details::NONCE))?;
let fresh = nonce_ms > now_ms - 1_800_000 && nonce_ms < now_ms + 300_000;
if fresh { Ok(nonce) } else { Err(differs(details::NONCE)) }
}
pub fn bridge_authorization(id: B256, payer: Address, nonce: u64) -> TypedData {
let mapping = typed::NonceMapping {
chainId: HYPERCORE.chain.to_owned(),
wallet: payer,
depositor: payer,
id,
nonce: U256::from(nonce),
};
eip712::typed(&mapping, eip712::domain("RelayNonceMapping", "2", 1, Some(Address::ZERO)))
}
pub(crate) fn bridge_send_asset(
amount: U256,
nonce: u64,
source_dex: Option<&str>,
) -> Result<SendAsset, VerificationError> {
let Some(source_dex @ ("" | "spot")) = source_dex else {
return Err(differs(details::SOURCE_DEX));
};
let million = U256::from(1_000_000u32);
let fraction = u32::try_from(amount % million).unwrap_or_default();
Ok(SendAsset {
hyperliquid_chain: "Mainnet".to_owned(),
destination: format!("{HYPERLIQUID_DEPOSITORY:#x}"),
source_dex: source_dex.to_owned(),
destination_dex: String::new(),
token: deployments::HYPERLIQUID_USDC.to_owned(),
amount: format!("{}.{fraction:06}", amount / million),
from_sub_account: String::new(),
nonce,
})
}
pub(crate) fn hypercore_payloads(
checked: Checked,
expect: &Expectation<'_>,
nonce: u64,
source_dex: Option<&str>,
) -> Result<[Verified; 2], VerificationError> {
if relay_endpoint(expect.from, true)?.vm != Vm::Hyperliquid {
return Err(unsupported(details::BRIDGE_ORIGIN));
}
if expect.amount_in.is_zero() || nonce == 0 {
return Err(differs(details::NONCE));
}
let send = bridge_send_asset(expect.amount_in, nonce, source_dex)?;
let not_after = Some(i64::from(checked.deadline) - 30);
let verified = |typed: TypedData| {
let digest = typed.eip712_signing_hash().map_err(|_| differs(details::DIGEST))?;
Verified::typed(typed, digest, expect.payer, not_after)
};
Ok([
verified(bridge_authorization(checked.id, expect.payer, nonce))?,
verified(send.typed_data())?,
])
}
#[cfg(test)]
mod tests;