bankai_sdk/lib.rs
1//! Bankai SDK
2//!
3//! **Trustless blockchain data access through zero-knowledge proofs**
4//!
5//! ## How It Works
6//!
7//! 1. **Verify the Bankai block proof**: validate the STWO proof to establish trust in the MMR roots
8//! 2. **Verify MMR proofs**: decommit and verify headers against those trusted MMR roots
9//! 3. **Verify chain data**: verify accounts/transactions/storage against the verified headers
10//!
11//! ## Getting Started (Fetch + Verify)
12//!
13//! This example follows the full flow: fetch a proof batch via the SDK, then verify it with
14//! `bankai-verify`, and finally use the verified results.
15//!
16//! ```no_run
17//! use alloy_primitives::{Address, FixedBytes, U256};
18//! use bankai_sdk::{Bankai, HashingFunctionDto, Network};
19//! use bankai_verify::verify_batch_proof;
20//!
21//! #[tokio::main]
22//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
23//! // Step 1: Initialize the SDK
24//! let bankai = Bankai::new(
25//! Network::Sepolia,
26//! Some("https://sepolia.infura.io/v3/YOUR_KEY".to_string()), // Execution RPC
27//! Some("https://sepolia.beacon-api.example.com".to_string()), // Beacon RPC
28//! );
29//!
30//! // Step 2: Build and fetch a batch with multiple proof requests
31//! let proof_batch = bankai
32//! .init_batch(Network::Sepolia, None, HashingFunctionDto::Keccak)
33//! .await?
34//! .evm_beacon_header(8_551_383)
35//! .evm_execution_header(9_231_247)
36//! .evm_account(9_231_247, Address::ZERO)
37//! .evm_storage_slot(9_231_247, Address::ZERO, U256::from(0))
38//! .evm_tx(FixedBytes::from([0u8; 32]))
39//! .execute()
40//! .await?;
41//!
42//! // Step 3: Verify everything (block proof + MMR proofs + Merkle proofs)
43//! let results = verify_batch_proof(proof_batch)?;
44//!
45//! // Step 4: Use the verified data (cryptographically guaranteed valid)
46//! for header in &results.evm.execution_header {
47//! println!("✓ Verified execution header at block {}", header.number);
48//! }
49//! for header in &results.evm.beacon_header {
50//! println!("✓ Verified beacon slot {}", header.slot);
51//! }
52//! for account in &results.evm.account {
53//! println!("✓ Verified account balance: {} wei", account.balance);
54//! }
55//! for slot in &results.evm.storage_slot {
56//! println!("✓ Verified storage slot: {}", slot);
57//! }
58//! for tx in &results.evm.tx {
59//! println!("✓ Verified transaction: {:?}", tx);
60//! }
61//!
62//! Ok(())
63//! }
64//! ```
65//!
66//! # API Client
67//!
68//! Direct access to the Bankai API for low-level operations:
69//!
70//! ```no_run
71//! use bankai_sdk::{Bankai, Network, HashingFunctionDto};
72//! use bankai_types::api::proofs::{MmrProofRequestDto, LightClientProofRequestDto, HeaderRequestDto};
73//!
74//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
75//! # let sdk = Bankai::new(Network::Sepolia, None, None);
76//!
77//! // Get latest Bankai block number
78//! let latest_block = sdk.api.get_latest_block_number().await?;
79//!
80//! // Fetch STWO block proof
81//! let block_proof = sdk.api.get_block_proof(latest_block).await?;
82//!
83//! // Fetch MMR proof for a specific header
84//! let mmr_request = MmrProofRequestDto {
85//! network_id: 1, // 0 = beacon, 1 = execution
86//! block_number: 12345, // Bankai block number
87//! hashing_function: HashingFunctionDto::Keccak,
88//! header_hash: "0x...".to_string(),
89//! };
90//! let mmr_proof = sdk.api.get_mmr_proof(&mmr_request).await?;
91//!
92//! // Fetch batch light client proof (STWO proof + multiple MMR proofs)
93//! let lc_request = LightClientProofRequestDto {
94//! bankai_block_number: Some(latest_block),
95//! hashing_function: HashingFunctionDto::Keccak,
96//! requested_headers: vec![
97//! HeaderRequestDto {
98//! network_id: 1, // Execution layer
99//! header_hash: "0x...".to_string(),
100//! },
101//! HeaderRequestDto {
102//! network_id: 0, // Beacon chain
103//! header_hash: "0x...".to_string(),
104//! },
105//! ],
106//! };
107//! let light_client_proof = sdk.api.get_light_client_proof(&lc_request).await?;
108//! # Ok(())
109//! # }
110//! ```
111//!
112//! # EVM Fetchers
113//!
114//! Use individual fetchers to generate storage proofs and retrieve MMR proofs for specific data:
115//!
116//! ```no_run
117//! use bankai_sdk::{Bankai, Network, HashingFunctionDto};
118//! use alloy_primitives::{Address, FixedBytes};
119//!
120//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
121//! # let sdk = Bankai::new(Network::Sepolia,
122//! # Some("https://eth-sepolia.rpc".to_string()),
123//! # Some("https://sepolia.beacon.api".to_string()));
124//!
125//! // Execution layer fetcher
126//! let execution = sdk.evm.execution()?;
127//!
128//! // Fetch execution header with MMR proof
129//! let header = execution.header(9231247, HashingFunctionDto::Keccak, 12345).await?;
130//!
131//! // Fetch account with storage proofs
132//! let account = execution.account(
133//! 9231247,
134//! Address::ZERO,
135//! HashingFunctionDto::Keccak,
136//! 12345
137//! ).await?;
138//!
139//! // Fetch transaction with proof (by hash)
140//! let tx_hash = FixedBytes::from([0u8; 32]);
141//! let tx = execution.transaction(9231247, tx_hash, HashingFunctionDto::Keccak, 12345).await?;
142//!
143//! // Beacon chain fetcher
144//! let beacon = sdk.evm.beacon()?;
145//!
146//! // Fetch beacon header with MMR proof
147//! let beacon_header = beacon.header(8551383, HashingFunctionDto::Keccak, 12345).await?;
148//! # Ok(())
149//! # }
150//! ```
151
152pub mod errors;
153
154// Re-export common types from bankai_types
155pub use bankai_types::api::proofs::HashingFunctionDto;
156pub use bankai_types::fetch::ProofWrapper;
157pub use bankai_types::verify::evm::beacon::BeaconHeader;
158
159// ============================================================================
160// Network Configuration
161// ============================================================================
162
163/// Supported blockchain networks
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum Network {
166 /// Ethereum Sepolia testnet
167 Sepolia,
168}
169
170impl Network {
171 /// Returns the API base URL for this network
172 pub fn api_url(&self) -> &'static str {
173 match self {
174 Network::Sepolia => "https://sepolia.api.bankai.xyz",
175 }
176 }
177
178 /// Returns the beacon chain network ID (always 0)
179 pub const fn beacon_network_id(&self) -> u64 {
180 0
181 }
182
183 /// Returns the execution layer network ID (always 1)
184 pub const fn execution_network_id(&self) -> u64 {
185 11155111
186 }
187}
188
189// ============================================================================
190// Public API Components
191// ============================================================================
192
193/// API client for interacting with Bankai's proof generation service
194pub use crate::fetch::clients::bankai_api::ApiClient;
195
196/// EVM execution and beacon chain fetchers
197///
198/// Access execution layer (headers, accounts, transactions) and beacon chain (consensus headers)
199/// data with MMR proofs for trustless verification.
200pub mod evm {
201
202 pub use crate::fetch::evm::beacon::BeaconChainFetcher;
203 pub use crate::fetch::evm::execution::ExecutionChainFetcher;
204
205 // Re-export common EVM types
206 pub use bankai_types::fetch::evm::{
207 beacon::BeaconHeaderProof,
208 execution::{AccountProof, ExecutionHeaderProof, StorageSlotProof, TxProof},
209 };
210}
211
212/// Batch proof generation for efficient multi-proof operations
213///
214/// Combine multiple proof requests into a single optimized operation.
215/// All proofs share the same STWO block proof and Bankai block number.
216pub mod batch {
217
218 pub use crate::fetch::batch::ProofBatchBuilder;
219}
220
221// Keep fetch module private (internal implementation details)
222mod fetch;
223
224use crate::errors::{SdkError, SdkResult};
225use crate::fetch::evm::{beacon::BeaconChainFetcher, execution::ExecutionChainFetcher};
226
227// ============================================================================
228// Main SDK Struct
229// ============================================================================
230
231/// Namespace for EVM-related operations
232pub struct EvmNamespace {
233 execution: Option<ExecutionChainFetcher>,
234 beacon: Option<BeaconChainFetcher>,
235}
236
237/// Namespace for verification operations (placeholder for future functionality)
238pub struct VerifyNamespace;
239
240/// Main entry point for the Bankai SDK
241pub struct Bankai {
242 /// Direct access to the Bankai API client
243 pub api: ApiClient,
244 /// EVM execution and beacon chain fetchers
245 pub evm: EvmNamespace,
246 /// Verification utilities
247 pub verify: VerifyNamespace,
248 network: Network,
249}
250
251impl Bankai {
252 /// Creates a new Bankai SDK instance
253 ///
254 /// # Arguments
255 ///
256 /// * `network` - The blockchain network (e.g., `Network::Sepolia`)
257 /// * `evm_execution_rpc` - Optional execution layer RPC endpoint
258 /// * `evm_beacon_rpc` - Optional beacon chain API endpoint
259 pub fn new(
260 network: Network,
261 evm_execution_rpc: Option<String>,
262 evm_beacon_rpc: Option<String>,
263 ) -> Self {
264 let api = ApiClient::new(network);
265 let execution = evm_execution_rpc.map(|rpc| {
266 ExecutionChainFetcher::new(api.clone(), rpc, network.execution_network_id())
267 });
268 let beacon = evm_beacon_rpc
269 .map(|rpc| BeaconChainFetcher::new(api.clone(), rpc, network.beacon_network_id()));
270
271 Bankai {
272 api: api.clone(),
273 evm: EvmNamespace { execution, beacon },
274 verify: VerifyNamespace,
275 network,
276 }
277 }
278
279 /// Returns the network this SDK instance is configured for
280 pub fn network(&self) -> Network {
281 self.network
282 }
283
284 /// Initialize a new batch proof builder
285 ///
286 /// # Arguments
287 ///
288 /// * `network` - The blockchain network (e.g., `Network::Sepolia`)
289 /// * `bankai_block_number` - Optional Bankai block number (uses latest if `None`)
290 /// * `hashing` - The hashing function for MMR proofs (Keccak, Poseidon, or Blake3)
291 pub async fn init_batch(
292 &self,
293 network: Network,
294 bankai_block_number: Option<u64>,
295 hashing: HashingFunctionDto,
296 ) -> SdkResult<batch::ProofBatchBuilder> {
297 let block_number = match bankai_block_number {
298 Some(bn) => bn,
299 None => self.api.get_latest_block_number().await?,
300 };
301 Ok(batch::ProofBatchBuilder::new(
302 self,
303 network,
304 block_number,
305 hashing,
306 ))
307 }
308}
309
310impl EvmNamespace {
311 /// Get the execution layer fetcher
312 pub fn execution(&self) -> SdkResult<&ExecutionChainFetcher> {
313 self.execution
314 .as_ref()
315 .ok_or_else(|| SdkError::NotConfigured("EVM execution fetcher".to_string()))
316 }
317
318 /// Get the beacon chain fetcher
319 pub fn beacon(&self) -> SdkResult<&BeaconChainFetcher> {
320 self.beacon
321 .as_ref()
322 .ok_or_else(|| SdkError::NotConfigured("EVM beacon fetcher".to_string()))
323 }
324}