web30 1.15.0

Async endian safe web3 library
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use std::time::{Duration, Instant};

use super::{core::Web3, ETHEREUM_INTRINSIC_GAS};
use crate::{
    jsonrpc::error::Web3Error,
    types::{Data, SendTxOption, TransactionRequest, TransactionResponse},
};
use clarity::{utils::bytes_to_hex_str, Address, PrivateKey, Transaction};
use futures::future::join4;
use num256::Uint256;
use num_traits::ToPrimitive;
use tokio::time::sleep;

// The state altering part of the "eth" namespace of the Web3 API, and convenience functions for transaction generation

impl Web3 {
    pub async fn eth_send_transaction(
        &self,
        transactions: Vec<TransactionRequest>,
    ) -> Result<Uint256, Web3Error> {
        self.jsonrpc_client
            .request_method("eth_sendTransaction", transactions, self.timeout)
            .await
    }

    pub async fn eth_call(&self, transaction: TransactionRequest) -> Result<Data, Web3Error> {
        //syncing check
        match self.eth_syncing().await? {
            false => {
                self.jsonrpc_client
                    .request_method("eth_call", (transaction, "latest"), self.timeout)
                    .await
            }
            true => Err(Web3Error::SyncingNode(
                "Cannot perform eth_call".to_string(),
            )),
        }
    }

    pub async fn eth_call_at_height(
        &self,
        transaction: TransactionRequest,
        block: Uint256,
    ) -> Result<Data, Web3Error> {
        let latest_known_block = self.eth_synced_block_number().await?;
        if block <= latest_known_block {
            self.jsonrpc_client
                .request_method(
                    "eth_call",
                    (transaction, format!("{:#x}", block.0)), // THIS IS THE MAGIC I NEEDED
                    self.timeout,
                )
                .await
        } else if self.eth_syncing().await? {
            Err(Web3Error::SyncingNode(
                "Cannot perform eth_call_at_height".to_string(),
            ))
        } else {
            //Invalid block number
            Err(Web3Error::BadInput(
                "Cannot perform eth_call_at_height, block number invalid".to_string(),
            ))
        }
    }

    /// Publishes a prepared transaction and returns the txhash on success. If you want to wait for the transaction
    /// to actually execute on chain, you can use `web3.wait_for_transaction()`
    pub async fn send_prepared_transaction(
        &self,
        transaction: Transaction,
    ) -> Result<Uint256, Web3Error> {
        self.eth_send_raw_transaction(transaction.to_bytes()).await
    }

    pub async fn eth_send_raw_transaction(&self, data: Vec<u8>) -> Result<Uint256, Web3Error> {
        self.jsonrpc_client
            .request_method(
                "eth_sendRawTransaction",
                vec![format!("0x{}", bytes_to_hex_str(&data))],
                self.timeout,
            )
            .await
    }

