13
13
//! let balance = account.balance();
14
14
//! ```
15
15
16
- use alloc:: vec;
17
- use alloc:: vec:: Vec ;
18
-
19
16
use crate :: hostio;
17
+ use alloc:: vec:: Vec ;
20
18
use alloy_primitives:: { b256, Address , B256 , U256 } ;
21
19
22
20
/// Trait that allows the [`Address`] type to inspect the corresponding account's balance and codehash.
23
21
pub trait AddressVM {
24
22
/// The balance in wei of the account.
25
23
fn balance ( & self ) -> U256 ;
26
24
27
- /// The code of the contract at the given address.
25
+ /// The account's code.
26
+ ///
27
+ /// Returns an empty [`vec`] for [`EOAs`].
28
+ ///
29
+ /// [`EOAs`]: https://ethereum.org/en/developers/docs/accounts/#types-of-account
28
30
fn code ( & self ) -> Vec < u8 > ;
29
31
32
+ /// The length of the account's code in bytes.
33
+ ///
34
+ /// Returns `0` for [`EOAs`].
35
+ ///
36
+ /// [`EOAs`]: https://ethereum.org/en/developers/docs/accounts/#types-of-account
37
+ fn code_size ( & self ) -> usize ;
38
+
30
39
/// The codehash of the contract or [`EOA`] at the given address.
31
40
///
32
41
/// [`EOA`]: https://ethereum.org/en/developers/docs/accounts/#types-of-account
@@ -43,22 +52,27 @@ pub trait AddressVM {
43
52
impl AddressVM for Address {
44
53
fn balance ( & self ) -> U256 {
45
54
let mut data = [ 0 ; 32 ] ;
46
- unsafe { hostio:: account_balance ( self . 0 . as_ptr ( ) , data. as_mut_ptr ( ) ) } ;
55
+ unsafe { hostio:: account_balance ( self . as_ptr ( ) , data. as_mut_ptr ( ) ) } ;
47
56
U256 :: from_be_bytes ( data)
48
57
}
49
58
50
59
fn code ( & self ) -> Vec < u8 > {
51
- let size = unsafe { hostio :: account_code_size ( self . 0 . as_ptr ( ) ) } ;
52
- let mut data = vec ! [ 0 ; size] ;
60
+ let size = self . code_size ( ) ;
61
+ let mut data = Vec :: with_capacity ( size) ;
53
62
unsafe {
54
- hostio:: account_code ( self . 0 . as_ptr ( ) , 0 , size, data. as_mut_ptr ( ) ) ;
63
+ hostio:: account_code ( self . as_ptr ( ) , 0 , size, data. as_mut_ptr ( ) ) ;
64
+ data. set_len ( size) ;
55
65
}
56
66
data
57
67
}
58
68
69
+ fn code_size ( & self ) -> usize {
70
+ unsafe { hostio:: account_code_size ( self . as_ptr ( ) ) }
71
+ }
72
+
59
73
fn codehash ( & self ) -> B256 {
60
74
let mut data = [ 0 ; 32 ] ;
61
- unsafe { hostio:: account_codehash ( self . 0 . as_ptr ( ) , data. as_mut_ptr ( ) ) } ;
75
+ unsafe { hostio:: account_codehash ( self . as_ptr ( ) , data. as_mut_ptr ( ) ) } ;
62
76
data. into ( )
63
77
}
64
78
0 commit comments