difftreelog
doc(refungible-pallet): add documentation for ERC-721 implementation
in: master
1 file 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/>.1617extern crate alloc;1819use alloc::string::ToString;20use core::{21 char::{REPLACEMENT_CHARACTER, decode_utf16},22 convert::TryInto,23};24use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};25use frame_support::{BoundedBTreeMap, BoundedVec};26use pallet_common::{27 CollectionHandle, CollectionPropertyPermissions,28 erc::{29 CommonEvmHandler, CollectionCall,30 static_property::{key, value as property_value},31 },32};33use pallet_evm::{account::CrossAccountId, PrecompileHandle};34use pallet_evm_coder_substrate::{call, dispatch_to_evm};35use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};36use sp_core::H160;37use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};38use up_data_structs::{39 CollectionId, CollectionPropertiesVec, Property, PropertyKey, PropertyKeyPermission,40 PropertyPermission, TokenId,41};4243use crate::{44 AccountBalance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,45 TokenProperties, TokensMinted, weights::WeightInfo,46};4748#[solidity_interface(name = "TokenProperties")]49impl<T: Config> RefungibleHandle<T> {50 fn set_token_property_permission(51 &mut self,52 caller: caller,53 key: string,54 is_mutable: bool,55 collection_admin: bool,56 token_owner: bool,57 ) -> Result<()> {58 let caller = T::CrossAccountId::from_eth(caller);59 <Pallet<T>>::set_token_property_permissions(60 self,61 &caller,62 vec![PropertyKeyPermission {63 key: <Vec<u8>>::from(key)64 .try_into()65 .map_err(|_| "too long key")?,66 permission: PropertyPermission {67 mutable: is_mutable,68 collection_admin,69 token_owner,70 },71 }],72 )73 .map_err(dispatch_to_evm::<T>)74 }7576 fn set_property(77 &mut self,78 caller: caller,79 token_id: uint256,80 key: string,81 value: bytes,82 ) -> Result<()> {83 let caller = T::CrossAccountId::from_eth(caller);84 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;85 let key = <Vec<u8>>::from(key)86 .try_into()87 .map_err(|_| "key too long")?;88 let value = value.try_into().map_err(|_| "value too long")?;8990 let nesting_budget = self91 .recorder92 .weight_calls_budget(<StructureWeight<T>>::find_parent());9394 <Pallet<T>>::set_token_property(95 self,96 &caller,97 TokenId(token_id),98 Property { key, value },99 &nesting_budget,100 )101 .map_err(dispatch_to_evm::<T>)102 }103104 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {105 let caller = T::CrossAccountId::from_eth(caller);106 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;107 let key = <Vec<u8>>::from(key)108 .try_into()109 .map_err(|_| "key too long")?;110111 let nesting_budget = self112 .recorder113 .weight_calls_budget(<StructureWeight<T>>::find_parent());114115 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)116 .map_err(dispatch_to_evm::<T>)117 }118119 /// Throws error if key not found120 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {121 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;122 let key = <Vec<u8>>::from(key)123 .try_into()124 .map_err(|_| "key too long")?;125126 let props = <TokenProperties<T>>::get((self.id, token_id));127 let prop = props.get(&key).ok_or("key not found")?;128129 Ok(prop.to_vec())130 }131}132133#[derive(ToLog)]134pub enum ERC721Events {135 Transfer {136 #[indexed]137 from: address,138 #[indexed]139 to: address,140 #[indexed]141 token_id: uint256,142 },143 /// @dev Not supported144 Approval {145 #[indexed]146 owner: address,147 #[indexed]148 approved: address,149 #[indexed]150 token_id: uint256,151 },152 /// @dev Not supported153 #[allow(dead_code)]154 ApprovalForAll {155 #[indexed]156 owner: address,157 #[indexed]158 operator: address,159 approved: bool,160 },161}162163#[derive(ToLog)]164pub enum ERC721MintableEvents {165 /// @dev Not supported166 #[allow(dead_code)]167 MintingFinished {},168}169170#[solidity_interface(name = "ERC721Metadata")]171impl<T: Config> RefungibleHandle<T> {172 fn name(&self) -> Result<string> {173 Ok(decode_utf16(self.name.iter().copied())174 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))175 .collect::<string>())176 }177178 fn symbol(&self) -> Result<string> {179 Ok(string::from_utf8_lossy(&self.token_prefix).into())180 }181182 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.183 ///184 /// @dev If the token has a `url` property and it is not empty, it is returned.185 /// 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`.186 /// If the collection property `baseURI` is empty or absent, return "" (empty string)187 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix188 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).189 ///190 /// @return token's const_metadata191 #[solidity(rename_selector = "tokenURI")]192 fn token_uri(&self, token_id: uint256) -> Result<string> {193 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;194195 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {196 if !url.is_empty() {197 return Ok(url);198 }199 } else if !is_erc721_metadata_compatible::<T>(self.id) {200 return Err("tokenURI not set".into());201 }202203 if let Some(base_uri) =204 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())205 {206 if !base_uri.is_empty() {207 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {208 Error::Revert(alloc::format!(209 "Can not convert value \"baseURI\" to string with error \"{}\"",210 e211 ))212 })?;213 if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {214 if !suffix.is_empty() {215 return Ok(base_uri + suffix.as_str());216 }217 }218219 return Ok(base_uri + token_id.to_string().as_str());220 }221 }222223 Ok("".into())224 }225}226227#[solidity_interface(name = "ERC721Enumerable")]228impl<T: Config> RefungibleHandle<T> {229 fn token_by_index(&self, index: uint256) -> Result<uint256> {230 Ok(index)231 }232233 /// Not implemented234 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {235 // TODO: Not implemetable236 Err("not implemented".into())237 }238239 fn total_supply(&self) -> Result<uint256> {240 self.consume_store_reads(1)?;241 Ok(<Pallet<T>>::total_supply(self).into())242 }243}244245#[solidity_interface(name = "ERC721", events(ERC721Events))]246impl<T: Config> RefungibleHandle<T> {247 fn balance_of(&self, owner: address) -> Result<uint256> {248 self.consume_store_reads(1)?;249 let owner = T::CrossAccountId::from_eth(owner);250 let balance = <AccountBalance<T>>::get((self.id, owner));251 Ok(balance.into())252 }253254 fn owner_of(&self, token_id: uint256) -> Result<address> {255 self.consume_store_reads(2)?;256 let token = token_id.try_into()?;257 let owner = <Pallet<T>>::token_owner(self.id, token);258 Ok(owner259 .map(|address| *address.as_eth())260 .unwrap_or_else(|| H160::default()))261 }262263 /// @dev Not implemented264 fn safe_transfer_from_with_data(265 &mut self,266 _from: address,267 _to: address,268 _token_id: uint256,269 _data: bytes,270 _value: value,271 ) -> Result<void> {272 // TODO: Not implemetable273 Err("not implemented".into())274 }275276 /// @dev Not implemented277 fn safe_transfer_from(278 &mut self,279 _from: address,280 _to: address,281 _token_id: uint256,282 _value: value,283 ) -> Result<void> {284 // TODO: Not implemetable285 Err("not implemented".into())286 }287288 /// @dev Not implemented289 fn transfer_from(290 &mut self,291 _caller: caller,292 _from: address,293 _to: address,294 _token_id: uint256,295 _value: value,296 ) -> Result<void> {297 Err("not implemented".into())298 }299300 /// @dev Not implemented301 fn approve(302 &mut self,303 _caller: caller,304 _approved: address,305 _token_id: uint256,306 _value: value,307 ) -> Result<void> {308 Err("not implemented".into())309 }310311 /// @dev Not implemented312 fn set_approval_for_all(313 &mut self,314 _caller: caller,315 _operator: address,316 _approved: bool,317 ) -> Result<void> {318 // TODO: Not implemetable319 Err("not implemented".into())320 }321322 /// @dev Not implemented323 fn get_approved(&self, _token_id: uint256) -> Result<address> {324 // TODO: Not implemetable325 Err("not implemented".into())326 }327328 /// @dev Not implemented329 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {330 // TODO: Not implemetable331 Err("not implemented".into())332 }333}334335#[solidity_interface(name = "ERC721Burnable")]336impl<T: Config> RefungibleHandle<T> {337 /// @dev Not implemented338 fn burn(&mut self, _caller: caller, _token_id: uint256, _value: value) -> Result<void> {339 Err("not implemented".into())340 }341}342343#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]344impl<T: Config> RefungibleHandle<T> {345 fn minting_finished(&self) -> Result<bool> {346 Ok(false)347 }348349 /// `token_id` should be obtained with `next_token_id` method,350 /// unlike standard, you can't specify it manually351 #[weight(<SelfWeightOf<T>>::create_item())]352 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {353 let caller = T::CrossAccountId::from_eth(caller);354 let to = T::CrossAccountId::from_eth(to);355 let token_id: u32 = token_id.try_into()?;356 let budget = self357 .recorder358 .weight_calls_budget(<StructureWeight<T>>::find_parent());359360 if <TokensMinted<T>>::get(self.id)361 .checked_add(1)362 .ok_or("item id overflow")?363 != token_id364 {365 return Err("item id should be next".into());366 }367368 let const_data = BoundedVec::default();369 let users = [(to.clone(), 1)]370 .into_iter()371 .collect::<BTreeMap<_, _>>()372 .try_into()373 .unwrap();374 <Pallet<T>>::create_item(375 self,376 &caller,377 CreateItemData::<T> {378 const_data,379 users,380 properties: CollectionPropertiesVec::default(),381 },382 &budget,383 )384 .map_err(dispatch_to_evm::<T>)?;385386 Ok(true)387 }388389 /// `token_id` should be obtained with `next_token_id` method,390 /// unlike standard, you can't specify it manually391 #[solidity(rename_selector = "mintWithTokenURI")]392 #[weight(<SelfWeightOf<T>>::create_item())]393 fn mint_with_token_uri(394 &mut self,395 caller: caller,396 to: address,397 token_id: uint256,398 token_uri: string,399 ) -> Result<bool> {400 let key = key::url();401 let permission = get_token_permission::<T>(self.id, &key)?;402 if !permission.collection_admin {403 return Err("Operation is not allowed".into());404 }405406 let caller = T::CrossAccountId::from_eth(caller);407 let to = T::CrossAccountId::from_eth(to);408 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;409 let budget = self410 .recorder411 .weight_calls_budget(<StructureWeight<T>>::find_parent());412413 if <TokensMinted<T>>::get(self.id)414 .checked_add(1)415 .ok_or("item id overflow")?416 != token_id417 {418 return Err("item id should be next".into());419 }420421 let mut properties = CollectionPropertiesVec::default();422 properties423 .try_push(Property {424 key,425 value: token_uri426 .into_bytes()427 .try_into()428 .map_err(|_| "token uri is too long")?,429 })430 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;431432 let const_data = BoundedVec::default();433 let users = [(to.clone(), 1)]434 .into_iter()435 .collect::<BTreeMap<_, _>>()436 .try_into()437 .unwrap();438 <Pallet<T>>::create_item(439 self,440 &caller,441 CreateItemData::<T> {442 const_data,443 users,444 properties,445 },446 &budget,447 )448 .map_err(dispatch_to_evm::<T>)?;449 Ok(true)450 }451452 /// @dev Not implemented453 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {454 Err("not implementable".into())455 }456}457458fn get_token_property<T: Config>(459 collection: &CollectionHandle<T>,460 token_id: u32,461 key: &up_data_structs::PropertyKey,462) -> Result<string> {463 collection.consume_store_reads(1)?;464 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))465 .map_err(|_| Error::Revert("Token properties not found".into()))?;466 if let Some(property) = properties.get(key) {467 return Ok(string::from_utf8_lossy(property).into());468 }469470 Err("Property tokenURI not found".into())471}472473fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {474 if let Some(shema_name) =475 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())476 {477 let shema_name = shema_name.into_inner();478 shema_name == property_value::ERC721_METADATA479 } else {480 false481 }482}483484fn get_token_permission<T: Config>(485 collection_id: CollectionId,486 key: &PropertyKey,487) -> Result<PropertyPermission> {488 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)489 .map_err(|_| Error::Revert("No permissions for collection".into()))?;490 let a = token_property_permissions491 .get(key)492 .map(Clone::clone)493 .ok_or_else(|| {494 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();495 Error::Revert(alloc::format!("No permission for key {}", key))496 })?;497 Ok(a)498}499500#[solidity_interface(name = "ERC721UniqueExtensions")]501impl<T: Config> RefungibleHandle<T> {502 /// @notice Returns next free RFT ID.503 fn next_token_id(&self) -> Result<uint256> {504 self.consume_store_reads(1)?;505 Ok(<TokensMinted<T>>::get(self.id)506 .checked_add(1)507 .ok_or("item id overflow")?508 .into())509 }510511 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]512 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {513 let caller = T::CrossAccountId::from_eth(caller);514 let to = T::CrossAccountId::from_eth(to);515 let mut expected_index = <TokensMinted<T>>::get(self.id)516 .checked_add(1)517 .ok_or("item id overflow")?;518 let budget = self519 .recorder520 .weight_calls_budget(<StructureWeight<T>>::find_parent());521522 let total_tokens = token_ids.len();523 for id in token_ids.into_iter() {524 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;525 if id != expected_index {526 return Err("item id should be next".into());527 }528 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;529 }530 let const_data = BoundedVec::default();531 let users = [(to.clone(), 1)]532 .into_iter()533 .collect::<BTreeMap<_, _>>()534 .try_into()535 .unwrap();536 let create_item_data = CreateItemData::<T> {537 const_data,538 users,539 properties: CollectionPropertiesVec::default(),540 };541 let data = (0..total_tokens)542 .map(|_| create_item_data.clone())543 .collect();544545 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)546 .map_err(dispatch_to_evm::<T>)?;547 Ok(true)548 }549550 #[solidity(rename_selector = "mintBulkWithTokenURI")]551 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]552 fn mint_bulk_with_token_uri(553 &mut self,554 caller: caller,555 to: address,556 tokens: Vec<(uint256, string)>,557 ) -> Result<bool> {558 let key = key::url();559 let caller = T::CrossAccountId::from_eth(caller);560 let to = T::CrossAccountId::from_eth(to);561 let mut expected_index = <TokensMinted<T>>::get(self.id)562 .checked_add(1)563 .ok_or("item id overflow")?;564 let budget = self565 .recorder566 .weight_calls_budget(<StructureWeight<T>>::find_parent());567568 let mut data = Vec::with_capacity(tokens.len());569 let const_data = BoundedVec::default();570 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]571 .into_iter()572 .collect::<BTreeMap<_, _>>()573 .try_into()574 .unwrap();575 for (id, token_uri) in tokens {576 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;577 if id != expected_index {578 return Err("item id should be next".into());579 }580 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;581582 let mut properties = CollectionPropertiesVec::default();583 properties584 .try_push(Property {585 key: key.clone(),586 value: token_uri587 .into_bytes()588 .try_into()589 .map_err(|_| "token uri is too long")?,590 })591 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;592593 let create_item_data = CreateItemData::<T> {594 const_data: const_data.clone(),595 users: users.clone(),596 properties,597 };598 data.push(create_item_data);599 }600601 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)602 .map_err(dispatch_to_evm::<T>)?;603 Ok(true)604 }605}606607#[solidity_interface(608 name = "UniqueRefungible",609 is(610 ERC721,611 ERC721Metadata,612 ERC721Enumerable,613 ERC721UniqueExtensions,614 ERC721Mintable,615 ERC721Burnable,616 via("CollectionHandle<T>", common_mut, Collection),617 TokenProperties,618 )619)]620impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> {}621622// Not a tests, but code generators623generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);624generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);625626impl<T: Config> CommonEvmHandler for RefungibleHandle<T>627where628 T::AccountId: From<[u8; 32]>,629{630 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");631 fn call(632 self,633 handle: &mut impl PrecompileHandle,634 ) -> Option<pallet_common::erc::PrecompileResult> {635 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)636 }637}