    /// Sends a transaction which changes blockchain state
    /// this function is the same as send_transaction except it sends
    /// a legacy format transaction with higher gas costs.
    /// The result can be immediately published using
    /// `self.send_prepared_transaction(transaction).await`
    pub async fn prepare_legacy_transaction(
        &self,
        to_address: Address,
        data: Vec<u8>,
        value: Uint256,
        own_address: Address,
        secret: PrivateKey,
        options: Vec<SendTxOption>,
    ) -> Result<Transaction, Web3Error> {
        let mut gas_price = None;
        let mut gas_price_multiplier = 1f32;
        let mut gas_limit_multiplier = 1f32;
        let mut gas_limit = None;
        let mut network_id = None;
        let our_balance = self.eth_get_balance(own_address).await?;
        if our_balance.is_zero() || our_balance < ETHEREUM_INTRINSIC_GAS.into() {
            // We only know that the balance is insufficient, we don't know how much gas is needed
            return Err(Web3Error::InsufficientGas {
                balance: our_balance,
                base_gas: ETHEREUM_INTRINSIC_GAS.into(),
                gas_required: ETHEREUM_INTRINSIC_GAS.into(),
            });
        }
        let mut nonce = self.eth_get_transaction_count(own_address).await?;

        for option in options {
            match option {
                SendTxOption::GasPrice(gp) => gas_price = Some(gp),
                SendTxOption::GasPriceMultiplier(gpm) => gas_price_multiplier = gpm,
                SendTxOption::GasLimitMultiplier(glm) => gas_limit_multiplier = glm,
                SendTxOption::GasLimit(gl) => gas_limit = Some(gl),
                SendTxOption::NetworkId(ni) => network_id = Some(ni),
                SendTxOption::Nonce(n) => nonce = n,
                SendTxOption::GasMaxFee(_)
                | SendTxOption::GasPriorityFee(_)
                | SendTxOption::AccessList(_)
                | SendTxOption::GasMaxFeeMultiplier(_) => {
                    return Err(Web3Error::BadInput(
                        "Invalid option for Legacy tx".to_string(),
                    ))
                }
            }
        }

        let mut gas_price = if let Some(gp) = gas_price {
            gp
        } else {
            let gas_price = self.eth_gas_price().await?;
            let f32_gas = gas_price.to_u128();
            if let Some(v) = f32_gas {
                // convert to f32, multiply, then convert back, this
                // will be lossy but you want an exact price you can set it
                ((v as f32 * gas_price_multiplier) as u128).into()
            } else {
                // gas price is insanely high, best effort rounding
                // perhaps we should panic here
                gas_price * (gas_price_multiplier.round() as u128).into()
            }
        };

        let mut gas_limit = if let Some(gl) = gas_limit {
            gl
        } else {
            let gas = self.simulated_gas_price_and_limit(our_balance).await?;
            self.eth_estimate_gas(TransactionRequest::Legacy {
                from: own_address,
                to: Some(to_address),
                nonce: Some(nonce.into()),
                gas_price: Some(gas.price.into()),
                gas: Some(gas.limit.into()),
                value: Some(value.into()),
                data: Some(data.clone().into()),
            })
            .await?
        };

        // multiply limit by gasLimitMultiplier
        let gas_limit_128 = gas_limit.to_u128();
        if let Some(v) = gas_limit_128 {
            gas_limit = ((v as f32 * gas_limit_multiplier) as u128).into()
        } else {
            gas_limit *= (gas_limit_multiplier.round() as u128).into()
        }

        let network_id = if let Some(ni) = network_id {
            ni
        } else {
            self.eth_chainid().await?
        };

        // this is an edge case where we are about to send a transaction that can't possibly
        // be valid, we simply don't have the the funds to pay the full gas amount we are promising
        // this segment computes either the highest valid gas price we can pay or in the post-london
        // chain case errors if we can't meet the minimum fee
        if gas_price * gas_limit > our_balance {
            let base_fee_per_gas = self.get_base_fee_per_gas().await?;
            if let Some(base_fee_per_gas) = base_fee_per_gas {
                if base_fee_per_gas * gas_limit > our_balance {
                    return Err(Web3Error::InsufficientGas {
                        balance: our_balance,
                        base_gas: base_fee_per_gas,
                        gas_required: gas_limit,
                    });
                }
            }
            // this will give some value >= base_fee_per_gas * gas_limit
            // in post-london and some non zero value in pre-london
            gas_price = our_balance / gas_limit;
        }

        let transaction = Transaction::Legacy {
            to: to_address,
            nonce,
            gas_price,
            gas_limit,
            value,
            data,
            signature: None,
        };

        Ok(transaction.sign(&secret, Some(network_id)))
    }

