difftreelog
feat erc nesting tests + some fixes
in: master
5 files changed
pallets/balances-adapter/src/lib.rsdiffbeforeafterboth1// #![doc = include_str!("../README.md")]2#![cfg_attr(not(feature = "std"), no_std)]34extern crate alloc;5use core::ops::Deref;67use frame_support::sp_runtime::DispatchResult;8use pallet_evm_coder_substrate::{WithRecorder, SubstrateRecorder};9pub use pallet::*;1011pub mod common;12pub mod erc;1314pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;1516const NATIVE_FUNGIBLE_COLLECTION_ID: up_data_structs::CollectionId =17 up_data_structs::CollectionId(0);1819/// Handle for native fungible collection20pub struct NativeFungibleHandle<T: Config>(SubstrateRecorder<T>);21impl<T: Config> NativeFungibleHandle<T> {22 /// Creates a handle23 pub fn new() -> NativeFungibleHandle<T> {24 Self(SubstrateRecorder::new(u64::MAX))25 }2627 /// Check if the collection is internal28 pub fn check_is_internal(&self) -> DispatchResult {29 Ok(())30 }31}3233impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {34 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {35 &self.036 }37 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {38 self.039 }40}4142impl<T: Config> Deref for NativeFungibleHandle<T> {43 type Target = SubstrateRecorder<T>;4445 fn deref(&self) -> &Self::Target {46 &self.047 }48}49#[frame_support::pallet]50pub mod pallet {51 use super::*;52 use alloc::string::String;53 use frame_support::{54 dispatch::PostDispatchInfo,55 ensure,56 pallet_prelude::{DispatchResultWithPostInfo, Pays},57 traits::{Currency, ExistenceRequirement, Get},58 };59 use pallet_balances::WeightInfo;60 use pallet_common::{erc::CrossAccountId, Error as CommonError, Pallet as PalletCommon};61 use pallet_structure::Pallet as PalletStructure;62 use sp_core::U256;63 use sp_runtime::DispatchError;64 use up_data_structs::{budget::Budget, mapping::TokenAddressMapping, TokenId};6566 #[pallet::config]67 pub trait Config:68 frame_system::Config69 + pallet_evm_coder_substrate::Config70 + pallet_common::Config71 + pallet_structure::Config72 {73 /// Currency from `pallet_balances`74 type Currency: frame_support::traits::Currency<75 Self::AccountId,76 Balance = Self::CurrencyBalance,77 >;78 /// Balance type of chain79 type CurrencyBalance: Into<U256> + TryFrom<U256> + PartialEq<u128> + From<u128> + Into<u128>;8081 /// Decimals of balance82 type Decimals: Get<u8>;83 /// Collection name84 type Name: Get<String>;85 /// Collection symbol86 type Symbol: Get<String>;8788 /// Weight information89 type WeightInfo: WeightInfo;90 }91 #[pallet::pallet]92 pub struct Pallet<T>(_);9394 impl<T: Config> Pallet<T> {95 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.96 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.97 ///98 /// - `collection`: Collection that contains the token.99 /// - `spender`: CrossAccountId who has the allowance rights.100 /// - `from`: The owner of the tokens who sets the allowance.101 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.102 fn check_allowed(103 spender: &T::CrossAccountId,104 from: &T::CrossAccountId,105 nesting_budget: &dyn Budget,106 ) -> Result<u128, DispatchError> {107 if spender.conv_eq(from) {108 return Ok(0);109 }110111 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {112 ensure!(113 <PalletStructure<T>>::check_indirectly_owned(114 spender.clone(),115 source.0,116 source.1,117 None,118 nesting_budget119 )?,120 <CommonError<T>>::ApprovedValueTooLow,121 );122 } else if spender != from {123 return Ok(0);124 }125126 Ok(<T as Config>::Currency::free_balance(from.as_sub()).into())127 }128129 /// Transfers the specified amount of tokens. Will check that130 /// the transfer is allowed for the token.131 ///132 /// - `from`: Owner of tokens to transfer.133 /// - `to`: Recepient of transfered tokens.134 /// - `amount`: Amount of tokens to transfer.135 /// - `collection`: Collection that contains the token136 pub fn transfer(137 _collection: &NativeFungibleHandle<T>,138 from: &T::CrossAccountId,139 to: &T::CrossAccountId,140 amount: u128,141 nesting_budget: &dyn Budget,142 ) -> DispatchResultWithPostInfo {143 <PalletCommon<T>>::ensure_correct_receiver(to)?;144145 if from != to && amount != 0 {146 <T as Config>::Currency::transfer(147 from.as_sub(),148 to.as_sub(),149 amount.into(),150 ExistenceRequirement::KeepAlive,151 )?;152153 <PalletStructure<T>>::nest_if_sent_to_token(154 from.clone(),155 to,156 NATIVE_FUNGIBLE_COLLECTION_ID,157 TokenId::default(),158 nesting_budget,159 )?;160161 let balance_from: u128 =162 <T as Config>::Currency::free_balance(from.as_sub()).into();163 if balance_from == 0 {164 <PalletStructure<T>>::unnest_if_nested(165 from,166 NATIVE_FUNGIBLE_COLLECTION_ID,167 TokenId::default(),168 );169 }170 };171172 Ok(PostDispatchInfo {173 actual_weight: Some(<SelfWeightOf<T>>::transfer()),174 pays_fee: Pays::Yes,175 })176 }177178 pub fn transfer_from(179 collection: &NativeFungibleHandle<T>,180 spender: &T::CrossAccountId,181 from: &T::CrossAccountId,182 to: &T::CrossAccountId,183 amount: u128,184 nesting_budget: &dyn Budget,185 ) -> DispatchResultWithPostInfo {186 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;187 if allowance < amount {188 return Err(<CommonError<T>>::ApprovedValueTooLow.into());189 }190 Self::transfer(collection, from, to, amount, nesting_budget)191 }192 }193}1// #![doc = include_str!("../README.md")]2#![cfg_attr(not(feature = "std"), no_std)]34extern crate alloc;5use core::ops::Deref;67use frame_support::sp_runtime::DispatchResult;8use pallet_evm_coder_substrate::{WithRecorder, SubstrateRecorder};9pub use pallet::*;1011pub mod common;12pub mod erc;1314pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;1516const NATIVE_FUNGIBLE_COLLECTION_ID: up_data_structs::CollectionId =17 up_data_structs::CollectionId(0);1819/// Handle for native fungible collection20pub struct NativeFungibleHandle<T: Config>(SubstrateRecorder<T>);21impl<T: Config> NativeFungibleHandle<T> {22 /// Creates a handle23 pub fn new() -> NativeFungibleHandle<T> {24 Self(SubstrateRecorder::new(u64::MAX))25 }2627 /// Check if the collection is internal28 pub fn check_is_internal(&self) -> DispatchResult {29 Ok(())30 }31}3233impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {34 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {35 &self.036 }37 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {38 self.039 }40}4142impl<T: Config> Deref for NativeFungibleHandle<T> {43 type Target = SubstrateRecorder<T>;4445 fn deref(&self) -> &Self::Target {46 &self.047 }48}49#[frame_support::pallet]50pub mod pallet {51 use super::*;52 use alloc::string::String;53 use frame_support::{54 dispatch::PostDispatchInfo,55 ensure,56 pallet_prelude::{DispatchResultWithPostInfo, Pays},57 traits::{Currency, ExistenceRequirement, Get},58 };59 use pallet_balances::WeightInfo;60 use pallet_common::{erc::CrossAccountId, Error as CommonError, Pallet as PalletCommon};61 use pallet_structure::Pallet as PalletStructure;62 use sp_core::U256;63 use sp_runtime::DispatchError;64 use up_data_structs::{budget::Budget, mapping::TokenAddressMapping, TokenId};6566 #[pallet::config]67 pub trait Config:68 frame_system::Config69 + pallet_evm_coder_substrate::Config70 + pallet_common::Config71 + pallet_structure::Config72 {73 /// Currency from `pallet_balances`74 type Currency: frame_support::traits::Currency<75 Self::AccountId,76 Balance = Self::CurrencyBalance,77 >;78 /// Balance type of chain79 type CurrencyBalance: Into<U256> + TryFrom<U256> + PartialEq<u128> + From<u128> + Into<u128>;8081 /// Decimals of balance82 type Decimals: Get<u8>;83 /// Collection name84 type Name: Get<String>;85 /// Collection symbol86 type Symbol: Get<String>;8788 /// Weight information89 type WeightInfo: WeightInfo;90 }91 #[pallet::pallet]92 pub struct Pallet<T>(_);9394 impl<T: Config> Pallet<T> {95 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.96 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.97 ///98 /// - `collection`: Collection that contains the token.99 /// - `spender`: CrossAccountId who has the allowance rights.100 /// - `from`: The owner of the tokens who sets the allowance.101 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.102 fn check_allowed(103 spender: &T::CrossAccountId,104 from: &T::CrossAccountId,105 nesting_budget: &dyn Budget,106 ) -> Result<u128, DispatchError> {107 if let Some((collection_id, token_id)) =108 T::CrossTokenAddressMapping::address_to_token(from)109 {110 ensure!(111 <PalletStructure<T>>::check_indirectly_owned(112 spender.clone(),113 collection_id,114 token_id,115 None,116 nesting_budget117 )?,118 <CommonError<T>>::ApprovedValueTooLow,119 );120 } else if !spender.conv_eq(from) {121 return Ok(0);122 }123124 Ok(<T as Config>::Currency::free_balance(from.as_sub()).into())125 }126127 /// Transfers the specified amount of tokens. Will check that128 /// the transfer is allowed for the token.129 ///130 /// - `from`: Owner of tokens to transfer.131 /// - `to`: Recepient of transfered tokens.132 /// - `amount`: Amount of tokens to transfer.133 /// - `collection`: Collection that contains the token134 pub fn transfer(135 _collection: &NativeFungibleHandle<T>,136 from: &T::CrossAccountId,137 to: &T::CrossAccountId,138 amount: u128,139 nesting_budget: &dyn Budget,140 ) -> DispatchResultWithPostInfo {141 <PalletCommon<T>>::ensure_correct_receiver(to)?;142143 if from != to && amount != 0 {144 <T as Config>::Currency::transfer(145 from.as_sub(),146 to.as_sub(),147 amount.into(),148 ExistenceRequirement::KeepAlive,149 )?;150151 <PalletStructure<T>>::nest_if_sent_to_token(152 from.clone(),153 to,154 NATIVE_FUNGIBLE_COLLECTION_ID,155 TokenId::default(),156 nesting_budget,157 )?;158159 let balance_from: u128 =160 <T as Config>::Currency::free_balance(from.as_sub()).into();161 if balance_from == 0 {162 <PalletStructure<T>>::unnest_if_nested(163 from,164 NATIVE_FUNGIBLE_COLLECTION_ID,165 TokenId::default(),166 );167 }168 };169170 Ok(PostDispatchInfo {171 actual_weight: Some(<SelfWeightOf<T>>::transfer()),172 pays_fee: Pays::Yes,173 })174 }175176 pub fn transfer_from(177 collection: &NativeFungibleHandle<T>,178 spender: &T::CrossAccountId,179 from: &T::CrossAccountId,180 to: &T::CrossAccountId,181 amount: u128,182 nesting_budget: &dyn Budget,183 ) -> DispatchResultWithPostInfo {184 let allowance = Self::check_allowed(spender, from, nesting_budget)?;185 if allowance < amount {186 return Err(<CommonError<T>>::ApprovedValueTooLow.into());187 }188 Self::transfer(collection, from, to, amount, nesting_budget)189 }190 }191}pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -109,7 +109,8 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;
+ <Pallet<T>>::transfer(self, &caller, &to, amount, &budget)
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(true)
}
tests/src/eth/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -187,4 +187,80 @@
.call()).to.be.rejectedWith('SourceCollectionIsNotAllowedToNest');
});
});
+
+ describe('Fungible', () => {
+ async function createFungibleCollection(helper: EthUniqueHelper, owner: string, mode: 'ft' | 'native ft') {
+ if (mode === 'ft') {
+ const {collectionAddress} = await helper.eth.createFungibleCollection(owner, '', 18, '', '');
+ const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+ await contract.methods.mint(owner, 100n).send({from: owner});
+ return {collectionAddress, contract};
+ }
+
+ // native ft
+ const collectionAddress = helper.ethAddress.fromCollectionId(0);
+ const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+ return {collectionAddress, contract};
+ }
+
+ [
+ {mode: 'ft' as const},
+ {mode: 'native ft' as const},
+ ].map(testCase => {
+ itEth(`Allow nest [${testCase.mode}]`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
+ const {contract: ftContract} = await createFungibleCollection(helper, owner, testCase.mode);
+
+ const mintingTargetTokenIdResult = await targetContract.methods.mint(owner).send({from: owner});
+ const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+ const targetTokenAddress = helper.ethAddress.fromTokenId(targetCollectionId, targetTokenId);
+
+ await ftContract.methods.transfer(targetTokenAddress, 10n).send({from: owner});
+ expect(await ftContract.methods.balanceOf(targetTokenAddress).call({from: owner})).to.be.equal('10');
+ });
+ });
+
+ [
+ {mode: 'ft' as const},
+ {mode: 'native ft' as const},
+ ].map(testCase => {
+ itEth(`Allow partial/full unnest [${testCase.mode}]`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
+ const {contract: ftContract} = await createFungibleCollection(helper, owner, testCase.mode);
+
+ const mintingTargetTokenIdResult = await targetContract.methods.mint(owner).send({from: owner});
+ const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+ const targetTokenAddress = helper.ethAddress.fromTokenId(targetCollectionId, targetTokenId);
+
+ await ftContract.methods.transfer(targetTokenAddress, 10n).send({from: owner});
+
+ await ftContract.methods.transferFrom(targetTokenAddress, owner, 5n).send({from: owner});
+ expect(await ftContract.methods.balanceOf(targetTokenAddress).call({from: owner})).to.be.equal('5');
+
+ await ftContract.methods.transferFrom(targetTokenAddress, owner, 5n).send({from: owner});
+ expect(await ftContract.methods.balanceOf(targetTokenAddress).call({from: owner})).to.be.equal('0');
+ });
+ });
+
+ [
+ {mode: 'ft' as const},
+ {mode: 'native ft' as const},
+ ].map(testCase => {
+ itEth(`Disallow nest into collection without nesting permission [${testCase.mode}]`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
+ await targetContract.methods.setCollectionNesting(false).send({from: owner});
+
+ const {contract: ftContract} = await createFungibleCollection(helper, owner, testCase.mode);
+
+ const mintingTargetTokenIdResult = await targetContract.methods.mint(owner).send({from: owner});
+ const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+ const targetTokenAddress = helper.ethAddress.fromTokenId(targetCollectionId, targetTokenId);
+
+ await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ });
+ });
+ });
});
tests/src/nativeFungible.test.tsdiffbeforeafterboth--- a/tests/src/nativeFungible.test.ts
+++ b/tests/src/nativeFungible.test.ts
@@ -207,7 +207,7 @@
)).to.be.rejectedWith('BadOrigin');
});
- itSub.only('Nest into NFT token()', async ({helper}) => {
+ itSub('Nest into NFT token()', async ({helper}) => {
const nftCollection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
const targetToken = await nftCollection.mintToken(alice);
tests/src/sub/nesting/unnesting.negative.test.tsdiffbeforeafterboth--- a/tests/src/sub/nesting/unnesting.negative.test.ts
+++ b/tests/src/sub/nesting/unnesting.negative.test.ts
@@ -58,7 +58,7 @@
{mode: md.mode, restrictedMode: true},
{mode: md.mode, restrictedMode: false},
].map(testCase => {
- itSub.only(`Fungible: disallows a non-Owner to unnest someone else's token [${testCase.mode}${testCase.restrictedMode ? ' (Restricted nesting)' : ''}]`, async ({helper}) => {
+ itSub(`Fungible: disallows a non-Owner to unnest someone else's token [${testCase.mode}${testCase.restrictedMode ? ' (Restricted nesting)' : ''}]`, async ({helper}) => {
const collectionNFT = await helper.nft.mintCollection(alice);
const collectionFT = await (
testCase.mode === 'ft'