-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenesis_config.rs
More file actions
285 lines (257 loc) · 8.7 KB
/
genesis_config.rs
File metadata and controls
285 lines (257 loc) · 8.7 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
use alloy_primitives::Address;
use borsh::{BorshDeserialize, BorshSerialize};
use evolve_core::AccountId;
use evolve_fungible_asset::FungibleAssetMetadata;
use evolve_node::HasTokenAccountId;
use serde::Deserialize;
use std::collections::BTreeSet;
pub type FundedAccount = ([u8; 20], u128);
/// Evd genesis configuration loaded from JSON.
#[derive(Deserialize)]
pub struct EvdGenesisConfig {
pub token: TokenConfig,
pub minter_id: u128,
pub accounts: Vec<AccountConfig>,
}
#[derive(Deserialize)]
pub struct TokenConfig {
pub name: String,
pub symbol: String,
pub decimals: u8,
pub icon_url: String,
pub description: String,
}
#[derive(Deserialize)]
pub struct AccountConfig {
pub eth_address: String,
pub balance: u128,
}
/// Persisted genesis result (replaces testapp's GenesisAccounts for evd).
#[derive(Debug, Clone, Copy, BorshSerialize, BorshDeserialize)]
pub struct EvdGenesisResult {
pub token: AccountId,
pub scheduler: AccountId,
}
impl HasTokenAccountId for EvdGenesisResult {
fn token_account_id(&self) -> AccountId {
self.token
}
}
impl EvdGenesisConfig {
/// Load genesis config from a JSON file.
pub fn load(path: &str) -> Result<Self, String> {
let data = std::fs::read_to_string(path)
.map_err(|e| format!("failed to read genesis file '{}': {}", path, e))?;
let config: Self =
serde_json::from_str(&data).map_err(|e| format!("invalid genesis JSON: {}", e))?;
config.validate()?;
Ok(config)
}
fn validate(&self) -> Result<(), String> {
if self.accounts.is_empty() {
return Err("genesis config must have at least one account".into());
}
let mut seen = BTreeSet::new();
for (i, acc) in self.accounts.iter().enumerate() {
let addr = acc
.parse_address()
.map_err(|e| format!("account[{}]: {}", i, e))?;
if !seen.insert(addr.into_array()) {
return Err(format!(
"account[{i}]: duplicate eth address '{}'",
acc.eth_address
));
}
}
Ok(())
}
/// Return funded accounts as (eth_address, balance) tuples for genesis execution.
pub fn funded_accounts(&self) -> Result<Vec<FundedAccount>, String> {
self.accounts
.iter()
.filter(|acc| acc.balance > 0)
.map(|acc| {
let addr = acc.parse_address()?;
Ok((addr.into_array(), acc.balance))
})
.collect()
}
}
/// Load an optional genesis config and validate it.
pub fn load_genesis_config(path: Option<&str>) -> Result<Option<EvdGenesisConfig>, String> {
path.map(|p| {
tracing::info!("Loading genesis config from: {}", p);
EvdGenesisConfig::load(p)
})
.transpose()
}
impl TokenConfig {
pub fn to_metadata(&self) -> FungibleAssetMetadata {
FungibleAssetMetadata {
name: self.name.clone(),
symbol: self.symbol.clone(),
decimals: self.decimals,
icon_url: self.icon_url.clone(),
description: self.description.clone(),
}
}
}
impl AccountConfig {
pub fn parse_address(&self) -> Result<Address, String> {
self.eth_address
.parse::<Address>()
.map_err(|e| format!("invalid eth address '{}': {}", self.eth_address, e))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
fn temp_genesis_file(contents: &str) -> PathBuf {
let mut path = std::env::temp_dir();
let id = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
path.push(format!("evd-genesis-{}-{id}.json", std::process::id()));
std::fs::write(&path, contents).unwrap();
path
}
#[test]
fn load_fails_for_missing_file() {
let path = "/definitely/not/present/evd-genesis.json";
let err = EvdGenesisConfig::load(path)
.err()
.expect("missing file must fail");
assert!(err.contains("failed to read genesis file"));
}
#[test]
fn load_fails_for_empty_accounts() {
let path = temp_genesis_file(
r#"{
"token": {
"name": "Evolve",
"symbol": "EV",
"decimals": 6,
"icon_url": "https://example.com/icon.png",
"description": "token"
},
"minter_id": 100,
"accounts": []
}"#,
);
let err = EvdGenesisConfig::load(path.to_str().unwrap())
.err()
.expect("empty accounts fail");
assert!(err.contains("at least one account"));
let _ = std::fs::remove_file(path);
}
#[test]
fn load_fails_for_invalid_account_address() {
let path = temp_genesis_file(
r#"{
"token": {
"name": "Evolve",
"symbol": "EV",
"decimals": 6,
"icon_url": "https://example.com/icon.png",
"description": "token"
},
"minter_id": 100,
"accounts": [
{ "eth_address": "not-an-address", "balance": 1 }
]
}"#,
);
let err = EvdGenesisConfig::load(path.to_str().unwrap())
.err()
.expect("invalid address must fail");
assert!(err.contains("account[0]"));
assert!(err.contains("invalid eth address"));
let _ = std::fs::remove_file(path);
}
#[test]
fn load_succeeds_for_valid_config() {
let path = temp_genesis_file(
r#"{
"token": {
"name": "Evolve",
"symbol": "EV",
"decimals": 6,
"icon_url": "https://example.com/icon.png",
"description": "token"
},
"minter_id": 100,
"accounts": [
{
"eth_address": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
"balance": 1000
}
]
}"#,
);
let cfg = EvdGenesisConfig::load(path.to_str().unwrap()).expect("valid config should load");
assert_eq!(cfg.minter_id, 100);
assert_eq!(cfg.accounts.len(), 1);
assert_eq!(cfg.accounts[0].balance, 1000);
let _ = std::fs::remove_file(path);
}
#[test]
fn load_fails_for_duplicate_account_address() {
let path = temp_genesis_file(
r#"{
"token": {
"name": "Evolve",
"symbol": "EV",
"decimals": 6,
"icon_url": "https://example.com/icon.png",
"description": "token"
},
"minter_id": 100,
"accounts": [
{
"eth_address": "0x0000000000000000000000000000000000000001",
"balance": 1000
},
{
"eth_address": "0x0000000000000000000000000000000000000001",
"balance": 2000
}
]
}"#,
);
let err = EvdGenesisConfig::load(path.to_str().unwrap())
.err()
.expect("duplicate address must fail");
assert!(err.contains("duplicate eth address"));
let _ = std::fs::remove_file(path);
}
#[test]
fn parse_address_rejects_invalid_and_accepts_valid() {
let bad = AccountConfig {
eth_address: "bad-address".to_string(),
balance: 1,
};
assert!(bad.parse_address().is_err());
let good = AccountConfig {
eth_address: "0x0000000000000000000000000000000000000001".to_string(),
balance: 1,
};
assert!(good.parse_address().is_ok());
}
#[test]
fn token_to_metadata_maps_all_fields() {
let token = TokenConfig {
name: "Evolve".to_string(),
symbol: "EV".to_string(),
decimals: 6,
icon_url: "https://example.com/token.png".to_string(),
description: "Sample token".to_string(),
};
let metadata = token.to_metadata();
assert_eq!(metadata.name, "Evolve");
assert_eq!(metadata.symbol, "EV");
assert_eq!(metadata.decimals, 6);
assert_eq!(metadata.icon_url, "https://example.com/token.png");
assert_eq!(metadata.description, "Sample token");
}
}