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

difftreelog

path: Add some methods for manipulate collection sponsor via eth.

Trubnikov Sergey2022-08-24parent: #8684bc0.patch.diff
in: master

8 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
26use sp_std::vec::Vec;26use sp_std::vec::Vec;
27use up_data_structs::{27use up_data_structs::{
28 AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,28 AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,
29 SponsoringRateLimit,29 SponsoringRateLimit, SponsorshipState,
30};30};
31use alloc::format;31use alloc::format;
3232
63#[solidity_interface(name = Collection)]63#[solidity_interface(name = Collection)]
64impl<T: Config> CollectionHandle<T>64impl<T: Config> CollectionHandle<T>
65where65where
66 T::AccountId: From<[u8; 32]>,66 T::AccountId: From<[u8; 32]> + AsRef<[u8]>,
67{67{
68 /// Set collection property.68 /// Set collection property.
69 ///69 ///
128 save(self)128 save(self)
129 }129 }
130
131 /// Set the substrate sponsor of the collection.
132 ///
133 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
134 ///
135 /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
136 fn set_collection_sponsor_substrate(&mut self, caller: caller, sponsor: uint256) -> Result<void> {
137 check_is_owner_or_admin(caller, self)?;
138
139 let sponsor = convert_uint256_to_cross_account::<T>(sponsor);
140 self.set_sponsor(sponsor.as_sub().clone())
141 .map_err(dispatch_to_evm::<T>)?;
142 save(self)
143 }
144
145 // /// Whether there is a pending sponsor.
146 fn has_collection_pending_sponsor(&self) -> Result<bool> {
147 Ok(matches!(self.collection.sponsorship, SponsorshipState::Unconfirmed(_)))
148 }
130149
131 /// Collection sponsorship confirmation.150 /// Collection sponsorship confirmation.
132 ///151 ///
142 save(self)161 save(self)
143 }162 }
163
164 /// Remove collection sponsor.
165 fn remove_collection_sponsor(&mut self, caller: caller) -> Result<void> {
166 check_is_owner_or_admin(caller, self)?;
167 self.remove_sponsor().map_err(dispatch_to_evm::<T>)?;
168 save(self)
169 }
170
171 /// Get current sponsor.
172 ///
173 /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
174 fn get_collection_sponsor(&self) -> Result<(address, uint256)> {
175 let sponsor = match self.collection.sponsorship {
176 SponsorshipState::Disabled | SponsorshipState::Unconfirmed(_) => return Ok(Default::default()),
177 SponsorshipState::Confirmed(ref sponsor) => sponsor,
178 };
179 let sponsor = T::CrossAccountId::from_sub(sponsor.clone());
180 let sponsor_sub = convert_cross_account_to_uint256::<T>(&sponsor)?;
181 Ok((*sponsor.as_eth(), sponsor_sub))
182 }
144183
145 /// Set limits for the collection.184 /// Set limits for the collection.
146 /// @dev Throws error if limit not found.185 /// @dev Throws error if limit not found.
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
59 uint256::from_big_endian(slice)59 uint256::from_big_endian(slice)
60}60}
61
62/// Convert `uint256` to `CrossAccountId`.
63pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId
64where
65 T::AccountId: From<[u8; 32]>,
66{
67 let mut new_admin_arr: [u8; 32] = Default::default();
68 from.to_big_endian(&mut new_admin_arr);
69 let account_id = T::AccountId::from(new_admin_arr);
70 T::CrossAccountId::from_sub(account_id)
71}
6172
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
231 Ok(true)231 Ok(true)
232 }232 }
233
234 /// Remove collection sponsor.
235 pub fn remove_sponsor(&mut self) -> DispatchResult {
236 self.collection.sponsorship = SponsorshipState::Disabled;
237 Ok(())
238 }
233239
234 /// Checks that the collection was created with, and must be operated upon through **Unique API**.240 /// Checks that the collection was created with, and must be operated upon through **Unique API**.
235 /// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.241 /// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.
732738
733 /// Get the effective limits for the collection.739 /// Get the effective limits for the collection.
734 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {740 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {
735 let collection = <CollectionById<T>>::get(collection);741 let collection = <CollectionById<T>>::get(collection)?;
736 if collection.is_none() {
737 return None;
738 }
739
740 let collection = collection.unwrap();
741 let limits = collection.limits;742 let limits = collection.limits;
742 let effective_limits = CollectionLimits {743 let effective_limits = CollectionLimits {
743 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),744 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
154 Collection(common_mut, CollectionHandle<T>),154 Collection(common_mut, CollectionHandle<T>),
155 )155 )
156)]156)]
157impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> {}157impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8]> {}
158158
159generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);159generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);
160generate_stubgen!(gen_iface, UniqueFungibleCall<()>, false);160generate_stubgen!(gen_iface, UniqueFungibleCall<()>, false);
161161
162impl<T: Config> CommonEvmHandler for FungibleHandle<T>162impl<T: Config> CommonEvmHandler for FungibleHandle<T>
163where163where
164 T::AccountId: From<[u8; 32]>,164 T::AccountId: From<[u8; 32]> + AsRef<[u8]>,
165{165{
166 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");166 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");
167167
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
740 TokenProperties,740 TokenProperties,
741 )741 )
742)]742)]
743impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}743impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8]> {}
744744
745// Not a tests, but code generators745// Not a tests, but code generators
746generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);746generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);
747generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);747generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);
748748
749impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>749impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>
750where750where
751 T::AccountId: From<[u8; 32]>,751 T::AccountId: From<[u8; 32]> + AsRef<[u8]>,
752{752{
753 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");753 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");
754754
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
789 TokenProperties,789 TokenProperties,
790 )790 )
791)]791)]
792impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> {}792impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8]> {}
793793
794// Not a tests, but code generators794// Not a tests, but code generators
795generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);795generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);
796generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);796generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);
797797
798impl<T: Config> CommonEvmHandler for RefungibleHandle<T>798impl<T: Config> CommonEvmHandler for RefungibleHandle<T>
799where799where
800 T::AccountId: From<[u8; 32]>,800 T::AccountId: From<[u8; 32]> + AsRef<[u8]>,
801{801{
802 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");802 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");
803 fn call(803 fn call(
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
124 + pallet_fungible::Config124 + pallet_fungible::Config
125 + pallet_nonfungible::Config125 + pallet_nonfungible::Config
126 + pallet_refungible::Config,126 + pallet_refungible::Config,
127 T::AccountId: From<[u8; 32]>,127 T::AccountId: From<[u8; 32]> + AsRef<[u8]>,
128{128{
129 fn is_reserved(target: &H160) -> bool {129 fn is_reserved(target: &H160) -> bool {
130 map_eth_to_id(target).is_some()130 map_eth_to_id(target).is_some()
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
1import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';1import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';
2import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub} from './util/helpers';2import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub, subToEth} from './util/helpers';
3import nonFungibleAbi from './nonFungibleAbi.json';3import nonFungibleAbi from './nonFungibleAbi.json';
4import {expect} from 'chai';4import {expect} from 'chai';
5import {evmToAddress} from '@polkadot/util-crypto';5import {evmToAddress} from '@polkadot/util-crypto';
6import {submitTransactionAsync} from '../substrate/substrate-api';
7import getBalance from '../substrate/get-balance';
68
7describe('evm collection sponsoring', () => {9describe('evm collection sponsoring', () => {
8 itWeb3('sponsors mint transactions', async ({web3, privateKeyWrapper}) => {10 itWeb3('sponsors mint transactions', async ({web3, privateKeyWrapper}) => {
38 ]);40 ]);
39 });41 });
42
43 itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {
44 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
45 const collectionHelpers = evmCollectionHelpers(web3, owner);
46 let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
47 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
48 const sponsor = privateKeyWrapper('//Alice');
49 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
50
51 expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
52 result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
53 expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
54
55 const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
56 await submitTransactionAsync(sponsor, confirmTx);
57 expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
58
59 const sponsorTuple = await collectionEvm.methods.getCollectionSponsor().call({from: owner});
60 expect(sponsorTuple.field_0).to.be.eq(subToEth(sponsor.address));
61 });
62
63 itWeb3('Remove sponsor', async ({api, web3, privateKeyWrapper}) => {
64 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
65 const collectionHelpers = evmCollectionHelpers(web3, owner);
66 let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
67 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
68 const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
69 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
70
71 expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
72 result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
73 expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
74
75 await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
76 expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
77
78 await collectionEvm.methods.removeCollectionSponsor().send({from: owner});
79
80 const sponsorTuple = await collectionEvm.methods.getCollectionSponsor().call({from: owner});
81 expect(sponsorTuple.field_0).to.be.eq('0x0000000000000000000000000000000000000000');
82 });
4083
41 itWeb3('Sponsoring collection from evm address via access list', async ({api, web3, privateKeyWrapper}) => {84 itWeb3('Sponsoring collection from evm address via access list', async ({api, web3, privateKeyWrapper}) => {
42 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);85 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
107 }150 }
108 });151 });
152
153 itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
154 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
155 const collectionHelpers = evmCollectionHelpers(web3, owner);
156 const result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
157 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
158 const sponsor = privateKeyWrapper('//Alice');
159 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
160
161 await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
162
163 const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
164 await submitTransactionAsync(sponsor, confirmTx);
165
166 const user = createEthAccount(web3);
167 const nextTokenId = await collectionEvm.methods.nextTokenId().call();
168 expect(nextTokenId).to.be.equal('1');
169
170 await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
171 await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
172 await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
173
174 const ownerBalanceBefore = await ethBalanceViaSub(api, owner);
175 const sponsorBalanceBefore = (await getBalance(api, [sponsor.address]))[0];
176
177 {
178 const nextTokenId = await collectionEvm.methods.nextTokenId().call();
179 expect(nextTokenId).to.be.equal('1');
180 const result = await collectionEvm.methods.mintWithTokenURI(
181 user,
182 nextTokenId,
183 'Test URI',
184 ).send({from: user});
185 const events = normalizeEvents(result.events);
186
187 expect(events).to.be.deep.equal([
188 {
189 address: collectionIdAddress,
190 event: 'Transfer',
191 args: {
192 from: '0x0000000000000000000000000000000000000000',
193 to: user,
194 tokenId: nextTokenId,
195 },
196 },
197 ]);
198
199 const ownerBalanceAfter = await ethBalanceViaSub(api, owner);
200 const sponsorBalanceAfter = (await getBalance(api, [sponsor.address]))[0];
201
202 expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
203 expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
204 expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
205 }
206 });
109207
110 itWeb3('Check that transaction via EVM spend money from sponsor address', async ({api, web3, privateKeyWrapper}) => {208 itWeb3('Check that transaction via EVM spend money from sponsor address', async ({api, web3, privateKeyWrapper}) => {
111 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);209 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);