    /// Generates but does not send a transaction which changes blockchain state.
    /// `options` takes a vector of `SendTxOption` for configuration
    /// unlike the lower level eth_send_transaction() this call builds
    /// the transaction abstracting away details like gas,
    /// The result can be immediately published using
    /// `self.send_prepared_transaction(transaction).await`
    pub async fn prepare_transaction(
        &self,
        to_address: Address,
        data: Vec<u8>,
        value: Uint256,
        secret: PrivateKey,
        options: Vec<SendTxOption>,
    ) -> Result<Transaction, Web3Error> {
        let mut max_priority_fee_per_gas = 1u8.into();
        let mut gas_limit_multiplier = 1f32;
        let mut gas_limit = None;
        let mut access_list = Vec::new();
        let own_address = secret.to_address();

        let our_balance = self.eth_get_balance(own_address);
        let nonce = self.eth_get_transaction_count(own_address);
        let max_fee_per_gas = self.get_base_fee_per_gas();
        let chain_id = self.eth_chainid();

        // request in parallel
        let (our_balance, nonce, base_fee_per_gas, chain_id) =
            join4(our_balance, nonce, max_fee_per_gas, chain_id).await;

        let (our_balance, mut nonce, base_fee_per_gas, chain_id) =
            (our_balance?, nonce?, base_fee_per_gas?, chain_id?);

        // check if we can send an EIP1559 tx on this chain
        let base_fee_per_gas = match base_fee_per_gas {
            Some(bf) => bf,
            None => return Err(Web3Error::PreLondon),
        };

        // max_fee_per_gas is base gas multiplied by 2, this is a maximum the actual price we pay is determined
        // by the block the transaction enters, if we put the price exactly as the base fee the tx will fail if
        // the price goes up at all in the next block. So some base level multiplier makes sense as a default
        let mut max_fee_per_gas = base_fee_per_gas * 2u8.into();

        if our_balance.is_zero() || our_balance < ETHEREUM_INTRINSIC_GAS.into() {
            // We only know that the balance is insufficient, we don't know how much gas is needed
            return Err(Web3Error::InsufficientGas {
                balance: our_balance,
                base_gas: ETHEREUM_INTRINSIC_GAS.into(),
                gas_required: ETHEREUM_INTRINSIC_GAS.into(),
            });
        }

        for option in options {
            match option {
                SendTxOption::GasMaxFee(gp) | SendTxOption::GasPrice(gp) => max_fee_per_gas = gp,
                SendTxOption::GasPriorityFee(gp) => max_priority_fee_per_gas = gp,
                SendTxOption::GasLimitMultiplier(glm) => gas_limit_multiplier = glm,
                SendTxOption::GasLimit(gl) => gas_limit = Some(gl),
                SendTxOption::Nonce(n) => nonce = n,
                SendTxOption::AccessList(list) => access_list = list,
                SendTxOption::GasPriceMultiplier(gm) | SendTxOption::GasMaxFeeMultiplier(gm) => {
                    let f32_gas = base_fee_per_gas.to_u128();
                    max_fee_per_gas = if let Some(v) = f32_gas {
                        // convert to f32, multiply, then convert back, this
                        // will be lossy but you want an exact price you can set it
                        ((v as f32 * gm) as u128).into()
                    } else {
                        // gas price is insanely high, best effort rounding
                        // perhaps we should panic here
                        base_fee_per_gas * (gm.round() as u128).into()
                    };
                }
                SendTxOption::NetworkId(_) => {
                    return Err(Web3Error::BadInput(
                        "Invalid option for eip1559 tx".to_string(),
                    ))
                }
            }
        }

        let mut transaction = Transaction::Eip1559 {
            chain_id: chain_id.into(),
            nonce,
            max_priority_fee_per_gas,
            max_fee_per_gas,
            gas_limit: 0u8.into(),
            to: to_address,
            value,
            data,
            signature: None,
            access_list,
        };

        let mut gas_limit = if let Some(gl) = gas_limit {
            gl
        } else {
            self.eth_estimate_gas(TransactionRequest::from_transaction(
                &transaction,
                own_address,
            ))
            .await?
        };

        // multiply limit by gasLimitMultiplier
        let gas_limit_128 = gas_limit.to_u128();
        if let Some(v) = gas_limit_128 {
            gas_limit = ((v as f32 * gas_limit_multiplier) as u128).into()
        } else {
            gas_limit *= (gas_limit_multiplier.round() as u128).into()
        }

        transaction.set_gas_limit(gas_limit);

        // this is an edge case where we are about to send a transaction that can't possibly
        // be valid, we simply don't have the the funds to pay the full gas amount we are promising
        // this segment computes either the highest valid gas price we can pay or in the post-london
        // chain case errors if we can't meet the minimum fee
        if max_fee_per_gas * gas_limit > our_balance {
            if base_fee_per_gas * gas_limit > our_balance {
                return Err(Web3Error::InsufficientGas {
                    balance: our_balance,
                    base_gas: base_fee_per_gas,
                    gas_required: gas_limit,
                });
            }
            // this will give some value >= base_fee_per_gas * gas_limit
            // in post-london and some non zero value in pre-london
            max_fee_per_gas = our_balance / gas_limit;
        }

        transaction.set_max_fee_per_gas(max_fee_per_gas);

        transaction.is_valid()?;

        let transaction = transaction.sign(&secret, None);

        transaction.is_valid()?;

        // signed transaction is now ready to publish
        Ok(transaction.sign(&secret, None))
    }

