diff --git a/Cargo.lock b/Cargo.lock index 1bdfa9ce..bd7e123e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "diorama-anvil" -version = "0.2.8" +version = "0.2.9" dependencies = [ "alloy-eips", "alloy-json-rpc", @@ -1533,7 +1533,7 @@ dependencies = [ [[package]] name = "diorama-ast-scope" -version = "0.2.8" +version = "0.2.9" dependencies = [ "proc-macro2", "quote", @@ -1542,7 +1542,7 @@ dependencies = [ [[package]] name = "diorama-cctp" -version = "0.2.8" +version = "0.2.9" dependencies = [ "alloy-chains", "alloy-consensus", @@ -1568,7 +1568,7 @@ dependencies = [ [[package]] name = "diorama-cctp-bridge" -version = "0.2.8" +version = "0.2.9" dependencies = [ "diorama-cctp", "diorama-config", @@ -1576,7 +1576,7 @@ dependencies = [ [[package]] name = "diorama-config" -version = "0.2.8" +version = "0.2.9" dependencies = [ "alloy-primitives", "clap", @@ -1591,7 +1591,7 @@ dependencies = [ [[package]] name = "diorama-devnet" -version = "0.2.8" +version = "0.2.9" dependencies = [ "alloy-consensus", "alloy-eips", @@ -1613,7 +1613,7 @@ dependencies = [ [[package]] name = "diorama-mainnet" -version = "0.2.8" +version = "0.2.9" dependencies = [ "alloy-eips", "alloy-json-rpc", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "diorama-mainnet-engine" -version = "0.2.8" +version = "0.2.9" dependencies = [ "diorama-config", "diorama-mainnet", @@ -1648,7 +1648,7 @@ dependencies = [ [[package]] name = "diorama-venue" -version = "0.2.8" +version = "0.2.9" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -1676,7 +1676,7 @@ dependencies = [ [[package]] name = "diorama-venue-engine" -version = "0.2.8" +version = "0.2.9" dependencies = [ "diorama-config", "diorama-venue", @@ -1684,7 +1684,7 @@ dependencies = [ [[package]] name = "diorama-venue-sim" -version = "0.2.8" +version = "0.2.9" dependencies = [ "diorama-config", "diorama-venue", diff --git a/Cargo.toml b/Cargo.toml index 6c3552cd..8e19c2a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ resolver = "2" # The image tag the staging pipeline derives: ghcr.io/herodotusdev/-stg:. # Bump per deploy-worthy change set; the pipeline also creates the matching # git tag (plain `0.2.0`, distinct from the legacy `v0.1.0`). -version = "0.2.8" +version = "0.2.9" edition = "2021" rust-version = "1.99" license = "MIT OR Apache-2.0" diff --git a/crates/venue/src/bridge/mod.rs b/crates/venue/src/bridge/mod.rs index 07c77d04..feaf3a32 100644 --- a/crates/venue/src/bridge/mod.rs +++ b/crates/venue/src/bridge/mod.rs @@ -6,7 +6,9 @@ //! //! - **EVM→Core**: an ERC20 transfer to a token's system address credits the //! sender's Core spot balance (from the `Transfer` log — the docs' exact -//! rule); +//! rule); a CoreDepositWallet `deposit` / `depositFor` (read from the call +//! trace) credits the wallet its `destinationDex` names instead (`u32::MAX` +//! spot, `0` the default perp dex, any other index that `perpDexs` dex); //! - **CoreWriter actions**: every call to `0x3333…3333` (top-level *and* //! contract-internal, via the callTracer — a contract's action is //! attributed to the contract) decodes to a typed action; the sim applies @@ -74,6 +76,43 @@ impl DexRoute { } } +/// Where an EVM→Core credit's log sits: its emitter, the same transaction's +/// earlier logs, and the transaction (block and index) for its call tree. +#[derive(Clone, Copy)] +struct CreditSite<'a> { + emitter: Address, + prior: &'a [(Address, &'a alloy_primitives::LogData)], + block: u64, + tx_index: usize, +} + +/// A block's call traces, one tree per transaction: unread (`None`), read +/// but unavailable (`Some(None)`), or read. +type BlockTraces = Option>>; + +/// The CoreDepositWallet call (`deposit` / `depositFor`) inside a call tree +/// that deposited `value` for `depositor`: its route on Core. Only a +/// successful call to the token's linked contract, made by the account whose +/// funds moved and carrying exactly the amount that moved, counts. +fn deposit_route_in( + frame: &CallFrame, + wallet: Address, + depositor: Address, + value: U256, +) -> Option { + if frame.to == Some(wallet) && frame.from == depositor && frame.error.is_none() { + if let Some((route, amount)) = system::deposit_call_of(frame.from, &frame.input) { + if amount == value { + return Some(route); + } + } + } + frame + .calls + .iter() + .find_map(|child| deposit_route_in(child, wallet, depositor, value)) +} + /// The bridge's own cursor and the persisted state it needs. The cursor lives /// in the sim's state file (one state root per service). pub struct Bridge { @@ -235,7 +274,10 @@ impl Bridge { /// from the receipts' logs. async fn apply_credits(&self, n: u64, tokens: &[TokenInfo]) -> Result<()> { let receipts = self.anvil_v.receipts(n).await?; - for receipt in &receipts { + // The block's call traces, read once and only when a deposit needs + // the CoreDepositWallet call it made (its `destinationDex`). + let mut traces: BlockTraces = None; + for (tx_index, receipt) in receipts.iter().enumerate() { // The logs decoded once, with their emitters, so a helper-hop // credit can look back at the same transaction's funding leg. let logs: Vec<(Address, &alloy_primitives::LogData)> = receipt @@ -253,7 +295,13 @@ impl Bridge { let Some(transfer) = system::transfer_of(log.data()) else { continue; }; - self.apply_credit(&transfer, log.address(), &logs[..index], tokens) + let site = CreditSite { + emitter: log.address(), + prior: &logs[..index], + block: n, + tx_index, + }; + self.apply_credit(&transfer, site, tokens, &mut traces) .await?; } } @@ -301,10 +349,11 @@ impl Bridge { async fn apply_credit( &self, transfer: &Transfer, - emitter: Address, - prior: &[(Address, &alloy_primitives::LogData)], + site: CreditSite<'_>, tokens: &[TokenInfo], + traces: &mut BlockTraces, ) -> Result<()> { + let CreditSite { emitter, prior, .. } = site; // The linked token's own log is the ordinary deposit. When a bridge // helper moves the tokens on, the helper's self-transfer is resolved // back to the depositor that funded it earlier in the same @@ -325,8 +374,11 @@ impl Bridge { } return Ok(()); }; - self.sim.credit_evm_deposit( - credit.sender, + let (account, wallet) = self + .deposit_destination(&credit, transfer.value, site, traces) + .await; + self.sim.credit_evm_deposit_to( + (account, &wallet), TokenRef { index: credit.token.index, coin: &credit.token.name, @@ -337,13 +389,84 @@ impl Bridge { self.metrics.inc_credits(); tracing::info!( from = %credit.sender, + to = %account, token = %credit.token.name, amount = %credit.amount, + wallet = ?wallet, "bridge: EVM→Core credit" ); Ok(()) } + /// The Core account and wallet a deposit lands in. A plain transfer to + /// the system address, and any deposit whose wallet call cannot be read, + /// credits the sender's spot wallet. A CoreDepositWallet `deposit` / + /// `depositFor` names its own: `destinationDex` `u32::MAX` is the spot + /// wallet, any other index the `perpDexs` position (`0` the default perp + /// dex), and `depositFor` credits its recipient. A dex the registry does + /// not list, or one that does not collateralise in the token, falls back + /// to spot (the funds stay visible rather than vanishing). + async fn deposit_destination( + &self, + credit: &system::EvmCredit<'_>, + value: U256, + site: CreditSite<'_>, + traces: &mut BlockTraces, + ) -> (Address, Wallet) { + let spot = (credit.sender, Wallet::Spot); + let Some(evm) = credit.token.evm else { + return spot; + }; + let Some(frame) = self.tx_frame(traces, site.block, site.tx_index).await else { + return spot; + }; + let Some(route) = deposit_route_in(frame, evm.address, credit.sender, value) else { + return spot; + }; + if route.dex == corewriter::SPOT_DEX { + return (route.recipient, Wallet::Spot); + } + match self.wallet_of(route.dex) { + Some(Wallet::Perp(dex)) + if self.feed.collateral_token_of(&dex) == credit.token.index => + { + (route.recipient, Wallet::Perp(dex)) + } + _ => { + tracing::warn!( + dex = route.dex, + token = %credit.token.name, + "bridge: deposit names a dex the registry does not list or that does not take the token; credited to spot" + ); + (route.recipient, Wallet::Spot) + } + } + } + + /// The call tree of one transaction of the block (the traces are read once + /// per block; a trace fault is counted and reads as "no tree"). + async fn tx_frame<'a>( + &self, + traces: &'a mut BlockTraces, + block: u64, + tx_index: usize, + ) -> Option<&'a CallFrame> { + if traces.is_none() { + *traces = Some(match self.anvil_v.trace_block_calls(block).await { + Ok(all) => Some(all), + Err(e) => { + self.metrics.inc_trace_faults(); + tracing::warn!(block, error = %e, "callTracer unavailable; deposits are credited to spot this block"); + None + } + }); + } + match traces.as_ref()?.as_ref()?.get(tx_index)?.success()? { + GethTrace::CallTracer(frame) => Some(frame), + _ => None, + } + } + /// The EVM→Core HYPE credit (the system contract's `Received` event). /// The emitter check is the address itself: only the real system contract /// can emit a credit, never a look-alike. @@ -995,6 +1118,68 @@ mod tests { input } + fn frame(from: Address, to: Address, input: Vec, calls: Vec) -> CallFrame { + CallFrame { + from, + to: Some(to), + input: input.into(), + calls, + ..Default::default() + } + } + + /// A CoreDepositWallet call inside the call tree names where the deposit + /// lands, but only when the depositor made it, it carries the amount that + /// moved and it did not revert. + #[test] + fn a_deposit_route_is_read_from_the_matching_wallet_call() { + use alloy_sol_types::SolCall; + let wallet = Address::repeat_byte(0x6b); + let agent = Address::repeat_byte(0xa1); + let value = U256::from(10_000_000u64); + let call = |dex| { + system::depositForCall { + recipient: agent, + amount: value, + destinationDex: dex, + } + .abi_encode() + }; + // The agent calls a helper, which is not the wallet; the wallet call + // is nested one level down. + let tree = |dex| { + frame( + Address::repeat_byte(0x01), + agent, + vec![], + vec![frame( + Address::repeat_byte(0x01), + agent, + vec![], + vec![frame(agent, wallet, call(dex), vec![])], + )], + ) + }; + let route = deposit_route_in(&tree(0), wallet, agent, value).expect("a route"); + assert_eq!((route.recipient, route.dex), (agent, 0)); + let route = deposit_route_in(&tree(u32::MAX), wallet, agent, value).expect("a route"); + assert_eq!(route.dex, u32::MAX); + + // A different amount, a different depositor or a different contract + // is not this deposit's call. + assert!(deposit_route_in(&tree(0), wallet, agent, value + U256::from(1u64)).is_none()); + assert!(deposit_route_in(&tree(0), wallet, Address::repeat_byte(0xcc), value).is_none()); + assert!(deposit_route_in(&tree(0), Address::repeat_byte(0x99), agent, value).is_none()); + // A reverted call made no deposit. + let mut reverted = tree(0); + reverted.calls[0].calls[0].error = Some("execution reverted".into()); + assert!(deposit_route_in(&reverted, wallet, agent, value).is_none()); + // A plain token transfer has no wallet call at all. + assert!( + deposit_route_in(&frame(agent, wallet, vec![], vec![]), wallet, agent, value).is_none() + ); + } + /// The CoreWriter order's units are the docs' own: 10^8 × human for both /// price and size, resolved against the live meta. #[test] diff --git a/crates/venue/src/bridge/system.rs b/crates/venue/src/bridge/system.rs index e96a11b8..9784f1aa 100644 --- a/crates/venue/src/bridge/system.rs +++ b/crates/venue/src/bridge/system.rs @@ -34,6 +34,39 @@ sol! { /// emits `Received(user, amount)` with `user = msg.sender`, so a tx value /// sent to `0x2222…2` is the EVM→Core HYPE transfer. event Received(address indexed user, uint256 amount); + /// The CoreDepositWallet's entry points (the linked USDC's bridge on + /// HyperEVM): the deposit names the Core wallet it lands in, + /// `destinationDex` (`u32::MAX` the spot wallet, otherwise the + /// `perpDexs` position: `0` the default perp dex). + function deposit(uint256 amount, uint32 destinationDex); + function depositFor(address recipient, uint256 amount, uint32 destinationDex); +} + +/// Where a CoreDepositWallet deposit lands on Core: the account and the dex +/// index (`u32::MAX` = spot) the call named. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct DepositRoute { + pub(crate) recipient: Address, + pub(crate) dex: u32, +} + +/// The deposit a call to the CoreDepositWallet makes: `deposit(amount, dex)` +/// credits the caller, `depositFor(recipient, amount, dex)` the recipient. +/// `None` for any other calldata (a plain token transfer has no route: spot). +pub(crate) fn deposit_call_of(caller: Address, input: &[u8]) -> Option<(DepositRoute, U256)> { + if let Ok(call) = depositCall::abi_decode(input) { + let route = DepositRoute { + recipient: caller, + dex: call.destinationDex, + }; + return Some((route, call.amount)); + } + let call = depositForCall::abi_decode(input).ok()?; + let route = DepositRoute { + recipient: call.recipient, + dex: call.destinationDex, + }; + Some((route, call.amount)) } /// The native HYPE system address (transfers as tx value; `Received` event). @@ -585,6 +618,51 @@ mod tests { assert!(hop_credit_of(&third, &[(linked, &funding)], &tokens, helper).is_none()); } + /// The CoreDepositWallet's own entry points name the Core wallet: `deposit` + /// credits the caller, `depositFor` the recipient; dex `0` is the default + /// perp dex and `u32::MAX` the spot wallet. Anything else has no route. + #[test] + fn deposit_calls_decode_to_their_route() { + let caller = Address::repeat_byte(0xaa); + let recipient = Address::repeat_byte(0xbb); + let amount = U256::from(25_000_000u64); + + let input = depositCall { + amount, + destinationDex: 0, + } + .abi_encode(); + let (route, decoded) = deposit_call_of(caller, &input).expect("deposit decodes"); + assert_eq!( + route, + DepositRoute { + recipient: caller, + dex: 0 + } + ); + assert_eq!(decoded, amount); + + let input = depositForCall { + recipient, + amount, + destinationDex: u32::MAX, + } + .abi_encode(); + let (route, decoded) = deposit_call_of(caller, &input).expect("depositFor decodes"); + assert_eq!( + route, + DepositRoute { + recipient, + dex: u32::MAX + } + ); + assert_eq!(decoded, amount); + + // An ERC-20 transfer (or garbage) is no deposit call. + assert!(deposit_call_of(caller, &transfer_calldata(recipient, amount)).is_none()); + assert!(deposit_call_of(caller, &[]).is_none()); + } + #[test] fn look_alike_and_malformed_events_never_decode() { let from = Address::repeat_byte(0xdd); diff --git a/crates/venue/src/sim/transfer.rs b/crates/venue/src/sim/transfer.rs index ae9b2711..af66e304 100644 --- a/crates/venue/src/sim/transfer.rs +++ b/crates/venue/src/sim/transfer.rs @@ -482,16 +482,29 @@ impl Sim { Ok(applied) } - /// EVM to Core: credit a deposit to `address` and write the system - /// address's ledger row. A deposit that creates the account is credited in - /// full; its activation is owed on its first outbound transfer (Circle's - /// rule), and the address exists from now on. + /// EVM to Core: credit a deposit to `address`'s spot wallet and write the + /// system address's ledger row. A deposit that creates the account is + /// credited in full; its activation is owed on its first outbound + /// transfer (Circle's rule), and the address exists from now on. pub(crate) fn credit_evm_deposit( &self, address: Address, token: TokenRef<'_>, amount: Decimal, feed: &MarketFeed, + ) -> Result<()> { + self.credit_evm_deposit_to((address, &Wallet::Spot), token, amount, feed) + } + + /// [`Self::credit_evm_deposit`] into `wallet`: the spot wallet for a plain + /// transfer to the system address, a perp dex's clearinghouse when the + /// CoreDepositWallet call named one (`destinationDex`). + pub(crate) fn credit_evm_deposit_to( + &self, + (address, wallet): (Address, &Wallet), + token: TokenRef<'_>, + amount: Decimal, + feed: &MarketFeed, ) -> Result<()> { let clock = self.clock(crate::now_ms())?; self.with_state(|state| { @@ -500,7 +513,14 @@ impl Sim { } let account = state.accounts.entry(address).or_default(); stamp_funding_baseline(account, clock); - account::credit_entry(account, token, amount, "spot credit")?; + match wallet { + Wallet::Spot => { + account::credit_entry(account, token, amount, "spot credit")?; + } + Wallet::Perp(dex) => { + account.credit_perp(dex, amount, "perp credit")?; + } + } state.activated.insert(address); let system = if token.coin == fees::GAS_TOKEN { crate::bridge::system::HYPE_SYSTEM @@ -508,10 +528,15 @@ impl Sim { crate::bridge::system::system_address(u64::from(token.index)) }; let row = TransferRow { - kind: RowKind::SpotTransfer, + // A spot credit is the spot transfer from the system address; + // a perp credit is a send into that dex's wallet. + kind: match wallet { + Wallet::Spot => RowKind::SpotTransfer, + Wallet::Perp(_) => RowKind::Send, + }, user: system, destination: address, - dexes: (SPOT_DEX_NAME, SPOT_DEX_NAME), + dexes: (SPOT_DEX_NAME, wallet.dex_name()), token: token.coin, amount, usdc_value: amount * fees::token_usd(feed, token.index).unwrap_or(Decimal::ZERO), diff --git a/crates/venue/src/sim/transfer_matrix_tests.rs b/crates/venue/src/sim/transfer_matrix_tests.rs index 967a503f..8b038d08 100644 --- a/crates/venue/src/sim/transfer_matrix_tests.rs +++ b/crates/venue/src/sim/transfer_matrix_tests.rs @@ -947,6 +947,39 @@ fn a_deposited_account_pays_its_activation_on_its_first_outbound_transfer() { .unwrap()); } +/// A CoreDepositWallet deposit names the wallet it lands in: the default perp +/// dex (`destinationDex` 0) credits the perp balance and no spot, a builder +/// dex its own, and the ledger row records the send from the system address. +#[test] +fn a_deposit_can_land_in_a_perp_dex_instead_of_spot() { + let feed = feed(); + let sim = Sim::memory(); + sim.credit_evm_deposit_to((ME, &Wallet::Perp(String::new())), USDC, dec("10"), &feed) + .unwrap(); + assert_eq!(perp_of(&sim, ME, ""), dec("10")); + assert_eq!(spot_of(&sim, ME, USDC), Decimal::ZERO); + let row = &deltas(&sim, ME)[0]; + assert_eq!(row["type"], "send"); + assert_eq!(row["user"], "0x2000000000000000000000000000000000000000"); + assert_eq!(row["destination"], format!("{ME:#x}")); + assert_eq!(row["sourceDex"], "spot"); + assert_eq!(row["destinationDex"], ""); + // The account exists from now on and owes its activation, as for a spot deposit. + assert!(owes(&sim, ME)); + + sim.credit_evm_deposit_to((ME, &Wallet::Perp("xyz".into())), USDC, dec("4"), &feed) + .unwrap(); + assert_eq!(perp_of(&sim, ME, "xyz"), dec("4")); + assert_eq!(perp_of(&sim, ME, ""), dec("10")); + assert_eq!(deltas(&sim, ME)[1]["destinationDex"], "xyz"); + + // The spot wallet stays the default of the plain deposit. + sim.credit_evm_deposit_to((ME, &Wallet::Spot), USDC, dec("1"), &feed) + .unwrap(); + assert_eq!(spot_of(&sim, ME, USDC), dec("1")); + assert_eq!(deltas(&sim, ME)[2]["type"], "spotTransfer"); +} + /// The debt follows the account, not the destination: a deposited account's /// first send to a brand new address pays the 1 USDC once, the new address /// owes its own, and the second send from the first account is free.