1234567891011121314151617#[cfg(not(feature = "std"))]18use alloc::{19 string::String,20 vec::Vec,21 collections::{BTreeSet, BTreeMap},22 format,23};24#[cfg(feature = "std")]25use std::collections::{BTreeSet, BTreeMap};26use core::{27 fmt::{self, Write},28 marker::PhantomData,29 cell::{Cell, RefCell},30};31use impl_trait_for_tuples::impl_for_tuples;32use crate::types::*;3334#[derive(Default)]35pub struct TypeCollector {36 structs: RefCell<BTreeSet<string>>,37 anonymous: RefCell<BTreeMap<Vec<string>, usize>>,38 id: Cell<usize>,39}40impl TypeCollector {41 pub fn new() -> Self {42 Self::default()43 }44 pub fn collect(&self, item: string) {45 self.structs.borrow_mut().insert(item);46 }47 pub fn next_id(&self) -> usize {48 let v = self.id.get();49 self.id.set(v + 1);50 v51 }52 pub fn collect_tuple<T: SolidityTupleType>(&self) -> String {53 let names = T::names(self);54 if let Some(id) = self.anonymous.borrow().get(&names).cloned() {55 return format!("Tuple{}", id);56 }57 let id = self.next_id();58 let mut str = String::new();59 writeln!(str, "// Anonymous struct").unwrap();60 writeln!(str, "struct Tuple{} {{", id).unwrap();61 for (i, name) in names.iter().enumerate() {62 writeln!(str, "\t{} field_{};", name, i).unwrap();63 }64 writeln!(str, "}}").unwrap();65 self.collect(str);66 self.anonymous.borrow_mut().insert(names, id);67 format!("Tuple{}", id)68 }69 pub fn finish(self) -> BTreeSet<string> {70 self.structs.into_inner()71 }72}7374pub trait SolidityTypeName: 'static {75 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;76 fn is_simple() -> bool;77 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;78 fn is_void() -> bool {79 false80 }81}82macro_rules! solidity_type_name {83 ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {84 $(85 impl SolidityTypeName for $ty {86 fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {87 write!(writer, $name)88 }89 fn is_simple() -> bool {90 $simple91 }92 fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {93 write!(writer, $default)94 }95 }96 )*97 };98}99100solidity_type_name! {101 uint8 => "uint8" true = "0",102 uint32 => "uint32" true = "0",103 uint64 => "uint64" true = "0",104 uint128 => "uint128" true = "0",105 uint256 => "uint256" true = "0",106 bytes4 => "bytes4" true = "bytes4(0)",107 address => "address" true = "0x0000000000000000000000000000000000000000",108 string => "string" false = "\"\"",109 bytes => "bytes" false = "hex\"\"",110 bool => "bool" true = "false",111}112impl SolidityTypeName for void {113 fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {114 Ok(())115 }116 fn is_simple() -> bool {117 true118 }119 fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {120 Ok(())121 }122 fn is_void() -> bool {123 true124 }125}126127mod sealed {128 pub trait CanBePlacedInVec {}129}130131impl sealed::CanBePlacedInVec for uint256 {}132impl sealed::CanBePlacedInVec for string {}133impl sealed::CanBePlacedInVec for address {}134135impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {136 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {137 T::solidity_name(writer, tc)?;138 write!(writer, "[]")139 }140 fn is_simple() -> bool {141 false142 }143 fn solidity_default(writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {144 write!(writer, "[]")145 }146}147148pub trait SolidityTupleType {149 fn names(tc: &TypeCollector) -> Vec<String>;150 fn len() -> usize;151}152153macro_rules! count {154 () => (0usize);155 ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));156}157158macro_rules! impl_tuples {159 ($($ident:ident)+) => {160 impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}161 impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {162 fn names(tc: &TypeCollector) -> Vec<string> {163 let mut collected = Vec::with_capacity(Self::len());164 $({165 let mut out = string::new();166 $ident::solidity_name(&mut out, tc).expect("no fmt error");167 collected.push(out);168 })*;169 collected170 }171172 fn len() -> usize {173 count!($($ident)*)174 }175 }176 impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {177 fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {178 write!(writer, "{}", tc.collect_tuple::<Self>())179 }180 fn is_simple() -> bool {181 false182 }183 #[allow(unused_assignments)]184 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {185 write!(writer, "{}(", tc.collect_tuple::<Self>())?;186 let mut first = true;187 $(188 if !first {189 write!(writer, ",")?;190 } else {191 first = false;192 }193 <$ident>::solidity_default(writer, tc)?;194 )*195 write!(writer, ")")196 }197 }198 };199}200201impl_tuples! {A}202impl_tuples! {A B}203impl_tuples! {A B C}204impl_tuples! {A B C D}205impl_tuples! {A B C D E}206impl_tuples! {A B C D E F}207impl_tuples! {A B C D E F G}208impl_tuples! {A B C D E F G H}209impl_tuples! {A B C D E F G H I}210impl_tuples! {A B C D E F G H I J}211212pub trait SolidityArguments {213 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;214 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;215 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;216 fn is_empty(&self) -> bool {217 self.len() == 0218 }219 fn len(&self) -> usize;220}221222#[derive(Default)]223pub struct UnnamedArgument<T>(PhantomData<*const T>);224225impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {226 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {227 if !T::is_void() {228 T::solidity_name(writer, tc)?;229 if !T::is_simple() {230 write!(writer, " memory")?;231 }232 Ok(())233 } else {234 Ok(())235 }236 }237 fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {238 Ok(())239 }240 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {241 T::solidity_default(writer, tc)242 }243 fn len(&self) -> usize {244 if T::is_void() {245 0246 } else {247 1248 }249 }250}251252pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);253254impl<T> NamedArgument<T> {255 pub fn new(name: &'static str) -> Self {256 Self(name, Default::default())257 }258}259260impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {261 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {262 if !T::is_void() {263 T::solidity_name(writer, tc)?;264 if !T::is_simple() {265 write!(writer, " memory")?;266 }267 write!(writer, " {}", self.0)268 } else {269 Ok(())270 }271 }272 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {273 writeln!(writer, "\t\t{};", self.0)274 }275 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {276 T::solidity_default(writer, tc)277 }278 fn len(&self) -> usize {279 if T::is_void() {280 0281 } else {282 1283 }284 }285}286287pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);288289impl<T> SolidityEventArgument<T> {290 pub fn new(indexed: bool, name: &'static str) -> Self {291 Self(indexed, name, Default::default())292 }293}294295impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {296 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {297 if !T::is_void() {298 T::solidity_name(writer, tc)?;299 if self.0 {300 write!(writer, " indexed")?;301 }302 write!(writer, " {}", self.1)303 } else {304 Ok(())305 }306 }307 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {308 writeln!(writer, "\t\t{};", self.1)309 }310 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {311 T::solidity_default(writer, tc)312 }313 fn len(&self) -> usize {314 if T::is_void() {315 0316 } else {317 1318 }319 }320}321322impl SolidityArguments for () {323 fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {324 Ok(())325 }326 fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {327 Ok(())328 }329 fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {330 Ok(())331 }332 fn len(&self) -> usize {333 0334 }335}336337#[impl_for_tuples(1, 12)]338impl SolidityArguments for Tuple {339 for_tuples!( where #( Tuple: SolidityArguments ),* );340341 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {342 let mut first = true;343 for_tuples!( #(344 if !Tuple.is_empty() {345 if !first {346 write!(writer, ", ")?;347 }348 first = false;349 Tuple.solidity_name(writer, tc)?;350 }351 )* );352 Ok(())353 }354 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {355 for_tuples!( #(356 Tuple.solidity_get(writer)?;357 )* );358 Ok(())359 }360 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {361 if self.is_empty() {362 Ok(())363 } else if self.len() == 1 {364 for_tuples!( #(365 Tuple.solidity_default(writer, tc)?;366 )* );367 Ok(())368 } else {369 write!(writer, "(")?;370 let mut first = true;371 for_tuples!( #(372 if !Tuple.is_empty() {373 if !first {374 write!(writer, ", ")?;375 }376 first = false;377 Tuple.solidity_default(writer, tc)?;378 }379 )* );380 write!(writer, ")")?;381 Ok(())382 }383 }384 fn len(&self) -> usize {385 for_tuples!( #( Tuple.len() )+* )386 }387}388389pub trait SolidityFunctions {390 fn solidity_name(391 &self,392 is_impl: bool,393 writer: &mut impl fmt::Write,394 tc: &TypeCollector,395 ) -> fmt::Result;396}397398pub enum SolidityMutability {399 Pure,400 View,401 Mutable,402}403pub struct SolidityFunction<A, R> {404 pub docs: &'static [&'static str],405 pub selector: &'static str,406 pub name: &'static str,407 pub args: A,408 pub result: R,409 pub mutability: SolidityMutability,410}411impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {412 fn solidity_name(413 &self,414 is_impl: bool,415 writer: &mut impl fmt::Write,416 tc: &TypeCollector,417 ) -> fmt::Result {418 for doc in self.docs {419 writeln!(writer, "\t//{}", doc)?;420 }421 if !self.docs.is_empty() {422 writeln!(writer, "\t//")?;423 }424 writeln!(writer, "\t// Selector: {}", self.selector)?;425 write!(writer, "\tfunction {}(", self.name)?;426 self.args.solidity_name(writer, tc)?;427 write!(writer, ")")?;428 if is_impl {429 write!(writer, " public")?;430 } else {431 write!(writer, " external")?;432 }433 match &self.mutability {434 SolidityMutability::Pure => write!(writer, " pure")?,435 SolidityMutability::View => write!(writer, " view")?,436 SolidityMutability::Mutable => {}437 }438 if !self.result.is_empty() {439 write!(writer, " returns (")?;440 self.result.solidity_name(writer, tc)?;441 write!(writer, ")")?;442 }443 if is_impl {444 writeln!(writer, " {{")?;445 writeln!(writer, "\t\trequire(false, stub_error);")?;446 self.args.solidity_get(writer)?;447 match &self.mutability {448 SolidityMutability::Pure => {}449 SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,450 SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,451 }452 if !self.result.is_empty() {453 write!(writer, "\t\treturn ")?;454 self.result.solidity_default(writer, tc)?;455 writeln!(writer, ";")?;456 }457 writeln!(writer, "\t}}")?;458 } else {459 writeln!(writer, ";")?;460 }461 Ok(())462 }463}464465#[impl_for_tuples(0, 24)]466impl SolidityFunctions for Tuple {467 for_tuples!( where #( Tuple: SolidityFunctions ),* );468469 fn solidity_name(470 &self,471 is_impl: bool,472 writer: &mut impl fmt::Write,473 tc: &TypeCollector,474 ) -> fmt::Result {475 let mut first = false;476 for_tuples!( #(477 Tuple.solidity_name(is_impl, writer, tc)?;478 )* );479 Ok(())480 }481}482483pub struct SolidityInterface<F: SolidityFunctions> {484 pub selector: bytes4,485 pub name: &'static str,486 pub is: &'static [&'static str],487 pub functions: F,488}489490impl<F: SolidityFunctions> SolidityInterface<F> {491 pub fn format(492 &self,493 is_impl: bool,494 out: &mut impl fmt::Write,495 tc: &TypeCollector,496 ) -> fmt::Result {497 const ZERO_BYTES: [u8; 4] = [0; 4];498 if self.selector != ZERO_BYTES {499 writeln!(500 out,501 "// Selector: {:0>8x}",502 u32::from_be_bytes(self.selector)503 )?;504 }505 if is_impl {506 write!(out, "contract ")?;507 } else {508 write!(out, "interface ")?;509 }510 write!(out, "{}", self.name)?;511 if !self.is.is_empty() {512 write!(out, " is")?;513 for (i, n) in self.is.iter().enumerate() {514 if i != 0 {515 write!(out, ",")?;516 }517 write!(out, " {}", n)?;518 }519 }520 writeln!(out, " {{")?;521 self.functions.solidity_name(is_impl, out, tc)?;522 writeln!(out, "}}")?;523 Ok(())524 }525}526527pub struct SolidityEvent<A> {528 pub name: &'static str,529 pub args: A,530}531532impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {533 fn solidity_name(534 &self,535 _is_impl: bool,536 writer: &mut impl fmt::Write,537 tc: &TypeCollector,538 ) -> fmt::Result {539 write!(writer, "\tevent {}(", self.name)?;540 self.args.solidity_name(writer, tc)?;541 writeln!(writer, ");")542 }543}