git.delta.rocks / unique-network / refs/commits / d7a043d9818f

difftreelog

CORE-302 Implement setSponsor method.

Trubnikov Sergey2022-04-20parent: #281abcb.patch.diff
in: master

10 files changed

modifiedMakefilediffbeforeafterboth
--- a/Makefile
+++ b/Makefile
@@ -21,7 +21,7 @@
 TESTS_API=./tests/src/eth/api/
 
 .PHONY: regenerate_solidity
-regenerate_solidity: UniqueFungible.sol UniqueNFT.sol ContractHelpers.sol
+regenerate_solidity: UniqueFungible.sol UniqueNFT.sol ContractHelpers.sol Collection.sol
 
 UniqueFungible.sol:
 	PACKAGE=pallet-fungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
@@ -36,8 +36,8 @@
 	PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=$(CONTRACT_HELPERS_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
 
 Collection.sol:
-	PACKAGE=pallet-evm-collection NAME=eth::contract_helpers_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
-	PACKAGE=pallet-evm-collection NAME=eth::contract_helpers_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+	PACKAGE=pallet-evm-collection NAME=eth::collection_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+	PACKAGE=pallet-evm-collection NAME=eth::collection_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
 
 UniqueFungible: UniqueFungible.sol
 	INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw ./.maintain/scripts/compile_stub.sh
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -114,6 +114,15 @@
 			recorder: SubstrateRecorder::new(gas_limit),
 		})
 	}
+
+	pub fn new_with_recorder(id: CollectionId, recorder: Rc<SubstrateRecorder<T>>) -> Option<Self> {
+		<CollectionById<T>>::get(id).map(|collection| Self {
+			id,
+			collection,
+			recorder,
+		})
+	}
+
 	pub fn new(id: CollectionId) -> Option<Self> {
 		Self::new_with_gas_limit(id, u64::MAX)
 	}
@@ -140,6 +149,10 @@
 		<CollectionById<T>>::insert(self.id, self.collection);
 		Ok(())
 	}
