123456789101112131415161718192021222324#[cfg(not(feature = "std"))]25use alloc::{string::String, vec::Vec, collections::BTreeMap, format};26#[cfg(feature = "std")]27use std::collections::BTreeMap;28use core::{29 fmt::{self, Write},30 marker::PhantomData,31 cell::{Cell, RefCell},32 cmp::Reverse,33};34use impl_trait_for_tuples::impl_for_tuples;35use crate::types::*;3637#[derive(Default)]38pub struct TypeCollector {39 40 41 structs: RefCell<BTreeMap<string, usize>>,42 anonymous: RefCell<BTreeMap<Vec<string>, usize>>,43 id: Cell<usize>,44}45impl TypeCollector {46 pub fn new() -> Self {47 Self::default()48 }49 pub fn collect(&self, item: string) {50 let id = self.next_id();51 self.structs.borrow_mut().insert(item, id);52 }53 pub fn next_id(&self) -> usize {54 let v = self.id.get();55 self.id.set(v + 1);56 v57 }58 pub fn collect_tuple<T: SolidityTupleType>(&self) -> String {59 let names = T::names(self);60 if let Some(id) = self.anonymous.borrow().get(&names).cloned() {61 return format!("Tuple{}", id);62 }63 let id = self.next_id();64 let mut str = String::new();65 writeln!(str, "/// @dev anonymous struct").unwrap();66 writeln!(str, "struct Tuple{} {{", id).unwrap();67 for (i, name) in names.iter().enumerate() {68 writeln!(str, "\t{} field_{};", name, i).unwrap();69 }70 writeln!(str, "}}").unwrap();71 self.collect(str);72 self.anonymous.borrow_mut().insert(names, id);73 format!("Tuple{}", id)74 }75 pub fn finish(self) -> Vec<string> {76 let mut data = self.structs.into_inner().into_iter().collect::<Vec<_>>();77 data.sort_by_key(|(_, id)| Reverse(*id));78 data.into_iter().map(|(code, _)| code).collect()79 }80}8182pub trait SolidityTypeName: 'static {83 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;84 85 fn is_simple() -> bool;86 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;87 88 fn is_void() -> bool {89 false90 }91}92macro_rules! solidity_type_name {93 ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {94 $(95 impl SolidityTypeName for $ty {96 fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {97 write!(writer, $name)98 }99 fn is_simple() -> bool {100 $simple101 }102 fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {103 write!(writer, $default)104 }105 }106 )*107 };108}109110solidity_type_name! {111 uint8 => "uint8" true = "0",112 uint32 => "uint32" true = "0",113 uint64 => "uint64" true = "0",114 uint128 => "uint128" true = "0",115 uint256 => "uint256" true = "0",116 bytes4 => "bytes4" true = "bytes4(0)",117 address => "address" true = "0x0000000000000000000000000000000000000000",118 string => "string" false = "\"\"",119 bytes => "bytes" false = "hex\"\"",120 bool => "bool" true = "false",121}122impl SolidityTypeName for void {123 fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {124 Ok(())125 }126 fn is_simple() -> bool {127 true128 }129 fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {130 Ok(())131 }132 fn is_void() -> bool {133 true134 }135}136137mod sealed {138 139 140 141 142 pub trait CanBePlacedInVec {}143}144145impl sealed::CanBePlacedInVec for uint256 {}146impl sealed::CanBePlacedInVec for string {}147impl sealed::CanBePlacedInVec for address {}148149impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {150 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {151 T::solidity_name(writer, tc)?;152 write!(writer, "[]")153 }154 fn is_simple() -> bool {155 false156 }157 fn solidity_default(writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {158 write!(writer, "[]")159 }160}161162pub trait SolidityTupleType {163 fn names(tc: &TypeCollector) -> Vec<String>;164 fn len() -> usize;165}166167macro_rules! count {168 () => (0usize);169 ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));170}171172macro_rules! impl_tuples {173 ($($ident:ident)+) => {174 impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}175 impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {176 fn names(tc: &TypeCollector) -> Vec<string> {177 let mut collected = Vec::with_capacity(Self::len());178 $({179 let mut out = string::new();180 $ident::solidity_name(&mut out, tc).expect("no fmt error");181 collected.push(out);182 })*;183 collected184 }185186 fn len() -> usize {187 count!($($ident)*)188 }189 }190 impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {191 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {192 write!(writer, "{}", tc.collect_tuple::<Self>())193 }194 fn is_simple() -> bool {195 false196 }197 #[allow(unused_assignments)]198 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {199 write!(writer, "{}(", tc.collect_tuple::<Self>())?;200 let mut first = true;201 $(202 if !first {203 write!(writer, ",")?;204 } else {205 first = false;206 }207 <$ident>::solidity_default(writer, tc)?;208 )*209 write!(writer, ")")210 }211 }212 };213}214215impl_tuples! {A}216impl_tuples! {A B}217impl_tuples! {A B C}218impl_tuples! {A B C D}219impl_tuples! {A B C D E}220impl_tuples! {A B C D E F}221impl_tuples! {A B C D E F G}222impl_tuples! {A B C D E F G H}223impl_tuples! {A B C D E F G H I}224impl_tuples! {A B C D E F G H I J}225226pub trait SolidityArguments {227 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;228 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result;229 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;230 fn is_empty(&self) -> bool {231 self.len() == 0232 }233 fn len(&self) -> usize;234}235236#[derive(Default)]237pub struct UnnamedArgument<T>(PhantomData<*const T>);238239impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {240 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {241 if !T::is_void() {242 T::solidity_name(writer, tc)?;243 if !T::is_simple() {244 write!(writer, " memory")?;245 }246 Ok(())247 } else {248 Ok(())249 }250 }251 fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {252 Ok(())253 }254 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {255 T::solidity_default(writer, tc)256 }257 fn len(&self) -> usize {258 if T::is_void() {259 0260 } else {261 1262 }263 }264}265266pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);267268impl<T> NamedArgument<T> {269 pub fn new(name: &'static str) -> Self {270 Self(name, Default::default())271 }272}273274impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {275 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {276 if !T::is_void() {277 T::solidity_name(writer, tc)?;278 if !T::is_simple() {279 write!(writer, " memory")?;280 }281 write!(writer, " {}", self.0)282 } else {283 Ok(())284 }285 }286 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {287 writeln!(writer, "\t{prefix}\t{};", self.0)288 }289 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {290 T::solidity_default(writer, tc)291 }292 fn len(&self) -> usize {293 if T::is_void() {294 0295 } else {296 1297 }298 }299}300301pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);302303impl<T> SolidityEventArgument<T> {304 pub fn new(indexed: bool, name: &'static str) -> Self {305 Self(indexed, name, Default::default())306 }307}308309impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {310 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {311 if !T::is_void() {312 T::solidity_name(writer, tc)?;313 if self.0 {314 write!(writer, " indexed")?;315 }316 write!(writer, " {}", self.1)317 } else {318 Ok(())319 }320 }321 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {322 writeln!(writer, "\t{prefix}\t{};", self.1)323 }324 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {325 T::solidity_default(writer, tc)326 }327 fn len(&self) -> usize {328 if T::is_void() {329 0330 } else {331 1332 }333 }334}335336impl SolidityArguments for () {337 fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {338 Ok(())339 }340 fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {341 Ok(())342 }343 fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {344 Ok(())345 }346 fn len(&self) -> usize {347 0348 }349}350351#[impl_for_tuples(1, 12)]352impl SolidityArguments for Tuple {353 for_tuples!( where #( Tuple: SolidityArguments ),* );354355 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {356 let mut first = true;357 for_tuples!( #(358 if !Tuple.is_empty() {359 if !first {360 write!(writer, ", ")?;361 }362 first = false;363 Tuple.solidity_name(writer, tc)?;364 }365 )* );366 Ok(())367 }368 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {369 for_tuples!( #(370 Tuple.solidity_get(prefix, writer)?;371 )* );372 Ok(())373 }374 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {375 if self.is_empty() {376 Ok(())377 } else if self.len() == 1 {378 for_tuples!( #(379 Tuple.solidity_default(writer, tc)?;380 )* );381 Ok(())382 } else {383 write!(writer, "(")?;384 let mut first = true;385 for_tuples!( #(386 if !Tuple.is_empty() {387 if !first {388 write!(writer, ", ")?;389 }390 first = false;391 Tuple.solidity_default(writer, tc)?;392 }393 )* );394 write!(writer, ")")?;395 Ok(())396 }397 }398 fn len(&self) -> usize {399 for_tuples!( #( Tuple.len() )+* )400 }401}402403pub trait SolidityFunctions {404 fn solidity_name(405 &self,406 is_impl: bool,407 writer: &mut impl fmt::Write,408 tc: &TypeCollector,409 ) -> fmt::Result;410}411412pub enum SolidityMutability {413 Pure,414 View,415 Mutable,416}417pub struct SolidityFunction<A, R> {418 pub docs: &'static [&'static str],419 pub selector_str: &'static str,420 pub selector: u32,421 pub hide: bool,422 pub name: &'static str,423 pub args: A,424 pub result: R,425 pub mutability: SolidityMutability,426 pub is_payable: bool,427}428impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {429 fn solidity_name(430 &self,431 is_impl: bool,432 writer: &mut impl fmt::Write,433 tc: &TypeCollector,434 ) -> fmt::Result {435 let hide_comment = self.hide.then(|| "// ").unwrap_or("");436 for doc in self.docs {437 writeln!(writer, "\t{hide_comment}///{}", doc)?;438 }439 writeln!(440 writer,441 "\t{hide_comment}/// @dev EVM selector for this function is: 0x{:0>8x},",442 self.selector443 )?;444 writeln!(445 writer,446 "\t{hide_comment}/// or in textual repr: {}",447 self.selector_str448 )?;449 write!(writer, "\t{hide_comment}function {}(", self.name)?;450 self.args.solidity_name(writer, tc)?;451 write!(writer, ")")?;452 if is_impl {453 write!(writer, " public")?;454 } else {455 write!(writer, " external")?;456 }457 match &self.mutability {458 SolidityMutability::Pure => write!(writer, " pure")?,459 SolidityMutability::View => write!(writer, " view")?,460 SolidityMutability::Mutable => {}461 }462 if self.is_payable {463 write!(writer, " payable")?;464 }465 if !self.result.is_empty() {466 write!(writer, " returns (")?;467 self.result.solidity_name(writer, tc)?;468 write!(writer, ")")?;469 }470 if is_impl {471 writeln!(writer, " {{")?;472 writeln!(writer, "\t{hide_comment}\trequire(false, stub_error);")?;473 self.args.solidity_get(hide_comment, writer)?;474 match &self.mutability {475 SolidityMutability::Pure => {}476 SolidityMutability::View => writeln!(writer, "\t{hide_comment}\tdummy;")?,477 SolidityMutability::Mutable => writeln!(writer, "\t{hide_comment}\tdummy = 0;")?,478 }479 if !self.result.is_empty() {480 write!(writer, "\t{hide_comment}\treturn ")?;481 self.result.solidity_default(writer, tc)?;482 writeln!(writer, ";")?;483 }484 writeln!(writer, "\t{hide_comment}}}")?;485 } else {486 writeln!(writer, ";")?;487 }488 if self.hide {489 writeln!(writer, "// FORMATTING: FORCE NEWLINE")?;490 }491 Ok(())492 }493}494495#[impl_for_tuples(0, 48)]496impl SolidityFunctions for Tuple {497 for_tuples!( where #( Tuple: SolidityFunctions ),* );498499 fn solidity_name(500 &self,501 is_impl: bool,502 writer: &mut impl fmt::Write,503 tc: &TypeCollector,504 ) -> fmt::Result {505 let mut first = false;506 for_tuples!( #(507 Tuple.solidity_name(is_impl, writer, tc)?;508 )* );509 Ok(())510 }511}512513pub struct SolidityInterface<F: SolidityFunctions> {514 pub docs: &'static [&'static str],515 pub selector: bytes4,516 pub name: &'static str,517 pub is: &'static [&'static str],518 pub functions: F,519}520521impl<F: SolidityFunctions> SolidityInterface<F> {522 pub fn format(523 &self,524 is_impl: bool,525 out: &mut impl fmt::Write,526 tc: &TypeCollector,527 ) -> fmt::Result {528 const ZERO_BYTES: [u8; 4] = [0; 4];529 for doc in self.docs {530 writeln!(out, "///{}", doc)?;531 }532 if self.selector != ZERO_BYTES {533 writeln!(534 out,535 "/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",536 u32::from_be_bytes(self.selector)537 )?;538 }539 if is_impl {540 write!(out, "contract ")?;541 } else {542 write!(out, "interface ")?;543 }544 write!(out, "{}", self.name)?;545 if !self.is.is_empty() {546 write!(out, " is")?;547 for (i, n) in self.is.iter().enumerate() {548 if i != 0 {549 write!(out, ",")?;550 }551 write!(out, " {}", n)?;552 }553 }554 writeln!(out, " {{")?;555 self.functions.solidity_name(is_impl, out, tc)?;556 writeln!(out, "}}")?;557 Ok(())558 }559}560561pub struct SolidityEvent<A> {562 pub name: &'static str,563 pub args: A,564}565566impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {567 fn solidity_name(568 &self,569 _is_impl: bool,570 writer: &mut impl fmt::Write,571 tc: &TypeCollector,572 ) -> fmt::Result {573 write!(writer, "\tevent {}(", self.name)?;574 self.args.solidity_name(writer, tc)?;575 writeln!(writer, ");")576 }577}