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 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {184 write!(writer, "{}(", tc.collect_tuple::<Self>())?;185 $(186 <$ident>::solidity_default(writer, tc)?;187 )*188 write!(writer, ")")189 }190 }191 };192}193194impl_tuples! {A}195impl_tuples! {A B}196impl_tuples! {A B C}197impl_tuples! {A B C D}198impl_tuples! {A B C D E}199impl_tuples! {A B C D E F}200impl_tuples! {A B C D E F G}201impl_tuples! {A B C D E F G H}202impl_tuples! {A B C D E F G H I}203impl_tuples! {A B C D E F G H I J}204205pub trait SolidityArguments {206 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;207 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;208 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;209 fn is_empty(&self) -> bool {210 self.len() == 0211 }212 fn len(&self) -> usize;213}214215#[derive(Default)]216pub struct UnnamedArgument<T>(PhantomData<*const T>);217218impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {219 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {220 if !T::is_void() {221 T::solidity_name(writer, tc)?;222 if !T::is_simple() {223 write!(writer, " memory")?;224 }225 Ok(())226 } else {227 Ok(())228 }229 }230 fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {231 Ok(())232 }233 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {234 T::solidity_default(writer, tc)235 }236 fn len(&self) -> usize {237 if T::is_void() {238 0239 } else {240 1241 }242 }243}244245pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);246247impl<T> NamedArgument<T> {248 pub fn new(name: &'static str) -> Self {249 Self(name, Default::default())250 }251}252253impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {254 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {255 if !T::is_void() {256 T::solidity_name(writer, tc)?;257 if !T::is_simple() {258 write!(writer, " memory")?;259 }260 write!(writer, " {}", self.0)261 } else {262 Ok(())263 }264 }265 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {266 writeln!(writer, "\t\t{};", self.0)267 }268 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {269 T::solidity_default(writer, tc)270 }271 fn len(&self) -> usize {272 if T::is_void() {273 0274 } else {275 1276 }277 }278}279280pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);281282impl<T> SolidityEventArgument<T> {283 pub fn new(indexed: bool, name: &'static str) -> Self {284 Self(indexed, name, Default::default())285 }286}287288impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {289 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {290 if !T::is_void() {291 T::solidity_name(writer, tc)?;292 if self.0 {293 write!(writer, " indexed")?;294 }295 write!(writer, " {}", self.1)296 } else {297 Ok(())298 }299 }300 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {301 writeln!(writer, "\t\t{};", self.1)302 }303 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {304 T::solidity_default(writer, tc)305 }306 fn len(&self) -> usize {307 if T::is_void() {308 0309 } else {310 1311 }312 }313}314315impl SolidityArguments for () {316 fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {317 Ok(())318 }319 fn solidity_get(&self, _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 Ok(())324 }325 fn len(&self) -> usize {326 0327 }328}329330#[impl_for_tuples(1, 12)]331impl SolidityArguments for Tuple {332 for_tuples!( where #( Tuple: SolidityArguments ),* );333334 fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {335 let mut first = true;336 for_tuples!( #(337 if !Tuple.is_empty() {338 if !first {339 write!(writer, ", ")?;340 }341 first = false;342 Tuple.solidity_name(writer, tc)?;343 }344 )* );345 Ok(())346 }347 fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {348 for_tuples!( #(349 Tuple.solidity_get(writer)?;350 )* );351 Ok(())352 }353 fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {354 if self.is_empty() {355 Ok(())356 } else if self.len() == 1 {357 for_tuples!( #(358 Tuple.solidity_default(writer, tc)?;359 )* );360 Ok(())361 } else {362 write!(writer, "(")?;363 let mut first = true;364 for_tuples!( #(365 if !Tuple.is_empty() {366 if !first {367 write!(writer, ", ")?;368 }369 first = false;370 Tuple.solidity_default(writer, tc)?;371 }372 )* );373 write!(writer, ")")?;374 Ok(())375 }376 }377 fn len(&self) -> usize {378 for_tuples!( #( Tuple.len() )+* )379 }380}381382pub trait SolidityFunctions {383 fn solidity_name(384 &self,385 is_impl: bool,386 writer: &mut impl fmt::Write,387 tc: &TypeCollector,388 ) -> fmt::Result;389}390391pub enum SolidityMutability {392 Pure,393 View,394 Mutable,395}396pub struct SolidityFunction<A, R> {397 pub docs: &'static [&'static str],398 pub selector: &'static str,399 pub name: &'static str,400 pub args: A,401 pub result: R,402 pub mutability: SolidityMutability,403}404impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {405 fn solidity_name(406 &self,407 is_impl: bool,408 writer: &mut impl fmt::Write,409 tc: &TypeCollector,410 ) -> fmt::Result {411 for doc in self.docs {412 writeln!(writer, "\t//{}", doc)?;413 }414 if !self.docs.is_empty() {415 writeln!(writer, "\t//")?;416 }417 writeln!(writer, "\t// Selector: {}", self.selector)?;418 write!(writer, "\tfunction {}(", self.name)?;419 self.args.solidity_name(writer, tc)?;420 write!(writer, ")")?;421 if is_impl {422 write!(writer, " public")?;423 } else {424 write!(writer, " external")?;425 }426 match &self.mutability {427 SolidityMutability::Pure => write!(writer, " pure")?,428 SolidityMutability::View => write!(writer, " view")?,429 SolidityMutability::Mutable => {}430 }431 if !self.result.is_empty() {432 write!(writer, " returns (")?;433 self.result.solidity_name(writer, tc)?;434 write!(writer, ")")?;435 }436 if is_impl {437 writeln!(writer, " {{")?;438 writeln!(writer, "\t\trequire(false, stub_error);")?;439 self.args.solidity_get(writer)?;440 match &self.mutability {441 SolidityMutability::Pure => {}442 SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,443 SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,444 }445 if !self.result.is_empty() {446 write!(writer, "\t\treturn ")?;447 self.result.solidity_default(writer, tc)?;448 writeln!(writer, ";")?;449 }450 writeln!(writer, "\t}}")?;451 } else {452 writeln!(writer, ";")?;453 }454 Ok(())455 }456}457458#[impl_for_tuples(0, 24)]459impl SolidityFunctions for Tuple {460 for_tuples!( where #( Tuple: SolidityFunctions ),* );461462 fn solidity_name(463 &self,464 is_impl: bool,465 writer: &mut impl fmt::Write,466 tc: &TypeCollector,467 ) -> fmt::Result {468 let mut first = false;469 for_tuples!( #(470 Tuple.solidity_name(is_impl, writer, tc)?;471 )* );472 Ok(())473 }474}475476pub struct SolidityInterface<F: SolidityFunctions> {477 pub selector: bytes4,478 pub name: &'static str,479 pub is: &'static [&'static str],480 pub functions: F,481}482483impl<F: SolidityFunctions> SolidityInterface<F> {484 pub fn format(485 &self,486 is_impl: bool,487 out: &mut impl fmt::Write,488 tc: &TypeCollector,489 ) -> fmt::Result {490 const ZERO_BYTES: [u8; 4] = [0; 4];491 if self.selector != ZERO_BYTES {492 writeln!(493 out,494 "// Selector: {:0>8x}",495 u32::from_be_bytes(self.selector)496 )?;497 }498 if is_impl {499 write!(out, "contract ")?;500 } else {501 write!(out, "interface ")?;502 }503 write!(out, "{}", self.name)?;504 if !self.is.is_empty() {505 write!(out, " is")?;506 for (i, n) in self.is.iter().enumerate() {507 if i != 0 {508 write!(out, ",")?;509 }510 write!(out, " {}", n)?;511 }512 }513 writeln!(out, " {{")?;514 self.functions.solidity_name(is_impl, out, tc)?;515 writeln!(out, "}}")?;516 Ok(())517 }518}519520pub struct SolidityEvent<A> {521 pub name: &'static str,522 pub args: A,523}524525impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {526 fn solidity_name(527 &self,528 _is_impl: bool,529 writer: &mut impl fmt::Write,530 tc: &TypeCollector,531 ) -> fmt::Result {532 write!(writer, "\tevent {}(", self.name)?;533 self.args.solidity_name(writer, tc)?;534 writeln!(writer, ");")535 }536}