+
+	pub fn set_sponsor(&mut self, sponsor: T::AccountId) {
+		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);
+	}
 }
 impl<T: Config> Deref for CollectionHandle<T> {
 	type Target = Collection<T::AccountId>;
modifiedpallets/evm-collection/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-collection/src/eth.rs
+++ b/pallets/evm-collection/src/eth.rs
@@ -17,7 +17,7 @@
 use core::marker::PhantomData;
 use evm_coder::{abi::AbiWriter, execution::*, generate_stubgen, solidity_interface, types::*, ToLog};
 use ethereum as _;
-use pallet_common::CollectionById;
+use pallet_common::{CollectionById, CollectionHandle};
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
 use pallet_evm::{
 	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure,
@@ -26,7 +26,7 @@
 use sp_core::H160;
 use up_data_structs::{
 	CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
-	MAX_COLLECTION_NAME_LENGTH,
+	MAX_COLLECTION_NAME_LENGTH, SponsorshipState,
 };
 use crate::{Config, Pallet};
 use frame_support::traits::Get;
@@ -57,6 +57,7 @@
 
 #[solidity_interface(name = "Collection")]
 impl<T: Config> EvmCollection<T> {
+
 	fn create_721_collection(
 		&self,
 		caller: caller,
@@ -102,15 +103,27 @@
 		Ok(address)
 	}
 
-	// fn set_sponsor(collection_id: address, sponsor: address) -> Result<void> {
-	// 	let collection_id =
-	// 		pallet_common::eth::map_eth_to_id(&collection_id).ok_or(Error::Revert("".into()))?;
-	// 	let mut collection = <CollectionById<T>>::get(collection_id).ok_or(Error::Revert("".into()))?;
-	// 	let sponsor = T::CrossAccountId::from_eth(sponsor);
-	// 	collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.as_sub().clone());
-	// 	<CollectionById<T>>::insert(collection_id, collection);
-	// 	Ok(())
-	// }
+	fn set_sponsor(
+		&self,
+		caller: caller,
+		contract_address: address,
+		sponsor: address,
+	) -> Result<void> {
+		let collection_id =
+			pallet_common::eth::map_eth_to_id(&contract_address).ok_or(Error::Revert("".into()))?;
+		let mut collection =
+			pallet_common::CollectionHandle::new_with_recorder(collection_id, self.0.clone())
+				.ok_or(Error::Revert("".into()))?;
+		
+		let caller = T::CrossAccountId::from_eth(caller);
+		collection.check_is_owner(&caller).map_err(|e| Error::Revert(format!("{:?}", e)))?;
+
+		let sponsor = T::CrossAccountId::from_eth(sponsor);
+		collection.set_sponsor(sponsor.as_sub().clone());
+		collection
+			.save()
+			.map_err(|e| Error::Revert(format!("{:?}", e)))
+	}
 
 	// fn set_offchain_shema(shema: string) -> Result<void> {
 	// 	Ok(())
modifiedpallets/evm-collection/src/stubs/Collection.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/evm-collection/src/stubs/Collection.soldiffbeforeafterboth
--- a/pallets/evm-collection/src/stubs/Collection.sol
+++ b/pallets/evm-collection/src/stubs/Collection.sol
@@ -21,130 +21,8 @@
 	}
 }
 
-// Selector: ee5467a8
+// Selector: 6503bbc2
 contract Collection is Dummy, ERC165 {
-	// Selector: contractOwner(address) 5152b14c
-	function contractOwner(address contractAddress)
-		public
-		view
-		returns (address)
-	{
-		require(false, stub_error);
-		contractAddress;
-		dummy;
-		return 0x0000000000000000000000000000000000000000;
-	}
-
-	// Selector: sponsoringEnabled(address) 6027dc61
-	function sponsoringEnabled(address contractAddress)
-		public
-		view
-		returns (bool)
-	{
-		require(false, stub_error);
-		contractAddress;
-		dummy;
-		return false;
-	}
-
-	// Deprecated
-	//
-	// Selector: toggleSponsoring(address,bool) fcac6d86
-	function toggleSponsoring(address contractAddress, bool enabled) public {
-		require(false, stub_error);
-		contractAddress;
-		enabled;
-		dummy = 0;
-	}
-
-	// Selector: setSponsoringMode(address,uint8) fde8a560
-	function setSponsoringMode(address contractAddress, uint8 mode) public {
-		require(false, stub_error);
-		contractAddress;
-		mode;
-		dummy = 0;
-	}
-
-	// Selector: sponsoringMode(address) b70c7267
-	function sponsoringMode(address contractAddress)
-		public
-		view
-		returns (uint8)
-	{
-		require(false, stub_error);
-		contractAddress;
-		dummy;
-		return 0;
-	}
-
-	// Selector: setSponsoringRateLimit(address,uint32) 77b6c908
-	function setSponsoringRateLimit(address contractAddress, uint32 rateLimit)
-		public
-	{
-		require(false, stub_error);
-		contractAddress;
-		rateLimit;
-		dummy = 0;
-	}
-
-	// Selector: getSponsoringRateLimit(address) 610cfabd
-	function getSponsoringRateLimit(address contractAddress)
-		public
-		view
-		returns (uint32)
-	{
-		require(false, stub_error);
-		contractAddress;
-		dummy;
-		return 0;
-	}
-
-	// Selector: allowed(address,address) 5c658165
-	function allowed(address contractAddress, address user)
-		public
-		view
-		returns (bool)
-	{
-		require(false, stub_error);
-		contractAddress;
-		user;
-		dummy;
-		return false;
-	}
-
-	// Selector: allowlistEnabled(address) c772ef6c
-	function allowlistEnabled(address contractAddress)
-		public
-		view
-		returns (bool)
-	{
-		require(false, stub_error);
-		contractAddress;
-		dummy;
-		return false;
-	}
-
-	// Selector: toggleAllowlist(address,bool) 36de20f5
-	function toggleAllowlist(address contractAddress, bool enabled) public {
-		require(false, stub_error);
-		contractAddress;
-		enabled;
-		dummy = 0;
-	}
-
-	// Selector: toggleAllowed(address,address,bool) 4706cc1c
-	function toggleAllowed(
-		address contractAddress,
-		address user,
-		bool allowed
-	) public {
-		require(false, stub_error);
-		contractAddress;
-		user;
-		allowed;
-		dummy = 0;
-	}
-
 	// Selector: create721Collection(string,string,string) 951c0151
 	function create721Collection(
 		string memory name,
@@ -158,4 +36,12 @@
 		dummy;
 		return 0x0000000000000000000000000000000000000000;
 	}
+
+	// Selector: setSponsor(address,address) f01fba93
+	function setSponsor(address contractAddress, address sponsor) public view {
+		require(false, stub_error);
+		contractAddress;
+		sponsor;
+		dummy;
+	}
 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -520,7 +520,7 @@
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.check_is_owner(&sender)?;
 
-			target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor.clone());
+			target_collection.set_sponsor(new_sponsor.clone());
 
 			<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(
 				collection_id,
modifiedtests/src/eth/api/Collection.soldiffbeforeafterboth
--- a/tests/src/eth/api/Collection.sol
+++ b/tests/src/eth/api/Collection.sol
@@ -12,70 +12,15 @@
 	function supportsInterface(bytes4 interfaceID) external view returns (bool);
 }
 
-// Selector: ee5467a8
+// Selector: 6503bbc2
 interface Collection is Dummy, ERC165 {
-	// Selector: contractOwner(address) 5152b14c
-	function contractOwner(address contractAddress)
-		external
-		view
-		returns (address);
-
-	// Selector: sponsoringEnabled(address) 6027dc61
-	function sponsoringEnabled(address contractAddress)
-		external
-		view
-		returns (bool);
-
-	// Deprecated
-	//
-	// Selector: toggleSponsoring(address,bool) fcac6d86
-	function toggleSponsoring(address contractAddress, bool enabled) external;
-
-	// Selector: setSponsoringMode(address,uint8) fde8a560
-	function setSponsoringMode(address contractAddress, uint8 mode) external;
-
-	// Selector: sponsoringMode(address) b70c7267
-	function sponsoringMode(address contractAddress)
-		external
-		view
-		returns (uint8);
-
-	// Selector: setSponsoringRateLimit(address,uint32) 77b6c908
-	function setSponsoringRateLimit(address contractAddress, uint32 rateLimit)
-		external;
-
-	// Selector: getSponsoringRateLimit(address) 610cfabd
-	function getSponsoringRateLimit(address contractAddress)
-		external
-		view
-		returns (uint32);
-
-	// Selector: allowed(address,address) 5c658165
-	function allowed(address contractAddress, address user)
-		external
-		view
-		returns (bool);
-
-	// Selector: allowlistEnabled(address) c772ef6c
-	function allowlistEnabled(address contractAddress)
-		external
-		view
-		returns (bool);
-
-	// Selector: toggleAllowlist(address,bool) 36de20f5
-	function toggleAllowlist(address contractAddress, bool enabled) external;
-
-	// Selector: toggleAllowed(address,address,bool) 4706cc1c
-	function toggleAllowed(
-		address contractAddress,
-		address user,
-		bool allowed
-	) external;
-
 	// Selector: create721Collection(string,string,string) 951c0151
 	function create721Collection(
 		string memory name,
 		string memory description,
 		string memory tokenPrefix
 	) external view returns (address);
+
+	// Selector: setSponsor(address,address) f01fba93
+	function setSponsor(address contractAddress, address sponsor) external view;
 }
modifiedtests/src/eth/collectionAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/collectionAbi.json
+++ b/tests/src/eth/collectionAbi.json
@@ -1,65 +1,12 @@
 [
   {
     "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      },
-      { "internalType": "address", "name": "user", "type": "address" }
-    ],
-    "name": "allowed",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      }
-    ],
-    "name": "allowlistEnabled",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      }
-    ],
-    "name": "contractOwner",
-    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [
       { "internalType": "string", "name": "name", "type": "string" },
       { "internalType": "string", "name": "description", "type": "string" },
       { "internalType": "string", "name": "tokenPrefix", "type": "string" }
     ],
     "name": "create721Collection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      }
