Skip to main content

forge/cmd/
eip712.rs

1use alloy_primitives::{B256, keccak256};
2use clap::{Parser, ValueHint};
3use eyre::Result;
4use foundry_cli::{opts::BuildOpts, utils::LoadConfig};
5use foundry_common::{compile::ProjectCompiler, shell};
6use serde::Serialize;
7use solar::sema::{
8    Gcx, Hir,
9    hir::StructId,
10    ty::{Ty, TyKind},
11};
12use std::{
13    collections::BTreeMap,
14    fmt::{Display, Formatter, Result as FmtResult, Write},
15    ops::ControlFlow,
16    path::{Path, PathBuf},
17};
18
19foundry_config::impl_figment_convert!(Eip712Args, build);
20
21/// CLI arguments for `forge eip712`.
22#[derive(Clone, Debug, Parser)]
23pub struct Eip712Args {
24    /// The path to the file from which to read struct definitions.
25    #[arg(value_hint = ValueHint::FilePath, value_name = "PATH")]
26    pub target_path: PathBuf,
27
28    #[command(flatten)]
29    build: BuildOpts,
30}
31
32#[derive(Debug, Serialize)]
33struct Eip712Output {
34    path: String,
35    #[serde(rename = "type")]
36    ty: String,
37    hash: B256,
38}
39
40impl Display for Eip712Output {
41    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
42        writeln!(f, "{}:", self.path)?;
43        writeln!(f, " - type: {}", self.ty)?;
44        writeln!(f, " - hash: {}", self.hash)
45    }
46}
47
48impl Eip712Args {
49    pub fn run(self) -> Result<()> {
50        let config = self.build.load_config()?;
51        let project = config.solar_project()?;
52        let mut output = ProjectCompiler::new().files([self.target_path]).compile(&project)?;
53        let compiler = output.parser_mut().solc_mut().compiler_mut();
54        compiler.enter_mut(|compiler| -> Result<()> {
55            let Ok(ControlFlow::Continue(())) = compiler.lower_asts() else { return Ok(()) };
56            let gcx = compiler.gcx();
57            let resolver = Resolver::new(gcx);
58
59            let outputs = resolver
60                .struct_ids()
61                .filter_map(|id| {
62                    let resolved = resolver.resolve_struct_eip712(id)?;
63                    Some(Eip712Output {
64                        path: resolver.get_struct_path(id),
65                        hash: keccak256(resolved.as_bytes()),
66                        ty: resolved,
67                    })
68                })
69                .collect::<Vec<_>>();
70
71            if shell::is_json() {
72                sh_println!("{json}", json = serde_json::to_string_pretty(&outputs)?)?;
73            } else {
74                for output in &outputs {
75                    sh_eprintln!("{output}")?;
76                }
77            }
78
79            Ok(())
80        })?;
81
82        // `compiler.sess()` inside of `ProjectCompileOutput` is built with `with_buffer_emitter`.
83        let diags = compiler.sess().dcx.emitted_diagnostics().unwrap();
84        if compiler.sess().dcx.has_errors().is_err() {
85            eyre::bail!("{diags}");
86        }
87        let _ = sh_eprint!("{diags}");
88
89        Ok(())
90    }
91}
92
93/// Generates the EIP-712 `encodeType` string for a given struct.
94///
95/// Requires a reference to the source HIR.
96pub struct Resolver<'gcx> {
97    gcx: Gcx<'gcx>,
98}
99
100impl<'gcx> Resolver<'gcx> {
101    /// Constructs a new [`Resolver`] for the supplied [`Hir`] instance.
102    pub const fn new(gcx: Gcx<'gcx>) -> Self {
103        Self { gcx }
104    }
105
106    #[inline]
107    fn hir(&self) -> &'gcx Hir<'gcx> {
108        &self.gcx.hir
109    }
110
111    /// Returns the [`StructId`]s of every user-defined struct in source order.
112    pub fn struct_ids(&self) -> impl Iterator<Item = StructId> {
113        self.hir().strukt_ids()
114    }
115
116    /// Returns the path for a struct, with the format: `file.sol > MyContract > MyStruct`
117    pub fn get_struct_path(&self, id: StructId) -> String {
118        let strukt = self.hir().strukt(id).name.as_str();
119        match self.hir().strukt(id).contract {
120            Some(cid) => {
121                let full_name = self.gcx.contract_fully_qualified_name(cid).to_string();
122                let relevant = Path::new(&full_name)
123                    .file_name()
124                    .and_then(|s| s.to_str())
125                    .unwrap_or(&full_name);
126
127                if let Some((file, contract)) = relevant.rsplit_once(':') {
128                    format!("{file} > {contract} > {strukt}")
129                } else {
130                    format!("{relevant} > {strukt}")
131                }
132            }
133            None => strukt.to_string(),
134        }
135    }
136
137    /// Converts a given struct into its EIP-712 `encodeType` representation.
138    ///
139    /// Returns `None` if the struct, or any of its fields, contains constructs
140    /// not supported by EIP-712 (mappings, function types, errors, etc).
141    pub fn resolve_struct_eip712(&self, id: StructId) -> Option<String> {
142        let mut subtypes = BTreeMap::new();
143        subtypes.insert(self.hir().strukt(id).name.as_str().into(), id);
144        self.resolve_eip712_inner(id, &mut subtypes, true, None)
145    }
146
147    fn resolve_eip712_inner(
148        &self,
149        id: StructId,
150        subtypes: &mut BTreeMap<String, StructId>,
151        append_subtypes: bool,
152        rename: Option<&str>,
153    ) -> Option<String> {
154        let def = self.hir().strukt(id);
155        let mut result = format!("{}(", rename.unwrap_or(def.name.as_str()));
156
157        for (idx, field_id) in def.fields.iter().enumerate() {
158            let field = self.hir().variable(*field_id);
159            let ty = self.resolve_type(self.gcx.type_of_hir_ty(&field.ty), subtypes)?;
160
161            write!(result, "{ty} {name}", name = field.name?.as_str()).ok()?;
162
163            if idx < def.fields.len() - 1 {
164                result.push(',');
165            }
166        }
167
168        result.push(')');
169
170        if append_subtypes {
171            for (subtype_name, subtype_id) in
172                subtypes.iter().map(|(name, id)| (name.clone(), *id)).collect::<Vec<_>>()
173            {
174                if subtype_id == id {
175                    continue;
176                }
177                let encoded_subtype =
178                    self.resolve_eip712_inner(subtype_id, subtypes, false, Some(&subtype_name))?;
179
180                result.push_str(&encoded_subtype);
181            }
182        }
183
184        Some(result)
185    }
186
187    fn resolve_type(
188        &self,
189        ty: Ty<'gcx>,
190        subtypes: &mut BTreeMap<String, StructId>,
191    ) -> Option<String> {
192        let ty = ty.peel_refs();
193        match ty.kind {
194            TyKind::Elementary(elem_ty) => Some(elem_ty.to_abi_str().to_string()),
195            TyKind::Array(element_ty, size) => {
196                let inner_type = self.resolve_type(element_ty, subtypes)?;
197                let size = size.to_string();
198                Some(format!("{inner_type}[{size}]"))
199            }
200            TyKind::DynArray(element_ty) => {
201                let inner_type = self.resolve_type(element_ty, subtypes)?;
202                Some(format!("{inner_type}[]"))
203            }
204            TyKind::Udvt(ty, _) => self.resolve_type(ty, subtypes),
205            TyKind::Struct(id) => {
206                let def = self.hir().strukt(id);
207                let name = match subtypes.iter().find(|(_, cached_id)| id == **cached_id) {
208                    Some((name, _)) => name.clone(),
209                    None => {
210                        // Otherwise, assign new name
211                        let mut i = 0;
212                        let mut name = def.name.as_str().into();
213                        while subtypes.contains_key(&name) {
214                            i += 1;
215                            name = format!("{}_{i}", def.name.as_str());
216                        }
217
218                        subtypes.insert(name.clone(), id);
219
220                        // Recursively resolve fields to populate subtypes
221                        for &field_id in def.fields {
222                            let field_ty = self.gcx.type_of_item(field_id.into());
223                            self.resolve_type(field_ty, subtypes)?;
224                        }
225                        name
226                    }
227                };
228
229                Some(name)
230            }
231            // For now, map enums to `uint8`
232            TyKind::Enum(_) => Some("uint8".to_string()),
233            // For now, map contracts to `address`
234            TyKind::Contract(_) => Some("address".to_string()),
235            // EIP-712 doesn't support tuples (should use structs), functions, mappings, nor errors
236            _ => None,
237        }
238    }
239}