difftreelog
Merge remote-tracking branch 'origin/feature/add_collection_sponsor_substrate' into develop
in: master
32 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5510,7 +5510,7 @@
[[package]]
name = "pallet-common"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"ethereum",
"evm-coder",
@@ -5748,7 +5748,7 @@
[[package]]
name = "pallet-fungible"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"ethereum",
"evm-coder",
@@ -5990,7 +5990,7 @@
[[package]]
name = "pallet-nonfungible"
-version = "0.1.4"
+version = "0.1.5"
dependencies = [
"ethereum",
"evm-coder",
@@ -6112,7 +6112,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.2.3"
+version = "0.2.4"
dependencies = [
"derivative",
"ethereum",
crates/evm-coder/CHANGELOG.mddiffbeforeafterboth--- a/crates/evm-coder/CHANGELOG.md
+++ b/crates/evm-coder/CHANGELOG.md
@@ -1,6 +1,8 @@
# Change Log
All notable changes to this project will be documented in this file.
+
+<!-- bureaucrate goes here -->
## [v0.1.2] 2022-08-19
### Added
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//! Implementation detail of [`crate::solidity_interface`] macro code-generation.18//! You should not rely on any public item from this module, as it is only intended to be used19//! by procedural macro, API and output format may be changed at any time.20//!21//! Purpose of this module is to receive solidity contract definition in module-specified22//! format, and then output string, representing interface of this contract in solidity language2324#[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 /// Code => id40 /// id ordering is required to perform topo-sort on the resulting data41 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 /// "simple" types are stored inline, no `memory` modifier should be used in solidity85 fn is_simple() -> bool;86 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;87 /// Specialization88 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 /// Not every type should be directly placed in vec.139 /// Vec encoding is not memory efficient, as every item will be padded140 /// to 32 bytes.141 /// Instead you should use specialized types (`bytes` in case of `Vec<u8>`)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}426impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {427 fn solidity_name(428 &self,429 is_impl: bool,430 writer: &mut impl fmt::Write,431 tc: &TypeCollector,432 ) -> fmt::Result {433 for doc in self.docs {434 writeln!(writer, "\t///{}", doc)?;435 }436 writeln!(437 writer,438 "\t/// @dev EVM selector for this function is: 0x{:0>8x},",439 self.selector440 )?;441 writeln!(writer, "\t/// or in textual repr: {}", self.selector_str)?;442 write!(writer, "\tfunction {}(", self.name)?;443 self.args.solidity_name(writer, tc)?;444 write!(writer, ")")?;445 if is_impl {446 write!(writer, " public")?;447 } else {448 write!(writer, " external")?;449 }450 match &self.mutability {451 SolidityMutability::Pure => write!(writer, " pure")?,452 SolidityMutability::View => write!(writer, " view")?,453 SolidityMutability::Mutable => {}454 }455 if !self.result.is_empty() {456 write!(writer, " returns (")?;457 self.result.solidity_name(writer, tc)?;458 write!(writer, ")")?;459 }460 if is_impl {461 writeln!(writer, " {{")?;462 writeln!(writer, "\t\trequire(false, stub_error);")?;463 self.args.solidity_get(writer)?;464 match &self.mutability {465 SolidityMutability::Pure => {}466 SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,467 SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,468 }469 if !self.result.is_empty() {470 write!(writer, "\t\treturn ")?;471 self.result.solidity_default(writer, tc)?;472 writeln!(writer, ";")?;473 }474 writeln!(writer, "\t}}")?;475 } else {476 writeln!(writer, ";")?;477 }478 Ok(())479 }480}481482#[impl_for_tuples(0, 24)]483impl SolidityFunctions for Tuple {484 for_tuples!( where #( Tuple: SolidityFunctions ),* );485486 fn solidity_name(487 &self,488 is_impl: bool,489 writer: &mut impl fmt::Write,490 tc: &TypeCollector,491 ) -> fmt::Result {492 let mut first = false;493 for_tuples!( #(494 Tuple.solidity_name(is_impl, writer, tc)?;495 )* );496 Ok(())497 }498}499500pub struct SolidityInterface<F: SolidityFunctions> {501 pub docs: &'static [&'static str],502 pub selector: bytes4,503 pub name: &'static str,504 pub is: &'static [&'static str],505 pub functions: F,506}507508impl<F: SolidityFunctions> SolidityInterface<F> {509 pub fn format(510 &self,511 is_impl: bool,512 out: &mut impl fmt::Write,513 tc: &TypeCollector,514 ) -> fmt::Result {515 const ZERO_BYTES: [u8; 4] = [0; 4];516 for doc in self.docs {517 writeln!(out, "///{}", doc)?;518 }519 if self.selector != ZERO_BYTES {520 writeln!(521 out,522 "/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",523 u32::from_be_bytes(self.selector)524 )?;525 }526 if is_impl {527 write!(out, "contract ")?;528 } else {529 write!(out, "interface ")?;530 }531 write!(out, "{}", self.name)?;532 if !self.is.is_empty() {533 write!(out, " is")?;534 for (i, n) in self.is.iter().enumerate() {535 if i != 0 {536 write!(out, ",")?;537 }538 write!(out, " {}", n)?;539 }540 }541 writeln!(out, " {{")?;542 self.functions.solidity_name(is_impl, out, tc)?;543 writeln!(out, "}}")?;544 Ok(())545 }546}547548pub struct SolidityEvent<A> {549 pub name: &'static str,550 pub args: A,551}552553impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {554 fn solidity_name(555 &self,556 _is_impl: bool,557 writer: &mut impl fmt::Write,558 tc: &TypeCollector,559 ) -> fmt::Result {560 write!(writer, "\tevent {}(", self.name)?;561 self.args.solidity_name(writer, tc)?;562 writeln!(writer, ");")563 }564}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//! Implementation detail of [`crate::solidity_interface`] macro code-generation.18//! You should not rely on any public item from this module, as it is only intended to be used19//! by procedural macro, API and output format may be changed at any time.20//!21//! Purpose of this module is to receive solidity contract definition in module-specified22//! format, and then output string, representing interface of this contract in solidity language2324#[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 /// Code => id40 /// id ordering is required to perform topo-sort on the resulting data41 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 /// "simple" types are stored inline, no `memory` modifier should be used in solidity85 fn is_simple() -> bool;86 fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;87 /// Specialization88 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 /// Not every type should be directly placed in vec.139 /// Vec encoding is not memory efficient, as every item will be padded140 /// to 32 bytes.141 /// Instead you should use specialized types (`bytes` in case of `Vec<u8>`)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}426impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {427 fn solidity_name(428 &self,429 is_impl: bool,430 writer: &mut impl fmt::Write,431 tc: &TypeCollector,432 ) -> fmt::Result {433 for doc in self.docs {434 writeln!(writer, "\t///{}", doc)?;435 }436 writeln!(437 writer,438 "\t/// @dev EVM selector for this function is: 0x{:0>8x},",439 self.selector440 )?;441 writeln!(writer, "\t/// or in textual repr: {}", self.selector_str)?;442 write!(writer, "\tfunction {}(", self.name)?;443 self.args.solidity_name(writer, tc)?;444 write!(writer, ")")?;445 if is_impl {446 write!(writer, " public")?;447 } else {448 write!(writer, " external")?;449 }450 match &self.mutability {451 SolidityMutability::Pure => write!(writer, " pure")?,452 SolidityMutability::View => write!(writer, " view")?,453 SolidityMutability::Mutable => {}454 }455 if !self.result.is_empty() {456 write!(writer, " returns (")?;457 self.result.solidity_name(writer, tc)?;458 write!(writer, ")")?;459 }460 if is_impl {461 writeln!(writer, " {{")?;462 writeln!(writer, "\t\trequire(false, stub_error);")?;463 self.args.solidity_get(writer)?;464 match &self.mutability {465 SolidityMutability::Pure => {}466 SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,467 SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,468 }469 if !self.result.is_empty() {470 write!(writer, "\t\treturn ")?;471 self.result.solidity_default(writer, tc)?;472 writeln!(writer, ";")?;473 }474 writeln!(writer, "\t}}")?;475 } else {476 writeln!(writer, ";")?;477 }478 Ok(())479 }480}481482#[impl_for_tuples(0, 48)]483impl SolidityFunctions for Tuple {484 for_tuples!( where #( Tuple: SolidityFunctions ),* );485486 fn solidity_name(487 &self,488 is_impl: bool,489 writer: &mut impl fmt::Write,490 tc: &TypeCollector,491 ) -> fmt::Result {492 let mut first = false;493 for_tuples!( #(494 Tuple.solidity_name(is_impl, writer, tc)?;495 )* );496 Ok(())497 }498}499500pub struct SolidityInterface<F: SolidityFunctions> {501 pub docs: &'static [&'static str],502 pub selector: bytes4,503 pub name: &'static str,504 pub is: &'static [&'static str],505 pub functions: F,506}507508impl<F: SolidityFunctions> SolidityInterface<F> {509 pub fn format(510 &self,511 is_impl: bool,512 out: &mut impl fmt::Write,513 tc: &TypeCollector,514 ) -> fmt::Result {515 const ZERO_BYTES: [u8; 4] = [0; 4];516 for doc in self.docs {517 writeln!(out, "///{}", doc)?;518 }519 if self.selector != ZERO_BYTES {520 writeln!(521 out,522 "/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",523 u32::from_be_bytes(self.selector)524 )?;525 }526 if is_impl {527 write!(out, "contract ")?;528 } else {529 write!(out, "interface ")?;530 }531 write!(out, "{}", self.name)?;532 if !self.is.is_empty() {533 write!(out, " is")?;534 for (i, n) in self.is.iter().enumerate() {535 if i != 0 {536 write!(out, ",")?;537 }538 write!(out, " {}", n)?;539 }540 }541 writeln!(out, " {{")?;542 self.functions.solidity_name(is_impl, out, tc)?;543 writeln!(out, "}}")?;544 Ok(())545 }546}547548pub struct SolidityEvent<A> {549 pub name: &'static str,550 pub args: A,551}552553impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {554 fn solidity_name(555 &self,556 _is_impl: bool,557 writer: &mut impl fmt::Write,558 tc: &TypeCollector,559 ) -> fmt::Result {560 write!(writer, "\tevent {}(", self.name)?;561 self.args.solidity_name(writer, tc)?;562 writeln!(writer, ");")563 }564}pallets/common/CHANGELOG.mddiffbeforeafterboth--- a/pallets/common/CHANGELOG.md
+++ b/pallets/common/CHANGELOG.md
@@ -2,6 +2,16 @@
All notable changes to this project will be documented in this file.
+## [0.1.8] - 2022-08-24
+
+## Added
+ - Eth methods for collection
+ + set_collection_sponsor_substrate
+ + has_collection_pending_sponsor
+ + remove_collection_sponsor
+ + get_collection_sponsor
+- Add convert function from `uint256` to `CrossAccountId`.
+
## [0.1.7] - 2022-08-19
### Added
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-common"
-version = "0.1.7"
+version = "0.1.8"
license = "GPLv3"
edition = "2021"
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -26,13 +26,13 @@
use sp_std::vec::Vec;
use up_data_structs::{
AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,
- SponsoringRateLimit,
+ SponsoringRateLimit, SponsorshipState,
};
use alloc::format;
use crate::{
Pallet, CollectionHandle, Config, CollectionProperties,
- eth::convert_substrate_address_to_cross_account_id,
+ eth::{convert_cross_account_to_uint256, convert_uint256_to_cross_account},
};
/// Events for ethereum collection helper.
@@ -63,7 +63,7 @@
#[solidity_interface(name = Collection)]
impl<T: Config> CollectionHandle<T>
where
- T::AccountId: From<[u8; 32]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
/// Set collection property.
///
@@ -128,6 +128,32 @@
save(self)
}
+ /// Set the substrate sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
+ fn set_collection_sponsor_substrate(
+ &mut self,
+ caller: caller,
+ sponsor: uint256,
+ ) -> Result<void> {
+ check_is_owner_or_admin(caller, self)?;
+
+ let sponsor = convert_uint256_to_cross_account::<T>(sponsor);
+ self.set_sponsor(sponsor.as_sub().clone())
+ .map_err(dispatch_to_evm::<T>)?;
+ save(self)
+ }
+
+ // /// Whether there is a pending sponsor.
+ fn has_collection_pending_sponsor(&self) -> Result<bool> {
+ Ok(matches!(
+ self.collection.sponsorship,
+ SponsorshipState::Unconfirmed(_)
+ ))
+ }
+
/// Collection sponsorship confirmation.
///
/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
@@ -142,6 +168,32 @@
save(self)
}
+ /// Remove collection sponsor.
+ fn remove_collection_sponsor(&mut self, caller: caller) -> Result<void> {
+ check_is_owner_or_admin(caller, self)?;
+ self.remove_sponsor().map_err(dispatch_to_evm::<T>)?;
+ save(self)
+ }
+
+ /// Get current sponsor.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
+ fn get_collection_sponsor(&self) -> Result<(address, uint256)> {
+ let sponsor = match self.collection.sponsorship.sponsor() {
+ Some(sponsor) => sponsor,
+ None => return Ok(Default::default()),
+ };
+ let sponsor = T::CrossAccountId::from_sub(sponsor.clone());
+ let result: (address, uint256) = if sponsor.is_canonical_substrate() {
+ let sponsor = convert_cross_account_to_uint256::<T>(&sponsor);
+ (Default::default(), sponsor)
+ } else {
+ let sponsor = *sponsor.as_eth();
+ (sponsor, Default::default())
+ };
+ Ok(result)
+ }
+
/// Set limits for the collection.
/// @dev Throws error if limit not found.
/// @param limit Name of the limit. Valid names:
@@ -235,7 +287,7 @@
new_admin: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let new_admin = convert_substrate_address_to_cross_account_id::<T>(new_admin);
+ let new_admin = convert_uint256_to_cross_account::<T>(new_admin);
<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -248,7 +300,7 @@
admin: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let admin = convert_substrate_address_to_cross_account_id::<T>(admin);
+ let admin = convert_uint256_to_cross_account::<T>(admin);
<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -422,7 +474,7 @@
/// @param user account to verify
/// @return "true" if account is the owner or admin
fn is_owner_or_admin_substrate(&self, user: uint256) -> Result<bool> {
- let user = convert_substrate_address_to_cross_account_id::<T>(user);
+ let user = convert_uint256_to_cross_account::<T>(user);
Ok(self.is_owner_or_admin(&user))
}
@@ -455,7 +507,7 @@
/// @param newOwner new owner substrate account
fn set_owner_substrate(&mut self, caller: caller, new_owner: uint256) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let new_owner = convert_substrate_address_to_cross_account_id::<T>(new_owner);
+ let new_owner = convert_uint256_to_cross_account::<T>(new_owner);
self.set_owner_internal(caller, new_owner)
.map_err(dispatch_to_evm::<T>)
}
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -59,15 +59,13 @@
uint256::from_big_endian(slice)
}
-/// Converts Substrate address to CrossAccountId
-pub fn convert_substrate_address_to_cross_account_id<T: Config>(
- address: uint256,
-) -> T::CrossAccountId
+/// Convert `uint256` to `CrossAccountId`.
+pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId
where
T::AccountId: From<[u8; 32]>,
{
- let mut address_arr: [u8; 32] = Default::default();
- address.to_big_endian(&mut address_arr);
- let account_id = T::AccountId::from(address_arr);
+ let mut new_admin_arr = [0_u8; 32];
+ from.to_big_endian(&mut new_admin_arr);
+ let account_id = T::AccountId::from(new_admin_arr);
T::CrossAccountId::from_sub(account_id)
}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -231,6 +231,12 @@
Ok(true)
}
+ /// Remove collection sponsor.
+ pub fn remove_sponsor(&mut self) -> DispatchResult {
+ self.collection.sponsorship = SponsorshipState::Disabled;
+ Ok(())
+ }
+
/// Checks that the collection was created with, and must be operated upon through **Unique API**.
/// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.
pub fn check_is_internal(&self) -> DispatchResult {
@@ -732,12 +738,7 @@
/// Get the effective limits for the collection.
pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {
- let collection = <CollectionById<T>>::get(collection);
- if collection.is_none() {
- return None;
- }
-
- let collection = collection.unwrap();
+ let collection = <CollectionById<T>>::get(collection)?;
let limits = collection.limits;
let effective_limits = CollectionLimits {
account_token_ownership_limit: Some(limits.account_token_ownership_limit()),
pallets/fungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/fungible/CHANGELOG.md
+++ b/pallets/fungible/CHANGELOG.md
@@ -2,6 +2,11 @@
All notable changes to this project will be documented in this file.
+## [v0.1.4] - 2022-08-24
+
+### Change
+ - Add bound `AsRef<[u8; 32]>` to `T::CrossAccountId`.
+
<!-- bureaucrate goes here -->
## [v0.1.3] 2022-08-16
pallets/fungible/Cargo.tomldiffbeforeafterboth--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-fungible"
-version = "0.1.3"
+version = "0.1.4"
license = "GPLv3"
edition = "2021"
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -154,14 +154,14 @@
Collection(common_mut, CollectionHandle<T>),
)
)]
-impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> {}
+impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}
generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);
generate_stubgen!(gen_iface, UniqueFungibleCall<()>, false);
impl<T: Config> CommonEvmHandler for FungibleHandle<T>
where
- T::AccountId: From<[u8; 32]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -22,7 +22,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xffe4da23
+/// @dev the ERC-165 identifier for this interface is 0xe54be640
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -82,6 +82,27 @@
dummy = 0;
}
+ /// Set the substrate sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0xc74d6751,
+ /// or in textual repr: setCollectionSponsorSubstrate(uint256)
+ function setCollectionSponsorSubstrate(uint256 sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
+ /// @dev EVM selector for this function is: 0x058ac185,
+ /// or in textual repr: hasCollectionPendingSponsor()
+ function hasCollectionPendingSponsor() public view returns (bool) {
+ require(false, stub_error);
+ dummy;
+ return false;
+ }
+
/// Collection sponsorship confirmation.
///
/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
@@ -92,6 +113,25 @@
dummy = 0;
}
+ /// Remove collection sponsor.
+ /// @dev EVM selector for this function is: 0x6e0326a3,
+ /// or in textual repr: removeCollectionSponsor()
+ function removeCollectionSponsor() public {
+ require(false, stub_error);
+ dummy = 0;
+ }
+
+ /// Get current sponsor.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
+ /// @dev EVM selector for this function is: 0xb66bbc14,
+ /// or in textual repr: getCollectionSponsor()
+ function getCollectionSponsor() public view returns (Tuple6 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ }
+
/// Set limits for the collection.
/// @dev Throws error if limit not found.
/// @param limit Name of the limit. Valid names:
@@ -310,6 +350,12 @@
}
}
+/// @dev anonymous struct
+struct Tuple6 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @dev the ERC-165 identifier for this interface is 0x79cc6790
contract ERC20UniqueExtensions is Dummy, ERC165 {
/// @dev EVM selector for this function is: 0x79cc6790,
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -2,6 +2,11 @@
All notable changes to this project will be documented in this file.
+## [v0.1.5] - 2022-08-24
+
+### Change
+ - Add bound `AsRef<[u8; 32]>` to `T::CrossAccountId`.
+
<!-- bureaucrate goes here -->
## [v0.1.4] 2022-08-16
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-nonfungible"
-version = "0.1.4"
+version = "0.1.5"
license = "GPLv3"
edition = "2021"
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -740,7 +740,7 @@
TokenProperties,
)
)]
-impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}
+impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}
// Not a tests, but code generators
generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);
@@ -748,7 +748,7 @@
impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>
where
- T::AccountId: From<[u8; 32]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");
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
@@ -99,7 +99,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xffe4da23
+/// @dev the ERC-165 identifier for this interface is 0xe54be640
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -159,6 +159,27 @@
dummy = 0;
}
+ /// Set the substrate sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0xc74d6751,
+ /// or in textual repr: setCollectionSponsorSubstrate(uint256)
+ function setCollectionSponsorSubstrate(uint256 sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
+ /// @dev EVM selector for this function is: 0x058ac185,
+ /// or in textual repr: hasCollectionPendingSponsor()
+ function hasCollectionPendingSponsor() public view returns (bool) {
+ require(false, stub_error);
+ dummy;
+ return false;
+ }
+
/// Collection sponsorship confirmation.
///
/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
@@ -169,6 +190,25 @@
dummy = 0;
}
+ /// Remove collection sponsor.
+ /// @dev EVM selector for this function is: 0x6e0326a3,
+ /// or in textual repr: removeCollectionSponsor()
+ function removeCollectionSponsor() public {
+ require(false, stub_error);
+ dummy = 0;
+ }
+
+ /// Get current sponsor.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
+ /// @dev EVM selector for this function is: 0xb66bbc14,
+ /// or in textual repr: getCollectionSponsor()
+ function getCollectionSponsor() public view returns (Tuple17 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ }
+
/// Set limits for the collection.
/// @dev Throws error if limit not found.
/// @param limit Name of the limit. Valid names:
@@ -387,6 +427,12 @@
}
}
+/// @dev anonymous struct
+struct Tuple17 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
contract ERC721Burnable is Dummy, ERC165 {
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -2,6 +2,11 @@
All notable changes to this project will be documented in this file.
+## [v0.2.4] - 2022-08-24
+
+### Change
+ - Add bound `AsRef<[u8; 32]>` to `T::CrossAccountId`.
+
<!-- bureaucrate goes here -->
## [v0.2.3] 2022-08-16
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-refungible"
-version = "0.2.3"
+version = "0.2.4"
license = "GPLv3"
edition = "2021"
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -789,7 +789,7 @@
TokenProperties,
)
)]
-impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> {}
+impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}
// Not a tests, but code generators
generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);
@@ -797,7 +797,7 @@
impl<T: Config> CommonEvmHandler for RefungibleHandle<T>
where
- T::AccountId: From<[u8; 32]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");
fn call(
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -99,7 +99,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xffe4da23
+/// @dev the ERC-165 identifier for this interface is 0xe54be640
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -159,6 +159,27 @@
dummy = 0;
}
+ /// Set the substrate sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0xc74d6751,
+ /// or in textual repr: setCollectionSponsorSubstrate(uint256)
+ function setCollectionSponsorSubstrate(uint256 sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
+ /// @dev EVM selector for this function is: 0x058ac185,
+ /// or in textual repr: hasCollectionPendingSponsor()
+ function hasCollectionPendingSponsor() public view returns (bool) {
+ require(false, stub_error);
+ dummy;
+ return false;
+ }
+
/// Collection sponsorship confirmation.
///
/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
@@ -169,6 +190,25 @@
dummy = 0;
}
+ /// Remove collection sponsor.
+ /// @dev EVM selector for this function is: 0x6e0326a3,
+ /// or in textual repr: removeCollectionSponsor()
+ function removeCollectionSponsor() public {
+ require(false, stub_error);
+ dummy = 0;
+ }
+
+ /// Get current sponsor.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
+ /// @dev EVM selector for this function is: 0xb66bbc14,
+ /// or in textual repr: getCollectionSponsor()
+ function getCollectionSponsor() public view returns (Tuple17 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ }
+
/// Set limits for the collection.
/// @dev Throws error if limit not found.
/// @param limit Name of the limit. Valid names:
@@ -387,6 +427,12 @@
}
}
+/// @dev anonymous struct
+struct Tuple17 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
contract ERC721Burnable is Dummy, ERC165 {
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -124,7 +124,7 @@
+ pallet_fungible::Config
+ pallet_nonfungible::Config
+ pallet_refungible::Config,
- T::AccountId: From<[u8; 32]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
fn is_reserved(target: &H160) -> bool {
map_eth_to_id(target).is_some()
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xffe4da23
+/// @dev the ERC-165 identifier for this interface is 0xe54be640
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -53,6 +53,19 @@
/// or in textual repr: setCollectionSponsor(address)
function setCollectionSponsor(address sponsor) external;
+ /// Set the substrate sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0xc74d6751,
+ /// or in textual repr: setCollectionSponsorSubstrate(uint256)
+ function setCollectionSponsorSubstrate(uint256 sponsor) external;
+
+ /// @dev EVM selector for this function is: 0x058ac185,
+ /// or in textual repr: hasCollectionPendingSponsor()
+ function hasCollectionPendingSponsor() external view returns (bool);
+
/// Collection sponsorship confirmation.
///
/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
@@ -60,6 +73,18 @@
/// or in textual repr: confirmCollectionSponsorship()
function confirmCollectionSponsorship() external;
+ /// Remove collection sponsor.
+ /// @dev EVM selector for this function is: 0x6e0326a3,
+ /// or in textual repr: removeCollectionSponsor()
+ function removeCollectionSponsor() external;
+
+ /// Get current sponsor.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
+ /// @dev EVM selector for this function is: 0xb66bbc14,
+ /// or in textual repr: getCollectionSponsor()
+ function getCollectionSponsor() external view returns (Tuple6 memory);
+
/// Set limits for the collection.
/// @dev Throws error if limit not found.
/// @param limit Name of the limit. Valid names:
@@ -200,6 +225,12 @@
function setOwnerSubstrate(uint256 newOwner) external;
}
+/// @dev anonymous struct
+struct Tuple6 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @dev the ERC-165 identifier for this interface is 0x79cc6790
interface ERC20UniqueExtensions is Dummy, ERC165 {
/// @dev EVM selector for this function is: 0x79cc6790,
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -65,7 +65,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xffe4da23
+/// @dev the ERC-165 identifier for this interface is 0xe54be640
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -105,6 +105,19 @@
/// or in textual repr: setCollectionSponsor(address)
function setCollectionSponsor(address sponsor) external;
+ /// Set the substrate sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0xc74d6751,
+ /// or in textual repr: setCollectionSponsorSubstrate(uint256)
+ function setCollectionSponsorSubstrate(uint256 sponsor) external;
+
+ /// @dev EVM selector for this function is: 0x058ac185,
+ /// or in textual repr: hasCollectionPendingSponsor()
+ function hasCollectionPendingSponsor() external view returns (bool);
+
/// Collection sponsorship confirmation.
///
/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
@@ -112,6 +125,18 @@
/// or in textual repr: confirmCollectionSponsorship()
function confirmCollectionSponsorship() external;
+ /// Remove collection sponsor.
+ /// @dev EVM selector for this function is: 0x6e0326a3,
+ /// or in textual repr: removeCollectionSponsor()
+ function removeCollectionSponsor() external;
+
+ /// Get current sponsor.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
+ /// @dev EVM selector for this function is: 0xb66bbc14,
+ /// or in textual repr: getCollectionSponsor()
+ function getCollectionSponsor() external view returns (Tuple17 memory);
+
/// Set limits for the collection.
/// @dev Throws error if limit not found.
/// @param limit Name of the limit. Valid names:
@@ -252,6 +277,12 @@
function setOwnerSubstrate(uint256 newOwner) external;
}
+/// @dev anonymous struct
+struct Tuple17 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
interface ERC721Burnable is Dummy, ERC165 {
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -65,7 +65,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xffe4da23
+/// @dev the ERC-165 identifier for this interface is 0xe54be640
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -105,6 +105,19 @@
/// or in textual repr: setCollectionSponsor(address)
function setCollectionSponsor(address sponsor) external;
+ /// Set the substrate sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0xc74d6751,
+ /// or in textual repr: setCollectionSponsorSubstrate(uint256)
+ function setCollectionSponsorSubstrate(uint256 sponsor) external;
+
+ /// @dev EVM selector for this function is: 0x058ac185,
+ /// or in textual repr: hasCollectionPendingSponsor()
+ function hasCollectionPendingSponsor() external view returns (bool);
+
/// Collection sponsorship confirmation.
///
/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
@@ -112,6 +125,18 @@
/// or in textual repr: confirmCollectionSponsorship()
function confirmCollectionSponsorship() external;
+ /// Remove collection sponsor.
+ /// @dev EVM selector for this function is: 0x6e0326a3,
+ /// or in textual repr: removeCollectionSponsor()
+ function removeCollectionSponsor() external;
+
+ /// Get current sponsor.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
+ /// @dev EVM selector for this function is: 0xb66bbc14,
+ /// or in textual repr: getCollectionSponsor()
+ function getCollectionSponsor() external view returns (Tuple17 memory);
+
/// Set limits for the collection.
/// @dev Throws error if limit not found.
/// @param limit Name of the limit. Valid names:
@@ -252,6 +277,12 @@
function setOwnerSubstrate(uint256 newOwner) external;
}
+/// @dev anonymous struct
+struct Tuple17 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
interface ERC721Burnable is Dummy, ERC165 {
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -1,8 +1,10 @@
-import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';
-import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub} from './util/helpers';
+import {addToAllowListExpectSuccess, bigIntToSub, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';
+import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub, subToEth} from './util/helpers';
import nonFungibleAbi from './nonFungibleAbi.json';
import {expect} from 'chai';
import {evmToAddress} from '@polkadot/util-crypto';
+import {submitTransactionAsync} from '../substrate/substrate-api';
+import getBalance from '../substrate/get-balance';
describe('evm collection sponsoring', () => {
itWeb3('sponsors mint transactions', async ({web3, privateKeyWrapper}) => {
@@ -38,6 +40,47 @@
]);
});
+ itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {
+ const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ 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 = privateKeyWrapper('//Alice');
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+ result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
+
+ const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
+ await submitTransactionAsync(sponsor, confirmTx);
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+
+ const sponsorTuple = await collectionEvm.methods.getCollectionSponsor().call({from: owner});
+ expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);
+ });
+
+ itWeb3('Remove sponsor', async ({api, web3, privateKeyWrapper}) => {
+ const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
+ let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
+ const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+ const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+ result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
+
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+
+ await collectionEvm.methods.removeCollectionSponsor().send({from: owner});
+
+ const sponsorTuple = await collectionEvm.methods.getCollectionSponsor().call({from: owner});
+ expect(sponsorTuple.field_0).to.be.eq('0x0000000000000000000000000000000000000000');
+ });
+
itWeb3('Sponsoring collection from evm address via access list', async ({api, web3, privateKeyWrapper}) => {
const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
const collectionHelpers = evmCollectionHelpers(web3, owner);
@@ -107,6 +150,61 @@
}
});
+ itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
+ const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
+ const result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const sponsor = privateKeyWrapper('//Alice');
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+
+ await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
+
+ const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
+ await submitTransactionAsync(sponsor, confirmTx);
+
+ const user = createEthAccount(web3);
+ const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+
+ await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
+ await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
+ await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+
+ const ownerBalanceBefore = await ethBalanceViaSub(api, owner);
+ const sponsorBalanceBefore = (await getBalance(api, [sponsor.address]))[0];
+
+ {
+ const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+ const result = await collectionEvm.methods.mintWithTokenURI(
+ user,
+ nextTokenId,
+ 'Test URI',
+ ).send({from: user});
+ const events = normalizeEvents(result.events);
+
+ expect(events).to.be.deep.equal([
+ {
+ address: collectionIdAddress,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: user,
+ tokenId: nextTokenId,
+ },
+ },
+ ]);
+
+ const ownerBalanceAfter = await ethBalanceViaSub(api, owner);
+ const sponsorBalanceAfter = (await getBalance(api, [sponsor.address]))[0];
+
+ expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
+ expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
+ }
+ });
+
itWeb3('Check that transaction via EVM spend money from sponsor address', async ({api, web3, privateKeyWrapper}) => {
const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
const collectionHelpers = evmCollectionHelpers(web3, owner);
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -151,6 +151,30 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "getCollectionSponsor",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "hasCollectionPendingSponsor",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "address", "name": "user", "type": "address" }
],
@@ -194,6 +218,13 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "removeCollectionSponsor",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "address", "name": "user", "type": "address" }
],
@@ -278,6 +309,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "sponsor", "type": "uint256" }
+ ],
+ "name": "setCollectionSponsorSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "newOwner", "type": "address" }
],
"name": "setOwner",
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -200,6 +200,30 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "getCollectionSponsor",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple17",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "hasCollectionPendingSponsor",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "address", "name": "owner", "type": "address" },
{ "internalType": "address", "name": "operator", "type": "address" }
@@ -335,6 +359,13 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "removeCollectionSponsor",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "address", "name": "user", "type": "address" }
],
@@ -452,6 +483,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "sponsor", "type": "uint256" }
+ ],
+ "name": "setCollectionSponsorSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "newOwner", "type": "address" }
],
"name": "setOwner",
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -200,6 +200,30 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "getCollectionSponsor",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple17",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "hasCollectionPendingSponsor",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "address", "name": "owner", "type": "address" },
{ "internalType": "address", "name": "operator", "type": "address" }
@@ -335,6 +359,13 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "removeCollectionSponsor",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "address", "name": "user", "type": "address" }
],
@@ -452,6 +483,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "sponsor", "type": "uint256" }
+ ],
+ "name": "setCollectionSponsorSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "newOwner", "type": "address" }
],
"name": "setOwner",
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -99,6 +99,10 @@
}
}
+export function bigIntToSub(api: ApiPromise, number: bigint) {
+ return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();
+}
+
export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {
if (typeof input === 'string') {
if (input.length >= 47) {