forked from foundry-rs/foundry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtempo.rs
More file actions
368 lines (325 loc) · 11.2 KB
/
tempo.rs
File metadata and controls
368 lines (325 loc) · 11.2 KB
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
//! Tempo precompile and contract initialization for Foundry.
//!
//! This module provides the core initialization logic for Tempo-specific precompiles,
//! fee tokens (PathUSD, AlphaUSD, BetaUSD, ThetaUSD), and standard contracts.
//!
//! It includes a storage provider adapter for Foundry's `Backend` and the shared
//! genesis initialization function used by both anvil and forge.
use std::collections::HashMap;
use alloy_primitives::{Address, Bytes, U256, address};
use revm::{
Database,
context::journaled_state::JournalCheckpoint,
state::{AccountInfo, Bytecode},
};
use tempo_chainspec::hardfork::TempoHardfork;
use tempo_contracts::{
ARACHNID_CREATE2_FACTORY_ADDRESS, CREATEX_ADDRESS, CreateX, MULTICALL3_ADDRESS, Multicall3,
PERMIT2_ADDRESS, Permit2, SAFE_DEPLOYER_ADDRESS, SafeDeployer,
contracts::ARACHNID_CREATE2_FACTORY_BYTECODE,
};
use tempo_precompiles::{
ACCOUNT_KEYCHAIN_ADDRESS, NONCE_PRECOMPILE_ADDRESS, STABLECOIN_DEX_ADDRESS,
TIP_FEE_MANAGER_ADDRESS, TIP20_FACTORY_ADDRESS, TIP403_REGISTRY_ADDRESS,
VALIDATOR_CONFIG_ADDRESS, VALIDATOR_CONFIG_V2_ADDRESS,
error::TempoPrecompileError,
storage::{PrecompileStorageProvider, StorageCtx},
tip20::{ISSUER_ROLE, ITIP20, TIP20Token},
tip20_factory::TIP20Factory,
validator_config,
};
use crate::backend::Backend;
pub use tempo_contracts::precompiles::{
ALPHA_USD_ADDRESS, BETA_USD_ADDRESS, PATH_USD_ADDRESS, THETA_USD_ADDRESS,
};
// TODO: remove once we can re-export from tempo_precompiles instead.
pub const SIGNATURE_VERIFIER_ADDRESS: Address =
address!("0x5165300000000000000000000000000000000000");
pub const ADDRESS_REGISTRY_ADDRESS: Address =
address!("0xFDC0000000000000000000000000000000000000");
/// All well-known Tempo precompile addresses.
pub const TEMPO_PRECOMPILE_ADDRESSES: &[Address] = &[
NONCE_PRECOMPILE_ADDRESS,
STABLECOIN_DEX_ADDRESS,
TIP20_FACTORY_ADDRESS,
TIP403_REGISTRY_ADDRESS,
TIP_FEE_MANAGER_ADDRESS,
VALIDATOR_CONFIG_ADDRESS,
VALIDATOR_CONFIG_V2_ADDRESS,
ACCOUNT_KEYCHAIN_ADDRESS,
];
/// All well-known TIP20 fee token addresses on Tempo networks.
pub const TEMPO_TIP20_TOKENS: &[Address] =
&[PATH_USD_ADDRESS, ALPHA_USD_ADDRESS, BETA_USD_ADDRESS, THETA_USD_ADDRESS];
/// Storage provider adapter that wraps Foundry's `Backend` to implement Tempo's
/// [`PrecompileStorageProvider`] trait for precompile initialization.
pub struct TempoStorageProvider<'a> {
backend: &'a mut Backend,
chain_id: u64,
timestamp: U256,
block_number: u64,
gas_used: u64,
gas_refunded: i64,
transient: HashMap<(Address, U256), U256>,
beneficiary: Address,
hardfork: TempoHardfork,
}
impl<'a> TempoStorageProvider<'a> {
pub fn new(
backend: &'a mut Backend,
chain_id: u64,
timestamp: U256,
block_number: u64,
hardfork: TempoHardfork,
) -> Self {
Self {
backend,
chain_id,
timestamp,
block_number,
gas_used: 0,
gas_refunded: 0,
transient: HashMap::new(),
beneficiary: Address::ZERO,
hardfork,
}
}
}
impl PrecompileStorageProvider for TempoStorageProvider<'_> {
fn spec(&self) -> TempoHardfork {
self.hardfork
}
fn chain_id(&self) -> u64 {
self.chain_id
}
fn timestamp(&self) -> U256 {
self.timestamp
}
fn block_number(&self) -> u64 {
self.block_number
}
fn set_code(&mut self, address: Address, code: Bytecode) -> Result<(), TempoPrecompileError> {
self.backend.insert_account_info(
address,
AccountInfo {
code_hash: code.hash_slow(),
code: Some(code),
nonce: 1,
..Default::default()
},
);
Ok(())
}
fn with_account_info(
&mut self,
address: Address,
f: &mut dyn FnMut(&AccountInfo),
) -> Result<(), TempoPrecompileError> {
if let Some(info) =
self.backend.basic(address).map_err(|e| TempoPrecompileError::Fatal(e.to_string()))?
{
f(&info);
Ok(())
} else {
Err(TempoPrecompileError::Fatal(format!("account '{address}' not found")))
}
}
fn sstore(
&mut self,
address: Address,
key: U256,
value: U256,
) -> Result<(), TempoPrecompileError> {
self.backend
.insert_account_storage(address, key, value)
.map_err(|e| TempoPrecompileError::Fatal(e.to_string()))
}
fn sload(&mut self, address: Address, key: U256) -> Result<U256, TempoPrecompileError> {
self.backend.storage(address, key).map_err(|e| TempoPrecompileError::Fatal(e.to_string()))
}
fn tstore(
&mut self,
address: Address,
key: U256,
value: U256,
) -> Result<(), TempoPrecompileError> {
self.transient.insert((address, key), value);
Ok(())
}
fn tload(&mut self, address: Address, key: U256) -> Result<U256, TempoPrecompileError> {
Ok(self.transient.get(&(address, key)).copied().unwrap_or(U256::ZERO))
}
fn emit_event(
&mut self,
_address: Address,
_event: alloy_primitives::LogData,
) -> Result<(), TempoPrecompileError> {
Ok(())
}
fn deduct_gas(&mut self, gas: u64) -> Result<(), TempoPrecompileError> {
self.gas_used = self.gas_used.saturating_add(gas);
Ok(())
}
fn gas_used(&self) -> u64 {
self.gas_used
}
fn gas_refunded(&self) -> i64 {
self.gas_refunded
}
fn refund_gas(&mut self, gas: i64) {
self.gas_refunded = self.gas_refunded.saturating_add(gas);
}
fn beneficiary(&self) -> Address {
self.beneficiary
}
fn is_static(&self) -> bool {
false
}
fn checkpoint(&mut self) -> JournalCheckpoint {
JournalCheckpoint { log_i: 0, journal_i: 0, selfdestructed_i: 0 }
}
fn checkpoint_commit(&mut self, _checkpoint: JournalCheckpoint) {}
fn checkpoint_revert(&mut self, _checkpoint: JournalCheckpoint) {}
}
/// Initialize Tempo precompiles and contracts using a storage provider.
///
/// This is the core initialization logic that sets up Tempo-specific precompiles,
/// fee tokens (PathUSD, AlphaUSD, BetaUSD, ThetaUSD), and standard contracts.
///
/// This function should be called during genesis setup when running in Tempo mode.
/// It uses the `StorageCtx` pattern to work with any storage backend that implements
/// `PrecompileStorageProvider`.
///
/// # Arguments
/// * `storage` - A mutable reference to a storage provider implementing `PrecompileStorageProvider`
/// * `admin` - The admin address that will have control over tokens and config
/// * `recipient` - The address that will receive minted tokens
///
/// Ref: <https://github.com/tempoxyz/tempo/blob/main/xtask/src/genesis_args.rs>
pub fn initialize_tempo_genesis(
storage: &mut impl PrecompileStorageProvider,
admin: Address,
recipient: Address,
) -> Result<(), TempoPrecompileError> {
StorageCtx::enter(storage, || -> Result<(), TempoPrecompileError> {
let mut ctx = StorageCtx;
// Set sentinel bytecode for precompile addresses
let sentinel = Bytecode::new_legacy(Bytes::from_static(&[0xef]));
for precompile in [
NONCE_PRECOMPILE_ADDRESS,
STABLECOIN_DEX_ADDRESS,
TIP20_FACTORY_ADDRESS,
TIP403_REGISTRY_ADDRESS,
TIP_FEE_MANAGER_ADDRESS,
VALIDATOR_CONFIG_ADDRESS,
VALIDATOR_CONFIG_V2_ADDRESS,
ACCOUNT_KEYCHAIN_ADDRESS,
SIGNATURE_VERIFIER_ADDRESS,
ADDRESS_REGISTRY_ADDRESS,
] {
ctx.set_code(precompile, sentinel.clone())?;
}
// Create PathUSD token: 0x20C0000000000000000000000000000000000000
let path_usd_token_address = create_and_mint_token(
address!("20C0000000000000000000000000000000000000"),
"PathUSD",
"PathUSD",
"USD",
Address::ZERO,
admin,
recipient,
U256::from(u64::MAX),
)?;
// Create AlphaUSD token: 0x20C0000000000000000000000000000000000001
let _alpha_usd_token_address = create_and_mint_token(
address!("20C0000000000000000000000000000000000001"),
"AlphaUSD",
"AlphaUSD",
"USD",
path_usd_token_address,
admin,
recipient,
U256::from(u64::MAX),
)?;
// Create BetaUSD token: 0x20C0000000000000000000000000000000000002
let _beta_usd_token_address = create_and_mint_token(
address!("20C0000000000000000000000000000000000002"),
"BetaUSD",
"BetaUSD",
"USD",
path_usd_token_address,
admin,
recipient,
U256::from(u64::MAX),
)?;
// Create ThetaUSD token: 0x20C0000000000000000000000000000000000003
let _theta_usd_token_address = create_and_mint_token(
address!("20C0000000000000000000000000000000000003"),
"ThetaUSD",
"ThetaUSD",
"USD",
path_usd_token_address,
admin,
recipient,
U256::from(u64::MAX),
)?;
// Initialize ValidatorConfig with admin as owner
ctx.sstore(
VALIDATOR_CONFIG_ADDRESS,
validator_config::slots::OWNER,
admin.into_word().into(),
)?;
// Set bytecode for standard contracts
ctx.set_code(
MULTICALL3_ADDRESS,
Bytecode::new_legacy(Bytes::from_static(&Multicall3::DEPLOYED_BYTECODE)),
)?;
ctx.set_code(
CREATEX_ADDRESS,
Bytecode::new_legacy(Bytes::from_static(&CreateX::DEPLOYED_BYTECODE)),
)?;
ctx.set_code(
SAFE_DEPLOYER_ADDRESS,
Bytecode::new_legacy(Bytes::from_static(&SafeDeployer::DEPLOYED_BYTECODE)),
)?;
ctx.set_code(
PERMIT2_ADDRESS,
Bytecode::new_legacy(Bytes::from_static(&Permit2::DEPLOYED_BYTECODE)),
)?;
ctx.set_code(
ARACHNID_CREATE2_FACTORY_ADDRESS,
Bytecode::new_legacy(ARACHNID_CREATE2_FACTORY_BYTECODE),
)?;
Ok(())
})?;
Ok(())
}
/// Helper function to create and mint a TIP20 token.
#[allow(clippy::too_many_arguments)]
fn create_and_mint_token(
address: Address,
symbol: &str,
name: &str,
currency: &str,
quote_token: Address,
admin: Address,
recipient: Address,
mint_amount: U256,
) -> Result<Address, TempoPrecompileError> {
let mut tip20_factory = TIP20Factory::new();
let token_address = tip20_factory.create_token_reserved_address(
address,
name,
symbol,
currency,
quote_token,
admin,
)?;
let mut token = TIP20Token::from_address(token_address)?;
token.grant_role_internal(admin, *ISSUER_ROLE)?;
token.mint(admin, ITIP20::mintCall { to: recipient, amount: mint_amount })?;
if admin != recipient {
token.mint(admin, ITIP20::mintCall { to: admin, amount: mint_amount })?;
}
Ok(token_address)
}