rust-x402 0.3.0

HTTP-native micropayments with x402 protocol
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Real blockchain integration for x402 payments
//!
//! This module provides real blockchain interactions for:
//! - Transaction monitoring
//! - Balance checking
//! - Network status verification
//! - Gas estimation

use crate::{Result, X402Error};
use serde::{Deserialize, Serialize};

/// Blockchain client for real network interactions
pub struct BlockchainClient {
    /// RPC endpoint URL
    rpc_url: String,
    /// Network name
    pub network: String,
    /// HTTP client for RPC calls
    client: reqwest::Client,
}

/// Blockchain transaction status
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TransactionStatus {
    Pending,
    Confirmed,
    Failed,
    Unknown,
}

/// Blockchain transaction information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionInfo {
    pub hash: String,
    pub status: TransactionStatus,
    pub block_number: Option<u64>,
    pub gas_used: Option<u64>,
    pub effective_gas_price: Option<String>,
    pub from: String,
    pub to: String,
    pub value: String,
}

/// Balance information for an address
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BalanceInfo {
    pub address: String,
    pub balance: String,
    pub token_balance: Option<String>,
    pub token_address: Option<String>,
}

/// Network information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkInfo {
    pub chain_id: u64,
    pub network_name: String,
    pub latest_block: u64,
    pub gas_price: String,
}

impl BlockchainClient {
    /// Create a new blockchain client
    pub fn new(rpc_url: String, network: String) -> Self {
        Self {
            rpc_url,
            network,
            client: reqwest::Client::new(),
        }
    }

    /// Get transaction status by hash
    pub async fn get_transaction_status(&self, tx_hash: &str) -> Result<TransactionInfo> {
        let response = self
            .client
            .post(&self.rpc_url)
            .json(&serde_json::json!({
                "jsonrpc": "2.0",
                "method": "eth_getTransactionByHash",
                "params": [tx_hash],
                "id": 1
            }))
            .send()
            .await
            .map_err(|e| X402Error::network_error(format!("RPC request failed: {}", e)))?;

        let response_json: serde_json::Value = response.json().await.map_err(|e| {
            X402Error::network_error(format!("Failed to parse RPC response: {}", e))
        })?;

        if let Some(result) = response_json.get("result") {
            if result.is_null() {
                return Ok(TransactionInfo {
                    hash: tx_hash.to_string(),
                    status: TransactionStatus::Unknown,
                    block_number: None,
                    gas_used: None,
                    effective_gas_price: None,
                    from: "".to_string(),
                    to: "".to_string(),
                    value: "".to_string(),
                });
            }

            let block_number = result
                .get("blockNumber")
                .and_then(|v| v.as_str())
                .and_then(|s| u64::from_str_radix(s.trim_start_matches("0x"), 16).ok());

            // Get transaction receipt for gas information
            let gas_info = self.get_transaction_receipt(tx_hash).await.ok();

            Ok(TransactionInfo {
                hash: tx_hash.to_string(),
                status: if block_number.is_some() {
                    TransactionStatus::Confirmed
                } else {
                    TransactionStatus::Pending
                },
                block_number,
                gas_used: gas_info
                    .as_ref()
                    .and_then(|r| r.get("gasUsed"))
                    .and_then(|v| {
                        v.as_str()
                            .and_then(|s| u64::from_str_radix(s.trim_start_matches("0x"), 16).ok())
                    }),
                effective_gas_price: gas_info
                    .as_ref()
                    .and_then(|r| r.get("effectiveGasPrice"))
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
                from: result
                    .get("from")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string(),
                to: result
                    .get("to")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string(),
                value: result
                    .get("value")
                    .and_then(|v| v.as_str())
                    .unwrap_or("0x0")
                    .to_string(),
            })
        } else {
            Err(X402Error::network_error(
                "Invalid RPC response format".to_string(),
            ))
        }
    }

    /// Get transaction receipt
    async fn get_transaction_receipt(&self, tx_hash: &str) -> Result<serde_json::Value> {
        let response = self
            .client
            .post(&self.rpc_url)
            .json(&serde_json::json!({
                "jsonrpc": "2.0",
                "method": "eth_getTransactionReceipt",
                "params": [tx_hash],
                "id": 1
            }))
            .send()
            .await
            .map_err(|e| X402Error::network_error(format!("RPC request failed: {}", e)))?;

        let response_json: serde_json::Value = response.json().await.map_err(|e| {
            X402Error::network_error(format!("Failed to parse RPC response: {}", e))
        })?;

        response_json
            .get("result")
            .ok_or_else(|| X402Error::network_error("No result in RPC response".to_string()))
            .cloned()
    }