-    ],
-    "name": "getSponsoringRateLimit",
-    "outputs": [{ "internalType": "uint32", "name": "", "type": "uint32" }],
     "stateMutability": "view",
     "type": "function"
   },
@@ -70,103 +17,20 @@
         "name": "contractAddress",
         "type": "address"
       },
-      { "internalType": "uint8", "name": "mode", "type": "uint8" }
-    ],
-    "name": "setSponsoringMode",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      },
-      { "internalType": "uint32", "name": "rateLimit", "type": "uint32" }
+      { "internalType": "address", "name": "sponsor", "type": "address" }
     ],
-    "name": "setSponsoringRateLimit",
+    "name": "setSponsor",
     "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      }
-    ],
-    "name": "sponsoringEnabled",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
   },
   {
     "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      }
-    ],
-    "name": "sponsoringMode",
-    "outputs": [{ "internalType": "uint8", "name": "", "type": "uint8" }],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [
       { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
     ],
     "name": "supportsInterface",
     "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      },
-      { "internalType": "address", "name": "user", "type": "address" },
-      { "internalType": "bool", "name": "allowed", "type": "bool" }
-    ],
-    "name": "toggleAllowed",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      },
-      { "internalType": "bool", "name": "enabled", "type": "bool" }
-    ],
-    "name": "toggleAllowlist",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      {
-        "internalType": "address",
-        "name": "contractAddress",
-        "type": "address"
-      },
-      { "internalType": "bool", "name": "enabled", "type": "bool" }
-    ],
-    "name": "toggleSponsoring",
-    "outputs": [],
-    "stateMutability": "nonpayable",
     "type": "function"
   }
 ]
