digdigdig3 0.1.29

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! # EvmProvider — alloy-backed EVM chain provider
//!
//! Implements [`ChainProvider`] and [`EvmChain`] for all EVM-compatible networks.
//!
//! ## Feature gate
//!
//! This entire module is gated behind the `onchain-evm` feature. Enable it in
//! your `Cargo.toml`:
//!
//! ```toml
//! digdigdig3 = { version = "...", features = ["onchain-evm"] }
//! ```
//!
//! ## Usage
//!
//! ```rust,ignore
//! use digdigdig3::core::chain::{EvmProvider, EvmChain};
//!
//! let provider = EvmProvider::arbitrum();
//! let height = provider.get_height().await?;
//! let balance = provider.erc20_balance(token_addr, owner_addr).await?;
//! ```

use alloy::network::Ethereum;
use alloy::primitives::{Address, Bytes, U256};
use alloy::providers::{DynProvider, Provider, ProviderBuilder};
use alloy::rpc::types::eth::{TransactionReceipt, TransactionRequest};

use async_trait::async_trait;

use super::provider::{ChainFamily, ChainProvider, TxStatus};
use crate::core::types::ExchangeError;

// ═══════════════════════════════════════════════════════════════════════════════
// ERC-20 SELECTOR
// ═══════════════════════════════════════════════════════════════════════════════

/// `balanceOf(address)` function selector — keccak256("balanceOf(address)")[0..4]
const BALANCE_OF_SELECTOR: [u8; 4] = [0x70, 0xa0, 0x82, 0x31];

// ═══════════════════════════════════════════════════════════════════════════════
// EVM CHAIN EXTENSION TRAIT
// ═══════════════════════════════════════════════════════════════════════════════

/// EVM-specific chain operations.
///
/// Extends [`ChainProvider`] with the full EVM JSON-RPC surface needed by
/// DeFi connectors: contract reads (`eth_call`), gas estimation, gas price
/// queries, receipt retrieval, and an ERC-20 balance convenience helper.
///
/// All EVM chains — Ethereum, Arbitrum, Optimism, Base, Polygon, BSC,
/// Avalanche — share the same implementation. The chain is selected by
/// the RPC URL and chain ID passed to [`EvmProvider::new`].
///
/// ## Object safety
///
/// This trait is **not** object-safe because it uses alloy SDK types in method
/// signatures. Store the concrete [`EvmProvider`] type in connector fields
/// rather than `Box<dyn EvmChain>`.
#[async_trait]
pub trait EvmChain: ChainProvider {
    /// Execute a read-only contract call (`eth_call`).
    ///
    /// `call` must have at minimum the `to` and `input` fields populated.
    /// `from` and `value` are optional.
    ///
    /// Returns the raw return bytes from the contract. The caller is
    /// responsible for decoding them according to the function's ABI.
    async fn eth_call(&self, call: TransactionRequest) -> Result<Bytes, ExchangeError>;

    /// Estimate gas for a transaction (`eth_estimateGas`).
    ///
    /// Returns the estimated gas units as `u64`. Add a safety buffer
    /// (e.g. multiply by 1.2) before setting `gas_limit` on the real tx.
    async fn estimate_gas(&self, call: TransactionRequest) -> Result<u64, ExchangeError>;

    /// Get the current base fee per gas in wei.
    ///
    /// Uses `eth_gasPrice` under the hood, which returns the effective gas price
    /// (base fee + priority fee on EIP-1559 chains) or the legacy gas price.
    async fn gas_price(&self) -> Result<U256, ExchangeError>;

    /// Get the suggested EIP-1559 max priority fee per gas (the "tip") in wei.
    ///
    /// Calls `eth_maxPriorityFeePerGas`. Add this to the base fee to get the
    /// `max_fee_per_gas` for EIP-1559 transactions.
    async fn max_priority_fee(&self) -> Result<U256, ExchangeError>;

