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 FunctionSelectorMaker {39 pub name: string,40 pub args: Vec<fn() -> string>,41}4243#[derive(Default)]44pub struct TypeCollector {45 46 47 structs: RefCell<BTreeMap<string, usize>>,48 anonymous: RefCell<BTreeMap<Vec<string>, usize>>,49 id: Cell<usize>,50}51impl TypeCollector {52 pub fn new() -> Self {53 Self::default()54 }55 pub fn collect(&self, item: string) {56 let id = self.next_id();57 self.structs.borrow_mut().insert(item, id);58 }59 pub fn next_id(&self) -> usize {60 let v = self.id.get();61 self.id.set(v + 1);62 v63 }64 pub fn collect_tuple<T: SolidityTupleType>(&self) -> String {65 let names = T::names(self);66 if let Some(id) = self.anonymous.borrow().get(&names).cloned() {67 return format!("Tuple{}", id);68 }69 let id = self.next_id();70 let mut str = String::new();71 writeln!(str, "/// @dev anonymous struct").unwrap();72 writeln!(str, "struct Tuple{} {{", id).unwrap();73 for (i, name) in names.iter().enumerate() {74 writeln!(str, "\t{} field_{};", name, i).unwrap();75 }76 writeln!(str, "}}").unwrap();77 self.collect(str);78 self.anonymous.borrow_mut().insert(names, id);79 format!("Tuple{}", id)80 }81 pub fn collect_struct<T: StructCollect>(&self) -> String {82 self.collect(<T as StructCollect>::declaration());83 <T as StructCollect>::name()84 }85 pub fn finish(self) -> Vec<string> {86 let mut data = self.structs.into_inner().into_iter().collect::<Vec<_>>();87 data.sort_by_key(|(_, id)| Reverse(*id));88 data.into_iter().map(|(code, _)| code).collect()89 }90}9192pub trait StructCollect: 'static {93 94 fn name() -> String;95 96 fn declaration() -> String;97}9899pub trait SolidityTypeName: 'static {100 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;101 102 fn is_simple() -> bool;103 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;104 105 fn is_void() -> bool {106 false107 }108}109macro_rules! solidity_type_name {110 ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {111 $(112 impl SolidityTypeName for $ty {113 fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {114 write!(writer, $name)115 }116 fn is_simple() -> bool {117 $simple118 }119 fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {120 write!(writer, $default)121 }122 }123 )*124 };125}126127solidity_type_name! {128 uint8 => "uint8" true = "0",129 uint32 => "uint32" true = "0",130 uint64 => "uint64" true = "0",131 uint128 => "uint128" true = "0",132 uint256 => "uint256" true = "0",133 bytes4 => "bytes4" true = "bytes4(0)",134 address => "address" true = "0x0000000000000000000000000000000000000000",135 string => "string" false = "\"\"",136 bytes => "bytes" false = "hex\"\"",137 bool => "bool" true = "false",138}139impl SolidityTypeName for void {140 fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {141 Ok(())142 }143 fn is_simple() -> bool {144 true145 }146 fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {147 Ok(())148 }149 fn is_void() -> bool {150 true151 }152}153154mod sealed {155 156 157 158 159 pub trait CanBePlacedInVec {}160}161162impl sealed::CanBePlacedInVec for uint256 {}163impl sealed::CanBePlacedInVec for string {}164impl sealed::CanBePlacedInVec for address {}165impl sealed::CanBePlacedInVec for EthCrossAccount {}166167impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {168 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {169 T::solidity_name(writer, tc)?;170 write!(writer, "[]")171 }172 fn is_simple() -> bool {173 false174 }175 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {176 write!(writer, "new ")?;177 T::solidity_name(writer, tc)?;178 write!(writer, "[](0)")179 }180}181182impl SolidityTupleType for EthCrossAccount {183 fn names(tc: &TypeCollector) -> Vec<string> {184 let mut collected = Vec::with_capacity(Self::len());185 {186 let mut out = string::new();187 address::solidity_name(&mut out, tc).expect("no fmt error");188 collected.push(out);189 }190 {191 let mut out = string::new();192 uint256::solidity_name(&mut out, tc).expect("no fmt error");193 collected.push(out);194 }195 collected196 }197198 fn len() -> usize {199 2200 }201}202impl SolidityTypeName for EthCrossAccount {203 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {204 write!(writer, "{}", tc.collect_struct::<Self>())205 }206207 fn is_simple() -> bool {208 false209 }210211 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {212 write!(writer, "{}(", tc.collect_tuple::<Self>())?;213 address::solidity_default(writer, tc)?;214 write!(writer, ",")?;215 uint256::solidity_default(writer, tc)?;216 write!(writer, ")")217 }218}219220impl StructCollect for EthCrossAccount {221 fn name() -> String {222 "EthCrossAccount".into()223 }224225 fn declaration() -> String {226 let mut str = String::new();227 writeln!(str, "/// @dev Cross account struct").unwrap();228 writeln!(str, "struct {} {{", Self::name()).unwrap();229 writeln!(str, "\taddress eth;").unwrap();230 writeln!(str, "\tuint256 sub;").unwrap();231 writeln!(str, "}}").unwrap();232 str233 }234}235236pub trait SolidityTupleType {237 fn names(tc: &TypeCollector) -> Vec<String>;238 fn len() -> usize;239}240241macro_rules! count {242 () => (0usize);243 ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));244}245246macro_rules! impl_tuples {247 ($($ident:ident)+) => {248 impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}249 impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {250 fn names(tc: &TypeCollector) -> Vec<string> {251 let mut collected = Vec::with_capacity(Self::len());252 $({253 let mut out = string::new();254 $ident::solidity_name(&mut out, tc).expect("no fmt error");255 collected.push(out);256 })*;257 collected258 }259260 fn len() -> usize {261 count!($($ident)*)262 }263 }264 impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {265 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {266 write!(writer, "{}", tc.collect_tuple::<Self>())267 }268 fn is_simple() -> bool {269 false270 }271 #[allow(unused_assignments)]272 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {273 write!(writer, "{}(", tc.collect_tuple::<Self>())?;274 let mut first = true;275 $(276 if !first {277 write!(writer, ",")?;278 } else {279 first = false;280 }281 <$ident>::solidity_default(writer, tc)?;282 )*283 write!(writer, ")")284 }285 }286 };287}288289impl_tuples! {A}290impl_tuples! {A B}291impl_tuples! {A B C}292impl_tuples! {A B C D}293impl_tuples! {A B C D E}294impl_tuples! {A B C D E F}295impl_tuples! {A B C D E F G}296impl_tuples! {A B C D E F G H}297impl_tuples! {A B C D E F G H I}298impl_tuples! {A B C D E F G H I J}299300pub trait SolidityArguments {301 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;302 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result;303 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;304 fn is_empty(&self) -> bool {305 self.len() == 0306 }307 fn len(&self) -> usize;308}309310#[derive(Default)]311pub struct UnnamedArgument<T>(PhantomData<*const T>);312313impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {314 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {315 if !T::is_void() {316 T::solidity_name(writer, tc)?;317 if !T::is_simple() {318 write!(writer, " memory")?;319 }320 Ok(())321 } else {322 Ok(())323 }324 }325 fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {326 Ok(())327 }328 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {329 T::solidity_default(writer, tc)330 }331 fn len(&self) -> usize {332 if T::is_void() {333 0334 } else {335 1336 }337 }338}339340pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);341342impl<T> NamedArgument<T> {343 pub fn new(name: &'static str) -> Self {344 Self(name, Default::default())345 }346}347348impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {349 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {350 if !T::is_void() {351 T::solidity_name(writer, tc)?;352 if !T::is_simple() {353 write!(writer, " memory")?;354 }355 write!(writer, " {}", self.0)356 } else {357 Ok(())358 }359 }360 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {361 writeln!(writer, "\t{prefix}\t{};", self.0)362 }363 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {364 T::solidity_default(writer, tc)365 }366 fn len(&self) -> usize {367 if T::is_void() {368 0369 } else {370 1371 }372 }373}374375pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);376377impl<T> SolidityEventArgument<T> {378 pub fn new(indexed: bool, name: &'static str) -> Self {379 Self(indexed, name, Default::default())380 }381}382383impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {384 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {385 if !T::is_void() {386 T::solidity_name(writer, tc)?;387 if self.0 {388 write!(writer, " indexed")?;389 }390 write!(writer, " {}", self.1)391 } else {392 Ok(())393 }394 }395 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {396 writeln!(writer, "\t{prefix}\t{};", self.1)397 }398 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {399 T::solidity_default(writer, tc)400 }401 fn len(&self) -> usize {402 if T::is_void() {403 0404 } else {405 1406 }407 }408}409410impl SolidityArguments for () {411 fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {412 Ok(())413 }414 fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {415 Ok(())416 }417 fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {418 Ok(())419 }420 fn len(&self) -> usize {421 0422 }423}424425#[impl_for_tuples(1, 12)]426impl SolidityArguments for Tuple {427 for_tuples!( where #( Tuple: SolidityArguments ),* );428429 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {430 let mut first = true;431 for_tuples!( #(432 if !Tuple.is_empty() {433 if !first {434 write!(writer, ", ")?;435 }436 first = false;437 Tuple.solidity_name(writer, tc)?;438 }439 )* );440 Ok(())441 }442 fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {443 for_tuples!( #(444 Tuple.solidity_get(prefix, writer)?;445 )* );446 Ok(())447 }448 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {449 if self.is_empty() {450 Ok(())451 } else if self.len() == 1 {452 for_tuples!( #(453 Tuple.solidity_default(writer, tc)?;454 )* );455 Ok(())456 } else {457 write!(writer, "(")?;458 let mut first = true;459 for_tuples!( #(460 if !Tuple.is_empty() {461 if !first {462 write!(writer, ", ")?;463 }464 first = false;465 Tuple.solidity_default(writer, tc)?;466 }467 )* );468 write!(writer, ")")?;469 Ok(())470 }471 }472 fn len(&self) -> usize {473 for_tuples!( #( Tuple.len() )+* )474 }475}476477pub trait SolidityFunctions {478 fn solidity_name(479 &self,480 is_impl: bool,481 writer: &mut impl fmt::Write,482 tc: &TypeCollector,483 ) -> fmt::Result;484}485486pub enum SolidityMutability {487 Pure,488 View,489 Mutable,490}491492493494495496497498499500501502503504pub struct SolidityFunction<A, R> {505 pub docs: &'static [&'static str],506 pub selector_str: &'static str,507 pub selector: u32,508 pub hide: bool,509 pub custom_signature: &'static str,510 pub name: &'static str,511 pub args: A,512 pub result: R,513 pub mutability: SolidityMutability,514 pub is_payable: bool,515}516impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {517 fn solidity_name(518 &self,519 is_impl: bool,520 writer: &mut impl fmt::Write,521 tc: &TypeCollector,522 ) -> fmt::Result {523 let hide_comment = self.hide.then(|| "// ").unwrap_or("");524 for doc in self.docs {525 writeln!(writer, "\t{hide_comment}///{}", doc)?;526 }527 writeln!(528 writer,529 "\t{hide_comment}/// @dev EVM selector for this function is: 0x{:0>8x},",530 self.selector531 )?;532 writeln!(533 writer,534 "\t{hide_comment}/// or in textual repr: {}",535 self.custom_signature536 )?;537 write!(writer, "\t{hide_comment}function {}(", self.name)?;538 self.args.solidity_name(writer, tc)?;539 write!(writer, ")")?;540 if is_impl {541 write!(writer, " public")?;542 } else {543 write!(writer, " external")?;544 }545 match &self.mutability {546 SolidityMutability::Pure => write!(writer, " pure")?,547 SolidityMutability::View => write!(writer, " view")?,548 SolidityMutability::Mutable => {}549 }550 if self.is_payable {551 write!(writer, " payable")?;552 }553 if !self.result.is_empty() {554 write!(writer, " returns (")?;555 self.result.solidity_name(writer, tc)?;556 write!(writer, ")")?;557 }558 if is_impl {559 writeln!(writer, " {{")?;560 writeln!(writer, "\t{hide_comment}\trequire(false, stub_error);")?;561 self.args.solidity_get(hide_comment, writer)?;562 match &self.mutability {563 SolidityMutability::Pure => {}564 SolidityMutability::View => writeln!(writer, "\t{hide_comment}\tdummy;")?,565 SolidityMutability::Mutable => writeln!(writer, "\t{hide_comment}\tdummy = 0;")?,566 }567 if !self.result.is_empty() {568 write!(writer, "\t{hide_comment}\treturn ")?;569 self.result.solidity_default(writer, tc)?;570 writeln!(writer, ";")?;571 }572 writeln!(writer, "\t{hide_comment}}}")?;573 } else {574 writeln!(writer, ";")?;575 }576 if self.hide {577 writeln!(writer, "// FORMATTING: FORCE NEWLINE")?;578 }579 Ok(())580 }581}582583#[impl_for_tuples(0, 48)]584impl SolidityFunctions for Tuple {585 for_tuples!( where #( Tuple: SolidityFunctions ),* );586587 fn solidity_name(588 &self,589 is_impl: bool,590 writer: &mut impl fmt::Write,591 tc: &TypeCollector,592 ) -> fmt::Result {593 let mut first = false;594 for_tuples!( #(595 Tuple.solidity_name(is_impl, writer, tc)?;596 )* );597 Ok(())598 }599}600601pub struct SolidityInterface<F: SolidityFunctions> {602 pub docs: &'static [&'static str],603 pub selector: bytes4,604 pub name: &'static str,605 pub is: &'static [&'static str],606 pub functions: F,607}608609impl<F: SolidityFunctions> SolidityInterface<F> {610 pub fn format(611 &self,612 is_impl: bool,613 out: &mut impl fmt::Write,614 tc: &TypeCollector,615 ) -> fmt::Result {616 const ZERO_BYTES: [u8; 4] = [0; 4];617 for doc in self.docs {618 writeln!(out, "///{}", doc)?;619 }620 if self.selector != ZERO_BYTES {621 writeln!(622 out,623 "/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",624 u32::from_be_bytes(self.selector)625 )?;626 }627 if is_impl {628 write!(out, "contract ")?;629 } else {630 write!(out, "interface ")?;631 }632 write!(out, "{}", self.name)?;633 if !self.is.is_empty() {634 write!(out, " is")?;635 for (i, n) in self.is.iter().enumerate() {636 if i != 0 {637 write!(out, ",")?;638 }639 write!(out, " {}", n)?;640 }641 }642 writeln!(out, " {{")?;643 self.functions.solidity_name(is_impl, out, tc)?;644 writeln!(out, "}}")?;645 Ok(())646 }647}648649pub struct SolidityEvent<A> {650 pub name: &'static str,651 pub args: A,652}653654impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {655 fn solidity_name(656 &self,657 _is_impl: bool,658 writer: &mut impl fmt::Write,659 tc: &TypeCollector,660 ) -> fmt::Result {661 write!(writer, "\tevent {}(", self.name)?;662 self.args.solidity_name(writer, tc)?;663 writeln!(writer, ");")664 }665}