difftreelog
CORE-302 Implement methods for setup collection.
in: master
8 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -115,7 +115,7 @@
})
}
- pub fn new_with_recorder(id: CollectionId, recorder: Rc<SubstrateRecorder<T>>) -> Option<Self> {
+ pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {
<CollectionById<T>>::get(id).map(|collection| Self {
id,
collection,
@@ -153,6 +153,15 @@
pub fn set_sponsor(&mut self, sponsor: T::AccountId) {
self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);
}
+
+ pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> bool {
+ if self.collection.sponsorship.pending_sponsor() != Some(sender) {
+ return false;
+ };
+
+ self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());
+ true
+ }
}
impl<T: Config> Deref for CollectionHandle<T> {
type Target = Collection<T::AccountId>;
pallets/evm-collection/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/>.1617use core::marker::PhantomData;18use evm_coder::{abi::AbiWriter, execution::*, generate_stubgen, solidity_interface, types::*, ToLog};19use ethereum as _;20use pallet_common::{CollectionById, CollectionHandle};21use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};22use pallet_evm::{23 ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure,24 account::CrossAccountId, Pallet as PalletEvm,25};26use sp_core::H160;27use up_data_structs::{28 CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,29 MAX_COLLECTION_NAME_LENGTH, SponsorshipState,30};31use crate::{Config, Pallet};32use frame_support::traits::Get;3334use sp_std::{vec::Vec, rc::Rc};35use alloc::format;3637struct EvmCollection<T: Config>(SubstrateRecorder<T>);38impl<T: Config> WithRecorder<T> for EvmCollection<T> {39 fn recorder(&self) -> &SubstrateRecorder<T> {40 &self.041 }4243 fn into_recorder(self) -> SubstrateRecorder<T> {44 self.045 }46}4748#[derive(ToLog)]49pub enum CollectionEvent {50 CollectionCreated {51 #[indexed]52 owner: address,53 #[indexed]54 collection_id: address,55 },56}5758#[solidity_interface(name = "Collection")]59impl<T: Config> EvmCollection<T> {6061 fn create_721_collection(62 &self,63 caller: caller,64 name: string,65 description: string,66 token_prefix: string,67 ) -> Result<address> {68 let caller = T::CrossAccountId::from_eth(caller);69 let name = name70 .encode_utf16()71 .collect::<Vec<u16>>()72 .try_into()73 .map_err(|_| error_feild_too_long("name", MAX_COLLECTION_NAME_LENGTH))?;74 let description = description75 .encode_utf16()76 .collect::<Vec<u16>>()77 .try_into()78 .map_err(|_| error_feild_too_long("description", MAX_COLLECTION_DESCRIPTION_LENGTH))?;79 let token_prefix = token_prefix80 .into_bytes()81 .try_into()82 .map_err(|_| error_feild_too_long("token_prefix", MAX_TOKEN_PREFIX_LENGTH))?;8384 let data = CreateCollectionData {85 name,86 description,87 token_prefix,88 ..Default::default()89 };9091 let collection_id =92 <pallet_nonfungible::Pallet<T>>::init_collection(caller.as_sub().clone(), data)93 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;9495 let address = pallet_common::eth::collection_id_to_address(collection_id);96 <PalletEvm<T>>::deposit_log(97 CollectionEvent::CollectionCreated {98 owner: *caller.as_eth(),99 collection_id: address,100 }101 .to_log(address),102 );103 Ok(address)104 }105106 fn set_sponsor(107 &self,108 caller: caller,109 contract_address: address,110 sponsor: address,111 ) -> Result<void> {112 let collection_id =113 pallet_common::eth::map_eth_to_id(&contract_address).ok_or(Error::Revert("".into()))?;114 let mut collection =115 pallet_common::CollectionHandle::new_with_recorder(collection_id, self.0.clone())116 .ok_or(Error::Revert("".into()))?;117 118 let caller = T::CrossAccountId::from_eth(caller);119 collection.check_is_owner(&caller).map_err(|e| Error::Revert(format!("{:?}", e)))?;120121 let sponsor = T::CrossAccountId::from_eth(sponsor);122 collection.set_sponsor(sponsor.as_sub().clone());123 collection124 .save()125 .map_err(|e| Error::Revert(format!("{:?}", e)))126 }127128 // fn set_offchain_shema(shema: string) -> Result<void> {129 // Ok(())130 // }131132 // fn set_const_on_chain_schema(shema: string) -> Result<void> {133 // Ok(())134 // }135136 // fn set_variable_on_chain_schema(shema: string) -> Result<void> {137 // Ok(())138 // }139140 // fn set_limits(limits: string) -> Result<void> {141 // Ok(())142 // }143}144145fn error_feild_too_long(feild: &str, bound: u32) -> Error {146 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))147}148149pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);150impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {151 fn is_reserved(contract: &sp_core::H160) -> bool {152 contract == &T::ContractAddress::get()153 }154155 fn is_used(contract: &sp_core::H160) -> bool {156 contract == &T::ContractAddress::get()157 }158159 fn call(160 source: &sp_core::H160,161 target: &sp_core::H160,162 gas_left: u64,163 input: &[u8],164 value: sp_core::U256,165 ) -> Option<PrecompileResult> {166 // TODO: Extract to another OnMethodCall handler167 if target != &T::ContractAddress::get() {168 return None;169 }170171 let helpers = EvmCollection::<T>(SubstrateRecorder::<T>::new(gas_left));172 pallet_evm_coder_substrate::call(*source, helpers, value, input)173 }174175 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {176 (contract == &T::ContractAddress::get())177 .then(|| include_bytes!("./stubs/Collection.raw").to_vec())178 }179}180181generate_stubgen!(collection_impl, CollectionCall<()>, true);182generate_stubgen!(collection_iface, CollectionCall<()>, false);pallets/evm-collection/src/stubs/Collection.rawdiffbeforeafterbothbinary blob — no preview
pallets/evm-collection/src/stubs/Collection.soldiffbeforeafterboth--- a/pallets/evm-collection/src/stubs/Collection.sol
+++ b/pallets/evm-collection/src/stubs/Collection.sol
@@ -21,7 +21,7 @@
}
}
-// Selector: 6503bbc2
+// Selector: d32d5104
contract Collection is Dummy, ERC165 {
// Selector: create721Collection(string,string,string) 951c0151
function create721Collection(
@@ -38,10 +38,53 @@
}
// Selector: setSponsor(address,address) f01fba93
- function setSponsor(address contractAddress, address sponsor) public view {
+ function setSponsor(address collectionAddress, address sponsor)
+ public
+ view
+ {
require(false, stub_error);
- contractAddress;
+ collectionAddress;
sponsor;
dummy;
}
+
+ // Selector: confirmSponsorship(address) abc00001
+ function confirmSponsorship(address collectionAddress) public view {
+ require(false, stub_error);
+ collectionAddress;
+ dummy;
+ }
+
+ // Selector: setOffchainShema(address,string) d7dc2de3
+ function setOffchainShema(address collectionAddress, string memory shema)
+ public
+ view
+ {
+ require(false, stub_error);
+ collectionAddress;
+ shema;
+ dummy;
+ }
+
+ // Selector: setVariableOnChainSchema(address,string) 582691c3
+ function setVariableOnChainSchema(
+ address collectionAddress,
+ string memory variable
+ ) public view {
+ require(false, stub_error);
+ collectionAddress;
+ variable;
+ dummy;
+ }
+
+ // Selector: setConstOnChainSchema(address,string) 921456e7
+ function setConstOnChainSchema(
+ address collectionAddress,
+ string memory constOnChain
+ ) public view {
+ require(false, stub_error);
+ collectionAddress;
+ constOnChain;
+ dummy;
+ }
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -544,11 +544,9 @@
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
ensure!(
- target_collection.sponsorship.pending_sponsor() == Some(&sender),
+ target_collection.confirm_sponsorship(&sender),
Error::<T>::ConfirmUnsetSponsorFail
);
-
- target_collection.sponsorship = SponsorshipState::Confirmed(sender.clone());
<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(
collection_id,
tests/src/eth/api/Collection.soldiffbeforeafterboth--- a/tests/src/eth/api/Collection.sol
+++ b/tests/src/eth/api/Collection.sol
@@ -12,7 +12,7 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
-// Selector: 6503bbc2
+// Selector: d32d5104
interface Collection is Dummy, ERC165 {
// Selector: create721Collection(string,string,string) 951c0151
function create721Collection(
@@ -22,5 +22,27 @@
) external view returns (address);
// Selector: setSponsor(address,address) f01fba93
- function setSponsor(address contractAddress, address sponsor) external view;
+ function setSponsor(address collectionAddress, address sponsor)
+ external
+ view;
+
+ // Selector: confirmSponsorship(address) abc00001
+ function confirmSponsorship(address collectionAddress) external view;
+
+ // Selector: setOffchainShema(address,string) d7dc2de3
+ function setOffchainShema(address collectionAddress, string memory shema)
+ external
+ view;
+
+ // Selector: setVariableOnChainSchema(address,string) 582691c3
+ function setVariableOnChainSchema(
+ address collectionAddress,
+ string memory variable
+ ) external view;
+
+ // Selector: setConstOnChainSchema(address,string) 921456e7
+ function setConstOnChainSchema(
+ address collectionAddress,
+ string memory constOnChain
+ ) external view;
}
tests/src/eth/collectionAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionAbi.json
+++ b/tests/src/eth/collectionAbi.json
@@ -1,6 +1,19 @@
[
{
"inputs": [
+ {
+ "internalType": "address",
+ "name": "collectionAddress",
+ "type": "address"
+ }
+ ],
+ "name": "confirmSponsorship",
+ "outputs": [],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "string", "name": "name", "type": "string" },
{ "internalType": "string", "name": "description", "type": "string" },
{ "internalType": "string", "name": "tokenPrefix", "type": "string" }
@@ -14,7 +27,35 @@
"inputs": [
{
"internalType": "address",
- "name": "contractAddress",
+ "name": "collectionAddress",
+ "type": "address"
+ },
+ { "internalType": "string", "name": "constOnChain", "type": "string" }
+ ],
+ "name": "setConstOnChainSchema",
+ "outputs": [],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "collectionAddress",
+ "type": "address"
+ },
+ { "internalType": "string", "name": "shema", "type": "string" }
+ ],
+ "name": "setOffchainShema",
+ "outputs": [],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "collectionAddress",
"type": "address"
},
{ "internalType": "address", "name": "sponsor", "type": "address" }
@@ -26,6 +67,20 @@
},
{
"inputs": [
+ {
+ "internalType": "address",
+ "name": "collectionAddress",
+ "type": "address"
+ },
+ { "internalType": "string", "name": "variable", "type": "string" }
+ ],
+ "name": "setVariableOnChainSchema",
+ "outputs": [],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
],
"name": "supportsInterface",
tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -57,10 +57,47 @@
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))!;
+ let collection = (await getDetailedCollectionInfo(api, collectionId))!;
expect(collection.sponsorship.isUnconfirmed).to.be.true;
expect(collection.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ await expect(helper.methods.confirmSponsorship(collectionIdAddress).call()).to.be.rejectedWith('Caller is not set as sponsor');
+ const sponsorHelper = collectionHelper(web3, sponsor);
+ await sponsorHelper.methods.confirmSponsorship(collectionIdAddress).send();
+ collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collection.sponsorship.isConfirmed).to.be.true;
+ expect(collection.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ });
+
+ itWeb3('Set offchain shema', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const helper = collectionHelper(web3, owner);
+ let result = await helper.methods.create721Collection('Shema collection', '2', '2').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const shema = 'Some shema';
+ result = await helper.methods.setOffchainShema(collectionIdAddress, shema).send();
+ const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collection.offchainSchema.toHuman()).to.be.eq(shema);
});
-
-
+
+ itWeb3('Set variable on chain schema', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const helper = collectionHelper(web3, owner);
+ let result = await helper.methods.create721Collection('Variable collection', '3', '3').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const variable = 'Some variable';
+ result = await helper.methods.setVariableOnChainSchema(collectionIdAddress, variable).send();
+ const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collection.variableOnChainSchema.toHuman()).to.be.eq(variable);
+ });
+
+ itWeb3('Set const on chain schema', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const helper = collectionHelper(web3, owner);
+ let result = await helper.methods.create721Collection('Const collection', '4', '4').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const constShema = 'Some const';
+ result = await helper.methods.setConstOnChainSchema(collectionIdAddress, constShema).send();
+ const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collection.constOnChainSchema.toHuman()).to.be.eq(constShema);
+ });
});
\ No newline at end of file