    /// Simulates an Ethereum contract call by making a fake transaction and sending it to a special endpoint
    /// this code is executed exactly as if it where an actual transaction executing. This can be used to execute
    /// both getter endpoints on Solidity contracts and to test actual executions. User beware, this function requires
    /// ETH in the caller address to run. Even if you're just trying to call a getter function and never need to actually
    /// run code this faithful simulation will fail if you have no ETH to pay for gas.
    ///
    /// In an attempt to maximize the amount of info you can get with this function gas is computed for you as the maximum
    /// possible value, if you need to get  gas estimation you should use `web3.eth_estimate_gas` instead.
    ///
    /// optionally this data can come from some historic block
    pub async fn simulate_transaction(
        &self,
        mut transaction: TransactionRequest,
        options: Vec<SendTxOption>,
        height: Option<Uint256>,
    ) -> Result<Vec<u8>, Web3Error> {
        let own_address = transaction.get_from();
        let our_balance = self.eth_get_balance(own_address).await?;
        if our_balance.is_zero() || our_balance < ETHEREUM_INTRINSIC_GAS.into() {
            // We only know that the balance is insufficient, we don't know how much gas is needed
            return Err(Web3Error::InsufficientGas {
                balance: our_balance,
                base_gas: ETHEREUM_INTRINSIC_GAS.into(),
                gas_required: ETHEREUM_INTRINSIC_GAS.into(),
            });
        }

        let nonce = self.eth_get_transaction_count(own_address).await?;

        let gas = self.simulated_gas_price_and_limit(our_balance).await?;

        transaction.set_nonce(nonce);
        transaction.set_gas_limit(gas.limit);
        transaction.set_gas_price(gas.price);

        let gas_limit_option_set = options
            .iter()
            .any(|opt| matches!(opt, SendTxOption::GasLimit(_)));

        for option in options {
            match option {
                SendTxOption::GasMaxFee(gp) | SendTxOption::GasPrice(gp) => {
                    transaction.set_gas_price(gp)
                }
                SendTxOption::GasPriorityFee(gp) => transaction.set_priority_fee(gp),
                SendTxOption::GasLimitMultiplier(glm) => {
                    // only apply this if gas limit is set. Otherwise we are using max gas already
                    // and applying a multiplier would likely push us over the balance limit, a multiplier
                    // lower than 1 is fine in this case as it reduces gas
                    if gas_limit_option_set || glm < 1.0 {
                        let f32_gas = gas.limit.to_u128();
                        let val = if let Some(v) = f32_gas {
                            // convert to f32, multiply, then convert back, this
                            // will be lossy but you want an exact price you can set it
                            ((v as f32 * glm) as u128).into()
                        } else {
                            // gas price is insanely high, best effort rounding
                            // perhaps we should panic here
                            gas.price * (glm.round() as u128).into()
                        };
                        transaction.set_gas_limit(val);
                    }
                }
                SendTxOption::GasLimit(gl) => transaction.set_gas_limit(gl),
                SendTxOption::Nonce(n) => transaction.set_nonce(n),
                SendTxOption::AccessList(list) => transaction.set_access_list(list),
                SendTxOption::GasPriceMultiplier(gm) | SendTxOption::GasMaxFeeMultiplier(gm) => {
                    // same reasoning as gas limit multiplier, we are already using max gas for the default gas
                    // price and our balance. So we can't do a higher price unless the gas limit has been set lower
                    // than max
                    if gas_limit_option_set || gm < 1.0 {
                        let f32_gas = gas.price.to_u128();
                        let val = if let Some(v) = f32_gas {
                            // convert to f32, multiply, then convert back, this
                            // will be lossy but you want an exact price you can set it
                            ((v as f32 * gm) as u128).into()
                        } else {
                            // gas price is insanely high, best effort rounding
                            // perhaps we should panic here
                            gas.price * (gm.round() as u128).into()
                        };
                        transaction.set_gas_price(val);
                    }
                }
                SendTxOption::NetworkId(_) => {
                    return Err(Web3Error::BadInput(
                        "Invalid option for eip1559 tx".to_string(),
                    ))
                }
            }
        }

        match height {
            Some(height) => {
                let bytes = match self.eth_call_at_height(transaction, height).await {
                    Ok(val) => val,
                    Err(e) => return Err(e),
                };
                Ok(bytes.0)
            }
            None => {
                let bytes = match self.eth_call(transaction).await {
                    Ok(val) => val,
                    Err(e) => return Err(e),
                };
                Ok(bytes.0)
            }
        }
    }