    /// Get the transaction receipt once the transaction is confirmed.
    ///
    /// Returns `Ok(None)` if the transaction is pending or not found.
    /// Returns `Ok(Some(receipt))` once the transaction is mined.
    async fn get_receipt(&self, tx_hash: &str) -> Result<Option<TransactionReceipt>, ExchangeError>;

    /// Read the ERC-20 `balanceOf(address)` for `token` contract.
    ///
    /// Convenience wrapper over `eth_call` for the most common on-chain
    /// read in DeFi connectors. Returns the raw balance as `U256` in the
    /// token's smallest unit (divide by `10^decimals` for display).
    async fn erc20_balance(&self, token: Address, account: Address) -> Result<U256, ExchangeError>;

    /// Access the underlying alloy [`DynProvider`] for advanced operations.
    ///
    /// Prefer the typed methods above when possible. This escape hatch is
    /// provided for operations not yet covered by the trait surface.
    fn inner(&self) -> &DynProvider<Ethereum>;
}

// ═══════════════════════════════════════════════════════════════════════════════
// EVM PROVIDER STRUCT
// ═══════════════════════════════════════════════════════════════════════════════

/// Concrete EVM chain provider backed by alloy's type-erased HTTP provider.
///
/// One `EvmProvider` per RPC endpoint is sufficient. Multiple DeFi connectors
/// targeting the same chain can share a single `EvmProvider` instance via
/// `Arc<EvmProvider>`, reusing the same HTTP connection pool and avoiding
/// duplicate RPC calls.
///
/// ## Construction
///
/// Use the chain-specific convenience constructors for known networks:
///
/// ```rust,ignore
/// let arb  = EvmProvider::arbitrum();
/// let eth  = EvmProvider::ethereum("https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY");
/// ```
///
/// Or construct from a custom RPC URL:
///
/// ```rust,ignore
/// let provider = EvmProvider::connect_http("https://my-rpc.example.com", 42161, "arbitrum").await?;
/// ```
pub struct EvmProvider {
    /// Type-erased alloy HTTP provider
    provider: DynProvider<Ethereum>,
    /// EIP-155 numeric chain ID
    chain_id: u64,
    /// Human-readable chain name (e.g. "arbitrum", "ethereum")
    chain_name: String,
}

impl EvmProvider {
    // ─────────────────────────────────────────────────────────────────────────
    // Constructors
    // ─────────────────────────────────────────────────────────────────────────

    /// Wrap an existing alloy [`DynProvider`].
    ///
    /// Prefer [`connect_http`][Self::connect_http] unless you already have
    /// a provider instance.
    pub fn new(provider: DynProvider<Ethereum>, chain_id: u64, chain_name: &str) -> Self {
        Self {
            provider,
            chain_id,
            chain_name: chain_name.to_lowercase(),
        }
    }

