loom_node_debug_provider/
anvilprovider.rs

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
use alloy::{
    primitives::{Address, Bytes, B256, U256, U64},
    providers::{network::Ethereum, Network, Provider, RootProvider},
    transports::{BoxTransport, Transport, TransportResult},
};

use crate::AnvilDebugProvider;

pub(crate) fn convert_u64(r: U64) -> u64 {
    r.to::<u64>()
}

pub trait AnvilProviderExt<T, N>
where
    N: Network,
    T: Transport + Clone,
{
    fn snapshot(&self) -> impl std::future::Future<Output = TransportResult<u64>> + Send;
    fn revert(&self, snap_id: u64) -> impl std::future::Future<Output = TransportResult<bool>> + Send;

    fn mine(&self) -> impl std::future::Future<Output = TransportResult<u64>> + Send;

    fn set_automine(&self, to_mine: bool) -> impl std::future::Future<Output = TransportResult<()>> + Send;

    fn set_code(&self, address: Address, code: Bytes) -> impl std::future::Future<Output = TransportResult<()>> + Send;

    fn set_balance(&self, address: Address, balance: U256) -> impl std::future::Future<Output = TransportResult<()>> + Send;

    //fn get_storage(&self, address: Address, cell: U256) -> impl std::future::Future<Output=TransportResult<U256>> + Send;
    fn set_storage(&self, address: Address, cell: B256, value: B256) -> impl std::future::Future<Output = TransportResult<bool>> + Send;
}

impl<PN, PA, TN, TA, N> AnvilProviderExt<TA, N> for AnvilDebugProvider<PN, PA, TN, TA, N>
where
    N: Network,
    TN: Transport + Clone,
    TA: Transport + Clone,
    PN: Provider<TN, N> + Send + Sync + Clone + 'static,
    PA: Provider<TA, N> + Send + Sync + Clone + 'static,
{
    fn snapshot(&self) -> impl std::future::Future<Output = TransportResult<u64>> + Send {
        self.anvil().client().request("evm_snapshot", ()).map_resp(convert_u64)
    }
    fn revert(&self, snap_id: u64) -> impl std::future::Future<Output = TransportResult<bool>> + Send {
        self.anvil().client().request("evm_revert", (U64::from(snap_id),))
    }

    fn mine(&self) -> impl std::future::Future<Output = TransportResult<u64>> + Send {
        self.anvil().client().request("evm_mine", ()).map_resp(convert_u64)
    }

    fn set_automine(&self, to_mine: bool) -> impl std::future::Future<Output = TransportResult<()>> + Send {
        self.anvil().client().request("evm_setAutomine", (to_mine,))
    }

    fn set_code(&self, address: Address, code: Bytes) -> impl std::future::Future<Output = TransportResult<()>> + Send {
        self.anvil().client().request("anvil_setCode", (address, code))
    }

    fn set_balance(&self, address: Address, balance: U256) -> impl std::future::Future<Output = TransportResult<()>> + Send {
        self.anvil().client().request("anvil_setBalance", (address, balance))
    }

    fn set_storage(&self, address: Address, cell: B256, value: B256) -> impl std::future::Future<Output = TransportResult<bool>> + Send {
        self.anvil().client().request("anvil_setStorageAt", (address, cell, value))
    }
    /*    fn get_storage(&self, address: Address, cell: U256) -> impl std::future::Future<Output=TransportResult<U256>> + Send {
        self.anvil().client().request("anvil_getStorageAt", (address, cell))
    }*/
}

impl AnvilProviderExt<BoxTransport, Ethereum> for RootProvider<BoxTransport> {
    fn snapshot(&self) -> impl std::future::Future<Output = TransportResult<u64>> + Send {
        self.client().request("evm_snapshot", ()).map_resp(convert_u64)
    }
    fn revert(&self, snap_id: u64) -> impl std::future::Future<Output = TransportResult<bool>> + Send {
        self.client().request("evm_revert", (U64::from(snap_id),))
    }

    fn mine(&self) -> impl std::future::Future<Output = TransportResult<u64>> + Send {
        self.client().request("evm_mine", ()).map_resp(convert_u64)
    }

    fn set_automine(&self, to_mine: bool) -> impl std::future::Future<Output = TransportResult<()>> + Send {
        self.client().request("evm_setAutomine", (to_mine,))
    }

    fn set_code(&self, address: Address, code: Bytes) -> impl std::future::Future<Output = TransportResult<()>> + Send {
        self.client().request("anvil_setCode", (address, code))
    }

