git.delta.rocks / unique-network / refs/commits / 310b60e05536

difftreelog

CORE-320 Sponsorship for evm minting

Trubnikov Sergey2022-03-22parent: #7e99203.patch.diff
in: master

2 files changed

modifiedpallets/unique/src/eth/sponsoring.rsdiffbeforeafterboth
before · pallets/unique/src/eth/sponsoring.rs
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//! Implements EVM sponsoring logic via OnChargeEVMTransaction1819use crate::{Config, sponsorship::*};20use evm_coder::{Call, abi::AbiReader};21use pallet_common::{CollectionHandle, eth::map_eth_to_id};22use sp_core::H160;23use sp_std::prelude::*;24use up_sponsorship::SponsorshipHandler;25use core::marker::PhantomData;26use core::convert::TryInto;27use up_data_structs::TokenId;28use pallet_evm::account::CrossAccountId;2930use pallet_nonfungible::erc::{UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721Call};31use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};3233pub struct UniqueEthSponsorshipHandler<T: Config>(PhantomData<*const T>);34impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)> for UniqueEthSponsorshipHandler<T> {35	fn get_sponsor(who: &T::CrossAccountId, call: &(H160, Vec<u8>)) -> Option<T::CrossAccountId> {36		let collection_id = map_eth_to_id(&call.0)?;37		let collection = <CollectionHandle<T>>::new(collection_id)?;38		let sponsor = collection.sponsorship.sponsor()?.clone();39		let (method_id, mut reader) = AbiReader::new_call(&call.1).ok()?;40		Some(T::CrossAccountId::from_sub(match &collection.mode {41			crate::CollectionMode::NFT => {42				let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;43				match call {44					UniqueNFTCall::ERC721UniqueExtensions(45						ERC721UniqueExtensionsCall::Transfer { token_id, .. },46					) => {47						let token_id: TokenId = token_id.try_into().ok()?;48						withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)49					}50					UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {51						let token_id: TokenId = token_id.try_into().ok()?;52						let from = T::CrossAccountId::from_eth(from);53						withdraw_transfer::<T>(&collection, &from, &token_id).map(|()| sponsor)54					}55					UniqueNFTCall::ERC721(ERC721Call::Approve { token_id, .. }) => {56						let token_id: TokenId = token_id.try_into().ok()?;57						withdraw_approve::<T>(&collection, who.as_sub(), &token_id)58							.map(|()| sponsor)59					}60					_ => None,61				}62			}63			crate::CollectionMode::Fungible(_) => {64				let call = <UniqueFungibleCall<T>>::parse(method_id, &mut reader).ok()??;65				#[allow(clippy::single_match)]66				match call {67					UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {68						withdraw_transfer::<T>(&collection, who, &TokenId::default())69							.map(|()| sponsor)70					}71					UniqueFungibleCall::ERC20(ERC20Call::TransferFrom { from, .. }) => {72						let from = T::CrossAccountId::from_eth(from);73						withdraw_transfer::<T>(&collection, &from, &TokenId::default())74							.map(|()| sponsor)75					}76					UniqueFungibleCall::ERC20(ERC20Call::Approve { .. }) => {77						withdraw_approve::<T>(&collection, who.as_sub(), &TokenId::default())78							.map(|()| sponsor)79					}80					_ => None,81				}82			}83			_ => None,84		}?))85	}86}
after · pallets/unique/src/eth/sponsoring.rs
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//! Implements EVM sponsoring logic via OnChargeEVMTransaction1819use crate::{Config, sponsorship::*};20use evm_coder::{Call, abi::AbiReader};21use pallet_common::{CollectionHandle, eth::map_eth_to_id};22use sp_core::H160;23use sp_std::prelude::*;24use up_sponsorship::SponsorshipHandler;25use core::marker::PhantomData;26use core::convert::TryInto;27use up_data_structs::TokenId;28use pallet_evm::account::CrossAccountId;2930use pallet_nonfungible::erc::{UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721Call};31use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};32use up_data_structs::{CreateItemData, CreateNftData};3334pub struct UniqueEthSponsorshipHandler<T: Config>(PhantomData<*const T>);35impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)> for UniqueEthSponsorshipHandler<T> {36	fn get_sponsor(who: &T::CrossAccountId, call: &(H160, Vec<u8>)) -> Option<T::CrossAccountId> {37		let collection_id = map_eth_to_id(&call.0)?;38		let collection = <CollectionHandle<T>>::new(collection_id)?;39		let sponsor = collection.sponsorship.sponsor()?.clone();40		let (method_id, mut reader) = AbiReader::new_call(&call.1).ok()?;41		Some(T::CrossAccountId::from_sub(match &collection.mode {42			crate::CollectionMode::NFT => {43				let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;44				match call {45					UniqueNFTCall::ERC721UniqueExtensions(46						ERC721UniqueExtensionsCall::Transfer { token_id, .. },47					) => {48						let token_id: TokenId = token_id.try_into().ok()?;49						withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)50					}51					UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {52						let token_id: TokenId = token_id.try_into().ok()?;53						let from = T::CrossAccountId::from_eth(from);54						withdraw_transfer::<T>(&collection, &from, &token_id).map(|()| sponsor)55					}56					UniqueNFTCall::ERC721(ERC721Call::Approve { token_id, .. }) => {57						let token_id: TokenId = token_id.try_into().ok()?;58						withdraw_approve::<T>(&collection, who.as_sub(), &token_id)59							.map(|()| sponsor)60					}61					UniqueNFTCall::ERC721Mintable(call) => match call {62						pallet_nonfungible::erc::ERC721MintableCall::Mint { .. } |63						pallet_nonfungible::erc::ERC721MintableCall::MintWithTokenUri { .. } => {64							withdraw_create_item(65								&collection, 66								who.as_sub(), 67								&CreateItemData::NFT(CreateNftData::default()))68							.map(|()| sponsor)69						}70						_ => None,71    				}72					_ => None,73				}74			}75			crate::CollectionMode::Fungible(_) => {76				let call = <UniqueFungibleCall<T>>::parse(method_id, &mut reader).ok()??;77				#[allow(clippy::single_match)]78				match call {79					UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {80						withdraw_transfer::<T>(&collection, who, &TokenId::default())81							.map(|()| sponsor)82					}83					UniqueFungibleCall::ERC20(ERC20Call::TransferFrom { from, .. }) => {84						let from = T::CrossAccountId::from_eth(from);85						withdraw_transfer::<T>(&collection, &from, &TokenId::default())86							.map(|()| sponsor)87					}88					UniqueFungibleCall::ERC20(ERC20Call::Approve { .. }) => {89						withdraw_approve::<T>(&collection, who.as_sub(), &TokenId::default())90							.map(|()| sponsor)91					}92					_ => None,93				}94			}95			_ => None,96		}?))97	}98}
modifiedtests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -30,16 +30,14 @@
 } from './util/helpers';
 import {
   createCollectionExpectSuccess,
-  createItemExpectSuccess,
   getCreateCollectionResult,
-  normalizeAccountId,
-  toSubstrateAddress,
 } from '../util/helpers';
 import nonFungibleAbi from './nonFungibleAbi.json';
 import {
   submitTransactionAsync,
 } from '../substrate/substrate-api';
