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 true196 $(197 && <$ident>::is_simple()198 )*199 }200 #[allow(unused_assignments)]201 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {202 write!(writer, "{}(", tc.collect_tuple::<Self>())?;203 let mut first = true;204 $(205 if !first {206 write!(writer, ",")?;207 } else {208 first = false;209 }210 <$ident>::solidity_default(writer, tc)?;211 )*212 write!(writer, ")")213 }214 }215 };216}217218impl_tuples! {A}219impl_tuples! {A B}220impl_tuples! {A B C}221impl_tuples! {A B C D}222impl_tuples! {A B C D E}223impl_tuples! {A B C D E F}224impl_tuples! {A B C D E F G}225impl_tuples! {A B C D E F G H}226impl_tuples! {A B C D E F G H I}227impl_tuples! {A B C D E F G H I J}228229pub trait SolidityArguments {230 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;231 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;232 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;233 fn is_empty(&self) -> bool {234 self.len() == 0235 }236 fn len(&self) -> usize;237}238239#[derive(Default)]240pub struct UnnamedArgument<T>(PhantomData<*const T>);241242impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {243 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {244 if !T::is_void() {245 T::solidity_name(writer, tc)?;246 if !T::is_simple() {247 write!(writer, " memory")?;248 }249 Ok(())250 } else {251 Ok(())252 }253 }254 fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {255 Ok(())256 }257 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {258 T::solidity_default(writer, tc)259 }260 fn len(&self) -> usize {261 if T::is_void() {262 0263 } else {264 1265 }266 }267}268269pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);270271impl<T> NamedArgument<T> {272 pub fn new(name: &'static str) -> Self {273 Self(name, Default::default())274 }275}276277impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {278 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {279 if !T::is_void() {280 T::solidity_name(writer, tc)?;281 if !T::is_simple() {282 write!(writer, " memory")?;283 }284 write!(writer, " {}", self.0)285 } else {286 Ok(())287 }288 }289 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {290 writeln!(writer, "\t\t{};", self.0)291 }292 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {293 T::solidity_default(writer, tc)294 }295 fn len(&self) -> usize {296 if T::is_void() {297 0298 } else {299 1300 }301 }302}303304pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);305306impl<T> SolidityEventArgument<T> {307 pub fn new(indexed: bool, name: &'static str) -> Self {308 Self(indexed, name, Default::default())309 }310}311312impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {313 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {314 if !T::is_void() {315 T::solidity_name(writer, tc)?;316 if self.0 {317 write!(writer, " indexed")?;318 }319 write!(writer, " {}", self.1)320 } else {321 Ok(())322 }323 }324 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {325 writeln!(writer, "\t\t{};", self.1)326 }327 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {328 T::solidity_default(writer, tc)329 }330 fn len(&self) -> usize {331 if T::is_void() {332 0333 } else {334 1335 }336 }337}338339impl SolidityArguments for () {340 fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {341 Ok(())342 }343 fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {344 Ok(())345 }346 fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {347 Ok(())348 }349 fn len(&self) -> usize {350 0351 }352}353354#[impl_for_tuples(1, 12)]355impl SolidityArguments for Tuple {356 for_tuples!( where #( Tuple: SolidityArguments ),* );357358 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {359 let mut first = true;360 for_tuples!( #(361 if !Tuple.is_empty() {362 if !first {363 write!(writer, ", ")?;364 }365 first = false;366 Tuple.solidity_name(writer, tc)?;367 }368 )* );369 Ok(())370 }371 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {372 for_tuples!( #(373 Tuple.solidity_get(writer)?;374 )* );375 Ok(())376 }377 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {378 if self.is_empty() {379 Ok(())380 } else if self.len() == 1 {381 for_tuples!( #(382 Tuple.solidity_default(writer, tc)?;383 )* );384 Ok(())385 } else {386 write!(writer, "(")?;387 let mut first = true;388 for_tuples!( #(389 if !Tuple.is_empty() {390 if !first {391 write!(writer, ", ")?;392 }393 first = false;394 Tuple.solidity_default(writer, tc)?;395 }396 )* );397 write!(writer, ")")?;398 Ok(())399 }400 }401 fn len(&self) -> usize {402 for_tuples!( #( Tuple.len() )+* )403 }404}405406pub trait SolidityFunctions {407 fn solidity_name(408 &self,409 is_impl: bool,410 writer: &mut impl fmt::Write,411 tc: &TypeCollector,412 ) -> fmt::Result;413}414415pub enum SolidityMutability {416 Pure,417 View,418 Mutable,419}420pub struct SolidityFunction<A, R> {421 pub docs: &'static [&'static str],422 pub selector_str: &'static str,423 pub selector: u32,424 pub name: &'static str,425 pub args: A,426 pub result: R,427 pub mutability: SolidityMutability,428}429impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {430 fn solidity_name(431 &self,432 is_impl: bool,433 writer: &mut impl fmt::Write,434 tc: &TypeCollector,435 ) -> fmt::Result {436 for doc in self.docs {437 writeln!(writer, "\t///{}", doc)?;438 }439 writeln!(440 writer,441 "\t/// @dev EVM selector for this function is: 0x{:0>8x},",442 self.selector443 )?;444 writeln!(writer, "\t/// or in textual repr: {}", self.selector_str)?;445 write!(writer, "\tfunction {}(", self.name)?;446 self.args.solidity_name(writer, tc)?;447 write!(writer, ")")?;448 if is_impl {449 write!(writer, " public")?;450 } else {451 write!(writer, " external")?;452 }453 match &self.mutability {454 SolidityMutability::Pure => write!(writer, " pure")?,455 SolidityMutability::View => write!(writer, " view")?,456 SolidityMutability::Mutable => {}457 }458 if !self.result.is_empty() {459 write!(writer, " returns (")?;460 self.result.solidity_name(writer, tc)?;461 write!(writer, ")")?;462 }463 if is_impl {464 writeln!(writer, " {{")?;465 writeln!(writer, "\t\trequire(false, stub_error);")?;466 self.args.solidity_get(writer)?;467 match &self.mutability {468 SolidityMutability::Pure => {}469 SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,470 SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,471 }472 if !self.result.is_empty() {473 write!(writer, "\t\treturn ")?;474 self.result.solidity_default(writer, tc)?;475 writeln!(writer, ";")?;476 }477 writeln!(writer, "\t}}")?;478 } else {479 writeln!(writer, ";")?;480 }481 Ok(())482 }483}484485#[impl_for_tuples(0, 48)]486impl SolidityFunctions for Tuple {487 for_tuples!( where #( Tuple: SolidityFunctions ),* );488489 fn solidity_name(490 &self,491 is_impl: bool,492 writer: &mut impl fmt::Write,493 tc: &TypeCollector,494 ) -> fmt::Result {495 let mut first = false;496 for_tuples!( #(497 Tuple.solidity_name(is_impl, writer, tc)?;498 )* );499 Ok(())500 }501}502503pub struct SolidityInterface<F: SolidityFunctions> {504 pub docs: &'static [&'static str],505 pub selector: bytes4,506 pub name: &'static str,507 pub is: &'static [&'static str],508 pub functions: F,509}510511impl<F: SolidityFunctions> SolidityInterface<F> {512 pub fn format(513 &self,514 is_impl: bool,515 out: &mut impl fmt::Write,516 tc: &TypeCollector,517 ) -> fmt::Result {518 const ZERO_BYTES: [u8; 4] = [0; 4];519 for doc in self.docs {520 writeln!(out, "///{}", doc)?;521 }522 if self.selector != ZERO_BYTES {523 writeln!(524 out,525 "/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",526 u32::from_be_bytes(self.selector)527 )?;528 }529 if is_impl {530 write!(out, "contract ")?;531 } else {532 write!(out, "interface ")?;533 }534 write!(out, "{}", self.name)?;535 if !self.is.is_empty() {536 write!(out, " is")?;537 for (i, n) in self.is.iter().enumerate() {538 if i != 0 {539 write!(out, ",")?;540 }541 write!(out, " {}", n)?;542 }543 }544 writeln!(out, " {{")?;545 self.functions.solidity_name(is_impl, out, tc)?;546 writeln!(out, "}}")?;547 Ok(())548 }549}550551pub struct SolidityEvent<A> {552 pub name: &'static str,553 pub args: A,554}555556impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {557 fn solidity_name(558 &self,559 _is_impl: bool,560 writer: &mut impl fmt::Write,561 tc: &TypeCollector,562 ) -> fmt::Result {563 write!(writer, "\tevent {}(", self.name)?;564 self.args.solidity_name(writer, tc)?;565 writeln!(writer, ");")566 }567}