difftreelog
Merge pull request #728 from UniqueNetwork/feature/newCallMethods
in: master
Added new call functions
31 files changed
crates/evm-coder/src/abi/impls.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi/impls.rs
+++ b/crates/evm-coder/src/abi/impls.rs
@@ -184,8 +184,7 @@
impl AbiWrite for Property {
fn abi_write(&self, writer: &mut AbiWriter) {
- self.key.abi_write(writer);
- self.value.abi_write(writer);
+ (&self.key, &self.value).abi_write(writer);
}
}
crates/evm-coder/src/abi/traits.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi/traits.rs
+++ b/crates/evm-coder/src/abi/traits.rs
@@ -49,3 +49,9 @@
Ok(writer.into())
}
}
+
+impl<T: AbiWrite> AbiWrite for &T {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ T::abi_write(self, writer);
+ }
+}
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -178,7 +178,7 @@
///
/// @param keys Properties keys. Empty keys for all propertyes.
/// @return Vector of properties key/value pairs.
- fn collection_properties(&self, keys: Vec<string>) -> Result<Vec<(string, bytes)>> {
+ fn collection_properties(&self, keys: Vec<string>) -> Result<Vec<PropertyStruct>> {
let keys = keys
.into_iter()
.map(|key| {
@@ -200,7 +200,7 @@
let key =
string::from_utf8(p.key.into()).map_err(|e| Error::Revert(format!("{}", e)))?;
let value = bytes(p.value.to_vec());
- Ok((key, value))
+ Ok(PropertyStruct { key, value })
})
.collect::<Result<Vec<_>>>()?;
Ok(properties)
pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/fungible/CHANGELOG.md
+++ b/pallets/fungible/CHANGELOG.md
@@ -4,12 +4,22 @@
<!-- bureaucrate goes here -->
+## [0.1.8] - 2022-11-18
+
+### Added
+
+- The function `description` to `ERC20UniqueExtensions` interface.
+
## [0.1.7] - 2022-11-14
### Changed
- Added `transfer_cross` in eth functions.
+### Changed
+
+- Use named structure `EthCrossAccount` in eth functions.
+
## [0.1.6] - 2022-11-02
### Changed
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -158,6 +158,13 @@
where
T::AccountId: From<[u8; 32]>,
{
+ /// @notice A description for the collection.
+ fn description(&self) -> Result<string> {
+ Ok(decode_utf16(self.description.iter().copied())
+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+ .collect::<string>())
+ }
+
#[weight(<SelfWeightOf<T>>::approve())]
fn approve_cross(
&mut self,
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
@@ -87,11 +87,11 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) public view returns (Tuple16[] memory) {
+ function collectionProperties(string[] memory keys) public view returns (Property[] memory) {
require(false, stub_error);
keys;
dummy;
- return new Tuple16[](0);
+ return new Property[](0);
}
// /// Set the sponsor of the collection.
@@ -425,20 +425,23 @@
uint256 sub;
}
-/// @dev anonymous struct
-struct Tuple16 {
- string field_0;
- bytes field_1;
-}
-
/// @dev Property struct
struct Property {
string key;
bytes value;
}
-/// @dev the ERC-165 identifier for this interface is 0x29f4dcd9
+/// @dev the ERC-165 identifier for this interface is 0x5b7038cf
contract ERC20UniqueExtensions is Dummy, ERC165 {
+ /// @notice A description for the collection.
+ /// @dev EVM selector for this function is: 0x7284e416,
+ /// or in textual repr: description()
+ function description() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
/// @dev EVM selector for this function is: 0x0ecd0ab0,
/// or in textual repr: approveCross((address,uint256),uint256)
function approveCross(EthCrossAccount memory spender, uint256 amount) public returns (bool) {
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.1.10] - 2022-11-18
+
+### Added
+
+- The functions `description`, `crossOwnerOf`, `tokenProperties` to `ERC721UniqueExtensions` interface.
+
## [0.1.9] - 2022-11-14
### Changed
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -37,7 +37,7 @@
use sp_std::vec::Vec;
use pallet_common::{
erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
- CollectionHandle, CollectionPropertyPermissions,
+ CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
@@ -278,7 +278,7 @@
#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]
impl<T: Config> NonfungibleHandle<T>
where
- T::AccountId: From<[u8; 32]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev real implementation of this function lies in `ERC721UniqueExtensions`
@@ -686,7 +686,7 @@
#[solidity_interface(name = ERC721UniqueExtensions)]
impl<T: Config> NonfungibleHandle<T>
where
- T::AccountId: From<[u8; 32]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
/// @notice A descriptive name for a collection of NFTs in this contract
fn name(&self) -> Result<string> {
@@ -700,6 +700,56 @@
Ok(string::from_utf8_lossy(&self.token_prefix).into())
}
+ /// @notice A description for the collection.
+ fn description(&self) -> Result<string> {
+ Ok(decode_utf16(self.description.iter().copied())
+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+ .collect::<string>())
+ }
+
+ /// Returns the owner (in cross format) of the token.
+ ///
+ /// @param tokenId Id for the token.
+ fn cross_owner_of(&self, token_id: uint256) -> Result<EthCrossAccount> {
+ Self::token_owner(&self, token_id.try_into()?)
+ .map(|o| EthCrossAccount::from_sub_cross_account::<T>(&o))
+ .ok_or(Error::Revert("key too large".into()))
+ }
+
+ /// Returns the token properties.
+ ///
+ /// @param tokenId Id for the token.
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @return Vector of properties key/value pairs.
+ fn token_properties(
+ &self,
+ token_id: uint256,
+ keys: Vec<string>,
+ ) -> Result<Vec<PropertyStruct>> {
+ let keys = keys
+ .into_iter()
+ .map(|key| {
+ <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| Error::Revert("key too large".into()))
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ <Self as CommonCollectionOperations<T>>::token_properties(
+ &self,
+ token_id.try_into()?,
+ if keys.is_empty() { None } else { Some(keys) },
+ )
+ .into_iter()
+ .map(|p| {
+ let key = string::from_utf8(p.key.to_vec())
+ .map_err(|e| Error::Revert(alloc::format!("{}", e)))?;
+ let value = bytes(p.value.to_vec());
+ Ok(PropertyStruct { key, value })
+ })
+ .collect::<Result<Vec<_>>>()
+ }
+
/// @notice Set or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
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
@@ -188,11 +188,11 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) public view returns (Tuple23[] memory) {
+ function collectionProperties(string[] memory keys) public view returns (Property[] memory) {
require(false, stub_error);
keys;
dummy;
- return new Tuple23[](0);
+ return new Property[](0);
}
// /// Set the sponsor of the collection.
@@ -253,10 +253,10 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() public view returns (Tuple26 memory) {
+ function collectionSponsor() public view returns (Tuple30 memory) {
require(false, stub_error);
dummy;
- return Tuple26(0x0000000000000000000000000000000000000000, 0);
+ return Tuple30(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -527,17 +527,11 @@
}
/// @dev anonymous struct
-struct Tuple26 {
+struct Tuple30 {
address field_0;
uint256 field_1;
}
-/// @dev anonymous struct
-struct Tuple23 {
- string field_0;
- bytes 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
@@ -682,7 +676,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x0e9fc611
+/// @dev the ERC-165 identifier for this interface is 0xb8f094a0
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,
@@ -702,6 +696,42 @@
return "";
}
+ /// @notice A description for the collection.
+ /// @dev EVM selector for this function is: 0x7284e416,
+ /// or in textual repr: description()
+ function description() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// Returns the owner (in cross format) of the token.
+ ///
+ /// @param tokenId Id for the token.
+ /// @dev EVM selector for this function is: 0x2b29dace,
+ /// or in textual repr: crossOwnerOf(uint256)
+ function crossOwnerOf(uint256 tokenId) public view returns (EthCrossAccount memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return EthCrossAccount(0x0000000000000000000000000000000000000000, 0);
+ }
+
+ /// Returns the token properties.
+ ///
+ /// @param tokenId Id for the token.
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @return Vector of properties key/value pairs.
+ /// @dev EVM selector for this function is: 0xefc26c69,
+ /// or in textual repr: tokenProperties(uint256,string[])
+ function tokenProperties(uint256 tokenId, string[] memory keys) public view returns (Property[] memory) {
+ require(false, stub_error);
+ tokenId;
+ keys;
+ dummy;
+ return new Property[](0);
+ }
+
/// @notice Set or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
@@ -825,7 +855,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, Tuple11[] memory tokens) public returns (bool) {
+ // function mintBulkWithTokenURI(address to, Tuple15[] memory tokens) public returns (bool) {
// require(false, stub_error);
// to;
// tokens;
@@ -836,7 +866,7 @@
}
/// @dev anonymous struct
-struct Tuple11 {
+struct Tuple15 {
uint256 field_0;
string field_1;
}
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.2.9] - 2022-11-18
+
+### Added
+
+- The functions `description`, `crossOwnerOf`, `tokenProperties` to `ERC721UniqueExtensions` interface.
+
## [0.2.8] - 2022-11-14
### Changed
pallets/refungible/src/erc.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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27};28use evm_coder::{29 abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,30 types::Property as PropertyStruct, weight,31};32use frame_support::{BoundedBTreeMap, BoundedVec};33use pallet_common::{34 CollectionHandle, CollectionPropertyPermissions,35 erc::{CommonEvmHandler, CollectionCall, static_property::key},36};37use pallet_evm::{account::CrossAccountId, PrecompileHandle};38use pallet_evm_coder_substrate::{call, dispatch_to_evm};39use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};40use sp_core::H160;41use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};42use up_data_structs::{43 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,44 PropertyKeyPermission, PropertyPermission, TokenId,45};4647use crate::{48 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,49 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,50};5152pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5354/// @title A contract that allows to set and delete token properties and change token property permissions.55#[solidity_interface(name = TokenProperties)]56impl<T: Config> RefungibleHandle<T> {57 /// @notice Set permissions for token property.58 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.59 /// @param key Property key.60 /// @param isMutable Permission to mutate property.61 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.62 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.63 fn set_token_property_permission(64 &mut self,65 caller: caller,66 key: string,67 is_mutable: bool,68 collection_admin: bool,69 token_owner: bool,70 ) -> Result<()> {71 let caller = T::CrossAccountId::from_eth(caller);72 <Pallet<T>>::set_token_property_permissions(73 self,74 &caller,75 vec![PropertyKeyPermission {76 key: <Vec<u8>>::from(key)77 .try_into()78 .map_err(|_| "too long key")?,79 permission: PropertyPermission {80 mutable: is_mutable,81 collection_admin,82 token_owner,83 },84 }],85 )86 .map_err(dispatch_to_evm::<T>)87 }8889 /// @notice Set token property value.90 /// @dev Throws error if `msg.sender` has no permission to edit the property.91 /// @param tokenId ID of the token.92 /// @param key Property key.93 /// @param value Property value.94 #[solidity(hide)]95 fn set_property(96 &mut self,97 caller: caller,98 token_id: uint256,99 key: string,100 value: bytes,101 ) -> Result<()> {102 let caller = T::CrossAccountId::from_eth(caller);103 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;104 let key = <Vec<u8>>::from(key)105 .try_into()106 .map_err(|_| "key too long")?;107 let value = value.0.try_into().map_err(|_| "value too long")?;108109 let nesting_budget = self110 .recorder111 .weight_calls_budget(<StructureWeight<T>>::find_parent());112113 <Pallet<T>>::set_token_property(114 self,115 &caller,116 TokenId(token_id),117 Property { key, value },118 &nesting_budget,119 )120 .map_err(dispatch_to_evm::<T>)121 }122123 /// @notice Set token properties value.124 /// @dev Throws error if `msg.sender` has no permission to edit the property.125 /// @param tokenId ID of the token.126 /// @param properties settable properties127 fn set_properties(128 &mut self,129 caller: caller,130 token_id: uint256,131 properties: Vec<PropertyStruct>,132 ) -> Result<()> {133 let caller = T::CrossAccountId::from_eth(caller);134 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;135136 let nesting_budget = self137 .recorder138 .weight_calls_budget(<StructureWeight<T>>::find_parent());139140 let properties = properties141 .into_iter()142 .map(|PropertyStruct { key, value }| {143 let key = <Vec<u8>>::from(key)144 .try_into()145 .map_err(|_| "key too large")?;146147 let value = value.0.try_into().map_err(|_| "value too large")?;148149 Ok(Property { key, value })150 })151 .collect::<Result<Vec<_>>>()?;152153 <Pallet<T>>::set_token_properties(154 self,155 &caller,156 TokenId(token_id),157 properties.into_iter(),158 <Pallet<T>>::token_exists(&self, TokenId(token_id)),159 &nesting_budget,160 )161 .map_err(dispatch_to_evm::<T>)162 }163164 /// @notice Delete token property value.165 /// @dev Throws error if `msg.sender` has no permission to edit the property.166 /// @param tokenId ID of the token.167 /// @param key Property key.168 #[solidity(hide)]169 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {170 let caller = T::CrossAccountId::from_eth(caller);171 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;172 let key = <Vec<u8>>::from(key)173 .try_into()174 .map_err(|_| "key too long")?;175176 let nesting_budget = self177 .recorder178 .weight_calls_budget(<StructureWeight<T>>::find_parent());179180 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)181 .map_err(dispatch_to_evm::<T>)182 }183184 /// @notice Delete token properties value.185 /// @dev Throws error if `msg.sender` has no permission to edit the property.186 /// @param tokenId ID of the token.187 /// @param keys Properties key.188 fn delete_properties(189 &mut self,190 token_id: uint256,191 caller: caller,192 keys: Vec<string>,193 ) -> Result<()> {194 let caller = T::CrossAccountId::from_eth(caller);195 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;196 let keys = keys197 .into_iter()198 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))199 .collect::<Result<Vec<_>>>()?;200201 let nesting_budget = self202 .recorder203 .weight_calls_budget(<StructureWeight<T>>::find_parent());204205 <Pallet<T>>::delete_token_properties(206 self,207 &caller,208 TokenId(token_id),209 keys.into_iter(),210 &nesting_budget,211 )212 .map_err(dispatch_to_evm::<T>)213 }214215 /// @notice Get token property value.216 /// @dev Throws error if key not found217 /// @param tokenId ID of the token.218 /// @param key Property key.219 /// @return Property value bytes220 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {221 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;222 let key = <Vec<u8>>::from(key)223 .try_into()224 .map_err(|_| "key too long")?;225226 let props = <TokenProperties<T>>::get((self.id, token_id));227 let prop = props.get(&key).ok_or("key not found")?;228229 Ok(prop.to_vec().into())230 }231}232233#[derive(ToLog)]234pub enum ERC721Events {235 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed236 /// (`to` == 0). Exception: during contract creation, any number of RFTs237 /// may be created and assigned without emitting Transfer.238 Transfer {239 #[indexed]240 from: address,241 #[indexed]242 to: address,243 #[indexed]244 token_id: uint256,245 },246 /// @dev Not supported247 Approval {248 #[indexed]249 owner: address,250 #[indexed]251 approved: address,252 #[indexed]253 token_id: uint256,254 },255 /// @dev Not supported256 #[allow(dead_code)]257 ApprovalForAll {258 #[indexed]259 owner: address,260 #[indexed]261 operator: address,262 approved: bool,263 },264}265266#[derive(ToLog)]267pub enum ERC721UniqueMintableEvents {268 /// @dev Not supported269 #[allow(dead_code)]270 MintingFinished {},271}272273#[solidity_interface(name = ERC721Metadata)]274impl<T: Config> RefungibleHandle<T>275where276 T::AccountId: From<[u8; 32]>,277{278 /// @notice A descriptive name for a collection of NFTs in this contract279 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`280 #[solidity(hide, rename_selector = "name")]281 fn name_proxy(&self) -> Result<string> {282 self.name()283 }284285 /// @notice An abbreviated name for NFTs in this contract286 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`287 #[solidity(hide, rename_selector = "symbol")]288 fn symbol_proxy(&self) -> Result<string> {289 self.symbol()290 }291292 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.293 ///294 /// @dev If the token has a `url` property and it is not empty, it is returned.295 /// 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`.296 /// If the collection property `baseURI` is empty or absent, return "" (empty string)297 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix298 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).299 ///300 /// @return token's const_metadata301 #[solidity(rename_selector = "tokenURI")]302 fn token_uri(&self, token_id: uint256) -> Result<string> {303 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;304305 match get_token_property(self, token_id_u32, &key::url()).as_deref() {306 Err(_) | Ok("") => (),307 Ok(url) => {308 return Ok(url.into());309 }310 };311312 let base_uri =313 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())314 .map(BoundedVec::into_inner)315 .map(string::from_utf8)316 .transpose()317 .map_err(|e| {318 Error::Revert(alloc::format!(319 "Can not convert value \"baseURI\" to string with error \"{}\"",320 e321 ))322 })?;323324 let base_uri = match base_uri.as_deref() {325 None | Some("") => {326 return Ok("".into());327 }328 Some(base_uri) => base_uri.into(),329 };330331 Ok(332 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {333 Err(_) | Ok("") => base_uri,334 Ok(suffix) => base_uri + suffix,335 },336 )337 }338}339340/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension341/// @dev See https://eips.ethereum.org/EIPS/eip-721342#[solidity_interface(name = ERC721Enumerable)]343impl<T: Config> RefungibleHandle<T> {344 /// @notice Enumerate valid RFTs345 /// @param index A counter less than `totalSupply()`346 /// @return The token identifier for the `index`th NFT,347 /// (sort order not specified)348 fn token_by_index(&self, index: uint256) -> Result<uint256> {349 Ok(index)350 }351352 /// Not implemented353 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {354 // TODO: Not implemetable355 Err("not implemented".into())356 }357358 /// @notice Count RFTs tracked by this contract359 /// @return A count of valid RFTs tracked by this contract, where each one of360 /// them has an assigned and queryable owner not equal to the zero address361 fn total_supply(&self) -> Result<uint256> {362 self.consume_store_reads(1)?;363 Ok(<Pallet<T>>::total_supply(self).into())364 }365}366367/// @title ERC-721 Non-Fungible Token Standard368/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md369#[solidity_interface(name = ERC721, events(ERC721Events))]370impl<T: Config> RefungibleHandle<T> {371 /// @notice Count all RFTs assigned to an owner372 /// @dev RFTs assigned to the zero address are considered invalid, and this373 /// function throws for queries about the zero address.374 /// @param owner An address for whom to query the balance375 /// @return The number of RFTs owned by `owner`, possibly zero376 fn balance_of(&self, owner: address) -> Result<uint256> {377 self.consume_store_reads(1)?;378 let owner = T::CrossAccountId::from_eth(owner);379 let balance = <AccountBalance<T>>::get((self.id, owner));380 Ok(balance.into())381 }382383 /// @notice Find the owner of an RFT384 /// @dev RFTs assigned to zero address are considered invalid, and queries385 /// about them do throw.386 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for387 /// the tokens that are partially owned.388 /// @param tokenId The identifier for an RFT389 /// @return The address of the owner of the RFT390 fn owner_of(&self, token_id: uint256) -> Result<address> {391 self.consume_store_reads(2)?;392 let token = token_id.try_into()?;393 let owner = <Pallet<T>>::token_owner(self.id, token);394 Ok(owner395 .map(|address| *address.as_eth())396 .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))397 }398399 /// @dev Not implemented400 fn safe_transfer_from_with_data(401 &mut self,402 _from: address,403 _to: address,404 _token_id: uint256,405 _data: bytes,406 ) -> Result<void> {407 // TODO: Not implemetable408 Err("not implemented".into())409 }410411 /// @dev Not implemented412 fn safe_transfer_from(413 &mut self,414 _from: address,415 _to: address,416 _token_id: uint256,417 ) -> Result<void> {418 // TODO: Not implemetable419 Err("not implemented".into())420 }421422 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE423 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE424 /// THEY MAY BE PERMANENTLY LOST425 /// @dev Throws unless `msg.sender` is the current owner or an authorized426 /// operator for this RFT. Throws if `from` is not the current owner. Throws427 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.428 /// Throws if RFT pieces have multiple owners.429 /// @param from The current owner of the NFT430 /// @param to The new owner431 /// @param tokenId The NFT to transfer432 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]433 fn transfer_from(434 &mut self,435 caller: caller,436 from: address,437 to: address,438 token_id: uint256,439 ) -> Result<void> {440 let caller = T::CrossAccountId::from_eth(caller);441 let from = T::CrossAccountId::from_eth(from);442 let to = T::CrossAccountId::from_eth(to);443 let token = token_id.try_into()?;444 let budget = self445 .recorder446 .weight_calls_budget(<StructureWeight<T>>::find_parent());447448 let balance = balance(&self, token, &from)?;449 ensure_single_owner(&self, token, balance)?;450451 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)452 .map_err(dispatch_to_evm::<T>)?;453454 Ok(())455 }456457 /// @dev Not implemented458 fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {459 Err("not implemented".into())460 }461462 /// @dev Not implemented463 fn set_approval_for_all(464 &mut self,465 _caller: caller,466 _operator: address,467 _approved: bool,468 ) -> Result<void> {469 // TODO: Not implemetable470 Err("not implemented".into())471 }472473 /// @dev Not implemented474 fn get_approved(&self, _token_id: uint256) -> Result<address> {475 // TODO: Not implemetable476 Err("not implemented".into())477 }478479 /// @dev Not implemented480 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {481 // TODO: Not implemetable482 Err("not implemented".into())483 }484}485486/// Returns amount of pieces of `token` that `owner` have487pub fn balance<T: Config>(488 collection: &RefungibleHandle<T>,489 token: TokenId,490 owner: &T::CrossAccountId,491) -> Result<u128> {492 collection.consume_store_reads(1)?;493 let balance = <Balance<T>>::get((collection.id, token, &owner));494 Ok(balance)495}496497/// Throws if `owner_balance` is lower than total amount of `token` pieces498pub fn ensure_single_owner<T: Config>(499 collection: &RefungibleHandle<T>,500 token: TokenId,501 owner_balance: u128,502) -> Result<()> {503 collection.consume_store_reads(1)?;504 let total_supply = <TotalSupply<T>>::get((collection.id, token));505 if total_supply != owner_balance {506 return Err("token has multiple owners".into());507 }508 Ok(())509}510511/// @title ERC721 Token that can be irreversibly burned (destroyed).512#[solidity_interface(name = ERC721Burnable)]513impl<T: Config> RefungibleHandle<T> {514 /// @notice Burns a specific ERC721 token.515 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized516 /// operator of the current owner.517 /// @param tokenId The RFT to approve518 #[weight(<SelfWeightOf<T>>::burn_item_fully())]519 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {520 let caller = T::CrossAccountId::from_eth(caller);521 let token = token_id.try_into()?;522523 let balance = balance(&self, token, &caller)?;524 ensure_single_owner(&self, token, balance)?;525526 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;527 Ok(())528 }529}530531/// @title ERC721 minting logic.532#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]533impl<T: Config> RefungibleHandle<T> {534 fn minting_finished(&self) -> Result<bool> {535 Ok(false)536 }537538 /// @notice Function to mint token.539 /// @param to The new owner540 /// @return uint256 The id of the newly minted token541 #[weight(<SelfWeightOf<T>>::create_item())]542 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {543 let token_id: uint256 = <TokensMinted<T>>::get(self.id)544 .checked_add(1)545 .ok_or("item id overflow")?546 .into();547 self.mint_check_id(caller, to, token_id)?;548 Ok(token_id)549 }550551 /// @notice Function to mint token.552 /// @dev `tokenId` should be obtained with `nextTokenId` method,553 /// unlike standard, you can't specify it manually554 /// @param to The new owner555 /// @param tokenId ID of the minted RFT556 #[solidity(hide, rename_selector = "mint")]557 #[weight(<SelfWeightOf<T>>::create_item())]558 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {559 let caller = T::CrossAccountId::from_eth(caller);560 let to = T::CrossAccountId::from_eth(to);561 let token_id: u32 = token_id.try_into()?;562 let budget = self563 .recorder564 .weight_calls_budget(<StructureWeight<T>>::find_parent());565566 if <TokensMinted<T>>::get(self.id)567 .checked_add(1)568 .ok_or("item id overflow")?569 != token_id570 {571 return Err("item id should be next".into());572 }573574 let users = [(to.clone(), 1)]575 .into_iter()576 .collect::<BTreeMap<_, _>>()577 .try_into()578 .unwrap();579 <Pallet<T>>::create_item(580 self,581 &caller,582 CreateItemData::<T::CrossAccountId> {583 users,584 properties: CollectionPropertiesVec::default(),585 },586 &budget,587 )588 .map_err(dispatch_to_evm::<T>)?;589590 Ok(true)591 }592593 /// @notice Function to mint token with the given tokenUri.594 /// @param to The new owner595 /// @param tokenUri Token URI that would be stored in the NFT properties596 /// @return uint256 The id of the newly minted token597 #[solidity(rename_selector = "mintWithTokenURI")]598 #[weight(<SelfWeightOf<T>>::create_item())]599 fn mint_with_token_uri(600 &mut self,601 caller: caller,602 to: address,603 token_uri: string,604 ) -> Result<uint256> {605 let token_id: uint256 = <TokensMinted<T>>::get(self.id)606 .checked_add(1)607 .ok_or("item id overflow")?608 .into();609 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;610 Ok(token_id)611 }612613 /// @notice Function to mint token with the given tokenUri.614 /// @dev `tokenId` should be obtained with `nextTokenId` method,615 /// unlike standard, you can't specify it manually616 /// @param to The new owner617 /// @param tokenId ID of the minted RFT618 /// @param tokenUri Token URI that would be stored in the RFT properties619 #[solidity(hide, rename_selector = "mintWithTokenURI")]620 #[weight(<SelfWeightOf<T>>::create_item())]621 fn mint_with_token_uri_check_id(622 &mut self,623 caller: caller,624 to: address,625 token_id: uint256,626 token_uri: string,627 ) -> Result<bool> {628 let key = key::url();629 let permission = get_token_permission::<T>(self.id, &key)?;630 if !permission.collection_admin {631 return Err("Operation is not allowed".into());632 }633634 let caller = T::CrossAccountId::from_eth(caller);635 let to = T::CrossAccountId::from_eth(to);636 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;637 let budget = self638 .recorder639 .weight_calls_budget(<StructureWeight<T>>::find_parent());640641 if <TokensMinted<T>>::get(self.id)642 .checked_add(1)643 .ok_or("item id overflow")?644 != token_id645 {646 return Err("item id should be next".into());647 }648649 let mut properties = CollectionPropertiesVec::default();650 properties651 .try_push(Property {652 key,653 value: token_uri654 .into_bytes()655 .try_into()656 .map_err(|_| "token uri is too long")?,657 })658 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;659660 let users = [(to.clone(), 1)]661 .into_iter()662 .collect::<BTreeMap<_, _>>()663 .try_into()664 .unwrap();665 <Pallet<T>>::create_item(666 self,667 &caller,668 CreateItemData::<T::CrossAccountId> { users, properties },669 &budget,670 )671 .map_err(dispatch_to_evm::<T>)?;672 Ok(true)673 }674675 /// @dev Not implemented676 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {677 Err("not implementable".into())678 }679}680681fn get_token_property<T: Config>(682 collection: &CollectionHandle<T>,683 token_id: u32,684 key: &up_data_structs::PropertyKey,685) -> Result<string> {686 collection.consume_store_reads(1)?;687 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))688 .map_err(|_| Error::Revert("Token properties not found".into()))?;689 if let Some(property) = properties.get(key) {690 return Ok(string::from_utf8_lossy(property).into());691 }692693 Err("Property tokenURI not found".into())694}695696fn get_token_permission<T: Config>(697 collection_id: CollectionId,698 key: &PropertyKey,699) -> Result<PropertyPermission> {700 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)701 .map_err(|_| Error::Revert("No permissions for collection".into()))?;702 let a = token_property_permissions703 .get(key)704 .map(Clone::clone)705 .ok_or_else(|| {706 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();707 Error::Revert(alloc::format!("No permission for key {}", key))708 })?;709 Ok(a)710}711712/// @title Unique extensions for ERC721.713#[solidity_interface(name = ERC721UniqueExtensions)]714impl<T: Config> RefungibleHandle<T>715where716 T::AccountId: From<[u8; 32]>,717{718 /// @notice A descriptive name for a collection of NFTs in this contract719 fn name(&self) -> Result<string> {720 Ok(decode_utf16(self.name.iter().copied())721 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))722 .collect::<string>())723 }724725 /// @notice An abbreviated name for NFTs in this contract726 fn symbol(&self) -> Result<string> {727 Ok(string::from_utf8_lossy(&self.token_prefix).into())728 }729730 /// @notice Transfer ownership of an RFT731 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`732 /// is the zero address. Throws if `tokenId` is not a valid RFT.733 /// Throws if RFT pieces have multiple owners.734 /// @param to The new owner735 /// @param tokenId The RFT to transfer736 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]737 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {738 let caller = T::CrossAccountId::from_eth(caller);739 let to = T::CrossAccountId::from_eth(to);740 let token = token_id.try_into()?;741 let budget = self742 .recorder743 .weight_calls_budget(<StructureWeight<T>>::find_parent());744745 let balance = balance(self, token, &caller)?;746 ensure_single_owner(self, token, balance)?;747748 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)749 .map_err(dispatch_to_evm::<T>)?;750 Ok(())751 }752753 /// @notice Transfer ownership of an RFT754 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`755 /// is the zero address. Throws if `tokenId` is not a valid RFT.756 /// Throws if RFT pieces have multiple owners.757 /// @param to The new owner758 /// @param tokenId The RFT to transfer759 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]760 fn transfer_cross(761 &mut self,762 caller: caller,763 to: EthCrossAccount,764 token_id: uint256,765 ) -> Result<void> {766 let caller = T::CrossAccountId::from_eth(caller);767 let to = to.into_sub_cross_account::<T>()?;768 let token = token_id.try_into()?;769 let budget = self770 .recorder771 .weight_calls_budget(<StructureWeight<T>>::find_parent());772773 let balance = balance(self, token, &caller)?;774 ensure_single_owner(self, token, balance)?;775776 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)777 .map_err(dispatch_to_evm::<T>)?;778 Ok(())779 }780781 /// @notice Transfer ownership of an RFT782 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`783 /// is the zero address. Throws if `tokenId` is not a valid RFT.784 /// Throws if RFT pieces have multiple owners.785 /// @param to The new owner786 /// @param tokenId The RFT to transfer787 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]788 fn transfer_from_cross(789 &mut self,790 caller: caller,791 from: EthCrossAccount,792 to: EthCrossAccount,793 token_id: uint256,794 ) -> Result<void> {795 let caller = T::CrossAccountId::from_eth(caller);796 let from = from.into_sub_cross_account::<T>()?;797 let to = to.into_sub_cross_account::<T>()?;798 let token_id = token_id.try_into()?;799 let budget = self800 .recorder801 .weight_calls_budget(<StructureWeight<T>>::find_parent());802803 let balance = balance(self, token_id, &from)?;804 ensure_single_owner(self, token_id, balance)?;805806 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)807 .map_err(dispatch_to_evm::<T>)?;808 Ok(())809 }810811 /// @notice Burns a specific ERC721 token.812 /// @dev Throws unless `msg.sender` is the current owner or an authorized813 /// operator for this RFT. Throws if `from` is not the current owner. Throws814 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.815 /// Throws if RFT pieces have multiple owners.816 /// @param from The current owner of the RFT817 /// @param tokenId The RFT to transfer818 #[solidity(hide)]819 #[weight(<SelfWeightOf<T>>::burn_from())]820 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {821 let caller = T::CrossAccountId::from_eth(caller);822 let from = T::CrossAccountId::from_eth(from);823 let token = token_id.try_into()?;824 let budget = self825 .recorder826 .weight_calls_budget(<StructureWeight<T>>::find_parent());827828 let balance = balance(self, token, &from)?;829 ensure_single_owner(self, token, balance)?;830831 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)832 .map_err(dispatch_to_evm::<T>)?;833 Ok(())834 }835836 /// @notice Burns a specific ERC721 token.837 /// @dev Throws unless `msg.sender` is the current owner or an authorized838 /// operator for this RFT. Throws if `from` is not the current owner. Throws839 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.840 /// Throws if RFT pieces have multiple owners.841 /// @param from The current owner of the RFT842 /// @param tokenId The RFT to transfer843 #[weight(<SelfWeightOf<T>>::burn_from())]844 fn burn_from_cross(845 &mut self,846 caller: caller,847 from: EthCrossAccount,848 token_id: uint256,849 ) -> Result<void> {850 let caller = T::CrossAccountId::from_eth(caller);851 let from = from.into_sub_cross_account::<T>()?;852 let token = token_id.try_into()?;853 let budget = self854 .recorder855 .weight_calls_budget(<StructureWeight<T>>::find_parent());856857 let balance = balance(self, token, &from)?;858 ensure_single_owner(self, token, balance)?;859860 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)861 .map_err(dispatch_to_evm::<T>)?;862 Ok(())863 }864865 /// @notice Returns next free RFT ID.866 fn next_token_id(&self) -> Result<uint256> {867 self.consume_store_reads(1)?;868 Ok(<TokensMinted<T>>::get(self.id)869 .checked_add(1)870 .ok_or("item id overflow")?871 .into())872 }873874 /// @notice Function to mint multiple tokens.875 /// @dev `tokenIds` should be an array of consecutive numbers and first number876 /// should be obtained with `nextTokenId` method877 /// @param to The new owner878 /// @param tokenIds IDs of the minted RFTs879 #[solidity(hide)]880 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]881 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {882 let caller = T::CrossAccountId::from_eth(caller);883 let to = T::CrossAccountId::from_eth(to);884 let mut expected_index = <TokensMinted<T>>::get(self.id)885 .checked_add(1)886 .ok_or("item id overflow")?;887 let budget = self888 .recorder889 .weight_calls_budget(<StructureWeight<T>>::find_parent());890891 let total_tokens = token_ids.len();892 for id in token_ids.into_iter() {893 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;894 if id != expected_index {895 return Err("item id should be next".into());896 }897 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;898 }899 let users = [(to.clone(), 1)]900 .into_iter()901 .collect::<BTreeMap<_, _>>()902 .try_into()903 .unwrap();904 let create_item_data = CreateItemData::<T::CrossAccountId> {905 users,906 properties: CollectionPropertiesVec::default(),907 };908 let data = (0..total_tokens)909 .map(|_| create_item_data.clone())910 .collect();911912 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)913 .map_err(dispatch_to_evm::<T>)?;914 Ok(true)915 }916917 /// @notice Function to mint multiple tokens with the given tokenUris.918 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive919 /// numbers and first number should be obtained with `nextTokenId` method920 /// @param to The new owner921 /// @param tokens array of pairs of token ID and token URI for minted tokens922 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]923 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]924 fn mint_bulk_with_token_uri(925 &mut self,926 caller: caller,927 to: address,928 tokens: Vec<(uint256, string)>,929 ) -> Result<bool> {930 let key = key::url();931 let caller = T::CrossAccountId::from_eth(caller);932 let to = T::CrossAccountId::from_eth(to);933 let mut expected_index = <TokensMinted<T>>::get(self.id)934 .checked_add(1)935 .ok_or("item id overflow")?;936 let budget = self937 .recorder938 .weight_calls_budget(<StructureWeight<T>>::find_parent());939940 let mut data = Vec::with_capacity(tokens.len());941 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]942 .into_iter()943 .collect::<BTreeMap<_, _>>()944 .try_into()945 .unwrap();946 for (id, token_uri) in tokens {947 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;948 if id != expected_index {949 return Err("item id should be next".into());950 }951 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;952953 let mut properties = CollectionPropertiesVec::default();954 properties955 .try_push(Property {956 key: key.clone(),957 value: token_uri958 .into_bytes()959 .try_into()960 .map_err(|_| "token uri is too long")?,961 })962 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;963964 let create_item_data = CreateItemData::<T::CrossAccountId> {965 users: users.clone(),966 properties,967 };968 data.push(create_item_data);969 }970971 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)972 .map_err(dispatch_to_evm::<T>)?;973 Ok(true)974 }975976 /// Returns EVM address for refungible token977 ///978 /// @param token ID of the token979 fn token_contract_address(&self, token: uint256) -> Result<address> {980 Ok(T::EvmTokenAddressMapping::token_to_address(981 self.id,982 token.try_into().map_err(|_| "token id overflow")?,983 ))984 }985}986987#[solidity_interface(988 name = UniqueRefungible,989 is(990 ERC721,991 ERC721Enumerable,992 ERC721UniqueExtensions,993 ERC721UniqueMintable,994 ERC721Burnable,995 ERC721Metadata(if(this.flags.erc721metadata)),996 Collection(via(common_mut returns CollectionHandle<T>)),997 TokenProperties,998 )999)]1000impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}10011002// Not a tests, but code generators1003generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1004generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);10051006impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1007where1008 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1009{1010 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1011 fn call(1012 self,1013 handle: &mut impl PrecompileHandle,1014 ) -> Option<pallet_common::erc::PrecompileResult> {1015 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1016 }1017}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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27};28use evm_coder::{29 abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,30 types::Property as PropertyStruct, weight,31};32use frame_support::{BoundedBTreeMap, BoundedVec};33use pallet_common::{34 CollectionHandle, CollectionPropertyPermissions,35 erc::{CommonEvmHandler, CollectionCall, static_property::key},36 CommonCollectionOperations,37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{call, dispatch_to_evm};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};41use sp_core::H160;42use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};43use up_data_structs::{44 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,45 PropertyKeyPermission, PropertyPermission, TokenId,46};4748use crate::{49 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,50 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,51};5253pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5455/// @title A contract that allows to set and delete token properties and change token property permissions.56#[solidity_interface(name = TokenProperties)]57impl<T: Config> RefungibleHandle<T> {58 /// @notice Set permissions for token property.59 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.60 /// @param key Property key.61 /// @param isMutable Permission to mutate property.62 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.63 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.64 fn set_token_property_permission(65 &mut self,66 caller: caller,67 key: string,68 is_mutable: bool,69 collection_admin: bool,70 token_owner: bool,71 ) -> Result<()> {72 let caller = T::CrossAccountId::from_eth(caller);73 <Pallet<T>>::set_token_property_permissions(74 self,75 &caller,76 vec![PropertyKeyPermission {77 key: <Vec<u8>>::from(key)78 .try_into()79 .map_err(|_| "too long key")?,80 permission: PropertyPermission {81 mutable: is_mutable,82 collection_admin,83 token_owner,84 },85 }],86 )87 .map_err(dispatch_to_evm::<T>)88 }8990 /// @notice Set token property value.91 /// @dev Throws error if `msg.sender` has no permission to edit the property.92 /// @param tokenId ID of the token.93 /// @param key Property key.94 /// @param value Property value.95 #[solidity(hide)]96 fn set_property(97 &mut self,98 caller: caller,99 token_id: uint256,100 key: string,101 value: bytes,102 ) -> Result<()> {103 let caller = T::CrossAccountId::from_eth(caller);104 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;105 let key = <Vec<u8>>::from(key)106 .try_into()107 .map_err(|_| "key too long")?;108 let value = value.0.try_into().map_err(|_| "value too long")?;109110 let nesting_budget = self111 .recorder112 .weight_calls_budget(<StructureWeight<T>>::find_parent());113114 <Pallet<T>>::set_token_property(115 self,116 &caller,117 TokenId(token_id),118 Property { key, value },119 &nesting_budget,120 )121 .map_err(dispatch_to_evm::<T>)122 }123124 /// @notice Set token properties value.125 /// @dev Throws error if `msg.sender` has no permission to edit the property.126 /// @param tokenId ID of the token.127 /// @param properties settable properties128 fn set_properties(129 &mut self,130 caller: caller,131 token_id: uint256,132 properties: Vec<PropertyStruct>,133 ) -> Result<()> {134 let caller = T::CrossAccountId::from_eth(caller);135 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;136137 let nesting_budget = self138 .recorder139 .weight_calls_budget(<StructureWeight<T>>::find_parent());140141 let properties = properties142 .into_iter()143 .map(|PropertyStruct { key, value }| {144 let key = <Vec<u8>>::from(key)145 .try_into()146 .map_err(|_| "key too large")?;147148 let value = value.0.try_into().map_err(|_| "value too large")?;149150 Ok(Property { key, value })151 })152 .collect::<Result<Vec<_>>>()?;153154 <Pallet<T>>::set_token_properties(155 self,156 &caller,157 TokenId(token_id),158 properties.into_iter(),159 <Pallet<T>>::token_exists(&self, TokenId(token_id)),160 &nesting_budget,161 )162 .map_err(dispatch_to_evm::<T>)163 }164165 /// @notice Delete token property value.166 /// @dev Throws error if `msg.sender` has no permission to edit the property.167 /// @param tokenId ID of the token.168 /// @param key Property key.169 #[solidity(hide)]170 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {171 let caller = T::CrossAccountId::from_eth(caller);172 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;173 let key = <Vec<u8>>::from(key)174 .try_into()175 .map_err(|_| "key too long")?;176177 let nesting_budget = self178 .recorder179 .weight_calls_budget(<StructureWeight<T>>::find_parent());180181 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)182 .map_err(dispatch_to_evm::<T>)183 }184185 /// @notice Delete token properties value.186 /// @dev Throws error if `msg.sender` has no permission to edit the property.187 /// @param tokenId ID of the token.188 /// @param keys Properties key.189 fn delete_properties(190 &mut self,191 token_id: uint256,192 caller: caller,193 keys: Vec<string>,194 ) -> Result<()> {195 let caller = T::CrossAccountId::from_eth(caller);196 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;197 let keys = keys198 .into_iter()199 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))200 .collect::<Result<Vec<_>>>()?;201202 let nesting_budget = self203 .recorder204 .weight_calls_budget(<StructureWeight<T>>::find_parent());205206 <Pallet<T>>::delete_token_properties(207 self,208 &caller,209 TokenId(token_id),210 keys.into_iter(),211 &nesting_budget,212 )213 .map_err(dispatch_to_evm::<T>)214 }215216 /// @notice Get token property value.217 /// @dev Throws error if key not found218 /// @param tokenId ID of the token.219 /// @param key Property key.220 /// @return Property value bytes221 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {222 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;223 let key = <Vec<u8>>::from(key)224 .try_into()225 .map_err(|_| "key too long")?;226227 let props = <TokenProperties<T>>::get((self.id, token_id));228 let prop = props.get(&key).ok_or("key not found")?;229230 Ok(prop.to_vec().into())231 }232}233234#[derive(ToLog)]235pub enum ERC721Events {236 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed237 /// (`to` == 0). Exception: during contract creation, any number of RFTs238 /// may be created and assigned without emitting Transfer.239 Transfer {240 #[indexed]241 from: address,242 #[indexed]243 to: address,244 #[indexed]245 token_id: uint256,246 },247 /// @dev Not supported248 Approval {249 #[indexed]250 owner: address,251 #[indexed]252 approved: address,253 #[indexed]254 token_id: uint256,255 },256 /// @dev Not supported257 #[allow(dead_code)]258 ApprovalForAll {259 #[indexed]260 owner: address,261 #[indexed]262 operator: address,263 approved: bool,264 },265}266267#[derive(ToLog)]268pub enum ERC721UniqueMintableEvents {269 /// @dev Not supported270 #[allow(dead_code)]271 MintingFinished {},272}273274#[solidity_interface(name = ERC721Metadata)]275impl<T: Config> RefungibleHandle<T>276where277 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,278{279 /// @notice A descriptive name for a collection of NFTs in this contract280 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`281 #[solidity(hide, rename_selector = "name")]282 fn name_proxy(&self) -> Result<string> {283 self.name()284 }285286 /// @notice An abbreviated name for NFTs in this contract287 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`288 #[solidity(hide, rename_selector = "symbol")]289 fn symbol_proxy(&self) -> Result<string> {290 self.symbol()291 }292293 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.294 ///295 /// @dev If the token has a `url` property and it is not empty, it is returned.296 /// 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`.297 /// If the collection property `baseURI` is empty or absent, return "" (empty string)298 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix299 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).300 ///301 /// @return token's const_metadata302 #[solidity(rename_selector = "tokenURI")]303 fn token_uri(&self, token_id: uint256) -> Result<string> {304 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;305306 match get_token_property(self, token_id_u32, &key::url()).as_deref() {307 Err(_) | Ok("") => (),308 Ok(url) => {309 return Ok(url.into());310 }311 };312313 let base_uri =314 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())315 .map(BoundedVec::into_inner)316 .map(string::from_utf8)317 .transpose()318 .map_err(|e| {319 Error::Revert(alloc::format!(320 "Can not convert value \"baseURI\" to string with error \"{}\"",321 e322 ))323 })?;324325 let base_uri = match base_uri.as_deref() {326 None | Some("") => {327 return Ok("".into());328 }329 Some(base_uri) => base_uri.into(),330 };331332 Ok(333 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {334 Err(_) | Ok("") => base_uri,335 Ok(suffix) => base_uri + suffix,336 },337 )338 }339}340341/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension342/// @dev See https://eips.ethereum.org/EIPS/eip-721343#[solidity_interface(name = ERC721Enumerable)]344impl<T: Config> RefungibleHandle<T> {345 /// @notice Enumerate valid RFTs346 /// @param index A counter less than `totalSupply()`347 /// @return The token identifier for the `index`th NFT,348 /// (sort order not specified)349 fn token_by_index(&self, index: uint256) -> Result<uint256> {350 Ok(index)351 }352353 /// Not implemented354 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {355 // TODO: Not implemetable356 Err("not implemented".into())357 }358359 /// @notice Count RFTs tracked by this contract360 /// @return A count of valid RFTs tracked by this contract, where each one of361 /// them has an assigned and queryable owner not equal to the zero address362 fn total_supply(&self) -> Result<uint256> {363 self.consume_store_reads(1)?;364 Ok(<Pallet<T>>::total_supply(self).into())365 }366}367368/// @title ERC-721 Non-Fungible Token Standard369/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md370#[solidity_interface(name = ERC721, events(ERC721Events))]371impl<T: Config> RefungibleHandle<T> {372 /// @notice Count all RFTs assigned to an owner373 /// @dev RFTs assigned to the zero address are considered invalid, and this374 /// function throws for queries about the zero address.375 /// @param owner An address for whom to query the balance376 /// @return The number of RFTs owned by `owner`, possibly zero377 fn balance_of(&self, owner: address) -> Result<uint256> {378 self.consume_store_reads(1)?;379 let owner = T::CrossAccountId::from_eth(owner);380 let balance = <AccountBalance<T>>::get((self.id, owner));381 Ok(balance.into())382 }383384 /// @notice Find the owner of an RFT385 /// @dev RFTs assigned to zero address are considered invalid, and queries386 /// about them do throw.387 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for388 /// the tokens that are partially owned.389 /// @param tokenId The identifier for an RFT390 /// @return The address of the owner of the RFT391 fn owner_of(&self, token_id: uint256) -> Result<address> {392 self.consume_store_reads(2)?;393 let token = token_id.try_into()?;394 let owner = <Pallet<T>>::token_owner(self.id, token);395 Ok(owner396 .map(|address| *address.as_eth())397 .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))398 }399400 /// @dev Not implemented401 fn safe_transfer_from_with_data(402 &mut self,403 _from: address,404 _to: address,405 _token_id: uint256,406 _data: bytes,407 ) -> Result<void> {408 // TODO: Not implemetable409 Err("not implemented".into())410 }411412 /// @dev Not implemented413 fn safe_transfer_from(414 &mut self,415 _from: address,416 _to: address,417 _token_id: uint256,418 ) -> Result<void> {419 // TODO: Not implemetable420 Err("not implemented".into())421 }422423 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE424 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE425 /// THEY MAY BE PERMANENTLY LOST426 /// @dev Throws unless `msg.sender` is the current owner or an authorized427 /// operator for this RFT. Throws if `from` is not the current owner. Throws428 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.429 /// Throws if RFT pieces have multiple owners.430 /// @param from The current owner of the NFT431 /// @param to The new owner432 /// @param tokenId The NFT to transfer433 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]434 fn transfer_from(435 &mut self,436 caller: caller,437 from: address,438 to: address,439 token_id: uint256,440 ) -> Result<void> {441 let caller = T::CrossAccountId::from_eth(caller);442 let from = T::CrossAccountId::from_eth(from);443 let to = T::CrossAccountId::from_eth(to);444 let token = token_id.try_into()?;445 let budget = self446 .recorder447 .weight_calls_budget(<StructureWeight<T>>::find_parent());448449 let balance = balance(&self, token, &from)?;450 ensure_single_owner(&self, token, balance)?;451452 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)453 .map_err(dispatch_to_evm::<T>)?;454455 Ok(())456 }457458 /// @dev Not implemented459 fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {460 Err("not implemented".into())461 }462463 /// @dev Not implemented464 fn set_approval_for_all(465 &mut self,466 _caller: caller,467 _operator: address,468 _approved: bool,469 ) -> Result<void> {470 // TODO: Not implemetable471 Err("not implemented".into())472 }473474 /// @dev Not implemented475 fn get_approved(&self, _token_id: uint256) -> Result<address> {476 // TODO: Not implemetable477 Err("not implemented".into())478 }479480 /// @dev Not implemented481 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {482 // TODO: Not implemetable483 Err("not implemented".into())484 }485}486487/// Returns amount of pieces of `token` that `owner` have488pub fn balance<T: Config>(489 collection: &RefungibleHandle<T>,490 token: TokenId,491 owner: &T::CrossAccountId,492) -> Result<u128> {493 collection.consume_store_reads(1)?;494 let balance = <Balance<T>>::get((collection.id, token, &owner));495 Ok(balance)496}497498/// Throws if `owner_balance` is lower than total amount of `token` pieces499pub fn ensure_single_owner<T: Config>(500 collection: &RefungibleHandle<T>,501 token: TokenId,502 owner_balance: u128,503) -> Result<()> {504 collection.consume_store_reads(1)?;505 let total_supply = <TotalSupply<T>>::get((collection.id, token));506 if total_supply != owner_balance {507 return Err("token has multiple owners".into());508 }509 Ok(())510}511512/// @title ERC721 Token that can be irreversibly burned (destroyed).513#[solidity_interface(name = ERC721Burnable)]514impl<T: Config> RefungibleHandle<T> {515 /// @notice Burns a specific ERC721 token.516 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized517 /// operator of the current owner.518 /// @param tokenId The RFT to approve519 #[weight(<SelfWeightOf<T>>::burn_item_fully())]520 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {521 let caller = T::CrossAccountId::from_eth(caller);522 let token = token_id.try_into()?;523524 let balance = balance(&self, token, &caller)?;525 ensure_single_owner(&self, token, balance)?;526527 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;528 Ok(())529 }530}531532/// @title ERC721 minting logic.533#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]534impl<T: Config> RefungibleHandle<T> {535 fn minting_finished(&self) -> Result<bool> {536 Ok(false)537 }538539 /// @notice Function to mint token.540 /// @param to The new owner541 /// @return uint256 The id of the newly minted token542 #[weight(<SelfWeightOf<T>>::create_item())]543 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {544 let token_id: uint256 = <TokensMinted<T>>::get(self.id)545 .checked_add(1)546 .ok_or("item id overflow")?547 .into();548 self.mint_check_id(caller, to, token_id)?;549 Ok(token_id)550 }551552 /// @notice Function to mint token.553 /// @dev `tokenId` should be obtained with `nextTokenId` method,554 /// unlike standard, you can't specify it manually555 /// @param to The new owner556 /// @param tokenId ID of the minted RFT557 #[solidity(hide, rename_selector = "mint")]558 #[weight(<SelfWeightOf<T>>::create_item())]559 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {560 let caller = T::CrossAccountId::from_eth(caller);561 let to = T::CrossAccountId::from_eth(to);562 let token_id: u32 = token_id.try_into()?;563 let budget = self564 .recorder565 .weight_calls_budget(<StructureWeight<T>>::find_parent());566567 if <TokensMinted<T>>::get(self.id)568 .checked_add(1)569 .ok_or("item id overflow")?570 != token_id571 {572 return Err("item id should be next".into());573 }574575 let users = [(to.clone(), 1)]576 .into_iter()577 .collect::<BTreeMap<_, _>>()578 .try_into()579 .unwrap();580 <Pallet<T>>::create_item(581 self,582 &caller,583 CreateItemData::<T::CrossAccountId> {584 users,585 properties: CollectionPropertiesVec::default(),586 },587 &budget,588 )589 .map_err(dispatch_to_evm::<T>)?;590591 Ok(true)592 }593594 /// @notice Function to mint token with the given tokenUri.595 /// @param to The new owner596 /// @param tokenUri Token URI that would be stored in the NFT properties597 /// @return uint256 The id of the newly minted token598 #[solidity(rename_selector = "mintWithTokenURI")]599 #[weight(<SelfWeightOf<T>>::create_item())]600 fn mint_with_token_uri(601 &mut self,602 caller: caller,603 to: address,604 token_uri: string,605 ) -> Result<uint256> {606 let token_id: uint256 = <TokensMinted<T>>::get(self.id)607 .checked_add(1)608 .ok_or("item id overflow")?609 .into();610 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;611 Ok(token_id)612 }613614 /// @notice Function to mint token with the given tokenUri.615 /// @dev `tokenId` should be obtained with `nextTokenId` method,616 /// unlike standard, you can't specify it manually617 /// @param to The new owner618 /// @param tokenId ID of the minted RFT619 /// @param tokenUri Token URI that would be stored in the RFT properties620 #[solidity(hide, rename_selector = "mintWithTokenURI")]621 #[weight(<SelfWeightOf<T>>::create_item())]622 fn mint_with_token_uri_check_id(623 &mut self,624 caller: caller,625 to: address,626 token_id: uint256,627 token_uri: string,628 ) -> Result<bool> {629 let key = key::url();630 let permission = get_token_permission::<T>(self.id, &key)?;631 if !permission.collection_admin {632 return Err("Operation is not allowed".into());633 }634635 let caller = T::CrossAccountId::from_eth(caller);636 let to = T::CrossAccountId::from_eth(to);637 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;638 let budget = self639 .recorder640 .weight_calls_budget(<StructureWeight<T>>::find_parent());641642 if <TokensMinted<T>>::get(self.id)643 .checked_add(1)644 .ok_or("item id overflow")?645 != token_id646 {647 return Err("item id should be next".into());648 }649650 let mut properties = CollectionPropertiesVec::default();651 properties652 .try_push(Property {653 key,654 value: token_uri655 .into_bytes()656 .try_into()657 .map_err(|_| "token uri is too long")?,658 })659 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;660661 let users = [(to.clone(), 1)]662 .into_iter()663 .collect::<BTreeMap<_, _>>()664 .try_into()665 .unwrap();666 <Pallet<T>>::create_item(667 self,668 &caller,669 CreateItemData::<T::CrossAccountId> { users, properties },670 &budget,671 )672 .map_err(dispatch_to_evm::<T>)?;673 Ok(true)674 }675676 /// @dev Not implemented677 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {678 Err("not implementable".into())679 }680}681682fn get_token_property<T: Config>(683 collection: &CollectionHandle<T>,684 token_id: u32,685 key: &up_data_structs::PropertyKey,686) -> Result<string> {687 collection.consume_store_reads(1)?;688 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))689 .map_err(|_| Error::Revert("Token properties not found".into()))?;690 if let Some(property) = properties.get(key) {691 return Ok(string::from_utf8_lossy(property).into());692 }693694 Err("Property tokenURI not found".into())695}696697fn get_token_permission<T: Config>(698 collection_id: CollectionId,699 key: &PropertyKey,700) -> Result<PropertyPermission> {701 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)702 .map_err(|_| Error::Revert("No permissions for collection".into()))?;703 let a = token_property_permissions704 .get(key)705 .map(Clone::clone)706 .ok_or_else(|| {707 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();708 Error::Revert(alloc::format!("No permission for key {}", key))709 })?;710 Ok(a)711}712713/// @title Unique extensions for ERC721.714#[solidity_interface(name = ERC721UniqueExtensions)]715impl<T: Config> RefungibleHandle<T>716where717 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,718{719 /// @notice A descriptive name for a collection of NFTs in this contract720 fn name(&self) -> Result<string> {721 Ok(decode_utf16(self.name.iter().copied())722 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))723 .collect::<string>())724 }725726 /// @notice An abbreviated name for NFTs in this contract727 fn symbol(&self) -> Result<string> {728 Ok(string::from_utf8_lossy(&self.token_prefix).into())729 }730731 /// @notice A description for the collection.732 fn description(&self) -> Result<string> {733 Ok(decode_utf16(self.description.iter().copied())734 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))735 .collect::<string>())736 }737738 /// Returns the owner (in cross format) of the token.739 ///740 /// @param tokenId Id for the token.741 fn cross_owner_of(&self, token_id: uint256) -> Result<EthCrossAccount> {742 Self::token_owner(&self, token_id.try_into()?)743 .map(|o| EthCrossAccount::from_sub_cross_account::<T>(&o))744 .ok_or(Error::Revert("key too large".into()))745 }746747 /// Returns the token properties.748 ///749 /// @param tokenId Id for the token.750 /// @param keys Properties keys. Empty keys for all propertyes.751 /// @return Vector of properties key/value pairs.752 fn token_properties(753 &self,754 token_id: uint256,755 keys: Vec<string>,756 ) -> Result<Vec<PropertyStruct>> {757 let keys = keys758 .into_iter()759 .map(|key| {760 <Vec<u8>>::from(key)761 .try_into()762 .map_err(|_| Error::Revert("key too large".into()))763 })764 .collect::<Result<Vec<_>>>()?;765766 <Self as CommonCollectionOperations<T>>::token_properties(767 &self,768 token_id.try_into()?,769 if keys.is_empty() { None } else { Some(keys) },770 )771 .into_iter()772 .map(|p| {773 let key = string::from_utf8(p.key.to_vec())774 .map_err(|e| Error::Revert(alloc::format!("{}", e)))?;775 let value = bytes(p.value.to_vec());776 Ok(PropertyStruct { key, value })777 })778 .collect::<Result<Vec<_>>>()779 }780 /// @notice Transfer ownership of an RFT781 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`782 /// is the zero address. Throws if `tokenId` is not a valid RFT.783 /// Throws if RFT pieces have multiple owners.784 /// @param to The new owner785 /// @param tokenId The RFT to transfer786 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]787 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {788 let caller = T::CrossAccountId::from_eth(caller);789 let to = T::CrossAccountId::from_eth(to);790 let token = token_id.try_into()?;791 let budget = self792 .recorder793 .weight_calls_budget(<StructureWeight<T>>::find_parent());794795 let balance = balance(self, token, &caller)?;796 ensure_single_owner(self, token, balance)?;797798 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)799 .map_err(dispatch_to_evm::<T>)?;800 Ok(())801 }802803 /// @notice Transfer ownership of an RFT804 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`805 /// is the zero address. Throws if `tokenId` is not a valid RFT.806 /// Throws if RFT pieces have multiple owners.807 /// @param to The new owner808 /// @param tokenId The RFT to transfer809 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]810 fn transfer_cross(811 &mut self,812 caller: caller,813 to: EthCrossAccount,814 token_id: uint256,815 ) -> Result<void> {816 let caller = T::CrossAccountId::from_eth(caller);817 let to = to.into_sub_cross_account::<T>()?;818 let token = token_id.try_into()?;819 let budget = self820 .recorder821 .weight_calls_budget(<StructureWeight<T>>::find_parent());822823 let balance = balance(self, token, &caller)?;824 ensure_single_owner(self, token, balance)?;825826 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)827 .map_err(dispatch_to_evm::<T>)?;828 Ok(())829 }830831 /// @notice Transfer ownership of an RFT832 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`833 /// is the zero address. Throws if `tokenId` is not a valid RFT.834 /// Throws if RFT pieces have multiple owners.835 /// @param to The new owner836 /// @param tokenId The RFT to transfer837 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]838 fn transfer_from_cross(839 &mut self,840 caller: caller,841 from: EthCrossAccount,842 to: EthCrossAccount,843 token_id: uint256,844 ) -> Result<void> {845 let caller = T::CrossAccountId::from_eth(caller);846 let from = from.into_sub_cross_account::<T>()?;847 let to = to.into_sub_cross_account::<T>()?;848 let token_id = token_id.try_into()?;849 let budget = self850 .recorder851 .weight_calls_budget(<StructureWeight<T>>::find_parent());852853 let balance = balance(self, token_id, &from)?;854 ensure_single_owner(self, token_id, balance)?;855856 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)857 .map_err(dispatch_to_evm::<T>)?;858 Ok(())859 }860861 /// @notice Burns a specific ERC721 token.862 /// @dev Throws unless `msg.sender` is the current owner or an authorized863 /// operator for this RFT. Throws if `from` is not the current owner. Throws864 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.865 /// Throws if RFT pieces have multiple owners.866 /// @param from The current owner of the RFT867 /// @param tokenId The RFT to transfer868 #[solidity(hide)]869 #[weight(<SelfWeightOf<T>>::burn_from())]870 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {871 let caller = T::CrossAccountId::from_eth(caller);872 let from = T::CrossAccountId::from_eth(from);873 let token = token_id.try_into()?;874 let budget = self875 .recorder876 .weight_calls_budget(<StructureWeight<T>>::find_parent());877878 let balance = balance(self, token, &from)?;879 ensure_single_owner(self, token, balance)?;880881 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)882 .map_err(dispatch_to_evm::<T>)?;883 Ok(())884 }885886 /// @notice Burns a specific ERC721 token.887 /// @dev Throws unless `msg.sender` is the current owner or an authorized888 /// operator for this RFT. Throws if `from` is not the current owner. Throws889 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.890 /// Throws if RFT pieces have multiple owners.891 /// @param from The current owner of the RFT892 /// @param tokenId The RFT to transfer893 #[weight(<SelfWeightOf<T>>::burn_from())]894 fn burn_from_cross(895 &mut self,896 caller: caller,897 from: EthCrossAccount,898 token_id: uint256,899 ) -> Result<void> {900 let caller = T::CrossAccountId::from_eth(caller);901 let from = from.into_sub_cross_account::<T>()?;902 let token = token_id.try_into()?;903 let budget = self904 .recorder905 .weight_calls_budget(<StructureWeight<T>>::find_parent());906907 let balance = balance(self, token, &from)?;908 ensure_single_owner(self, token, balance)?;909910 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)911 .map_err(dispatch_to_evm::<T>)?;912 Ok(())913 }914915 /// @notice Returns next free RFT ID.916 fn next_token_id(&self) -> Result<uint256> {917 self.consume_store_reads(1)?;918 Ok(<TokensMinted<T>>::get(self.id)919 .checked_add(1)920 .ok_or("item id overflow")?921 .into())922 }923924 /// @notice Function to mint multiple tokens.925 /// @dev `tokenIds` should be an array of consecutive numbers and first number926 /// should be obtained with `nextTokenId` method927 /// @param to The new owner928 /// @param tokenIds IDs of the minted RFTs929 #[solidity(hide)]930 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]931 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {932 let caller = T::CrossAccountId::from_eth(caller);933 let to = T::CrossAccountId::from_eth(to);934 let mut expected_index = <TokensMinted<T>>::get(self.id)935 .checked_add(1)936 .ok_or("item id overflow")?;937 let budget = self938 .recorder939 .weight_calls_budget(<StructureWeight<T>>::find_parent());940941 let total_tokens = token_ids.len();942 for id in token_ids.into_iter() {943 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;944 if id != expected_index {945 return Err("item id should be next".into());946 }947 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;948 }949 let users = [(to.clone(), 1)]950 .into_iter()951 .collect::<BTreeMap<_, _>>()952 .try_into()953 .unwrap();954 let create_item_data = CreateItemData::<T::CrossAccountId> {955 users,956 properties: CollectionPropertiesVec::default(),957 };958 let data = (0..total_tokens)959 .map(|_| create_item_data.clone())960 .collect();961962 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)963 .map_err(dispatch_to_evm::<T>)?;964 Ok(true)965 }966967 /// @notice Function to mint multiple tokens with the given tokenUris.968 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive969 /// numbers and first number should be obtained with `nextTokenId` method970 /// @param to The new owner971 /// @param tokens array of pairs of token ID and token URI for minted tokens972 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]973 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]974 fn mint_bulk_with_token_uri(975 &mut self,976 caller: caller,977 to: address,978 tokens: Vec<(uint256, string)>,979 ) -> Result<bool> {980 let key = key::url();981 let caller = T::CrossAccountId::from_eth(caller);982 let to = T::CrossAccountId::from_eth(to);983 let mut expected_index = <TokensMinted<T>>::get(self.id)984 .checked_add(1)985 .ok_or("item id overflow")?;986 let budget = self987 .recorder988 .weight_calls_budget(<StructureWeight<T>>::find_parent());989990 let mut data = Vec::with_capacity(tokens.len());991 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]992 .into_iter()993 .collect::<BTreeMap<_, _>>()994 .try_into()995 .unwrap();996 for (id, token_uri) in tokens {997 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;998 if id != expected_index {999 return Err("item id should be next".into());1000 }1001 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10021003 let mut properties = CollectionPropertiesVec::default();1004 properties1005 .try_push(Property {1006 key: key.clone(),1007 value: token_uri1008 .into_bytes()1009 .try_into()1010 .map_err(|_| "token uri is too long")?,1011 })1012 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;10131014 let create_item_data = CreateItemData::<T::CrossAccountId> {1015 users: users.clone(),1016 properties,1017 };1018 data.push(create_item_data);1019 }10201021 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1022 .map_err(dispatch_to_evm::<T>)?;1023 Ok(true)1024 }10251026 /// Returns EVM address for refungible token1027 ///1028 /// @param token ID of the token1029 fn token_contract_address(&self, token: uint256) -> Result<address> {1030 Ok(T::EvmTokenAddressMapping::token_to_address(1031 self.id,1032 token.try_into().map_err(|_| "token id overflow")?,1033 ))1034 }1035}10361037#[solidity_interface(1038 name = UniqueRefungible,1039 is(1040 ERC721,1041 ERC721Enumerable,1042 ERC721UniqueExtensions,1043 ERC721UniqueMintable,1044 ERC721Burnable,1045 ERC721Metadata(if(this.flags.erc721metadata)),1046 Collection(via(common_mut returns CollectionHandle<T>)),1047 TokenProperties,1048 )1049)]1050impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}10511052// Not a tests, but code generators1053generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1054generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);10551056impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1057where1058 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1059{1060 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1061 fn call(1062 self,1063 handle: &mut impl PrecompileHandle,1064 ) -> Option<pallet_common::erc::PrecompileResult> {1065 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1066 }1067}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
@@ -188,11 +188,11 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) public view returns (Tuple22[] memory) {
+ function collectionProperties(string[] memory keys) public view returns (Property[] memory) {
require(false, stub_error);
keys;
dummy;
- return new Tuple22[](0);
+ return new Property[](0);
}
// /// Set the sponsor of the collection.
@@ -253,10 +253,10 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() public view returns (Tuple25 memory) {
+ function collectionSponsor() public view returns (Tuple29 memory) {
require(false, stub_error);
dummy;
- return Tuple25(0x0000000000000000000000000000000000000000, 0);
+ return Tuple29(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -527,17 +527,11 @@
}
/// @dev anonymous struct
-struct Tuple25 {
+struct Tuple29 {
address field_0;
uint256 field_1;
}
-/// @dev anonymous struct
-struct Tuple22 {
- string field_0;
- bytes 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
@@ -680,7 +674,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xab243667
+/// @dev the ERC-165 identifier for this interface is 0x1d4b64d6
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,
@@ -700,6 +694,42 @@
return "";
}
+ /// @notice A description for the collection.
+ /// @dev EVM selector for this function is: 0x7284e416,
+ /// or in textual repr: description()
+ function description() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// Returns the owner (in cross format) of the token.
+ ///
+ /// @param tokenId Id for the token.
+ /// @dev EVM selector for this function is: 0x2b29dace,
+ /// or in textual repr: crossOwnerOf(uint256)
+ function crossOwnerOf(uint256 tokenId) public view returns (EthCrossAccount memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return EthCrossAccount(0x0000000000000000000000000000000000000000, 0);
+ }
+
+ /// Returns the token properties.
+ ///
+ /// @param tokenId Id for the token.
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @return Vector of properties key/value pairs.
+ /// @dev EVM selector for this function is: 0xefc26c69,
+ /// or in textual repr: tokenProperties(uint256,string[])
+ function tokenProperties(uint256 tokenId, string[] memory keys) public view returns (Property[] memory) {
+ require(false, stub_error);
+ tokenId;
+ keys;
+ dummy;
+ return new Property[](0);
+ }
+
/// @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.
@@ -813,7 +843,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, Tuple10[] memory tokens) public returns (bool) {
+ // function mintBulkWithTokenURI(address to, Tuple14[] memory tokens) public returns (bool) {
// require(false, stub_error);
// to;
// tokens;
@@ -835,7 +865,7 @@
}
/// @dev anonymous struct
-struct Tuple10 {
+struct Tuple14 {
uint256 field_0;
string field_1;
}
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
tests/src/eth/abi/fungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/fungible.json
+++ b/tests/src/eth/abi/fungible.json
@@ -216,10 +216,10 @@
"outputs": [
{
"components": [
- { "internalType": "string", "name": "field_0", "type": "string" },
- { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
],
- "internalType": "struct Tuple16[]",
+ "internalType": "struct Property[]",
"name": "",
"type": "tuple[]"
}
@@ -283,6 +283,13 @@
},
{
"inputs": [],
+ "name": "description",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "hasCollectionPendingSponsor",
"outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "view",
tests/src/eth/abi/nonFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -246,10 +246,10 @@
"outputs": [
{
"components": [
- { "internalType": "string", "name": "field_0", "type": "string" },
- { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
],
- "internalType": "struct Tuple23[]",
+ "internalType": "struct Property[]",
"name": "",
"type": "tuple[]"
}
@@ -273,7 +273,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple26",
+ "internalType": "struct Tuple30",
"name": "",
"type": "tuple"
}
@@ -297,6 +297,25 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "crossOwnerOf",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "string[]", "name": "keys", "type": "string[]" }
],
"name": "deleteCollectionProperties",
@@ -316,6 +335,13 @@
},
{
"inputs": [],
+ "name": "description",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "finishMinting",
"outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "nonpayable",
@@ -641,6 +667,26 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string[]", "name": "keys", "type": "string[]" }
+ ],
+ "name": "tokenProperties",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+ ],
+ "internalType": "struct Property[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
"name": "tokenURI",
tests/src/eth/abi/reFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -228,10 +228,10 @@
"outputs": [
{
"components": [
- { "internalType": "string", "name": "field_0", "type": "string" },
- { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
],
- "internalType": "struct Tuple22[]",
+ "internalType": "struct Property[]",
"name": "",
"type": "tuple[]"
}
@@ -255,7 +255,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple25",
+ "internalType": "struct Tuple29",
"name": "",
"type": "tuple"
}
@@ -279,6 +279,25 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "crossOwnerOf",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "string[]", "name": "keys", "type": "string[]" }
],
"name": "deleteCollectionProperties",
@@ -298,6 +317,13 @@
},
{
"inputs": [],
+ "name": "description",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "finishMinting",
"outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "nonpayable",
@@ -632,6 +658,26 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string[]", "name": "keys", "type": "string[]" }
+ ],
+ "name": "tokenProperties",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+ ],
+ "internalType": "struct Property[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
"name": "tokenURI",
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -60,7 +60,7 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) external view returns (Tuple16[] memory);
+ function collectionProperties(string[] memory keys) external view returns (Property[] memory);
// /// Set the sponsor of the collection.
// ///
@@ -276,12 +276,6 @@
struct EthCrossAccount {
address eth;
uint256 sub;
-}
-
-/// @dev anonymous struct
-struct Tuple16 {
- string field_0;
- bytes field_1;
}
/// @dev Property struct
@@ -290,8 +284,13 @@
bytes value;
}
-/// @dev the ERC-165 identifier for this interface is 0x29f4dcd9
+/// @dev the ERC-165 identifier for this interface is 0x5b7038cf
interface ERC20UniqueExtensions is Dummy, ERC165 {
+ /// @notice A description for the collection.
+ /// @dev EVM selector for this function is: 0x7284e416,
+ /// or in textual repr: description()
+ function description() external view returns (string memory);
+
/// @dev EVM selector for this function is: 0x0ecd0ab0,
/// or in textual repr: approveCross((address,uint256),uint256)
function approveCross(EthCrossAccount memory spender, uint256 amount) external returns (bool);
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -127,7 +127,7 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) external view returns (Tuple23[] memory);
+ function collectionProperties(string[] memory keys) external view returns (Property[] memory);
// /// Set the sponsor of the collection.
// ///
@@ -169,7 +169,7 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() external view returns (Tuple26 memory);
+ function collectionSponsor() external view returns (Tuple27 memory);
/// Set limits for the collection.
/// @dev Throws error if limit not found.
@@ -346,15 +346,9 @@
}
/// @dev anonymous struct
-struct Tuple26 {
+struct Tuple27 {
address field_0;
uint256 field_1;
-}
-
-/// @dev anonymous struct
-struct Tuple23 {
- string field_0;
- bytes field_1;
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
@@ -452,7 +446,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x0e9fc611
+/// @dev the ERC-165 identifier for this interface is 0xb8f094a0
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,
@@ -464,6 +458,27 @@
/// or in textual repr: symbol()
function symbol() external view returns (string memory);
+ /// @notice A description for the collection.
+ /// @dev EVM selector for this function is: 0x7284e416,
+ /// or in textual repr: description()
+ function description() external view returns (string memory);
+
+ /// Returns the owner (in cross format) of the token.
+ ///
+ /// @param tokenId Id for the token.
+ /// @dev EVM selector for this function is: 0x2b29dace,
+ /// or in textual repr: crossOwnerOf(uint256)
+ function crossOwnerOf(uint256 tokenId) external view returns (EthCrossAccount memory);
+
+ /// Returns the token properties.
+ ///
+ /// @param tokenId Id for the token.
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @return Vector of properties key/value pairs.
+ /// @dev EVM selector for this function is: 0xefc26c69,
+ /// or in textual repr: tokenProperties(uint256,string[])
+ function tokenProperties(uint256 tokenId, string[] memory keys) external view returns (Property[] memory);
+
/// @notice Set or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
@@ -546,12 +561,12 @@
// /// @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, Tuple11[] memory tokens) external returns (bool);
+ // function mintBulkWithTokenURI(address to, Tuple13[] memory tokens) external returns (bool);
}
/// @dev anonymous struct
-struct Tuple11 {
+struct Tuple13 {
uint256 field_0;
string field_1;
}
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -127,7 +127,7 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) external view returns (Tuple22[] memory);
+ function collectionProperties(string[] memory keys) external view returns (Property[] memory);
// /// Set the sponsor of the collection.
// ///
@@ -169,7 +169,7 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() external view returns (Tuple25 memory);
+ function collectionSponsor() external view returns (Tuple26 memory);
/// Set limits for the collection.
/// @dev Throws error if limit not found.
@@ -346,15 +346,9 @@
}
/// @dev anonymous struct
-struct Tuple25 {
+struct Tuple26 {
address field_0;
uint256 field_1;
-}
-
-/// @dev anonymous struct
-struct Tuple22 {
- string field_0;
- bytes field_1;
}
/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
@@ -450,7 +444,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xab243667
+/// @dev the ERC-165 identifier for this interface is 0x1d4b64d6
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,
@@ -462,6 +456,27 @@
/// or in textual repr: symbol()
function symbol() external view returns (string memory);
+ /// @notice A description for the collection.
+ /// @dev EVM selector for this function is: 0x7284e416,
+ /// or in textual repr: description()
+ function description() external view returns (string memory);
+
+ /// Returns the owner (in cross format) of the token.
+ ///
+ /// @param tokenId Id for the token.
+ /// @dev EVM selector for this function is: 0x2b29dace,
+ /// or in textual repr: crossOwnerOf(uint256)
+ function crossOwnerOf(uint256 tokenId) external view returns (EthCrossAccount memory);
+
+ /// Returns the token properties.
+ ///
+ /// @param tokenId Id for the token.
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @return Vector of properties key/value pairs.
+ /// @dev EVM selector for this function is: 0xefc26c69,
+ /// or in textual repr: tokenProperties(uint256,string[])
+ function tokenProperties(uint256 tokenId, string[] memory keys) external view returns (Property[] 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.
@@ -539,7 +554,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, Tuple10[] memory tokens) external returns (bool);
+ // function mintBulkWithTokenURI(address to, Tuple12[] memory tokens) external returns (bool);
/// Returns EVM address for refungible token
///
@@ -550,7 +565,7 @@
}
/// @dev anonymous struct
-struct Tuple10 {
+struct Tuple12 {
uint256 field_0;
string field_1;
}
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -117,7 +117,7 @@
});
itEth('ERC721UniqueExtensions support', async ({helper}) => {
- await checkInterface(helper, '0x0e9fc611', true, true);
+ await checkInterface(helper, '0xb8f094a0', true, true);
});
itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {
tests/src/eth/createFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createFTCollection.test.ts
+++ b/tests/src/eth/createFTCollection.test.ts
@@ -36,9 +36,11 @@
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.createFungibleCollection(owner, 'Sponsor', DECIMALS, 'absolutely anything', 'ENVY');
+ const description = 'absolutely anything';
+
+ const {collectionId, collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Sponsor', DECIMALS, description, 'ENVY');
- const collection = helper.ethNativeContract.collection(collectionAddress, 'rft', owner, true);
+ const collection = helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);
await collection.methods.setCollectionSponsor(sponsor).send();
let data = (await helper.rft.getData(collectionId))!;
@@ -57,8 +59,9 @@
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.createFungibleCollection(owner, 'Sponsor', DECIMALS, 'absolutely anything', 'ENVY');
-
+ const description = 'absolutely anything';
+ const {collectionId, collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Sponsor', DECIMALS, description, 'ENVY');
+
const collection = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);
await collection.methods.setCollectionSponsorCross(sponsorCross).send();
@@ -73,6 +76,7 @@
data = (await helper.rft.getData(collectionId))!;
expect(data.raw.sponsorship.Confirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
+ expect(await collection.methods.description().call()).to.deep.equal(description);
});
itEth('Set limits', async ({helper}) => {
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -28,7 +28,7 @@
});
});
- itEth('Create collection with properties', async ({helper}) => {
+ itEth('Create collection with properties & get desctription', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const name = 'CollectionEVM';
@@ -37,7 +37,8 @@
const baseUri = 'BaseURI';
const {collectionId, collectionAddress, events} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, name, description, prefix, baseUri);
-
+ const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
+
expect(events).to.be.deep.equal([
{
address: '0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F',
@@ -56,7 +57,9 @@
expect(data.description).to.be.eq(description);
expect(data.raw.tokenPrefix).to.be.eq(prefix);
expect(data.raw.mode).to.be.eq('NFT');
-
+
+ expect(await contract.methods.description().call()).to.deep.equal(description);
+
const options = await collection.getOptions();
expect(options.tokenPropertyPermissions).to.be.deep.equal([
{
@@ -92,11 +95,12 @@
expect(data.raw.sponsorship.Confirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
});
- itEth('[cross] Set sponsorship', async ({helper}) => {
+ itEth('[cross] Set sponsorship & get description', async ({helper}) => {
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.createNFTCollection(owner, 'Sponsor', 'absolutely anything', 'ROC');
+ const description = 'absolutely anything';
+ const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(owner, 'Sponsor', description, 'ROC');
const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);
@@ -112,6 +116,8 @@
data = (await helper.nft.getData(collectionId))!;
expect(data.raw.sponsorship.Confirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
+
+ expect(await sponsorCollection.methods.description().call()).to.deep.equal(description);
});
itEth('Set limits', async ({helper}) => {
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -53,7 +53,7 @@
- itEth('Create collection with properties', async ({helper}) => {
+ itEth('Create collection with properties & get description', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const name = 'CollectionEVM';
@@ -61,7 +61,8 @@
const prefix = 'token prefix';
const baseUri = 'BaseURI';
- const {collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, name, description, prefix, baseUri);
+ const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, name, description, prefix, baseUri);
+ const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
const collection = helper.rft.getCollectionObject(collectionId);
const data = (await collection.getData())!;
@@ -71,6 +72,8 @@
expect(data.raw.tokenPrefix).to.be.eq(prefix);
expect(data.raw.mode).to.be.eq('ReFungible');
+ expect(await contract.methods.description().call()).to.deep.equal(description);
+
const options = await collection.getOptions();
expect(options.tokenPropertyPermissions).to.be.deep.equal([
{
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -17,6 +17,7 @@
import {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util';
import {IKeyringPair} from '@polkadot/types/types';
import {Contract} from 'web3-eth-contract';
+import exp from 'constants';
describe('NFT: Information getting', () => {
@@ -149,7 +150,7 @@
});
});
- itEth('Can perform mint()', async ({helper}) => {
+ itEth('Can perform mint() & get crossOwner()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
@@ -166,7 +167,8 @@
expect(event.returnValues.to).to.be.equal(receiver);
expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
-
+ console.log(await contract.methods.crossOwnerOf(tokenId).call());
+ expect(await contract.methods.crossOwnerOf(tokenId).call()).to.be.like([receiver, '0']);
// TODO: this wont work right now, need release 919000 first
// await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();
// const tokenUri = await contract.methods.tokenURI(nextTokenId).call();
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -117,7 +117,7 @@
});
});
- itEth('Can perform mint()', async ({helper}) => {
+ itEth('Can perform mint() & crossOwnerOf()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Minty', '6', '6', '');
@@ -132,6 +132,7 @@
const tokenId = event.returnValues.tokenId;
expect(tokenId).to.be.equal('1');
+ expect(await contract.methods.crossOwnerOf(tokenId).call()).to.be.like([receiver, '0']);
expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
});
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -14,10 +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 {IKeyringPair} from '@polkadot/types/types';
-import {ITokenPropertyPermission} from '../util/playgrounds/types';
+import {ITokenPropertyPermission, TCollectionMode} from '../util/playgrounds/types';
import {Pallets} from '../util';
+import {UniqueNFTCollection, UniqueRFTCollection} from '../util/playgrounds/unique';
describe('EVM token properties', () => {
let donor: IKeyringPair;
@@ -95,7 +96,7 @@
expect(value).to.equal('testValue');
});
- itEth('Can be multiple set for NFT ', async({helper}) => {
+ async function checkProps(helper: EthUniqueHelper, mode: TCollectionMode) {
const caller = await helper.eth.createAccountWithBalance(donor);
const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });
@@ -103,56 +104,44 @@
collectionAdmin: true,
mutable: true}}; });
- const collection = await helper.nft.mintCollection(alice, {
+ const collection = await helper[mode].mintCollection(alice, {
tokenPrefix: 'ethp',
tokenPropertyPermissions: permissions,
- });
+ }) as UniqueNFTCollection | UniqueRFTCollection;
const token = await collection.mintToken(alice);
const valuesBefore = await token.getProperties(properties.map(p => p.key));
expect(valuesBefore).to.be.deep.equal([]);
+
await collection.addAdmin(alice, {Ethereum: caller});
-
+
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
- const contract = helper.ethNativeContract.collection(address, 'nft', caller);
+ const contract = helper.ethNativeContract.collection(address, mode, caller);
+
+ expect(await contract.methods.tokenProperties(token.tokenId, []).call()).to.be.deep.equal([]);
await contract.methods.setProperties(token.tokenId, properties).send({from: caller});
const values = await token.getProperties(properties.map(p => p.key));
expect(values).to.be.deep.equal(properties.map(p => { return {key: p.key, value: p.value.toString()}; }));
- });
-
- itEth.ifWithPallets('Can be multiple set for RFT ', [Pallets.ReFungible], async({helper}) => {
- const caller = await helper.eth.createAccountWithBalance(donor);
- const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });
- const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,
- collectionAdmin: true,
- mutable: true}}; });
-
- const collection = await helper.rft.mintCollection(alice, {
- tokenPrefix: 'ethp',
- tokenPropertyPermissions: permissions,
- });
-
- const token = await collection.mintToken(alice);
-
- const valuesBefore = await token.getProperties(properties.map(p => p.key));
- expect(valuesBefore).to.be.deep.equal([]);
+ expect(await contract.methods.tokenProperties(token.tokenId, []).call()).to.be.like(properties
+ .map(p => { return helper.ethProperty.property(p.key, p.value.toString()); }));
- await collection.addAdmin(alice, {Ethereum: caller});
-
- const address = helper.ethAddress.fromCollectionId(collection.collectionId);
- const contract = helper.ethNativeContract.collection(address, 'rft', caller);
-
- await contract.methods.setProperties(token.tokenId, properties).send({from: caller});
-
- const values = await token.getProperties(properties.map(p => p.key));
- expect(values).to.be.deep.equal(properties.map(p => { return {key: p.key, value: p.value.toString()}; }));
+ expect(await contract.methods.tokenProperties(token.tokenId, [properties[0].key]).call())
+ .to.be.like([helper.ethProperty.property(properties[0].key, properties[0].value.toString())]);
+ }
+
+ itEth('Can be multiple set/read for NFT ', async({helper}) => {
+ await checkProps(helper, 'nft');
+ });
+
+ itEth.ifWithPallets('Can be multiple set/read for RFT ', [Pallets.ReFungible], async({helper}) => {
+ await checkProps(helper, 'rft');
});
-
+
itEth('Can be deleted', async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const collection = await helper.nft.mintCollection(alice, {