-import { evmToAddress } from '@polkadot/util-crypto';
+import getBalance from '../substrate/get-balance';
+import {alicesPublicKey} from '../accounts';
 
 describe('Sponsoring EVM contracts', () => {
   itWeb3('Sponsoring can be set by the address that has deployed the contract', async ({api, web3}) => {
@@ -214,18 +212,10 @@
     const helpers = contractHelpers(web3, owner);
     expect(await helpers.methods.getSponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');
   });
-
 
-
-
-
-
-
-  
   itWeb3.only('Sponsoring evm address from substrate collection', async ({api, web3}) => {
     const owner = privateKey('//Alice');
     const userEth = createEthAccount(web3);
-    const userSub = evmToAddress(userEth);
     const collectionId = await createCollectionExpectSuccess();
 
     {
@@ -243,31 +233,15 @@
 
     const address = collectionIdToAddress(collectionId);
     const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: userEth, ...GAS_ARGS});
-    const receiver = createEthAccount(web3);
 
     { // This part should fail, because user not in access list and user have no money
-      // const nextTokenId = await contract.methods.nextTokenId().call();
-      // expect(nextTokenId).to.be.equal('1');
-      // const result = await contract.methods.mintWithTokenURI(
-      //   receiver,
-      //   nextTokenId,
-      //   'Test URI',
-      // ).send({from: userEth});
-      // const events = normalizeEvents(result.events);
-
-      // expect(events).to.be.deep.equal([
-      //   {
-      //     address,
-      //     event: 'Transfer',
-      //     args: {
-      //       from: '0x0000000000000000000000000000000000000000',
-      //       to: receiver,
-      //       tokenId: nextTokenId,
-      //     },
-      //   },
-      // ]);
-
-      // expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+      const nextTokenId = await contract.methods.nextTokenId().call();
+      expect(nextTokenId).to.be.equal('1');
+      await expect(contract.methods.mintWithTokenURI(
+        userEth,
+        nextTokenId,
+        'Test URI',
+      ).call({from: userEth})).to.be.rejectedWith(/PublicMintingNotAllowed/);
     }
 
     {
@@ -289,11 +263,13 @@
       expect(result.success).to.be.true;
     }
 
+    const [alicesBalanceBefore] = await getBalance(api, [alicesPublicKey]);
+
     {
       const nextTokenId = await contract.methods.nextTokenId().call();
       expect(nextTokenId).to.be.equal('1');
       const result = await contract.methods.mintWithTokenURI(
-        receiver,
+        userEth,
         nextTokenId,
         'Test URI',
       ).send({from: userEth});
@@ -305,7 +281,7 @@
           event: 'Transfer',
           args: {
             from: '0x0000000000000000000000000000000000000000',
-            to: receiver,
+            to: userEth,
             tokenId: nextTokenId,
           },
         },
@@ -314,5 +290,7 @@
       expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
     }
 
+    const [alicesBalanceAfter] = await getBalance(api, [alicesPublicKey]);
+    expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;
   });
 });