modifiedtests/src/eth/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -14,32 +14,53 @@
 // 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 {ApiPromise} from '@polkadot/api';
+import {evmToAddress} from '@polkadot/util-crypto';
 import {expect} from 'chai';
 import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';
-import {collectionHelper, collectionIdFromAddress, contractHelpers, createEthAccountWithBalance, itWeb3} from './util/helpers';
+import {collectionHelper, collectionIdFromAddress, createEthAccountWithBalance, itWeb3, normalizeAddress} from './util/helpers';
 
+async function getCollectionAddressFromResult(api: ApiPromise, result: any) {
+  const collectionIdAddress = normalizeAddress(result.events[0].raw.topics[2]);
+  const collectionId = collectionIdFromAddress(collectionIdAddress);  
+  const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+  return {collectionIdAddress, collectionId, collection};
+}
+
 describe('Create collection from EVM', () => {
   itWeb3('Create collection', async ({api, web3}) => {
     const owner = await createEthAccountWithBalance(api, web3);
-    const helpers = collectionHelper(web3, owner);
+    const helper = collectionHelper(web3, owner);
     const collectionName = 'CollectionEVM';
     const description = 'Some description';
     const tokenPrefix = 'token prefix';
   
     const collectionCountBefore = await getCreatedCollectionCount(api);
-    const result = await helpers.methods
+    const result = await helper.methods
       .create721Collection(collectionName, description, tokenPrefix)
       .send();
     const collectionCountAfter = await getCreatedCollectionCount(api);
   
-    const collectionId = collectionIdFromAddress(result.events[0].raw.topics[2]);
+    const {collectionId, collection} = await getCollectionAddressFromResult(api, result);
     expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
     expect(collectionId).to.be.eq(collectionCountAfter);
-      
-    const collection = (await getDetailedCollectionInfo(api, collectionId))!;
     expect(collection.name.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(collectionName);
     expect(collection.description.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(description);
     expect(collection.tokenPrefix.toHuman()).to.be.eq(tokenPrefix);
     expect(collection.schemaVersion.type).to.be.eq('ImageURL');
   });
+  
+  itWeb3('Set sponsorship', async ({api, web3}) => {
+    const owner = await createEthAccountWithBalance(api, web3);
+    const helper = collectionHelper(web3, owner);
+    let result = await helper.methods.create721Collection('Sponsor collection', '1', '1').send();
+    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+    const sponsor = await createEthAccountWithBalance(api, web3);
+    result = await helper.methods.setSponsor(collectionIdAddress, sponsor).send();
+    const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+    expect(collection.sponsorship.isUnconfirmed).to.be.true;
+    expect(collection.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+  });
+
+
 });
\ No newline at end of file
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
before · tests/src/eth/util/helpers.ts
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// eslint-disable-next-line @typescript-eslint/triple-slash-reference18/// <reference path="helpers.d.ts" />1920import {ApiPromise} from '@polkadot/api';21import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';22import Web3 from 'web3';23import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';24import {IKeyringPair} from '@polkadot/types/types';25import {expect} from 'chai';26import {CrossAccountId, getGenericResult, UNIQUE} from '../../util/helpers';27import * as solc from 'solc';28import config from '../../config';29import privateKey from '../../substrate/privateKey';30import contractHelpersAbi from './contractHelpersAbi.json';31import collectionAbi from '../collectionAbi.json';32import getBalance from '../../substrate/get-balance';33import waitNewBlocks from '../../substrate/wait-new-blocks';3435export const GAS_ARGS = {gas: 2500000};3637export enum SponsoringMode {38  Disabled = 0,39  Allowlisted = 1,40  Generous = 2,41}4243let web3Connected = false;44export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {45  if (web3Connected) throw new Error('do not nest usingWeb3 calls');46  web3Connected = true;4748  const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);49  const web3 = new Web3(provider);5051  try {52    return await cb(web3);53  } finally {54    // provider.disconnect(3000, 'normal disconnect');55    provider.connection.close();56    web3Connected = false;57  }58}5960function encodeIntBE(v: number): number[] {61  if (v >= 0xffffffff || v < 0) throw new Error('id overflow');62  return [63    v >> 24,64    (v >> 16) & 0xff,65    (v >> 8) & 0xff,66    v & 0xff,67  ];68}6970export function collectionIdToAddress(collection: number): string {71  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,72    ...encodeIntBE(collection),73  ]);74  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));75}76export function collectionIdFromAddress(address: string): number {77  return Number('0x' + address.substring(address.length - 8));78}7980export function tokenIdToAddress(collection: number, token: number): string {81  const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,82    ...encodeIntBE(collection),83    ...encodeIntBE(token),84  ]);85  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));86}87export function tokenIdToCross(collection: number, token: number): CrossAccountId {88  return {89    Ethereum: tokenIdToAddress(collection, token),90  };9192export function createEthAccount(web3: Web3) {93  const account = web3.eth.accounts.create();94  web3.eth.accounts.wallet.add(account.privateKey);95  return account.address;96}9798export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {99  const alice = privateKey('//Alice');100  const account = createEthAccount(web3);101  await transferBalanceToEth(api, alice, account);102103  return account;104}105106export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {107  const tx = api.tx.balances.transfer(evmToAddress(target), amount);108  const events = await submitTransactionAsync(source, tx);109  const result = getGenericResult(events);110  expect(result.success).to.be.true;111}112113export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {114  let i: any = it;115  if (opts.only) i = i.only;116  else if (opts.skip) i = i.skip;117  i(name, async () => {118    await usingApi(async api => {119      await usingWeb3(async web3 => {120        await cb({api, web3});121      });122    });123  });124}125itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});126itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});127128export async function generateSubstrateEthPair(web3: Web3) {129  const account = web3.eth.accounts.create();130  evmToAddress(account.address);131}132133type NormalizedEvent = {134    address: string,135    event: string,136    args: { [key: string]: string }137};138139export function normalizeEvents(events: any): NormalizedEvent[] {140  const output = [];141  for (const key of Object.keys(events)) {142    if (key.match(/^[0-9]+$/)) {143      output.push(events[key]);144    } else if (Array.isArray(events[key])) {145      output.push(...events[key]);146    } else {147      output.push(events[key]);148    }149  }150  output.sort((a, b) => a.logIndex - b.logIndex);151  return output.map(({address, event, returnValues}) => {152    const args: { [key: string]: string } = {};153    for (const key of Object.keys(returnValues)) {154      if (!key.match(/^[0-9]+$/)) {155        args[key] = returnValues[key];156      }157    }158    return {159      address,160      event,161      args,162    };163  });164}165166export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {167  const out: any = [];168  contract.events.allEvents((_: any, event: any) => {169    out.push(event);170  });171  await action();172  return normalizeEvents(out);173}174175export function subToEthLowercase(eth: string): string {176  const bytes = addressToEvm(eth);177  return '0x' + Buffer.from(bytes).toString('hex');178}179180export function subToEth(eth: string): string {181  return Web3.utils.toChecksumAddress(subToEthLowercase(eth));182}183184export function compileContract(name: string, src: string) {185  const out = JSON.parse(solc.compile(JSON.stringify({186    language: 'Solidity',187    sources: {188      [`${name}.sol`]: {189        content: `190          // SPDX-License-Identifier: UNLICENSED191          pragma solidity ^0.8.6;192193          ${src}194        `,195      },196    },197    settings: {198      outputSelection: {199        '*': {200          '*': ['*'],201        },202      },203    },204  }))).contracts[`${name}.sol`][name];205206  return {207    abi: out.abi,208    object: '0x' + out.evm.bytecode.object,209  };210}211212export async function deployFlipper(web3: Web3, deployer: string) {213  const compiled = compileContract('Flipper', `214    contract Flipper {215      bool value = false;216      function flip() public {217        value = !value;218      }219      function getValue() public view returns (bool) {220        return value;221      }222    }223  `);224  const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {225    data: compiled.object,226    from: deployer,227    ...GAS_ARGS,228  });229  const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});230231  return flipper;232}233234export async function deployCollector(web3: Web3, deployer: string) {235  const compiled = compileContract('Collector', `236    contract Collector {237      uint256 collected;238      fallback() external payable {239        giveMoney();240      }241      function giveMoney() public payable {242        collected += msg.value;243      }244      function getCollected() public view returns (uint256) {245        return collected;246      }247      function getUnaccounted() public view returns (uint256) {248        return address(this).balance - collected;249      }250251      function withdraw(address payable target) public {252        target.transfer(collected);253        collected = 0;254      }255    }256  `);257  const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {258    data: compiled.object,259    from: deployer,260    ...GAS_ARGS,261  });262  const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});263264  return collector;265}266267/** 268 * pallet evm_contract_helpers269 * @param web3 270 * @param caller - eth address271 * @returns 272 */273export function contractHelpers(web3: Web3, caller: string) {274  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});275}276277/** 278 * pallet evm_collection279 * @param web3 280 * @param caller - eth address281 * @returns 282 */283export function collectionHelper(web3: Web3, caller: string) {284  return new web3.eth.Contract(collectionAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});285}286287/**288 * Execute ethereum method call using substrate account289 * @param to target contract290 * @param mkTx - closure, receiving `contract.methods`, and returning method call,291 * to be used as following (assuming `to` = erc20 contract):292 * `m => m.transfer(to, amount)`293 *294 * # Example295 * ```ts296 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));297 * ```298 */299export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {300  const tx = api.tx.evm.call(301    subToEth(from.address),302    to.options.address,303    mkTx(to.methods).encodeABI(),304    value,305    GAS_ARGS.gas,306    await web3.eth.getGasPrice(),307    null,308    null,309    [],310  );311  const events = await submitTransactionAsync(from, tx);312  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;313}314315export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {316  return (await getBalance(api, [evmToAddress(address)]))[0];317}318319/**320 * Measure how much gas given closure consumes321 *322 * @param user which user balance will be checked323 */324export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {325  const before = await ethBalanceViaSub(api, user);326327  await call();328329  // In dev mode, the transaction might not finish processing in time330  await waitNewBlocks(api, 1);331  const after = await ethBalanceViaSub(api, user);332333  // Can't use .to.be.less, because chai doesn't supports bigint334  expect(after < before).to.be.true;335336  return before - after;337}338339type ElementOf<A> = A extends readonly (infer T)[] ? T : never;340// I want a fancier api, not a memory efficiency341export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {342  if(args.length === 0) {343    yield internalRest as any;344    return;345  }346  for(const value of args[0]) {347    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;348  }349}
after · tests/src/eth/util/helpers.ts
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// eslint-disable-next-line @typescript-eslint/triple-slash-reference18/// <reference path="helpers.d.ts" />1920import {ApiPromise} from '@polkadot/api';21import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';22import Web3 from 'web3';23import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';24import {IKeyringPair} from '@polkadot/types/types';25import {expect} from 'chai';26import {CrossAccountId, getGenericResult, UNIQUE} from '../../util/helpers';27import * as solc from 'solc';28import config from '../../config';29import privateKey from '../../substrate/privateKey';30import contractHelpersAbi from './contractHelpersAbi.json';31import collectionAbi from '../collectionAbi.json';32import getBalance from '../../substrate/get-balance';33import waitNewBlocks from '../../substrate/wait-new-blocks';3435export const GAS_ARGS = {gas: 2500000};3637export enum SponsoringMode {38  Disabled = 0,39  Allowlisted = 1,40  Generous = 2,41}4243let web3Connected = false;44export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {45  if (web3Connected) throw new Error('do not nest usingWeb3 calls');46  web3Connected = true;4748  const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);49  const web3 = new Web3(provider);5051  try {52    return await cb(web3);53  } finally {54    // provider.disconnect(3000, 'normal disconnect');55    provider.connection.close();56    web3Connected = false;57  }58}5960function encodeIntBE(v: number): number[] {61  if (v >= 0xffffffff || v < 0) throw new Error('id overflow');62  return [63    v >> 24,64    (v >> 16) & 0xff,65    (v >> 8) & 0xff,66    v & 0xff,67  ];68}6970export function collectionIdToAddress(collection: number): string {71  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,72    ...encodeIntBE(collection),73  ]);74  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));75}76export function collectionIdFromAddress(address: string): number {77  if (!address.startsWith('0x'))78    throw 'address not starts with "0x"';79  if (address.length > 42)80    throw 'address length is more than 20 bytes';81    return Number('0x' + address.substring(address.length - 8));82}83  84export function normalizeAddress(address: string): string {85  return '0x' + address.substring(address.length - 40);86}8788export function tokenIdToAddress(collection: number, token: number): string {89  const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,90    ...encodeIntBE(collection),91    ...encodeIntBE(token),92  ]);93  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));94}95export function tokenIdToCross(collection: number, token: number): CrossAccountId {96  return {97    Ethereum: tokenIdToAddress(collection, token),98  };99100export function createEthAccount(web3: Web3) {101  const account = web3.eth.accounts.create();102  web3.eth.accounts.wallet.add(account.privateKey);103  return account.address;104}105106export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {107  const alice = privateKey('//Alice');108  const account = createEthAccount(web3);109  await transferBalanceToEth(api, alice, account);110111  return account;112}113114export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {115  const tx = api.tx.balances.transfer(evmToAddress(target), amount);116  const events = await submitTransactionAsync(source, tx);117  const result = getGenericResult(events);118  expect(result.success).to.be.true;119}120121export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {122  let i: any = it;123  if (opts.only) i = i.only;124  else if (opts.skip) i = i.skip;125  i(name, async () => {126    await usingApi(async api => {127      await usingWeb3(async web3 => {128        await cb({api, web3});129      });130    });131  });132}133itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});134itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});135136export async function generateSubstrateEthPair(web3: Web3) {137  const account = web3.eth.accounts.create();138  evmToAddress(account.address);139}140141type NormalizedEvent = {142    address: string,143    event: string,144    args: { [key: string]: string }145};146147export function normalizeEvents(events: any): NormalizedEvent[] {148  const output = [];149  for (const key of Object.keys(events)) {150    if (key.match(/^[0-9]+$/)) {151      output.push(events[key]);152    } else if (Array.isArray(events[key])) {153      output.push(...events[key]);154    } else {155      output.push(events[key]);156    }157  }158  output.sort((a, b) => a.logIndex - b.logIndex);159  return output.map(({address, event, returnValues}) => {160    const args: { [key: string]: string } = {};161    for (const key of Object.keys(returnValues)) {162      if (!key.match(/^[0-9]+$/)) {163        args[key] = returnValues[key];164      }165    }166    return {167      address,168      event,169      args,170    };171  });172}173174export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {175  const out: any = [];176  contract.events.allEvents((_: any, event: any) => {177    out.push(event);178  });179  await action();180  return normalizeEvents(out);181}182183export function subToEthLowercase(eth: string): string {184  const bytes = addressToEvm(eth);185  return '0x' + Buffer.from(bytes).toString('hex');186}187188export function subToEth(eth: string): string {189  return Web3.utils.toChecksumAddress(subToEthLowercase(eth));190}191192export function compileContract(name: string, src: string) {193  const out = JSON.parse(solc.compile(JSON.stringify({194    language: 'Solidity',195    sources: {196      [`${name}.sol`]: {197        content: `198          // SPDX-License-Identifier: UNLICENSED199          pragma solidity ^0.8.6;200201          ${src}202        `,203      },204    },205    settings: {206      outputSelection: {207        '*': {208          '*': ['*'],209        },210      },211    },212  }))).contracts[`${name}.sol`][name];213214  return {215    abi: out.abi,216    object: '0x' + out.evm.bytecode.object,217  };218}219220export async function deployFlipper(web3: Web3, deployer: string) {221  const compiled = compileContract('Flipper', `222    contract Flipper {223      bool value = false;224      function flip() public {225        value = !value;226      }227      function getValue() public view returns (bool) {228        return value;229      }230    }231  `);232  const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {233    data: compiled.object,234    from: deployer,235    ...GAS_ARGS,236  });237  const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});238239  return flipper;240}241242export async function deployCollector(web3: Web3, deployer: string) {243  const compiled = compileContract('Collector', `244    contract Collector {245      uint256 collected;246      fallback() external payable {247        giveMoney();248      }249      function giveMoney() public payable {250        collected += msg.value;251      }252      function getCollected() public view returns (uint256) {253        return collected;254      }255      function getUnaccounted() public view returns (uint256) {256        return address(this).balance - collected;257      }258259      function withdraw(address payable target) public {260        target.transfer(collected);261        collected = 0;262      }263    }264  `);265  const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {266    data: compiled.object,267    from: deployer,268    ...GAS_ARGS,269  });270  const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});271272  return collector;273}274275/** 276 * pallet evm_contract_helpers277 * @param web3 278 * @param caller - eth address279 * @returns 280 */281export function contractHelpers(web3: Web3, caller: string) {282  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});283}284285/** 286 * pallet evm_collection287 * @param web3 288 * @param caller - eth address289 * @returns 290 */291export function collectionHelper(web3: Web3, caller: string) {292  return new web3.eth.Contract(collectionAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});293}294295/**296 * Execute ethereum method call using substrate account297 * @param to target contract298 * @param mkTx - closure, receiving `contract.methods`, and returning method call,299 * to be used as following (assuming `to` = erc20 contract):300 * `m => m.transfer(to, amount)`301 *302 * # Example303 * ```ts304 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));305 * ```306 */307export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {308  const tx = api.tx.evm.call(309    subToEth(from.address),310    to.options.address,311    mkTx(to.methods).encodeABI(),312    value,313    GAS_ARGS.gas,314    await web3.eth.getGasPrice(),315    null,316    null,317    [],318  );319  const events = await submitTransactionAsync(from, tx);320  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;321}322323export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {324  return (await getBalance(api, [evmToAddress(address)]))[0];325}326327/**328 * Measure how much gas given closure consumes329 *330 * @param user which user balance will be checked331 */332export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {333  const before = await ethBalanceViaSub(api, user);334335  await call();336337  // In dev mode, the transaction might not finish processing in time338  await waitNewBlocks(api, 1);339  const after = await ethBalanceViaSub(api, user);340341  // Can't use .to.be.less, because chai doesn't supports bigint342  expect(after < before).to.be.true;343344  return before - after;345}346347type ElementOf<A> = A extends readonly (infer T)[] ? T : never;348// I want a fancier api, not a memory efficiency349export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {350  if(args.length === 0) {351    yield internalRest as any;352    return;353  }354  for(const value of args[0]) {355    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;356  }357}