    /// Get balance for an address
    pub async fn get_balance(&self, address: &str) -> Result<BalanceInfo> {
        let response = self
            .client
            .post(&self.rpc_url)
            .json(&serde_json::json!({
                "jsonrpc": "2.0",
                "method": "eth_getBalance",
                "params": [address, "latest"],
                "id": 1
            }))
            .send()
            .await
            .map_err(|e| X402Error::network_error(format!("RPC request failed: {}", e)))?;

        let response_json: serde_json::Value = response.json().await.map_err(|e| {
            X402Error::network_error(format!("Failed to parse RPC response: {}", e))
        })?;

        let balance = response_json
            .get("result")
            .and_then(|v| v.as_str())
            .unwrap_or("0x0")
            .to_string();

        Ok(BalanceInfo {
            address: address.to_string(),
            balance,
            token_balance: None,
            token_address: None,
        })
    }

    /// Get USDC balance for an address
    pub async fn get_usdc_balance(&self, address: &str) -> Result<BalanceInfo> {
        let usdc_contract = self.get_usdc_contract_address()?;

        // Call balanceOf function on USDC contract
        let response = self
            .client
            .post(&self.rpc_url)
            .json(&serde_json::json!({
                "jsonrpc": "2.0",
                "method": "eth_call",
                "params": [{
                    "to": usdc_contract,
                    "data": format!("0x70a08231000000000000000000000000{}", address.trim_start_matches("0x"))
                }, "latest"],
                "id": 1
            }))
            .send()
            .await
            .map_err(|e| X402Error::network_error(format!("RPC request failed: {}", e)))?;

        let response_json: serde_json::Value = response.json().await.map_err(|e| {
            X402Error::network_error(format!("Failed to parse RPC response: {}", e))
        })?;

        let token_balance = response_json
            .get("result")
            .and_then(|v| v.as_str())
            .unwrap_or("0x0")
            .to_string();

        Ok(BalanceInfo {
            address: address.to_string(),
            balance: "0x0".to_string(), // We're only getting token balance
            token_balance: Some(token_balance),
            token_address: Some(usdc_contract),
        })
    }

    /// Get network information
    pub async fn get_network_info(&self) -> Result<NetworkInfo> {
        // Get chain ID
        let chain_id_response = self
            .client
            .post(&self.rpc_url)
            .json(&serde_json::json!({
                "jsonrpc": "2.0",
                "method": "eth_chainId",
                "params": [],
                "id": 1
            }))
            .send()
            .await
            .map_err(|e| X402Error::network_error(format!("RPC request failed: {}", e)))?;

        let chain_id_json: serde_json::Value = chain_id_response.json().await.map_err(|e| {
            X402Error::network_error(format!("Failed to parse RPC response: {}", e))
        })?;

        let chain_id = chain_id_json
            .get("result")
            .and_then(|v| v.as_str())
            .and_then(|s| u64::from_str_radix(s.trim_start_matches("0x"), 16).ok())
            .unwrap_or(0);

        // Get latest block number
        let block_response = self
            .client
            .post(&self.rpc_url)
            .json(&serde_json::json!({
                "jsonrpc": "2.0",
                "method": "eth_blockNumber",
                "params": [],
                "id": 1
            }))
            .send()
            .await
            .map_err(|e| X402Error::network_error(format!("RPC request failed: {}", e)))?;

        let block_json: serde_json::Value = block_response.json().await.map_err(|e| {
            X402Error::network_error(format!("Failed to parse RPC response: {}", e))
        })?;

        let latest_block = block_json
            .get("result")
            .and_then(|v| v.as_str())
            .and_then(|s| u64::from_str_radix(s.trim_start_matches("0x"), 16).ok())
            .unwrap_or(0);

        // Get gas price
        let gas_response = self
            .client
            .post(&self.rpc_url)
            .json(&serde_json::json!({
                "jsonrpc": "2.0",
                "method": "eth_gasPrice",
                "params": [],
                "id": 1
            }))
            .send()
            .await
            .map_err(|e| X402Error::network_error(format!("RPC request failed: {}", e)))?;

        let gas_json: serde_json::Value = gas_response.json().await.map_err(|e| {
            X402Error::network_error(format!("Failed to parse RPC response: {}", e))
        })?;

        let gas_price = gas_json
            .get("result")
            .and_then(|v| v.as_str())
            .unwrap_or("0x0")
            .to_string();

        Ok(NetworkInfo {
            chain_id,
            network_name: self.network.clone(),
            latest_block,
            gas_price,
        })
    }

