difftreelog
refactor `collection_limits`, add docs for `CollectionLimits`
in: master
9 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -358,18 +358,16 @@
),
limits
.sponsored_data_rate_limit
- .map(|limit| {
- (
- EvmCollectionLimits::SponsoredDataRateLimit,
- match limit {
- SponsoringRateLimit::Blocks(_) => true,
- _ => false,
- },
- match limit {
- SponsoringRateLimit::Blocks(blocks) => blocks.into(),
- _ => Default::default(),
- },
- )
+ .and_then(|limit| {
+ if let SponsoringRateLimit::Blocks(blocks) = limit {
+ Some((
+ EvmCollectionLimits::SponsoredDataRateLimit,
+ true,
+ blocks.into(),
+ ))
+ } else {
+ None
+ }
})
.unwrap_or((
EvmCollectionLimits::SponsoredDataRateLimit,
pallets/common/src/eth.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//! The module contains a number of functions for converting and checking ethereum identifiers.1819use evm_coder::{20 AbiCoder,21 types::{uint256, address},22};23pub use pallet_evm::{Config, account::CrossAccountId};24use sp_core::H160;25use up_data_structs::CollectionId;2627// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 128// TODO: Unhardcode prefix29const ETH_COLLECTION_PREFIX: [u8; 16] = [30 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,31];3233/// Maps the ethereum address of the collection in substrate.34pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {35 if eth[0..16] != ETH_COLLECTION_PREFIX {36 return None;37 }38 let mut id_bytes = [0; 4];39 id_bytes.copy_from_slice(ð[16..20]);40 Some(CollectionId(u32::from_be_bytes(id_bytes)))41}4243/// Maps the substrate collection id in ethereum.44pub fn collection_id_to_address(id: CollectionId) -> H160 {45 let mut out = [0; 20];46 out[0..16].copy_from_slice(Ð_COLLECTION_PREFIX);47 out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));48 H160(out)49}5051/// Check if the ethereum address is a collection.52pub fn is_collection(address: &H160) -> bool {53 address[0..16] == ETH_COLLECTION_PREFIX54}5556/// Convert `CrossAccountId` to `uint256`.57pub fn convert_cross_account_to_uint256<T: Config>(from: &T::CrossAccountId) -> uint25658where59 T::AccountId: AsRef<[u8; 32]>,60{61 let slice = from.as_sub().as_ref();62 uint256::from_big_endian(slice)63}6465/// Convert `uint256` to `CrossAccountId`.66pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId67where68 T::AccountId: From<[u8; 32]>,69{70 let mut new_admin_arr = [0_u8; 32];71 from.to_big_endian(&mut new_admin_arr);72 let account_id = T::AccountId::from(new_admin_arr);73 T::CrossAccountId::from_sub(account_id)74}7576/// Convert `CrossAccountId` to `(address, uint256)`.77pub fn convert_cross_account_to_tuple<T: Config>(78 cross_account_id: &T::CrossAccountId,79) -> (address, uint256)80where81 T::AccountId: AsRef<[u8; 32]>,82{83 if cross_account_id.is_canonical_substrate() {84 let sub = convert_cross_account_to_uint256::<T>(cross_account_id);85 (Default::default(), sub)86 } else {87 let eth = *cross_account_id.as_eth();88 (eth, Default::default())89 }90}9192/// Convert tuple `(address, uint256)` to `CrossAccountId`.93///94/// If `address` in the tuple has *default* value, then the canonical form is substrate,95/// if `uint256` has *default* value, then the ethereum form is canonical,96/// if both values are *default* or *non default*, then this is considered an invalid address and `Error` is returned.97pub fn convert_tuple_to_cross_account<T: Config>(98 eth_cross_account_id: (address, uint256),99) -> evm_coder::execution::Result<T::CrossAccountId>100where101 T::AccountId: From<[u8; 32]>,102{103 if eth_cross_account_id == Default::default() {104 Err("All fields of cross account is zeroed".into())105 } else if eth_cross_account_id.0 == Default::default() {106 Ok(convert_uint256_to_cross_account::<T>(107 eth_cross_account_id.1,108 ))109 } else if eth_cross_account_id.1 == Default::default() {110 Ok(T::CrossAccountId::from_eth(eth_cross_account_id.0))111 } else {112 Err("All fields of cross account is non zeroed".into())113 }114}115116/// Cross account struct117#[derive(Debug, Default, AbiCoder)]118pub struct EthCrossAccount {119 pub(crate) eth: address,120 pub(crate) sub: uint256,121}122123impl EthCrossAccount {124 pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self125 where126 T: pallet_evm::Config,127 T::AccountId: AsRef<[u8; 32]>,128 {129 if cross_account_id.is_canonical_substrate() {130 Self {131 eth: Default::default(),132 sub: convert_cross_account_to_uint256::<T>(cross_account_id),133 }134 } else {135 Self {136 eth: *cross_account_id.as_eth(),137 sub: Default::default(),138 }139 }140 }141142 pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>143 where144 T: pallet_evm::Config,145 T::AccountId: From<[u8; 32]>,146 {147 if self.eth == Default::default() && self.sub == Default::default() {148 Err("All fields of cross account is zeroed".into())149 } else if self.eth == Default::default() {150 Ok(convert_uint256_to_cross_account::<T>(self.sub))151 } else if self.sub == Default::default() {152 Ok(T::CrossAccountId::from_eth(self.eth))153 } else {154 Err("All fields of cross account is non zeroed".into())155 }156 }157}158#[derive(Debug, Default, Clone, Copy, AbiCoder)]159#[repr(u8)]160pub enum CollectionLimits {161 #[default]162 AccountTokenOwnership,163 SponsoredDataSize,164 SponsoredDataRateLimit,165 TokenLimit,166 SponsorTransferTimeout,167 SponsorApproveTimeout,168 OwnerCanTransfer,169 OwnerCanDestroy,170 TransferEnabled,171}172#[derive(Default, Debug, Clone, Copy, AbiCoder)]173#[repr(u8)]174pub enum CollectionPermissions {175 #[default]176 CollectionAdmin,177 TokenOwner,178}179180/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.181#[derive(AbiCoder, Copy, Clone, Default, Debug)]182#[repr(u8)]183pub enum EthTokenPermissions {184 /// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]185 #[default]186 Mutable,187188 /// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]189 TokenOwner,190191 /// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]192 CollectionAdmin,193}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//! The module contains a number of functions for converting and checking ethereum identifiers.1819use evm_coder::{20 AbiCoder,21 types::{uint256, address},22};23pub use pallet_evm::{Config, account::CrossAccountId};24use sp_core::H160;25use up_data_structs::CollectionId;2627// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 128// TODO: Unhardcode prefix29const ETH_COLLECTION_PREFIX: [u8; 16] = [30 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,31];3233/// Maps the ethereum address of the collection in substrate.34pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {35 if eth[0..16] != ETH_COLLECTION_PREFIX {36 return None;37 }38 let mut id_bytes = [0; 4];39 id_bytes.copy_from_slice(ð[16..20]);40 Some(CollectionId(u32::from_be_bytes(id_bytes)))41}4243/// Maps the substrate collection id in ethereum.44pub fn collection_id_to_address(id: CollectionId) -> H160 {45 let mut out = [0; 20];46 out[0..16].copy_from_slice(Ð_COLLECTION_PREFIX);47 out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));48 H160(out)49}5051/// Check if the ethereum address is a collection.52pub fn is_collection(address: &H160) -> bool {53 address[0..16] == ETH_COLLECTION_PREFIX54}5556/// Convert `CrossAccountId` to `uint256`.57pub fn convert_cross_account_to_uint256<T: Config>(from: &T::CrossAccountId) -> uint25658where59 T::AccountId: AsRef<[u8; 32]>,60{61 let slice = from.as_sub().as_ref();62 uint256::from_big_endian(slice)63}6465/// Convert `uint256` to `CrossAccountId`.66pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId67where68 T::AccountId: From<[u8; 32]>,69{70 let mut new_admin_arr = [0_u8; 32];71 from.to_big_endian(&mut new_admin_arr);72 let account_id = T::AccountId::from(new_admin_arr);73 T::CrossAccountId::from_sub(account_id)74}7576/// Convert `CrossAccountId` to `(address, uint256)`.77pub fn convert_cross_account_to_tuple<T: Config>(78 cross_account_id: &T::CrossAccountId,79) -> (address, uint256)80where81 T::AccountId: AsRef<[u8; 32]>,82{83 if cross_account_id.is_canonical_substrate() {84 let sub = convert_cross_account_to_uint256::<T>(cross_account_id);85 (Default::default(), sub)86 } else {87 let eth = *cross_account_id.as_eth();88 (eth, Default::default())89 }90}9192/// Convert tuple `(address, uint256)` to `CrossAccountId`.93///94/// If `address` in the tuple has *default* value, then the canonical form is substrate,95/// if `uint256` has *default* value, then the ethereum form is canonical,96/// if both values are *default* or *non default*, then this is considered an invalid address and `Error` is returned.97pub fn convert_tuple_to_cross_account<T: Config>(98 eth_cross_account_id: (address, uint256),99) -> evm_coder::execution::Result<T::CrossAccountId>100where101 T::AccountId: From<[u8; 32]>,102{103 if eth_cross_account_id == Default::default() {104 Err("All fields of cross account is zeroed".into())105 } else if eth_cross_account_id.0 == Default::default() {106 Ok(convert_uint256_to_cross_account::<T>(107 eth_cross_account_id.1,108 ))109 } else if eth_cross_account_id.1 == Default::default() {110 Ok(T::CrossAccountId::from_eth(eth_cross_account_id.0))111 } else {112 Err("All fields of cross account is non zeroed".into())113 }114}115116/// Cross account struct117#[derive(Debug, Default, AbiCoder)]118pub struct EthCrossAccount {119 pub(crate) eth: address,120 pub(crate) sub: uint256,121}122123impl EthCrossAccount {124 pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self125 where126 T: pallet_evm::Config,127 T::AccountId: AsRef<[u8; 32]>,128 {129 if cross_account_id.is_canonical_substrate() {130 Self {131 eth: Default::default(),132 sub: convert_cross_account_to_uint256::<T>(cross_account_id),133 }134 } else {135 Self {136 eth: *cross_account_id.as_eth(),137 sub: Default::default(),138 }139 }140 }141142 pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>143 where144 T: pallet_evm::Config,145 T::AccountId: From<[u8; 32]>,146 {147 if self.eth == Default::default() && self.sub == Default::default() {148 Err("All fields of cross account is zeroed".into())149 } else if self.eth == Default::default() {150 Ok(convert_uint256_to_cross_account::<T>(self.sub))151 } else if self.sub == Default::default() {152 Ok(T::CrossAccountId::from_eth(self.eth))153 } else {154 Err("All fields of cross account is non zeroed".into())155 }156 }157}158159/// [`CollectionLimits`](up_data_structs::CollectionLimits) representation for EVM.160#[derive(Debug, Default, Clone, Copy, AbiCoder)]161#[repr(u8)]162pub enum CollectionLimits {163 #[default]164 AccountTokenOwnership,165 SponsoredDataSize,166 SponsoredDataRateLimit,167 TokenLimit,168 SponsorTransferTimeout,169 SponsorApproveTimeout,170 OwnerCanTransfer,171 OwnerCanDestroy,172 TransferEnabled,173}174#[derive(Default, Debug, Clone, Copy, AbiCoder)]175#[repr(u8)]176pub enum CollectionPermissions {177 #[default]178 CollectionAdmin,179 TokenOwner,180}181182/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.183#[derive(AbiCoder, Copy, Clone, Default, Debug)]184#[repr(u8)]185pub enum EthTokenPermissions {186 /// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]187 #[default]188 Mutable,189190 /// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]191 TokenOwner,192193 /// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]194 CollectionAdmin,195}tests/src/eth/collectionLimits.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionLimits.test.ts
+++ b/tests/src/eth/collectionLimits.test.ts
@@ -1,6 +1,7 @@
import {IKeyringPair} from '@polkadot/types/types';
import {Pallets} from '../util';
-import {CollectionLimits, expect, itEth, usingEthPlaygrounds} from './util';
+import {expect, itEth, usingEthPlaygrounds} from './util';
+import {CollectionLimits} from './util/playgrounds/types';
describe('Can set collection limits', () => {
@@ -62,15 +63,15 @@
// Check limits from eth:
const limitsEvm = await collectionEvm.methods.collectionLimits().call({from: owner});
expect(limitsEvm).to.have.length(9);
- expect(limitsEvm[0]).to.deep.eq(['0', true, limits.accountTokenOwnershipLimit.toString()]);
- expect(limitsEvm[1]).to.deep.eq(['1', true, limits.sponsoredDataSize.toString()]);
- expect(limitsEvm[2]).to.deep.eq(['2', true, limits.sponsoredDataRateLimit.toString()]);
- expect(limitsEvm[3]).to.deep.eq(['3', true, limits.tokenLimit.toString()]);
- expect(limitsEvm[4]).to.deep.eq(['4', true, limits.sponsorTransferTimeout.toString()]);
- expect(limitsEvm[5]).to.deep.eq(['5', true, limits.sponsorApproveTimeout.toString()]);
- expect(limitsEvm[6]).to.deep.eq(['6', true, limits.ownerCanTransfer.toString()]);
- expect(limitsEvm[7]).to.deep.eq(['7', true, limits.ownerCanDestroy.toString()]);
- expect(limitsEvm[8]).to.deep.eq(['8', true, limits.transfersEnabled.toString()]);
+ expect(limitsEvm[0]).to.deep.eq([CollectionLimits.AccountTokenOwnership.toString(), true, limits.accountTokenOwnershipLimit.toString()]);
+ expect(limitsEvm[1]).to.deep.eq([CollectionLimits.SponsoredDataSize.toString(), true, limits.sponsoredDataSize.toString()]);
+ expect(limitsEvm[2]).to.deep.eq([CollectionLimits.SponsoredDataRateLimit.toString(), true, limits.sponsoredDataRateLimit.toString()]);
+ expect(limitsEvm[3]).to.deep.eq([CollectionLimits.TokenLimit.toString(), true, limits.tokenLimit.toString()]);
+ expect(limitsEvm[4]).to.deep.eq([CollectionLimits.SponsorTransferTimeout.toString(), true, limits.sponsorTransferTimeout.toString()]);
+ expect(limitsEvm[5]).to.deep.eq([CollectionLimits.SponsorApproveTimeout.toString(), true, limits.sponsorApproveTimeout.toString()]);
+ expect(limitsEvm[6]).to.deep.eq([CollectionLimits.OwnerCanTransfer.toString(), true, limits.ownerCanTransfer.toString()]);
+ expect(limitsEvm[7]).to.deep.eq([CollectionLimits.OwnerCanDestroy.toString(), true, limits.ownerCanDestroy.toString()]);
+ expect(limitsEvm[8]).to.deep.eq([CollectionLimits.TransferEnabled.toString(), true, limits.transfersEnabled.toString()]);
}));
});
tests/src/eth/createFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createFTCollection.test.ts
+++ b/tests/src/eth/createFTCollection.test.ts
@@ -17,7 +17,8 @@
import {IKeyringPair} from '@polkadot/types/types';
import {evmToAddress} from '@polkadot/util-crypto';
import {Pallets, requirePalletsOrSkip} from '../util';
-import {CollectionLimits, expect, itEth, usingEthPlaygrounds} from './util';
+import {expect, itEth, usingEthPlaygrounds} from './util';
+import { CollectionLimits } from './util/playgrounds/types';
const DECIMALS = 18;
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -16,7 +16,8 @@
import {evmToAddress} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
-import {CollectionLimits, expect, itEth, usingEthPlaygrounds} from './util';
+import {expect, itEth, usingEthPlaygrounds} from './util';
+import { CollectionLimits } from './util/playgrounds/types';
describe('Create NFT collection from EVM', () => {
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -17,7 +17,8 @@
import {evmToAddress} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
import {Pallets, requirePalletsOrSkip} from '../util';
-import {CollectionLimits, expect, itEth, usingEthPlaygrounds} from './util';
+import {expect, itEth, usingEthPlaygrounds} from './util';
+import { CollectionLimits } from './util/playgrounds/types';
describe('Create RFT collection from EVM', () => {
tests/src/eth/events.test.tsdiffbeforeafterboth--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -16,10 +16,10 @@
import {expect} from 'chai';
import {IKeyringPair} from '@polkadot/types/types';
-import {CollectionLimits, EthUniqueHelper, itEth, usingEthPlaygrounds} from './util';
+import {EthUniqueHelper, itEth, usingEthPlaygrounds} from './util';
import {IEvent, TCollectionMode} from '../util/playgrounds/types';
import {Pallets, requirePalletsOrSkip} from '../util';
-import {EthTokenPermissions, NormalizedEvent} from './util/playgrounds/types';
+import {CollectionLimits, EthTokenPermissions, NormalizedEvent} from './util/playgrounds/types';
let donor: IKeyringPair;
tests/src/eth/util/index.tsdiffbeforeafterboth--- a/tests/src/eth/util/index.ts
+++ b/tests/src/eth/util/index.ts
@@ -26,18 +26,8 @@
Allowlisted = 1,
Generous = 2,
}
-export enum CollectionLimits {
- AccountTokenOwnership,
- SponsoredDataSize,
- SponsoredDataRateLimit,
- TokenLimit,
- SponsorTransferTimeout,
- SponsorApproveTimeout,
- OwnerCanTransfer,
- OwnerCanDestroy,
- TransferEnabled
-}
+
export const usingEthPlaygrounds = async (code: (helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair>) => Promise<void>) => {
const silentConsole = new SilentConsole();
silentConsole.enable();
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -24,4 +24,15 @@
Mutable,
TokenOwner,
CollectionAdmin
-}
\ No newline at end of file
+}
+export enum CollectionLimits {
+ AccountTokenOwnership,
+ SponsoredDataSize,
+ SponsoredDataRateLimit,
+ TokenLimit,
+ SponsorTransferTimeout,
+ SponsorApproveTimeout,
+ OwnerCanTransfer,
+ OwnerCanDestroy,
+ TransferEnabled
+}