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 collect_struct<T: StructCollect>(&self) -> String {76 self.collect(<T as StructCollect>::declaration());77 <T as StructCollect>::name()78 }79 pub fn finish(self) -> Vec<string> {80 let mut data = self.structs.into_inner().into_iter().collect::<Vec<_>>();81 data.sort_by_key(|(_, id)| Reverse(*id));82 data.into_iter().map(|(code, _)| code).collect()83 }84}8586pub trait StructCollect: 'static {87 88 fn name() -> String;89 90 fn declaration() -> String;91}9293pub trait SolidityTypeName: 'static {94 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;95 96 fn is_simple() -> bool;97 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;98 99 fn is_void() -> bool {100 false101 }102}103macro_rules! solidity_type_name {104 ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {105 $(106 impl SolidityTypeName for $ty {107 fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {108 write!(writer, $name)109 }110 fn is_simple() -> bool {111 $simple112 }113 fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {114 write!(writer, $default)115 }116 }117 )*118 };119}120121solidity_type_name! {122 uint8 => "uint8" true = "0",123 uint32 => "uint32" true = "0",124 uint64 => "uint64" true = "0",125 uint128 => "uint128" true = "0",126 uint256 => "uint256" true = "0",127 bytes4 => "bytes4" true = "bytes4(0)",128 address => "address" true = "0x0000000000000000000000000000000000000000",129 string => "string" false = "\"\"",130 bytes => "bytes" false = "hex\"\"",131 bool => "bool" true = "false",132}133impl SolidityTypeName for void {134 fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {135 Ok(())136 }137 fn is_simple() -> bool {138 true139 }140 fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {141 Ok(())142 }143 fn is_void() -> bool {144 true145 }146}147148mod sealed {149 150 151 152 153 pub trait CanBePlacedInVec {}154}155156impl sealed::CanBePlacedInVec for uint256 {}157impl sealed::CanBePlacedInVec for string {}158impl sealed::CanBePlacedInVec for address {}159impl sealed::CanBePlacedInVec for EthCrossAccount {}160161impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {162 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {163 T::solidity_name(writer, tc)?;164 write!(writer, "[]")165 }166 fn is_simple() -> bool {167 false168 }169 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {170 write!(writer, "new ")?;171 T::solidity_name(writer, tc)?;172 write!(writer, "[](0)")173 }174}175176impl SolidityTupleType for EthCrossAccount {177 fn names(tc: &TypeCollector) -> Vec<string> {178 let mut collected = Vec::with_capacity(Self::len());179 {180 let mut out = string::new();181 address::solidity_name(&mut out, tc).expect("no fmt error");182 collected.push(out);183 }184 {185 let mut out = string::new();186 uint256::solidity_name(&mut out, tc).expect("no fmt error");187 collected.push(out);188 }189 collected190 }191192 fn len() -> usize {193 2194 }195}196impl SolidityTypeName for EthCrossAccount {197 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {198 write!(writer, "{}", tc.collect_struct::<Self>())199 }200201 fn is_simple() -> bool {202 false203 }204205 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {206 write!(writer, "{}(", tc.collect_tuple::<Self>())?;207 address::solidity_default(writer, tc)?;208 write!(writer, ",")?;209 uint256::solidity_default(writer, tc)?;210 write!(writer, ")")211 }212}213214impl StructCollect for EthCrossAccount {215 fn name() -> String {216 "EthCrossAccount".into()217 }218219 fn declaration() -> String {220 let mut str = String::new();221 writeln!(str, "/// @dev Cross account struct").unwrap();222 writeln!(str, "struct {} {{", Self::name()).unwrap();223 writeln!(str, "\taddress eth;").unwrap();224 writeln!(str, "\tuint256 sub;").unwrap();225 writeln!(str, "}}").unwrap();226 str227 }228}229230pub trait SolidityTupleType {231 fn names(tc: &TypeCollector) -> Vec<String>;232 fn len() -> usize;233}234235macro_rules! count {236 () => (0usize);237 ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));238}239240macro_rules! impl_tuples {241 ($($ident:ident)+) => {242 impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}243 impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {244 fn names(tc: &TypeCollector) -> Vec<string> {245 let mut collected = Vec::with_capacity(Self::len());246 $({247 let mut out = string::new();248 $ident::solidity_name(&mut out, tc).expect("no fmt error");249 collected.push(out);250 })*;251 collected252 }253254 fn len() -> usize {255 count!($($ident)*)256 }257 }258 impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {259 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {260 write!(writer, "{}", tc.collect_tuple::<Self>())261 }262 fn is_simple() -> bool {263 false264 }265 #[allow(unused_assignments)]266 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {267 write!(writer, "{}(", tc.collect_tuple::<Self>())?;268 let mut first = true;269 $(270 if !first {271 write!(writer, ",")?;272 } else {273 first = false;274 }275 <$ident>::solidity_default(writer, tc)?;276 )*277 write!(writer, ")")278 }279 }280 };281}282283impl_tuples! {A}284impl_tuples! {A B}285impl_tuples! {A B C}286impl_tuples! {A B C D}287impl_tuples! {A B C D E}288impl_tuples! {A B C D E F}289impl_tuples! {A B C D E F G}290impl_tuples! {A B C D E F G H}291impl_tuples! {A B C D E F G H I}292impl_tuples! {A B C D E F G H I J}293294pub trait SolidityArguments {295 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;296 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result;297 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;298 fn is_empty(&self) -> bool {299 self.len() == 0300 }301 fn len(&self) -> usize;302}303304#[derive(Default)]305pub struct UnnamedArgument<T>(PhantomData<*const T>);306307impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {308 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {309 if !T::is_void() {310 T::solidity_name(writer, tc)?;311 if !T::is_simple() {312 write!(writer, " memory")?;313 }314 Ok(())315 } else {316 Ok(())317 }318 }319 fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {320 Ok(())321 }322 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {323 T::solidity_default(writer, tc)324 }325 fn len(&self) -> usize {326 if T::is_void() {327 0328 } else {329 1330 }331 }332}333334pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);335336impl<T> NamedArgument<T> {337 pub fn new(name: &'static str) -> Self {338 Self(name, Default::default())339 }340}341342impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {343 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {344 if !T::is_void() {345 T::solidity_name(writer, tc)?;346 if !T::is_simple() {347 write!(writer, " memory")?;348 }349 write!(writer, " {}", self.0)350 } else {351 Ok(())352 }353 }354 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {355 writeln!(writer, "\t{prefix}\t{};", self.0)356 }357 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {358 T::solidity_default(writer, tc)359 }360 fn len(&self) -> usize {361 if T::is_void() {362 0363 } else {364 1365 }366 }367}368369pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);370371impl<T> SolidityEventArgument<T> {372 pub fn new(indexed: bool, name: &'static str) -> Self {373 Self(indexed, name, Default::default())374 }375}376377impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {378 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {379 if !T::is_void() {380 T::solidity_name(writer, tc)?;381 if self.0 {382 write!(writer, " indexed")?;383 }384 write!(writer, " {}", self.1)385 } else {386 Ok(())387 }388 }389 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {390 writeln!(writer, "\t{prefix}\t{};", self.1)391 }392 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {393 T::solidity_default(writer, tc)394 }395 fn len(&self) -> usize {396 if T::is_void() {397 0398 } else {399 1400 }401 }402}403404impl SolidityArguments for () {405 fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {406 Ok(())407 }408 fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {409 Ok(())410 }411 fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {412 Ok(())413 }414 fn len(&self) -> usize {415 0416 }417}418419#[impl_for_tuples(1, 12)]420impl SolidityArguments for Tuple {421 for_tuples!( where #( Tuple: SolidityArguments ),* );422423 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {424 let mut first = true;425 for_tuples!( #(426 if !Tuple.is_empty() {427 if !first {428 write!(writer, ", ")?;429 }430 first = false;431 Tuple.solidity_name(writer, tc)?;432 }433 )* );434 Ok(())435 }436 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {437 for_tuples!( #(438 Tuple.solidity_get(prefix, writer)?;439 )* );440 Ok(())441 }442 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {443 if self.is_empty() {444 Ok(())445 } else if self.len() == 1 {446 for_tuples!( #(447 Tuple.solidity_default(writer, tc)?;448 )* );449 Ok(())450 } else {451 write!(writer, "(")?;452 let mut first = true;453 for_tuples!( #(454 if !Tuple.is_empty() {455 if !first {456 write!(writer, ", ")?;457 }458 first = false;459 Tuple.solidity_default(writer, tc)?;460 }461 )* );462 write!(writer, ")")?;463 Ok(())464 }465 }466 fn len(&self) -> usize {467 for_tuples!( #( Tuple.len() )+* )468 }469}470471pub trait SolidityFunctions {472 fn solidity_name(473 &self,474 is_impl: bool,475 writer: &mut impl fmt::Write,476 tc: &TypeCollector,477 ) -> fmt::Result;478}479480pub enum SolidityMutability {481 Pure,482 View,483 Mutable,484}485pub struct SolidityFunction<A, R> {486 pub docs: &'static [&'static str],487 pub selector_str: &'static str,488 pub selector: u32,489 pub hide: bool,490 pub name: &'static str,491 pub args: A,492 pub result: R,493 pub mutability: SolidityMutability,494 pub is_payable: bool,495}496impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {497 fn solidity_name(498 &self,499 is_impl: bool,500 writer: &mut impl fmt::Write,501 tc: &TypeCollector,502 ) -> fmt::Result {503 let hide_comment = self.hide.then(|| "// ").unwrap_or("");504 for doc in self.docs {505 writeln!(writer, "\t{hide_comment}///{}", doc)?;506 }507 writeln!(508 writer,509 "\t{hide_comment}/// @dev EVM selector for this function is: 0x{:0>8x},",510 self.selector511 )?;512 writeln!(513 writer,514 "\t{hide_comment}/// or in textual repr: {}",515 self.selector_str516 )?;517 write!(writer, "\t{hide_comment}function {}(", self.name)?;518 self.args.solidity_name(writer, tc)?;519 write!(writer, ")")?;520 if is_impl {521 write!(writer, " public")?;522 } else {523 write!(writer, " external")?;524 }525 match &self.mutability {526 SolidityMutability::Pure => write!(writer, " pure")?,527 SolidityMutability::View => write!(writer, " view")?,528 SolidityMutability::Mutable => {}529 }530 if self.is_payable {531 write!(writer, " payable")?;532 }533 if !self.result.is_empty() {534 write!(writer, " returns (")?;535 self.result.solidity_name(writer, tc)?;536 write!(writer, ")")?;537 }538 if is_impl {539 writeln!(writer, " {{")?;540 writeln!(writer, "\t{hide_comment}\trequire(false, stub_error);")?;541 self.args.solidity_get(hide_comment, writer)?;542 match &self.mutability {543 SolidityMutability::Pure => {}544 SolidityMutability::View => writeln!(writer, "\t{hide_comment}\tdummy;")?,545 SolidityMutability::Mutable => writeln!(writer, "\t{hide_comment}\tdummy = 0;")?,546 }547 if !self.result.is_empty() {548 write!(writer, "\t{hide_comment}\treturn ")?;549 self.result.solidity_default(writer, tc)?;550 writeln!(writer, ";")?;551 }552 writeln!(writer, "\t{hide_comment}}}")?;553 } else {554 writeln!(writer, ";")?;555 }556 if self.hide {557 writeln!(writer, "// FORMATTING: FORCE NEWLINE")?;558 }559 Ok(())560 }561}562563#[impl_for_tuples(0, 48)]564impl SolidityFunctions for Tuple {565 for_tuples!( where #( Tuple: SolidityFunctions ),* );566567 fn solidity_name(568 &self,569 is_impl: bool,570 writer: &mut impl fmt::Write,571 tc: &TypeCollector,572 ) -> fmt::Result {573 let mut first = false;574 for_tuples!( #(575 Tuple.solidity_name(is_impl, writer, tc)?;576 )* );577 Ok(())578 }579}580581pub struct SolidityInterface<F: SolidityFunctions> {582 pub docs: &'static [&'static str],583 pub selector: bytes4,584 pub name: &'static str,585 pub is: &'static [&'static str],586 pub functions: F,587}588589impl<F: SolidityFunctions> SolidityInterface<F> {590 pub fn format(591 &self,592 is_impl: bool,593 out: &mut impl fmt::Write,594 tc: &TypeCollector,595 ) -> fmt::Result {596 const ZERO_BYTES: [u8; 4] = [0; 4];597 for doc in self.docs {598 writeln!(out, "///{}", doc)?;599 }600 if self.selector != ZERO_BYTES {601 writeln!(602 out,603 "/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",604 u32::from_be_bytes(self.selector)605 )?;606 }607 if is_impl {608 write!(out, "contract ")?;609 } else {610 write!(out, "interface ")?;611 }612 write!(out, "{}", self.name)?;613 if !self.is.is_empty() {614 write!(out, " is")?;615 for (i, n) in self.is.iter().enumerate() {616 if i != 0 {617 write!(out, ",")?;618 }619 write!(out, " {}", n)?;620 }621 }622 writeln!(out, " {{")?;623 self.functions.solidity_name(is_impl, out, tc)?;624 writeln!(out, "}}")?;625 Ok(())626 }627}628629pub struct SolidityEvent<A> {630 pub name: &'static str,631 pub args: A,632}633634impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {635 fn solidity_name(636 &self,637 _is_impl: bool,638 writer: &mut impl fmt::Write,639 tc: &TypeCollector,640 ) -> fmt::Result {641 write!(writer, "\tevent {}(", self.name)?;642 self.args.solidity_name(writer, tc)?;643 writeln!(writer, ");")644 }645}