    /// Estimate gas for a transaction
    pub async fn estimate_gas(&self, transaction: &TransactionRequest) -> Result<u64> {
        let response = self
            .client
            .post(&self.rpc_url)
            .json(&serde_json::json!({
                "jsonrpc": "2.0",
                "method": "eth_estimateGas",
                "params": [transaction],
                "id": 1
            }))
            .send()
            .await
            .map_err(|e| X402Error::network_error(format!("RPC request failed: {}", e)))?;

        let response_json: serde_json::Value = response.json().await.map_err(|e| {
            X402Error::network_error(format!("Failed to parse RPC response: {}", e))
        })?;

        let gas_hex = response_json
            .get("result")
            .and_then(|v| v.as_str())
            .ok_or_else(|| X402Error::network_error("No gas estimate in response".to_string()))?;

        u64::from_str_radix(gas_hex.trim_start_matches("0x"), 16)
            .map_err(|_| X402Error::network_error("Invalid gas estimate format".to_string()))
    }

    /// Get USDC contract address for current network
    pub fn get_usdc_contract_address(&self) -> Result<String> {
        match self.network.as_str() {
            "base-sepolia" => Ok("0x036CbD53842c5426634e7929541eC2318f3dCF7e".to_string()),
            "base" => Ok("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913".to_string()),
            "avalanche-fuji" => Ok("0x5425890298aed601595a70AB815c96711a31Bc65".to_string()),
            "avalanche" => Ok("0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E".to_string()),
            _ => Err(X402Error::invalid_network(format!(
                "Unsupported network: {}",
                self.network
            ))),
        }
    }
}

/// Transaction request for gas estimation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionRequest {
    pub from: String,
    pub to: String,
    pub value: Option<String>,
    pub data: Option<String>,
    pub gas: Option<String>,
    pub gas_price: Option<String>,
}

/// Blockchain client factory
pub struct BlockchainClientFactory;

impl BlockchainClientFactory {
    /// Create client for Base Sepolia testnet
    pub fn base_sepolia() -> BlockchainClient {
        BlockchainClient::new(
            "https://sepolia.base.org".to_string(),
            "base-sepolia".to_string(),
        )
    }

    /// Create client for Base mainnet
    pub fn base() -> BlockchainClient {
        BlockchainClient::new("https://mainnet.base.org".to_string(), "base".to_string())
    }

    /// Create client for Avalanche Fuji testnet
    pub fn avalanche_fuji() -> BlockchainClient {
        BlockchainClient::new(
            "https://api.avax-test.network/ext/bc/C/rpc".to_string(),
            "avalanche-fuji".to_string(),
        )
    }

    /// Create client for Avalanche mainnet
    pub fn avalanche() -> BlockchainClient {
        BlockchainClient::new(
            "https://api.avax.network/ext/bc/C/rpc".to_string(),
            "avalanche".to_string(),
        )
    }

    /// Create client with custom RPC URL
    pub fn custom(rpc_url: &str, network: &str) -> BlockchainClient {
        BlockchainClient::new(rpc_url.to_string(), network.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_blockchain_client_creation() {
        let client =
            BlockchainClient::new("https://example.com".to_string(), "testnet".to_string());
        assert_eq!(client.network, "testnet");
    }

    #[test]
    fn test_usdc_contract_address() {
        let client = BlockchainClient::new(
            "https://example.com".to_string(),
            "base-sepolia".to_string(),
        );
        let address = client.get_usdc_contract_address().unwrap();
        assert_eq!(address, "0x036CbD53842c5426634e7929541eC2318f3dCF7e");
    }

    #[test]
    fn test_transaction_request_serialization() {
        let tx = TransactionRequest {
            from: "0x123".to_string(),
            to: "0x456".to_string(),
            value: Some("0x1000".to_string()),
            data: None,
            gas: None,
            gas_price: None,
        };

        let json = serde_json::to_string(&tx).unwrap();
        assert!(json.contains("0x123"));
    }
}