    /// Waits for a transaction with the given hash to be included in a block
    /// it will wait for at most timeout time and optionally can wait for n
    /// blocks to have passed
    pub async fn wait_for_transaction(
        &self,
        tx_hash: Uint256,
        timeout: Duration,
        blocks_to_wait: Option<Uint256>,
    ) -> Result<TransactionResponse, Web3Error> {
        let start = Instant::now();
        loop {
            sleep(Duration::from_secs(1)).await;
            match self.eth_get_transaction_by_hash(tx_hash).await {
                Ok(maybe_transaction) => {
                    if let Some(transaction) = maybe_transaction {
                        // if no wait time is specified and the tx is in a block return right away
                        if blocks_to_wait.clone().is_none()
                            && transaction.get_block_number().is_some()
                        {
                            return Ok(transaction);
                        }
                        // One the tx is in a block we start waiting here
                        else if let (Some(blocks_to_wait), Some(tx_block)) =
                            (blocks_to_wait, transaction.get_block_number())
                        {
                            let current_block = self.eth_block_number().await?;
                            // we check for underflow, which is possible on testnets
                            if current_block > blocks_to_wait
                                && current_block - blocks_to_wait >= tx_block
                            {
                                return Ok(transaction);
                            }
                        }
                    }
                }
                Err(e) => return Err(e),
            }

            if Instant::now() - start > timeout {
                return Err(Web3Error::TransactionTimeout);
            }
        }
    }

    /// Deploy a contract to the blockchain.
    ///
    /// This is a high-level convenience function that handles all the details of
    /// contract deployment including nonce management, gas estimation, transaction
    /// signing, and waiting for confirmation.
    ///
    /// # Arguments
    /// * `deployer` - Private key of the deploying account
    /// * `init_code` - Contract initialization code (bytecode)
    /// * `constructor_args` - ABI-encoded constructor arguments (use clarity::abi to encode)
    /// * `value` - Amount of ETH to send with deployment (in wei)
    /// * `options` - Vector of SendTxOption for configuration (gas, nonce, etc.)
    /// * `wait_timeout` - Optional timeout for waiting for the deployment transaction to be mined, if none
    ///   we will not wait for deployment and return immediately with the predicted address.
    ///
    /// # Returns
    /// The address where the contract was deployed
    ///
    /// # Examples
    /// ```no_run
    /// # use web30::client::Web3;
    /// # use clarity::{PrivateKey, Uint256};
    /// # use std::time::Duration;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let web3 = Web3::new("https://eth.althea.net", Duration::from_secs(30));
    /// let private_key: PrivateKey = "0x...".parse()?;
    /// let init_code = vec![0x60, 0x80, 0x60, 0x40]; // Your contract bytecode
    /// let constructor_args = vec![]; // ABI-encoded constructor args
    ///
    /// let contract_address = web3.deploy_contract(
    ///     &private_key,
    ///     init_code,
    ///     constructor_args,
    ///     Uint256::from(0u8),
    ///     vec![],
    ///     None,
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn deploy_contract(
        &self,
        deployer: &PrivateKey,
        init_code: Vec<u8>,
        constructor_args: Vec<u8>,
        value: Uint256,
        options: Vec<SendTxOption>,
        wait_timeout: Option<Duration>,
    ) -> Result<Address, Web3Error> {
        let deployer_address = deployer.to_address();

        // Combine init code with constructor args
        let mut full_init_code = init_code;
        full_init_code.extend(constructor_args);

        // Determine the nonce: use the caller-supplied Nonce option if present,
        // otherwise fetch it from the chain and inject it so prepare_transaction
        // uses the exact same value we use for address prediction.
        let caller_nonce = options.iter().find_map(|o| {
            if let SendTxOption::Nonce(n) = o {
                Some(*n)
            } else {
                None
            }
        });
        let (nonce, options) = if let Some(n) = caller_nonce {
            (n, options)
        } else {
            // if we have no nonce we must set it as an optoin so that prepare_transaction doesn't fetch a different one and cause our prediction to be wrong
            let n = self.eth_get_transaction_count(deployer_address).await?;
            let mut opts = options;
            opts.push(SendTxOption::Nonce(n));
            (n, opts)
        };

        // Predict the contract address
        let predicted_address = clarity::calculate_contract_address(deployer_address, nonce);

        // Prepare and send the deployment transaction
        let tx = self
            .prepare_transaction(
                Address::default(), // Zero address for deployment
                full_init_code,
                value,
                *deployer,
                options,
            )
            .await?;

        let tx_hash = self.send_prepared_transaction(tx).await?;

        match wait_timeout {
            Some(timeout) => {
                self.wait_for_deployment(tx_hash, timeout, predicted_address)
                    .await
            }
            None => Ok(predicted_address),
        }
    }

