difftreelog
Merge pull request #647 from UniqueNetwork/feature/supports-interface-for-erc721-metadata
in: master
57 files changed
.maintain/scripts/generate_sol.shdiffbeforeafterboth--- a/.maintain/scripts/generate_sol.sh
+++ b/.maintain/scripts/generate_sol.sh
@@ -11,4 +11,6 @@
formatted=$(mktemp)
prettier --config $PRETTIER_CONFIG $raw > $formatted
+sed -i -E -e "s/.+\/\/ FORMATTING: FORCE NEWLINE//g" $formatted
+
mv $formatted $OUTPUT
crates/evm-coder/procedural/src/solidity_interface.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#![allow(dead_code)]1819// NOTE: In order to understand this Rust macro better, first read this chapter20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html2223use quote::{quote, ToTokens};24use inflector::cases;25use std::fmt::Write;26use syn::{27 Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,28 MetaNameValue, PatType, PathArguments, ReturnType, Type,29 spanned::Spanned,30 parse::{Parse, ParseStream},31 parenthesized, Token, LitInt, LitStr,32};3334use crate::{35 fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,36 parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,37 snake_ident_to_screaming,38};3940struct Is {41 name: Ident,42 pascal_call_name: Ident,43 snake_call_name: Ident,44 via: Option<(Type, Ident)>,45 condition: Option<Expr>,46}47impl Is {48 fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {49 let name = &self.name;50 let pascal_call_name = &self.pascal_call_name;51 quote! {52 #name(#pascal_call_name #gen_ref)53 }54 }5556 fn expand_interface_id(&self) -> proc_macro2::TokenStream {57 let pascal_call_name = &self.pascal_call_name;58 quote! {59 interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());60 }61 }6263 fn expand_supports_interface(64 &self,65 generics: &proc_macro2::TokenStream,66 ) -> proc_macro2::TokenStream {67 let pascal_call_name = &self.pascal_call_name;68 let condition = self.condition.as_ref().map(|condition| {69 quote! {70 (#condition) &&71 }72 });73 quote! {74 #condition <#pascal_call_name #generics>::supports_interface(this, interface_id)75 }76 }7778 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {79 let name = &self.name;80 quote! {81 Self::#name(call) => call.weight()82 }83 }8485 fn expand_variant_call(86 &self,87 call_name: &proc_macro2::Ident,88 generics: &proc_macro2::TokenStream,89 ) -> proc_macro2::TokenStream {90 let name = &self.name;91 let pascal_call_name = &self.pascal_call_name;92 let via_typ = self93 .via94 .as_ref()95 .map(|(t, _)| quote! {#t})96 .unwrap_or_else(|| quote! {Self});97 let via_map = self98 .via99 .as_ref()100 .map(|(_, i)| quote! {.#i()})101 .unwrap_or_default();102 let condition = self.condition.as_ref().map(|condition| {103 quote! {104 if ({let this = &self; (#condition)})105 }106 });107 quote! {108 #call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {109 call,110 caller: c.caller,111 value: c.value,112 })113 }114 }115116 fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {117 let name = &self.name;118 let pascal_call_name = &self.pascal_call_name;119 quote! {120 if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {121 return Ok(Some(Self::#name(parsed_call)))122 }123 }124 }125126 fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {127 let pascal_call_name = &self.pascal_call_name;128 quote! {129 <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);130 }131 }132133 fn expand_event_generator(&self) -> proc_macro2::TokenStream {134 let name = &self.name;135 quote! {136 #name::generate_solidity_interface(tc, is_impl);137 }138 }139}140141#[derive(Default)]142struct IsList(Vec<Is>);143impl Parse for IsList {144 fn parse(input: ParseStream) -> syn::Result<Self> {145 let mut out = vec![];146 loop {147 if input.is_empty() {148 break;149 }150 let name = input.parse::<Ident>()?;151 let lookahead = input.lookahead1();152153 let mut condition: Option<Expr> = None;154 let mut via: Option<(Type, Ident)> = None;155156 if lookahead.peek(syn::token::Paren) {157 let contents;158 parenthesized!(contents in input);159 let input = contents;160161 while !input.is_empty() {162 let lookahead = input.lookahead1();163 if lookahead.peek(Token![if]) {164 input.parse::<Token![if]>()?;165 let contents;166 parenthesized!(contents in input);167 let contents = contents.parse::<Expr>()?;168169 if condition.replace(contents).is_some() {170 return Err(syn::Error::new(input.span(), "condition is already set"));171 }172 } else if lookahead.peek(kw::via) {173 input.parse::<kw::via>()?;174 let contents;175 parenthesized!(contents in input);176177 let method = contents.parse::<Ident>()?;178 contents.parse::<kw::returns>()?;179 let ty = contents.parse::<Type>()?;180181 if via.replace((ty, method)).is_some() {182 return Err(syn::Error::new(input.span(), "via is already set"));183 }184 } else {185 return Err(lookahead.error());186 }187188 if input.peek(Token![,]) {189 input.parse::<Token![,]>()?;190 } else if !input.is_empty() {191 return Err(syn::Error::new(input.span(), "expected end"));192 }193 }194 } else if lookahead.peek(Token![,]) || input.is_empty() {195 // Pass196 } else {197 return Err(lookahead.error());198 };199 out.push(Is {200 pascal_call_name: pascal_ident_to_call(&name),201 snake_call_name: pascal_ident_to_snake_call(&name),202 name,203 via,204 condition,205 });206 if input.peek(Token![,]) {207 input.parse::<Token![,]>()?;208 continue;209 } else {210 break;211 }212 }213 Ok(Self(out))214 }215}216217pub struct InterfaceInfo {218 name: Ident,219 is: IsList,220 inline_is: IsList,221 events: IsList,222 expect_selector: Option<u32>,223}224impl Parse for InterfaceInfo {225 fn parse(input: ParseStream) -> syn::Result<Self> {226 let mut name = None;227 let mut is = None;228 let mut inline_is = None;229 let mut events = None;230 let mut expect_selector = None;231 // TODO: create proc-macro to optimize proc-macro boilerplate? :D232 loop {233 let lookahead = input.lookahead1();234 if lookahead.peek(kw::name) {235 let k = input.parse::<kw::name>()?;236 input.parse::<Token![=]>()?;237 if name.replace(input.parse::<Ident>()?).is_some() {238 return Err(syn::Error::new(k.span(), "name is already set"));239 }240 } else if lookahead.peek(kw::is) {241 let k = input.parse::<kw::is>()?;242 let contents;243 parenthesized!(contents in input);244 if is.replace(contents.parse::<IsList>()?).is_some() {245 return Err(syn::Error::new(k.span(), "is is already set"));246 }247 } else if lookahead.peek(kw::inline_is) {248 let k = input.parse::<kw::inline_is>()?;249 let contents;250 parenthesized!(contents in input);251 if inline_is.replace(contents.parse::<IsList>()?).is_some() {252 return Err(syn::Error::new(k.span(), "inline_is is already set"));253 }254 } else if lookahead.peek(kw::events) {255 let k = input.parse::<kw::events>()?;256 let contents;257 parenthesized!(contents in input);258 if events.replace(contents.parse::<IsList>()?).is_some() {259 return Err(syn::Error::new(k.span(), "events is already set"));260 }261 } else if lookahead.peek(kw::expect_selector) {262 let k = input.parse::<kw::expect_selector>()?;263 input.parse::<Token![=]>()?;264 let value = input.parse::<LitInt>()?;265 if expect_selector266 .replace(value.base10_parse::<u32>()?)267 .is_some()268 {269 return Err(syn::Error::new(k.span(), "expect_selector is already set"));270 }271 } else if input.is_empty() {272 break;273 } else {274 return Err(lookahead.error());275 }276 if input.peek(Token![,]) {277 input.parse::<Token![,]>()?;278 } else {279 break;280 }281 }282 Ok(Self {283 name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,284 is: is.unwrap_or_default(),285 inline_is: inline_is.unwrap_or_default(),286 events: events.unwrap_or_default(),287 expect_selector,288 })289 }290}291292struct MethodInfo {293 rename_selector: Option<String>,294}295impl Parse for MethodInfo {296 fn parse(input: ParseStream) -> syn::Result<Self> {297 let mut rename_selector = None;298 let lookahead = input.lookahead1();299 if lookahead.peek(kw::rename_selector) {300 let k = input.parse::<kw::rename_selector>()?;301 input.parse::<Token![=]>()?;302 if rename_selector303 .replace(input.parse::<LitStr>()?.value())304 .is_some()305 {306 return Err(syn::Error::new(k.span(), "rename_selector is already set"));307 }308 }309 Ok(Self { rename_selector })310 }311}312313enum AbiType {314 // type315 Plain(Ident),316 // (type1,type2)317 Tuple(Vec<AbiType>),318 // type[]319 Vec(Box<AbiType>),320 // type[20]321 Array(Box<AbiType>, usize),322}323impl AbiType {324 fn try_from(value: &Type) -> syn::Result<Self> {325 let value = Self::try_maybe_special_from(value)?;326 if value.is_special() {327 return Err(syn::Error::new(value.span(), "unexpected special type"));328 }329 Ok(value)330 }331 fn try_maybe_special_from(value: &Type) -> syn::Result<Self> {332 match value {333 Type::Array(arr) => {334 let wrapped = AbiType::try_from(&arr.elem)?;335 match &arr.len {336 Expr::Lit(l) => match &l.lit {337 Lit::Int(i) => {338 let num = i.base10_parse::<usize>()?;339 Ok(AbiType::Array(Box::new(wrapped), num as usize))340 }341 _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),342 },343 _ => Err(syn::Error::new(arr.len.span(), "should be literal")),344 }345 }346 Type::Path(_) => {347 let path = parse_path(value)?;348 let segment = parse_path_segment(path)?;349 if segment.ident == "Vec" {350 let args = match &segment.arguments {351 PathArguments::AngleBracketed(e) => e,352 _ => {353 return Err(syn::Error::new(354 segment.arguments.span(),355 "missing Vec generic",356 ))357 }358 };359 let args = &args.args;360 if args.len() != 1 {361 return Err(syn::Error::new(362 args.span(),363 "expected only one generic for vec",364 ));365 }366 let arg = args.first().expect("first arg");367368 let ty = match arg {369 GenericArgument::Type(ty) => ty,370 _ => {371 return Err(syn::Error::new(372 arg.span(),373 "expected first generic to be type",374 ))375 }376 };377378 let wrapped = AbiType::try_from(ty)?;379 Ok(Self::Vec(Box::new(wrapped)))380 } else {381 if !segment.arguments.is_empty() {382 return Err(syn::Error::new(383 segment.arguments.span(),384 "unexpected generic arguments for non-vec type",385 ));386 }387 Ok(Self::Plain(segment.ident.clone()))388 }389 }390 Type::Tuple(t) => {391 let mut out = Vec::with_capacity(t.elems.len());392 for el in t.elems.iter() {393 out.push(AbiType::try_from(el)?)394 }395 Ok(Self::Tuple(out))396 }397 _ => Err(syn::Error::new(398 value.span(),399 "unexpected type, only arrays, plain types and tuples are supported",400 )),401 }402 }403 fn is_value(&self) -> bool {404 matches!(self, Self::Plain(v) if v == "value")405 }406 fn is_caller(&self) -> bool {407 matches!(self, Self::Plain(v) if v == "caller")408 }409 fn is_special(&self) -> bool {410 self.is_caller() || self.is_value()411 }412 fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {413 match self {414 AbiType::Plain(t) => {415 write!(buf, "{}", t)416 }417 AbiType::Tuple(t) => {418 write!(buf, "(")?;419 for (i, t) in t.iter().enumerate() {420 if i != 0 {421 write!(buf, ",")?;422 }423 t.selector_ty_buf(buf)?;424 }425 write!(buf, ")")426 }427 AbiType::Vec(v) => {428 v.selector_ty_buf(buf)?;429 write!(buf, "[]")430 }431 AbiType::Array(v, len) => {432 v.selector_ty_buf(buf)?;433 write!(buf, "[{}]", len)434 }435 }436 }437 fn selector_ty(&self) -> String {438 let mut out = String::new();439 self.selector_ty_buf(&mut out).expect("no fmt error");440 out441 }442}443impl ToTokens for AbiType {444 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {445 match self {446 AbiType::Plain(t) => tokens.extend(quote! {#t}),447 AbiType::Tuple(t) => {448 tokens.extend(quote! {(449 #(#t),*450 )});451 }452 AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),453 AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),454 }455 }456}457458struct MethodArg {459 name: Ident,460 camel_name: String,461 ty: AbiType,462}463impl MethodArg {464 fn try_from(value: &PatType) -> syn::Result<Self> {465 let name = parse_ident_from_pat(&value.pat)?.clone();466 Ok(Self {467 camel_name: cases::camelcase::to_camel_case(&name.to_string()),468 name,469 ty: AbiType::try_maybe_special_from(&value.ty)?,470 })471 }472 fn is_value(&self) -> bool {473 self.ty.is_value()474 }475 fn is_caller(&self) -> bool {476 self.ty.is_caller()477 }478 fn is_special(&self) -> bool {479 self.ty.is_special()480 }481 fn selector_ty(&self) -> String {482 assert!(!self.is_special());483 self.ty.selector_ty()484 }485486 fn expand_call_def(&self) -> proc_macro2::TokenStream {487 assert!(!self.is_special());488 let name = &self.name;489 let ty = &self.ty;490491 quote! {492 #name: #ty493 }494 }495496 fn expand_parse(&self) -> proc_macro2::TokenStream {497 assert!(!self.is_special());498 let name = &self.name;499 quote! {500 #name: reader.abi_read()?501 }502 }503504 fn expand_call_arg(&self) -> proc_macro2::TokenStream {505 if self.is_value() {506 quote! {507 c.value.clone()508 }509 } else if self.is_caller() {510 quote! {511 c.caller.clone()512 }513 } else {514 let name = &self.name;515 quote! {516 #name517 }518 }519 }520521 fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {522 let camel_name = &self.camel_name.to_string();523 let ty = &self.ty;524 quote! {525 <NamedArgument<#ty>>::new(#camel_name)526 }527 }528}529530#[derive(PartialEq)]531enum Mutability {532 Mutable,533 View,534 Pure,535}536537/// Group all keywords for this macro. Usage example:538/// #[solidity_interface(name = "B", inline_is(A))]539mod kw {540 syn::custom_keyword!(weight);541542 syn::custom_keyword!(via);543 syn::custom_keyword!(returns);544 syn::custom_keyword!(name);545 syn::custom_keyword!(is);546 syn::custom_keyword!(inline_is);547 syn::custom_keyword!(events);548 syn::custom_keyword!(expect_selector);549550 syn::custom_keyword!(rename_selector);551}552553/// Rust methods are parsed into this structure when Solidity code is generated554struct Method {555 name: Ident,556 camel_name: String,557 pascal_name: Ident,558 screaming_name: Ident,559 selector_str: String,560 selector: u32,561 args: Vec<MethodArg>,562 has_normal_args: bool,563 has_value_args: bool,564 mutability: Mutability,565 result: Type,566 weight: Option<Expr>,567 docs: Vec<String>,568}569impl Method {570 fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {571 let mut info = MethodInfo {572 rename_selector: None,573 };574 let mut docs = Vec::new();575 let mut weight = None;576 for attr in &value.attrs {577 let ident = parse_ident_from_path(&attr.path, false)?;578 if ident == "solidity" {579 info = attr.parse_args::<MethodInfo>()?;580 } else if ident == "doc" {581 let args = attr.parse_meta().unwrap();582 let value = match args {583 Meta::NameValue(MetaNameValue {584 lit: Lit::Str(str), ..585 }) => str.value(),586 _ => unreachable!(),587 };588 docs.push(value);589 } else if ident == "weight" {590 weight = Some(attr.parse_args::<Expr>()?);591 }592 }593 let ident = &value.sig.ident;594 let ident_str = ident.to_string();595 if !cases::snakecase::is_snake_case(&ident_str) {596 return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));597 }598599 let mut mutability = Mutability::Pure;600601 if let Some(FnArg::Receiver(receiver)) = value602 .sig603 .inputs604 .iter()605 .find(|arg| matches!(arg, FnArg::Receiver(_)))606 {607 if receiver.reference.is_none() {608 return Err(syn::Error::new(609 receiver.span(),610 "receiver should be by ref",611 ));612 }613 if receiver.mutability.is_some() {614 mutability = Mutability::Mutable;615 } else {616 mutability = Mutability::View;617 }618 }619 let mut args = Vec::new();620 for typ in value621 .sig622 .inputs623 .iter()624 .filter(|arg| matches!(arg, FnArg::Typed(_)))625 {626 let typ = match typ {627 FnArg::Typed(typ) => typ,628 _ => unreachable!(),629 };630 args.push(MethodArg::try_from(typ)?);631 }632633 if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {634 return Err(syn::Error::new(635 args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),636 "payable function should be mutable",637 ));638 }639640 let result = match &value.sig.output {641 ReturnType::Type(_, ty) => ty,642 _ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),643 };644 let result = parse_result_ok(result)?;645646 let camel_name = info647 .rename_selector648 .unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));649 let mut selector_str = camel_name.clone();650 selector_str.push('(');651 let mut has_normal_args = false;652 for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {653 if i != 0 {654 selector_str.push(',');655 }656 write!(selector_str, "{}", arg.selector_ty()).unwrap();657 has_normal_args = true;658 }659 let has_value_args = args.iter().any(|a| a.is_value());660 selector_str.push(')');661 let selector = fn_selector_str(&selector_str);662663 Ok(Self {664 name: ident.clone(),665 camel_name,666 pascal_name: snake_ident_to_pascal(ident),667 screaming_name: snake_ident_to_screaming(ident),668 selector_str,669 selector,670 args,671 has_normal_args,672 has_value_args,673 mutability,674 result: result.clone(),675 weight,676 docs,677 })678 }679 fn expand_call_def(&self) -> proc_macro2::TokenStream {680 let defs = self681 .args682 .iter()683 .filter(|a| !a.is_special())684 .map(|a| a.expand_call_def());685 let pascal_name = &self.pascal_name;686 let docs = &self.docs;687688 if self.has_normal_args {689 quote! {690 #(#[doc = #docs])*691 #[allow(missing_docs)]692 #pascal_name {693 #(694 #defs,695 )*696 }697 }698 } else {699 quote! {#pascal_name}700 }701 }702703 fn expand_const(&self) -> proc_macro2::TokenStream {704 let screaming_name = &self.screaming_name;705 let selector = u32::to_be_bytes(self.selector);706 let selector_str = &self.selector_str;707 quote! {708 #[doc = #selector_str]709 const #screaming_name: ::evm_coder::types::bytes4 = [#(#selector,)*];710 }711 }712713 fn expand_interface_id(&self) -> proc_macro2::TokenStream {714 let screaming_name = &self.screaming_name;715 quote! {716 interface_id ^= u32::from_be_bytes(Self::#screaming_name);717 }718 }719720 fn expand_parse(&self) -> proc_macro2::TokenStream {721 let pascal_name = &self.pascal_name;722 let screaming_name = &self.screaming_name;723 if self.has_normal_args {724 let parsers = self725 .args726 .iter()727 .filter(|a| !a.is_special())728 .map(|a| a.expand_parse());729 quote! {730 Self::#screaming_name => return Ok(Some(Self::#pascal_name {731 #(732 #parsers,733 )*734 }))735 }736 } else {737 quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }738 }739 }740741 fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {742 let pascal_name = &self.pascal_name;743 let name = &self.name;744745 let matcher = if self.has_normal_args {746 let names = self747 .args748 .iter()749 .filter(|a| !a.is_special())750 .map(|a| &a.name);751752 quote! {{753 #(754 #names,755 )*756 }}757 } else {758 quote! {}759 };760761 let receiver = match self.mutability {762 Mutability::Mutable | Mutability::View => quote! {self.},763 Mutability::Pure => quote! {Self::},764 };765 let args = self.args.iter().map(|a| a.expand_call_arg());766767 quote! {768 #call_name::#pascal_name #matcher => {769 let result = #receiver #name(770 #(771 #args,772 )*773 )?;774 (&result).to_result()775 }776 }777 }778779 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {780 let pascal_name = &self.pascal_name;781 if let Some(weight) = &self.weight {782 let matcher = if self.has_normal_args {783 let names = self784 .args785 .iter()786 .filter(|a| !a.is_special())787 .map(|a| &a.name);788789 quote! {{790 #(791 #names,792 )*793 }}794 } else {795 quote! {}796 };797 quote! {798 Self::#pascal_name #matcher => (#weight).into()799 }800 } else {801 let matcher = if self.has_normal_args {802 quote! {{..}}803 } else {804 quote! {}805 };806 quote! {807 Self::#pascal_name #matcher => ().into()808 }809 }810 }811812 fn expand_solidity_function(&self) -> proc_macro2::TokenStream {813 let camel_name = &self.camel_name;814 let mutability = match self.mutability {815 Mutability::Mutable => quote! {SolidityMutability::Mutable},816 Mutability::View => quote! { SolidityMutability::View },817 Mutability::Pure => quote! {SolidityMutability::Pure},818 };819 let result = &self.result;820821 let args = self822 .args823 .iter()824 .filter(|a| !a.is_special())825 .map(MethodArg::expand_solidity_argument);826 let docs = &self.docs;827 let selector_str = &self.selector_str;828 let selector = self.selector;829 let is_payable = self.has_value_args;830 quote! {831 SolidityFunction {832 docs: &[#(#docs),*],833 selector_str: #selector_str,834 selector: #selector,835 name: #camel_name,836 mutability: #mutability,837 is_payable: #is_payable,838 args: (839 #(840 #args,841 )*842 ),843 result: <UnnamedArgument<#result>>::default(),844 }845 }846 }847}848849fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {850 if gen.params.is_empty() {851 return quote! {};852 }853 let params = gen.params.iter().map(|p| match p {854 syn::GenericParam::Type(id) => {855 let v = &id.ident;856 quote! {#v}857 }858 syn::GenericParam::Lifetime(lt) => {859 let v = <.lifetime;860 quote! {#v}861 }862 syn::GenericParam::Const(c) => {863 let i = &c.ident;864 quote! {#i}865 }866 });867 quote! { #(#params),* }868}869fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {870 if gen.params.is_empty() {871 return quote! {};872 }873 let list = generics_list(gen);874 quote! { <#list> }875}876fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {877 let list = generics_list(gen);878 if gen.params.len() == 1 {879 quote! {#list}880 } else {881 quote! { (#list) }882 }883}884885pub struct SolidityInterface {886 generics: Generics,887 name: Box<syn::Type>,888 info: InterfaceInfo,889 methods: Vec<Method>,890 docs: Vec<String>,891}892impl SolidityInterface {893 pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {894 let mut methods = Vec::new();895896 for item in &value.items {897 if let ImplItem::Method(method) = item {898 methods.push(Method::try_from(method)?)899 }900 }901 let mut docs = vec![];902 for attr in &value.attrs {903 let ident = parse_ident_from_path(&attr.path, false)?;904 if ident == "doc" {905 let args = attr.parse_meta().unwrap();906 let value = match args {907 Meta::NameValue(MetaNameValue {908 lit: Lit::Str(str), ..909 }) => str.value(),910 _ => unreachable!(),911 };912 docs.push(value);913 }914 }915 Ok(Self {916 generics: value.generics.clone(),917 name: value.self_ty.clone(),918 info,919 methods,920 docs,921 })922 }923 pub fn expand(self) -> proc_macro2::TokenStream {924 let name = self.name;925926 let solidity_name = self.info.name.to_string();927 let call_name = pascal_ident_to_call(&self.info.name);928 let generics = self.generics;929 let gen_ref = generics_reference(&generics);930 let gen_data = generics_data(&generics);931 let gen_where = &generics.where_clause;932933 let call_sub = self934 .info935 .inline_is936 .0937 .iter()938 .chain(self.info.is.0.iter())939 .map(|c| Is::expand_call_def(c, &gen_ref));940 let call_parse = self941 .info942 .inline_is943 .0944 .iter()945 .chain(self.info.is.0.iter())946 .map(|is| Is::expand_parse(is, &gen_ref));947 let call_variants = self948 .info949 .inline_is950 .0951 .iter()952 .chain(self.info.is.0.iter())953 .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));954 let weight_variants = self955 .info956 .inline_is957 .0958 .iter()959 .chain(self.info.is.0.iter())960 .map(Is::expand_variant_weight);961962 let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);963 let supports_interface = self964 .info965 .is966 .0967 .iter()968 .map(|is| Is::expand_supports_interface(is, &gen_ref));969970 let calls = self.methods.iter().map(Method::expand_call_def);971 let consts = self.methods.iter().map(Method::expand_const);972 let interface_id = self.methods.iter().map(Method::expand_interface_id);973 let parsers = self.methods.iter().map(Method::expand_parse);974 let call_variants_this = self975 .methods976 .iter()977 .map(|m| Method::expand_variant_call(m, &call_name));978 let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);979 let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);980981 // TODO: Inline inline_is982 let solidity_is = self983 .info984 .is985 .0986 .iter()987 .chain(self.info.inline_is.0.iter())988 .map(|is| is.name.to_string());989 let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());990 let solidity_generators = self991 .info992 .is993 .0994 .iter()995 .chain(self.info.inline_is.0.iter())996 .map(|is| Is::expand_generator(is, &gen_ref));997 let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);998999 let docs = &self.docs;10001001 if let Some(expect_selector) = &self.info.expect_selector {1002 if !self.info.inline_is.0.is_empty() {1003 return syn::Error::new(1004 name.span(),1005 "expect_selector is not compatible with inline_is",1006 )1007 .to_compile_error();1008 }1009 let selector = self1010 .methods1011 .iter()1012 .map(|m| m.selector)1013 .fold(0, |a, b| a ^ b);10141015 if *expect_selector != selector {1016 let mut methods = String::new();1017 for meth in self.methods.iter() {1018 write!(methods, "\n- {}", meth.selector_str).expect("write to string");1019 }1020 return syn::Error::new(name.span(), format!("expected selector mismatch, expected {expect_selector:0>8x}, but implementation has {selector:0>8x}{methods}")).to_compile_error();1021 }1022 }1023 // let methods = self.methods.iter().map(Method::solidity_def);10241025 quote! {1026 #[derive(Debug)]1027 #(#[doc = #docs])*1028 pub enum #call_name #gen_ref {1029 /// Inherited method1030 ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),1031 #(1032 #calls,1033 )*1034 #(1035 #call_sub,1036 )*1037 }1038 impl #gen_ref #call_name #gen_ref {1039 #(1040 #consts1041 )*1042 /// Return this call ERC165 selector1043 pub fn interface_id() -> ::evm_coder::types::bytes4 {1044 let mut interface_id = 0;1045 #(#interface_id)*1046 #(#inline_interface_id)*1047 u32::to_be_bytes(interface_id)1048 }1049 /// Generate solidity definitions for methods described in this interface1050 pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {1051 use evm_coder::solidity::*;1052 use core::fmt::Write;1053 let interface = SolidityInterface {1054 docs: &[#(#docs),*],1055 name: #solidity_name,1056 selector: Self::interface_id(),1057 is: &["Dummy", "ERC165", #(1058 #solidity_is,1059 )* #(1060 #solidity_events_is,1061 )* ],1062 functions: (#(1063 #solidity_functions,1064 )*),1065 };10661067 let mut out = ::evm_coder::types::string::new();1068 if #solidity_name.starts_with("Inline") {1069 out.push_str("/// @dev inlined interface\n");1070 }1071 let _ = interface.format(is_impl, &mut out, tc);1072 tc.collect(out);1073 #(1074 #solidity_event_generators1075 )*1076 #(1077 #solidity_generators1078 )*1079 if is_impl {1080 tc.collect("/// @dev common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());1081 } else {1082 tc.collect("/// @dev common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());1083 }1084 }1085 }1086 impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1087 fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1088 use ::evm_coder::abi::AbiRead;1089 match method_id {1090 ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1091 ::evm_coder::ERC165Call::parse(method_id, reader)?1092 .map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1093 ),1094 #(1095 #parsers,1096 )*1097 _ => {},1098 }1099 #(1100 #call_parse1101 )else*1102 return Ok(None);1103 }1104 }1105 impl #generics #call_name #gen_ref1106 #gen_where1107 {1108 /// Is this contract implements specified ERC165 selector1109 pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1110 interface_id != u32::to_be_bytes(0xffffff) && (1111 interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1112 interface_id == Self::interface_id()1113 #(1114 || #supports_interface1115 )*1116 )1117 }1118 }1119 impl #generics ::evm_coder::Weighted for #call_name #gen_ref1120 #gen_where1121 {1122 #[allow(unused_variables)]1123 fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1124 match self {1125 #(1126 #weight_variants,1127 )*1128 // TODO: It should be very cheap, but not free1129 Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1130 #(1131 #weight_variants_this,1132 )*1133 }1134 }1135 }1136 impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1137 #gen_where1138 {1139 #[allow(unreachable_code)] // In case of no inner calls1140 fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1141 use ::evm_coder::abi::AbiWrite;1142 match c.call {1143 #(1144 #call_variants,1145 )*1146 #call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1147 let mut writer = ::evm_coder::abi::AbiWriter::default();1148 writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1149 return Ok(writer.into());1150 }1151 _ => {},1152 }1153 let mut writer = ::evm_coder::abi::AbiWriter::default();1154 match c.call {1155 #(1156 #call_variants_this,1157 )*1158 _ => Err(::evm_coder::execution::Error::from("method is not available").into()),1159 }1160 }1161 }1162 }1163 }1164}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#![allow(dead_code)]1819// NOTE: In order to understand this Rust macro better, first read this chapter20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html2223use quote::{quote, ToTokens};24use inflector::cases;25use std::fmt::Write;26use syn::{27 Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,28 MetaNameValue, PatType, PathArguments, ReturnType, Type,29 spanned::Spanned,30 parse::{Parse, ParseStream},31 parenthesized, Token, LitInt, LitStr,32};3334use crate::{35 fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,36 parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,37 snake_ident_to_screaming,38};3940struct Is {41 name: Ident,42 pascal_call_name: Ident,43 snake_call_name: Ident,44 via: Option<(Type, Ident)>,45 condition: Option<Expr>,46}47impl Is {48 fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {49 let name = &self.name;50 let pascal_call_name = &self.pascal_call_name;51 quote! {52 #name(#pascal_call_name #gen_ref)53 }54 }5556 fn expand_interface_id(&self) -> proc_macro2::TokenStream {57 let pascal_call_name = &self.pascal_call_name;58 quote! {59 interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());60 }61 }6263 fn expand_supports_interface(64 &self,65 generics: &proc_macro2::TokenStream,66 ) -> proc_macro2::TokenStream {67 let pascal_call_name = &self.pascal_call_name;68 let condition = self.condition.as_ref().map(|condition| {69 quote! {70 (#condition) &&71 }72 });73 quote! {74 #condition <#pascal_call_name #generics>::supports_interface(this, interface_id)75 }76 }7778 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {79 let name = &self.name;80 quote! {81 Self::#name(call) => call.weight()82 }83 }8485 fn expand_variant_call(86 &self,87 call_name: &proc_macro2::Ident,88 generics: &proc_macro2::TokenStream,89 ) -> proc_macro2::TokenStream {90 let name = &self.name;91 let pascal_call_name = &self.pascal_call_name;92 let via_typ = self93 .via94 .as_ref()95 .map(|(t, _)| quote! {#t})96 .unwrap_or_else(|| quote! {Self});97 let via_map = self98 .via99 .as_ref()100 .map(|(_, i)| quote! {.#i()})101 .unwrap_or_default();102 let condition = self.condition.as_ref().map(|condition| {103 quote! {104 if ({let this = &self; (#condition)})105 }106 });107 quote! {108 #call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {109 call,110 caller: c.caller,111 value: c.value,112 })113 }114 }115116 fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {117 let name = &self.name;118 let pascal_call_name = &self.pascal_call_name;119 quote! {120 if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {121 return Ok(Some(Self::#name(parsed_call)))122 }123 }124 }125126 fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {127 let pascal_call_name = &self.pascal_call_name;128 quote! {129 <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);130 }131 }132133 fn expand_event_generator(&self) -> proc_macro2::TokenStream {134 let name = &self.name;135 quote! {136 #name::generate_solidity_interface(tc, is_impl);137 }138 }139}140141#[derive(Default)]142struct IsList(Vec<Is>);143impl Parse for IsList {144 fn parse(input: ParseStream) -> syn::Result<Self> {145 let mut out = vec![];146 loop {147 if input.is_empty() {148 break;149 }150 let name = input.parse::<Ident>()?;151 let lookahead = input.lookahead1();152153 let mut condition: Option<Expr> = None;154 let mut via: Option<(Type, Ident)> = None;155156 if lookahead.peek(syn::token::Paren) {157 let contents;158 parenthesized!(contents in input);159 let input = contents;160161 while !input.is_empty() {162 let lookahead = input.lookahead1();163 if lookahead.peek(Token![if]) {164 input.parse::<Token![if]>()?;165 let contents;166 parenthesized!(contents in input);167 let contents = contents.parse::<Expr>()?;168169 if condition.replace(contents).is_some() {170 return Err(syn::Error::new(input.span(), "condition is already set"));171 }172 } else if lookahead.peek(kw::via) {173 input.parse::<kw::via>()?;174 let contents;175 parenthesized!(contents in input);176177 let method = contents.parse::<Ident>()?;178 contents.parse::<kw::returns>()?;179 let ty = contents.parse::<Type>()?;180181 if via.replace((ty, method)).is_some() {182 return Err(syn::Error::new(input.span(), "via is already set"));183 }184 } else {185 return Err(lookahead.error());186 }187188 if input.peek(Token![,]) {189 input.parse::<Token![,]>()?;190 } else if !input.is_empty() {191 return Err(syn::Error::new(input.span(), "expected end"));192 }193 }194 } else if lookahead.peek(Token![,]) || input.is_empty() {195 // Pass196 } else {197 return Err(lookahead.error());198 };199 out.push(Is {200 pascal_call_name: pascal_ident_to_call(&name),201 snake_call_name: pascal_ident_to_snake_call(&name),202 name,203 via,204 condition,205 });206 if input.peek(Token![,]) {207 input.parse::<Token![,]>()?;208 continue;209 } else {210 break;211 }212 }213 Ok(Self(out))214 }215}216217pub struct InterfaceInfo {218 name: Ident,219 is: IsList,220 inline_is: IsList,221 events: IsList,222 expect_selector: Option<u32>,223}224impl Parse for InterfaceInfo {225 fn parse(input: ParseStream) -> syn::Result<Self> {226 let mut name = None;227 let mut is = None;228 let mut inline_is = None;229 let mut events = None;230 let mut expect_selector = None;231 // TODO: create proc-macro to optimize proc-macro boilerplate? :D232 loop {233 let lookahead = input.lookahead1();234 if lookahead.peek(kw::name) {235 let k = input.parse::<kw::name>()?;236 input.parse::<Token![=]>()?;237 if name.replace(input.parse::<Ident>()?).is_some() {238 return Err(syn::Error::new(k.span(), "name is already set"));239 }240 } else if lookahead.peek(kw::is) {241 let k = input.parse::<kw::is>()?;242 let contents;243 parenthesized!(contents in input);244 if is.replace(contents.parse::<IsList>()?).is_some() {245 return Err(syn::Error::new(k.span(), "is is already set"));246 }247 } else if lookahead.peek(kw::inline_is) {248 let k = input.parse::<kw::inline_is>()?;249 let contents;250 parenthesized!(contents in input);251 if inline_is.replace(contents.parse::<IsList>()?).is_some() {252 return Err(syn::Error::new(k.span(), "inline_is is already set"));253 }254 } else if lookahead.peek(kw::events) {255 let k = input.parse::<kw::events>()?;256 let contents;257 parenthesized!(contents in input);258 if events.replace(contents.parse::<IsList>()?).is_some() {259 return Err(syn::Error::new(k.span(), "events is already set"));260 }261 } else if lookahead.peek(kw::expect_selector) {262 let k = input.parse::<kw::expect_selector>()?;263 input.parse::<Token![=]>()?;264 let value = input.parse::<LitInt>()?;265 if expect_selector266 .replace(value.base10_parse::<u32>()?)267 .is_some()268 {269 return Err(syn::Error::new(k.span(), "expect_selector is already set"));270 }271 } else if input.is_empty() {272 break;273 } else {274 return Err(lookahead.error());275 }276 if input.peek(Token![,]) {277 input.parse::<Token![,]>()?;278 } else {279 break;280 }281 }282 Ok(Self {283 name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,284 is: is.unwrap_or_default(),285 inline_is: inline_is.unwrap_or_default(),286 events: events.unwrap_or_default(),287 expect_selector,288 })289 }290}291292struct MethodInfo {293 rename_selector: Option<String>,294 hide: bool,295}296impl Parse for MethodInfo {297 fn parse(input: ParseStream) -> syn::Result<Self> {298 let mut rename_selector = None;299 let mut hide = false;300 while !input.is_empty() {301 let lookahead = input.lookahead1();302 if lookahead.peek(kw::rename_selector) {303 let k = input.parse::<kw::rename_selector>()?;304 input.parse::<Token![=]>()?;305 if rename_selector306 .replace(input.parse::<LitStr>()?.value())307 .is_some()308 {309 return Err(syn::Error::new(k.span(), "rename_selector is already set"));310 }311 } else if lookahead.peek(kw::hide) {312 input.parse::<kw::hide>()?;313 hide = true;314 } else {315 return Err(lookahead.error());316 }317318 if input.peek(Token![,]) {319 input.parse::<Token![,]>()?;320 } else if !input.is_empty() {321 return Err(syn::Error::new(input.span(), "expected end"));322 }323 }324 Ok(Self {325 rename_selector,326 hide,327 })328 }329}330331enum AbiType {332 // type333 Plain(Ident),334 // (type1,type2)335 Tuple(Vec<AbiType>),336 // type[]337 Vec(Box<AbiType>),338 // type[20]339 Array(Box<AbiType>, usize),340}341impl AbiType {342 fn try_from(value: &Type) -> syn::Result<Self> {343 let value = Self::try_maybe_special_from(value)?;344 if value.is_special() {345 return Err(syn::Error::new(value.span(), "unexpected special type"));346 }347 Ok(value)348 }349 fn try_maybe_special_from(value: &Type) -> syn::Result<Self> {350 match value {351 Type::Array(arr) => {352 let wrapped = AbiType::try_from(&arr.elem)?;353 match &arr.len {354 Expr::Lit(l) => match &l.lit {355 Lit::Int(i) => {356 let num = i.base10_parse::<usize>()?;357 Ok(AbiType::Array(Box::new(wrapped), num as usize))358 }359 _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),360 },361 _ => Err(syn::Error::new(arr.len.span(), "should be literal")),362 }363 }364 Type::Path(_) => {365 let path = parse_path(value)?;366 let segment = parse_path_segment(path)?;367 if segment.ident == "Vec" {368 let args = match &segment.arguments {369 PathArguments::AngleBracketed(e) => e,370 _ => {371 return Err(syn::Error::new(372 segment.arguments.span(),373 "missing Vec generic",374 ))375 }376 };377 let args = &args.args;378 if args.len() != 1 {379 return Err(syn::Error::new(380 args.span(),381 "expected only one generic for vec",382 ));383 }384 let arg = args.first().expect("first arg");385386 let ty = match arg {387 GenericArgument::Type(ty) => ty,388 _ => {389 return Err(syn::Error::new(390 arg.span(),391 "expected first generic to be type",392 ))393 }394 };395396 let wrapped = AbiType::try_from(ty)?;397 Ok(Self::Vec(Box::new(wrapped)))398 } else {399 if !segment.arguments.is_empty() {400 return Err(syn::Error::new(401 segment.arguments.span(),402 "unexpected generic arguments for non-vec type",403 ));404 }405 Ok(Self::Plain(segment.ident.clone()))406 }407 }408 Type::Tuple(t) => {409 let mut out = Vec::with_capacity(t.elems.len());410 for el in t.elems.iter() {411 out.push(AbiType::try_from(el)?)412 }413 Ok(Self::Tuple(out))414 }415 _ => Err(syn::Error::new(416 value.span(),417 "unexpected type, only arrays, plain types and tuples are supported",418 )),419 }420 }421 fn is_value(&self) -> bool {422 matches!(self, Self::Plain(v) if v == "value")423 }424 fn is_caller(&self) -> bool {425 matches!(self, Self::Plain(v) if v == "caller")426 }427 fn is_special(&self) -> bool {428 self.is_caller() || self.is_value()429 }430 fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {431 match self {432 AbiType::Plain(t) => {433 write!(buf, "{}", t)434 }435 AbiType::Tuple(t) => {436 write!(buf, "(")?;437 for (i, t) in t.iter().enumerate() {438 if i != 0 {439 write!(buf, ",")?;440 }441 t.selector_ty_buf(buf)?;442 }443 write!(buf, ")")444 }445 AbiType::Vec(v) => {446 v.selector_ty_buf(buf)?;447 write!(buf, "[]")448 }449 AbiType::Array(v, len) => {450 v.selector_ty_buf(buf)?;451 write!(buf, "[{}]", len)452 }453 }454 }455 fn selector_ty(&self) -> String {456 let mut out = String::new();457 self.selector_ty_buf(&mut out).expect("no fmt error");458 out459 }460}461impl ToTokens for AbiType {462 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {463 match self {464 AbiType::Plain(t) => tokens.extend(quote! {#t}),465 AbiType::Tuple(t) => {466 tokens.extend(quote! {(467 #(#t),*468 )});469 }470 AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),471 AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),472 }473 }474}475476struct MethodArg {477 name: Ident,478 camel_name: String,479 ty: AbiType,480}481impl MethodArg {482 fn try_from(value: &PatType) -> syn::Result<Self> {483 let name = parse_ident_from_pat(&value.pat)?.clone();484 Ok(Self {485 camel_name: cases::camelcase::to_camel_case(&name.to_string()),486 name,487 ty: AbiType::try_maybe_special_from(&value.ty)?,488 })489 }490 fn is_value(&self) -> bool {491 self.ty.is_value()492 }493 fn is_caller(&self) -> bool {494 self.ty.is_caller()495 }496 fn is_special(&self) -> bool {497 self.ty.is_special()498 }499 fn selector_ty(&self) -> String {500 assert!(!self.is_special());501 self.ty.selector_ty()502 }503504 fn expand_call_def(&self) -> proc_macro2::TokenStream {505 assert!(!self.is_special());506 let name = &self.name;507 let ty = &self.ty;508509 quote! {510 #name: #ty511 }512 }513514 fn expand_parse(&self) -> proc_macro2::TokenStream {515 assert!(!self.is_special());516 let name = &self.name;517 quote! {518 #name: reader.abi_read()?519 }520 }521522 fn expand_call_arg(&self) -> proc_macro2::TokenStream {523 if self.is_value() {524 quote! {525 c.value.clone()526 }527 } else if self.is_caller() {528 quote! {529 c.caller.clone()530 }531 } else {532 let name = &self.name;533 quote! {534 #name535 }536 }537 }538539 fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {540 let camel_name = &self.camel_name.to_string();541 let ty = &self.ty;542 quote! {543 <NamedArgument<#ty>>::new(#camel_name)544 }545 }546}547548#[derive(PartialEq)]549enum Mutability {550 Mutable,551 View,552 Pure,553}554555/// Group all keywords for this macro. Usage example:556/// #[solidity_interface(name = "B", inline_is(A))]557mod kw {558 syn::custom_keyword!(weight);559560 syn::custom_keyword!(via);561 syn::custom_keyword!(returns);562 syn::custom_keyword!(name);563 syn::custom_keyword!(is);564 syn::custom_keyword!(inline_is);565 syn::custom_keyword!(events);566 syn::custom_keyword!(expect_selector);567568 syn::custom_keyword!(rename_selector);569 syn::custom_keyword!(hide);570}571572/// Rust methods are parsed into this structure when Solidity code is generated573struct Method {574 name: Ident,575 camel_name: String,576 pascal_name: Ident,577 screaming_name: Ident,578 selector_str: String,579 selector: u32,580 hide: bool,581 args: Vec<MethodArg>,582 has_normal_args: bool,583 has_value_args: bool,584 mutability: Mutability,585 result: Type,586 weight: Option<Expr>,587 docs: Vec<String>,588}589impl Method {590 fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {591 let mut info = MethodInfo {592 rename_selector: None,593 hide: false,594 };595 let mut docs = Vec::new();596 let mut weight = None;597 for attr in &value.attrs {598 let ident = parse_ident_from_path(&attr.path, false)?;599 if ident == "solidity" {600 info = attr.parse_args::<MethodInfo>()?;601 } else if ident == "doc" {602 let args = attr.parse_meta().unwrap();603 let value = match args {604 Meta::NameValue(MetaNameValue {605 lit: Lit::Str(str), ..606 }) => str.value(),607 _ => unreachable!(),608 };609 docs.push(value);610 } else if ident == "weight" {611 weight = Some(attr.parse_args::<Expr>()?);612 }613 }614 let ident = &value.sig.ident;615 let ident_str = ident.to_string();616 if !cases::snakecase::is_snake_case(&ident_str) {617 return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));618 }619620 let mut mutability = Mutability::Pure;621622 if let Some(FnArg::Receiver(receiver)) = value623 .sig624 .inputs625 .iter()626 .find(|arg| matches!(arg, FnArg::Receiver(_)))627 {628 if receiver.reference.is_none() {629 return Err(syn::Error::new(630 receiver.span(),631 "receiver should be by ref",632 ));633 }634 if receiver.mutability.is_some() {635 mutability = Mutability::Mutable;636 } else {637 mutability = Mutability::View;638 }639 }640 let mut args = Vec::new();641 for typ in value642 .sig643 .inputs644 .iter()645 .filter(|arg| matches!(arg, FnArg::Typed(_)))646 {647 let typ = match typ {648 FnArg::Typed(typ) => typ,649 _ => unreachable!(),650 };651 args.push(MethodArg::try_from(typ)?);652 }653654 if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {655 return Err(syn::Error::new(656 args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),657 "payable function should be mutable",658 ));659 }660661 let result = match &value.sig.output {662 ReturnType::Type(_, ty) => ty,663 _ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),664 };665 let result = parse_result_ok(result)?;666667 let camel_name = info668 .rename_selector669 .unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));670 let mut selector_str = camel_name.clone();671 selector_str.push('(');672 let mut has_normal_args = false;673 for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {674 if i != 0 {675 selector_str.push(',');676 }677 write!(selector_str, "{}", arg.selector_ty()).unwrap();678 has_normal_args = true;679 }680 let has_value_args = args.iter().any(|a| a.is_value());681 selector_str.push(')');682 let selector = fn_selector_str(&selector_str);683684 Ok(Self {685 name: ident.clone(),686 camel_name,687 pascal_name: snake_ident_to_pascal(ident),688 screaming_name: snake_ident_to_screaming(ident),689 selector_str,690 selector,691 hide: info.hide,692 args,693 has_normal_args,694 has_value_args,695 mutability,696 result: result.clone(),697 weight,698 docs,699 })700 }701 fn expand_call_def(&self) -> proc_macro2::TokenStream {702 let defs = self703 .args704 .iter()705 .filter(|a| !a.is_special())706 .map(|a| a.expand_call_def());707 let pascal_name = &self.pascal_name;708 let docs = &self.docs;709710 if self.has_normal_args {711 quote! {712 #(#[doc = #docs])*713 #[allow(missing_docs)]714 #pascal_name {715 #(716 #defs,717 )*718 }719 }720 } else {721 quote! {#pascal_name}722 }723 }724725 fn expand_const(&self) -> proc_macro2::TokenStream {726 let screaming_name = &self.screaming_name;727 let selector = u32::to_be_bytes(self.selector);728 let selector_str = &self.selector_str;729 quote! {730 #[doc = #selector_str]731 const #screaming_name: ::evm_coder::types::bytes4 = [#(#selector,)*];732 }733 }734735 fn expand_interface_id(&self) -> proc_macro2::TokenStream {736 let screaming_name = &self.screaming_name;737 quote! {738 interface_id ^= u32::from_be_bytes(Self::#screaming_name);739 }740 }741742 fn expand_parse(&self) -> proc_macro2::TokenStream {743 let pascal_name = &self.pascal_name;744 let screaming_name = &self.screaming_name;745 if self.has_normal_args {746 let parsers = self747 .args748 .iter()749 .filter(|a| !a.is_special())750 .map(|a| a.expand_parse());751 quote! {752 Self::#screaming_name => return Ok(Some(Self::#pascal_name {753 #(754 #parsers,755 )*756 }))757 }758 } else {759 quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }760 }761 }762763 fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {764 let pascal_name = &self.pascal_name;765 let name = &self.name;766767 let matcher = if self.has_normal_args {768 let names = self769 .args770 .iter()771 .filter(|a| !a.is_special())772 .map(|a| &a.name);773774 quote! {{775 #(776 #names,777 )*778 }}779 } else {780 quote! {}781 };782783 let receiver = match self.mutability {784 Mutability::Mutable | Mutability::View => quote! {self.},785 Mutability::Pure => quote! {Self::},786 };787 let args = self.args.iter().map(|a| a.expand_call_arg());788789 quote! {790 #call_name::#pascal_name #matcher => {791 let result = #receiver #name(792 #(793 #args,794 )*795 )?;796 (&result).to_result()797 }798 }799 }800801 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {802 let pascal_name = &self.pascal_name;803 if let Some(weight) = &self.weight {804 let matcher = if self.has_normal_args {805 let names = self806 .args807 .iter()808 .filter(|a| !a.is_special())809 .map(|a| &a.name);810811 quote! {{812 #(813 #names,814 )*815 }}816 } else {817 quote! {}818 };819 quote! {820 Self::#pascal_name #matcher => (#weight).into()821 }822 } else {823 let matcher = if self.has_normal_args {824 quote! {{..}}825 } else {826 quote! {}827 };828 quote! {829 Self::#pascal_name #matcher => ().into()830 }831 }832 }833834 fn expand_solidity_function(&self) -> proc_macro2::TokenStream {835 let camel_name = &self.camel_name;836 let mutability = match self.mutability {837 Mutability::Mutable => quote! {SolidityMutability::Mutable},838 Mutability::View => quote! { SolidityMutability::View },839 Mutability::Pure => quote! {SolidityMutability::Pure},840 };841 let result = &self.result;842843 let args = self844 .args845 .iter()846 .filter(|a| !a.is_special())847 .map(MethodArg::expand_solidity_argument);848 let docs = &self.docs;849 let selector_str = &self.selector_str;850 let selector = self.selector;851 let hide = self.hide;852 let is_payable = self.has_value_args;853 quote! {854 SolidityFunction {855 docs: &[#(#docs),*],856 selector_str: #selector_str,857 selector: #selector,858 hide: #hide,859 name: #camel_name,860 mutability: #mutability,861 is_payable: #is_payable,862 args: (863 #(864 #args,865 )*866 ),867 result: <UnnamedArgument<#result>>::default(),868 }869 }870 }871}872873fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {874 if gen.params.is_empty() {875 return quote! {};876 }877 let params = gen.params.iter().map(|p| match p {878 syn::GenericParam::Type(id) => {879 let v = &id.ident;880 quote! {#v}881 }882 syn::GenericParam::Lifetime(lt) => {883 let v = <.lifetime;884 quote! {#v}885 }886 syn::GenericParam::Const(c) => {887 let i = &c.ident;888 quote! {#i}889 }890 });891 quote! { #(#params),* }892}893fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {894 if gen.params.is_empty() {895 return quote! {};896 }897 let list = generics_list(gen);898 quote! { <#list> }899}900fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {901 let list = generics_list(gen);902 if gen.params.len() == 1 {903 quote! {#list}904 } else {905 quote! { (#list) }906 }907}908909pub struct SolidityInterface {910 generics: Generics,911 name: Box<syn::Type>,912 info: InterfaceInfo,913 methods: Vec<Method>,914 docs: Vec<String>,915}916impl SolidityInterface {917 pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {918 let mut methods = Vec::new();919920 for item in &value.items {921 if let ImplItem::Method(method) = item {922 methods.push(Method::try_from(method)?)923 }924 }925 let mut docs = vec![];926 for attr in &value.attrs {927 let ident = parse_ident_from_path(&attr.path, false)?;928 if ident == "doc" {929 let args = attr.parse_meta().unwrap();930 let value = match args {931 Meta::NameValue(MetaNameValue {932 lit: Lit::Str(str), ..933 }) => str.value(),934 _ => unreachable!(),935 };936 docs.push(value);937 }938 }939 Ok(Self {940 generics: value.generics.clone(),941 name: value.self_ty.clone(),942 info,943 methods,944 docs,945 })946 }947 pub fn expand(self) -> proc_macro2::TokenStream {948 let name = self.name;949950 let solidity_name = self.info.name.to_string();951 let call_name = pascal_ident_to_call(&self.info.name);952 let generics = self.generics;953 let gen_ref = generics_reference(&generics);954 let gen_data = generics_data(&generics);955 let gen_where = &generics.where_clause;956957 let call_sub = self958 .info959 .inline_is960 .0961 .iter()962 .chain(self.info.is.0.iter())963 .map(|c| Is::expand_call_def(c, &gen_ref));964 let call_parse = self965 .info966 .inline_is967 .0968 .iter()969 .chain(self.info.is.0.iter())970 .map(|is| Is::expand_parse(is, &gen_ref));971 let call_variants = self972 .info973 .inline_is974 .0975 .iter()976 .chain(self.info.is.0.iter())977 .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));978 let weight_variants = self979 .info980 .inline_is981 .0982 .iter()983 .chain(self.info.is.0.iter())984 .map(Is::expand_variant_weight);985986 let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);987 let supports_interface = self988 .info989 .is990 .0991 .iter()992 .map(|is| Is::expand_supports_interface(is, &gen_ref));993994 let calls = self.methods.iter().map(Method::expand_call_def);995 let consts = self.methods.iter().map(Method::expand_const);996 let interface_id = self.methods.iter().map(Method::expand_interface_id);997 let parsers = self.methods.iter().map(Method::expand_parse);998 let call_variants_this = self999 .methods1000 .iter()1001 .map(|m| Method::expand_variant_call(m, &call_name));1002 let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);1003 let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);10041005 // TODO: Inline inline_is1006 let solidity_is = self1007 .info1008 .is1009 .01010 .iter()1011 .chain(self.info.inline_is.0.iter())1012 .map(|is| is.name.to_string());1013 let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());1014 let solidity_generators = self1015 .info1016 .is1017 .01018 .iter()1019 .chain(self.info.inline_is.0.iter())1020 .map(|is| Is::expand_generator(is, &gen_ref));1021 let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);10221023 let docs = &self.docs;10241025 if let Some(expect_selector) = &self.info.expect_selector {1026 if !self.info.inline_is.0.is_empty() {1027 return syn::Error::new(1028 name.span(),1029 "expect_selector is not compatible with inline_is",1030 )1031 .to_compile_error();1032 }1033 let selector = self1034 .methods1035 .iter()1036 .map(|m| m.selector)1037 .fold(0, |a, b| a ^ b);10381039 if *expect_selector != selector {1040 let mut methods = String::new();1041 for meth in self.methods.iter() {1042 write!(methods, "\n- {}", meth.selector_str).expect("write to string");1043 }1044 return syn::Error::new(name.span(), format!("expected selector mismatch, expected {expect_selector:0>8x}, but implementation has {selector:0>8x}{methods}")).to_compile_error();1045 }1046 }1047 // let methods = self.methods.iter().map(Method::solidity_def);10481049 quote! {1050 #[derive(Debug)]1051 #(#[doc = #docs])*1052 pub enum #call_name #gen_ref {1053 /// Inherited method1054 ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),1055 #(1056 #calls,1057 )*1058 #(1059 #call_sub,1060 )*1061 }1062 impl #gen_ref #call_name #gen_ref {1063 #(1064 #consts1065 )*1066 /// Return this call ERC165 selector1067 pub fn interface_id() -> ::evm_coder::types::bytes4 {1068 let mut interface_id = 0;1069 #(#interface_id)*1070 #(#inline_interface_id)*1071 u32::to_be_bytes(interface_id)1072 }1073 /// Generate solidity definitions for methods described in this interface1074 pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {1075 use evm_coder::solidity::*;1076 use core::fmt::Write;1077 let interface = SolidityInterface {1078 docs: &[#(#docs),*],1079 name: #solidity_name,1080 selector: Self::interface_id(),1081 is: &["Dummy", "ERC165", #(1082 #solidity_is,1083 )* #(1084 #solidity_events_is,1085 )* ],1086 functions: (#(1087 #solidity_functions,1088 )*),1089 };10901091 let mut out = ::evm_coder::types::string::new();1092 if #solidity_name.starts_with("Inline") {1093 out.push_str("/// @dev inlined interface\n");1094 }1095 let _ = interface.format(is_impl, &mut out, tc);1096 tc.collect(out);1097 #(1098 #solidity_event_generators1099 )*1100 #(1101 #solidity_generators1102 )*1103 if is_impl {1104 tc.collect("/// @dev common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());1105 } else {1106 tc.collect("/// @dev common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());1107 }1108 }1109 }1110 impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1111 fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1112 use ::evm_coder::abi::AbiRead;1113 match method_id {1114 ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1115 ::evm_coder::ERC165Call::parse(method_id, reader)?1116 .map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1117 ),1118 #(1119 #parsers,1120 )*1121 _ => {},1122 }1123 #(1124 #call_parse1125 )else*1126 return Ok(None);1127 }1128 }1129 impl #generics #call_name #gen_ref1130 #gen_where1131 {1132 /// Is this contract implements specified ERC165 selector1133 pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1134 interface_id != u32::to_be_bytes(0xffffff) && (1135 interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1136 interface_id == Self::interface_id()1137 #(1138 || #supports_interface1139 )*1140 )1141 }1142 }1143 impl #generics ::evm_coder::Weighted for #call_name #gen_ref1144 #gen_where1145 {1146 #[allow(unused_variables)]1147 fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1148 match self {1149 #(1150 #weight_variants,1151 )*1152 // TODO: It should be very cheap, but not free1153 Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1154 #(1155 #weight_variants_this,1156 )*1157 }1158 }1159 }1160 impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1161 #gen_where1162 {1163 #[allow(unreachable_code)] // In case of no inner calls1164 fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1165 use ::evm_coder::abi::AbiWrite;1166 match c.call {1167 #(1168 #call_variants,1169 )*1170 #call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1171 let mut writer = ::evm_coder::abi::AbiWriter::default();1172 writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1173 return Ok(writer.into());1174 }1175 _ => {},1176 }1177 let mut writer = ::evm_coder::abi::AbiWriter::default();1178 match c.call {1179 #(1180 #call_variants_this,1181 )*1182 _ => Err(::evm_coder::execution::Error::from("method is not available").into()),1183 }1184 }1185 }1186 }1187 }1188}crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -225,7 +225,7 @@
pub trait SolidityArguments {
fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;
- fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;
+ fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result;
fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;
fn is_empty(&self) -> bool {
self.len() == 0
@@ -248,7 +248,7 @@
Ok(())
}
}
- fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {
+ fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {
Ok(())
}
fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
@@ -283,8 +283,8 @@
Ok(())
}
}
- fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {
- writeln!(writer, "\t\t{};", self.0)
+ fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {
+ writeln!(writer, "\t{prefix}\t{};", self.0)
}
fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
T::solidity_default(writer, tc)
@@ -318,8 +318,8 @@
Ok(())
}
}
- fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {
- writeln!(writer, "\t\t{};", self.1)
+ fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {
+ writeln!(writer, "\t{prefix}\t{};", self.1)
}
fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
T::solidity_default(writer, tc)
@@ -337,7 +337,7 @@
fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {
Ok(())
}
- fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {
+ fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {
Ok(())
}
fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {
@@ -365,9 +365,9 @@
)* );
Ok(())
}
- fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {
+ fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {
for_tuples!( #(
- Tuple.solidity_get(writer)?;
+ Tuple.solidity_get(prefix, writer)?;
)* );
Ok(())
}
@@ -418,6 +418,7 @@
pub docs: &'static [&'static str],
pub selector_str: &'static str,
pub selector: u32,
+ pub hide: bool,
pub name: &'static str,
pub args: A,
pub result: R,
@@ -431,16 +432,21 @@
writer: &mut impl fmt::Write,
tc: &TypeCollector,
) -> fmt::Result {
+ let hide_comment = self.hide.then(|| "// ").unwrap_or("");
for doc in self.docs {
- writeln!(writer, "\t///{}", doc)?;
+ writeln!(writer, "\t{hide_comment}///{}", doc)?;
}
writeln!(
writer,
- "\t/// @dev EVM selector for this function is: 0x{:0>8x},",
+ "\t{hide_comment}/// @dev EVM selector for this function is: 0x{:0>8x},",
self.selector
)?;
- writeln!(writer, "\t/// or in textual repr: {}", self.selector_str)?;
- write!(writer, "\tfunction {}(", self.name)?;
+ writeln!(
+ writer,
+ "\t{hide_comment}/// or in textual repr: {}",
+ self.selector_str
+ )?;
+ write!(writer, "\t{hide_comment}function {}(", self.name)?;
self.args.solidity_name(writer, tc)?;
write!(writer, ")")?;
if is_impl {
@@ -463,22 +469,25 @@
}
if is_impl {
writeln!(writer, " {{")?;
- writeln!(writer, "\t\trequire(false, stub_error);")?;
- self.args.solidity_get(writer)?;
+ writeln!(writer, "\t{hide_comment}\trequire(false, stub_error);")?;
+ self.args.solidity_get(hide_comment, writer)?;
match &self.mutability {
SolidityMutability::Pure => {}
- SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,
- SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,
+ SolidityMutability::View => writeln!(writer, "\t{hide_comment}\tdummy;")?,
+ SolidityMutability::Mutable => writeln!(writer, "\t{hide_comment}\tdummy = 0;")?,
}
if !self.result.is_empty() {
- write!(writer, "\t\treturn ")?;
+ write!(writer, "\t{hide_comment}\treturn ")?;
self.result.solidity_default(writer, tc)?;
writeln!(writer, ";")?;
}
- writeln!(writer, "\t}}")?;
+ writeln!(writer, "\t{hide_comment}}}")?;
} else {
writeln!(writer, ";")?;
}
+ if self.hide {
+ writeln!(writer, "// FORMATTING: FORCE NEWLINE")?;
+ }
Ok(())
}
}
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -9,7 +9,7 @@
traits::Get,
};
use sp_runtime::DispatchError;
-use up_data_structs::{CollectionId, CreateCollectionData};
+use up_data_structs::{CollectionId, CreateCollectionData, CollectionFlags};
use crate::{pallet::Config, CommonCollectionOperations, CollectionHandle};
@@ -80,6 +80,7 @@
sender: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError>;
/// Delete the collection.
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -592,6 +592,7 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
+ #[solidity(rename_selector = "changeCollectionOwner")]
fn set_owner(&mut self, caller: caller, new_owner: address) -> Result<void> {
self.consume_store_writes(1)?;
@@ -659,11 +660,6 @@
/// Keys.
pub mod key {
use super::*;
-
- /// Key "schemaName".
- pub fn schema_name() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"schemaName").expect(EXPECT_CONVERT_ERROR)
- }
/// Key "baseURI".
pub fn base_uri() -> up_data_structs::PropertyKey {
@@ -672,30 +668,17 @@
/// Key "url".
pub fn url() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"url").expect(EXPECT_CONVERT_ERROR)
+ property_key_from_bytes(b"URI").expect(EXPECT_CONVERT_ERROR)
}
/// Key "suffix".
pub fn suffix() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"suffix").expect(EXPECT_CONVERT_ERROR)
+ property_key_from_bytes(b"URISuffix").expect(EXPECT_CONVERT_ERROR)
}
/// Key "parentNft".
pub fn parent_nft() -> up_data_structs::PropertyKey {
property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)
- }
- }
-
- /// Values.
- pub mod value {
- use super::*;
-
- /// Value "ERC721Metadata".
- pub const ERC721_METADATA: &[u8] = b"ERC721Metadata";
-
- /// Value for [`ERC721_METADATA`].
- pub fn erc721() -> up_data_structs::PropertyValue {
- property_value_from_bytes(ERC721_METADATA).expect(EXPECT_CONVERT_ERROR)
}
}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -71,6 +71,7 @@
Collection,
RpcCollection,
CollectionFlags,
+ RpcCollectionFlags,
CollectionId,
CreateItemData,
MAX_TOKEN_PREFIX_LENGTH,
@@ -824,7 +825,11 @@
token_property_permissions,
properties,
read_only: flags.external,
- foreign: flags.foreign,
+
+ flags: RpcCollectionFlags {
+ foreign: flags.foreign,
+ erc721metadata: flags.erc721metadata,
+ },
})
}
}
pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -212,8 +212,9 @@
owner: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data, CollectionFlags::default())
+ <PalletCommon<T>>::init_collection(owner, payer, data, flags)
}
/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
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
@@ -18,7 +18,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -296,9 +296,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) public {
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -55,7 +55,7 @@
owner,
CollectionMode::NFT,
|owner: T::CrossAccountId, data| {
- <Pallet<T>>::init_collection(owner.clone(), owner, data, true)
+ <Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())
},
NonfungibleHandle::cast,
)
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -33,16 +33,12 @@
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_std::vec::Vec;
use pallet_common::{
- erc::{
- CommonEvmHandler, PrecompileResult, CollectionCall,
- static_property::{key, value as property_value},
- },
+ erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
CollectionHandle, CollectionPropertyPermissions,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
-use alloc::string::ToString;
use crate::{
AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
@@ -194,7 +190,7 @@
}
#[derive(ToLog)]
-pub enum ERC721MintableEvents {
+pub enum ERC721UniqueMintableEvents {
#[allow(dead_code)]
MintingFinished {},
}
@@ -204,15 +200,17 @@
#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]
impl<T: Config> NonfungibleHandle<T> {
/// @notice A descriptive name for a collection of NFTs in this contract
- fn name(&self) -> Result<string> {
- Ok(decode_utf16(self.name.iter().copied())
- .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
- .collect::<string>())
+ /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ #[solidity(hide, rename_selector = "name")]
+ fn name_proxy(&self) -> Result<string> {
+ self.name()
}
/// @notice An abbreviated name for NFTs in this contract
- fn symbol(&self) -> Result<string> {
- Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ #[solidity(hide, rename_selector = "symbol")]
+ fn symbol_proxy(&self) -> Result<string> {
+ self.symbol()
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
@@ -228,35 +226,38 @@
fn token_uri(&self, token_id: uint256) -> Result<string> {
let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
- if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {
- if !url.is_empty() {
- return Ok(url);
+ match get_token_property(self, token_id_u32, &key::url()).as_deref() {
+ Err(_) | Ok("") => (),
+ Ok(url) => {
+ return Ok(url.into());
}
- } else if !is_erc721_metadata_compatible::<T>(self.id) {
- return Err("tokenURI not set".into());
- }
+ };
- if let Some(base_uri) =
+ let base_uri =
pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())
- {
- if !base_uri.is_empty() {
- let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {
+ .map(BoundedVec::into_inner)
+ .map(string::from_utf8)
+ .transpose()
+ .map_err(|e| {
Error::Revert(alloc::format!(
"Can not convert value \"baseURI\" to string with error \"{}\"",
e
))
})?;
- if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {
- if !suffix.is_empty() {
- return Ok(base_uri + suffix.as_str());
- }
- }
- return Ok(base_uri + token_id.to_string().as_str());
+ let base_uri = match base_uri.as_deref() {
+ None | Some("") => {
+ return Ok("".into());
}
- }
+ Some(base_uri) => base_uri.into(),
+ };
- Ok("".into())
+ Ok(
+ match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {
+ Err(_) | Ok("") => base_uri,
+ Ok(suffix) => base_uri + suffix,
+ },
+ )
}
}
@@ -427,19 +428,33 @@
}
/// @title ERC721 minting logic.
-#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]
+#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]
impl<T: Config> NonfungibleHandle<T> {
fn minting_finished(&self) -> Result<bool> {
Ok(false)
}
/// @notice Function to mint token.
+ /// @param to The new owner
+ /// @return uint256 The id of the newly minted token
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {
+ let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into();
+ self.mint_check_id(caller, to, token_id)?;
+ Ok(token_id)
+ }
+
+ /// @notice Function to mint token.
/// @dev `tokenId` should be obtained with `nextTokenId` method,
/// unlike standard, you can't specify it manually
/// @param to The new owner
/// @param tokenId ID of the minted NFT
+ #[solidity(hide, rename_selector = "mint")]
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
+ fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let token_id: u32 = token_id.try_into()?;
@@ -470,14 +485,34 @@
}
/// @notice Function to mint token with the given tokenUri.
+ /// @param to The new owner
+ /// @param tokenUri Token URI that would be stored in the NFT properties
+ /// @return uint256 The id of the newly minted token
+ #[solidity(rename_selector = "mintWithTokenURI")]
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint_with_token_uri(
+ &mut self,
+ caller: caller,
+ to: address,
+ token_uri: string,
+ ) -> Result<uint256> {
+ let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into();
+ self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;
+ Ok(token_id)
+ }
+
+ /// @notice Function to mint token with the given tokenUri.
/// @dev `tokenId` should be obtained with `nextTokenId` method,
/// unlike standard, you can't specify it manually
/// @param to The new owner
/// @param tokenId ID of the minted NFT
/// @param tokenUri Token URI that would be stored in the NFT properties
- #[solidity(rename_selector = "mintWithTokenURI")]
+ #[solidity(hide, rename_selector = "mintWithTokenURI")]
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint_with_token_uri(
+ fn mint_with_token_uri_check_id(
&mut self,
caller: caller,
to: address,
@@ -550,17 +585,6 @@
Err("Property tokenURI not found".into())
}
-fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {
- if let Some(shema_name) =
- pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())
- {
- let shema_name = shema_name.into_inner();
- shema_name == property_value::ERC721_METADATA
- } else {
- false
- }
-}
-
fn get_token_permission<T: Config>(
collection_id: CollectionId,
key: &PropertyKey,
@@ -575,21 +599,23 @@
Error::Revert(alloc::format!("No permission for key {}", key))
})?;
Ok(a)
-}
-
-fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {
- if let Ok(token_property_permissions) =
- CollectionPropertyPermissions::<T>::try_get(collection_id)
- {
- return token_property_permissions.contains_key(key);
- }
-
- false
}
/// @title Unique extensions for ERC721.
#[solidity_interface(name = ERC721UniqueExtensions)]
impl<T: Config> NonfungibleHandle<T> {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ fn name(&self) -> Result<string> {
+ Ok(decode_utf16(self.name.iter().copied())
+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+ .collect::<string>())
+ }
+
+ /// @notice An abbreviated name for NFTs in this contract
+ fn symbol(&self) -> Result<string> {
+ Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ }
+
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -642,6 +668,7 @@
/// should be obtained with `nextTokenId` method
/// @param to The new owner
/// @param tokenIds IDs of the minted NFTs
+ // #[solidity(hide)]
#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]
fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -678,7 +705,7 @@
/// numbers and first number should be obtained with `nextTokenId` method
/// @param to The new owner
/// @param tokens array of pairs of token ID and token URI for minted tokens
- #[solidity(rename_selector = "mintBulkWithTokenURI")]
+ #[solidity(/*hide,*/ rename_selector = "mintBulkWithTokenURI")]
#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]
fn mint_bulk_with_token_uri(
&mut self,
@@ -731,11 +758,11 @@
name = UniqueNFT,
is(
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata(if(this.flags.erc721metadata)),
Collection(via(common_mut returns CollectionHandle<T>)),
TokenProperties,
)
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -295,6 +295,7 @@
&mut self.0
}
}
+
impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
self.0.recorder()
@@ -407,17 +408,9 @@
owner: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
- is_external: bool,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(
- owner,
- payer,
- data,
- CollectionFlags {
- external: is_external,
- ..Default::default()
- },
- )
+ <PalletCommon<T>>::init_collection(owner, payer, data, flags)
}
/// Destroy NFT collection
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
@@ -91,7 +91,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -369,9 +369,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) public {
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
@@ -384,6 +384,49 @@
uint256 field_1;
}
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+contract ERC721Metadata is Dummy, ERC165 {
+ // /// @notice A descriptive name for a collection of NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x06fdde03,
+ // /// or in textual repr: name()
+ // function name() public view returns (string memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return "";
+ // }
+
+ // /// @notice An abbreviated name for NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x95d89b41,
+ // /// or in textual repr: symbol()
+ // function symbol() public view returns (string memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return "";
+ // }
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token has a `url` property and it is not empty, it is returned.
+ /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+ /// If the collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+ /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) public view returns (string memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return "";
+ }
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
contract ERC721Burnable is Dummy, ERC165 {
@@ -401,13 +444,13 @@
}
/// @dev inlined interface
-contract ERC721MintableEvents {
+contract ERC721UniqueMintableEvents {
event MintingFinished();
}
/// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-contract ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+contract ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
/// @dev EVM selector for this function is: 0x05d2035b,
/// or in textual repr: mintingFinished()
function mintingFinished() public view returns (bool) {
@@ -417,41 +460,63 @@
}
/// @notice Function to mint token.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted NFT
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 tokenId) public returns (bool) {
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x6a627842,
+ /// or in textual repr: mint(address)
+ function mint(address to) public returns (uint256) {
require(false, stub_error);
to;
- tokenId;
dummy = 0;
- return false;
+ return 0;
}
+ // /// @notice Function to mint token.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted NFT
+ // /// @dev EVM selector for this function is: 0x40c10f19,
+ // /// or in textual repr: mint(address,uint256)
+ // function mint(address to, uint256 tokenId) public returns (bool) {
+ // require(false, stub_error);
+ // to;
+ // tokenId;
+ // dummy = 0;
+ // return false;
+ // }
+
/// @notice Function to mint token with the given tokenUri.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted NFT
/// @param tokenUri Token URI that would be stored in the NFT properties
- /// @dev EVM selector for this function is: 0x50bb4e7f,
- /// or in textual repr: mintWithTokenURI(address,uint256,string)
- function mintWithTokenURI(
- address to,
- uint256 tokenId,
- string memory tokenUri
- ) public returns (bool) {
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x45c17782,
+ /// or in textual repr: mintWithTokenURI(address,string)
+ function mintWithTokenURI(address to, string memory tokenUri) public returns (uint256) {
require(false, stub_error);
to;
- tokenId;
tokenUri;
dummy = 0;
- return false;
+ return 0;
}
+ // /// @notice Function to mint token with the given tokenUri.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted NFT
+ // /// @param tokenUri Token URI that would be stored in the NFT properties
+ // /// @dev EVM selector for this function is: 0x50bb4e7f,
+ // /// or in textual repr: mintWithTokenURI(address,uint256,string)
+ // function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) public returns (bool) {
+ // require(false, stub_error);
+ // to;
+ // tokenId;
+ // tokenUri;
+ // dummy = 0;
+ // return false;
+ // }
+
/// @dev Not implemented
/// @dev EVM selector for this function is: 0x7d64bcb4,
/// or in textual repr: finishMinting()
@@ -463,8 +528,26 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xd74d154f
+/// @dev the ERC-165 identifier for this interface is 0x4468500d
contract ERC721UniqueExtensions is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -525,7 +608,7 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) public returns (bool) {
require(false, stub_error);
to;
tokens;
@@ -535,7 +618,7 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -579,48 +662,7 @@
return 0;
}
}
-
-/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
-/// @dev See https://eips.ethereum.org/EIPS/eip-721
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-contract ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of NFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @notice An abbreviated name for NFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token has a `url` property and it is not empty, it is returned.
- /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
- /// If the collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
- /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) public view returns (string memory) {
- require(false, stub_error);
- tokenId;
- dummy;
- return "";
- }
-}
-
/// @dev inlined interface
contract ERC721Events {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -766,11 +808,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata,
Collection,
TokenProperties
{}
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -1448,7 +1448,15 @@
data: CreateCollectionData<T::AccountId>,
properties: impl Iterator<Item = Property>,
) -> Result<CollectionId, DispatchError> {
- let collection_id = <PalletNft<T>>::init_collection(sender.clone(), sender, data, true);
+ let collection_id = <PalletNft<T>>::init_collection(
+ sender.clone(),
+ sender,
+ data,
+ up_data_structs::CollectionFlags {
+ external: true,
+ ..Default::default()
+ },
+ );
if let Err(DispatchError::Arithmetic(_)) = &collection_id {
return Err(<Error<T>>::NoAvailableCollectionId.into());
pallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -254,7 +254,10 @@
cross_sender.clone(),
cross_sender.clone(),
data,
- true,
+ up_data_structs::CollectionFlags {
+ external: true,
+ ..Default::default()
+ },
);
if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,19 +21,15 @@
extern crate alloc;
-use alloc::string::ToString;
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
-use frame_support::BoundedBTreeMap;
+use frame_support::{BoundedBTreeMap, BoundedVec};
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions,
- erc::{
- CommonEvmHandler, CollectionCall,
- static_property::{key, value as property_value},
- },
+ erc::{CommonEvmHandler, CollectionCall, static_property::key},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -191,7 +187,7 @@
}
#[derive(ToLog)]
-pub enum ERC721MintableEvents {
+pub enum ERC721UniqueMintableEvents {
/// @dev Not supported
#[allow(dead_code)]
MintingFinished {},
@@ -199,16 +195,18 @@
#[solidity_interface(name = ERC721Metadata)]
impl<T: Config> RefungibleHandle<T> {
- /// @notice A descriptive name for a collection of RFTs in this contract
- fn name(&self) -> Result<string> {
- Ok(decode_utf16(self.name.iter().copied())
- .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
- .collect::<string>())
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ #[solidity(hide, rename_selector = "name")]
+ fn name_proxy(&self) -> Result<string> {
+ self.name()
}
- /// @notice An abbreviated name for RFTs in this contract
- fn symbol(&self) -> Result<string> {
- Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ #[solidity(hide, rename_selector = "symbol")]
+ fn symbol_proxy(&self) -> Result<string> {
+ self.symbol()
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
@@ -224,35 +222,38 @@
fn token_uri(&self, token_id: uint256) -> Result<string> {
let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
- if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {
- if !url.is_empty() {
- return Ok(url);
+ match get_token_property(self, token_id_u32, &key::url()).as_deref() {
+ Err(_) | Ok("") => (),
+ Ok(url) => {
+ return Ok(url.into());
}
- } else if !is_erc721_metadata_compatible::<T>(self.id) {
- return Err("tokenURI not set".into());
- }
+ };
- if let Some(base_uri) =
+ let base_uri =
pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())
- {
- if !base_uri.is_empty() {
- let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {
+ .map(BoundedVec::into_inner)
+ .map(string::from_utf8)
+ .transpose()
+ .map_err(|e| {
Error::Revert(alloc::format!(
"Can not convert value \"baseURI\" to string with error \"{}\"",
e
))
})?;
- if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {
- if !suffix.is_empty() {
- return Ok(base_uri + suffix.as_str());
- }
- }
- return Ok(base_uri + token_id.to_string().as_str());
+ let base_uri = match base_uri.as_deref() {
+ None | Some("") => {
+ return Ok("".into());
}
- }
+ Some(base_uri) => base_uri.into(),
+ };
- Ok("".into())
+ Ok(
+ match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {
+ Err(_) | Ok("") => base_uri,
+ Ok(suffix) => base_uri + suffix,
+ },
+ )
}
}
@@ -448,19 +449,33 @@
}
/// @title ERC721 minting logic.
-#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]
+#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]
impl<T: Config> RefungibleHandle<T> {
fn minting_finished(&self) -> Result<bool> {
Ok(false)
}
/// @notice Function to mint token.
+ /// @param to The new owner
+ /// @return uint256 The id of the newly minted token
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {
+ let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into();
+ self.mint_check_id(caller, to, token_id)?;
+ Ok(token_id)
+ }
+
+ /// @notice Function to mint token.
/// @dev `tokenId` should be obtained with `nextTokenId` method,
/// unlike standard, you can't specify it manually
/// @param to The new owner
/// @param tokenId ID of the minted RFT
+ #[solidity(hide, rename_selector = "mint")]
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
+ fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let token_id: u32 = token_id.try_into()?;
@@ -496,14 +511,34 @@
}
/// @notice Function to mint token with the given tokenUri.
+ /// @param to The new owner
+ /// @param tokenUri Token URI that would be stored in the NFT properties
+ /// @return uint256 The id of the newly minted token
+ #[solidity(rename_selector = "mintWithTokenURI")]
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint_with_token_uri(
+ &mut self,
+ caller: caller,
+ to: address,
+ token_uri: string,
+ ) -> Result<uint256> {
+ let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into();
+ self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;
+ Ok(token_id)
+ }
+
+ /// @notice Function to mint token with the given tokenUri.
/// @dev `tokenId` should be obtained with `nextTokenId` method,
/// unlike standard, you can't specify it manually
/// @param to The new owner
/// @param tokenId ID of the minted RFT
/// @param tokenUri Token URI that would be stored in the RFT properties
- #[solidity(rename_selector = "mintWithTokenURI")]
+ #[solidity(hide, rename_selector = "mintWithTokenURI")]
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint_with_token_uri(
+ fn mint_with_token_uri_check_id(
&mut self,
caller: caller,
to: address,
@@ -578,17 +613,6 @@
Err("Property tokenURI not found".into())
}
-fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {
- if let Some(shema_name) =
- pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())
- {
- let shema_name = shema_name.into_inner();
- shema_name == property_value::ERC721_METADATA
- } else {
- false
- }
-}
-
fn get_token_permission<T: Config>(
collection_id: CollectionId,
key: &PropertyKey,
@@ -608,6 +632,18 @@
/// @title Unique extensions for ERC721.
#[solidity_interface(name = ERC721UniqueExtensions)]
impl<T: Config> RefungibleHandle<T> {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ fn name(&self) -> Result<string> {
+ Ok(decode_utf16(self.name.iter().copied())
+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+ .collect::<string>())
+ }
+
+ /// @notice An abbreviated name for NFTs in this contract
+ fn symbol(&self) -> Result<string> {
+ Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ }
+
/// @notice Transfer ownership of an RFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid RFT.
@@ -669,6 +705,7 @@
/// should be obtained with `nextTokenId` method
/// @param to The new owner
/// @param tokenIds IDs of the minted RFTs
+ // #[solidity(hide)]
#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]
fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -711,7 +748,7 @@
/// numbers and first number should be obtained with `nextTokenId` method
/// @param to The new owner
/// @param tokens array of pairs of token ID and token URI for minted tokens
- #[solidity(rename_selector = "mintBulkWithTokenURI")]
+ #[solidity(/*hide,*/ rename_selector = "mintBulkWithTokenURI")]
#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]
fn mint_bulk_with_token_uri(
&mut self,
@@ -780,11 +817,11 @@
name = UniqueRefungible,
is(
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata(if(this.flags.erc721metadata)),
Collection(via(common_mut returns CollectionHandle<T>)),
TokenProperties,
)
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -92,9 +92,11 @@
use codec::{Encode, Decode, MaxEncodedLen};
use core::ops::Deref;
+use derivative::Derivative;
use evm_coder::ToLog;
use frame_support::{
- BoundedVec, ensure, fail, storage::with_transaction, transactional, pallet_prelude::ConstU32,
+ BoundedBTreeMap, BoundedVec, ensure, fail, storage::with_transaction, transactional,
+ pallet_prelude::ConstU32,
};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_evm_coder_substrate::WithRecorder;
@@ -113,8 +115,6 @@
MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,
PropertyScope, PropertyValue, TokenId, TrySetProperty,
};
-use frame_support::BoundedBTreeMap;
-use derivative::Derivative;
pub use pallet::*;
#[cfg(feature = "runtime-benchmarks")]
@@ -371,8 +371,9 @@
owner: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data, CollectionFlags::default())
+ <PalletCommon<T>>::init_collection(owner, payer, data, flags)
}
/// Destroy RFT collection
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
@@ -91,7 +91,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -369,9 +369,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) public {
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
@@ -384,6 +384,47 @@
uint256 field_1;
}
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+contract ERC721Metadata is Dummy, ERC165 {
+ // /// @notice A descriptive name for a collection of NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x06fdde03,
+ // /// or in textual repr: name()
+ // function name() public view returns (string memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return "";
+ // }
+
+ // /// @notice An abbreviated name for NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x95d89b41,
+ // /// or in textual repr: symbol()
+ // function symbol() public view returns (string memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return "";
+ // }
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token has a `url` property and it is not empty, it is returned.
+ /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+ /// If the collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+ /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) public view returns (string memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return "";
+ }
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
contract ERC721Burnable is Dummy, ERC165 {
@@ -401,13 +442,13 @@
}
/// @dev inlined interface
-contract ERC721MintableEvents {
+contract ERC721UniqueMintableEvents {
event MintingFinished();
}
/// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-contract ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+contract ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
/// @dev EVM selector for this function is: 0x05d2035b,
/// or in textual repr: mintingFinished()
function mintingFinished() public view returns (bool) {
@@ -417,41 +458,63 @@
}
/// @notice Function to mint token.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted RFT
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 tokenId) public returns (bool) {
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x6a627842,
+ /// or in textual repr: mint(address)
+ function mint(address to) public returns (uint256) {
require(false, stub_error);
to;
- tokenId;
dummy = 0;
- return false;
+ return 0;
}
+ // /// @notice Function to mint token.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted RFT
+ // /// @dev EVM selector for this function is: 0x40c10f19,
+ // /// or in textual repr: mint(address,uint256)
+ // function mint(address to, uint256 tokenId) public returns (bool) {
+ // require(false, stub_error);
+ // to;
+ // tokenId;
+ // dummy = 0;
+ // return false;
+ // }
+
/// @notice Function to mint token with the given tokenUri.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted RFT
- /// @param tokenUri Token URI that would be stored in the RFT properties
- /// @dev EVM selector for this function is: 0x50bb4e7f,
- /// or in textual repr: mintWithTokenURI(address,uint256,string)
- function mintWithTokenURI(
- address to,
- uint256 tokenId,
- string memory tokenUri
- ) public returns (bool) {
+ /// @param tokenUri Token URI that would be stored in the NFT properties
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x45c17782,
+ /// or in textual repr: mintWithTokenURI(address,string)
+ function mintWithTokenURI(address to, string memory tokenUri) public returns (uint256) {
require(false, stub_error);
to;
- tokenId;
tokenUri;
dummy = 0;
- return false;
+ return 0;
}
+ // /// @notice Function to mint token with the given tokenUri.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted RFT
+ // /// @param tokenUri Token URI that would be stored in the RFT properties
+ // /// @dev EVM selector for this function is: 0x50bb4e7f,
+ // /// or in textual repr: mintWithTokenURI(address,uint256,string)
+ // function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) public returns (bool) {
+ // require(false, stub_error);
+ // to;
+ // tokenId;
+ // tokenUri;
+ // dummy = 0;
+ // return false;
+ // }
+
/// @dev Not implemented
/// @dev EVM selector for this function is: 0x7d64bcb4,
/// or in textual repr: finishMinting()
@@ -463,8 +526,26 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x7c3bef89
+/// @dev the ERC-165 identifier for this interface is 0xef1eaacb
contract ERC721UniqueExtensions is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
/// @notice Transfer ownership of an RFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid RFT.
@@ -527,7 +608,7 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) public returns (bool) {
require(false, stub_error);
to;
tokens;
@@ -549,7 +630,7 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -591,46 +672,7 @@
require(false, stub_error);
dummy;
return 0;
- }
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-contract ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of RFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @notice An abbreviated name for RFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
}
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token has a `url` property and it is not empty, it is returned.
- /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
- /// If the collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
- /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) public view returns (string memory) {
- require(false, stub_error);
- tokenId;
- dummy;
- return "";
- }
}
/// @dev inlined interface
@@ -776,11 +818,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata,
Collection,
TokenProperties
{}
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -25,14 +25,16 @@
dispatch::CollectionDispatch,
erc::{
CollectionHelpersEvents,
- static_property::{key, value as property_value},
+ static_property::{key},
},
+ Pallet as PalletCommon,
};
use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};
use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
+use sp_std::vec;
use up_data_structs::{
CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
- CollectionMode, PropertyValue,
+ CollectionMode, PropertyValue, CollectionFlags,
};
use crate::{Config, SelfWeightOf, weights::WeightInfo};
@@ -57,13 +59,11 @@
name: string,
description: string,
token_prefix: string,
- base_uri: string,
) -> Result<(
T::CrossAccountId,
CollectionName,
CollectionDescription,
CollectionTokenPrefix,
- PropertyValue,
)> {
let caller = T::CrossAccountId::from_eth(caller);
let name = name
@@ -81,75 +81,7 @@
let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {
error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())
})?;
- let base_uri_value = base_uri
- .into_bytes()
- .try_into()
- .map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;
- Ok((caller, name, description, token_prefix, base_uri_value))
-}
-
-fn make_data<T: Config>(
- name: CollectionName,
- mode: CollectionMode,
- description: CollectionDescription,
- token_prefix: CollectionTokenPrefix,
- base_uri_value: PropertyValue,
- add_properties: bool,
-) -> Result<CreateCollectionData<T::AccountId>> {
- let mut properties = up_data_structs::CollectionPropertiesVec::default();
- let mut token_property_permissions =
- up_data_structs::CollectionPropertiesPermissionsVec::default();
-
- token_property_permissions
- .try_push(up_data_structs::PropertyKeyPermission {
- key: key::url(),
- permission: up_data_structs::PropertyPermission {
- mutable: false,
- collection_admin: true,
- token_owner: false,
- },
- })
- .map_err(|e| Error::Revert(format!("{:?}", e)))?;
-
- if add_properties {
- token_property_permissions
- .try_push(up_data_structs::PropertyKeyPermission {
- key: key::suffix(),
- permission: up_data_structs::PropertyPermission {
- mutable: false,
- collection_admin: true,
- token_owner: false,
- },
- })
- .map_err(|e| Error::Revert(format!("{:?}", e)))?;
-
- properties
- .try_push(up_data_structs::Property {
- key: key::schema_name(),
- value: property_value::erc721(),
- })
- .map_err(|e| Error::Revert(format!("{:?}", e)))?;
-
- if !base_uri_value.is_empty() {
- properties
- .try_push(up_data_structs::Property {
- key: key::base_uri(),
- value: base_uri_value,
- })
- .map_err(|e| Error::Revert(format!("{:?}", e)))?;
- }
- }
-
- let data = CreateCollectionData {
- name,
- mode,
- description,
- token_prefix,
- token_property_permissions,
- properties,
- ..Default::default()
- };
- Ok(data)
+ Ok((caller, name, description, token_prefix))
}
fn create_refungible_collection_internal<
@@ -160,26 +92,27 @@
name: string,
description: string,
token_prefix: string,
- base_uri: string,
- add_properties: bool,
) -> Result<address> {
- let (caller, name, description, token_prefix, base_uri_value) =
- convert_data::<T>(caller, name, description, token_prefix, base_uri)?;
- let data = make_data::<T>(
+ let (caller, name, description, token_prefix) =
+ convert_data::<T>(caller, name, description, token_prefix)?;
+ let data = CreateCollectionData {
name,
- CollectionMode::ReFungible,
+ mode: CollectionMode::ReFungible,
description,
token_prefix,
- base_uri_value,
- add_properties,
- )?;
+ ..Default::default()
+ };
check_sent_amount_equals_collection_creation_price::<T>(value)?;
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id =
- T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(
+ caller.clone(),
+ collection_helpers_address,
+ data,
+ Default::default(),
+ )
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
@@ -212,7 +145,8 @@
/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
/// @return address Address of the newly created collection
#[weight(<SelfWeightOf<T>>::create_collection())]
- fn create_nonfungible_collection(
+ #[solidity(rename_selector = "createNFTCollection")]
+ fn create_nft_collection(
&mut self,
caller: caller,
value: value,
@@ -220,60 +154,51 @@
description: string,
token_prefix: string,
) -> Result<address> {
- let (caller, name, description, token_prefix, _base_uri_value) =
- convert_data::<T>(caller, name, description, token_prefix, "".into())?;
- let data = make_data::<T>(
+ let (caller, name, description, token_prefix) =
+ convert_data::<T>(caller, name, description, token_prefix)?;
+ let data = CreateCollectionData {
name,
- CollectionMode::NFT,
+ mode: CollectionMode::NFT,
description,
token_prefix,
- Default::default(),
- false,
- )?;
+ ..Default::default()
+ };
check_sent_amount_equals_collection_creation_price::<T>(value)?;
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
- .map_err(dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(
+ caller,
+ collection_helpers_address,
+ data,
+ Default::default(),
+ )
+ .map_err(dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
-
+ /// Create an NFT collection
+ /// @param name Name of the collection
+ /// @param description Informative description of the collection
+ /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
+ /// @return address Address of the newly created collection
#[weight(<SelfWeightOf<T>>::create_collection())]
- #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]
- fn create_nonfungible_collection_with_properties(
+ #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]
+ #[solidity(hide)]
+ fn create_nonfungible_collection(
&mut self,
caller: caller,
value: value,
name: string,
description: string,
token_prefix: string,
- base_uri: string,
) -> Result<address> {
- let (caller, name, description, token_prefix, base_uri_value) =
- convert_data::<T>(caller, name, description, token_prefix, base_uri)?;
- let data = make_data::<T>(
- name,
- CollectionMode::NFT,
- description,
- token_prefix,
- base_uri_value,
- true,
- )?;
- check_sent_amount_equals_collection_creation_price::<T>(value)?;
- let collection_helpers_address =
- T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
-
- let address = pallet_common::eth::collection_id_to_address(collection_id);
- Ok(address)
+ self.create_nft_collection(caller, value, name, description, token_prefix)
}
#[weight(<SelfWeightOf<T>>::create_collection())]
#[solidity(rename_selector = "createRFTCollection")]
- fn create_refungible_collection(
+ fn create_rft_collection(
&mut self,
caller: caller,
value: value,
@@ -281,37 +206,94 @@
description: string,
token_prefix: string,
) -> Result<address> {
- create_refungible_collection_internal::<T>(
- caller,
- value,
- name,
- description,
- token_prefix,
- Default::default(),
- false,
- )
+ create_refungible_collection_internal::<T>(caller, value, name, description, token_prefix)
}
- #[weight(<SelfWeightOf<T>>::create_collection())]
- #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]
- fn create_refungible_collection_with_properties(
+ #[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]
+ fn make_collection_metadata_compatible(
&mut self,
caller: caller,
- value: value,
- name: string,
- description: string,
- token_prefix: string,
+ collection: address,
base_uri: string,
- ) -> Result<address> {
- create_refungible_collection_internal::<T>(
- caller,
- value,
- name,
- description,
- token_prefix,
- base_uri,
- true,
- )
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let collection =
+ pallet_common::eth::map_eth_to_id(&collection).ok_or("not a collection address")?;
+ let mut collection =
+ <crate::CollectionHandle<T>>::new(collection).ok_or("collection not found")?;
+
+ if !matches!(
+ collection.mode,
+ CollectionMode::NFT | CollectionMode::ReFungible
+ ) {
+ return Err("target collection should be either NFT or Refungible".into());
+ }
+
+ self.recorder().consume_sstore()?;
+ collection
+ .check_is_owner_or_admin(&caller)
+ .map_err(dispatch_to_evm::<T>)?;
+
+ if collection.flags.erc721metadata {
+ return Err("target collection is already Erc721Metadata compatible".into());
+ }
+ collection.flags.erc721metadata = true;
+
+ let all_permissions = <pallet_common::CollectionPropertyPermissions<T>>::get(collection.id);
+ if all_permissions.get(&key::url()).is_none() {
+ self.recorder().consume_sstore()?;
+ <PalletCommon<T>>::set_property_permission(
+ &collection,
+ &caller,
+ up_data_structs::PropertyKeyPermission {
+ key: key::url(),
+ permission: up_data_structs::PropertyPermission {
+ mutable: true,
+ collection_admin: true,
+ token_owner: false,
+ },
+ },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ }
+ if all_permissions.get(&key::suffix()).is_none() {
+ self.recorder().consume_sstore()?;
+ <PalletCommon<T>>::set_property_permission(
+ &collection,
+ &caller,
+ up_data_structs::PropertyKeyPermission {
+ key: key::suffix(),
+ permission: up_data_structs::PropertyPermission {
+ mutable: true,
+ collection_admin: true,
+ token_owner: false,
+ },
+ },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ }
+
+ let all_properties = <pallet_common::CollectionProperties<T>>::get(collection.id);
+ if all_properties.get(&key::base_uri()).is_none() && !base_uri.is_empty() {
+ self.recorder().consume_sstore()?;
+ <PalletCommon<T>>::set_collection_properties(
+ &collection,
+ &caller,
+ vec![up_data_structs::Property {
+ key: key::base_uri(),
+ value: base_uri
+ .into_bytes()
+ .try_into()
+ .map_err(|_| "base uri is too large")?,
+ }],
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ }
+
+ self.recorder().consume_sstore()?;
+ collection.save().map_err(dispatch_to_evm::<T>)?;
+
+ Ok(())
}
/// Check if a collection exists
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -23,16 +23,16 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x5ad4f440
+/// @dev the ERC-165 identifier for this interface is 0x58918631
contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
/// @param description Informative description of the collection
/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
/// @return address Address of the newly created collection
- /// @dev EVM selector for this function is: 0xe34a6844,
- /// or in textual repr: createNonfungibleCollection(string,string,string)
- function createNonfungibleCollection(
+ /// @dev EVM selector for this function is: 0x844af658,
+ /// or in textual repr: createNFTCollection(string,string,string)
+ function createNFTCollection(
string memory name,
string memory description,
string memory tokenPrefix
@@ -45,22 +45,21 @@
return 0x0000000000000000000000000000000000000000;
}
- /// @dev EVM selector for this function is: 0xa634a5f9,
- /// or in textual repr: createERC721MetadataCompatibleCollection(string,string,string,string)
- function createERC721MetadataCompatibleCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix,
- string memory baseUri
- ) public payable returns (address) {
- require(false, stub_error);
- name;
- description;
- tokenPrefix;
- baseUri;
- dummy = 0;
- return 0x0000000000000000000000000000000000000000;
- }
+ // /// Create an NFT collection
+ // /// @param name Name of the collection
+ // /// @param description Informative description of the collection
+ // /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
+ // /// @return address Address of the newly created collection
+ // /// @dev EVM selector for this function is: 0xe34a6844,
+ // /// or in textual repr: createNonfungibleCollection(string,string,string)
+ // function createNonfungibleCollection(string memory name, string memory description, string memory tokenPrefix) public payable returns (address) {
+ // require(false, stub_error);
+ // name;
+ // description;
+ // tokenPrefix;
+ // dummy = 0;
+ // return 0x0000000000000000000000000000000000000000;
+ // }
/// @dev EVM selector for this function is: 0xab173450,
/// or in textual repr: createRFTCollection(string,string,string)
@@ -77,21 +76,13 @@
return 0x0000000000000000000000000000000000000000;
}
- /// @dev EVM selector for this function is: 0xa5596388,
- /// or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
- function createERC721MetadataCompatibleRFTCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix,
- string memory baseUri
- ) public payable returns (address) {
+ /// @dev EVM selector for this function is: 0x85624258,
+ /// or in textual repr: makeCollectionERC721MetadataCompatible(address,string)
+ function makeCollectionERC721MetadataCompatible(address collection, string memory baseUri) public {
require(false, stub_error);
- name;
- description;
- tokenPrefix;
+ collection;
baseUri;
dummy = 0;
- return 0x0000000000000000000000000000000000000000;
}
/// Check if a collection exists
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -345,7 +345,7 @@
// =========
let sender = T::CrossAccountId::from_sub(sender);
- let _id = T::CollectionDispatch::create(sender.clone(), sender, data)?;
+ let _id = T::CollectionDispatch::create(sender.clone(), sender, data, Default::default())?;
Ok(())
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -365,11 +365,14 @@
/// Tokens in foreign collections can be transferred, but not burnt
#[bondrewd(bits = "0..1")]
pub foreign: bool,
+ /// Supports ERC721Metadata
+ #[bondrewd(bits = "1..2")]
+ pub erc721metadata: bool,
/// External collections can't be managed using `unique` api
#[bondrewd(bits = "7..8")]
pub external: bool,
- #[bondrewd(reserve, bits = "1..7")]
+ #[bondrewd(reserve, bits = "2..7")]
pub reserved: u8,
}
bondrewd_codec!(CollectionFlags);
@@ -434,6 +437,15 @@
pub meta_update_permission: MetaUpdatePermission,
}
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct RpcCollectionFlags {
+ /// Is collection is foreign.
+ pub foreign: bool,
+ /// Collection supports ERC721Metadata.
+ pub erc721metadata: bool,
+}
+
/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
@@ -471,8 +483,8 @@
/// Is collection read only.
pub read_only: bool,
- /// Is collection is foreign.
- pub foreign: bool,
+ /// Extra collection flags
+ pub flags: RpcCollectionFlags,
}
/// Data used for create collection.
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -31,7 +31,7 @@
};
use up_data_structs::{
CollectionMode, CreateCollectionData, MAX_DECIMAL_POINTS, mapping::TokenAddressMapping,
- CollectionId,
+ CollectionId, CollectionFlags,
};
#[cfg(not(feature = "refungible"))]
@@ -57,10 +57,11 @@
sender: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError> {
let id = match data.mode {
CollectionMode::NFT => {
- <PalletNonfungible<T>>::init_collection(sender, payer, data, false)?
+ <PalletNonfungible<T>>::init_collection(sender, payer, data, flags)?
}
CollectionMode::Fungible(decimal_points) => {
// check params
@@ -68,11 +69,13 @@
decimal_points <= MAX_DECIMAL_POINTS,
pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
);
- <PalletFungible<T>>::init_collection(sender, payer, data)?
+ <PalletFungible<T>>::init_collection(sender, payer, data, flags)?
}
#[cfg(feature = "refungible")]
- CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, payer, data)?,
+ CollectionMode::ReFungible => {
+ <PalletRefungible<T>>::init_collection(sender, payer, data, flags)?
+ }
#[cfg(not(feature = "refungible"))]
CollectionMode::ReFungible => return unsupported!(T),
runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -24,7 +24,7 @@
use pallet_nonfungible::{
Config as NonfungibleConfig,
erc::{
- UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721MintableCall, ERC721Call,
+ UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721UniqueMintableCall, ERC721Call,
TokenPropertiesCall,
},
};
@@ -82,18 +82,17 @@
let token_id: TokenId = token_id.try_into().ok()?;
withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
}
- UniqueNFTCall::ERC721Mintable(
- ERC721MintableCall::Mint { token_id, .. }
- | ERC721MintableCall::MintWithTokenUri { token_id, .. },
- ) => {
- let _token_id: TokenId = token_id.try_into().ok()?;
- withdraw_create_item::<T>(
- &collection,
- &who,
- &CreateItemData::NFT(CreateNftData::default()),
- )
- .map(|()| sponsor)
- }
+ UniqueNFTCall::ERC721UniqueMintable(
+ ERC721UniqueMintableCall::Mint { .. }
+ | ERC721UniqueMintableCall::MintCheckId { .. }
+ | ERC721UniqueMintableCall::MintWithTokenUri { .. }
+ | ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },
+ ) => withdraw_create_item::<T>(
+ &collection,
+ &who,
+ &CreateItemData::NFT(CreateNftData::default()),
+ )
+ .map(|()| sponsor),
UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {
let token_id: TokenId = token_id.try_into().ok()?;
let from = T::CrossAccountId::from_eth(from);
tests/src/eth/allowlist.test.tsdiffbeforeafterboth--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -78,7 +78,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const user = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
@@ -94,7 +94,7 @@
// const owner = await helper.eth.createAccountWithBalance(donor);
// const user = donor;
- // const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ // const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
// const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
// expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
@@ -110,7 +110,7 @@
const notOwner = await helper.eth.createAccountWithBalance(donor);
const user = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
@@ -129,7 +129,7 @@
// const notOwner = await helper.eth.createAccountWithBalance(donor);
// const user = donor;
- // const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ // const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
// const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
// expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
tests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -18,29 +18,29 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x5ad4f440
+/// @dev the ERC-165 identifier for this interface is 0x58918631
interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
/// @param description Informative description of the collection
/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
/// @return address Address of the newly created collection
- /// @dev EVM selector for this function is: 0xe34a6844,
- /// or in textual repr: createNonfungibleCollection(string,string,string)
- function createNonfungibleCollection(
+ /// @dev EVM selector for this function is: 0x844af658,
+ /// or in textual repr: createNFTCollection(string,string,string)
+ function createNFTCollection(
string memory name,
string memory description,
string memory tokenPrefix
) external payable returns (address);
- /// @dev EVM selector for this function is: 0xa634a5f9,
- /// or in textual repr: createERC721MetadataCompatibleCollection(string,string,string,string)
- function createERC721MetadataCompatibleCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix,
- string memory baseUri
- ) external payable returns (address);
+ // /// Create an NFT collection
+ // /// @param name Name of the collection
+ // /// @param description Informative description of the collection
+ // /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
+ // /// @return address Address of the newly created collection
+ // /// @dev EVM selector for this function is: 0xe34a6844,
+ // /// or in textual repr: createNonfungibleCollection(string,string,string)
+ // function createNonfungibleCollection(string memory name, string memory description, string memory tokenPrefix) external payable returns (address);
/// @dev EVM selector for this function is: 0xab173450,
/// or in textual repr: createRFTCollection(string,string,string)
@@ -50,14 +50,9 @@
string memory tokenPrefix
) external payable returns (address);
- /// @dev EVM selector for this function is: 0xa5596388,
- /// or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
- function createERC721MetadataCompatibleRFTCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix,
- string memory baseUri
- ) external payable returns (address);
+ /// @dev EVM selector for this function is: 0x85624258,
+ /// or in textual repr: makeCollectionERC721MetadataCompatible(address,string)
+ function makeCollectionERC721MetadataCompatible(address collection, string memory baseUri) external;
/// Check if a collection exists
/// @param collectionAddress Address of the collection in question
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 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -194,9 +194,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) external;
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) external;
}
/// @dev the ERC-165 identifier for this interface is 0x63034ac5
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -62,7 +62,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -243,9 +243,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) external;
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) external;
}
/// @dev anonymous struct
@@ -254,6 +254,36 @@
uint256 field_1;
}
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+interface ERC721Metadata is Dummy, ERC165 {
+ // /// @notice A descriptive name for a collection of NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x06fdde03,
+ // /// or in textual repr: name()
+ // function name() external view returns (string memory);
+
+ // /// @notice An abbreviated name for NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x95d89b41,
+ // /// or in textual repr: symbol()
+ // function symbol() external view returns (string memory);
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token has a `url` property and it is not empty, it is returned.
+ /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+ /// If the collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+ /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) external view returns (string memory);
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
interface ERC721Burnable is Dummy, ERC165 {
@@ -267,39 +297,50 @@
}
/// @dev inlined interface
-interface ERC721MintableEvents {
+interface ERC721UniqueMintableEvents {
event MintingFinished();
}
/// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-interface ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+interface ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
/// @dev EVM selector for this function is: 0x05d2035b,
/// or in textual repr: mintingFinished()
function mintingFinished() external view returns (bool);
/// @notice Function to mint token.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted NFT
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 tokenId) external returns (bool);
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x6a627842,
+ /// or in textual repr: mint(address)
+ function mint(address to) external returns (uint256);
+
+ // /// @notice Function to mint token.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted NFT
+ // /// @dev EVM selector for this function is: 0x40c10f19,
+ // /// or in textual repr: mint(address,uint256)
+ // function mint(address to, uint256 tokenId) external returns (bool);
/// @notice Function to mint token with the given tokenUri.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted NFT
/// @param tokenUri Token URI that would be stored in the NFT properties
- /// @dev EVM selector for this function is: 0x50bb4e7f,
- /// or in textual repr: mintWithTokenURI(address,uint256,string)
- function mintWithTokenURI(
- address to,
- uint256 tokenId,
- string memory tokenUri
- ) external returns (bool);
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x45c17782,
+ /// or in textual repr: mintWithTokenURI(address,string)
+ function mintWithTokenURI(address to, string memory tokenUri) external returns (uint256);
+
+ // /// @notice Function to mint token with the given tokenUri.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted NFT
+ // /// @param tokenUri Token URI that would be stored in the NFT properties
+ // /// @dev EVM selector for this function is: 0x50bb4e7f,
+ // /// or in textual repr: mintWithTokenURI(address,uint256,string)
+ // function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) external returns (bool);
/// @dev Not implemented
/// @dev EVM selector for this function is: 0x7d64bcb4,
@@ -308,8 +349,18 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xd74d154f
+/// @dev the ERC-165 identifier for this interface is 0x4468500d
interface ERC721UniqueExtensions is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() external view returns (string memory);
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() external view returns (string memory);
+
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -350,11 +401,11 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) external returns (bool);
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -384,34 +435,6 @@
function totalSupply() external view returns (uint256);
}
-/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
-/// @dev See https://eips.ethereum.org/EIPS/eip-721
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-interface ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of NFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() external view returns (string memory);
-
- /// @notice An abbreviated name for NFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() external view returns (string memory);
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token has a `url` property and it is not empty, it is returned.
- /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
- /// If the collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
- /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) external view returns (string memory);
-}
-
/// @dev inlined interface
interface ERC721Events {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -507,11 +530,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata,
Collection,
TokenProperties
{}
tests/src/eth/api/UniqueRFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRFT.sol
+++ /dev/null
@@ -1,163 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-// Common stubs holder
-interface Dummy {
-
-}
-
-interface ERC165 is Dummy {
- function supportsInterface(bytes4 interfaceID) external view returns (bool);
-}
-
-// Selector: 7d9262e6
-interface Collection is Dummy, ERC165 {
- // Set collection property.
- //
- // @param key Property key.
- // @param value Propery value.
- //
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- external;
-
- // Delete collection property.
- //
- // @param key Property key.
- //
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) external;
-
- // Get collection property.
- //
- // @dev Throws error if key not found.
- //
- // @param key Property key.
- // @return bytes The property corresponding to the key.
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- external
- view
- returns (bytes memory);
-
- // Set the sponsor of the collection.
- //
- // @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
- //
- // @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.
- //
- // Selector: setCollectionSponsor(address) 7623402e
- function setCollectionSponsor(address sponsor) external;
-
- // Collection sponsorship confirmation.
- //
- // @dev After setting the sponsor for the collection, it must be confirmed with this function.
- //
- // Selector: confirmCollectionSponsorship() 3c50e97a
- function confirmCollectionSponsorship() external;
-
- // Set limits for the collection.
- // @dev Throws error if limit not found.
- // @param limit Name of the limit. Valid names:
- // "accountTokenOwnershipLimit",
- // "sponsoredDataSize",
- // "sponsoredDataRateLimit",
- // "tokenLimit",
- // "sponsorTransferTimeout",
- // "sponsorApproveTimeout"
- // @param value Value of the limit.
- //
- // Selector: setCollectionLimit(string,uint32) 6a3841db
- function setCollectionLimit(string memory limit, uint32 value) external;
-
- // Set limits for the collection.
- // @dev Throws error if limit not found.
- // @param limit Name of the limit. Valid names:
- // "ownerCanTransfer",
- // "ownerCanDestroy",
- // "transfersEnabled"
- // @param value Value of the limit.
- //
- // Selector: setCollectionLimit(string,bool) 993b7fba
- function setCollectionLimit(string memory limit, bool value) external;
-
- // Get contract address.
- //
- // Selector: contractAddress() f6b4dfb4
- function contractAddress() external view returns (address);
-
- // Add collection admin by substrate address.
- // @param new_admin Substrate administrator address.
- //
- // Selector: addCollectionAdminSubstrate(uint256) 5730062b
- function addCollectionAdminSubstrate(uint256 newAdmin) external;
-
- // Remove collection admin by substrate address.
- // @param admin Substrate administrator address.
- //
- // Selector: removeCollectionAdminSubstrate(uint256) 4048fcf9
- function removeCollectionAdminSubstrate(uint256 admin) external;
-
- // Add collection admin.
- // @param new_admin Address of the added administrator.
- //
- // Selector: addCollectionAdmin(address) 92e462c7
- function addCollectionAdmin(address newAdmin) external;
-
- // Remove collection admin.
- //
- // @param new_admin Address of the removed administrator.
- //
- // Selector: removeCollectionAdmin(address) fafd7b42
- function removeCollectionAdmin(address admin) external;
-
- // Toggle accessibility of collection nesting.
- //
- // @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- //
- // Selector: setCollectionNesting(bool) 112d4586
- function setCollectionNesting(bool enable) external;
-
- // Toggle accessibility of collection nesting.
- //
- // @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- // @param collections Addresses of collections that will be available for nesting.
- //
- // Selector: setCollectionNesting(bool,address[]) 64872396
- function setCollectionNesting(bool enable, address[] memory collections)
- external;
-
- // Set the collection access method.
- // @param mode Access mode
- // 0 for Normal
- // 1 for AllowList
- //
- // Selector: setCollectionAccess(uint8) 41835d4c
- function setCollectionAccess(uint8 mode) external;
-
- // Add the user to the allowed list.
- //
- // @param user Address of a trusted user.
- //
- // Selector: addToCollectionAllowList(address) 67844fe6
- function addToCollectionAllowList(address user) external;
-
- // Remove the user from the allowed list.
- //
- // @param user Address of a removed user.
- //
- // Selector: removeFromCollectionAllowList(address) 85c51acb
- function removeFromCollectionAllowList(address user) external;
-
- // Switch permission for minting.
- //
- // @param mode Enable if "true".
- //
- // Selector: setCollectionMintMode(bool) 00018e84
- function setCollectionMintMode(bool mode) external;
-}
-
-interface UniqueRFT is Dummy, ERC165, Collection {}
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -62,7 +62,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -243,9 +243,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) external;
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) external;
}
/// @dev anonymous struct
@@ -254,6 +254,34 @@
uint256 field_1;
}
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+interface ERC721Metadata is Dummy, ERC165 {
+ // /// @notice A descriptive name for a collection of NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x06fdde03,
+ // /// or in textual repr: name()
+ // function name() external view returns (string memory);
+
+ // /// @notice An abbreviated name for NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x95d89b41,
+ // /// or in textual repr: symbol()
+ // function symbol() external view returns (string memory);
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token has a `url` property and it is not empty, it is returned.
+ /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+ /// If the collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+ /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) external view returns (string memory);
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
interface ERC721Burnable is Dummy, ERC165 {
@@ -267,40 +295,51 @@
}
/// @dev inlined interface
-interface ERC721MintableEvents {
+interface ERC721UniqueMintableEvents {
event MintingFinished();
}
/// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-interface ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+interface ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
/// @dev EVM selector for this function is: 0x05d2035b,
/// or in textual repr: mintingFinished()
function mintingFinished() external view returns (bool);
/// @notice Function to mint token.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted RFT
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 tokenId) external returns (bool);
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x6a627842,
+ /// or in textual repr: mint(address)
+ function mint(address to) external returns (uint256);
+
+ // /// @notice Function to mint token.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted RFT
+ // /// @dev EVM selector for this function is: 0x40c10f19,
+ // /// or in textual repr: mint(address,uint256)
+ // function mint(address to, uint256 tokenId) external returns (bool);
/// @notice Function to mint token with the given tokenUri.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted RFT
- /// @param tokenUri Token URI that would be stored in the RFT properties
- /// @dev EVM selector for this function is: 0x50bb4e7f,
- /// or in textual repr: mintWithTokenURI(address,uint256,string)
- function mintWithTokenURI(
- address to,
- uint256 tokenId,
- string memory tokenUri
- ) external returns (bool);
+ /// @param tokenUri Token URI that would be stored in the NFT properties
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x45c17782,
+ /// or in textual repr: mintWithTokenURI(address,string)
+ function mintWithTokenURI(address to, string memory tokenUri) external returns (uint256);
+ // /// @notice Function to mint token with the given tokenUri.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted RFT
+ // /// @param tokenUri Token URI that would be stored in the RFT properties
+ // /// @dev EVM selector for this function is: 0x50bb4e7f,
+ // /// or in textual repr: mintWithTokenURI(address,uint256,string)
+ // function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) external returns (bool);
+
/// @dev Not implemented
/// @dev EVM selector for this function is: 0x7d64bcb4,
/// or in textual repr: finishMinting()
@@ -308,8 +347,18 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x7c3bef89
+/// @dev the ERC-165 identifier for this interface is 0xef1eaacb
interface ERC721UniqueExtensions is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() external view returns (string memory);
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() external view returns (string memory);
+
/// @notice Transfer ownership of an RFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid RFT.
@@ -352,7 +401,7 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) external returns (bool);
/// Returns EVM address for refungible token
///
@@ -363,7 +412,7 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -393,32 +442,6 @@
function totalSupply() external view returns (uint256);
}
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-interface ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of RFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() external view returns (string memory);
-
- /// @notice An abbreviated name for RFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() external view returns (string memory);
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token has a `url` property and it is not empty, it is returned.
- /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
- /// If the collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
- /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) external view returns (string memory);
-}
-
/// @dev inlined interface
interface ERC721Events {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -512,11 +535,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata,
Collection,
TokenProperties
{}
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -23,7 +23,7 @@
describe('Contract calls', () => {
let donor: IKeyringPair;
- before(async function() {
+ before(async function () {
await usingEthPlaygrounds(async (_helper, privateKey) => {
donor = await privateKey({filename: __filename});
});
@@ -40,7 +40,12 @@
itEth('Balance transfer fee is less than 0.2 UNQ', async ({helper}) => {
const userA = await helper.eth.createAccountWithBalance(donor);
const userB = helper.eth.createAccount();
- const cost = await helper.eth.calculateFee({Ethereum: userA}, () => helper.getWeb3().eth.sendTransaction({from: userA, to: userB, value: '1000000', gas: helper.eth.DEFAULT_GAS}));
+ const cost = await helper.eth.calculateFee({Ethereum: userA}, () => helper.getWeb3().eth.sendTransaction({
+ from: userA,
+ to: userB,
+ value: '1000000',
+ gas: helper.eth.DEFAULT_GAS
+ }));
const balanceB = await helper.balance.getEthereum(userB);
expect(cost - balanceB < BigInt(0.2 * Number(helper.balance.getOneTokenNominal()))).to.be.true;
});
@@ -69,51 +74,59 @@
describe('ERC165 tests', async () => {
// https://eips.ethereum.org/EIPS/eip-165
- let collection: number;
+ let erc721MetadataCompatibleNftCollectionId: number;
+ let simpleNftCollectionId: number;
let minter: string;
- function contract(helper: EthUniqueHelper): Contract {
- return helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection), 'nft', minter);
+ const BASE_URI = 'base/';
+
+ async function checkInterface(helper: EthUniqueHelper, interfaceId: string, simpleResult: boolean, compatibleResult: boolean) {
+ const simple = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(simpleNftCollectionId), 'nft', minter);
+ const compatible = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(erc721MetadataCompatibleNftCollectionId), 'nft', minter);
+
+ expect(await simple.methods.supportsInterface(interfaceId).call()).to.equal(simpleResult, `empty (not ERC721Metadata compatible) NFT collection returns not ${simpleResult}`);
+ expect(await compatible.methods.supportsInterface(interfaceId).call()).to.equal(compatibleResult, `ERC721Metadata compatible NFT collection returns not ${compatibleResult}`);
}
before(async () => {
await usingEthPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
const [alice] = await helper.arrange.createAccounts([10n], donor);
- ({collectionId: collection} = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'}));
+ ({collectionId: simpleNftCollectionId} = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'}));
minter = helper.eth.createAccount();
+ ({collectionId: erc721MetadataCompatibleNftCollectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(minter, 'n', 'd', 'p', BASE_URI));
});
});
- itEth('interfaceID == 0xffffffff always false', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0xffffffff').call()).to.be.false;
+ itEth('nonexistent interfaceID - 0xffffffff - always false', async ({helper}) => {
+ await checkInterface(helper, '0xffffffff', false, false);
});
- itEth('ERC721 support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x780e9d63').call()).to.be.true;
+ itEth('ERC721 - 0x780e9d63 - support', async ({helper}) => {
+ await checkInterface(helper, '0x780e9d63', true, true);
});
- itEth('ERC721Metadata support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x5b5e139f').call()).to.be.true;
+ itEth('ERC721Metadata - 0x5b5e139f - support', async ({helper}) => {
+ await checkInterface(helper, '0x5b5e139f', false, true);
});
- itEth('ERC721Mintable support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x68ccfe89').call()).to.be.true;
+ itEth('ERC721UniqueMintable - 0x476ff149 - support', async ({helper}) => {
+ await checkInterface(helper, '0x476ff149', true, true);
});
- itEth('ERC721Enumerable support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x780e9d63').call()).to.be.true;
+ itEth('ERC721Enumerable - 0x780e9d63 - support', async ({helper}) => {
+ await checkInterface(helper, '0x780e9d63', true, true);
});
- itEth('ERC721UniqueExtensions support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0xd74d154f').call()).to.be.true;
+ itEth('ERC721UniqueExtensions - 0x4468500d - support', async ({helper}) => {
+ await checkInterface(helper, '0x4468500d', true, true);
});
- itEth('ERC721Burnable support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x42966c68').call()).to.be.true;
+ itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {
+ await checkInterface(helper, '0x42966c68', true, true);
});
- itEth('ERC165 support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x01ffc9a7').call()).to.be.true;
+ itEth('ERC165 - 0x01ffc9a7 - support', async ({helper}) => {
+ await checkInterface(helper, '0x01ffc9a7', true, true);
});
});
tests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -38,7 +38,7 @@
itEth('Add admin by owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const newAdmin = helper.eth.createAccount();
@@ -51,7 +51,7 @@
itEth.skip('Add substrate admin by owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const [newAdmin] = await helper.arrange.createAccounts([10n], donor);
@@ -64,7 +64,7 @@
itEth('Verify owner or admin', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const newAdmin = helper.eth.createAccount();
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -75,7 +75,7 @@
itEth('(!negative tests!) Add admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const admin = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -93,7 +93,7 @@
itEth('(!negative tests!) Add admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const notAdmin = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -108,7 +108,7 @@
itEth.skip('(!negative tests!) Add substrate admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const admin = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -126,7 +126,7 @@
itEth.skip('(!negative tests!) Add substrate admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const notAdmin0 = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -150,7 +150,7 @@
itEth('Remove admin by owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const newAdmin = helper.eth.createAccount();
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -170,7 +170,7 @@
itEth.skip('Remove substrate admin by owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const [newAdmin] = await helper.arrange.createAccounts([10n], donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -188,7 +188,7 @@
itEth('(!negative tests!) Remove admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -210,7 +210,7 @@
itEth('(!negative tests!) Remove admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -230,7 +230,7 @@
itEth.skip('(!negative tests!) Remove substrate admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const [adminSub] = await helper.arrange.createAccounts([10n], donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -250,7 +250,7 @@
itEth.skip('(!negative tests!) Remove substrate admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const [adminSub] = await helper.arrange.createAccounts([10n], donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -279,10 +279,10 @@
itEth('Change owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const newOwner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- await collectionEvm.methods.setOwner(newOwner).send();
+ await collectionEvm.methods.changeCollectionOwner(newOwner).send();
expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.false;
expect(await collectionEvm.methods.isOwnerOrAdmin(newOwner).call()).to.be.true;
@@ -291,9 +291,9 @@
itEth('change owner call fee', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const newOwner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- const cost = await recordEthFee(helper, owner, () => collectionEvm.methods.setOwner(newOwner).send());
+ const cost = await recordEthFee(helper, owner, () => collectionEvm.methods.changeCollectionOwner(newOwner).send());
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
expect(cost > 0);
});
@@ -301,10 +301,10 @@
itEth('(!negative tests!) call setOwner by non owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const newOwner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- await expect(collectionEvm.methods.setOwner(newOwner).send({from: newOwner})).to.be.rejected;
+ await expect(collectionEvm.methods.changeCollectionOwner(newOwner).send({from: newOwner})).to.be.rejected;
expect(await collectionEvm.methods.isOwnerOrAdmin(newOwner).call()).to.be.false;
});
});
@@ -321,7 +321,7 @@
itEth.skip('Change owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const [newOwner] = await helper.arrange.createAccounts([10n], donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.true;
@@ -336,7 +336,7 @@
itEth.skip('change owner call fee', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const [newOwner] = await helper.arrange.createAccounts([10n], donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const cost = await recordEthFee(helper, owner, () => collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send());
@@ -348,7 +348,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const otherReceiver = await helper.eth.createAccountWithBalance(donor);
const [newOwner] = await helper.arrange.createAccounts([10n], donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
await expect(collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send({from: otherReceiver})).to.be.rejected;
tests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -29,33 +29,9 @@
"inputs": [
{ "internalType": "string", "name": "name", "type": "string" },
{ "internalType": "string", "name": "description", "type": "string" },
- { "internalType": "string", "name": "tokenPrefix", "type": "string" },
- { "internalType": "string", "name": "baseUri", "type": "string" }
- ],
- "name": "createERC721MetadataCompatibleCollection",
- "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
- "stateMutability": "payable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "string", "name": "name", "type": "string" },
- { "internalType": "string", "name": "description", "type": "string" },
- { "internalType": "string", "name": "tokenPrefix", "type": "string" },
- { "internalType": "string", "name": "baseUri", "type": "string" }
- ],
- "name": "createERC721MetadataCompatibleRFTCollection",
- "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
- "stateMutability": "payable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "string", "name": "name", "type": "string" },
- { "internalType": "string", "name": "description", "type": "string" },
{ "internalType": "string", "name": "tokenPrefix", "type": "string" }
],
- "name": "createNonfungibleCollection",
+ "name": "createNFTCollection",
"outputs": [{ "internalType": "address", "name": "", "type": "address" }],
"stateMutability": "payable",
"type": "function"
@@ -86,6 +62,16 @@
},
{
"inputs": [
+ { "internalType": "address", "name": "collection", "type": "address" },
+ { "internalType": "string", "name": "baseUri", "type": "string" }
+ ],
+ "name": "makeCollectionERC721MetadataCompatible",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
],
"name": "supportsInterface",
tests/src/eth/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -14,8 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {itEth, usingEthPlaygrounds, expect} from './util';
+import {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util';
+import {Pallets} from '../util';
+import {IProperty, ITokenPropertyPermission} from '../util/playgrounds/types';
import {IKeyringPair} from '@polkadot/types/types';
+import {Contract} from 'web3-eth-contract';
describe('EVM collection properties', () => {
let donor: IKeyringPair;
@@ -30,7 +33,7 @@
itEth('Can be set', async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test'});
+ const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test', properties: []});
await collection.addAdmin(alice, {Ethereum: caller});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
@@ -70,3 +73,92 @@
expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));
});
});
+
+describe('Supports ERC721Metadata', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_helper, privateKey) => {
+ donor = await privateKey({filename: __filename});
+ });
+ });
+
+ const checkERC721Metadata = async (helper: EthUniqueHelper, mode: 'nft' | 'rft') => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const bruh = await helper.eth.createAccountWithBalance(donor);
+
+ const BASE_URI = 'base/'
+ const SUFFIX = 'suffix1'
+ const URI = 'uri1'
+
+ const collectionHelpers = helper.ethNativeContract.collectionHelpers(caller);
+ const creatorMethod = mode === 'rft' ? 'createRFTCollection' : 'createNFTCollection'
+
+ const {collectionId, collectionAddress} = await helper.eth[creatorMethod](caller, 'n', 'd', 'p')
+
+ const contract = helper.ethNativeContract.collectionById(collectionId, mode, caller);
+ await contract.methods.addCollectionAdmin(bruh).send(); // to check that admin will work too
+
+ const collection1 = await helper.nft.getCollectionObject(collectionId);
+ const data1 = await collection1.getData()
+ expect(data1?.raw.flags.erc721metadata).to.be.false;
+ expect(await contract.methods.supportsInterface('0x5b5e139f').call()).to.be.false;
+
+ await collectionHelpers.methods.makeCollectionERC721MetadataCompatible(collectionAddress, BASE_URI)
+ .send({from: bruh});
+
+ expect(await contract.methods.supportsInterface('0x5b5e139f').call()).to.be.true;
+
+ const collection2 = await helper.nft.getCollectionObject(collectionId);
+ const data2 = await collection2.getData()
+ expect(data2?.raw.flags.erc721metadata).to.be.true;
+
+ const TPPs = data2?.raw.tokenPropertyPermissions
+ expect(TPPs?.length).to.equal(2);
+
+ expect(TPPs.find((tpp: ITokenPropertyPermission) => {
+ return tpp.key === "URI" && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner
+ })).to.be.not.null
+
+ expect(TPPs.find((tpp: ITokenPropertyPermission) => {
+ return tpp.key === "URISuffix" && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner
+ })).to.be.not.null
+
+ expect(data2?.raw.properties?.find((property: IProperty) => {
+ return property.key === "baseURI" && property.value === BASE_URI
+ })).to.be.not.null
+
+ const token1Result = await contract.methods.mint(bruh).send();
+ const tokenId1 = token1Result.events.Transfer.returnValues.tokenId;
+
+ expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(BASE_URI);
+
+ await contract.methods.setProperty(tokenId1, "URISuffix", Buffer.from(SUFFIX)).send();
+ expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(BASE_URI + SUFFIX);
+
+ await contract.methods.setProperty(tokenId1, "URI", Buffer.from(URI)).send();
+ expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(URI);
+
+ await contract.methods.deleteProperty(tokenId1, "URI").send();
+ expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(BASE_URI + SUFFIX);
+
+ const token2Result = await contract.methods.mintWithTokenURI(bruh, URI).send();
+ const tokenId2 = token2Result.events.Transfer.returnValues.tokenId;
+
+ expect(await contract.methods.tokenURI(tokenId2).call()).to.equal(URI);
+
+ await contract.methods.deleteProperty(tokenId2, "URI").send();
+ expect(await contract.methods.tokenURI(tokenId2).call()).to.equal(BASE_URI);
+
+ await contract.methods.setProperty(tokenId2, "URISuffix", Buffer.from(SUFFIX)).send();
+ expect(await contract.methods.tokenURI(tokenId2).call()).to.equal(BASE_URI + SUFFIX);
+ }
+
+ itEth('ERC721Metadata property can be set for NFT collection', async({helper}) => {
+ await checkERC721Metadata(helper, 'nft');
+ });
+
+ itEth.ifWithPallets('ERC721Metadata property can be set for RFT collection', [Pallets.ReFungible], async({helper}) => {
+ await checkERC721Metadata(helper, 'rft');
+ });
+});
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -44,9 +44,8 @@
await collection.addToAllowList(alice, {Ethereum: minter});
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.equal('1');
- const result = await contract.methods.mint(minter, nextTokenId).send();
+ const result = await contract.methods.mint(minter).send();
+
const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -55,7 +54,7 @@
args: {
from: '0x0000000000000000000000000000000000000000',
to: minter,
- tokenId: nextTokenId,
+ tokenId: '1',
},
},
]);
@@ -65,7 +64,7 @@
// 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();
+ // let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send();
// const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
// const sponsor = privateKeyWrapper('//Alice');
// const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
@@ -73,11 +72,11 @@
// 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.collectionSponsor().call({from: owner});
// expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);
// });
@@ -86,7 +85,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+ let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const sponsor = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
@@ -94,28 +93,26 @@
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.collectionSponsor().call({from: owner});
expect(sponsorTuple.field_0).to.be.eq('0x0000000000000000000000000000000000000000');
});
itEth('Sponsoring collection from evm address via access list', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
- const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
- const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+ const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Sponsor collection', '1', '1', '');
+
const collection = helper.nft.getCollectionObject(collectionId);
const sponsor = await helper.eth.createAccountWithBalance(donor);
- const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
+ await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
let collectionData = (await collection.getData())!;
expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
@@ -144,23 +141,17 @@
const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
{
- 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 result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
- address: collectionIdAddress,
+ address: collectionAddress,
event: 'Transfer',
args: {
from: '0x0000000000000000000000000000000000000000',
to: user,
- tokenId: nextTokenId,
+ tokenId: '1',
},
},
]);
@@ -178,16 +169,16 @@
// 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 result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('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');
@@ -232,39 +223,32 @@
itEth('Check that transaction via EVM spend money from sponsor address', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
- const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
- const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner,'Sponsor collection', '1', '1', '');
const collection = helper.nft.getCollectionObject(collectionId);
const sponsor = await helper.eth.createAccountWithBalance(donor);
- const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- result = await collectionEvm.methods.setCollectionSponsor(sponsor).send();
+ await collectionEvm.methods.setCollectionSponsor(sponsor).send();
let collectionData = (await collection.getData())!;
expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
- const sponsorCollection = helper.ethNativeContract.collection(collectionIdAddress, 'nft', sponsor);
+ const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor);
await sponsorCollection.methods.confirmCollectionSponsorship().send();
collectionData = (await collection.getData())!;
expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
const user = helper.eth.createAccount();
await collectionEvm.methods.addCollectionAdmin(user).send();
-
+
const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
- const userCollectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', user);
- const nextTokenId = await userCollectionEvm.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- result = await userCollectionEvm.methods.mintWithTokenURI(
- user,
- nextTokenId,
- 'Test URI',
- ).send();
+ const userCollectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', user);
+
+ let result = await userCollectionEvm.methods.mintWithTokenURI(user, 'Test URI',).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const events = helper.eth.normalizeEvents(result.events);
const address = helper.ethAddress.fromCollectionId(collectionId);
@@ -276,12 +260,12 @@
args: {
from: '0x0000000000000000000000000000000000000000',
to: user,
- tokenId: nextTokenId,
+ tokenId: '1',
},
},
]);
- expect(await userCollectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
-
+ expect(await userCollectionEvm.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
+
const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -35,13 +35,49 @@
const description = 'Some description';
const prefix = 'token prefix';
- const {collectionId} = await helper.eth.createNonfungibleCollection(owner, name, description, prefix);
+ const {collectionId} = await helper.eth.createNFTCollection(owner, name, description, prefix);
const data = (await helper.rft.getData(collectionId))!;
+ const collection = helper.nft.getCollectionObject(collectionId);
+
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('NFT');
+
+ const options = await collection.getOptions();
+
+ expect(options.tokenPropertyPermissions).to.be.empty;
+ });
+
+ itEth('Create collection with properties', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+ const baseUri = 'BaseURI';
+
+ const {collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, name, description, prefix, baseUri);
+
+ const collection = helper.nft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
expect(data.name).to.be.eq(name);
expect(data.description).to.be.eq(description);
expect(data.raw.tokenPrefix).to.be.eq(prefix);
expect(data.raw.mode).to.be.eq('NFT');
+
+ const options = await collection.getOptions();
+ expect(options.tokenPropertyPermissions).to.be.deep.equal([
+ {
+ key: 'URI',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ {
+ key: 'URISuffix',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ ]);
});
// this test will occasionally fail when in async environment.
@@ -57,7 +93,7 @@
.call()).to.be.false;
await collectionHelpers.methods
- .createNonfungibleCollection('A', 'A', 'A')
+ .createNFTCollection('A', 'A', 'A')
.send({value: Number(2n * helper.balance.getOneTokenNominal())});
expect(await collectionHelpers.methods
@@ -69,7 +105,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const sponsor = await helper.eth.createAccountWithBalance(donor);
const ss58Format = helper.chain.getChainProperties().ss58Format;
- const {collectionId, collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Sponsor', 'absolutely anything', 'ROC');
+ const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(owner, 'Sponsor', 'absolutely anything', 'ROC');
const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
await collection.methods.setCollectionSponsor(sponsor).send();
@@ -88,7 +124,7 @@
itEth('Set limits', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionId, collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Limits', 'absolutely anything', 'FLO');
+ const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(owner, 'Limits', 'absolutely anything', 'FLO');
const limits = {
accountTokenOwnershipLimit: 1000,
sponsoredDataSize: 1024,
@@ -131,7 +167,7 @@
.methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
.to.be.false;
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Exister', 'absolutely anything', 'EVC');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Exister', 'absolutely anything', 'EVC');
expect(await helper.ethNativeContract.collectionHelpers(collectionAddress)
.methods.isCollectionExist(collectionAddress).call())
.to.be.true;
@@ -159,7 +195,7 @@
const tokenPrefix = 'A';
await expect(collectionHelper.methods
- .createNonfungibleCollection(collectionName, description, tokenPrefix)
+ .createNFTCollection(collectionName, description, tokenPrefix)
.call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
}
@@ -169,7 +205,7 @@
const description = 'A'.repeat(MAX_DESCRIPTION_LENGTH + 1);
const tokenPrefix = 'A';
await expect(collectionHelper.methods
- .createNonfungibleCollection(collectionName, description, tokenPrefix)
+ .createNFTCollection(collectionName, description, tokenPrefix)
.call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
}
{
@@ -178,7 +214,7 @@
const description = 'A';
const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
await expect(collectionHelper.methods
- .createNonfungibleCollection(collectionName, description, tokenPrefix)
+ .createNFTCollection(collectionName, description, tokenPrefix)
.call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
}
});
@@ -187,14 +223,14 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
await expect(collectionHelper.methods
- .createNonfungibleCollection('Peasantry', 'absolutely anything', 'CVE')
+ .createNFTCollection('Peasantry', 'absolutely anything', 'CVE')
.call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
itEth('(!negative test!) Check owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const malfeasant = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Transgressed', 'absolutely anything', 'COR');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Transgressed', 'absolutely anything', 'COR');
const malfeasantCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', malfeasant);
const EXPECTED_ERROR = 'NoPermission';
{
@@ -217,10 +253,10 @@
itEth('(!negative test!) Set limits', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Limits', 'absolutely anything', 'OLF');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Limits', 'absolutely anything', 'OLF');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
await expect(collectionEvm.methods
.setCollectionLimit('badLimit', 'true')
.call()).to.be.rejectedWith('unknown boolean limit "badLimit"');
});
-});
\ No newline at end of file
+});
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -37,13 +37,51 @@
const description = 'Some description';
const prefix = 'token prefix';
- const {collectionId} = await helper.eth.createRefungibleCollection(owner, name, description, prefix);
+ const {collectionId} = await helper.eth.createRFTCollection(owner, name, description, prefix);
const data = (await helper.rft.getData(collectionId))!;
+ const collection = helper.rft.getCollectionObject(collectionId);
+
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('ReFungible');
+
+ const options = await collection.getOptions();
+
+ expect(options.tokenPropertyPermissions).to.be.empty;
+ });
+
+
+
+ itEth('Create collection with properties', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+ const baseUri = 'BaseURI';
+
+ const {collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, name, description, prefix, baseUri);
+ const collection = helper.rft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
+
expect(data.name).to.be.eq(name);
expect(data.description).to.be.eq(description);
expect(data.raw.tokenPrefix).to.be.eq(prefix);
expect(data.raw.mode).to.be.eq('ReFungible');
+
+ const options = await collection.getOptions();
+ expect(options.tokenPropertyPermissions).to.be.deep.equal([
+ {
+ key: 'URI',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ {
+ key: 'URISuffix',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ ]);
});
// this test will occasionally fail when in async environment.
@@ -71,7 +109,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const sponsor = await helper.eth.createAccountWithBalance(donor);
const ss58Format = helper.chain.getChainProperties().ss58Format;
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Sponsor', 'absolutely anything', 'ENVY');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Sponsor', 'absolutely anything', 'ENVY');
const collection = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
await collection.methods.setCollectionSponsor(sponsor).send();
@@ -90,7 +128,7 @@
itEth('Set limits', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Limits', 'absolutely anything', 'INSI');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Limits', 'absolutely anything', 'INSI');
const limits = {
accountTokenOwnershipLimit: 1000,
sponsoredDataSize: 1024,
@@ -133,7 +171,7 @@
.methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
.to.be.false;
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Exister', 'absolutely anything', 'WIWT');
+ const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Exister', 'absolutely anything', 'WIWT');
expect(await helper.ethNativeContract.collectionHelpers(collectionAddress)
.methods.isCollectionExist(collectionAddress).call())
.to.be.true;
@@ -196,7 +234,7 @@
itEth('(!negative test!) Check owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const peasant = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Transgressed', 'absolutely anything', 'YVNE');
+ const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Transgressed', 'absolutely anything', 'YVNE');
const peasantCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', peasant);
const EXPECTED_ERROR = 'NoPermission';
{
@@ -219,7 +257,7 @@
itEth('(!negative test!) Set limits', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Limits', 'absolutely anything', 'ISNI');
+ const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Limits', 'absolutely anything', 'ISNI');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
await expect(collectionEvm.methods
.setCollectionLimit('badLimit', 'true')
tests/src/eth/evmCoder.test.tsdiffbeforeafterboth--- a/tests/src/eth/evmCoder.test.ts
+++ b/tests/src/eth/evmCoder.test.ts
@@ -65,7 +65,7 @@
itEth('Call non-existing function', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.eth.createNonfungibleCollection(owner, 'EVMCODER', '', 'TEST');
+ const collection = await helper.eth.createNFTCollection(owner, 'EVMCODER', '', 'TEST');
const contract = await helper.ethContract.deployByCode(owner, 'Test', getContractSource(collection.collectionAddress, '0x1bfed5D614b886b9Ab2eA4CBAc22A96B7EC29c9c'));
const testContract = await helper.ethContract.deployByCode(owner, 'Test', getContractSource(collection.collectionAddress, contract.options.address));
{
tests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth--- a/tests/src/eth/fractionalizer/Fractionalizer.sol
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -124,8 +124,7 @@
address rftTokenAddress;
UniqueRefungibleToken rftTokenContract;
if (nft2rftMapping[_collection][_token] == 0) {
- rftTokenId = rftCollectionContract.nextTokenId();
- rftCollectionContract.mint(address(this), rftTokenId);
+ rftTokenId = rftCollectionContract.mint(address(this));
rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);
nft2rftMapping[_collection][_token] = rftTokenId;
rft2nftMapping[rftTokenAddress] = Token(_collection, _token);
tests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth--- a/tests/src/eth/fractionalizer/fractionalizer.test.ts
+++ b/tests/src/eth/fractionalizer/fractionalizer.test.ts
@@ -62,10 +62,10 @@
const mintRFTToken = async (helper: EthUniqueHelper, owner: string, fractionalizer: Contract, amount: bigint): Promise<{
nftCollectionAddress: string, nftTokenId: number, rftTokenAddress: string
}> => {
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
await fractionalizer.methods.setNftCollectionIsAllowed(nftCollection.collectionAddress, true).send({from: owner});
await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send({from: owner});
@@ -92,7 +92,7 @@
itEth('Set RFT collection', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 10n);
const fractionalizer = await deployContract(helper, owner);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const rftContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
await rftContract.methods.addCollectionAdmin(fractionalizer.options.address).send({from: owner});
@@ -121,7 +121,7 @@
itEth('Set Allowlist', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const {contract: fractionalizer} = await initContract(helper, owner);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollection.collectionAddress, true).send({from: owner});
expect(result1.events).to.be.like({
@@ -146,10 +146,10 @@
itEth('NFT to RFT', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
const {contract: fractionalizer} = await initContract(helper, owner);
@@ -231,7 +231,7 @@
itEth('call setRFTCollection twice', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
const fractionalizer = await deployContract(helper, owner);
@@ -244,7 +244,7 @@
itEth('call setRFTCollection with NFT collection', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
const fractionalizer = await deployContract(helper, owner);
@@ -257,7 +257,7 @@
itEth('call setRFTCollection while not collection admin', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const fractionalizer = await deployContract(helper, owner);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
await expect(fractionalizer.methods.setRFTCollection(rftCollection.collectionAddress).call())
.to.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);
@@ -278,10 +278,10 @@
itEth('call nft2rft without setting RFT collection for contract', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
const fractionalizer = await deployContract(helper, owner);
@@ -293,10 +293,10 @@
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const nftOwner = await helper.eth.createAccountWithBalance(donor, 10n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
await nftContract.methods.transfer(nftOwner, 1).send({from: owner});
@@ -310,10 +310,10 @@
itEth('call nft2rft while not in list of allowed accounts', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
const {contract: fractionalizer} = await initContract(helper, owner);
@@ -325,10 +325,10 @@
itEth('call nft2rft while fractionalizer doesnt have approval for nft token', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
const {contract: fractionalizer} = await initContract(helper, owner);
@@ -341,11 +341,11 @@
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const fractionalizer = await deployContract(helper, owner);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
- const rftTokenId = await refungibleContract.methods.nextTokenId().call();
- await refungibleContract.methods.mint(owner, rftTokenId).send({from: owner});
-
+ const mintResult = await refungibleContract.methods.mint(owner).send({from: owner});
+ const rftTokenId = mintResult.events.Transfer.returnValues.tokenId;
+
await expect(fractionalizer.methods.rft2nft(rftCollection.collectionAddress, rftTokenId).call({from: owner}))
.to.be.rejectedWith(/RFT collection is not set$/g);
});
@@ -354,18 +354,18 @@
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const {contract: fractionalizer} = await initContract(helper, owner);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
- const rftTokenId = await refungibleContract.methods.nextTokenId().call();
- await refungibleContract.methods.mint(owner, rftTokenId).send({from: owner});
-
+ const mintResult = await refungibleContract.methods.mint(owner).send({from: owner});
+ const rftTokenId = mintResult.events.Transfer.returnValues.tokenId;
+
await expect(fractionalizer.methods.rft2nft(rftCollection.collectionAddress, rftTokenId).call())
.to.be.rejectedWith(/Wrong RFT collection$/g);
});
itEth('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
const fractionalizer = await deployContract(helper, owner);
@@ -373,9 +373,9 @@
await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send({from: owner});
await fractionalizer.methods.setRFTCollection(rftCollection.collectionAddress).send({from: owner});
- const rftTokenId = await refungibleContract.methods.nextTokenId().call();
- await refungibleContract.methods.mint(owner, rftTokenId).send({from: owner});
-
+ const mintResult = await refungibleContract.methods.mint(owner).send({from: owner});
+ const rftTokenId = mintResult.events.Transfer.returnValues.tokenId;
+
await expect(fractionalizer.methods.rft2nft(rftCollection.collectionAddress, rftTokenId).call())
.to.be.rejectedWith(/No corresponding NFT token found$/g);
});
@@ -386,7 +386,7 @@
const {contract: fractionalizer, rftCollectionAddress} = await initContract(helper, owner);
const {rftTokenAddress} = await mintRFTToken(helper, owner, fractionalizer, 100n);
-
+
const {tokenId} = helper.ethAddress.extractTokenId(rftTokenAddress);
const refungibleTokenContract = helper.ethNativeContract.rftToken(rftTokenAddress, owner);
await refungibleTokenContract.methods.transfer(receiver, 50).send({from: owner});
@@ -420,7 +420,7 @@
await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftToken.tokenId, 100).call())
.to.be.rejectedWith(/TransferNotAllowed$/g);
});
-
+
itEth('fractionalize NFT with RFT transfers disallowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
@@ -432,10 +432,10 @@
await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send({from: owner});
await helper.executeExtrinsic(donor, 'api.tx.unique.setTransfersEnabledFlag', [rftCollection.collectionId, false], true);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
await fractionalizer.methods.setNftCollectionIsAllowed(nftCollection.collectionAddress, true).send({from: owner});
await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send({from: owner});
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -116,6 +116,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "address", "name": "newOwner", "type": "address" }
+ ],
+ "name": "changeCollectionOwner",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "collectionOwner",
"outputs": [
@@ -329,15 +338,6 @@
{ "internalType": "address", "name": "sponsor", "type": "address" }
],
"name": "setCollectionSponsor",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "address", "name": "newOwner", "type": "address" }
- ],
- "name": "setOwner",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
tests/src/eth/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -7,7 +7,7 @@
helper: EthUniqueHelper,
owner: string,
): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
await contract.methods.setCollectionNesting(true).send({from: owner});
@@ -29,74 +29,53 @@
itEth('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionId, contract} = await createNestingCollection(helper, owner);
-
- // Create a token to be nested
- const targetNFTTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- targetNFTTokenId,
- ).send({from: owner});
-
+
+ // Create a token to be nested to
+ const mintingTargetNFTTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const targetNFTTokenId = mintingTargetNFTTokenIdResult.events.Transfer.returnValues.tokenId;
const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNFTTokenId);
-
+
// Create a nested token
- const firstTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- targetNftTokenAddress,
- firstTokenId,
- ).send({from: owner});
-
+ const mintingFirstTokenIdResult = await contract.methods.mint(targetNftTokenAddress).send({from: owner});
+ const firstTokenId = mintingFirstTokenIdResult.events.Transfer.returnValues.tokenId;
expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
-
+
// Create a token to be nested and nest
- const secondTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- secondTokenId,
- ).send({from: owner});
-
+ const mintingSecondTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const secondTokenId = mintingSecondTokenIdResult.events.Transfer.returnValues.tokenId;
+
await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
-
expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
-
+
// Unnest token back
await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
});
-
+
itEth('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
-
+
// Create a token to nest into
- const targetNftTokenId = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- targetNftTokenId,
- ).send({from: owner});
+ const mintingtargetNftTokenIdResult = await contractA.methods.mint(owner).send({from: owner});
+ const targetNftTokenId = mintingtargetNftTokenIdResult.events.Transfer.returnValues.tokenId;
const nftTokenAddressA1 = helper.ethAddress.fromTokenId(collectionIdA, targetNftTokenId);
-
+
// Create a token for nesting in the same collection as the target
- const nftTokenIdA = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- nftTokenIdA,
- ).send({from: owner});
-
+ const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
+ const nftTokenIdA = mintingTokenIdAResult.events.Transfer.returnValues.tokenId;
+
// Create a token for nesting in a different collection
- const nftTokenIdB = await contractB.methods.nextTokenId().call();
- await contractB.methods.mint(
- owner,
- nftTokenIdB,
- ).send({from: owner});
-
+ const mintingTokenIdBResult = await contractB.methods.mint(owner).send({from: owner});
+ const nftTokenIdB = mintingTokenIdBResult.events.Transfer.returnValues.tokenId;
+
// Nest
await contractA.methods.transfer(nftTokenAddressA1, nftTokenIdA).send({from: owner});
expect(await contractA.methods.ownerOf(nftTokenIdA).call()).to.be.equal(nftTokenAddressA1);
-
+
await contractB.methods.transfer(nftTokenAddressA1, nftTokenIdB).send({from: owner});
expect(await contractB.methods.ownerOf(nftTokenIdB).call()).to.be.equal(nftTokenAddressA1);
});
@@ -105,112 +84,88 @@
describe('Negative Test: EVM Nesting', async() => {
itEth('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId, contract} = await createNestingCollection(helper, owner);
await contract.methods.setCollectionNesting(false).send({from: owner});
-
+
// Create a token to nest into
- const targetNftTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- targetNftTokenId,
- ).send({from: owner});
-
- const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNftTokenId);
-
+ const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+ const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
+
// Create a token to nest
- const nftTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- nftTokenId,
- ).send({from: owner});
-
+ const mintingNftTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintingNftTokenIdResult.events.Transfer.returnValues.tokenId;
+
// Try to nest
await expect(contract.methods
.transfer(targetNftTokenAddress, nftTokenId)
.call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
});
-
+
itEth('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const malignant = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId, contract} = await createNestingCollection(helper, owner);
-
+
// Mint a token
- const targetTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- targetTokenId,
- ).send({from: owner});
+ const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
const targetTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
-
+
// Mint a token belonging to a different account
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- malignant,
- tokenId,
- ).send({from: owner});
-
+ const mintingTokenIdResult = await contract.methods.mint(malignant).send({from: owner});
+ const tokenId = mintingTokenIdResult.events.Transfer.returnValues.tokenId;
+
// Try to nest one token in another as a non-owner account
await expect(contract.methods
.transfer(targetTokenAddress, tokenId)
.call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
});
-
+
itEth('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const malignant = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
-
+
await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
-
+
// Create a token in one collection
- const nftTokenIdA = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- nftTokenIdA,
- ).send({from: owner});
+ const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
+ const nftTokenIdA = mintingTokenIdAResult.events.Transfer.returnValues.tokenId;
const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
-
- // Create a token in another collection belonging to someone else
- const nftTokenIdB = await contractB.methods.nextTokenId().call();
- await contractB.methods.mint(
- malignant,
- nftTokenIdB,
- ).send({from: owner});
-
+
+ // Create a token in another collection
+ const mintingTokenIdBResult = await contractB.methods.mint(malignant).send({from: owner});
+ const nftTokenIdB = mintingTokenIdBResult.events.Transfer.returnValues.tokenId;
+
// Try to drag someone else's token into the other collection and nest
await expect(contractB.methods
.transfer(nftTokenAddressA, nftTokenIdB)
.call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
});
-
+
itEth('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
const {contract: contractB} = await createNestingCollection(helper, owner);
-
+
await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});
-
+
// Create a token in one collection
- const nftTokenIdA = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- nftTokenIdA,
- ).send({from: owner});
+ const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
+ const nftTokenIdA = mintingTokenIdAResult.events.Transfer.returnValues.tokenId;
const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
-
+
// Create a token in another collection
- const nftTokenIdB = await contractB.methods.nextTokenId().call();
- await contractB.methods.mint(
- owner,
- nftTokenIdB,
- ).send({from: owner});
-
+ const mintingTokenIdBResult = await contractB.methods.mint(owner).send({from: owner});
+ const nftTokenIdB = mintingTokenIdBResult.events.Transfer.returnValues.tokenId;
+
+
// Try to nest into a token in the other collection, disallowed in the first
await expect(contractB.methods
.transfer(nftTokenAddressA, nftTokenIdB)
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -29,7 +29,7 @@
[alice] = await helper.arrange.createAccounts([10n], donor);
});
});
-
+
itEth('totalSupply', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {});
await collection.mintToken(alice);
@@ -68,6 +68,16 @@
expect(owner).to.equal(caller);
});
+
+ itEth('name/symbol is available regardless of ERC721Metadata support', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'test', tokenPrefix: 'TEST'});
+ const caller = helper.eth.createAccount();
+
+ const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
+
+ expect(await contract.methods.name().call()).to.equal('test');
+ expect(await contract.methods.symbol().call()).to.equal('TEST');
+ });
});
describe('Check ERC721 token URI for NFT', () => {
@@ -79,34 +89,29 @@
});
});
- async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+ async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
- const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
-
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- result = await contract.methods.mint(
- receiver,
- nextTokenId,
- ).send();
+ const result = await contract.methods.mint(receiver).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
+
if (propertyKey && propertyValue) {
// Set URL or suffix
- await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();
+ await contract.methods.setProperty(tokenId, propertyKey, Buffer.from(propertyValue)).send();
}
const event = result.events.Transfer;
expect(event.address).to.be.equal(collectionAddress);
expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.be.equal(receiver);
- expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
+ expect(event.returnValues.tokenId).to.be.equal(tokenId);
- return {contract, nextTokenId};
+ return {contract, nextTokenId: tokenId};
}
itEth('Empty tokenURI', async ({helper}) => {
@@ -115,18 +120,18 @@
});
itEth('TokenURI from url', async ({helper}) => {
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
});
- itEth('TokenURI from baseURI + tokenId', async ({helper}) => {
+ itEth('TokenURI from baseURI', async ({helper}) => {
const {contract, nextTokenId} = await setup(helper, 'BaseURI_');
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);
+ expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');
});
itEth('TokenURI from baseURI + suffix', async ({helper}) => {
const suffix = '/some/suffix';
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
});
});
@@ -146,24 +151,19 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Minty', '6', '6');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- const result = await contract.methods.mintWithTokenURI(
- receiver,
- nextTokenId,
- 'Test URI',
- ).send();
+ const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
const event = result.events.Transfer;
expect(event.address).to.be.equal(collectionAddress);
expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.be.equal(receiver);
- expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
// TODO: this wont work right now, need release 919000 first
// await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();
@@ -216,7 +216,7 @@
{
const result = await contract.methods.burn(tokenId).send({from: caller});
-
+
const event = result.events.Transfer;
expect(event.address).to.be.equal(collectionAddress);
expect(event.returnValues.from).to.be.equal(caller);
@@ -322,7 +322,7 @@
[alice] = await helper.arrange.createAccounts([10n], donor);
});
});
-
+
itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const spender = helper.eth.createAccount();
@@ -403,7 +403,7 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-
+
const events: any = [];
contract.events.allEvents((_: any, event: any) => {
events.push(event);
@@ -428,7 +428,7 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-
+
const events: any = [];
contract.events.allEvents((_: any, event: any) => {
events.push(event);
@@ -455,13 +455,14 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-
+
const events: any = [];
contract.events.allEvents((_: any, event: any) => {
events.push(event);
});
await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver});
+
if (events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
@@ -479,13 +480,14 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-
+
const events: any = [];
contract.events.allEvents((_: any, event: any) => {
events.push(event);
});
await token.transfer(alice, {Ethereum: receiver});
+
if (events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
@@ -509,7 +511,23 @@
itEth('Returns collection name', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.nft.mintCollection(
+ alice,
+ {
+ name: 'oh River',
+ tokenPrefix: 'CHANGE',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
const name = await contract.methods.name().call();
@@ -518,10 +536,26 @@
itEth('Returns symbol name', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.nft.mintCollection(
+ alice,
+ {
+ name: 'oh River',
+ tokenPrefix: 'CHANGE',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
const symbol = await contract.methods.symbol().call();
expect(symbol).to.equal('CHANGE');
});
-});
\ No newline at end of file
+});
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -146,6 +146,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "address", "name": "newOwner", "type": "address" }
+ ],
+ "name": "changeCollectionOwner",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "collectionOwner",
"outputs": [
@@ -260,12 +269,9 @@
"type": "function"
},
{
- "inputs": [
- { "internalType": "address", "name": "to", "type": "address" },
- { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
- ],
+ "inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
"name": "mint",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
"type": "function"
},
@@ -287,7 +293,7 @@
{ "internalType": "uint256", "name": "field_0", "type": "uint256" },
{ "internalType": "string", "name": "field_1", "type": "string" }
],
- "internalType": "struct Tuple8[]",
+ "internalType": "struct Tuple6[]",
"name": "tokens",
"type": "tuple[]"
}
@@ -300,11 +306,10 @@
{
"inputs": [
{ "internalType": "address", "name": "to", "type": "address" },
- { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{ "internalType": "string", "name": "tokenUri", "type": "string" }
],
"name": "mintWithTokenURI",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
"type": "function"
},
@@ -476,15 +481,6 @@
{ "internalType": "address", "name": "sponsor", "type": "address" }
],
"name": "setCollectionSponsor",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "address", "name": "newOwner", "type": "address" }
- ],
- "name": "setOwner",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
tests/src/eth/payable.test.tsdiffbeforeafterboth--- a/tests/src/eth/payable.test.ts
+++ b/tests/src/eth/payable.test.ts
@@ -118,7 +118,7 @@
const deployer = await helper.eth.createAccountWithBalance(donor);
const caller = await helper.eth.createAccountWithBalance(donor);
const contract = await helper.eth.deployFlipper(deployer);
-
+
const initialCallerBalance = await helper.balance.getEthereum(caller);
await contract.methods.flip().send({from: caller});
const finalCallerBalance = await helper.balance.getEthereum(caller);
@@ -129,7 +129,7 @@
const deployer = await helper.eth.createAccountWithBalance(donor);
const caller = await helper.eth.createAccountWithBalance(donor);
const contract = await deployProxyContract(helper, deployer);
-
+
const initialCallerBalance = await helper.balance.getEthereum(caller);
const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
await contract.methods.flip().send({from: caller});
@@ -138,7 +138,7 @@
expect(finalCallerBalance < initialCallerBalance).to.be.true;
expect(finalContractBalance == initialContractBalance).to.be.true;
});
-
+
itEth('Fee for nested calls to native methods is withdrawn from the user', async({helper}) => {
const CONTRACT_BALANCE = 2n * helper.balance.getOneTokenNominal();
@@ -146,7 +146,7 @@
const caller = await helper.eth.createAccountWithBalance(donor);
const contract = await deployProxyContract(helper, deployer);
- const collectionAddress = (await contract.methods.createNonfungibleCollection().send({from: caller, value: Number(CONTRACT_BALANCE)})).events.CollectionCreated.returnValues.collection;
+ const collectionAddress = (await contract.methods.createNFTCollection().send({from: caller, value: Number(CONTRACT_BALANCE)})).events.CollectionCreated.returnValues.collection;
const initialCallerBalance = await helper.balance.getEthereum(caller);
const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
await contract.methods.mintNftToken(collectionAddress).send({from: caller});
@@ -155,7 +155,7 @@
expect(finalCallerBalance < initialCallerBalance).to.be.true;
expect(finalContractBalance == initialContractBalance).to.be.true;
});
-
+
itEth('Fee for nested calls to create*Collection methods is withdrawn from the user and from the contract', async({helper}) => {
const CONTRACT_BALANCE = 2n * helper.balance.getOneTokenNominal();
const deployer = await helper.eth.createAccountWithBalance(donor);
@@ -164,7 +164,7 @@
const initialCallerBalance = await helper.balance.getEthereum(caller);
const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
- await contract.methods.createNonfungibleCollection().send({from: caller, value: Number(CONTRACT_BALANCE)});
+ await contract.methods.createNFTCollection().send({from: caller, value: Number(CONTRACT_BALANCE)});
const finalCallerBalance = await helper.balance.getEthereum(caller);
const finalContractBalance = await helper.balance.getEthereum(contract.options.address);
expect(finalCallerBalance < initialCallerBalance).to.be.true;
@@ -176,9 +176,9 @@
const BIG_FEE = 3n * helper.balance.getOneTokenNominal();
const caller = await helper.eth.createAccountWithBalance(donor);
const collectionHelper = helper.ethNativeContract.collectionHelpers(caller);
-
- await expect(collectionHelper.methods.createNonfungibleCollection('A', 'B', 'C').call({value: Number(SMALL_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
- await expect(collectionHelper.methods.createNonfungibleCollection('A', 'B', 'C').call({value: Number(BIG_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+
+ await expect(collectionHelper.methods.createNFTCollection('A', 'B', 'C').call({value: Number(SMALL_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+ await expect(collectionHelper.methods.createNFTCollection('A', 'B', 'C').call({value: Number(BIG_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
itEth('Negative test: call createRFTCollection with wrong fee', async({helper}) => {
@@ -186,7 +186,7 @@
const BIG_FEE = 3n * helper.balance.getOneTokenNominal();
const caller = await helper.eth.createAccountWithBalance(donor);
const collectionHelper = helper.ethNativeContract.collectionHelpers(caller);
-
+
await expect(collectionHelper.methods.createRFTCollection('A', 'B', 'C').call({value: Number(SMALL_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
await expect(collectionHelper.methods.createRFTCollection('A', 'B', 'C').call({value: Number(BIG_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
@@ -227,16 +227,15 @@
InnerContract(innerContract).flip();
}
- function createNonfungibleCollection() external payable {
+ function createNFTCollection() external payable {
address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;
- address nftCollection = CollectionHelpers(collectionHelpers).createNonfungibleCollection{value: msg.value}("A", "B", "C");
+ address nftCollection = CollectionHelpers(collectionHelpers).createNFTCollection{value: msg.value}("A", "B", "C");
emit CollectionCreated(nftCollection);
}
function mintNftToken(address collectionAddress) external {
UniqueNFT collection = UniqueNFT(collectionAddress);
- uint256 tokenId = collection.nextTokenId();
- collection.mint(msg.sender, tokenId);
+ uint256 tokenId = collection.mint(msg.sender);
emit TokenMinted(tokenId);
}
tests/src/eth/proxy/UniqueNFTProxy.soldiffbeforeafterboth--- a/tests/src/eth/proxy/UniqueNFTProxy.sol
+++ b/tests/src/eth/proxy/UniqueNFTProxy.sol
@@ -120,20 +120,19 @@
return proxied.mintingFinished();
}
- function mint(address to, uint256 tokenId)
+ function mint(address to)
external
override
- returns (bool)
+ returns (uint256)
{
- return proxied.mint(to, tokenId);
+ return proxied.mint(to);
}
function mintWithTokenURI(
address to,
- uint256 tokenId,
string memory tokenUri
- ) external override returns (bool) {
- return proxied.mintWithTokenURI(to, tokenId, tokenUri);
+ ) external override returns (uint256) {
+ return proxied.mintWithTokenURI(to, tokenUri);
}
function finishMinting() external override returns (bool) {
@@ -169,7 +168,7 @@
return proxied.mintBulk(to, tokenIds);
}
- function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens)
external
override
returns (bool)
tests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -101,7 +101,7 @@
itEth('Can perform mint()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'A', 'A');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'A', 'A', '');
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
@@ -111,13 +111,11 @@
await collectionEvmOwned.methods.addCollectionAdmin(contract.options.address).send();
{
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- const result = await contract.methods.mintWithTokenURI(
- receiver,
- nextTokenId,
- 'Test URI',
- ).send({from: caller});
+ const nextTokenId = await contract.methods.nextTokenId().call()
+ const result = await contract.methods.mintWithTokenURI(receiver, nextTokenId, 'Test URI').send({from: caller});
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
+
const events = helper.eth.normalizeEvents(result.events);
events[0].address = events[0].address.toLocaleLowerCase();
@@ -128,12 +126,12 @@
args: {
from: '0x0000000000000000000000000000000000000000',
to: receiver,
- tokenId: nextTokenId,
+ tokenId,
},
},
]);
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
}
});
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -31,31 +31,23 @@
itEth('totalSupply', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TotalSupply', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'TotalSupply', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const nextTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, nextTokenId).send();
+
+ await contract.methods.mint(caller).send();
+
const totalSupply = await contract.methods.totalSupply().call();
expect(totalSupply).to.equal('1');
});
itEth('balanceOf', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'BalanceOf', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'BalanceOf', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- {
- const nextTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, nextTokenId).send();
- }
- {
- const nextTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, nextTokenId).send();
- }
- {
- const nextTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, nextTokenId).send();
- }
+ await contract.methods.mint(caller).send();
+ await contract.methods.mint(caller).send();
+ await contract.methods.mint(caller).send();
const balance = await contract.methods.balanceOf(caller).call();
expect(balance).to.equal('3');
@@ -63,11 +55,11 @@
itEth('ownerOf', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'OwnerOf', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const owner = await contract.methods.ownerOf(tokenId).call();
expect(owner).to.equal(caller);
@@ -76,11 +68,11 @@
itEth('ownerOf after burn', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf-AfterBurn', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'OwnerOf-AfterBurn', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
await tokenContract.methods.repartition(2).send();
@@ -95,11 +87,11 @@
itEth('ownerOf for partial ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Partial-OwnerOf', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Partial-OwnerOf', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
await tokenContract.methods.repartition(2).send();
@@ -124,30 +116,25 @@
itEth('Can perform mint()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Minty', '6', '6');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Minty', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- const result = await contract.methods.mintWithTokenURI(
- receiver,
- nextTokenId,
- 'Test URI',
- ).send();
+ const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();
+
const event = result.events.Transfer;
expect(event.address).to.equal(collectionAddress);
expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.equal(receiver);
- expect(event.returnValues.tokenId).to.equal(nextTokenId);
+ const tokenId = event.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
});
itEth('Can perform mintBulk()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'MintBulky', '6', '6');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'MintBulky', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
{
@@ -179,11 +166,11 @@
itEth('Can perform burn()', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Burny', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Burny', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
{
const result = await contract.methods.burn(tokenId).send();
const event = result.events.Transfer;
@@ -197,12 +184,13 @@
itEth('Can perform transferFrom()', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TransferFromy', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'TransferFromy', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+
const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
- await contract.methods.mint(caller, tokenId).send();
const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);
await tokenContract.methods.repartition(15).send();
@@ -241,15 +229,15 @@
itEth('Can perform transfer()', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
{
const result = await contract.methods.transfer(receiver, tokenId).send();
-
+
const event = result.events.Transfer;
expect(event.address).to.equal(collectionAddress);
expect(event.returnValues.from).to.equal(caller);
@@ -271,11 +259,11 @@
itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Partial-to-Full', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Partial-to-Full', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
@@ -300,11 +288,11 @@
itEth('transfer event on transfer from full ownership to partial ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Full-to-Partial', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Full-to-Partial', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
@@ -340,11 +328,11 @@
itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer-From', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer-From', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
@@ -354,11 +342,11 @@
itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transfer(receiver, tokenId).send());
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
@@ -381,8 +369,24 @@
itEth('Returns collection name', async ({helper}) => {
const caller = helper.eth.createAccount();
- const collection = await helper.rft.mintCollection(alice, {name: 'Leviathan', tokenPrefix: '11'});
-
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.rft.mintCollection(
+ alice,
+ {
+ name: 'Leviathan',
+ tokenPrefix: '11',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
+
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);
const name = await contract.methods.name().call();
expect(name).to.equal('Leviathan');
@@ -390,8 +394,25 @@
itEth('Returns symbol name', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Leviathan', '', '12');
- const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const {collectionId} = await helper.rft.mintCollection(
+ alice,
+ {
+ name: 'Leviathan',
+ tokenPrefix: '12',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
+
+ const contract = helper.ethNativeContract.collectionById(collectionId, 'rft', caller);
const symbol = await contract.methods.symbol().call();
expect(symbol).to.equal('12');
});
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -146,6 +146,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "address", "name": "newOwner", "type": "address" }
+ ],
+ "name": "changeCollectionOwner",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "collectionOwner",
"outputs": [
@@ -260,12 +269,9 @@
"type": "function"
},
{
- "inputs": [
- { "internalType": "address", "name": "to", "type": "address" },
- { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
- ],
+ "inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
"name": "mint",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
"type": "function"
},
@@ -287,7 +293,7 @@
{ "internalType": "uint256", "name": "field_0", "type": "uint256" },
{ "internalType": "string", "name": "field_1", "type": "string" }
],
- "internalType": "struct Tuple8[]",
+ "internalType": "struct Tuple6[]",
"name": "tokens",
"type": "tuple[]"
}
@@ -300,11 +306,10 @@
{
"inputs": [
{ "internalType": "address", "name": "to", "type": "address" },
- { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{ "internalType": "string", "name": "tokenUri", "type": "string" }
],
"name": "mintWithTokenURI",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
"type": "function"
},
@@ -476,15 +481,6 @@
{ "internalType": "address", "name": "sponsor", "type": "address" }
],
"name": "setCollectionSponsor",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "address", "name": "newOwner", "type": "address" }
- ],
- "name": "setOwner",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -76,34 +76,28 @@
});
});
- async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+ async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
- const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- result = await contract.methods.mint(
- receiver,
- nextTokenId,
- ).send();
- if (propertyKey && propertyValue) {
- // Set URL or suffix
- await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();
- }
+ const result = await contract.methods.mint(receiver).send();
const event = result.events.Transfer;
+ const tokenId = event.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
expect(event.address).to.be.equal(collectionAddress);
expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.be.equal(receiver);
- expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
- return {contract, nextTokenId};
+ if (propertyKey && propertyValue) {
+ // Set URL or suffix
+ await contract.methods.setProperty(tokenId, propertyKey, Buffer.from(propertyValue)).send();
+ }
+
+ return {contract, nextTokenId: tokenId};
}
itEth('Empty tokenURI', async ({helper}) => {
@@ -112,18 +106,18 @@
});
itEth('TokenURI from url', async ({helper}) => {
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
});
- itEth('TokenURI from baseURI + tokenId', async ({helper}) => {
+ itEth('TokenURI from baseURI', async ({helper}) => {
const {contract, nextTokenId} = await setup(helper, 'BaseURI_');
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);
+ expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');
});
itEth('TokenURI from baseURI + suffix', async ({helper}) => {
const suffix = '/some/suffix';
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
});
});
@@ -294,11 +288,11 @@
itEth('Receiving Transfer event on burning into full ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = await helper.eth.createAccountWithBalance(donor);
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Devastation', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Devastation', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);
@@ -484,11 +478,12 @@
itEth('Default parent token address and id', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Sands', '', 'GRAIN');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Sands', '', 'GRAIN');
const collectionContract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-
- const tokenId = await collectionContract.methods.nextTokenId().call();
- await collectionContract.methods.mint(owner, tokenId).send();
+
+ const result = await collectionContract.methods.mint(owner).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+
const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, owner);
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -43,12 +43,12 @@
if(!imports) return function(path: string) {
return {error: `File not found: ${path}`};
};
-
+
const knownImports = {} as {[key: string]: string};
for(const imp of imports) {
knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();
}
-
+
return function(path: string) {
if(path in knownImports) return {contents: knownImports[path]};
return {error: `File not found: ${path}`};
@@ -71,7 +71,7 @@
},
},
}), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];
-
+
return {
abi: out.abi,
object: '0x' + out.evm.bytecode.object,
@@ -94,7 +94,7 @@
}
}
-
+
class NativeContractGroup extends EthGroupBase {
contractHelpers(caller: string): Contract {
@@ -145,14 +145,14 @@
async createAccountWithBalance(donor: IKeyringPair, amount=100n) {
const account = this.createAccount();
await this.transferBalanceFromSubstrate(donor, account, amount);
-
+
return account;
}
async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=100n, inTokens=true) {
return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));
}
-
+
async getCollectionCreationFee(signer: string) {
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
return await collectionHelper.methods.collectionCreationFee().call();
@@ -174,22 +174,32 @@
return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);
}
- async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+ async createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
-
- const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
+ const result = await collectionHelper.methods.createNFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
+
const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
return {collectionId, collectionAddress};
}
- async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+ async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+ const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
+
+ const {collectionId, collectionAddress} = await this.createNFTCollection(signer, name, description, tokenPrefix)
+
+ await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
+
+ return {collectionId, collectionAddress};
+ }
+
+ async createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
-
+
const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
@@ -198,6 +208,16 @@
return {collectionId, collectionAddress};
}
+ async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+ const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
+
+ const {collectionId, collectionAddress} = await this.createRFTCollection(signer, name, description, tokenPrefix)
+
+ await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
+
+ return {collectionId, collectionAddress};
+ }
+
async deployCollectorContract(signer: string): Promise<Contract> {
return await this.helper.ethContract.deployByCode(signer, 'Collector', `
// SPDX-License-Identifier: UNLICENSED
@@ -288,7 +308,7 @@
};
return await this.helper.arrange.calculcateFee(address, wrappedCode);
}
-}
+}
class EthAddressGroup extends EthGroupBase {
extractCollectionId(address: string): number {
@@ -319,8 +339,8 @@
normalizeAddress(address: string): string {
return '0x' + address.substring(address.length - 40);
}
-}
-
+}
+
export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;
export class EthUniqueHelper extends DevUniqueHelper {
@@ -373,4 +393,3 @@
return newHelper;
}
}
-
\ No newline at end of file
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -1026,6 +1026,10 @@
return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();
}
+ async getCollectionOptions(collectionId: number) {
+ return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();
+ }
+
/**
* Deletes onchain properties from the collection.
*
@@ -2839,6 +2843,10 @@
return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);
}
+ async getOptions() {
+ return await this.helper.collection.getCollectionOptions(this.collectionId);
+ }
+
async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {
return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);
}