    /// Connect via an HTTP RPC URL and return a ready `EvmProvider`.
    ///
    /// Parses `rpc_url`, builds an alloy `ProviderBuilder` HTTP transport,
    /// and wraps it in a type-erased `DynProvider`.
    pub async fn connect_http(
        rpc_url: &str,
        chain_id: u64,
        chain_name: &str,
    ) -> Result<Self, ExchangeError> {
        let url: reqwest::Url = rpc_url.parse().map_err(|e| {
            ExchangeError::InvalidRequest(format!("Invalid RPC URL '{}': {}", rpc_url, e))
        })?;
        let provider = ProviderBuilder::new().connect_http(url);
        Ok(Self::new(DynProvider::new(provider), chain_id, chain_name))
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Known-chain convenience constructors (sync — no async needed for HTTP)
    // ─────────────────────────────────────────────────────────────────────────

    /// Ethereum mainnet using the public PublicNode RPC.
    pub fn ethereum(rpc_url: &str) -> Result<Self, ExchangeError> {
        let url: reqwest::Url = rpc_url.parse().map_err(|e| {
            ExchangeError::InvalidRequest(format!("Invalid Ethereum RPC URL '{}': {}", rpc_url, e))
        })?;
        let provider = ProviderBuilder::new().connect_http(url);
        Ok(Self::new(DynProvider::new(provider), 1, "ethereum"))
    }

    /// Arbitrum One using the public Offchain Labs RPC.
    pub fn arbitrum() -> Self {
        let url: reqwest::Url = "https://arb1.arbitrum.io/rpc".parse().expect("static URL");
        let provider = ProviderBuilder::new().connect_http(url);
        Self::new(DynProvider::new(provider), 42161, "arbitrum")
    }

    /// Base mainnet using the public Coinbase RPC.
    pub fn base() -> Self {
        let url: reqwest::Url = "https://mainnet.base.org".parse().expect("static URL");
        let provider = ProviderBuilder::new().connect_http(url);
        Self::new(DynProvider::new(provider), 8453, "base")
    }

    /// Polygon PoS mainnet using the public Polygon RPC.
    pub fn polygon() -> Self {
        let url: reqwest::Url = "https://polygon-rpc.com".parse().expect("static URL");
        let provider = ProviderBuilder::new().connect_http(url);
        Self::new(DynProvider::new(provider), 137, "polygon")
    }

    /// Avalanche C-Chain using the public Ava Labs RPC.
    pub fn avalanche() -> Self {
        let url: reqwest::Url = "https://api.avax.network/ext/bc/C/rpc"
            .parse()
            .expect("static URL");
        let provider = ProviderBuilder::new().connect_http(url);
        Self::new(DynProvider::new(provider), 43114, "avalanche")
    }

    /// BNB Smart Chain mainnet using the public BSC RPC.
    pub fn bsc() -> Self {
        let url: reqwest::Url = "https://bsc-dataseed.binance.org".parse().expect("static URL");
        let provider = ProviderBuilder::new().connect_http(url);
        Self::new(DynProvider::new(provider), 56, "bsc")
    }

    /// Optimism mainnet using the public OP Labs RPC.
    pub fn optimism() -> Self {
        let url: reqwest::Url = "https://mainnet.optimism.io".parse().expect("static URL");
        let provider = ProviderBuilder::new().connect_http(url);
        Self::new(DynProvider::new(provider), 10, "optimism")
    }

    /// Human-readable chain name (e.g. `"ethereum"`, `"arbitrum"`).
    pub fn chain_name(&self) -> &str {
        &self.chain_name
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ChainProvider IMPL
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl ChainProvider for EvmProvider {
    fn chain_family(&self) -> ChainFamily {
        ChainFamily::Evm { chain_id: self.chain_id }
    }

    async fn broadcast_tx(&self, tx_bytes: &[u8]) -> Result<String, ExchangeError> {
        let pending = self
            .provider
            .send_raw_transaction(tx_bytes)
            .await
            .map_err(|e| ExchangeError::Network(format!("send_raw_transaction failed: {}", e)))?;

        Ok(format!("{:#x}", pending.tx_hash()))
    }

    async fn get_height(&self) -> Result<u64, ExchangeError> {
        self.provider
            .get_block_number()
            .await
            .map_err(|e| ExchangeError::Network(format!("eth_blockNumber failed: {}", e)))
    }

    async fn get_nonce(&self, address: &str) -> Result<u64, ExchangeError> {
        let addr: Address = address.parse().map_err(|e| {
            ExchangeError::InvalidRequest(format!("Invalid address '{}': {}", address, e))
        })?;
        let count = self
            .provider
            .get_transaction_count(addr)
            .await
            .map_err(|e| ExchangeError::Network(format!("eth_getTransactionCount failed: {}", e)))?;
        Ok(count)
    }

    async fn get_native_balance(&self, address: &str) -> Result<String, ExchangeError> {
        let addr: Address = address.parse().map_err(|e| {
            ExchangeError::InvalidRequest(format!("Invalid address '{}': {}", address, e))
        })?;
        let balance = self
            .provider
            .get_balance(addr)
            .await
            .map_err(|e| ExchangeError::Network(format!("eth_getBalance failed: {}", e)))?;
        Ok(balance.to_string())
    }

    async fn get_tx_status(&self, tx_hash: &str) -> Result<TxStatus, ExchangeError> {
        let hash: alloy::primitives::TxHash = tx_hash.parse().map_err(|e| {
            ExchangeError::InvalidRequest(format!("Invalid tx hash '{}': {}", tx_hash, e))
        })?;

        let receipt = self
            .provider
            .get_transaction_receipt(hash)
            .await
            .map_err(|e| ExchangeError::Network(format!("eth_getTransactionReceipt failed: {}", e)))?;

        match receipt {
            None => Ok(TxStatus::Pending),
            Some(r) => {
                let block = r.block_number.unwrap_or(0);
                if r.status() {
                    Ok(TxStatus::Confirmed { block })
                } else {
                    Ok(TxStatus::Failed {
                        reason: "transaction reverted".to_string(),
                    })
                }
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EvmChain IMPL
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl EvmChain for EvmProvider {
    async fn eth_call(&self, call: TransactionRequest) -> Result<Bytes, ExchangeError> {
        self.provider
            .call(call)
            .await
            .map_err(|e| ExchangeError::Network(format!("eth_call failed: {}", e)))
    }

    async fn estimate_gas(&self, call: TransactionRequest) -> Result<u64, ExchangeError> {
        self.provider
            .estimate_gas(call)
            .await
            .map_err(|e| ExchangeError::Network(format!("eth_estimateGas failed: {}", e)))
    }

    async fn gas_price(&self) -> Result<U256, ExchangeError> {
        let price_u128 = self
            .provider
            .get_gas_price()
            .await
            .map_err(|e| ExchangeError::Network(format!("eth_gasPrice failed: {}", e)))?;
        Ok(U256::from(price_u128))
    }

    async fn max_priority_fee(&self) -> Result<U256, ExchangeError> {
        let fee_u128 = self
            .provider
            .get_max_priority_fee_per_gas()
            .await
            .map_err(|e| {
                ExchangeError::Network(format!("eth_maxPriorityFeePerGas failed: {}", e))
            })?;
        Ok(U256::from(fee_u128))
    }

    async fn get_receipt(
        &self,
        tx_hash: &str,
    ) -> Result<Option<TransactionReceipt>, ExchangeError> {
        let hash: alloy::primitives::TxHash = tx_hash.parse().map_err(|e| {
            ExchangeError::InvalidRequest(format!("Invalid tx hash '{}': {}", tx_hash, e))
        })?;
        self.provider
            .get_transaction_receipt(hash)
            .await
            .map_err(|e| {
                ExchangeError::Network(format!("eth_getTransactionReceipt failed: {}", e))
            })
    }

    async fn erc20_balance(
        &self,
        token: Address,
        account: Address,
    ) -> Result<U256, ExchangeError> {
        // ABI-encode: balanceOf(address) = selector (4 bytes) + padded address (32 bytes)
        let mut calldata = Vec::with_capacity(4 + 32);
        calldata.extend_from_slice(&BALANCE_OF_SELECTOR);
        // Left-zero-pad the 20-byte address to 32 bytes
        calldata.extend_from_slice(&[0u8; 12]);
        calldata.extend_from_slice(account.as_slice());

        let tx = TransactionRequest::default()
            .to(token)
            .input(Bytes::from(calldata).into());

        let result = self
            .provider
            .call(tx)
            .await
            .map_err(|e| ExchangeError::Network(format!("eth_call (balanceOf) failed: {}", e)))?;

        if result.len() < 32 {
            return Err(ExchangeError::Parse(format!(
                "balanceOf returned {} bytes, expected at least 32",
                result.len()
            )));
        }

        Ok(U256::from_be_slice(&result[..32]))
    }

    fn inner(&self) -> &DynProvider<Ethereum> {
        &self.provider
    }
}