difftreelog
CORE-386 Implement eth methods
in: master
7 files changed
crates/evm-coder/src/solidity.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#[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, 12)]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}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#[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}pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -23,7 +23,7 @@
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256, H256};
use sp_std::vec::Vec;
-use up_data_structs::{Property, SponsoringRateLimit, NestingRule, OwnerRestrictedSet};
+use up_data_structs::{Property, SponsoringRateLimit, NestingRule, OwnerRestrictedSet, AccessMode};
use alloc::format;
use crate::{Pallet, CollectionHandle, Config, CollectionProperties};
@@ -252,6 +252,42 @@
save(self);
Ok(())
}
+
+ fn set_access(&mut self, caller: caller, mode: string) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ self.check_is_owner_or_admin(&caller)
+ .map_err(dispatch_to_evm::<T>)?;
+ self.collection.permissions.access = Some(match mode.as_str() {
+ "Normal" => AccessMode::Normal,
+ "AllowList" => AccessMode::AllowList,
+ _ => return Err("Not supported access mode".into()),
+ });
+ save(self);
+ Ok(())
+ }
+
+ fn add_to_allow_list(&self, caller: caller, user: address) -> Result<void> {
+ let caller = check_is_owner_or_admin(caller, self)?;
+ let user = T::CrossAccountId::from_eth(user);
+ <Pallet<T>>::toggle_allowlist(self, &caller, &user, true)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn remove_from_allow_list(&self, caller: caller, user: address) -> Result<void> {
+ let caller = check_is_owner_or_admin(caller, self)?;
+ let user = T::CrossAccountId::from_eth(user);
+ <Pallet<T>>::toggle_allowlist(self, &caller, &user, false)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn set_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {
+ check_is_owner_or_admin(caller, self)?;
+ self.collection.permissions.mint_mode = Some(mode);
+ save(self);
+ Ok(())
+ }
}
fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {
@@ -262,6 +298,14 @@
Ok(())
}
+fn check_is_owner_or_admin<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<T::CrossAccountId> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ collection
+ .check_is_owner_or_admin(&caller)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ Ok(caller)
+}
+
fn save<T: Config>(collection: &CollectionHandle<T>) {
<crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());
}
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -51,105 +51,6 @@
event MintingFinished();
}
-// Selector: 3a54513b
-contract Collection is Dummy, ERC165 {
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- public
- {
- require(false, stub_error);
- key;
- value;
- dummy = 0;
- }
-
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) public {
- require(false, stub_error);
- key;
- dummy = 0;
- }
-
- // Throws error if key not found
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- public
- view
- returns (bytes memory)
- {
- require(false, stub_error);
- key;
- dummy;
- return hex"";
- }
-
- // Selector: ethSetSponsor(address) 8f9af356
- function ethSetSponsor(address sponsor) public {
- require(false, stub_error);
- sponsor;
- dummy = 0;
- }
-
- // Selector: ethConfirmSponsorship() a8580d1a
- function ethConfirmSponsorship() public {
- require(false, stub_error);
- dummy = 0;
- }
-
- // Selector: setLimit(string,uint32) 68db30ca
- function setLimit(string memory limit, uint32 value) public {
- require(false, stub_error);
- limit;
- value;
- dummy = 0;
- }
-
- // Selector: setLimit(string,bool) ea67e4c2
- function setLimit(string memory limit, bool value) public {
- require(false, stub_error);
- limit;
- value;
- dummy = 0;
- }
-
- // Selector: contractAddress() f6b4dfb4
- function contractAddress() public view returns (address) {
- require(false, stub_error);
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-
- // Selector: addAdmin(address) 70480275
- function addAdmin(address newAdmin) public view {
- require(false, stub_error);
- newAdmin;
- dummy;
- }
-
- // Selector: removeAdmin(address) 1785f53c
- function removeAdmin(address admin) public view {
- require(false, stub_error);
- admin;
- dummy;
- }
-
- // Selector: setNesting(bool) e8fc50dd
- function setNesting(bool enable) public {
- require(false, stub_error);
- enable;
- dummy = 0;
- }
-
- // Selector: setNesting(bool,address[]) 7df12a9a
- function setNesting(bool enable, address[] memory collections) public {
- require(false, stub_error);
- enable;
- collections;
- dummy = 0;
- }
-}
-
// Selector: 41369377
contract TokenProperties is Dummy, ERC165 {
// Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
@@ -479,6 +380,133 @@
}
}
+// Selector: f56cd7fa
+contract Collection is Dummy, ERC165 {
+ // Selector: setCollectionProperty(string,bytes) 2f073f66
+ function setCollectionProperty(string memory key, bytes memory value)
+ public
+ {
+ require(false, stub_error);
+ key;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: deleteCollectionProperty(string) 7b7debce
+ function deleteCollectionProperty(string memory key) public {
+ require(false, stub_error);
+ key;
+ dummy = 0;
+ }
+
+ // Throws error if key not found
+ //
+ // Selector: collectionProperty(string) cf24fd6d
+ function collectionProperty(string memory key)
+ public
+ view
+ returns (bytes memory)
+ {
+ require(false, stub_error);
+ key;
+ dummy;
+ return hex"";
+ }
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() public {
+ require(false, stub_error);
+ dummy = 0;
+ }
+
+ // Selector: setLimit(string,uint32) 68db30ca
+ function setLimit(string memory limit, uint32 value) public {
+ require(false, stub_error);
+ limit;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: setLimit(string,bool) ea67e4c2
+ function setLimit(string memory limit, bool value) public {
+ require(false, stub_error);
+ limit;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() public view returns (address) {
+ require(false, stub_error);
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
+ // Selector: addAdmin(address) 70480275
+ function addAdmin(address newAdmin) public view {
+ require(false, stub_error);
+ newAdmin;
+ dummy;
+ }
+
+ // Selector: removeAdmin(address) 1785f53c
+ function removeAdmin(address admin) public view {
+ require(false, stub_error);
+ admin;
+ dummy;
+ }
+
+ // Selector: setNesting(bool) e8fc50dd
+ function setNesting(bool enable) public {
+ require(false, stub_error);
+ enable;
+ dummy = 0;
+ }
+
+ // Selector: setNesting(bool,address[]) 7df12a9a
+ function setNesting(bool enable, address[] memory collections) public {
+ require(false, stub_error);
+ enable;
+ collections;
+ dummy = 0;
+ }
+
+ // Selector: setAccess(string) 488f56aa
+ function setAccess(string memory mode) public {
+ require(false, stub_error);
+ mode;
+ dummy = 0;
+ }
+
+ // Selector: addToAllowList(address) 31f59102
+ function addToAllowList(address user) public view {
+ require(false, stub_error);
+ user;
+ dummy;
+ }
+
+ // Selector: removeFromAllowList(address) eba8dabc
+ function removeFromAllowList(address user) public view {
+ require(false, stub_error);
+ user;
+ dummy;
+ }
+
+ // Selector: setMintMode(bool) 5dea9bd5
+ function setMintMode(bool mode) public {
+ require(false, stub_error);
+ mode;
+ dummy = 0;
+ }
+}
+
contract UniqueNFT is
Dummy,
ERC165,
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -42,51 +42,6 @@
event MintingFinished();
}
-// Selector: 3a54513b
-interface Collection is Dummy, ERC165 {
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- external;
-
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) external;
-
- // Throws error if key not found
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- external
- view
- returns (bytes memory);
-
- // Selector: ethSetSponsor(address) 8f9af356
- function ethSetSponsor(address sponsor) external;
-
- // Selector: ethConfirmSponsorship() a8580d1a
- function ethConfirmSponsorship() external;
-
- // Selector: setLimit(string,uint32) 68db30ca
- function setLimit(string memory limit, uint32 value) external;
-
- // Selector: setLimit(string,bool) ea67e4c2
- function setLimit(string memory limit, bool value) external;
-
- // Selector: contractAddress() f6b4dfb4
- function contractAddress() external view returns (address);
-
- // Selector: addAdmin(address) 70480275
- function addAdmin(address newAdmin) external view;
-
- // Selector: removeAdmin(address) 1785f53c
- function removeAdmin(address admin) external view;
-
- // Selector: setNesting(bool) e8fc50dd
- function setNesting(bool enable) external;
-
- // Selector: setNesting(bool,address[]) 7df12a9a
- function setNesting(bool enable, address[] memory collections) external;
-}
-
// Selector: 41369377
interface TokenProperties is Dummy, ERC165 {
// Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
@@ -258,6 +213,63 @@
returns (bool);
}
+// Selector: f56cd7fa
+interface Collection is Dummy, ERC165 {
+ // Selector: setCollectionProperty(string,bytes) 2f073f66
+ function setCollectionProperty(string memory key, bytes memory value)
+ external;
+
+ // Selector: deleteCollectionProperty(string) 7b7debce
+ function deleteCollectionProperty(string memory key) external;
+
+ // Throws error if key not found
+ //
+ // Selector: collectionProperty(string) cf24fd6d
+ function collectionProperty(string memory key)
+ external
+ view
+ returns (bytes memory);
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) external;
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() external;
+
+ // Selector: setLimit(string,uint32) 68db30ca
+ function setLimit(string memory limit, uint32 value) external;
+
+ // Selector: setLimit(string,bool) ea67e4c2
+ function setLimit(string memory limit, bool value) external;
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() external view returns (address);
+
+ // Selector: addAdmin(address) 70480275
+ function addAdmin(address newAdmin) external view;
+
+ // Selector: removeAdmin(address) 1785f53c
+ function removeAdmin(address admin) external view;
+
+ // Selector: setNesting(bool) e8fc50dd
+ function setNesting(bool enable) external;
+
+ // Selector: setNesting(bool,address[]) 7df12a9a
+ function setNesting(bool enable, address[] memory collections) external;
+
+ // Selector: setAccess(string) 488f56aa
+ function setAccess(string memory mode) external;
+
+ // Selector: addToAllowList(address) 31f59102
+ function addToAllowList(address user) external view;
+
+ // Selector: removeFromAllowList(address) eba8dabc
+ function removeFromAllowList(address user) external view;
+
+ // Selector: setMintMode(bool) 5dea9bd5
+ function setMintMode(bool mode) external;
+}
+
interface UniqueNFT is
Dummy,
ERC165,
tests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -31,6 +31,7 @@
evmCollectionHelpers,
getCollectionAddressFromResult,
evmCollection,
+ ethBalanceViaSub,
} from './util/helpers';
import {
addCollectionAdminExpectSuccess,
@@ -221,66 +222,51 @@
});
//TODO: CORE-302 add eth methods
- itWeb3.skip('Sponsoring evm address from substrate collection', async ({api, web3}) => {
+ itWeb3('Sponsoring collection from evm address via access list', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
const collectionHelpers = evmCollectionHelpers(web3, owner);
let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const sponsor = await createEthAccountWithBalance(api, web3);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
- result = await collectionEvm.methods.ethSetSponsor(sponsor).send();
+ result = await collectionEvm.methods.ethSetSponsor(sponsor).send({from: owner});
let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
await expect(collectionEvm.methods.ethConfirmSponsorship().call()).to.be.rejectedWith('Caller is not set as sponsor');
- const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
- await sponsorCollection.methods.ethConfirmSponsorship().send();
+ await collectionEvm.methods.ethConfirmSponsorship().send({from: sponsor});
collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
expect(collectionSub.sponsorship.isConfirmed).to.be.true;
expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
const user = createEthAccount(web3);
- const userContract = evmCollection(web3, user, collectionIdAddress);
- const nextTokenId = await userContract.methods.nextTokenId().call();
-
+ const nextTokenId = await collectionEvm.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
- await expect(userContract.methods.mintWithTokenURI(
- user,
- nextTokenId,
- 'Test URI',
- ).call()).to.be.rejectedWith('PublicMintingNotAllowed');
-
- // TODO: add this methods to eth
- // {
- // const tx = api.tx.unique.setPublicAccessMode(collectionId, 'AllowList');
- // const events = await submitTransactionAsync(owner, tx);
- // const result = getCreateCollectionResult(events);
- // expect(result.success).to.be.true;
- // }
- // {
- // const tx = api.tx.unique.addToAllowList(collectionId, {Ethereum: userEth});
- // const events = await submitTransactionAsync(owner, tx);
- // const result = getCreateCollectionResult(events);
- // expect(result.success).to.be.true;
- // }
- // {
- // const tx = api.tx.unique.setMintPermission(collectionId, true);
- // const events = await submitTransactionAsync(owner, tx);
- // const result = getCreateCollectionResult(events);
- // expect(result.success).to.be.true;
- // }
+ const oldPermissions = (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
+ expect(oldPermissions.mintMode).to.be.false;
+ expect(oldPermissions.access).to.be.equal('Normal');
+
+ await collectionEvm.methods.setAccess('AllowList').send({from: owner});
+ await collectionEvm.methods.addToAllowList(user).send({from: owner});
+ await collectionEvm.methods.setMintMode(true).send({from: owner});
+
+ const newPermissions = (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
+ expect(newPermissions.mintMode).to.be.true;
+ expect(newPermissions.access).to.be.equal('AllowList');
+
// const [alicesBalanceBefore] = await getBalance(api, [alicesPublicKey]);
{
- const nextTokenId = await userContract.methods.nextTokenId().call();
+ const nextTokenId = await collectionEvm.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
- const result = await userContract.methods.mintWithTokenURI(
+ const result = await collectionEvm.methods.mintWithTokenURI(
user,
nextTokenId,
'Test URI',
- ).send();
+ ).call({from: user});
+ console.log(result);
const events = normalizeEvents(result.events);
expect(events).to.be.deep.equal([
@@ -295,37 +281,63 @@
},
]);
- expect(await userContract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
}
});
- //TODO: CORE-302 add eth methods
- itWeb3.skip('Check that transaction via EVM spend money from substrate address', async ({api, web3, privateKeyWrapper}) => {
- const owner = privateKeyWrapper('//Alice');
- const user = privateKeyWrapper(`//User/${Date.now()}`);
- const userEth = subToEth(user.address);
- const collectionId = await createCollectionExpectSuccess();
- await addCollectionAdminExpectSuccess(owner, collectionId, {Ethereum: userEth});
- await transferBalanceTo(api, owner, user.address);
+ itWeb3('Check that transaction via EVM spend money from sponsor address', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
+ let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const sponsor = await createEthAccountWithBalance(api, web3);
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ result = await collectionEvm.methods.ethSetSponsor(sponsor).send();
+ let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
+ expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ await expect(collectionEvm.methods.ethConfirmSponsorship().call()).to.be.rejectedWith('Caller is not set as sponsor');
+ const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+ await sponsorCollection.methods.ethConfirmSponsorship().send();
+ collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.sponsorship.isConfirmed).to.be.true;
+ expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+
+ const user = createEthAccount(web3);
+ await collectionEvm.methods.addAdmin(user).send();
+
+ const ownerBalanceBefore = await ethBalanceViaSub(api, owner);
+ const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);
+
+
+ const userCollectionEvm = evmCollection(web3, user, collectionIdAddress);
+ const nextTokenId = await userCollectionEvm.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+ result = await userCollectionEvm.methods.mintWithTokenURI(
+ user,
+ nextTokenId,
+ 'Test URI',
+ ).send();
+ const events = normalizeEvents(result.events);
const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: userEth, ...GAS_ARGS});
- const [userBalanceBefore] = await getBalance(api, [user.address]);
-
- {
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- await executeEthTxOnSub(web3, api, user, contract, m => m.mintWithTokenURI(
- userEth,
- nextTokenId,
- 'Test URI',
- ));
-
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
- }
-
- const [userBalanceAfter] = await getBalance(api, [user.address]);
- expect(userBalanceAfter < userBalanceBefore).to.be.true;
+ expect(events).to.be.deep.equal([
+ {
+ address,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: user,
+ tokenId: nextTokenId,
+ },
+ },
+ ]);
+ expect(await userCollectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+
+ const ownerBalanceAfter = await ethBalanceViaSub(api, owner);
+ expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+ const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);
+ expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
});
});
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -91,6 +91,15 @@
},
{
"inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "addToAllowList",
+ "outputs": [],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "approved", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
@@ -300,6 +309,15 @@
},
{
"inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "removeFromAllowList",
+ "outputs": [],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "from", "type": "address" },
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
@@ -322,6 +340,13 @@
"type": "function"
},
{
+ "inputs": [{ "internalType": "string", "name": "mode", "type": "string" }],
+ "name": "setAccess",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "address", "name": "operator", "type": "address" },
{ "internalType": "bool", "name": "approved", "type": "bool" }
@@ -362,6 +387,13 @@
"type": "function"
},
{
+ "inputs": [{ "internalType": "bool", "name": "mode", "type": "bool" }],
+ "name": "setMintMode",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "bool", "name": "enable", "type": "bool" },
{