    fn set_balance(&self, address: Address, balance: U256) -> impl std::future::Future<Output = TransportResult<()>> + Send {
        self.client().request("anvil_setBalance", (address, balance))
    }

    fn set_storage(&self, address: Address, cell: B256, value: B256) -> impl std::future::Future<Output = TransportResult<bool>> + Send {
        self.client().request("anvil_setStorageAt", (address, cell, value))
    }
    /*    fn get_storage(&self, address: Address, cell: U256) -> impl std::future::Future<Output=TransportResult<U256>> + Send {
        self.anvil().client().request("anvil_getStorageAt", (address, cell))
    }*/
}

#[cfg(test)]
mod test {
    use alloy::node_bindings::Anvil;
    use alloy::primitives::{B256, U256};
    use alloy::rpc::types::BlockNumberOrTag;
    use alloy::transports::http::Http;
    use alloy_provider::ext::AnvilApi;
    use alloy_provider::ProviderBuilder;
    use alloy_rpc_client::ClientBuilder;
    use env_logger::Env as EnvLog;
    use eyre::Result;
    use reqwest::Client;
    use std::ops::Deref;
    use std::sync::Arc;

    use super::*;

    #[tokio::test]
    async fn test_storage() -> Result<()> {
        let _ = env_logger::try_init_from_env(EnvLog::default().default_filter_or("info"));

        let anvil = Anvil::new().try_spawn()?;

        let client_anvil = ClientBuilder::default().http(anvil.endpoint_url()).boxed();

        let provider = ProviderBuilder::new().on_client(client_anvil);

        let address: Address = Address::repeat_byte(0x12);

        if let Err(e) = provider.set_storage(address, B256::from(U256::from(1)), B256::from(U256::from(2))).await {
            panic!("{}", e);
        }

        let value = provider.get_storage_at(address, U256::from(1)).await?;
        if value != U256::from(2) {
            panic!("Incorrect value {}", value);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_anvil_commands() -> Result<()> {
        let _ = env_logger::try_init_from_env(EnvLog::default().default_filter_or("info"));
        let anvil = Anvil::new().try_spawn()?;

        let node_url = std::env::var("MAINNET_HTTP").unwrap().to_string();

        let test_node_url = anvil.endpoint_url();

        let node_url = url::Url::parse(node_url.as_str())?;

        let client_anvil = ClientBuilder::default().http(test_node_url).boxed();
        let provider_anvil = ProviderBuilder::new().on_client(client_anvil).boxed();

        let client_node = ClientBuilder::default().http(node_url).boxed();
        let provider_node = ProviderBuilder::new().on_client(client_node).boxed();

        let provider = AnvilDebugProvider::new(provider_node, provider_anvil, BlockNumberOrTag::Number(10));

        let client = Arc::new(provider);

        let snap = client.snapshot().await?;
        let _ = client.revert(snap).await?;
        client.set_automine(false).await?;
        let _ = client.mine().await;
        client.set_automine(true).await?;

        Ok(())
    }

    #[derive(Clone)]
    struct DynPrv<T> {
        pub provider: Arc<Box<dyn Provider<T>>>,
    }

    impl<T> Deref for DynPrv<T>
    where
        T: Transport + Clone,
    {
        type Target = Arc<Box<dyn Provider<T> + 'static>>;

        fn deref(&self) -> &Self::Target {
            &self.provider
        }
    }

    struct DynProvider {
        inner: DynPrv<BoxTransport>,
    }

    impl From<DynPrv<Http<Client>>> for DynProvider {
        fn from(value: DynPrv<Http<Client>>) -> Self {
            let provider = DynPrv { provider: Arc::new(Box::new(ProviderBuilder::new().on_provider(value.root().clone().boxed()))) };
            Self { inner: provider }
        }
    }

    impl Provider for DynProvider {
        fn root(&self) -> &RootProvider<BoxTransport, Ethereum> {
            self.inner.root()
        }
    }

    #[tokio::test]
    async fn test_dyn_provider() -> Result<()> {
        let provider = ProviderBuilder::new().with_recommended_fillers().on_anvil();

        let dyn_prv = Arc::new(Box::new(provider) as Box<dyn Provider<_>>);

        let dyn_prv = DynPrv { provider: dyn_prv.clone() };

        let dyn_prv = DynProvider::from(dyn_prv);

        let _ = dyn_prv.anvil_drop_all_transactions().await;

        Ok(())
    }
}