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, 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, _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, writer: &mut impl fmt::Write) -> fmt::Result {287 writeln!(writer, "\t\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, writer: &mut impl fmt::Write) -> fmt::Result {322 writeln!(writer, "\t\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, _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, writer: &mut impl fmt::Write) -> fmt::Result {369 for_tuples!( #(370 Tuple.solidity_get(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 name: &'static str,422 pub args: A,423 pub result: R,424 pub mutability: SolidityMutability,425 pub is_payable: bool,426}427impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {428 fn solidity_name(429 &self,430 is_impl: bool,431 writer: &mut impl fmt::Write,432 tc: &TypeCollector,433 ) -> fmt::Result {434 for doc in self.docs {435 writeln!(writer, "\t///{}", doc)?;436 }437 writeln!(438 writer,439 "\t/// @dev EVM selector for this function is: 0x{:0>8x},",440 self.selector441 )?;442 writeln!(writer, "\t/// or in textual repr: {}", self.selector_str)?;443 write!(writer, "\tfunction {}(", self.name)?;444 self.args.solidity_name(writer, tc)?;445 write!(writer, ")")?;446 if is_impl {447 write!(writer, " public")?;448 } else {449 write!(writer, " external")?;450 }451 match &self.mutability {452 SolidityMutability::Pure => write!(writer, " pure")?,453 SolidityMutability::View => write!(writer, " view")?,454 SolidityMutability::Mutable => {}455 }456 if self.is_payable {457 write!(writer, " payable")?;458 }459 if !self.result.is_empty() {460 write!(writer, " returns (")?;461 self.result.solidity_name(writer, tc)?;462 write!(writer, ")")?;463 }464 if is_impl {465 writeln!(writer, " {{")?;466 writeln!(writer, "\t\trequire(false, stub_error);")?;467 self.args.solidity_get(writer)?;468 match &self.mutability {469 SolidityMutability::Pure => {}470 SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,471 SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,472 }473 if !self.result.is_empty() {474 write!(writer, "\t\treturn ")?;475 self.result.solidity_default(writer, tc)?;476 writeln!(writer, ";")?;477 }478 writeln!(writer, "\t}}")?;479 } else {480 writeln!(writer, ";")?;481 }482 Ok(())483 }484}485486#[impl_for_tuples(0, 48)]487impl SolidityFunctions for Tuple {488 for_tuples!( where #( Tuple: SolidityFunctions ),* );489490 fn solidity_name(491 &self,492 is_impl: bool,493 writer: &mut impl fmt::Write,494 tc: &TypeCollector,495 ) -> fmt::Result {496 let mut first = false;497 for_tuples!( #(498 Tuple.solidity_name(is_impl, writer, tc)?;499 )* );500 Ok(())501 }502}503504pub struct SolidityInterface<F: SolidityFunctions> {505 pub docs: &'static [&'static str],506 pub selector: bytes4,507 pub name: &'static str,508 pub is: &'static [&'static str],509 pub functions: F,510}511512impl<F: SolidityFunctions> SolidityInterface<F> {513 pub fn format(514 &self,515 is_impl: bool,516 out: &mut impl fmt::Write,517 tc: &TypeCollector,518 ) -> fmt::Result {519 const ZERO_BYTES: [u8; 4] = [0; 4];520 for doc in self.docs {521 writeln!(out, "///{}", doc)?;522 }523 if self.selector != ZERO_BYTES {524 writeln!(525 out,526 "/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",527 u32::from_be_bytes(self.selector)528 )?;529 }530 if is_impl {531 write!(out, "contract ")?;532 } else {533 write!(out, "interface ")?;534 }535 write!(out, "{}", self.name)?;536 if !self.is.is_empty() {537 write!(out, " is")?;538 for (i, n) in self.is.iter().enumerate() {539 if i != 0 {540 write!(out, ",")?;541 }542 write!(out, " {}", n)?;543 }544 }545 writeln!(out, " {{")?;546 self.functions.solidity_name(is_impl, out, tc)?;547 writeln!(out, "}}")?;548 Ok(())549 }550}551552pub struct SolidityEvent<A> {553 pub name: &'static str,554 pub args: A,555}556557impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {558 fn solidity_name(559 &self,560 _is_impl: bool,561 writer: &mut impl fmt::Write,562 tc: &TypeCollector,563 ) -> fmt::Result {564 write!(writer, "\tevent {}(", self.name)?;565 self.args.solidity_name(writer, tc)?;566 writeln!(writer, ");")567 }568}