1use crate::{
4 Cheatcode, CheatcodesCore, Result,
5 Vm::*,
6 json::{
7 check_json_key_exists, parse_json, parse_json_coerce, parse_json_coerce_default,
8 parse_json_keys, resolve_type, split_value_key,
9 },
10};
11use alloy_dyn_abi::DynSolType;
12use alloy_sol_types::SolValue;
13use foundry_common::{fmt::StructDefinitions, fs};
14use foundry_config::fs_permissions::FsAccessKind;
15use serde_json::Value as JsonValue;
16use toml::Value as TomlValue;
17use toml_edit::{DocumentMut, Item, Table, TableLike};
18
19impl Cheatcode for keyExistsTomlCall {
20 fn apply_context_free(&self) -> Result {
21 let Self { toml, key } = self;
22 check_json_key_exists(&toml_to_json_string(toml)?, key)
23 }
24}
25
26impl Cheatcode for parseToml_0Call {
27 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
28 let Self { toml } = self;
29 parse_toml(
30 toml,
31 "$",
32 state.analysis.as_ref().and_then(|analysis| analysis.struct_defs().ok()),
33 )
34 }
35}
36
37impl Cheatcode for parseToml_1Call {
38 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
39 let Self { toml, key } = self;
40 parse_toml(
41 toml,
42 key,
43 state.analysis.as_ref().and_then(|analysis| analysis.struct_defs().ok()),
44 )
45 }
46}
47
48macro_rules! impl_parse_toml {
49 ($call:ident, $call_with_default:ident, $ty:expr) => {
50 impl Cheatcode for $call {
51 fn apply_context_free(&self) -> Result {
52 let Self { toml, key } = self;
53 parse_toml_coerce(toml, key, &$ty)
54 }
55 }
56
57 impl Cheatcode for $call_with_default {
58 fn apply_context_free(&self) -> Result {
59 let Self { toml, key, defaultValue } = self;
60 parse_toml_coerce_default(toml, key, &$ty, defaultValue)
61 }
62 }
63 };
64}
65
66impl_parse_toml!(parseTomlUint_0Call, parseTomlUint_1Call, DynSolType::Uint(256));
67impl_parse_toml!(
68 parseTomlUintArray_0Call,
69 parseTomlUintArray_1Call,
70 DynSolType::Array(Box::new(DynSolType::Uint(256)))
71);
72impl_parse_toml!(parseTomlInt_0Call, parseTomlInt_1Call, DynSolType::Int(256));
73impl_parse_toml!(
74 parseTomlIntArray_0Call,
75 parseTomlIntArray_1Call,
76 DynSolType::Array(Box::new(DynSolType::Int(256)))
77);
78impl_parse_toml!(parseTomlBool_0Call, parseTomlBool_1Call, DynSolType::Bool);
79impl_parse_toml!(
80 parseTomlBoolArray_0Call,
81 parseTomlBoolArray_1Call,
82 DynSolType::Array(Box::new(DynSolType::Bool))
83);
84impl_parse_toml!(parseTomlAddress_0Call, parseTomlAddress_1Call, DynSolType::Address);
85impl_parse_toml!(
86 parseTomlAddressArray_0Call,
87 parseTomlAddressArray_1Call,
88 DynSolType::Array(Box::new(DynSolType::Address))
89);
90impl_parse_toml!(parseTomlString_0Call, parseTomlString_1Call, DynSolType::String);
91impl_parse_toml!(
92 parseTomlStringArray_0Call,
93 parseTomlStringArray_1Call,
94 DynSolType::Array(Box::new(DynSolType::String))
95);
96impl_parse_toml!(parseTomlBytes_0Call, parseTomlBytes_1Call, DynSolType::Bytes);
97impl_parse_toml!(
98 parseTomlBytesArray_0Call,
99 parseTomlBytesArray_1Call,
100 DynSolType::Array(Box::new(DynSolType::Bytes))
101);
102impl_parse_toml!(parseTomlBytes32_0Call, parseTomlBytes32_1Call, DynSolType::FixedBytes(32));
103impl_parse_toml!(
104 parseTomlBytes32Array_0Call,
105 parseTomlBytes32Array_1Call,
106 DynSolType::Array(Box::new(DynSolType::FixedBytes(32)))
107);
108
109impl Cheatcode for parseTomlType_0Call {
110 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
111 let Self { toml, typeDescription } = self;
112 parse_toml_coerce(
113 toml,
114 "$",
115 &resolve_type(
116 typeDescription,
117 state.analysis.as_ref().and_then(|analysis| analysis.struct_defs().ok()),
118 )?,
119 )
120 .map(|v| v.abi_encode())
121 }
122}
123
124impl Cheatcode for parseTomlType_1Call {
125 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
126 let Self { toml, key, typeDescription } = self;
127 parse_toml_coerce(
128 toml,
129 key,
130 &resolve_type(
131 typeDescription,
132 state.analysis.as_ref().and_then(|analysis| analysis.struct_defs().ok()),
133 )?,
134 )
135 .map(|v| v.abi_encode())
136 }
137}
138
139impl Cheatcode for parseTomlTypeArrayCall {
140 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
141 let Self { toml, key, typeDescription } = self;
142 let ty = resolve_type(
143 typeDescription,
144 state.analysis.as_ref().and_then(|analysis| analysis.struct_defs().ok()),
145 )?;
146 parse_toml_coerce(toml, key, &DynSolType::Array(Box::new(ty))).map(|v| v.abi_encode())
147 }
148}
149
150impl Cheatcode for parseTomlKeysCall {
151 fn apply_context_free(&self) -> Result {
152 let Self { toml, key } = self;
153 parse_toml_keys(toml, key)
154 }
155}
156
157impl Cheatcode for writeToml_0Call {
158 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
159 let Self { json, path } = self;
160 let value =
161 serde_json::from_str(json).unwrap_or_else(|_| JsonValue::String(json.to_owned()));
162
163 let toml_string = format_json_to_toml(value)?;
164 super::fs::write_file(state, path.as_ref(), toml_string.as_bytes())
165 }
166}
167
168impl Cheatcode for writeToml_1Call {
169 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
170 let Self { json: value, path, valueKey } = self;
171
172 let data_path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
175 let mut document = if data_path.exists() {
176 parse_toml_document(&fs::locked_read_to_string(&data_path)?)?
177 } else {
178 DocumentMut::new()
179 };
180 upsert_toml_value(&mut document, value, valueKey)?;
181
182 super::fs::write_file(state, path.as_ref(), document.to_string().as_bytes())
183 }
184}
185
186fn parse_toml_str(toml: &str) -> Result<TomlValue> {
188 toml::from_str(toml).map_err(|e| fmt_err!("failed parsing TOML: {e}"))
189}
190
191fn parse_toml(toml: &str, key: &str, struct_defs: Option<&StructDefinitions>) -> Result {
193 parse_json(&toml_to_json_string(toml)?, key, struct_defs)
194}
195
196fn parse_toml_coerce(toml: &str, key: &str, ty: &DynSolType) -> Result {
198 parse_json_coerce(&toml_to_json_string(toml)?, key, ty)
199}
200
201fn parse_toml_coerce_default<T: SolValue>(
204 toml: &str,
205 key: &str,
206 ty: &DynSolType,
207 default: &T,
208) -> Result {
209 parse_json_coerce_default(&toml_to_json_string(toml)?, key, ty, default)
210}
211
212fn parse_toml_keys(toml: &str, key: &str) -> Result {
214 parse_json_keys(&toml_to_json_string(toml)?, key)
215}
216
217fn toml_to_json_string(toml: &str) -> Result<String> {
219 let toml = parse_toml_str(toml)?;
220 let json = toml_to_json_value(toml);
221 serde_json::to_string(&json).map_err(|e| fmt_err!("failed to serialize JSON: {e}"))
222}
223
224fn format_json_to_toml(json: JsonValue) -> Result<String> {
226 let toml = json_to_toml_value(json);
227 toml::to_string_pretty(&toml).map_err(|e| fmt_err!("failed to serialize TOML: {e}"))
228}
229
230pub(super) fn toml_to_json_value(toml: TomlValue) -> JsonValue {
232 match toml {
233 TomlValue::String(s) => match s.as_str() {
234 "null" => JsonValue::Null,
235 _ => JsonValue::String(s),
236 },
237 TomlValue::Integer(i) => JsonValue::Number(i.into()),
238 TomlValue::Float(f) => match serde_json::Number::from_f64(f) {
239 Some(n) => JsonValue::Number(n),
240 None => JsonValue::String(f.to_string()),
241 },
242 TomlValue::Boolean(b) => JsonValue::Bool(b),
243 TomlValue::Array(a) => JsonValue::Array(a.into_iter().map(toml_to_json_value).collect()),
244 TomlValue::Table(t) => {
245 JsonValue::Object(t.into_iter().map(|(k, v)| (k, toml_to_json_value(v))).collect())
246 }
247 TomlValue::Datetime(d) => JsonValue::String(d.to_string()),
248 }
249}
250
251fn json_to_toml_value(json: JsonValue) -> TomlValue {
253 match json {
254 JsonValue::String(s) => TomlValue::String(s),
255 JsonValue::Number(n) => match n.as_i64() {
256 Some(i) => TomlValue::Integer(i),
257 None if n.is_u64() => TomlValue::String(n.to_string()),
259 None => match n.as_f64() {
260 Some(f) => TomlValue::Float(f),
261 None => TomlValue::String(n.to_string()),
262 },
263 },
264 JsonValue::Bool(b) => TomlValue::Boolean(b),
265 JsonValue::Array(a) => TomlValue::Array(a.into_iter().map(json_to_toml_value).collect()),
266 JsonValue::Object(o) => {
267 TomlValue::Table(o.into_iter().map(|(k, v)| (k, json_to_toml_value(v))).collect())
268 }
269 JsonValue::Null => TomlValue::String("null".to_string()),
270 }
271}
272
273fn parse_toml_document(toml: &str) -> Result<DocumentMut> {
275 toml.parse().map_err(|e| fmt_err!("failed parsing TOML: {e}"))
276}
277
278fn upsert_toml_value(document: &mut DocumentMut, value: &str, key: &str) -> Result<()> {
284 let parts = split_value_key(key)?;
285
286 if let Some((key_to_insert, path_to_parent)) = parts.split_last() {
289 let mut current_level = document.as_item_mut();
290
291 for segment in path_to_parent {
292 let is_inline = current_level.is_inline_table();
293 let Some(table) = current_level.as_table_like_mut() else {
294 return Err(fmt_err!("path segment '{segment}' does not resolve to an object."));
295 };
296 if !table.contains_key(segment) {
297 let mut intermediary = Table::new();
298 intermediary.set_implicit(true);
299 insert_toml_item(table, is_inline, segment, Item::Table(intermediary));
300 }
301 current_level = table.get_mut(segment).unwrap();
302 }
303
304 let is_inline = current_level.is_inline_table();
305 let Some(parent) = current_level.as_table_like_mut() else {
306 return Err(fmt_err!("final destination is not an object, cannot insert key."));
307 };
308
309 let value =
310 serde_json::from_str(value).unwrap_or_else(|_| JsonValue::String(value.to_owned()));
311 let mut item = json_to_toml_item(value)?;
312
313 match parent.get_mut(key_to_insert) {
316 Some(existing) if !existing.is_none() => {
317 if existing.is_value() {
318 item = item.into_value().map_or_else(|item| item, Item::Value);
320 }
321 let shape_changed =
322 std::mem::discriminant(existing) != std::mem::discriminant(&item);
323 let header_prefix =
325 tables(existing).first().and_then(|table| table.decor().prefix()).cloned();
326 match (&*existing, &mut item) {
327 (Item::Value(old), Item::Value(new)) => {
328 *new.decor_mut() = old.decor().clone();
329 }
330 (old, new) => {
331 for (old, new) in tables(old).into_iter().zip(tables_mut(new)) {
332 *new.decor_mut() = old.decor().clone();
333 new.set_position(old.position());
334 if !old.is_implicit() {
335 new.set_implicit(false);
336 }
337 }
338 }
339 }
340 let new_is_value = item.is_value();
341 *existing = item;
342 if shape_changed {
343 let mut key = parent.key_mut(key_to_insert).expect("replaced key must exist");
344 let decor = key.leaf_decor_mut();
345 decor.clear();
346 if new_is_value {
347 decor.set_suffix(" ");
348 if let Some(prefix) = header_prefix {
349 decor.set_prefix(prefix);
350 }
351 }
352 }
353 }
354 _ => insert_toml_item(parent, is_inline, key_to_insert, item),
355 }
356 }
357
358 Ok(())
359}
360
361fn insert_toml_item(parent: &mut dyn TableLike, is_inline: bool, key: &str, mut item: Item) {
366 if is_inline {
367 let trailing =
368 parent.iter_mut().filter_map(|(_, item)| item.as_value_mut()).last().and_then(|last| {
369 let suffix = last.decor().suffix().cloned();
370 last.decor_mut().set_suffix("");
371 suffix
372 });
373 item = item.into_value().map_or_else(|item| item, Item::Value);
374 if let Some(value) = item.as_value_mut() {
375 value.decor_mut().clear();
376 if let Some(trailing) = trailing {
377 value.decor_mut().set_suffix(trailing);
378 }
379 }
380 }
381 parent.insert(key, item);
382}
383
384fn json_to_toml_item(value: JsonValue) -> Result<Item> {
386 const KEY: &str = "value";
387
388 let wrapper = JsonValue::Object([(KEY.to_string(), value)].into_iter().collect());
389 let mut item = parse_toml_document(&format_json_to_toml(wrapper)?)?
390 .remove(KEY)
391 .ok_or_else(|| fmt_err!("failed to serialize TOML value"))?;
392 reset_table_layout(&mut item);
394 Ok(item)
395}
396
397fn reset_table_layout(item: &mut Item) {
399 for table in tables_mut(item) {
400 table.set_position(None);
401 table.decor_mut().clear();
402 for (_, item) in table.iter_mut() {
403 reset_table_layout(item);
404 }
405 }
406}
407
408fn tables(item: &Item) -> Vec<&Table> {
410 match item {
411 Item::Table(table) => vec![table],
412 Item::ArrayOfTables(array) => array.iter().collect(),
413 _ => Vec::new(),
414 }
415}
416
417fn tables_mut(item: &mut Item) -> Vec<&mut Table> {
419 match item {
420 Item::Table(table) => vec![table],
421 Item::ArrayOfTables(array) => array.iter_mut().collect(),
422 _ => Vec::new(),
423 }
424}
425
426#[cfg(test)]
427mod tests {
428 use super::*;
429
430 const CONFIG: &str = r#"# Deployment config.
431
432owner = "0x000000000000000000000000000000000000dEaD" # multisig
433deployed_at = 2024-04-27T11:57:21Z
434max_supply = 0xffff_ffff
435salt = 'literal-string'
436
437# Mainnet settings.
438[mainnet]
439token = "0x0000000000000000000000000000000000000000" # filled by script
440limits = { daily = 1_000, weekly = 5_000 }
441
442# Base settings.
443[base]
444chain_id = 8453
445"#;
446
447 fn upsert(toml: &str, value: &str, key: &str) -> Result<String> {
448 let mut document = parse_toml_document(toml)?;
449 upsert_toml_value(&mut document, value, key)?;
450 Ok(document.to_string())
451 }
452
453 #[test]
454 fn write_toml_keeps_u64_above_i64_max() {
455 let toml = format_json_to_toml(serde_json::json!({ "amount": u64::MAX })).unwrap();
456 assert_eq!(toml, "amount = \"18446744073709551615\"\n");
457 let value = parse_toml_coerce(&toml, ".amount", &DynSolType::Uint(256)).unwrap();
458 assert_eq!(value, alloy_primitives::U256::from(u64::MAX).abi_encode());
459
460 assert_eq!(
461 upsert("", "9223372036854775809", ".amount").unwrap(),
462 "amount = \"9223372036854775809\"\n"
463 );
464 }
465
466 #[test]
467 fn upsert_toml_keeps_comment_above_key() {
468 let toml = "key1 = \"1\"\n\n# this is key2\nkey2 = \"2\"\n";
469 assert_eq!(
470 upsert(toml, "abcd", ".key2").unwrap(),
471 "key1 = \"1\"\n\n# this is key2\nkey2 = \"abcd\"\n"
472 );
473 }
474
475 #[test]
476 fn upsert_toml_replaces_only_the_value() {
477 let address = "0x000000000000000000000000000000000000bEEF";
478 assert_eq!(
479 upsert(CONFIG, address, ".mainnet.token").unwrap(),
480 CONFIG.replace(
481 r#"token = "0x0000000000000000000000000000000000000000""#,
482 &format!(r#"token = "{address}""#)
483 )
484 );
485 assert_eq!(
486 upsert(CONFIG, "2000", ".mainnet.limits.daily").unwrap(),
487 CONFIG.replace("daily = 1_000", "daily = 2000")
488 );
489 assert_eq!(
490 upsert(CONFIG, "{\"chain_id\": 10}", "base").unwrap(),
491 CONFIG.replace("chain_id = 8453", "chain_id = 10")
492 );
493 assert_eq!(
494 upsert(CONFIG, "{\"daily\": 2000}", ".mainnet.limits").unwrap(),
495 CONFIG.replace("daily = 1_000, weekly = 5_000", "daily = 2000")
496 );
497 }
498
499 #[test]
500 fn upsert_toml_adds_keys() {
501 assert_eq!(
502 upsert(CONFIG, "30000000", ".base.gas_limit").unwrap(),
503 format!("{CONFIG}gas_limit = 30000000\n")
504 );
505 assert_eq!(
506 upsert(CONFIG, "{\"block\": 123}", ".optimism.contracts").unwrap(),
507 format!("{CONFIG}\n[optimism.contracts]\nblock = 123\n")
508 );
509 assert_eq!(
510 upsert(CONFIG, "{\"monthly\": 9}", ".mainnet.limits.extra").unwrap(),
511 CONFIG.replace("weekly = 5_000 }", "weekly = 5_000, extra = { monthly = 9 } }")
512 );
513 }
514
515 #[test]
516 fn upsert_toml_preserves_inline_table_formatting_when_adding_keys() {
517 let toml = "limits = { daily = 1_000, weekly = 5_000 }\n";
518 assert_eq!(
519 upsert(toml, "9000", ".limits.monthly").unwrap(),
520 "limits = { daily = 1_000, weekly = 5_000, monthly = 9000 }\n"
521 );
522 assert_eq!(
523 upsert(toml, "9000", ".limits.extra.monthly").unwrap(),
524 "limits = { daily = 1_000, weekly = 5_000, extra = { monthly = 9000 } }\n"
525 );
526
527 let toml = "limits={daily=1_000,weekly = 5_000}\n";
528 assert_eq!(
529 upsert(toml, "9000", ".limits.monthly").unwrap(),
530 "limits={daily=1_000,weekly = 5_000, monthly = 9000}\n"
531 );
532
533 let toml = "limits = {\n # Keep this cap conservative.\n daily = 1_000,\n weekly = 5_000,\n}\n";
534 assert_eq!(
535 upsert(toml, "9000", ".limits.monthly").unwrap(),
536 "limits = {\n # Keep this cap conservative.\n daily = 1_000,\n weekly = 5_000, monthly = 9000,\n}\n"
537 );
538 }
539
540 #[test]
541 fn upsert_toml_replaces_arrays_of_tables_in_place() {
542 let toml = "# Production RPC endpoints.\n[[rpc]]\nurl = \"old\"\n";
543 assert_eq!(
544 upsert(toml, r#"[{"url":"new"}]"#, ".rpc").unwrap(),
545 "# Production RPC endpoints.\n[[rpc]]\nurl = \"new\"\n"
546 );
547 }
548
549 #[test]
550 fn upsert_toml_keeps_comments_when_the_item_shape_changes() {
551 let toml = "# Deployment settings.\n[deployment] # maintained by the deploy script\nchain_id = 1\n";
552 assert_eq!(
553 upsert(toml, "disabled", ".deployment").unwrap(),
554 "# Deployment settings.\ndeployment = \"disabled\"\n"
555 );
556
557 let toml = "# Production RPC endpoint.\n[rpc]\nurl = \"a\"\n";
558 assert_eq!(
559 upsert(toml, r#"[{"url":"a"},{"url":"b"}]"#, ".rpc").unwrap(),
560 "# Production RPC endpoint.\n[[rpc]]\nurl = \"a\"\n\n[[rpc]]\nurl = \"b\"\n"
561 );
562
563 let toml = "# Production RPC endpoints.\nrpc = []\n";
564 assert_eq!(
565 upsert(toml, r#"[{"url":"a"},{"url":"b"}]"#, ".rpc").unwrap(),
566 "# Production RPC endpoints.\nrpc = [{ url = \"a\" }, { url = \"b\" }]\n"
567 );
568 }
569
570 #[test]
571 fn upsert_toml_formats_new_values_like_write_toml() {
572 let value = r#"{"list": ["0x01", "0x02"], "empty": {}, "nested": {"a": {"b": 1}}}"#;
573 let expected = format_json_to_toml(
574 serde_json::json!({ "new": serde_json::from_str::<JsonValue>(value).unwrap() }),
575 )
576 .unwrap();
577 assert_eq!(upsert("", value, ".new").unwrap(), expected);
578 }
579
580 #[test]
581 fn upsert_toml_errors() {
582 assert_eq!(
583 upsert(CONFIG, "1", ".owner.x").unwrap_err().to_string(),
584 "final destination is not an object, cannot insert key."
585 );
586 assert_eq!(
587 upsert(CONFIG, "1", ".owner.x.y").unwrap_err().to_string(),
588 "path segment 'x' does not resolve to an object."
589 );
590 assert_eq!(
591 upsert(CONFIG, "1", "$.").unwrap_err().to_string(),
592 "'valueKey' cannot be empty or just '$'"
593 );
594 }
595}