    /// Estimate gas for a contract deployment.
    ///
    /// This function simulates the contract deployment to estimate how much gas
    /// it will require.
    ///
    /// # Arguments
    /// * `deployer` - Address that will deploy the contract
    /// * `init_code` - Contract initialization code
    /// * `constructor_args` - ABI-encoded constructor arguments
    /// * `value` - Amount of ETH to send with deployment
    ///
    /// # Returns
    /// Estimated gas required for deployment
    pub async fn estimate_deploy_gas(
        &self,
        deployer: Address,
        init_code: Vec<u8>,
        constructor_args: Vec<u8>,
        value: Uint256,
    ) -> Result<Uint256, Web3Error> {
        let mut full_init_code = init_code;
        full_init_code.extend(constructor_args);

        self.eth_estimate_gas(TransactionRequest::Legacy {
            from: deployer,
            to: None, // Omitted for contract creation
            nonce: None,
            gas_price: None,
            gas: None,
            value: Some(value.into()),
            data: Some(full_init_code.into()),
        })
        .await
    }

    /// Wait for a deployment transaction to complete and return the contract address.
    ///
    /// This function waits for a deployment transaction to be mined and then
    /// extracts the contract address from the transaction receipt.
    ///
    /// # Arguments
    /// * `tx_hash` - Transaction hash of the deployment
    /// * `timeout` - Maximum time to wait
    ///
    /// # Returns
    /// The address where the contract was deployed
    pub async fn wait_for_deployment(
        &self,
        tx_hash: Uint256,
        timeout: Duration,
        expected_address: Address,
    ) -> Result<Address, Web3Error> {
        // Wait for transaction to be mined, wait at least one block after as well
        self.wait_for_transaction(tx_hash, timeout, Some(1u8.into()))
            .await?;

        // Get the transaction receipt
        let receipt = self
            .eth_get_transaction_receipt(tx_hash)
            .await?
            .ok_or_else(|| {
                Web3Error::BadResponse("No receipt found for deployment transaction".to_string())
            })?;

        if !receipt.get_success() {
            return Err(Web3Error::ContractCallError(format!(
                "Contract deployment failed, transaction reverted. Receipt: {:#?}",
                receipt
            )));
        }

        // Extract contract address from receipt
        let contract_address = receipt.get_contract_address().ok_or_else(|| {
            Web3Error::BadResponse("No contract address in deployment receipt".to_string())
        })?;

        if contract_address != expected_address {
            return Err(Web3Error::BadResponse(format!(
                "Deployed contract address does not match expected address. Got: {:?}, Expected: {:?}",
                contract_address, expected_address
            )));
        }

        // Verify contract code exists
        let code = self.eth_get_code(contract_address, None).await?;
        if code.is_empty() {
            return Err(Web3Error::ContractCallError(
                "Contract deployment: no code at address".to_string(),
            ));
        }

        Ok(contract_address)
    }
}