difftreelog
Merge branch 'develop' into test/playground-migration
in: master
40 files changed
.docker/Dockerfile-chain-dev-unitdiffbeforeafterboth232324WORKDIR /dev_chain24WORKDIR /dev_chain252526CMD cargo test --features=limit-testing26CMD cargo test --features=limit-testing --workspace2727.docker/Dockerfile-testnet.j2diffbeforeafterbothno changes
.docker/testnet-config/launch-config.jsondiffbeforeafterbothno changes
.github/workflows/ci-develop.ymldiffbeforeafterboth3on:3on:4 pull_request:4 pull_request:5 branches: [ 'develop' ]5 branches: [ 'develop' ]6 types: [ opened, reopened, synchronize, ready_for_review ]6 types: [ opened, reopened, synchronize, ready_for_review, converted_to_draft ]778concurrency:8concurrency:9 group: ${{ github.workflow }}-${{ github.head_ref }}9 group: ${{ github.workflow }}-${{ github.head_ref }}12jobs:12jobs:131314 yarn-test-dev:14 yarn-test-dev:15 if: github.event.pull_request.draft == false15 uses: ./.github/workflows/dev-build-tests_v2.yml16 uses: ./.github/workflows/dev-build-tests_v2.yml17161817 unit-test:19 unit-test:20 if: github.event.pull_request.draft == false18 uses: ./.github/workflows/unit-test_v2.yml21 uses: ./.github/workflows/unit-test_v2.yml192220 canary:23 canary:21 if: ${{ contains( github.event.pull_request.labels.*.name, 'canary') }}24 if: ${{ (github.event.pull_request.draft == false && contains( github.event.pull_request.labels.*.name, 'canary')) }}22 uses: ./.github/workflows/canary.yml25 uses: ./.github/workflows/canary.yml23 secrets: inherit # pass all secrets26 secrets: inherit # pass all secrets242725 xcm:28 xcm:26 if: ${{ contains( github.event.pull_request.labels.*.name, 'xcm') }}29 if: ${{ (github.event.pull_request.draft == false && contains( github.event.pull_request.labels.*.name, 'xcm')) }}27 uses: ./.github/workflows/xcm.yml30 uses: ./.github/workflows/xcm.yml28 secrets: inherit # pass all secrets31 secrets: inherit # pass all secrets293230 codestyle:33 codestyle:34 if: github.event.pull_request.draft == false31 uses: ./.github/workflows/codestyle_v2.yml35 uses: ./.github/workflows/codestyle_v2.yml32 36 33 yarn_eslint:37 yarn_eslint:38 if: github.event.pull_request.draft == false34 uses: ./.github/workflows/test_codestyle_v2.yml39 uses: ./.github/workflows/test_codestyle_v2.yml3540.github/workflows/testnet-build.ymldiffbeforeafterbothno changes
pallets/common/src/erc.rsdiffbeforeafterboth139 save(self)139 save(self)140 }140 }141141142 // TODO: Temprorary off. Need refactor142 /// Set the substrate sponsor of the collection.143 // /// Set the substrate sponsor of the collection.143 ///144 // ///144 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.145 // /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.145 ///146 // ///146 /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.147 // /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.147 fn set_collection_sponsor_substrate(148 // fn set_collection_sponsor_substrate(148 &mut self,149 // &mut self,149 caller: caller,150 // caller: caller,150 sponsor: uint256,151 // sponsor: uint256,151 ) -> Result<void> {152 // ) -> Result<void> {152 self.consume_store_reads_and_writes(1, 1)?;153 // self.consume_store_reads_and_writes(1, 1)?;153154154 check_is_owner_or_admin(caller, self)?;155 // check_is_owner_or_admin(caller, self)?;155156156 let sponsor = convert_uint256_to_cross_account::<T>(sponsor);157 // let sponsor = convert_uint256_to_cross_account::<T>(sponsor);157 self.set_sponsor(sponsor.as_sub().clone())158 // self.set_sponsor(sponsor.as_sub().clone())158 .map_err(dispatch_to_evm::<T>)?;159 // .map_err(dispatch_to_evm::<T>)?;159 save(self)160 // save(self)160 }161 // }161162162 /// Whether there is a pending sponsor.163 /// Whether there is a pending sponsor.163 fn has_collection_pending_sponsor(&self) -> Result<bool> {164 fn has_collection_pending_sponsor(&self) -> Result<bool> {299 Ok(crate::eth::collection_id_to_address(self.id))300 Ok(crate::eth::collection_id_to_address(self.id))300 }301 }301302303 // TODO: Temprorary off. Need refactor302 /// Add collection admin by substrate address.304 // /// Add collection admin by substrate address.303 /// @param newAdmin Substrate administrator address.305 // /// @param newAdmin Substrate administrator address.304 fn add_collection_admin_substrate(306 // fn add_collection_admin_substrate(305 &mut self,307 // &mut self,306 caller: caller,308 // caller: caller,307 new_admin: uint256,309 // new_admin: uint256,308 ) -> Result<void> {310 // ) -> Result<void> {309 self.consume_store_writes(2)?;311 // self.consume_store_writes(2)?;310312311 let caller = T::CrossAccountId::from_eth(caller);313 // let caller = T::CrossAccountId::from_eth(caller);312 let new_admin = convert_uint256_to_cross_account::<T>(new_admin);314 // let new_admin = convert_uint256_to_cross_account::<T>(new_admin);313 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;315 // <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;314 Ok(())316 // Ok(())315 }317 // }316318319 // TODO: Temprorary off. Need refactor317 /// Remove collection admin by substrate address.320 // /// Remove collection admin by substrate address.318 /// @param admin Substrate administrator address.321 // /// @param admin Substrate administrator address.319 fn remove_collection_admin_substrate(322 // fn remove_collection_admin_substrate(320 &mut self,323 // &mut self,321 caller: caller,324 // caller: caller,322 admin: uint256,325 // admin: uint256,323 ) -> Result<void> {326 // ) -> Result<void> {324 self.consume_store_writes(2)?;327 // self.consume_store_writes(2)?;325328326 let caller = T::CrossAccountId::from_eth(caller);329 // let caller = T::CrossAccountId::from_eth(caller);327 let admin = convert_uint256_to_cross_account::<T>(admin);330 // let admin = convert_uint256_to_cross_account::<T>(admin);328 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;331 // <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;329 Ok(())332 // Ok(())330 }333 // }331334332 /// Add collection admin.335 /// Add collection admin.333 /// @param newAdmin Address of the added administrator.336 /// @param newAdmin Address of the added administrator.476 Ok(())479 Ok(())477 }480 }478481482 // TODO: Temprorary off. Need refactor479 /// Add substrate user to allowed list.483 // /// Add substrate user to allowed list.480 ///484 // ///481 /// @param user User substrate address.485 // /// @param user User substrate address.482 fn add_to_collection_allow_list_substrate(486 // fn add_to_collection_allow_list_substrate(483 &mut self,487 // &mut self,484 caller: caller,488 // caller: caller,485 user: uint256,489 // user: uint256,486 ) -> Result<void> {490 // ) -> Result<void> {487 self.consume_store_writes(1)?;491 // self.consume_store_writes(1)?;488492489 let caller = T::CrossAccountId::from_eth(caller);493 // let caller = T::CrossAccountId::from_eth(caller);490 let user = convert_uint256_to_cross_account::<T>(user);494 // let user = convert_uint256_to_cross_account::<T>(user);491 Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;495 // Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;492 Ok(())496 // Ok(())493 }497 // }494498495 /// Remove the user from the allowed list.499 /// Remove the user from the allowed list.496 ///500 ///504 Ok(())508 Ok(())505 }509 }506510511 // TODO: Temprorary off. Need refactor507 /// Remove substrate user from allowed list.512 // /// Remove substrate user from allowed list.508 ///513 // ///509 /// @param user User substrate address.514 // /// @param user User substrate address.510 fn remove_from_collection_allow_list_substrate(515 // fn remove_from_collection_allow_list_substrate(511 &mut self,516 // &mut self,512 caller: caller,517 // caller: caller,513 user: uint256,518 // user: uint256,514 ) -> Result<void> {519 // ) -> Result<void> {515 self.consume_store_writes(1)?;520 // self.consume_store_writes(1)?;516521517 let caller = T::CrossAccountId::from_eth(caller);522 // let caller = T::CrossAccountId::from_eth(caller);518 let user = convert_uint256_to_cross_account::<T>(user);523 // let user = convert_uint256_to_cross_account::<T>(user);519 Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;524 // Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;520 Ok(())525 // Ok(())521 }526 // }522527523 /// Switch permission for minting.528 /// Switch permission for minting.524 ///529 ///551 Ok(self.is_owner_or_admin(&user))556 Ok(self.is_owner_or_admin(&user))552 }557 }553558559 // TODO: Temprorary off. Need refactor554 /// Check that substrate account is the owner or admin of the collection560 // /// Check that substrate account is the owner or admin of the collection555 ///561 // ///556 /// @param user account to verify562 // /// @param user account to verify557 /// @return "true" if account is the owner or admin563 // /// @return "true" if account is the owner or admin558 fn is_owner_or_admin_substrate(&self, user: uint256) -> Result<bool> {564 // fn is_owner_or_admin_substrate(&self, user: uint256) -> Result<bool> {559 let user = convert_uint256_to_cross_account::<T>(user);565 // let user = convert_uint256_to_cross_account::<T>(user);560 Ok(self.is_owner_or_admin(&user))566 // Ok(self.is_owner_or_admin(&user))561 }567 // }562568563 /// Returns collection type569 /// Returns collection type564 ///570 ///595 .map_err(dispatch_to_evm::<T>)601 .map_err(dispatch_to_evm::<T>)596 }602 }597603604 // TODO: Temprorary off. Need refactor598 /// Changes collection owner to another substrate account605 // /// Changes collection owner to another substrate account599 ///606 // ///600 /// @dev Owner can be changed only by current owner607 // /// @dev Owner can be changed only by current owner601 /// @param newOwner new owner substrate account608 // /// @param newOwner new owner substrate account602 fn set_owner_substrate(&mut self, caller: caller, new_owner: uint256) -> Result<void> {609 // fn set_owner_substrate(&mut self, caller: caller, new_owner: uint256) -> Result<void> {603 self.consume_store_writes(1)?;610 // self.consume_store_writes(1)?;604611605 let caller = T::CrossAccountId::from_eth(caller);612 // let caller = T::CrossAccountId::from_eth(caller);606 let new_owner = convert_uint256_to_cross_account::<T>(new_owner);613 // let new_owner = convert_uint256_to_cross_account::<T>(new_owner);607 self.set_owner_internal(caller, new_owner)614 // self.set_owner_internal(caller, new_owner)608 .map_err(dispatch_to_evm::<T>)615 // .map_err(dispatch_to_evm::<T>)609 }616 // }610617611 // TODO: need implement AbiWriter for &Vec<T>618 // TODO: need implement AbiWriter for &Vec<T>612 // fn collection_admins(&self) -> Result<Vec<(address, uint256)>> {619 // fn collection_admins(&self) -> Result<Vec<(address, uint256)>> {pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth18}18}191920/// @title A contract that allows you to work with collections.20/// @title A contract that allows you to work with collections.21/// @dev the ERC-165 identifier for this interface is 0x47dbc10521/// @dev the ERC-165 identifier for this interface is 0x3e1e808322contract Collection is Dummy, ERC165 {22contract Collection is Dummy, ERC165 {23 /// Set collection property.23 /// Set collection property.24 ///24 ///72 dummy = 0;72 dummy = 0;73 }73 }7475 /// Set the substrate sponsor of the collection.76 ///77 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.78 ///79 /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.80 /// @dev EVM selector for this function is: 0xc74d6751,81 /// or in textual repr: setCollectionSponsorSubstrate(uint256)82 function setCollectionSponsorSubstrate(uint256 sponsor) public {83 require(false, stub_error);84 sponsor;85 dummy = 0;86 }877488 /// Whether there is a pending sponsor.75 /// Whether there is a pending sponsor.89 /// @dev EVM selector for this function is: 0x058ac185,76 /// @dev EVM selector for this function is: 0x058ac185,167 return 0x0000000000000000000000000000000000000000;154 return 0x0000000000000000000000000000000000000000;168 }155 }169170 /// Add collection admin by substrate address.171 /// @param newAdmin Substrate administrator address.172 /// @dev EVM selector for this function is: 0x5730062b,173 /// or in textual repr: addCollectionAdminSubstrate(uint256)174 function addCollectionAdminSubstrate(uint256 newAdmin) public {175 require(false, stub_error);176 newAdmin;177 dummy = 0;178 }179180 /// Remove collection admin by substrate address.181 /// @param admin Substrate administrator address.182 /// @dev EVM selector for this function is: 0x4048fcf9,183 /// or in textual repr: removeCollectionAdminSubstrate(uint256)184 function removeCollectionAdminSubstrate(uint256 admin) public {185 require(false, stub_error);186 admin;187 dummy = 0;188 }189156190 /// Add collection admin.157 /// Add collection admin.191 /// @param newAdmin Address of the added administrator.158 /// @param newAdmin Address of the added administrator.267 dummy = 0;234 dummy = 0;268 }235 }269270 /// Add substrate user to allowed list.271 ///272 /// @param user User substrate address.273 /// @dev EVM selector for this function is: 0xd06ad267,274 /// or in textual repr: addToCollectionAllowListSubstrate(uint256)275 function addToCollectionAllowListSubstrate(uint256 user) public {276 require(false, stub_error);277 user;278 dummy = 0;279 }280236281 /// Remove the user from the allowed list.237 /// Remove the user from the allowed list.282 ///238 ///289 dummy = 0;245 dummy = 0;290 }246 }291292 /// Remove substrate user from allowed list.293 ///294 /// @param user User substrate address.295 /// @dev EVM selector for this function is: 0xa31913ed,296 /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)297 function removeFromCollectionAllowListSubstrate(uint256 user) public {298 require(false, stub_error);299 user;300 dummy = 0;301 }302247303 /// Switch permission for minting.248 /// Switch permission for minting.304 ///249 ///324 return false;269 return false;325 }270 }326327 /// Check that substrate account is the owner or admin of the collection328 ///329 /// @param user account to verify330 /// @return "true" if account is the owner or admin331 /// @dev EVM selector for this function is: 0x68910e00,332 /// or in textual repr: isOwnerOrAdminSubstrate(uint256)333 function isOwnerOrAdminSubstrate(uint256 user) public view returns (bool) {334 require(false, stub_error);335 user;336 dummy;337 return false;338 }339271340 /// Returns collection type272 /// Returns collection type341 ///273 ///372 dummy = 0;304 dummy = 0;373 }305 }374375 /// Changes collection owner to another substrate account376 ///377 /// @dev Owner can be changed only by current owner378 /// @param newOwner new owner substrate account379 /// @dev EVM selector for this function is: 0xb212138f,380 /// or in textual repr: setOwnerSubstrate(uint256)381 function setOwnerSubstrate(uint256 newOwner) public {382 require(false, stub_error);383 newOwner;384 dummy = 0;385 }386}306}387307388/// @dev the ERC-165 identifier for this interface is 0x63034ac5308/// @dev the ERC-165 identifier for this interface is 0x63034ac5pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth91}91}929293/// @title A contract that allows you to work with collections.93/// @title A contract that allows you to work with collections.94/// @dev the ERC-165 identifier for this interface is 0x47dbc10594/// @dev the ERC-165 identifier for this interface is 0x3e1e808395contract Collection is Dummy, ERC165 {95contract Collection is Dummy, ERC165 {96 /// Set collection property.96 /// Set collection property.97 ///97 ///145 dummy = 0;145 dummy = 0;146 }146 }147148 /// Set the substrate sponsor of the collection.149 ///150 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.151 ///152 /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.153 /// @dev EVM selector for this function is: 0xc74d6751,154 /// or in textual repr: setCollectionSponsorSubstrate(uint256)155 function setCollectionSponsorSubstrate(uint256 sponsor) public {156 require(false, stub_error);157 sponsor;158 dummy = 0;159 }160147161 /// Whether there is a pending sponsor.148 /// Whether there is a pending sponsor.162 /// @dev EVM selector for this function is: 0x058ac185,149 /// @dev EVM selector for this function is: 0x058ac185,240 return 0x0000000000000000000000000000000000000000;227 return 0x0000000000000000000000000000000000000000;241 }228 }242243 /// Add collection admin by substrate address.244 /// @param newAdmin Substrate administrator address.245 /// @dev EVM selector for this function is: 0x5730062b,246 /// or in textual repr: addCollectionAdminSubstrate(uint256)247 function addCollectionAdminSubstrate(uint256 newAdmin) public {248 require(false, stub_error);249 newAdmin;250 dummy = 0;251 }252253 /// Remove collection admin by substrate address.254 /// @param admin Substrate administrator address.255 /// @dev EVM selector for this function is: 0x4048fcf9,256 /// or in textual repr: removeCollectionAdminSubstrate(uint256)257 function removeCollectionAdminSubstrate(uint256 admin) public {258 require(false, stub_error);259 admin;260 dummy = 0;261 }262229263 /// Add collection admin.230 /// Add collection admin.264 /// @param newAdmin Address of the added administrator.231 /// @param newAdmin Address of the added administrator.340 dummy = 0;307 dummy = 0;341 }308 }342343 /// Add substrate user to allowed list.344 ///345 /// @param user User substrate address.346 /// @dev EVM selector for this function is: 0xd06ad267,347 /// or in textual repr: addToCollectionAllowListSubstrate(uint256)348 function addToCollectionAllowListSubstrate(uint256 user) public {349 require(false, stub_error);350 user;351 dummy = 0;352 }353309354 /// Remove the user from the allowed list.310 /// Remove the user from the allowed list.355 ///311 ///362 dummy = 0;318 dummy = 0;363 }319 }364365 /// Remove substrate user from allowed list.366 ///367 /// @param user User substrate address.368 /// @dev EVM selector for this function is: 0xa31913ed,369 /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)370 function removeFromCollectionAllowListSubstrate(uint256 user) public {371 require(false, stub_error);372 user;373 dummy = 0;374 }375320376 /// Switch permission for minting.321 /// Switch permission for minting.377 ///322 ///397 return false;342 return false;398 }343 }399400 /// Check that substrate account is the owner or admin of the collection401 ///402 /// @param user account to verify403 /// @return "true" if account is the owner or admin404 /// @dev EVM selector for this function is: 0x68910e00,405 /// or in textual repr: isOwnerOrAdminSubstrate(uint256)406 function isOwnerOrAdminSubstrate(uint256 user) public view returns (bool) {407 require(false, stub_error);408 user;409 dummy;410 return false;411 }412344413 /// Returns collection type345 /// Returns collection type414 ///346 ///445 dummy = 0;377 dummy = 0;446 }378 }447448 /// Changes collection owner to another substrate account449 ///450 /// @dev Owner can be changed only by current owner451 /// @param newOwner new owner substrate account452 /// @dev EVM selector for this function is: 0xb212138f,453 /// or in textual repr: setOwnerSubstrate(uint256)454 function setOwnerSubstrate(uint256 newOwner) public {455 require(false, stub_error);456 newOwner;457 dummy = 0;458 }459}379}460380461/// @dev anonymous struct381/// @dev anonymous structpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth91}91}929293/// @title A contract that allows you to work with collections.93/// @title A contract that allows you to work with collections.94/// @dev the ERC-165 identifier for this interface is 0x47dbc10594/// @dev the ERC-165 identifier for this interface is 0x3e1e808395contract Collection is Dummy, ERC165 {95contract Collection is Dummy, ERC165 {96 /// Set collection property.96 /// Set collection property.97 ///97 ///145 dummy = 0;145 dummy = 0;146 }146 }147148 /// Set the substrate sponsor of the collection.149 ///150 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.151 ///152 /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.153 /// @dev EVM selector for this function is: 0xc74d6751,154 /// or in textual repr: setCollectionSponsorSubstrate(uint256)155 function setCollectionSponsorSubstrate(uint256 sponsor) public {156 require(false, stub_error);157 sponsor;158 dummy = 0;159 }160147161 /// Whether there is a pending sponsor.148 /// Whether there is a pending sponsor.162 /// @dev EVM selector for this function is: 0x058ac185,149 /// @dev EVM selector for this function is: 0x058ac185,240 return 0x0000000000000000000000000000000000000000;227 return 0x0000000000000000000000000000000000000000;241 }228 }242243 /// Add collection admin by substrate address.244 /// @param newAdmin Substrate administrator address.245 /// @dev EVM selector for this function is: 0x5730062b,246 /// or in textual repr: addCollectionAdminSubstrate(uint256)247 function addCollectionAdminSubstrate(uint256 newAdmin) public {248 require(false, stub_error);249 newAdmin;250 dummy = 0;251 }252253 /// Remove collection admin by substrate address.254 /// @param admin Substrate administrator address.255 /// @dev EVM selector for this function is: 0x4048fcf9,256 /// or in textual repr: removeCollectionAdminSubstrate(uint256)257 function removeCollectionAdminSubstrate(uint256 admin) public {258 require(false, stub_error);259 admin;260 dummy = 0;261 }262229263 /// Add collection admin.230 /// Add collection admin.264 /// @param newAdmin Address of the added administrator.231 /// @param newAdmin Address of the added administrator.340 dummy = 0;307 dummy = 0;341 }308 }342343 /// Add substrate user to allowed list.344 ///345 /// @param user User substrate address.346 /// @dev EVM selector for this function is: 0xd06ad267,347 /// or in textual repr: addToCollectionAllowListSubstrate(uint256)348 function addToCollectionAllowListSubstrate(uint256 user) public {349 require(false, stub_error);350 user;351 dummy = 0;352 }353309354 /// Remove the user from the allowed list.310 /// Remove the user from the allowed list.355 ///311 ///362 dummy = 0;318 dummy = 0;363 }319 }364365 /// Remove substrate user from allowed list.366 ///367 /// @param user User substrate address.368 /// @dev EVM selector for this function is: 0xa31913ed,369 /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)370 function removeFromCollectionAllowListSubstrate(uint256 user) public {371 require(false, stub_error);372 user;373 dummy = 0;374 }375320376 /// Switch permission for minting.321 /// Switch permission for minting.377 ///322 ///397 return false;342 return false;398 }343 }399400 /// Check that substrate account is the owner or admin of the collection401 ///402 /// @param user account to verify403 /// @return "true" if account is the owner or admin404 /// @dev EVM selector for this function is: 0x68910e00,405 /// or in textual repr: isOwnerOrAdminSubstrate(uint256)406 function isOwnerOrAdminSubstrate(uint256 user) public view returns (bool) {407 require(false, stub_error);408 user;409 dummy;410 return false;411 }412344413 /// Returns collection type345 /// Returns collection type414 ///346 ///445 dummy = 0;377 dummy = 0;446 }378 }447448 /// Changes collection owner to another substrate account449 ///450 /// @dev Owner can be changed only by current owner451 /// @param newOwner new owner substrate account452 /// @dev EVM selector for this function is: 0xb212138f,453 /// or in textual repr: setOwnerSubstrate(uint256)454 function setOwnerSubstrate(uint256 newOwner) public {455 require(false, stub_error);456 newOwner;457 dummy = 0;458 }459}379}460380461/// @dev anonymous struct381/// @dev anonymous structtests/package.jsondiffbeforeafterboth88 "testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",88 "testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",89 "testEthCreateNFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createNFTCollection.test.ts",89 "testEthCreateNFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createNFTCollection.test.ts",90 "testEthCreateRFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createRFTCollection.test.ts",90 "testEthCreateRFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createRFTCollection.test.ts",91 "testEthNFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/nonFungible.test.ts",91 "testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",92 "testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",93 "testEthRFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/reFungible.test.ts ./**/eth/reFungibleToken.test.ts",92 "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",94 "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",95 "testEthFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/fungible.test.ts",93 "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",96 "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",94 "testPromotion": "mocha --timeout 9999999 -r ts-node/register ./**/app-promotion.test.ts",97 "testPromotion": "mocha --timeout 9999999 -r ts-node/register ./**/app-promotion.test.ts",95 "polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",98 "polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",tests/src/eth/allowlist.test.tsdiffbeforeafterboth95 expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;95 expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;96 });96 });979798 itEth('Collection allowlist can be added and removed by [sub] address', async ({helper}) => {98 // TODO: Temprorary off. Need refactor99 const owner = await helper.eth.createAccountWithBalance(donor);99 // itEth('Collection allowlist can be added and removed by [sub] address', async ({helper}) => {100 const user = donor;100 // const owner = await helper.eth.createAccountWithBalance(donor);101 101 // const user = donor;102 const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');102 103 const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);103 // const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');104 104 // const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);105 expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;105 106 await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});106 // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;107 expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;107 // await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});108 108 // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;109 await collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).send({from: owner});109 110 expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;110 // await collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).send({from: owner});111 });111 // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;112 // });112113113 itEth('Collection allowlist can not be add and remove [eth] address by not owner', async ({helper}) => {114 itEth('Collection allowlist can not be add and remove [eth] address by not owner', async ({helper}) => {114 const owner = await helper.eth.createAccountWithBalance(donor);115 const owner = await helper.eth.createAccountWithBalance(donor);128 expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;129 expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;129 });130 });130131131 itEth('Collection allowlist can not be add and remove [sub] address by not owner', async ({helper}) => {132 // TODO: Temprorary off. Need refactor132 const owner = await helper.eth.createAccountWithBalance(donor);133 // itEth('Collection allowlist can not be add and remove [sub] address by not owner', async ({helper}) => {133 const notOwner = await helper.eth.createAccountWithBalance(donor);134 // const owner = await helper.eth.createAccountWithBalance(donor);134 const user = donor;135 // const notOwner = await helper.eth.createAccountWithBalance(donor);135 136 // const user = donor;136 const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');137 137 const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);138 // const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');138 139 // const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);139 expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;140 140 await expect(collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');141 // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;141 expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;142 // await expect(collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');142 await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});143 // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;143 144 // await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});144 expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;145 145 await expect(collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');146 // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;146 expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;147 // await expect(collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');147 });148 // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;149 // });148});150});149151tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth13}13}141415/// @title A contract that allows you to work with collections.15/// @title A contract that allows you to work with collections.16/// @dev the ERC-165 identifier for this interface is 0x47dbc10516/// @dev the ERC-165 identifier for this interface is 0x3e1e808317interface Collection is Dummy, ERC165 {17interface Collection is Dummy, ERC165 {18 /// Set collection property.18 /// Set collection property.19 ///19 ///49 /// or in textual repr: setCollectionSponsor(address)49 /// or in textual repr: setCollectionSponsor(address)50 function setCollectionSponsor(address sponsor) external;50 function setCollectionSponsor(address sponsor) external;5152 /// Set the substrate sponsor of the collection.53 ///54 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.55 ///56 /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.57 /// @dev EVM selector for this function is: 0xc74d6751,58 /// or in textual repr: setCollectionSponsorSubstrate(uint256)59 function setCollectionSponsorSubstrate(uint256 sponsor) external;605161 /// Whether there is a pending sponsor.52 /// Whether there is a pending sponsor.62 /// @dev EVM selector for this function is: 0x058ac185,53 /// @dev EVM selector for this function is: 0x058ac185,112 /// or in textual repr: contractAddress()103 /// or in textual repr: contractAddress()113 function contractAddress() external view returns (address);104 function contractAddress() external view returns (address);114115 /// Add collection admin by substrate address.116 /// @param newAdmin Substrate administrator address.117 /// @dev EVM selector for this function is: 0x5730062b,118 /// or in textual repr: addCollectionAdminSubstrate(uint256)119 function addCollectionAdminSubstrate(uint256 newAdmin) external;120121 /// Remove collection admin by substrate address.122 /// @param admin Substrate administrator address.123 /// @dev EVM selector for this function is: 0x4048fcf9,124 /// or in textual repr: removeCollectionAdminSubstrate(uint256)125 function removeCollectionAdminSubstrate(uint256 admin) external;126105127 /// Add collection admin.106 /// Add collection admin.128 /// @param newAdmin Address of the added administrator.107 /// @param newAdmin Address of the added administrator.174 /// or in textual repr: addToCollectionAllowList(address)153 /// or in textual repr: addToCollectionAllowList(address)175 function addToCollectionAllowList(address user) external;154 function addToCollectionAllowList(address user) external;176177 /// Add substrate user to allowed list.178 ///179 /// @param user User substrate address.180 /// @dev EVM selector for this function is: 0xd06ad267,181 /// or in textual repr: addToCollectionAllowListSubstrate(uint256)182 function addToCollectionAllowListSubstrate(uint256 user) external;183155184 /// Remove the user from the allowed list.156 /// Remove the user from the allowed list.185 ///157 ///188 /// or in textual repr: removeFromCollectionAllowList(address)160 /// or in textual repr: removeFromCollectionAllowList(address)189 function removeFromCollectionAllowList(address user) external;161 function removeFromCollectionAllowList(address user) external;190191 /// Remove substrate user from allowed list.192 ///193 /// @param user User substrate address.194 /// @dev EVM selector for this function is: 0xa31913ed,195 /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)196 function removeFromCollectionAllowListSubstrate(uint256 user) external;197162198 /// Switch permission for minting.163 /// Switch permission for minting.199 ///164 ///210 /// or in textual repr: isOwnerOrAdmin(address)175 /// or in textual repr: isOwnerOrAdmin(address)211 function isOwnerOrAdmin(address user) external view returns (bool);176 function isOwnerOrAdmin(address user) external view returns (bool);212213 /// Check that substrate account is the owner or admin of the collection214 ///215 /// @param user account to verify216 /// @return "true" if account is the owner or admin217 /// @dev EVM selector for this function is: 0x68910e00,218 /// or in textual repr: isOwnerOrAdminSubstrate(uint256)219 function isOwnerOrAdminSubstrate(uint256 user) external view returns (bool);220177221 /// Returns collection type178 /// Returns collection type222 ///179 ///241 /// or in textual repr: setOwner(address)198 /// or in textual repr: setOwner(address)242 function setOwner(address newOwner) external;199 function setOwner(address newOwner) external;243244 /// Changes collection owner to another substrate account245 ///246 /// @dev Owner can be changed only by current owner247 /// @param newOwner new owner substrate account248 /// @dev EVM selector for this function is: 0xb212138f,249 /// or in textual repr: setOwnerSubstrate(uint256)250 function setOwnerSubstrate(uint256 newOwner) external;251}200}252201253/// @dev the ERC-165 identifier for this interface is 0x63034ac5202/// @dev the ERC-165 identifier for this interface is 0x63034ac5tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth62}62}636364/// @title A contract that allows you to work with collections.64/// @title A contract that allows you to work with collections.65/// @dev the ERC-165 identifier for this interface is 0x47dbc10565/// @dev the ERC-165 identifier for this interface is 0x3e1e808366interface Collection is Dummy, ERC165 {66interface Collection is Dummy, ERC165 {67 /// Set collection property.67 /// Set collection property.68 ///68 ///98 /// or in textual repr: setCollectionSponsor(address)98 /// or in textual repr: setCollectionSponsor(address)99 function setCollectionSponsor(address sponsor) external;99 function setCollectionSponsor(address sponsor) external;100101 /// Set the substrate sponsor of the collection.102 ///103 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.104 ///105 /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.106 /// @dev EVM selector for this function is: 0xc74d6751,107 /// or in textual repr: setCollectionSponsorSubstrate(uint256)108 function setCollectionSponsorSubstrate(uint256 sponsor) external;109100110 /// Whether there is a pending sponsor.101 /// Whether there is a pending sponsor.111 /// @dev EVM selector for this function is: 0x058ac185,102 /// @dev EVM selector for this function is: 0x058ac185,161 /// or in textual repr: contractAddress()152 /// or in textual repr: contractAddress()162 function contractAddress() external view returns (address);153 function contractAddress() external view returns (address);163164 /// Add collection admin by substrate address.165 /// @param newAdmin Substrate administrator address.166 /// @dev EVM selector for this function is: 0x5730062b,167 /// or in textual repr: addCollectionAdminSubstrate(uint256)168 function addCollectionAdminSubstrate(uint256 newAdmin) external;169170 /// Remove collection admin by substrate address.171 /// @param admin Substrate administrator address.172 /// @dev EVM selector for this function is: 0x4048fcf9,173 /// or in textual repr: removeCollectionAdminSubstrate(uint256)174 function removeCollectionAdminSubstrate(uint256 admin) external;175154176 /// Add collection admin.155 /// Add collection admin.177 /// @param newAdmin Address of the added administrator.156 /// @param newAdmin Address of the added administrator.223 /// or in textual repr: addToCollectionAllowList(address)202 /// or in textual repr: addToCollectionAllowList(address)224 function addToCollectionAllowList(address user) external;203 function addToCollectionAllowList(address user) external;225226 /// Add substrate user to allowed list.227 ///228 /// @param user User substrate address.229 /// @dev EVM selector for this function is: 0xd06ad267,230 /// or in textual repr: addToCollectionAllowListSubstrate(uint256)231 function addToCollectionAllowListSubstrate(uint256 user) external;232204233 /// Remove the user from the allowed list.205 /// Remove the user from the allowed list.234 ///206 ///237 /// or in textual repr: removeFromCollectionAllowList(address)209 /// or in textual repr: removeFromCollectionAllowList(address)238 function removeFromCollectionAllowList(address user) external;210 function removeFromCollectionAllowList(address user) external;239240 /// Remove substrate user from allowed list.241 ///242 /// @param user User substrate address.243 /// @dev EVM selector for this function is: 0xa31913ed,244 /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)245 function removeFromCollectionAllowListSubstrate(uint256 user) external;246211247 /// Switch permission for minting.212 /// Switch permission for minting.248 ///213 ///259 /// or in textual repr: isOwnerOrAdmin(address)224 /// or in textual repr: isOwnerOrAdmin(address)260 function isOwnerOrAdmin(address user) external view returns (bool);225 function isOwnerOrAdmin(address user) external view returns (bool);261262 /// Check that substrate account is the owner or admin of the collection263 ///264 /// @param user account to verify265 /// @return "true" if account is the owner or admin266 /// @dev EVM selector for this function is: 0x68910e00,267 /// or in textual repr: isOwnerOrAdminSubstrate(uint256)268 function isOwnerOrAdminSubstrate(uint256 user) external view returns (bool);269226270 /// Returns collection type227 /// Returns collection type271 ///228 ///290 /// or in textual repr: setOwner(address)247 /// or in textual repr: setOwner(address)291 function setOwner(address newOwner) external;248 function setOwner(address newOwner) external;292293 /// Changes collection owner to another substrate account294 ///295 /// @dev Owner can be changed only by current owner296 /// @param newOwner new owner substrate account297 /// @dev EVM selector for this function is: 0xb212138f,298 /// or in textual repr: setOwnerSubstrate(uint256)299 function setOwnerSubstrate(uint256 newOwner) external;300}249}301250302/// @dev anonymous struct251/// @dev anonymous structtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth62}62}636364/// @title A contract that allows you to work with collections.64/// @title A contract that allows you to work with collections.65/// @dev the ERC-165 identifier for this interface is 0x47dbc10565/// @dev the ERC-165 identifier for this interface is 0x3e1e808366interface Collection is Dummy, ERC165 {66interface Collection is Dummy, ERC165 {67 /// Set collection property.67 /// Set collection property.68 ///68 ///98 /// or in textual repr: setCollectionSponsor(address)98 /// or in textual repr: setCollectionSponsor(address)99 function setCollectionSponsor(address sponsor) external;99 function setCollectionSponsor(address sponsor) external;100101 /// Set the substrate sponsor of the collection.102 ///103 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.104 ///105 /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.106 /// @dev EVM selector for this function is: 0xc74d6751,107 /// or in textual repr: setCollectionSponsorSubstrate(uint256)108 function setCollectionSponsorSubstrate(uint256 sponsor) external;109100110 /// Whether there is a pending sponsor.101 /// Whether there is a pending sponsor.111 /// @dev EVM selector for this function is: 0x058ac185,102 /// @dev EVM selector for this function is: 0x058ac185,161 /// or in textual repr: contractAddress()152 /// or in textual repr: contractAddress()162 function contractAddress() external view returns (address);153 function contractAddress() external view returns (address);163164 /// Add collection admin by substrate address.165 /// @param newAdmin Substrate administrator address.166 /// @dev EVM selector for this function is: 0x5730062b,167 /// or in textual repr: addCollectionAdminSubstrate(uint256)168 function addCollectionAdminSubstrate(uint256 newAdmin) external;169170 /// Remove collection admin by substrate address.171 /// @param admin Substrate administrator address.172 /// @dev EVM selector for this function is: 0x4048fcf9,173 /// or in textual repr: removeCollectionAdminSubstrate(uint256)174 function removeCollectionAdminSubstrate(uint256 admin) external;175154176 /// Add collection admin.155 /// Add collection admin.177 /// @param newAdmin Address of the added administrator.156 /// @param newAdmin Address of the added administrator.223 /// or in textual repr: addToCollectionAllowList(address)202 /// or in textual repr: addToCollectionAllowList(address)224 function addToCollectionAllowList(address user) external;203 function addToCollectionAllowList(address user) external;225226 /// Add substrate user to allowed list.227 ///228 /// @param user User substrate address.229 /// @dev EVM selector for this function is: 0xd06ad267,230 /// or in textual repr: addToCollectionAllowListSubstrate(uint256)231 function addToCollectionAllowListSubstrate(uint256 user) external;232204233 /// Remove the user from the allowed list.205 /// Remove the user from the allowed list.234 ///206 ///237 /// or in textual repr: removeFromCollectionAllowList(address)209 /// or in textual repr: removeFromCollectionAllowList(address)238 function removeFromCollectionAllowList(address user) external;210 function removeFromCollectionAllowList(address user) external;239240 /// Remove substrate user from allowed list.241 ///242 /// @param user User substrate address.243 /// @dev EVM selector for this function is: 0xa31913ed,244 /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)245 function removeFromCollectionAllowListSubstrate(uint256 user) external;246211247 /// Switch permission for minting.212 /// Switch permission for minting.248 ///213 ///259 /// or in textual repr: isOwnerOrAdmin(address)224 /// or in textual repr: isOwnerOrAdmin(address)260 function isOwnerOrAdmin(address user) external view returns (bool);225 function isOwnerOrAdmin(address user) external view returns (bool);261262 /// Check that substrate account is the owner or admin of the collection263 ///264 /// @param user account to verify265 /// @return "true" if account is the owner or admin266 /// @dev EVM selector for this function is: 0x68910e00,267 /// or in textual repr: isOwnerOrAdminSubstrate(uint256)268 function isOwnerOrAdminSubstrate(uint256 user) external view returns (bool);269226270 /// Returns collection type227 /// Returns collection type271 ///228 ///290 /// or in textual repr: setOwner(address)247 /// or in textual repr: setOwner(address)291 function setOwner(address newOwner) external;248 function setOwner(address newOwner) external;292293 /// Changes collection owner to another substrate account294 ///295 /// @dev Owner can be changed only by current owner296 /// @param newOwner new owner substrate account297 /// @dev EVM selector for this function is: 0xb212138f,298 /// or in textual repr: setOwnerSubstrate(uint256)299 function setOwnerSubstrate(uint256 newOwner) external;300}249}301250302/// @dev anonymous struct251/// @dev anonymous structtests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth44 .to.be.eq(newAdmin.toLocaleLowerCase());44 .to.be.eq(newAdmin.toLocaleLowerCase());45 });45 });464647 itWeb3('Add substrate admin by owner', async ({api, web3, privateKeyWrapper}) => {47 // TODO: Temprorary off. Need refactor48 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);48 // itWeb3('Add substrate admin by owner', async ({api, web3, privateKeyWrapper}) => {49 const collectionHelper = evmCollectionHelpers(web3, owner);49 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);50 50 // const collectionHelper = evmCollectionHelpers(web3, owner);51 const result = await collectionHelper.methods51 52 .createNonfungibleCollection('A', 'B', 'C')52 // const result = await collectionHelper.methods53 .send();53 // .createNonfungibleCollection('A', 'B', 'C')54 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);54 // .send();5555 // const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);56 const newAdmin = privateKeyWrapper('//Alice');5657 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);57 // const newAdmin = privateKeyWrapper('//Alice');58 await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();58 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);5959 // await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();60 const adminList = await api.rpc.unique.adminlist(collectionId);6061 expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())61 // const adminList = await api.rpc.unique.adminlist(collectionId);62 .to.be.eq(newAdmin.address.toLocaleLowerCase());62 // expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())63 });63 // .to.be.eq(newAdmin.address.toLocaleLowerCase());64 64 // });65 65 itWeb3('Verify owner or admin', async ({api, web3, privateKeyWrapper}) => {66 itWeb3('Verify owner or admin', async ({api, web3, privateKeyWrapper}) => {66 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);67 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);121 expect(adminList.length).to.be.eq(0);122 expect(adminList.length).to.be.eq(0);122 });123 });123124124 itWeb3('(!negative tests!) Add substrate admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {125 // TODO: Temprorary off. Need refactor125 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);126 // itWeb3('(!negative tests!) Add substrate admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {126 const collectionHelper = evmCollectionHelpers(web3, owner);127 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);127 128 // const collectionHelper = evmCollectionHelpers(web3, owner);128 const result = await collectionHelper.methods129 129 .createNonfungibleCollection('A', 'B', 'C')130 // const result = await collectionHelper.methods130 .send();131 // .createNonfungibleCollection('A', 'B', 'C')131 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);132 // .send();132133 // const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);133 const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);134134 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);135 // const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);135 await collectionEvm.methods.addCollectionAdmin(admin).send();136 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);136137 // await collectionEvm.methods.addCollectionAdmin(admin).send();137 const notAdmin = privateKey('//Alice');138138 await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin.addressRaw).call({from: admin}))139 // const notAdmin = privateKey('//Alice');139 .to.be.rejectedWith('NoPermission');140 // await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin.addressRaw).call({from: admin}))140141 // .to.be.rejectedWith('NoPermission');141 const adminList = await api.rpc.unique.adminlist(collectionId);142142 expect(adminList.length).to.be.eq(1);143 // const adminList = await api.rpc.unique.adminlist(collectionId);143 expect(adminList[0].asEthereum.toString().toLocaleLowerCase())144 // expect(adminList.length).to.be.eq(1);144 .to.be.eq(admin.toLocaleLowerCase());145 // expect(adminList[0].asEthereum.toString().toLocaleLowerCase())145 });146 // .to.be.eq(admin.toLocaleLowerCase());146 147 // });147 itWeb3('(!negative tests!) Add substrate admin by USER is not allowed', async ({api, web3, privateKeyWrapper}) => {148 148 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);149 // TODO: Temprorary off. Need refactor149 const collectionHelper = evmCollectionHelpers(web3, owner);150 // itWeb3('(!negative tests!) Add substrate admin by USER is not allowed', async ({api, web3, privateKeyWrapper}) => {150 151 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);151 const result = await collectionHelper.methods152 // const collectionHelper = evmCollectionHelpers(web3, owner);152 .createNonfungibleCollection('A', 'B', 'C')153 153 .send();154 // const result = await collectionHelper.methods154 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);155 // .createNonfungibleCollection('A', 'B', 'C')155156 // .send();156 const notAdmin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);157 // const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);157 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);158158 const notAdmin1 = privateKey('//Alice');159 // const notAdmin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);159 await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin1.addressRaw).call({from: notAdmin0}))160 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);160 .to.be.rejectedWith('NoPermission');161 // const notAdmin1 = privateKey('//Alice');161162 // await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin1.addressRaw).call({from: notAdmin0}))162 const adminList = await api.rpc.unique.adminlist(collectionId);163 // .to.be.rejectedWith('NoPermission');163 expect(adminList.length).to.be.eq(0);164164 });165 // const adminList = await api.rpc.unique.adminlist(collectionId);166 // expect(adminList.length).to.be.eq(0);167 // });165});168});166169167describe('Remove collection admins', () => {170describe('Remove collection admins', () => {189 expect(adminList.length).to.be.eq(0);192 expect(adminList.length).to.be.eq(0);190 });193 });191194192 itWeb3('Remove substrate admin by owner', async ({api, web3, privateKeyWrapper}) => {195 // TODO: Temprorary off. Need refactor193 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);196 // itWeb3('Remove substrate admin by owner', async ({api, web3, privateKeyWrapper}) => {194 const collectionHelper = evmCollectionHelpers(web3, owner);197 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);195 198 // const collectionHelper = evmCollectionHelpers(web3, owner);196 const result = await collectionHelper.methods199 197 .createNonfungibleCollection('A', 'B', 'C')200 // const result = await collectionHelper.methods198 .send();201 // .createNonfungibleCollection('A', 'B', 'C')199 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);202 // .send();200203 // const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);201 const newAdmin = privateKeyWrapper('//Alice');204202 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);205 // const newAdmin = privateKeyWrapper('//Alice');203 await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();206 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);204 {207 // await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();205 const adminList = await api.rpc.unique.adminlist(collectionId);208 // {206 expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())209 // const adminList = await api.rpc.unique.adminlist(collectionId);207 .to.be.eq(newAdmin.address.toLocaleLowerCase());210 // expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())208 }211 // .to.be.eq(newAdmin.address.toLocaleLowerCase());209 212 // }210 await collectionEvm.methods.removeCollectionAdminSubstrate(newAdmin.addressRaw).send();213 211 const adminList = await api.rpc.unique.adminlist(collectionId);214 // await collectionEvm.methods.removeCollectionAdminSubstrate(newAdmin.addressRaw).send();212 expect(adminList.length).to.be.eq(0);215 // const adminList = await api.rpc.unique.adminlist(collectionId);213 });216 // expect(adminList.length).to.be.eq(0);217 // });214218215 itWeb3('(!negative tests!) Remove admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {219 itWeb3('(!negative tests!) Remove admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {216 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);220 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);264 }268 }265 });269 });266270267 itWeb3('(!negative tests!) Remove substrate admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {271 // TODO: Temprorary off. Need refactor268 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);272 // itWeb3('(!negative tests!) Remove substrate admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {269 const collectionHelper = evmCollectionHelpers(web3, owner);273 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);270 274 // const collectionHelper = evmCollectionHelpers(web3, owner);271 const result = await collectionHelper.methods275 272 .createNonfungibleCollection('A', 'B', 'C')276 // const result = await collectionHelper.methods273 .send();277 // .createNonfungibleCollection('A', 'B', 'C')274 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);278 // .send();275279 // const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);276 const adminSub = privateKeyWrapper('//Alice');280277 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);281 // const adminSub = privateKeyWrapper('//Alice');278 await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();282 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);279 const adminEth = await createEthAccountWithBalance(api, web3, privateKeyWrapper);283 // await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();280 await collectionEvm.methods.addCollectionAdmin(adminEth).send();284 // const adminEth = await createEthAccountWithBalance(api, web3, privateKeyWrapper);281285 // await collectionEvm.methods.addCollectionAdmin(adminEth).send();282 await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: adminEth}))286283 .to.be.rejectedWith('NoPermission');287 // await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: adminEth}))284288 // .to.be.rejectedWith('NoPermission');285 const adminList = await api.rpc.unique.adminlist(collectionId);289286 expect(adminList.length).to.be.eq(2);290 // const adminList = await api.rpc.unique.adminlist(collectionId);287 expect(adminList.toString().toLocaleLowerCase())291 // expect(adminList.length).to.be.eq(2);288 .to.be.deep.contains(adminSub.address.toLocaleLowerCase())292 // expect(adminList.toString().toLocaleLowerCase())289 .to.be.deep.contains(adminEth.toLocaleLowerCase());293 // .to.be.deep.contains(adminSub.address.toLocaleLowerCase())290 });294 // .to.be.deep.contains(adminEth.toLocaleLowerCase());291295 // });292 itWeb3('(!negative tests!) Remove substrate admin by USER is not allowed', async ({api, web3, privateKeyWrapper}) => {296293 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);297 // TODO: Temprorary off. Need refactor294 const collectionHelper = evmCollectionHelpers(web3, owner);298 // itWeb3('(!negative tests!) Remove substrate admin by USER is not allowed', async ({api, web3, privateKeyWrapper}) => {295 299 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);296 const result = await collectionHelper.methods300 // const collectionHelper = evmCollectionHelpers(web3, owner);297 .createNonfungibleCollection('A', 'B', 'C')301 298 .send();302 // const result = await collectionHelper.methods299 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);303 // .createNonfungibleCollection('A', 'B', 'C')300304 // .send();301 const adminSub = privateKeyWrapper('//Alice');305 // const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);302 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);306303 await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();307 // const adminSub = privateKeyWrapper('//Alice');304 const notAdminEth = await createEthAccountWithBalance(api, web3, privateKeyWrapper);308 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);305309 // await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();306 await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: notAdminEth}))310 // const notAdminEth = await createEthAccountWithBalance(api, web3, privateKeyWrapper);307 .to.be.rejectedWith('NoPermission');311308312 // await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: notAdminEth}))309 const adminList = await api.rpc.unique.adminlist(collectionId);313 // .to.be.rejectedWith('NoPermission');310 expect(adminList.length).to.be.eq(1);314311 expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())315 // const adminList = await api.rpc.unique.adminlist(collectionId);312 .to.be.eq(adminSub.address.toLocaleLowerCase());316 // expect(adminList.length).to.be.eq(1);313 });317 // expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())318 // .to.be.eq(adminSub.address.toLocaleLowerCase());319 // });314});320});315321316describe('Change owner tests', () => {322describe('Change owner tests', () => {361});367});362368363describe('Change substrate owner tests', () => {369describe('Change substrate owner tests', () => {364 itWeb3('Change owner', async ({api, web3, privateKeyWrapper}) => {370 // TODO: Temprorary off. Need refactor365 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);371 // itWeb3('Change owner', async ({api, web3, privateKeyWrapper}) => {366 const newOwner = privateKeyWrapper('//Alice');372 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);367 const collectionHelper = evmCollectionHelpers(web3, owner);373 // const newOwner = privateKeyWrapper('//Alice');368 const result = await collectionHelper.methods374 // const collectionHelper = evmCollectionHelpers(web3, owner);369 .createNonfungibleCollection('A', 'B', 'C')375 // const result = await collectionHelper.methods370 .send();376 // .createNonfungibleCollection('A', 'B', 'C')371 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);377 // .send();372 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);378 // const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);373 379 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);374 expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.true;380 375 expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;381 // expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.true;376 382 // expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;377 await collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send();383 378 384 // await collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send();379 expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.false;385 380 expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.true;386 // expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.false;381 });387 // expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.true;382388 // });383 itWeb3('change owner call fee', async ({web3, api, privateKeyWrapper}) => {389384 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);390 // TODO: Temprorary off. Need refactor385 const newOwner = privateKeyWrapper('//Alice');391 // itWeb3('change owner call fee', async ({web3, api, privateKeyWrapper}) => {386 const collectionHelper = evmCollectionHelpers(web3, owner);392 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);387 const result = await collectionHelper.methods393 // const newOwner = privateKeyWrapper('//Alice');388 .createNonfungibleCollection('A', 'B', 'C')394 // const collectionHelper = evmCollectionHelpers(web3, owner);389 .send();395 // const result = await collectionHelper.methods390 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);396 // .createNonfungibleCollection('A', 'B', 'C')391 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);397 // .send();392398 // const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);393 const cost = await recordEthFee(api, owner, () => collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send());399 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);394 expect(cost < BigInt(0.2 * Number(UNIQUE)));400395 expect(cost > 0);401 // const cost = await recordEthFee(api, owner, () => collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send());396 });402 // expect(cost < BigInt(0.2 * Number(UNIQUE)));397403 // expect(cost > 0);398 itWeb3('(!negative tests!) call setOwner by non owner', async ({api, web3, privateKeyWrapper}) => {404 // });399 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);405400 const otherReceiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);406 // TODO: Temprorary off. Need refactor401 const newOwner = privateKeyWrapper('//Alice');407 // itWeb3('(!negative tests!) call setOwner by non owner', async ({api, web3, privateKeyWrapper}) => {402 const collectionHelper = evmCollectionHelpers(web3, owner);408 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);403 const result = await collectionHelper.methods409 // const otherReceiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);404 .createNonfungibleCollection('A', 'B', 'C')410 // const newOwner = privateKeyWrapper('//Alice');405 .send();411 // const collectionHelper = evmCollectionHelpers(web3, owner);406 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);412 // const result = await collectionHelper.methods407 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);413 // .createNonfungibleCollection('A', 'B', 'C')408 414 // .send();409 await expect(collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send({from: otherReceiver})).to.be.rejected;415 // const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);410 expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;416 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);411 });417 418 // await expect(collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send({from: otherReceiver})).to.be.rejected;419 // expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;420 // });412});421});tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth40 ]);40 ]);41 });41 });424243 itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {43 // TODO: Temprorary off. Need refactor44 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);44 // itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {45 const collectionHelpers = evmCollectionHelpers(web3, owner);45 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);46 let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();46 // const collectionHelpers = evmCollectionHelpers(web3, owner);47 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);47 // let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();48 const sponsor = privateKeyWrapper('//Alice');48 // const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);49 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);49 // const sponsor = privateKeyWrapper('//Alice');5050 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);51 expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;5152 result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});52 // expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;53 expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;53 // result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});54 54 // expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;55 const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);55 56 await submitTransactionAsync(sponsor, confirmTx);56 // const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);57 expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;57 // await submitTransactionAsync(sponsor, confirmTx);58 58 // expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;59 const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});59 60 expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);60 // const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});61 });61 // expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);62 // });626363 itWeb3('Remove sponsor', async ({api, web3, privateKeyWrapper}) => {64 itWeb3('Remove sponsor', async ({api, web3, privateKeyWrapper}) => {64 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);65 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);150 }151 }151 });152 });152153153 itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {154 // TODO: Temprorary off. Need refactor154 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);155 // itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {155 const collectionHelpers = evmCollectionHelpers(web3, owner);156 // const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);156 const result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();157 // const collectionHelpers = evmCollectionHelpers(web3, owner);157 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);158 // const result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();158 const sponsor = privateKeyWrapper('//Alice');159 // const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);159 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);160 // const sponsor = privateKeyWrapper('//Alice');160161 // const collectionEvm = evmCollection(web3, owner, collectionIdAddress);161 await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});162162 163 // await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});163 const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);164 164 await submitTransactionAsync(sponsor, confirmTx);165 // const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);165 166 // await submitTransactionAsync(sponsor, confirmTx);166 const user = createEthAccount(web3);167 167 const nextTokenId = await collectionEvm.methods.nextTokenId().call();168 // const user = createEthAccount(web3);168 expect(nextTokenId).to.be.equal('1');169 // const nextTokenId = await collectionEvm.methods.nextTokenId().call();169170 // expect(nextTokenId).to.be.equal('1');170 await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});171171 await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});172 // await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});172 await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});173 // await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});173174 // await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});174 const ownerBalanceBefore = await ethBalanceViaSub(api, owner);175175 const sponsorBalanceBefore = (await getBalance(api, [sponsor.address]))[0];176 // const ownerBalanceBefore = await ethBalanceViaSub(api, owner);176177 // const sponsorBalanceBefore = (await getBalance(api, [sponsor.address]))[0];177 {178178 const nextTokenId = await collectionEvm.methods.nextTokenId().call();179 // {179 expect(nextTokenId).to.be.equal('1');180 // const nextTokenId = await collectionEvm.methods.nextTokenId().call();180 const result = await collectionEvm.methods.mintWithTokenURI(181 // expect(nextTokenId).to.be.equal('1');181 user,182 // const result = await collectionEvm.methods.mintWithTokenURI(182 nextTokenId,183 // user,183 'Test URI',184 // nextTokenId,184 ).send({from: user});185 // 'Test URI',185 const events = normalizeEvents(result.events);186 // ).send({from: user});186187 // const events = normalizeEvents(result.events);187 expect(events).to.be.deep.equal([188188 {189 // expect(events).to.be.deep.equal([189 address: collectionIdAddress,190 // {190 event: 'Transfer',191 // address: collectionIdAddress,191 args: {192 // event: 'Transfer',192 from: '0x0000000000000000000000000000000000000000',193 // args: {193 to: user,194 // from: '0x0000000000000000000000000000000000000000',194 tokenId: nextTokenId,195 // to: user,195 },196 // tokenId: nextTokenId,196 },197 // },197 ]);198 // },198199 // ]);199 const ownerBalanceAfter = await ethBalanceViaSub(api, owner);200200 const sponsorBalanceAfter = (await getBalance(api, [sponsor.address]))[0];201 // const ownerBalanceAfter = await ethBalanceViaSub(api, owner);201202 // const sponsorBalanceAfter = (await getBalance(api, [sponsor.address]))[0];202 expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');203203 expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);204 // expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');204 expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;205 // expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);205 }206 // expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;206 });207 // }208 // });207209208 itWeb3('Check that transaction via EVM spend money from sponsor address', async ({api, web3, privateKeyWrapper}) => {210 itWeb3('Check that transaction via EVM spend money from sponsor address', async ({api, web3, privateKeyWrapper}) => {209 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);211 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);tests/src/eth/fungible.test.tsdiffbeforeafterboth14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617import {approveExpectSuccess, createCollection, createCollectionExpectSuccess, createFungibleItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE} from '../util/helpers';17import {expect, itEth, usingEthPlaygrounds} from './util/playgrounds';18import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, GAS_ARGS, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';18import {IKeyringPair} from '@polkadot/types/types';19import fungibleAbi from './fungibleAbi.json';20import {expect} from 'chai';21import {submitTransactionAsync} from '../substrate/substrate-api';221923describe('Fungible: Information getting', () => {20describe('Fungible: Information getting', () => {24 itWeb3('totalSupply', async ({api, web3, privateKeyWrapper}) => {21 let donor: IKeyringPair;22 let alice: IKeyringPair;2325 const collection = await createCollectionExpectSuccess({24 before(async function() {25 await usingEthPlaygrounds(async (helper, privateKey) => {26 name: 'token name',26 donor = privateKey('//Alice');27 mode: {type: 'Fungible', decimalPoints: 0},27 [alice] = await helper.arrange.createAccounts([20n], donor);28 });28 });29 const alice = privateKeyWrapper('//Alice');29 });303031 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);31 itEth('totalSupply', async ({helper}) => {32 const caller = await helper.eth.createAccountWithBalance(donor);33 const collection = await helper.ft.mintCollection(alice);34 await collection.mint(alice, 200n);323533 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Substrate: alice.address});36 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'ft', caller);3435 const address = collectionIdToAddress(collection);36 const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: caller, ...GAS_ARGS});37 const totalSupply = await contract.methods.totalSupply().call();37 const totalSupply = await contract.methods.totalSupply().call();3839 expect(totalSupply).to.equal('200');38 expect(totalSupply).to.equal('200');40 });39 });414042 itWeb3('balanceOf', async ({api, web3, privateKeyWrapper}) => {41 itEth('balanceOf', async ({helper}) => {43 const collection = await createCollectionExpectSuccess({42 const caller = await helper.eth.createAccountWithBalance(donor);44 name: 'token name',43 const collection = await helper.ft.mintCollection(alice);45 mode: {type: 'Fungible', decimalPoints: 0},44 await collection.mint(alice, 200n, {Ethereum: caller});46 });47 const alice = privateKeyWrapper('//Alice');484549 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);46 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'ft', caller);5051 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: caller});5253 const address = collectionIdToAddress(collection);54 const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: caller, ...GAS_ARGS});55 const balance = await contract.methods.balanceOf(caller).call();47 const balance = await contract.methods.balanceOf(caller).call();5657 expect(balance).to.equal('200');48 expect(balance).to.equal('200');58 });49 });59});50});605161describe('Fungible: Plain calls', () => {52describe('Fungible: Plain calls', () => {62 itWeb3('Can perform mint()', async ({web3, api, privateKeyWrapper}) => {53 let donor: IKeyringPair;54 let alice: IKeyringPair;5556 before(async function() {57 await usingEthPlaygrounds(async (helper, privateKey) => {63 const alice = privateKeyWrapper('//Alice');58 donor = privateKey('//Alice');64 const collection = await createCollection(api, alice, {59 [alice] = await helper.arrange.createAccounts([20n], donor);65 name: 'token name',66 mode: {type: 'Fungible', decimalPoints: 0},67 });60 });61 });686269 const receiver = createEthAccount(web3);63 itEth('Can perform mint()', async ({helper}) => {64 const owner = await helper.eth.createAccountWithBalance(donor);65 const receiver = helper.eth.createAccount();66 const collection = await helper.ft.mintCollection(alice);67 await collection.addAdmin(alice, {Ethereum: owner});706871 const collectionIdAddress = collectionIdToAddress(collection.collectionId);69 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);72 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);70 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);73 const changeAdminTx = api.tx.unique.addCollectionAdmin(collection.collectionId, {Ethereum: owner});74 await submitTransactionAsync(alice, changeAdminTx);757176 const collectionContract = evmCollection(web3, owner, collectionIdAddress, {type: 'Fungible', decimalPoints: 0});72 const result = await contract.methods.mint(receiver, 100).send();77 const result = await collectionContract.methods.mint(receiver, 100).send();78 const events = normalizeEvents(result.events);79 73 80 expect(events).to.be.deep.equal([74 const event = result.events.Transfer;81 {82 address: collectionIdAddress,75 expect(event.address).to.equal(collectionAddress);83 event: 'Transfer',76 expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');84 args: {85 from: '0x0000000000000000000000000000000000000000',86 to: receiver,77 expect(event.returnValues.to).to.equal(receiver);87 value: '100',78 expect(event.returnValues.value).to.equal('100');88 },89 },90 ]);91 });79 });928093 itWeb3('Can perform mintBulk()', async ({web3, api, privateKeyWrapper}) => {81 itEth('Can perform mintBulk()', async ({helper}) => {94 const alice = privateKeyWrapper('//Alice');82 const owner = await helper.eth.createAccountWithBalance(donor);95 const collection = await createCollection(api, alice, {83 const bulkSize = 3;96 name: 'token name',84 const receivers = [...new Array(bulkSize)].map(() => helper.eth.createAccount());97 mode: {type: 'Fungible', decimalPoints: 0},85 const collection = await helper.ft.mintCollection(alice);98 });86 await collection.addAdmin(alice, {Ethereum: owner});9987100 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);88 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);101 const receiver1 = createEthAccount(web3);89 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);102 const receiver2 = createEthAccount(web3);103 const receiver3 = createEthAccount(web3);10490105 const collectionIdAddress = collectionIdToAddress(collection.collectionId);91 const result = await contract.methods.mintBulk(Array.from({length: bulkSize}, (_, i) => (106 const changeAdminTx = api.tx.unique.addCollectionAdmin(collection.collectionId, {Ethereum: owner});107 await submitTransactionAsync(alice, changeAdminTx);108109 const collectionContract = evmCollection(web3, owner, collectionIdAddress, {type: 'Fungible', decimalPoints: 0});110 const result = await collectionContract.methods.mintBulk([111 [receiver1, 10],92 [receivers[i], (i + 1) * 10]112 [receiver2, 20],113 [receiver3, 30],114 ]).send();93 ))).send();115 const events = normalizeEvents(result.events);94 const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.value - b.returnValues.value);116117 expect(events).to.be.deep.contain({118 address:collectionIdAddress,119 event: 'Transfer',120 args: {121 from: '0x0000000000000000000000000000000000000000',122 to: receiver1,95 for (let i = 0; i < bulkSize; i++) {123 value: '10',124 },96 const event = events[i];125 });126 97 expect(event.address).to.equal(collectionAddress);127 expect(events).to.be.deep.contain({128 address:collectionIdAddress,98 expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');129 event: 'Transfer',130 args: {131 from: '0x0000000000000000000000000000000000000000',132 to: receiver2,133 value: '20',134 },135 });136 99 expect(event.returnValues.to).to.equal(receivers[i]);137 expect(events).to.be.deep.contain({138 address:collectionIdAddress,100 expect(event.returnValues.value).to.equal(String(10 * (i + 1)));139 event: 'Transfer',140 args: {141 from: '0x0000000000000000000000000000000000000000',142 to: receiver3,143 value: '30',144 },101 }145 });146 });102 });147103148 itWeb3('Can perform burn()', async ({web3, api, privateKeyWrapper}) => {104 itEth('Can perform burn()', async ({helper}) => {149 const alice = privateKeyWrapper('//Alice');105 const owner = await helper.eth.createAccountWithBalance(donor);150 const collection = await createCollection(api, alice, {106 const receiver = await helper.eth.createAccountWithBalance(donor);151 name: 'token name',107 const collection = await helper.ft.mintCollection(alice);152 mode: {type: 'Fungible', decimalPoints: 0},108 await collection.addAdmin(alice, {Ethereum: owner});153 });154109155 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);110 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);156 const changeAdminTx = api.tx.unique.addCollectionAdmin(collection.collectionId, {Ethereum: owner});111 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);157 await submitTransactionAsync(alice, changeAdminTx);112 await contract.methods.mint(receiver, 100).send();158 const receiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);159113160 const collectionIdAddress = collectionIdToAddress(collection.collectionId);114 const result = await contract.methods.burnFrom(receiver, 49).send({from: receiver});161 const collectionContract = evmCollection(web3, owner, collectionIdAddress, {type: 'Fungible', decimalPoints: 0});162 await collectionContract.methods.mint(receiver, 100).send();163164 const result = await collectionContract.methods.burnFrom(receiver, 49).send({from: receiver});165 115 166 const events = normalizeEvents(result.events);116 const event = result.events.Transfer;117 expect(event.address).to.equal(collectionAddress);118 expect(event.returnValues.from).to.equal(receiver);119 expect(event.returnValues.to).to.equal('0x0000000000000000000000000000000000000000');120 expect(event.returnValues.value).to.equal('49');167121168 expect(events).to.be.deep.equal([122 const balance = await contract.methods.balanceOf(receiver).call();169 {170 address: collectionIdAddress,171 event: 'Transfer',172 args: {173 from: receiver,174 to: '0x0000000000000000000000000000000000000000',175 value: '49',176 },177 },178 ]);179180 const balance = await collectionContract.methods.balanceOf(receiver).call();181 expect(balance).to.equal('51');123 expect(balance).to.equal('51');182 });124 });183125184 itWeb3('Can perform approve()', async ({web3, api, privateKeyWrapper}) => {126 itEth('Can perform approve()', async ({helper}) => {185 const collection = await createCollectionExpectSuccess({127 const owner = await helper.eth.createAccountWithBalance(donor);186 name: 'token name',128 const spender = helper.eth.createAccount();187 mode: {type: 'Fungible', decimalPoints: 0},129 const collection = await helper.ft.mintCollection(alice);188 });189 const alice = privateKeyWrapper('//Alice');130 await collection.mint(alice, 200n, {Ethereum: owner});190131191 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);132 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);133 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);192134193 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});194195 const spender = createEthAccount(web3);196197 const address = collectionIdToAddress(collection);198 const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});199200 {135 {201 const result = await contract.methods.approve(spender, 100).send({from: owner});136 const result = await contract.methods.approve(spender, 100).send({from: owner});202 const events = normalizeEvents(result.events);203137204 expect(events).to.be.deep.equal([138 const event = result.events.Approval;205 {206 address,139 expect(event.address).to.be.equal(collectionAddress);207 event: 'Approval',140 expect(event.returnValues.owner).to.be.equal(owner);208 args: {209 owner,210 spender,141 expect(event.returnValues.spender).to.be.equal(spender);211 value: '100',142 expect(event.returnValues.value).to.be.equal('100');212 },213 },214 ]);215 }143 }216144217 {145 {220 }148 }221 });149 });222150223 itWeb3('Can perform transferFrom()', async ({web3, api, privateKeyWrapper}) => {151 itEth('Can perform transferFrom()', async ({helper}) => {224 const collection = await createCollectionExpectSuccess({152 const owner = await helper.eth.createAccountWithBalance(donor);225 name: 'token name',153 const spender = await helper.eth.createAccountWithBalance(donor);226 mode: {type: 'Fungible', decimalPoints: 0},154 const receiver = helper.eth.createAccount();227 });155 const collection = await helper.ft.mintCollection(alice);228 const alice = privateKeyWrapper('//Alice');156 await collection.mint(alice, 200n, {Ethereum: owner});229157230 const owner = createEthAccount(web3);158 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);231 await transferBalanceToEth(api, alice, owner);159 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);232160233 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});234235 const spender = createEthAccount(web3);236 await transferBalanceToEth(api, alice, spender);237238 const receiver = createEthAccount(web3);239240 const address = collectionIdToAddress(collection);241 const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});242243 await contract.methods.approve(spender, 100).send();161 await contract.methods.approve(spender, 100).send();244162245 {163 {246 const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});164 const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});247 const events = normalizeEvents(result.events);165 166 let event = result.events.Transfer;248 expect(events).to.be.deep.equal([167 expect(event.address).to.be.equal(collectionAddress);249 {168 expect(event.returnValues.from).to.be.equal(owner);250 address,251 event: 'Transfer',252 args: {253 from: owner,254 to: receiver,169 expect(event.returnValues.to).to.be.equal(receiver);255 value: '49',170 expect(event.returnValues.value).to.be.equal('49');256 },171257 },172 event = result.events.Approval;258 {173 expect(event.address).to.be.equal(collectionAddress);259 address,260 event: 'Approval',174 expect(event.returnValues.owner).to.be.equal(owner);261 args: {262 owner,263 spender,175 expect(event.returnValues.spender).to.be.equal(spender);264 value: '51',176 expect(event.returnValues.value).to.be.equal('51');265 },266 },267 ]);268 }177 }269178270 {179 {278 }187 }279 });188 });280189281 itWeb3('Can perform transfer()', async ({web3, api, privateKeyWrapper}) => {190 itEth('Can perform transfer()', async ({helper}) => {282 const collection = await createCollectionExpectSuccess({191 const owner = await helper.eth.createAccountWithBalance(donor);283 name: 'token name',192 const receiver = await helper.eth.createAccountWithBalance(donor);284 mode: {type: 'Fungible', decimalPoints: 0},193 const collection = await helper.ft.mintCollection(alice);285 });286 const alice = privateKeyWrapper('//Alice');194 await collection.mint(alice, 200n, {Ethereum: owner});287195288 const owner = createEthAccount(web3);196 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);289 await transferBalanceToEth(api, alice, owner);197 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);290198291 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});292293 const receiver = createEthAccount(web3);294 await transferBalanceToEth(api, alice, receiver);295296 const address = collectionIdToAddress(collection);297 const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});298299 {199 {300 const result = await contract.methods.transfer(receiver, 50).send({from: owner});200 const result = await contract.methods.transfer(receiver, 50).send({from: owner});301 const events = normalizeEvents(result.events);201 202 const event = result.events.Transfer;302 expect(events).to.be.deep.equal([203 expect(event.address).to.be.equal(collectionAddress);303 {204 expect(event.returnValues.from).to.be.equal(owner);304 address,305 event: 'Transfer',306 args: {307 from: owner,308 to: receiver,205 expect(event.returnValues.to).to.be.equal(receiver);309 value: '50',206 expect(event.returnValues.value).to.be.equal('50');310 },311 },312 ]);313 }207 }314208315 {209 {325});219});326220327describe('Fungible: Fees', () => {221describe('Fungible: Fees', () => {328 itWeb3('approve() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {222 let donor: IKeyringPair;223 let alice: IKeyringPair;224225 before(async function() {226 await usingEthPlaygrounds(async (helper, privateKey) => {329 const collection = await createCollectionExpectSuccess({227 donor = privateKey('//Alice');330 mode: {type: 'Fungible', decimalPoints: 0},228 [alice] = await helper.arrange.createAccounts([20n], donor);331 });229 });332 const alice = privateKeyWrapper('//Alice');230 });231 232 itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {233 const owner = await helper.eth.createAccountWithBalance(donor);234 const spender = helper.eth.createAccount();235 const collection = await helper.ft.mintCollection(alice);236 await collection.mint(alice, 200n, {Ethereum: owner});333237334 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);238 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);335 const spender = createEthAccount(web3);239 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);336240337 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});241 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, 100).send({from: owner}));338339 const address = collectionIdToAddress(collection);340 const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});341342 const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, 100).send({from: owner}));343 expect(cost < BigInt(0.2 * Number(UNIQUE)));242 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));344 });243 });345244346 itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {245 itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {347 const collection = await createCollectionExpectSuccess({246 const owner = await helper.eth.createAccountWithBalance(donor);348 mode: {type: 'Fungible', decimalPoints: 0},247 const spender = await helper.eth.createAccountWithBalance(donor);349 });248 const collection = await helper.ft.mintCollection(alice);350 const alice = privateKeyWrapper('//Alice');249 await collection.mint(alice, 200n, {Ethereum: owner});351250352 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);251 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);353 const spender = await createEthAccountWithBalance(api, web3, privateKeyWrapper);252 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);354253355 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});356357 const address = collectionIdToAddress(collection);358 const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});359360 await contract.methods.approve(spender, 100).send({from: owner});254 await contract.methods.approve(spender, 100).send({from: owner});361255362 const cost = await recordEthFee(api, spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));256 const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));363 expect(cost < BigInt(0.2 * Number(UNIQUE)));257 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));364 });258 });365259366 itWeb3('transfer() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {260 itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {367 const collection = await createCollectionExpectSuccess({261 const owner = await helper.eth.createAccountWithBalance(donor);368 mode: {type: 'Fungible', decimalPoints: 0},262 const receiver = helper.eth.createAccount();369 });263 const collection = await helper.ft.mintCollection(alice);370 const alice = privateKeyWrapper('//Alice');264 await collection.mint(alice, 200n, {Ethereum: owner});371265372 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);266 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);373 const receiver = createEthAccount(web3);267 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);374268375 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});269 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));376377 const address = collectionIdToAddress(collection);378 const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});379380 const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));381 expect(cost < BigInt(0.2 * Number(UNIQUE)));270 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));382 });271 });383});272});384273385describe('Fungible: Substrate calls', () => {274describe('Fungible: Substrate calls', () => {386 itWeb3('Events emitted for approve()', async ({web3, privateKeyWrapper}) => {275 let donor: IKeyringPair;276 let alice: IKeyringPair;277278 before(async function() {279 await usingEthPlaygrounds(async (helper, privateKey) => {387 const collection = await createCollectionExpectSuccess({280 donor = privateKey('//Alice');388 mode: {type: 'Fungible', decimalPoints: 0},281 [alice] = await helper.arrange.createAccounts([20n], donor);389 });282 });390 const alice = privateKeyWrapper('//Alice');283 });391284392 const receiver = createEthAccount(web3);285 itEth('Events emitted for approve()', async ({helper}) => {286 const receiver = helper.eth.createAccount();287 const collection = await helper.ft.mintCollection(alice);288 await collection.mint(alice, 200n);393289394 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n});290 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);291 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft');395292396 const address = collectionIdToAddress(collection);293 const events: any = [];397 const contract = new web3.eth.Contract(fungibleAbi as any, address);294 contract.events.allEvents((_: any, event: any) => {398399 const events = await recordEvents(contract, async () => {400 await approveExpectSuccess(collection, 0, alice, {Ethereum: receiver}, 100);295 events.push(event);401 });296 });297 await collection.approveTokens(alice, {Ethereum: receiver}, 100n);402298403 expect(events).to.be.deep.equal([299 const event = events[0];404 {405 address,406 event: 'Approval',300 expect(event.event).to.be.equal('Approval');407 args: {301 expect(event.address).to.be.equal(collectionAddress);408 owner: subToEth(alice.address),302 expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));409 spender: receiver,303 expect(event.returnValues.spender).to.be.equal(receiver);410 value: '100',304 expect(event.returnValues.value).to.be.equal('100');411 },412 },413 ]);414 });305 });415306416 itWeb3('Events emitted for transferFrom()', async ({web3, privateKeyWrapper}) => {307 itEth('Events emitted for transferFrom()', async ({helper}) => {417 const collection = await createCollectionExpectSuccess({308 const [bob] = await helper.arrange.createAccounts([10n], donor);418 mode: {type: 'Fungible', decimalPoints: 0},309 const receiver = helper.eth.createAccount();419 });310 const collection = await helper.ft.mintCollection(alice);420 const alice = privateKeyWrapper('//Alice');311 await collection.mint(alice, 200n);421 const bob = privateKeyWrapper('//Bob');312 await collection.approveTokens(alice, {Substrate: bob.address}, 100n);422313423 const receiver = createEthAccount(web3);314 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);315 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft');424316425 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n});317 const events: any = [];426 await approveExpectSuccess(collection, 0, alice, bob.address, 100);427428 const address = collectionIdToAddress(collection);429 const contract = new web3.eth.Contract(fungibleAbi as any, address);318 contract.events.allEvents((_: any, event: any) => {430431 const events = await recordEvents(contract, async () => {432 await transferFromExpectSuccess(collection, 0, bob, alice, {Ethereum: receiver}, 51, 'Fungible');319 events.push(event);433 });320 });321 await collection.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n);434322435 expect(events).to.be.deep.equal([323 let event = events[0];436 {437 address,438 event: 'Transfer',324 expect(event.event).to.be.equal('Transfer');439 args: {325 expect(event.address).to.be.equal(collectionAddress);440 from: subToEth(alice.address),441 to: receiver,442 value: '51',326 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));443 },444 },445 {446 address,447 event: 'Approval',448 args: {449 owner: subToEth(alice.address),450 spender: subToEth(bob.address),327 expect(event.returnValues.to).to.be.equal(receiver);451 value: '49',328 expect(event.returnValues.value).to.be.equal('51');452 },453 },454 ]);455 });456329457 itWeb3('Events emitted for transfer()', async ({web3, privateKeyWrapper}) => {330 event = events[1];458 const collection = await createCollectionExpectSuccess({331 expect(event.event).to.be.equal('Approval');332 expect(event.address).to.be.equal(collectionAddress);459 mode: {type: 'Fungible', decimalPoints: 0},333 expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));460 });334 expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(bob.address));461 const alice = privateKeyWrapper('//Alice');335 expect(event.returnValues.value).to.be.equal('49');462463 const receiver = createEthAccount(web3);336 });464337465 await createFungibleItemExpectSuccess(alice, collection, {Value: 200n});338 itEth('Events emitted for transfer()', async ({helper}) => {339 const receiver = helper.eth.createAccount();340 const collection = await helper.ft.mintCollection(alice);341 await collection.mint(alice, 200n);466342467 const address = collectionIdToAddress(collection);343 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);468 const contract = new web3.eth.Contract(fungibleAbi as any, address);344 const contract = helper.ethNativeContract.collection(collectionAddress, 'ft');469345470 const events = await recordEvents(contract, async () => {346 const events: any = [];347 contract.events.allEvents((_: any, event: any) => {471 await transferExpectSuccess(collection, 0, alice, {Ethereum:receiver}, 51, 'Fungible');348 events.push(event);472 });349 });350 await collection.transfer(alice, {Ethereum:receiver}, 51n);473351474 expect(events).to.be.deep.equal([352 const event = events[0];475 {476 address,477 event: 'Transfer',353 expect(event.event).to.be.equal('Transfer');478 args: {354 expect(event.address).to.be.equal(collectionAddress);479 from: subToEth(alice.address),355 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));480 to: receiver,356 expect(event.returnValues.to).to.be.equal(receiver);481 value: '51',357 expect(event.returnValues.value).to.be.equal('51');482 },483 },484 ]);485 });358 });486});359});487360tests/src/eth/fungibleAbi.jsondiffbeforeafterboth58 "stateMutability": "nonpayable",58 "stateMutability": "nonpayable",59 "type": "function"59 "type": "function"60 },60 },61 {62 "inputs": [63 { "internalType": "uint256", "name": "newAdmin", "type": "uint256" }64 ],65 "name": "addCollectionAdminSubstrate",66 "outputs": [],67 "stateMutability": "nonpayable",68 "type": "function"69 },70 {61 {71 "inputs": [62 "inputs": [72 { "internalType": "address", "name": "user", "type": "address" }63 { "internalType": "address", "name": "user", "type": "address" }76 "stateMutability": "nonpayable",67 "stateMutability": "nonpayable",77 "type": "function"68 "type": "function"78 },69 },79 {80 "inputs": [81 { "internalType": "uint256", "name": "user", "type": "uint256" }82 ],83 "name": "addToCollectionAllowListSubstrate",84 "outputs": [],85 "stateMutability": "nonpayable",86 "type": "function"87 },88 {70 {89 "inputs": [71 "inputs": [90 { "internalType": "address", "name": "owner", "type": "address" },72 { "internalType": "address", "name": "owner", "type": "address" },218 "stateMutability": "view",200 "stateMutability": "view",219 "type": "function"201 "type": "function"220 },202 },221 {222 "inputs": [223 { "internalType": "uint256", "name": "user", "type": "uint256" }224 ],225 "name": "isOwnerOrAdminSubstrate",226 "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],227 "stateMutability": "view",228 "type": "function"229 },230 {203 {231 "inputs": [204 "inputs": [232 { "internalType": "address", "name": "to", "type": "address" },205 { "internalType": "address", "name": "to", "type": "address" },270 "stateMutability": "nonpayable",243 "stateMutability": "nonpayable",271 "type": "function"244 "type": "function"272 },245 },273 {274 "inputs": [275 { "internalType": "uint256", "name": "admin", "type": "uint256" }276 ],277 "name": "removeCollectionAdminSubstrate",278 "outputs": [],279 "stateMutability": "nonpayable",280 "type": "function"281 },282 {246 {283 "inputs": [],247 "inputs": [],284 "name": "removeCollectionSponsor",248 "name": "removeCollectionSponsor",295 "stateMutability": "nonpayable",259 "stateMutability": "nonpayable",296 "type": "function"260 "type": "function"297 },261 },298 {299 "inputs": [300 { "internalType": "uint256", "name": "user", "type": "uint256" }301 ],302 "name": "removeFromCollectionAllowListSubstrate",303 "outputs": [],304 "stateMutability": "nonpayable",305 "type": "function"306 },307 {262 {308 "inputs": [{ "internalType": "uint8", "name": "mode", "type": "uint8" }],263 "inputs": [{ "internalType": "uint8", "name": "mode", "type": "uint8" }],309 "name": "setCollectionAccess",264 "name": "setCollectionAccess",378 "stateMutability": "nonpayable",333 "stateMutability": "nonpayable",379 "type": "function"334 "type": "function"380 },335 },381 {382 "inputs": [383 { "internalType": "uint256", "name": "sponsor", "type": "uint256" }384 ],385 "name": "setCollectionSponsorSubstrate",386 "outputs": [],387 "stateMutability": "nonpayable",388 "type": "function"389 },390 {336 {391 "inputs": [337 "inputs": [392 { "internalType": "address", "name": "newOwner", "type": "address" }338 { "internalType": "address", "name": "newOwner", "type": "address" }396 "stateMutability": "nonpayable",342 "stateMutability": "nonpayable",397 "type": "function"343 "type": "function"398 },344 },399 {400 "inputs": [401 { "internalType": "uint256", "name": "newOwner", "type": "uint256" }402 ],403 "name": "setOwnerSubstrate",404 "outputs": [],405 "stateMutability": "nonpayable",406 "type": "function"407 },408 {345 {409 "inputs": [346 "inputs": [410 { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }347 { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }tests/src/eth/nonFungible.test.tsdiffbeforeafterboth14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE} from '../util/helpers';17import {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util/playgrounds';18import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';18import {IKeyringPair} from '@polkadot/types/types';19import nonFungibleAbi from './nonFungibleAbi.json';19import {Contract} from 'web3-eth-contract';20import {expect} from 'chai';21import {submitTransactionAsync} from '../substrate/substrate-api';222023describe('NFT: Information getting', () => {21describe('NFT: Information getting', () => {24 itWeb3('totalSupply', async ({api, web3, privateKeyWrapper}) => {22 let donor: IKeyringPair;23 let alice: IKeyringPair;2425 before(async function() {26 await usingEthPlaygrounds(async (helper, privateKey) => {25 const collection = await createCollectionExpectSuccess({27 donor = privateKey('//Alice');26 mode: {type: 'NFT'},28 [alice] = await helper.arrange.createAccounts([10n], donor);27 });29 });28 const alice = privateKeyWrapper('//Alice');30 });31 32 itEth('totalSupply', async ({helper}) => {29 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);33 const collection = await helper.nft.mintCollection(alice, {});34 await collection.mintToken(alice);303531 await createItemExpectSuccess(alice, collection, 'NFT', {Substrate: alice.address});36 const caller = await helper.eth.createAccountWithBalance(donor);323733 const address = collectionIdToAddress(collection);38 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);34 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});35 const totalSupply = await contract.methods.totalSupply().call();39 const totalSupply = await contract.methods.totalSupply().call();364037 expect(totalSupply).to.equal('1');41 expect(totalSupply).to.equal('1');38 });42 });394340 itWeb3('balanceOf', async ({api, web3, privateKeyWrapper}) => {44 itEth('balanceOf', async ({helper}) => {41 const collection = await createCollectionExpectSuccess({45 const collection = await helper.nft.mintCollection(alice, {});42 mode: {type: 'NFT'},43 });44 const alice = privateKeyWrapper('//Alice');46 const caller = await helper.eth.createAccountWithBalance(donor);454746 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);48 await collection.mintToken(alice, {Ethereum: caller});47 await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum:caller});48 await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: caller});49 await collection.mintToken(alice, {Ethereum: caller});49 await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: caller});50 await collection.mintToken(alice, {Ethereum: caller});505151 const address = collectionIdToAddress(collection);52 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);52 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});53 const balance = await contract.methods.balanceOf(caller).call();53 const balance = await contract.methods.balanceOf(caller).call();545455 expect(balance).to.equal('3');55 expect(balance).to.equal('3');56 });56 });575758 itWeb3('ownerOf', async ({api, web3, privateKeyWrapper}) => {58 itEth('ownerOf', async ({helper}) => {59 const collection = await createCollectionExpectSuccess({59 const collection = await helper.nft.mintCollection(alice, {});60 mode: {type: 'NFT'},61 });62 const alice = privateKeyWrapper('//Alice');60 const caller = await helper.eth.createAccountWithBalance(donor);636164 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);62 const token = await collection.mintToken(alice, {Ethereum: caller});65 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: caller});666367 const address = collectionIdToAddress(collection);64 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);68 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});69 const owner = await contract.methods.ownerOf(tokenId).call();706566 const owner = await contract.methods.ownerOf(token.tokenId).call();6771 expect(owner).to.equal(caller);68 expect(owner).to.equal(caller);72 });69 });73});70});747175describe('Check ERC721 token URI for NFT', () => {72describe('Check ERC721 token URI for NFT', () => {76 itWeb3('Empty tokenURI', async ({web3, api, privateKeyWrapper}) => {73 let donor: IKeyringPair;7475 before(async function() {76 await usingEthPlaygrounds(async (_helper, privateKey) => {77 donor = privateKey('//Alice');78 });79 });8081 async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {77 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);82 const owner = await helper.eth.createAccountWithBalance(donor);83 const receiver = helper.eth.createAccount();8478 const helper = evmCollectionHelpers(web3, owner);85 const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);79 let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', '').send();86 let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send();80 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);87 const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);81 const receiver = createEthAccount(web3);88 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);82 const contract = evmCollection(web3, owner, collectionIdAddress);83 89 84 const nextTokenId = await contract.methods.nextTokenId().call();90 const nextTokenId = await contract.methods.nextTokenId().call();85 expect(nextTokenId).to.be.equal('1');91 expect(nextTokenId).to.be.equal('1');88 nextTokenId,94 nextTokenId,89 ).send();95 ).send();909691 const events = normalizeEvents(result.events);97 if (propertyKey && propertyValue) {92 const address = collectionIdToAddress(collectionId);98 // Set URL or suffix99 await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();100 }9310194 expect(events).to.be.deep.equal([102 const event = result.events.Transfer;103 expect(event.address).to.be.equal(collectionAddress);95 {104 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');96 address,97 event: 'Transfer',98 args: {99 from: '0x0000000000000000000000000000000000000000',100 to: receiver,105 expect(event.returnValues.to).to.be.equal(receiver);101 tokenId: nextTokenId,106 expect(event.returnValues.tokenId).to.be.equal(nextTokenId);102 },103 },104 ]);105107108 return {contract, nextTokenId};109 }110111 itEth('Empty tokenURI', async ({helper}) => {112 const {contract, nextTokenId} = await setup(helper, '');106 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');113 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');107 });114 });108115109 itWeb3('TokenURI from url', async ({web3, api, privateKeyWrapper}) => {116 itEth('TokenURI from url', async ({helper}) => {110 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);117 const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');111 const helper = evmCollectionHelpers(web3, owner);112 let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();113 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);114 const receiver = createEthAccount(web3);115 const contract = evmCollection(web3, owner, collectionIdAddress);116 117 const nextTokenId = await contract.methods.nextTokenId().call();118 expect(nextTokenId).to.be.equal('1');119 result = await contract.methods.mint(120 receiver,121 nextTokenId,122 ).send();123 124 // Set URL125 await contract.methods.setProperty(nextTokenId, 'url', Buffer.from('Token URI')).send();126 127 const events = normalizeEvents(result.events);128 const address = collectionIdToAddress(collectionId);129130 expect(events).to.be.deep.equal([131 {132 address,133 event: 'Transfer',134 args: {135 from: '0x0000000000000000000000000000000000000000',136 to: receiver,137 tokenId: nextTokenId,138 },139 },140 ]);141142 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');118 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');143 });119 });144120145 itWeb3('TokenURI from baseURI + tokenId', async ({web3, api, privateKeyWrapper}) => {121 itEth('TokenURI from baseURI + tokenId', async ({helper}) => {146 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);122 const {contract, nextTokenId} = await setup(helper, 'BaseURI_');147 const helper = evmCollectionHelpers(web3, owner);148 let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();149 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);150 const receiver = createEthAccount(web3);151 const contract = evmCollection(web3, owner, collectionIdAddress);152 153 const nextTokenId = await contract.methods.nextTokenId().call();154 expect(nextTokenId).to.be.equal('1');155 result = await contract.methods.mint(156 receiver,157 nextTokenId,158 ).send();159 160 const events = normalizeEvents(result.events);161 const address = collectionIdToAddress(collectionId);162163 expect(events).to.be.deep.equal([164 {165 address,166 event: 'Transfer',167 args: {168 from: '0x0000000000000000000000000000000000000000',169 to: receiver,170 tokenId: nextTokenId,171 },172 },173 ]);174175 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);123 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);176 });124 });177125178 itWeb3('TokenURI from baseURI + suffix', async ({web3, api, privateKeyWrapper}) => {126 itEth('TokenURI from baseURI + suffix', async ({helper}) => {179 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);180 const helper = evmCollectionHelpers(web3, owner);181 let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();182 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);183 const receiver = createEthAccount(web3);184 const contract = evmCollection(web3, owner, collectionIdAddress);185 186 const nextTokenId = await contract.methods.nextTokenId().call();187 expect(nextTokenId).to.be.equal('1');188 result = await contract.methods.mint(189 receiver,190 nextTokenId,191 ).send();192 193 // Set suffix194 const suffix = '/some/suffix';127 const suffix = '/some/suffix';195 await contract.methods.setProperty(nextTokenId, 'suffix', Buffer.from(suffix)).send();128 const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);196197 const events = normalizeEvents(result.events);198 const address = collectionIdToAddress(collectionId);199200 expect(events).to.be.deep.equal([201 {202 address,203 event: 'Transfer',204 args: {205 from: '0x0000000000000000000000000000000000000000',206 to: receiver,207 tokenId: nextTokenId,208 },209 },210 ]);211212 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);129 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);213 });130 });214});131});215132216describe('NFT: Plain calls', () => {133describe('NFT: Plain calls', () => {217 itWeb3('Can perform mint()', async ({web3, api, privateKeyWrapper}) => {134 let donor: IKeyringPair;135 let alice: IKeyringPair;136137 before(async function() {138 await usingEthPlaygrounds(async (helper, privateKey) => {218 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);139 donor = privateKey('//Alice');219 const helper = evmCollectionHelpers(web3, owner);140 [alice] = await helper.arrange.createAccounts([10n], donor);220 let result = await helper.methods.createNonfungibleCollection('Mint collection', '6', '6').send();141 });142 });143144 itEth('Can perform mint()', async ({helper}) => {221 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);145 const owner = await helper.eth.createAccountWithBalance(donor);222 const receiver = createEthAccount(web3);146 const receiver = helper.eth.createAccount();147223 const contract = evmCollection(web3, owner, collectionIdAddress);148 const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Minty', '6', '6');149 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);224 const nextTokenId = await contract.methods.nextTokenId().call();150 const nextTokenId = await contract.methods.nextTokenId().call();225151226 expect(nextTokenId).to.be.equal('1');152 expect(nextTokenId).to.be.equal('1');227 result = await contract.methods.mintWithTokenURI(153 const result = await contract.methods.mintWithTokenURI(228 receiver,154 receiver,229 nextTokenId,155 nextTokenId,230 'Test URI',156 'Test URI',231 ).send();157 ).send();232158233 const events = normalizeEvents(result.events);159 const event = result.events.Transfer;160 expect(event.address).to.be.equal(collectionAddress);234 const address = collectionIdToAddress(collectionId);161 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');162 expect(event.returnValues.to).to.be.equal(receiver);163 expect(event.returnValues.tokenId).to.be.equal(nextTokenId);235164236 expect(events).to.be.deep.equal([237 {238 address,239 event: 'Transfer',240 args: {241 from: '0x0000000000000000000000000000000000000000',242 to: receiver,243 tokenId: nextTokenId,244 },245 },246 ]);247248 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');165 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');249166250 // TODO: this wont work right now, need release 919000 first167 // TODO: this wont work right now, need release 919000 first254 });171 });255172256 //TODO: CORE-302 add eth methods173 //TODO: CORE-302 add eth methods257 itWeb3.skip('Can perform mintBulk()', async ({web3, api, privateKeyWrapper}) => {174 /* todo:playgrounds skipped test!175 itWeb3.skip('Can perform mintBulk()', async ({helper}) => {258 const collection = await createCollectionExpectSuccess({176 const collection = await createCollectionExpectSuccess({259 mode: {type: 'NFT'},177 mode: {type: 'NFT'},260 });178 });316 expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');234 expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');317 }235 }318 });236 });237 */319238320 itWeb3('Can perform burn()', async ({web3, api, privateKeyWrapper}) => {239 itEth('Can perform burn()', async ({helper}) => {321 const collection = await createCollectionExpectSuccess({240 const caller = await helper.eth.createAccountWithBalance(donor);322 mode: {type: 'NFT'},323 });324 const alice = privateKeyWrapper('//Alice');325241326 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);242 const collection = await helper.nft.mintCollection(alice, {});243 const {tokenId} = await collection.mintToken(alice, {Ethereum: caller});327244328 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});245 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);246 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', caller);329247330 const address = collectionIdToAddress(collection);331 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});332333 {248 {334 const result = await contract.methods.burn(tokenId).send({from: owner});249 const result = await contract.methods.burn(tokenId).send({from: caller});335 const events = normalizeEvents(result.events);250 336251 const event = result.events.Transfer;337 expect(events).to.be.deep.equal([252 expect(event.address).to.be.equal(collectionAddress);338 {253 expect(event.returnValues.from).to.be.equal(caller);339 address,340 event: 'Transfer',341 args: {342 from: owner,343 to: '0x0000000000000000000000000000000000000000',254 expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');344 tokenId: tokenId.toString(),255 expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);345 },346 },347 ]);348 }256 }349 });257 });350258351 itWeb3('Can perform approve()', async ({web3, api, privateKeyWrapper}) => {259 itEth('Can perform approve()', async ({helper}) => {352 const collection = await createCollectionExpectSuccess({260 const owner = await helper.eth.createAccountWithBalance(donor);353 mode: {type: 'NFT'},354 });355 const alice = privateKeyWrapper('//Alice');261 const spender = helper.eth.createAccount();356262357 const owner = createEthAccount(web3);263 const collection = await helper.nft.mintCollection(alice, {});358 await transferBalanceToEth(api, alice, owner);264 const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});359265360 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});266 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);267 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);361268362 const spender = createEthAccount(web3);363364 const address = collectionIdToAddress(collection);365 const contract = new web3.eth.Contract(nonFungibleAbi as any, address);366367 {269 {368 const result = await contract.methods.approve(spender, tokenId).send({from: owner, ...GAS_ARGS});270 const result = await contract.methods.approve(spender, tokenId).send({from: owner});369 const events = normalizeEvents(result.events);370271371 expect(events).to.be.deep.equal([272 const event = result.events.Approval;372 {373 address,273 expect(event.address).to.be.equal(collectionAddress);374 event: 'Approval',274 expect(event.returnValues.owner).to.be.equal(owner);375 args: {376 owner,377 approved: spender,275 expect(event.returnValues.approved).to.be.equal(spender);378 tokenId: tokenId.toString(),276 expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);379 },380 },381 ]);382 }277 }383 });278 });384279385 itWeb3('Can perform transferFrom()', async ({web3, api, privateKeyWrapper}) => {280 itEth('Can perform transferFrom()', async ({helper}) => {386 const collection = await createCollectionExpectSuccess({281 const owner = await helper.eth.createAccountWithBalance(donor);387 mode: {type: 'NFT'},282 const spender = await helper.eth.createAccountWithBalance(donor);388 });389 const alice = privateKeyWrapper('//Alice');283 const receiver = helper.eth.createAccount();390284391 const owner = createEthAccount(web3);285 const collection = await helper.nft.mintCollection(alice, {});392 await transferBalanceToEth(api, alice, owner);286 const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});393287394 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});288 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);289 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);395290396 const spender = createEthAccount(web3);397 await transferBalanceToEth(api, alice, spender);398399 const receiver = createEthAccount(web3);400401 const address = collectionIdToAddress(collection);402 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});403404 await contract.methods.approve(spender, tokenId).send({from: owner});291 await contract.methods.approve(spender, tokenId).send({from: owner});405292406 {293 {407 const result = await contract.methods.transferFrom(owner, receiver, tokenId).send({from: spender});294 const result = await contract.methods.transferFrom(owner, receiver, tokenId).send({from: spender});295408 const events = normalizeEvents(result.events);296 const event = result.events.Transfer;409 expect(events).to.be.deep.equal([297 expect(event.address).to.be.equal(collectionAddress);410 {298 expect(event.returnValues.from).to.be.equal(owner);411 address,412 event: 'Transfer',413 args: {414 from: owner,415 to: receiver,299 expect(event.returnValues.to).to.be.equal(receiver);416 tokenId: tokenId.toString(),300 expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);417 },418 },419 ]);420 }301 }421302422 {303 {430 }311 }431 });312 });432313433 itWeb3('Can perform transfer()', async ({web3, api, privateKeyWrapper}) => {314 itEth('Can perform transfer()', async ({helper}) => {434 const collection = await createCollectionExpectSuccess({315 const collection = await helper.nft.mintCollection(alice, {});435 mode: {type: 'NFT'},316 const owner = await helper.eth.createAccountWithBalance(donor);436 });437 const alice = privateKeyWrapper('//Alice');317 const receiver = helper.eth.createAccount();438318439 const owner = createEthAccount(web3);319 const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});440 await transferBalanceToEth(api, alice, owner);441320442 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});321 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);322 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);443323444 const receiver = createEthAccount(web3);445 await transferBalanceToEth(api, alice, receiver);446447 const address = collectionIdToAddress(collection);448 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});449450 {324 {451 const result = await contract.methods.transfer(receiver, tokenId).send({from: owner});325 const result = await contract.methods.transfer(receiver, tokenId).send({from: owner});326452 const events = normalizeEvents(result.events);327 const event = result.events.Transfer;453 expect(events).to.be.deep.equal([328 expect(event.address).to.be.equal(collectionAddress);454 {329 expect(event.returnValues.from).to.be.equal(owner);455 address,456 event: 'Transfer',457 args: {458 from: owner,459 to: receiver,330 expect(event.returnValues.to).to.be.equal(receiver);460 tokenId: tokenId.toString(),331 expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);461 },462 },463 ]);464 }332 }465333466 {334 {476});344});477345478describe('NFT: Fees', () => {346describe('NFT: Fees', () => {479 itWeb3('approve() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {347 let donor: IKeyringPair;348 let alice: IKeyringPair;349350 before(async function() {351 await usingEthPlaygrounds(async (helper, privateKey) => {480 const collection = await createCollectionExpectSuccess({352 donor = privateKey('//Alice');481 mode: {type: 'NFT'},353 [alice] = await helper.arrange.createAccounts([10n], donor);482 });354 });483 const alice = privateKeyWrapper('//Alice');355 });356 357 itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {358 const owner = await helper.eth.createAccountWithBalance(donor);359 const spender = helper.eth.createAccount();484360485 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);361 const collection = await helper.nft.mintCollection(alice, {});486 const spender = createEthAccount(web3);362 const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});487363488 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});364 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);489365490 const address = collectionIdToAddress(collection);366 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, tokenId).send({from: owner}));491 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});492493 const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, tokenId).send({from: owner}));494 expect(cost < BigInt(0.2 * Number(UNIQUE)));367 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));495 });368 });496369497 itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {370 itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {498 const collection = await createCollectionExpectSuccess({371 const owner = await helper.eth.createAccountWithBalance(donor);499 mode: {type: 'NFT'},500 });501 const alice = privateKeyWrapper('//Alice');372 const spender = await helper.eth.createAccountWithBalance(donor);502373503 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);374 const collection = await helper.nft.mintCollection(alice, {});504 const spender = await createEthAccountWithBalance(api, web3, privateKeyWrapper);375 const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});505376506 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});377 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);507378508 const address = collectionIdToAddress(collection);509 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});510511 await contract.methods.approve(spender, tokenId).send({from: owner});379 await contract.methods.approve(spender, tokenId).send({from: owner});512380513 const cost = await recordEthFee(api, spender, () => contract.methods.transferFrom(owner, spender, tokenId).send({from: spender}));381 const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, tokenId).send({from: spender}));514 expect(cost < BigInt(0.2 * Number(UNIQUE)));382 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));515 });383 });516384517 itWeb3('transfer() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {385 itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {518 const collection = await createCollectionExpectSuccess({386 const owner = await helper.eth.createAccountWithBalance(donor);519 mode: {type: 'NFT'},520 });521 const alice = privateKeyWrapper('//Alice');387 const receiver = helper.eth.createAccount();522388523 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);389 const collection = await helper.nft.mintCollection(alice, {});524 const receiver = createEthAccount(web3);390 const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});525391526 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});392 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);527393528 const address = collectionIdToAddress(collection);394 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, tokenId).send({from: owner}));529 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});530531 const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, tokenId).send({from: owner}));532 expect(cost < BigInt(0.2 * Number(UNIQUE)));395 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));533 });396 });534});397});535398536describe('NFT: Substrate calls', () => {399describe('NFT: Substrate calls', () => {537 itWeb3('Events emitted for mint()', async ({web3, privateKeyWrapper}) => {400 let donor: IKeyringPair;538 const collection = await createCollectionExpectSuccess({539 mode: {type: 'NFT'},540 });541 const alice = privateKeyWrapper('//Alice');401 let alice: IKeyringPair;542402543 const address = collectionIdToAddress(collection);403 before(async function() {544 const contract = new web3.eth.Contract(nonFungibleAbi as any, address);404 await usingEthPlaygrounds(async (helper, privateKey) => {545546 let tokenId: number;547 const events = await recordEvents(contract, async () => {405 donor = privateKey('//Alice');548 tokenId = await createItemExpectSuccess(alice, collection, 'NFT');406 [alice] = await helper.arrange.createAccounts([20n], donor);549 });407 });550551 expect(events).to.be.deep.equal([552 {553 address,554 event: 'Transfer',555 args: {556 from: '0x0000000000000000000000000000000000000000',557 to: subToEth(alice.address),558 tokenId: tokenId!.toString(),559 },560 },561 ]);562 });408 });563409564 itWeb3('Events emitted for burn()', async ({web3, privateKeyWrapper}) => {410 itEth('Events emitted for mint()', async ({helper}) => {565 const collection = await createCollectionExpectSuccess({411 const collection = await helper.nft.mintCollection(alice, {});566 mode: {type: 'NFT'},412 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);567 });568 const alice = privateKeyWrapper('//Alice');413 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');569414570 const address = collectionIdToAddress(collection);415 const events: any = [];571 const contract = new web3.eth.Contract(nonFungibleAbi as any, address);416 contract.events.allEvents((_: any, event: any) => {572573 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT');574 const events = await recordEvents(contract, async () => {575 await burnItemExpectSuccess(alice, collection, tokenId);417 events.push(event);576 });418 });419 const {tokenId} = await collection.mintToken(alice);577420578 expect(events).to.be.deep.equal([421 const event = events[0];579 {580 address,581 event: 'Transfer',422 expect(event.event).to.be.equal('Transfer');582 args: {423 expect(event.address).to.be.equal(collectionAddress);583 from: subToEth(alice.address),584 to: '0x0000000000000000000000000000000000000000',424 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');585 tokenId: tokenId.toString(),425 expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(alice.address));586 },587 },588 ]);426 expect(event.returnValues.tokenId).to.be.equal(tokenId.toString());589 });427 });590428591 itWeb3('Events emitted for approve()', async ({web3, privateKeyWrapper}) => {429 itEth('Events emitted for burn()', async ({helper}) => {592 const collection = await createCollectionExpectSuccess({430 const collection = await helper.nft.mintCollection(alice, {});593 mode: {type: 'NFT'},431 const token = await collection.mintToken(alice);432433 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);434 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');435 436 const events: any = [];437 contract.events.allEvents((_: any, event: any) => {438 events.push(event);594 });439 });595 const alice = privateKeyWrapper('//Alice');596440597 const receiver = createEthAccount(web3);441 await token.burn(alice);598442599 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT');443 const event = events[0];444 expect(event.event).to.be.equal('Transfer');445 expect(event.address).to.be.equal(collectionAddress);446 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));447 expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');448 expect(event.returnValues.tokenId).to.be.equal(token.tokenId.toString());449 });600450601 const address = collectionIdToAddress(collection);451 itEth('Events emitted for approve()', async ({helper}) => {602 const contract = new web3.eth.Contract(nonFungibleAbi as any, address);452 const receiver = helper.eth.createAccount();603453604 const events = await recordEvents(contract, async () => {454 const collection = await helper.nft.mintCollection(alice, {});605 await approveExpectSuccess(collection, tokenId, alice, {Ethereum: receiver}, 1);455 const token = await collection.mintToken(alice);606 });607456608 expect(events).to.be.deep.equal([457 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);609 {458 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');610 address,611 event: 'Approval',612 args: {613 owner: subToEth(alice.address),614 approved: receiver,459 615 tokenId: tokenId.toString(),460 const events: any = [];616 },617 },618 ]);619 });461 contract.events.allEvents((_: any, event: any) => {620621 itWeb3('Events emitted for transferFrom()', async ({web3, privateKeyWrapper}) => {622 const collection = await createCollectionExpectSuccess({462 events.push(event);623 mode: {type: 'NFT'},624 });463 });625 const alice = privateKeyWrapper('//Alice');626 const bob = privateKeyWrapper('//Bob');627464628 const receiver = createEthAccount(web3);465 await token.approve(alice, {Ethereum: receiver});629466630 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT');467 const event = events[0];468 expect(event.event).to.be.equal('Approval');631 await approveExpectSuccess(collection, tokenId, alice, bob.address, 1);469 expect(event.address).to.be.equal(collectionAddress);470 expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));471 expect(event.returnValues.approved).to.be.equal(receiver);472 expect(event.returnValues.tokenId).to.be.equal(token.tokenId.toString());473 });632474633 const address = collectionIdToAddress(collection);475 itEth('Events emitted for transferFrom()', async ({helper}) => {476 const [bob] = await helper.arrange.createAccounts([10n], donor);634 const contract = new web3.eth.Contract(nonFungibleAbi as any, address);477 const receiver = helper.eth.createAccount();635478636 const events = await recordEvents(contract, async () => {479 const collection = await helper.nft.mintCollection(alice, {});480 const token = await collection.mintToken(alice);481 await token.approve(alice, {Substrate: bob.address});482637 await transferFromExpectSuccess(collection, tokenId, bob, alice, {Ethereum: receiver}, 1, 'NFT');483 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);484 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');485 486 const events: any = [];487 contract.events.allEvents((_: any, event: any) => {488 events.push(event);638 });489 });639490640 expect(events).to.be.deep.equal([491 await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver});641 {642 address,643 event: 'Transfer',492 644 args: {493 const event = events[0];645 from: subToEth(alice.address),494 expect(event.address).to.be.equal(collectionAddress);495 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));646 to: receiver,496 expect(event.returnValues.to).to.be.equal(receiver);647 tokenId: tokenId.toString(),497 expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);648 },649 },650 ]);651 });498 });652499653 itWeb3('Events emitted for transfer()', async ({web3, privateKeyWrapper}) => {500 itEth('Events emitted for transfer()', async ({helper}) => {654 const collection = await createCollectionExpectSuccess({501 const receiver = helper.eth.createAccount();655 mode: {type: 'NFT'},656 });657 const alice = privateKeyWrapper('//Alice');658502659 const receiver = createEthAccount(web3);503 const collection = await helper.nft.mintCollection(alice, {});504 const token = await collection.mintToken(alice);660505661 const tokenId = await createItemExpectSuccess(alice, collection, 'NFT');506 const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);662663 const address = collectionIdToAddress(collection);507 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');664 const contract = new web3.eth.Contract(nonFungibleAbi as any, address);508 665509 const events: any = [];666 const events = await recordEvents(contract, async () => {510 contract.events.allEvents((_: any, event: any) => {667 await transferExpectSuccess(collection, tokenId, alice, {Ethereum: receiver}, 1, 'NFT');511 events.push(event);668 });512 });669513670 expect(events).to.be.deep.equal([514 await token.transfer(alice, {Ethereum: receiver});671 {515 672 address,516 const event = events[0];673 event: 'Transfer',517 expect(event.address).to.be.equal(collectionAddress);674 args: {518 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));675 from: subToEth(alice.address),676 to: receiver,519 expect(event.returnValues.to).to.be.equal(receiver);677 tokenId: tokenId.toString(),520 expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);678 },679 },680 ]);681 });521 });682});522});683523684describe('Common metadata', () => {524describe('Common metadata', () => {685 itWeb3('Returns collection name', async ({api, web3, privateKeyWrapper}) => {525 let donor: IKeyringPair;526 let alice: IKeyringPair;527528 before(async function() {686 const collection = await createCollectionExpectSuccess({529 await usingEthPlaygrounds(async (helper, privateKey) => {687 name: 'token name',530 donor = privateKey('//Alice');688 mode: {type: 'NFT'},531 [alice] = await helper.arrange.createAccounts([20n], donor);689 });532 });690 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);533 });691534692 const address = collectionIdToAddress(collection);535 itEth('Returns collection name', async ({helper}) => {693 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});536 const caller = await helper.eth.createAccountWithBalance(donor);694 const name = await contract.methods.name().call();537 const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});695538696 expect(name).to.equal('token name');539 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);540 const name = await contract.methods.name().call();541 expect(name).to.equal('oh River');697 });542 });698543699 itWeb3('Returns symbol name', async ({api, web3, privateKeyWrapper}) => {544 itEth('Returns symbol name', async ({helper}) => {700 const collection = await createCollectionExpectSuccess({545 const caller = await helper.eth.createAccountWithBalance(donor);701 tokenPrefix: 'TOK',702 mode: {type: 'NFT'},703 });704 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);546 const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});705547706 const address = collectionIdToAddress(collection);548 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);707 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});708 const symbol = await contract.methods.symbol().call();549 const symbol = await contract.methods.symbol().call();709710 expect(symbol).to.equal('TOK');550 expect(symbol).to.equal('CHANGE');711 });551 });712});552});tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth89 "stateMutability": "nonpayable",89 "stateMutability": "nonpayable",90 "type": "function"90 "type": "function"91 },91 },92 {93 "inputs": [94 { "internalType": "uint256", "name": "newAdmin", "type": "uint256" }95 ],96 "name": "addCollectionAdminSubstrate",97 "outputs": [],98 "stateMutability": "nonpayable",99 "type": "function"100 },101 {92 {102 "inputs": [93 "inputs": [103 { "internalType": "address", "name": "user", "type": "address" }94 { "internalType": "address", "name": "user", "type": "address" }107 "stateMutability": "nonpayable",98 "stateMutability": "nonpayable",108 "type": "function"99 "type": "function"109 },100 },110 {111 "inputs": [112 { "internalType": "uint256", "name": "user", "type": "uint256" }113 ],114 "name": "addToCollectionAllowListSubstrate",115 "outputs": [],116 "stateMutability": "nonpayable",117 "type": "function"118 },119 {101 {120 "inputs": [102 "inputs": [121 { "internalType": "address", "name": "user", "type": "address" }103 { "internalType": "address", "name": "user", "type": "address" }277 "stateMutability": "view",259 "stateMutability": "view",278 "type": "function"260 "type": "function"279 },261 },280 {281 "inputs": [282 { "internalType": "uint256", "name": "user", "type": "uint256" }283 ],284 "name": "isOwnerOrAdminSubstrate",285 "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],286 "stateMutability": "view",287 "type": "function"288 },289 {262 {290 "inputs": [263 "inputs": [291 { "internalType": "address", "name": "to", "type": "address" },264 { "internalType": "address", "name": "to", "type": "address" },384 "stateMutability": "nonpayable",357 "stateMutability": "nonpayable",385 "type": "function"358 "type": "function"386 },359 },387 {388 "inputs": [389 { "internalType": "uint256", "name": "admin", "type": "uint256" }390 ],391 "name": "removeCollectionAdminSubstrate",392 "outputs": [],393 "stateMutability": "nonpayable",394 "type": "function"395 },396 {360 {397 "inputs": [],361 "inputs": [],398 "name": "removeCollectionSponsor",362 "name": "removeCollectionSponsor",409 "stateMutability": "nonpayable",373 "stateMutability": "nonpayable",410 "type": "function"374 "type": "function"411 },375 },412 {413 "inputs": [414 { "internalType": "uint256", "name": "user", "type": "uint256" }415 ],416 "name": "removeFromCollectionAllowListSubstrate",417 "outputs": [],418 "stateMutability": "nonpayable",419 "type": "function"420 },421 {376 {422 "inputs": [377 "inputs": [423 { "internalType": "address", "name": "from", "type": "address" },378 { "internalType": "address", "name": "from", "type": "address" },525 "stateMutability": "nonpayable",480 "stateMutability": "nonpayable",526 "type": "function"481 "type": "function"527 },482 },528 {529 "inputs": [530 { "internalType": "uint256", "name": "sponsor", "type": "uint256" }531 ],532 "name": "setCollectionSponsorSubstrate",533 "outputs": [],534 "stateMutability": "nonpayable",535 "type": "function"536 },537 {483 {538 "inputs": [484 "inputs": [539 { "internalType": "address", "name": "newOwner", "type": "address" }485 { "internalType": "address", "name": "newOwner", "type": "address" }543 "stateMutability": "nonpayable",489 "stateMutability": "nonpayable",544 "type": "function"490 "type": "function"545 },491 },546 {547 "inputs": [548 { "internalType": "uint256", "name": "newOwner", "type": "uint256" }549 ],550 "name": "setOwnerSubstrate",551 "outputs": [],552 "stateMutability": "nonpayable",553 "type": "function"554 },555 {492 {556 "inputs": [493 "inputs": [557 { "internalType": "uint256", "name": "tokenId", "type": "uint256" },494 { "internalType": "uint256", "name": "tokenId", "type": "uint256" },tests/src/eth/payable.test.tsdiffbeforeafterboth50 await helper.eth.transferBalanceFromSubstrate(alice, helper.address.substrateToEth(alice.address), 5n);50 await helper.eth.transferBalanceFromSubstrate(alice, helper.address.substrateToEth(alice.address), 5n);5151525253 await helper.eth.callEVM(alice, contract.options.address, contract.methods.giveMoney().encodeABI(), weiCount);53 await helper.eth.sendEVM(alice, contract.options.address, contract.methods.giveMoney().encodeABI(), weiCount);545455 expect(await contract.methods.getCollected().call()).to.be.equal(weiCount);55 expect(await contract.methods.getCollected().call()).to.be.equal(weiCount);56 });56 });tests/src/eth/reFungible.test.tsdiffbeforeafterboth14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617import {createCollectionExpectSuccess, UNIQUE, requirePallets, Pallets} from '../util/helpers';17import {Pallets, requirePalletsOrSkip} from '../util/playgrounds';18import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, tokenIdToAddress, uniqueRefungibleToken} from './util/helpers';18import {expect, itEth, usingEthPlaygrounds} from './util/playgrounds';19import {expect} from 'chai';19import {IKeyringPair} from '@polkadot/types/types';202021describe('Refungible: Information getting', () => {21describe('Refungible: Information getting', () => {22 let donor: IKeyringPair;2322 before(async function() {24 before(async function() {23 await requirePallets(this, [Pallets.ReFungible]);25 await usingEthPlaygrounds(async (helper, privateKey) => {26 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);2728 donor = privateKey('//Alice');29 });24 });30 });253126 itWeb3('totalSupply', async ({api, web3, privateKeyWrapper}) => {32 itEth('totalSupply', async ({helper}) => {27 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);33 const caller = await helper.eth.createAccountWithBalance(donor);28 const helper = evmCollectionHelpers(web3, caller);29 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();34 const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TotalSupply', '6', '6');30 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);35 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);31 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});32 const nextTokenId = await contract.methods.nextTokenId().call();36 const nextTokenId = await contract.methods.nextTokenId().call();33 await contract.methods.mint(caller, nextTokenId).send();37 await contract.methods.mint(caller, nextTokenId).send();34 const totalSupply = await contract.methods.totalSupply().call();38 const totalSupply = await contract.methods.totalSupply().call();35 expect(totalSupply).to.equal('1');39 expect(totalSupply).to.equal('1');36 });40 });374138 itWeb3('balanceOf', async ({api, web3, privateKeyWrapper}) => {42 itEth('balanceOf', async ({helper}) => {39 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);43 const caller = await helper.eth.createAccountWithBalance(donor);40 const helper = evmCollectionHelpers(web3, caller);41 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();44 const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'BalanceOf', '6', '6');42 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);45 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);43 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});444645 {47 {46 const nextTokenId = await contract.methods.nextTokenId().call();48 const nextTokenId = await contract.methods.nextTokenId().call();56 }58 }575958 const balance = await contract.methods.balanceOf(caller).call();60 const balance = await contract.methods.balanceOf(caller).call();5960 expect(balance).to.equal('3');61 expect(balance).to.equal('3');61 });62 });626363 itWeb3('ownerOf', async ({api, web3, privateKeyWrapper}) => {64 itEth('ownerOf', async ({helper}) => {64 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);65 const caller = await helper.eth.createAccountWithBalance(donor);65 const helper = evmCollectionHelpers(web3, caller);66 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();66 const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf', '6', '6');67 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);67 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);68 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});696870 const tokenId = await contract.methods.nextTokenId().call();69 const tokenId = await contract.methods.nextTokenId().call();71 await contract.methods.mint(caller, tokenId).send();70 await contract.methods.mint(caller, tokenId).send();727173 const owner = await contract.methods.ownerOf(tokenId).call();72 const owner = await contract.methods.ownerOf(tokenId).call();7475 expect(owner).to.equal(caller);73 expect(owner).to.equal(caller);76 });74 });777578 itWeb3('ownerOf after burn', async ({api, web3, privateKeyWrapper}) => {76 itEth('ownerOf after burn', async ({helper}) => {79 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);77 const caller = await helper.eth.createAccountWithBalance(donor);80 const receiver = createEthAccount(web3);78 const receiver = helper.eth.createAccount();81 const helper = evmCollectionHelpers(web3, caller);79 const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf-AfterBurn', '6', '6');82 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();83 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);80 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);84 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});858186 const tokenId = await contract.methods.nextTokenId().call();82 const tokenId = await contract.methods.nextTokenId().call();87 await contract.methods.mint(caller, tokenId).send();83 await contract.methods.mint(caller, tokenId).send();84 const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);888589 const tokenAddress = tokenIdToAddress(collectionId, tokenId);90 const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);9192 await tokenContract.methods.repartition(2).send();86 await tokenContract.methods.repartition(2).send();93 await tokenContract.methods.transfer(receiver, 1).send();87 await tokenContract.methods.transfer(receiver, 1).send();948895 await tokenContract.methods.burnFrom(caller, 1).send();89 await tokenContract.methods.burnFrom(caller, 1).send();969097 const owner = await contract.methods.ownerOf(tokenId).call();91 const owner = await contract.methods.ownerOf(tokenId).call();9899 expect(owner).to.equal(receiver);92 expect(owner).to.equal(receiver);100 });93 });10194102 itWeb3('ownerOf for partial ownership', async ({api, web3, privateKeyWrapper}) => {95 itEth('ownerOf for partial ownership', async ({helper}) => {103 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);96 const caller = await helper.eth.createAccountWithBalance(donor);104 const receiver = createEthAccount(web3);97 const receiver = helper.eth.createAccount();105 const helper = evmCollectionHelpers(web3, caller);98 const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Partial-OwnerOf', '6', '6');106 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();107 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);99 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);108 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});109100110 const tokenId = await contract.methods.nextTokenId().call();101 const tokenId = await contract.methods.nextTokenId().call();111 await contract.methods.mint(caller, tokenId).send();102 await contract.methods.mint(caller, tokenId).send();103 const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);112104113 const tokenAddress = tokenIdToAddress(collectionId, tokenId);114 const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);115116 await tokenContract.methods.repartition(2).send();105 await tokenContract.methods.repartition(2).send();117 await tokenContract.methods.transfer(receiver, 1).send();106 await tokenContract.methods.transfer(receiver, 1).send();118107119 const owner = await contract.methods.ownerOf(tokenId).call();108 const owner = await contract.methods.ownerOf(tokenId).call();120121 expect(owner).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');109 expect(owner).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');122 });110 });123});111});124112125describe('Refungible: Plain calls', () => {113describe('Refungible: Plain calls', () => {114 let donor: IKeyringPair;115126 before(async function() {116 before(async function() {127 await requirePallets(this, [Pallets.ReFungible]);117 await usingEthPlaygrounds(async (helper, privateKey) => {118 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);119120 donor = privateKey('//Alice');121 });128 });122 });129123130 itWeb3('Can perform mint()', async ({web3, api, privateKeyWrapper}) => {124 itEth('Can perform mint()', async ({helper}) => {131 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);125 const owner = await helper.eth.createAccountWithBalance(donor);132 const helper = evmCollectionHelpers(web3, owner);126 const receiver = helper.eth.createAccount();133 let result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();127 const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Minty', '6', '6');134 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);128 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);135 const receiver = createEthAccount(web3);136 const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});129 137 const nextTokenId = await contract.methods.nextTokenId().call();130 const nextTokenId = await contract.methods.nextTokenId().call();138139 expect(nextTokenId).to.be.equal('1');131 expect(nextTokenId).to.be.equal('1');140 result = await contract.methods.mintWithTokenURI(132 const result = await contract.methods.mintWithTokenURI(141 receiver,133 receiver,142 nextTokenId,134 nextTokenId,143 'Test URI',135 'Test URI',144 ).send();136 ).send();145137146 const events = normalizeEvents(result.events);138 const event = result.events.Transfer;139 expect(event.address).to.equal(collectionAddress);140 expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');141 expect(event.returnValues.to).to.equal(receiver);142 expect(event.returnValues.tokenId).to.equal(nextTokenId);147143148 expect(events).to.include.deep.members([149 {150 address: collectionIdAddress,151 event: 'Transfer',152 args: {153 from: '0x0000000000000000000000000000000000000000',154 to: receiver,155 tokenId: nextTokenId,156 },157 },158 ]);159160 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');144 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');161 });145 });162146163 itWeb3('Can perform mintBulk()', async ({web3, api, privateKeyWrapper}) => {147 itEth('Can perform mintBulk()', async ({helper}) => {164 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);148 const owner = await helper.eth.createAccountWithBalance(donor);165 const helper = evmCollectionHelpers(web3, caller);149 const receiver = helper.eth.createAccount();166 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();150 const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'MintBulky', '6', '6');167 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);151 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);168 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});169152170 const receiver = createEthAccount(web3);171172 {153 {173 const nextTokenId = await contract.methods.nextTokenId().call();154 const nextTokenId = await contract.methods.nextTokenId().call();174 expect(nextTokenId).to.be.equal('1');155 expect(nextTokenId).to.be.equal('1');180 [+nextTokenId + 2, 'Test URI 2'],161 [+nextTokenId + 2, 'Test URI 2'],181 ],162 ],182 ).send();163 ).send();183 const events = normalizeEvents(result.events);184164185 expect(events).to.include.deep.members([165 const events = result.events.Transfer;186 {187 address: collectionIdAddress,188 event: 'Transfer',189 args: {166 for (let i = 0; i < 2; i++) {190 from: '0x0000000000000000000000000000000000000000',191 to: receiver,192 tokenId: nextTokenId,193 },194 },195 {196 address: collectionIdAddress,167 const event = events[i];197 event: 'Transfer',198 args: {199 from: '0x0000000000000000000000000000000000000000',168 expect(event.address).to.equal(collectionAddress);200 to: receiver,201 tokenId: String(+nextTokenId + 1),202 },169 expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');203 },204 {205 address: collectionIdAddress,206 event: 'Transfer',207 args: {208 from: '0x0000000000000000000000000000000000000000',209 to: receiver,170 expect(event.returnValues.to).to.equal(receiver);210 tokenId: String(+nextTokenId + 2),171 expect(event.returnValues.tokenId).to.equal(String(+nextTokenId + i));211 },172 }212 },213 ]);214173215 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');174 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');216 expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');175 expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');217 expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');176 expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');218 }177 }219 });178 });220179221 itWeb3('Can perform burn()', async ({web3, api, privateKeyWrapper}) => {180 itEth('Can perform burn()', async ({helper}) => {222 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);181 const caller = await helper.eth.createAccountWithBalance(donor);223 const helper = evmCollectionHelpers(web3, caller);224 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();182 const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Burny', '6', '6');225 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);183 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);226 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});227184228 const tokenId = await contract.methods.nextTokenId().call();185 const tokenId = await contract.methods.nextTokenId().call();229 await contract.methods.mint(caller, tokenId).send();186 await contract.methods.mint(caller, tokenId).send();230 {187 {231 const result = await contract.methods.burn(tokenId).send();188 const result = await contract.methods.burn(tokenId).send();232 const events = normalizeEvents(result.events);189 const event = result.events.Transfer;233 expect(events).to.include.deep.members([190 expect(event.address).to.equal(collectionAddress);234 {191 expect(event.returnValues.from).to.equal(caller);235 address: collectionIdAddress,236 event: 'Transfer',237 args: {238 from: caller,239 to: '0x0000000000000000000000000000000000000000',192 expect(event.returnValues.to).to.equal('0x0000000000000000000000000000000000000000');240 tokenId: tokenId.toString(),193 expect(event.returnValues.tokenId).to.equal(tokenId.toString());241 },242 },243 ]);244 }194 }245 });195 });246196247 itWeb3('Can perform transferFrom()', async ({web3, api, privateKeyWrapper}) => {197 itEth('Can perform transferFrom()', async ({helper}) => {248 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);198 const caller = await helper.eth.createAccountWithBalance(donor);249 const helper = evmCollectionHelpers(web3, caller);199 const receiver = helper.eth.createAccount();250 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();200 const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TransferFromy', '6', '6');251 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);201 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);252 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});253202254 const receiver = createEthAccount(web3);255256 const tokenId = await contract.methods.nextTokenId().call();203 const tokenId = await contract.methods.nextTokenId().call();204 const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);257 await contract.methods.mint(caller, tokenId).send();205 await contract.methods.mint(caller, tokenId).send();258206259 const address = tokenIdToAddress(collectionId, tokenId);207 const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);260 const tokenContract = uniqueRefungibleToken(web3, address, caller);261 await tokenContract.methods.repartition(15).send();208 await tokenContract.methods.repartition(15).send();262209263 {210 {264 const erc20Events = await recordEvents(tokenContract, async () => {211 const tokenEvents: any = [];265 const result = await contract.methods.transferFrom(caller, receiver, tokenId).send();266 const events = normalizeEvents(result.events);212 tokenContract.events.allEvents((_: any, event: any) => {267 expect(events).to.include.deep.members([268 {269 address: collectionIdAddress,270 event: 'Transfer',271 args: {272 from: caller,213 tokenEvents.push(event);273 to: receiver,274 tokenId: tokenId.toString(),275 },276 },277 ]);278 });214 });215 const result = await contract.methods.transferFrom(caller, receiver, tokenId).send();279216280 expect(erc20Events).to.include.deep.members([217 let event = result.events.Transfer;218 expect(event.address).to.equal(collectionAddress);281 {219 expect(event.returnValues.from).to.equal(caller);282 address,220 expect(event.returnValues.to).to.equal(receiver);283 event: 'Transfer',221 expect(event.returnValues.tokenId).to.equal(tokenId.toString());222284 args: {223 event = tokenEvents[0];285 from: caller,224 expect(event.address).to.equal(tokenAddress);225 expect(event.returnValues.from).to.equal(caller);286 to: receiver,226 expect(event.returnValues.to).to.equal(receiver);287 value: '15',227 expect(event.returnValues.value).to.equal('15');288 },289 },290 ]);291 }228 }292229293 {230 {301 }238 }302 });239 });303240304 itWeb3('Can perform transfer()', async ({web3, api, privateKeyWrapper}) => {241 itEth('Can perform transfer()', async ({helper}) => {305 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);242 const caller = await helper.eth.createAccountWithBalance(donor);306 const helper = evmCollectionHelpers(web3, caller);243 const receiver = helper.eth.createAccount();307 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();244 const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry', '6', '6');308 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);245 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);309 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});310246311 const receiver = createEthAccount(web3);312313 const tokenId = await contract.methods.nextTokenId().call();247 const tokenId = await contract.methods.nextTokenId().call();314 await contract.methods.mint(caller, tokenId).send();248 await contract.methods.mint(caller, tokenId).send();315249316 {250 {317 const result = await contract.methods.transfer(receiver, tokenId).send();251 const result = await contract.methods.transfer(receiver, tokenId).send();318 const events = normalizeEvents(result.events);252 253 const event = result.events.Transfer;319 expect(events).to.include.deep.members([254 expect(event.address).to.equal(collectionAddress);320 {255 expect(event.returnValues.from).to.equal(caller);321 address: collectionIdAddress,322 event: 'Transfer',323 args: {324 from: caller,325 to: receiver,256 expect(event.returnValues.to).to.equal(receiver);326 tokenId: tokenId.toString(),257 expect(event.returnValues.tokenId).to.equal(tokenId.toString());327 },328 },329 ]);330 }258 }331259332 {260 {340 }268 }341 });269 });342270343 itWeb3('transfer event on transfer from partial ownership to full ownership', async ({api, web3, privateKeyWrapper}) => {271 itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {344 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);272 const caller = await helper.eth.createAccountWithBalance(donor);345 const receiver = createEthAccount(web3);273 const receiver = helper.eth.createAccount();346 const helper = evmCollectionHelpers(web3, caller);274 const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Partial-to-Full', '6', '6');347 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();348 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);275 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);349 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});350276351 const tokenId = await contract.methods.nextTokenId().call();277 const tokenId = await contract.methods.nextTokenId().call();352 await contract.methods.mint(caller, tokenId).send();278 await contract.methods.mint(caller, tokenId).send();353279354 const tokenAddress = tokenIdToAddress(collectionId, tokenId);280 const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);355 const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);356281357 await tokenContract.methods.repartition(2).send();282 await tokenContract.methods.repartition(2).send();358 await tokenContract.methods.transfer(receiver, 1).send();283 await tokenContract.methods.transfer(receiver, 1).send();359284360 const events = await recordEvents(contract, async () =>285 const events: any = [];286 contract.events.allEvents((_: any, event: any) => {361 await tokenContract.methods.transfer(receiver, 1).send());287 events.push(event);362 expect(events).to.deep.equal([288 });289 await tokenContract.methods.transfer(receiver, 1).send();290363 {291 const event = events[0];364 address: collectionIdAddress,365 event: 'Transfer',292 expect(event.address).to.equal(collectionAddress);366 args: {293 expect(event.returnValues.from).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');367 from: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',368 to: receiver,294 expect(event.returnValues.to).to.equal(receiver);369 tokenId: tokenId.toString(),295 expect(event.returnValues.tokenId).to.equal(tokenId.toString());370 },371 },372 ]);373 });296 });374297375 itWeb3('transfer event on transfer from full ownership to partial ownership', async ({api, web3, privateKeyWrapper}) => {298 itEth('transfer event on transfer from full ownership to partial ownership', async ({helper}) => {376 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);299 const caller = await helper.eth.createAccountWithBalance(donor);377 const receiver = createEthAccount(web3);300 const receiver = helper.eth.createAccount();378 const helper = evmCollectionHelpers(web3, caller);301 const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Full-to-Partial', '6', '6');379 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();380 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);302 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);381 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});382303383 const tokenId = await contract.methods.nextTokenId().call();304 const tokenId = await contract.methods.nextTokenId().call();384 await contract.methods.mint(caller, tokenId).send();305 await contract.methods.mint(caller, tokenId).send();385306386 const tokenAddress = tokenIdToAddress(collectionId, tokenId);307 const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);387 const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);388308389 await tokenContract.methods.repartition(2).send();309 await tokenContract.methods.repartition(2).send();390310391 const events = await recordEvents(contract, async () =>311 const events: any = [];312 contract.events.allEvents((_: any, event: any) => {392 await tokenContract.methods.transfer(receiver, 1).send());313 events.push(event);314 });315 await tokenContract.methods.transfer(receiver, 1).send();393316394 expect(events).to.deep.equal([317 const event = events[0];395 {396 address: collectionIdAddress,318 expect(event.address).to.equal(collectionAddress);397 event: 'Transfer',319 expect(event.returnValues.from).to.equal(caller);398 args: {399 from: caller,400 to: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',320 expect(event.returnValues.to).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');401 tokenId: tokenId.toString(),321 expect(event.returnValues.tokenId).to.equal(tokenId.toString());402 },403 },404 ]);405 });322 });406});323});407324408describe('RFT: Fees', () => {325describe('RFT: Fees', () => {326 let donor: IKeyringPair;327409 before(async function() {328 before(async function() {410 await requirePallets(this, [Pallets.ReFungible]);329 await usingEthPlaygrounds(async (helper, privateKey) => {330 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);331332 donor = privateKey('//Alice');333 });411 });334 });412335413 itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {336 itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {414 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);337 const caller = await helper.eth.createAccountWithBalance(donor);415 const helper = evmCollectionHelpers(web3, caller);338 const receiver = helper.eth.createAccount();416 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();339 const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer-From', '6', '6');417 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);340 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);418 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});419341420 const receiver = createEthAccount(web3);421422 const tokenId = await contract.methods.nextTokenId().call();342 const tokenId = await contract.methods.nextTokenId().call();423 await contract.methods.mint(caller, tokenId).send();343 await contract.methods.mint(caller, tokenId).send();424344425 const cost = await recordEthFee(api, caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());345 const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());426 expect(cost < BigInt(0.2 * Number(UNIQUE)));346 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));427 expect(cost > 0n);347 expect(cost > 0n);428 });348 });429349430 itWeb3('transfer() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {350 itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {431 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);351 const caller = await helper.eth.createAccountWithBalance(donor);432 const helper = evmCollectionHelpers(web3, caller);352 const receiver = helper.eth.createAccount();433 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();353 const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer', '6', '6');434 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);354 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);435 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});436355437 const receiver = createEthAccount(web3);438439 const tokenId = await contract.methods.nextTokenId().call();356 const tokenId = await contract.methods.nextTokenId().call();440 await contract.methods.mint(caller, tokenId).send();357 await contract.methods.mint(caller, tokenId).send();441358442 const cost = await recordEthFee(api, caller, () => contract.methods.transfer(receiver, tokenId).send());359 const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transfer(receiver, tokenId).send());443 expect(cost < BigInt(0.2 * Number(UNIQUE)));360 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));444 expect(cost > 0n);361 expect(cost > 0n);445 });362 });446});363});447364448describe('Common metadata', () => {365describe('Common metadata', () => {366 let donor: IKeyringPair;367 let alice: IKeyringPair;368449 before(async function() {369 before(async function() {450 await requirePallets(this, [Pallets.ReFungible]);370 await usingEthPlaygrounds(async (helper, privateKey) => {451 });371 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);452372453 itWeb3('Returns collection name', async ({api, web3, privateKeyWrapper}) => {373 donor = privateKey('//Alice');454 const collection = await createCollectionExpectSuccess({374 [alice] = await helper.arrange.createAccounts([20n], donor);455 name: 'token name',456 mode: {type: 'ReFungible'},457 });375 });458 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);376 });459377460 const address = collectionIdToAddress(collection);378 itEth('Returns collection name', async ({helper}) => {379 const caller = helper.eth.createAccount();461 const contract = evmCollection(web3, caller, address, {type: 'ReFungible'});380 const collection = await helper.rft.mintCollection(alice, {name: 'Leviathan', tokenPrefix: '11'});381 382 const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);462 const name = await contract.methods.name().call();383 const name = await contract.methods.name().call();463464 expect(name).to.equal('token name');384 expect(name).to.equal('Leviathan');465 });385 });466386467 itWeb3('Returns symbol name', async ({api, web3, privateKeyWrapper}) => {387 itEth('Returns symbol name', async ({helper}) => {468 const collection = await createCollectionExpectSuccess({388 const caller = await helper.eth.createAccountWithBalance(donor);469 tokenPrefix: 'TOK',470 mode: {type: 'ReFungible'},471 });472 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);389 const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Leviathan', '', '12');473474 const address = collectionIdToAddress(collection);475 const contract = evmCollection(web3, caller, address, {type: 'ReFungible'});390 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);476 const symbol = await contract.methods.symbol().call();391 const symbol = await contract.methods.symbol().call();477478 expect(symbol).to.equal('TOK');392 expect(symbol).to.equal('12');479 });393 });480});394});481395tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth89 "stateMutability": "nonpayable",89 "stateMutability": "nonpayable",90 "type": "function"90 "type": "function"91 },91 },92 {93 "inputs": [94 { "internalType": "uint256", "name": "newAdmin", "type": "uint256" }95 ],96 "name": "addCollectionAdminSubstrate",97 "outputs": [],98 "stateMutability": "nonpayable",99 "type": "function"100 },101 {92 {102 "inputs": [93 "inputs": [103 { "internalType": "address", "name": "user", "type": "address" }94 { "internalType": "address", "name": "user", "type": "address" }107 "stateMutability": "nonpayable",98 "stateMutability": "nonpayable",108 "type": "function"99 "type": "function"109 },100 },110 {111 "inputs": [112 { "internalType": "uint256", "name": "user", "type": "uint256" }113 ],114 "name": "addToCollectionAllowListSubstrate",115 "outputs": [],116 "stateMutability": "nonpayable",117 "type": "function"118 },119 {101 {120 "inputs": [102 "inputs": [121 { "internalType": "address", "name": "user", "type": "address" }103 { "internalType": "address", "name": "user", "type": "address" }277 "stateMutability": "view",259 "stateMutability": "view",278 "type": "function"260 "type": "function"279 },261 },280 {281 "inputs": [282 { "internalType": "uint256", "name": "user", "type": "uint256" }283 ],284 "name": "isOwnerOrAdminSubstrate",285 "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],286 "stateMutability": "view",287 "type": "function"288 },289 {262 {290 "inputs": [263 "inputs": [291 { "internalType": "address", "name": "to", "type": "address" },264 { "internalType": "address", "name": "to", "type": "address" },384 "stateMutability": "nonpayable",357 "stateMutability": "nonpayable",385 "type": "function"358 "type": "function"386 },359 },387 {388 "inputs": [389 { "internalType": "uint256", "name": "admin", "type": "uint256" }390 ],391 "name": "removeCollectionAdminSubstrate",392 "outputs": [],393 "stateMutability": "nonpayable",394 "type": "function"395 },396 {360 {397 "inputs": [],361 "inputs": [],398 "name": "removeCollectionSponsor",362 "name": "removeCollectionSponsor",409 "stateMutability": "nonpayable",373 "stateMutability": "nonpayable",410 "type": "function"374 "type": "function"411 },375 },412 {413 "inputs": [414 { "internalType": "uint256", "name": "user", "type": "uint256" }415 ],416 "name": "removeFromCollectionAllowListSubstrate",417 "outputs": [],418 "stateMutability": "nonpayable",419 "type": "function"420 },421 {376 {422 "inputs": [377 "inputs": [423 { "internalType": "address", "name": "from", "type": "address" },378 { "internalType": "address", "name": "from", "type": "address" },525 "stateMutability": "nonpayable",480 "stateMutability": "nonpayable",526 "type": "function"481 "type": "function"527 },482 },528 {529 "inputs": [530 { "internalType": "uint256", "name": "sponsor", "type": "uint256" }531 ],532 "name": "setCollectionSponsorSubstrate",533 "outputs": [],534 "stateMutability": "nonpayable",535 "type": "function"536 },537 {483 {538 "inputs": [484 "inputs": [539 { "internalType": "address", "name": "newOwner", "type": "address" }485 { "internalType": "address", "name": "newOwner", "type": "address" }543 "stateMutability": "nonpayable",489 "stateMutability": "nonpayable",544 "type": "function"490 "type": "function"545 },491 },546 {547 "inputs": [548 { "internalType": "uint256", "name": "newOwner", "type": "uint256" }549 ],550 "name": "setOwnerSubstrate",551 "outputs": [],552 "stateMutability": "nonpayable",553 "type": "function"554 },555 {492 {556 "inputs": [493 "inputs": [557 { "internalType": "uint256", "name": "tokenId", "type": "uint256" },494 { "internalType": "uint256", "name": "tokenId", "type": "uint256" },tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE, requirePallets, Pallets} from '../util/helpers';17import {Pallets, requirePalletsOrSkip} from '../util/playgrounds';18import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createRFTCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';18import {EthUniqueHelper, expect, itEth, usingEthPlaygrounds} from './util/playgrounds';19import {IKeyringPair} from '@polkadot/types/types';20import {Contract} from 'web3-eth-contract';192120import chai from 'chai';21import chaiAsPromised from 'chai-as-promised';22chai.use(chaiAsPromised);23const expect = chai.expect;2425describe('Refungible token: Information getting', () => {22describe('Refungible token: Information getting', () => {23 let donor: IKeyringPair;24 let alice: IKeyringPair;2526 before(async function() {26 before(async function() {27 await requirePallets(this, [Pallets.ReFungible]);27 await usingEthPlaygrounds(async (helper, privateKey) => {28 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);2930 donor = privateKey('//Alice');31 [alice] = await helper.arrange.createAccounts([20n], donor);32 });28 });33 });293430 itWeb3('totalSupply', async ({api, web3, privateKeyWrapper}) => {35 itEth('totalSupply', async ({helper}) => {31 const alice = privateKeyWrapper('//Alice');36 const caller = await helper.eth.createAccountWithBalance(donor);37 const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});38 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});323933 const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;40 const contract = helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);3435 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);3637 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;3839 const address = tokenIdToAddress(collectionId, tokenId);40 const contract = uniqueRefungibleToken(web3, address, caller);41 const totalSupply = await contract.methods.totalSupply().call();41 const totalSupply = await contract.methods.totalSupply().call();4243 expect(totalSupply).to.equal('200');42 expect(totalSupply).to.equal('200');44 });43 });454446 itWeb3('balanceOf', async ({api, web3, privateKeyWrapper}) => {45 itEth('balanceOf', async ({helper}) => {47 const alice = privateKeyWrapper('//Alice');46 const caller = await helper.eth.createAccountWithBalance(donor);47 const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});48 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});484949 const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;50 const contract = helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);5051 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);5253 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;5455 const address = tokenIdToAddress(collectionId, tokenId);56 const contract = uniqueRefungibleToken(web3, address, caller);57 const balance = await contract.methods.balanceOf(caller).call();51 const balance = await contract.methods.balanceOf(caller).call();5859 expect(balance).to.equal('200');52 expect(balance).to.equal('200');60 });53 });615462 itWeb3('decimals', async ({api, web3, privateKeyWrapper}) => {55 itEth('decimals', async ({helper}) => {63 const alice = privateKeyWrapper('//Alice');56 const caller = await helper.eth.createAccountWithBalance(donor);57 const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});58 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});645965 const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;60 const contract = helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);6667 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);6869 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;7071 const address = tokenIdToAddress(collectionId, tokenId);72 const contract = uniqueRefungibleToken(web3, address, caller);73 const decimals = await contract.methods.decimals().call();61 const decimals = await contract.methods.decimals().call();7475 expect(decimals).to.equal('0');62 expect(decimals).to.equal('0');76 });63 });77});64});786579// FIXME: Need erc721 for ReFubgible.66// FIXME: Need erc721 for ReFubgible.80describe('Check ERC721 token URI for ReFungible', () => {67describe('Check ERC721 token URI for ReFungible', () => {68 let donor: IKeyringPair;6981 before(async function() {70 before(async function() {82 await requirePallets(this, [Pallets.ReFungible]);71 await usingEthPlaygrounds(async (helper, privateKey) => {72 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);7374 donor = privateKey('//Alice');75 });83 });76 });847785 itWeb3('Empty tokenURI', async ({web3, api, privateKeyWrapper}) => {78 async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {86 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);87 const helper = evmCollectionHelpers(web3, owner);79 const owner = await helper.eth.createAccountWithBalance(donor);88 let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', '').send();89 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);80 const receiver = helper.eth.createAccount();90 const receiver = createEthAccount(web3);91 const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});928182 const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);83 let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send();84 const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);85 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);86 93 const nextTokenId = await contract.methods.nextTokenId().call();87 const nextTokenId = await contract.methods.nextTokenId().call();94 expect(nextTokenId).to.be.equal('1');88 expect(nextTokenId).to.be.equal('1');95 result = await contract.methods.mint(89 result = await contract.methods.mint(96 receiver,90 receiver,97 nextTokenId,91 nextTokenId,98 ).send();92 ).send();9993100 const events = normalizeEvents(result.events);94 if (propertyKey && propertyValue) {101 const address = collectionIdToAddress(collectionId);95 // Set URL or suffix96 await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();97 }10298103 expect(events).to.be.deep.equal([99 const event = result.events.Transfer;100 expect(event.address).to.be.equal(collectionAddress);104 {101 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');105 address,106 event: 'Transfer',107 args: {108 from: '0x0000000000000000000000000000000000000000',109 to: receiver,102 expect(event.returnValues.to).to.be.equal(receiver);110 tokenId: nextTokenId,103 expect(event.returnValues.tokenId).to.be.equal(nextTokenId);111 },112 },113 ]);114104105 return {contract, nextTokenId};106 }107108 itEth('Empty tokenURI', async ({helper}) => {109 const {contract, nextTokenId} = await setup(helper, '');115 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');110 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');116 });111 });117112118 itWeb3('TokenURI from url', async ({web3, api, privateKeyWrapper}) => {113 itEth('TokenURI from url', async ({helper}) => {119 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);114 const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');120 const helper = evmCollectionHelpers(web3, owner);121 let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();122 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);123 const receiver = createEthAccount(web3);124 const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});125126 const nextTokenId = await contract.methods.nextTokenId().call();127 expect(nextTokenId).to.be.equal('1');128 result = await contract.methods.mint(129 receiver,130 nextTokenId,131 ).send();132133 // Set URL134 await contract.methods.setProperty(nextTokenId, 'url', Buffer.from('Token URI')).send();135136 const events = normalizeEvents(result.events);137 const address = collectionIdToAddress(collectionId);138139 expect(events).to.be.deep.equal([140 {141 address,142 event: 'Transfer',143 args: {144 from: '0x0000000000000000000000000000000000000000',145 to: receiver,146 tokenId: nextTokenId,147 },148 },149 ]);150151 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');115 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');152 });116 });153117154 itWeb3('TokenURI from baseURI + tokenId', async ({web3, api, privateKeyWrapper}) => {118 itEth('TokenURI from baseURI + tokenId', async ({helper}) => {155 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);119 const {contract, nextTokenId} = await setup(helper, 'BaseURI_');156 const helper = evmCollectionHelpers(web3, owner);157 let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();158 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);159 const receiver = createEthAccount(web3);160 const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});161162 const nextTokenId = await contract.methods.nextTokenId().call();163 expect(nextTokenId).to.be.equal('1');164 result = await contract.methods.mint(165 receiver,166 nextTokenId,167 ).send();168169 const events = normalizeEvents(result.events);170 const address = collectionIdToAddress(collectionId);171172 expect(events).to.be.deep.equal([173 {174 address,175 event: 'Transfer',176 args: {177 from: '0x0000000000000000000000000000000000000000',178 to: receiver,179 tokenId: nextTokenId,180 },181 },182 ]);183184 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);120 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);185 });121 });186122187 itWeb3('TokenURI from baseURI + suffix', async ({web3, api, privateKeyWrapper}) => {123 itEth('TokenURI from baseURI + suffix', async ({helper}) => {188 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);189 const helper = evmCollectionHelpers(web3, owner);190 let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();191 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);192 const receiver = createEthAccount(web3);193 const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});194195 const nextTokenId = await contract.methods.nextTokenId().call();196 expect(nextTokenId).to.be.equal('1');197 result = await contract.methods.mint(198 receiver,199 nextTokenId,200 ).send();201202 // Set suffix203 const suffix = '/some/suffix';124 const suffix = '/some/suffix';204 await contract.methods.setProperty(nextTokenId, 'suffix', Buffer.from(suffix)).send();125 const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);205206 const events = normalizeEvents(result.events);207 const address = collectionIdToAddress(collectionId);208209 expect(events).to.be.deep.equal([210 {211 address,212 event: 'Transfer',213 args: {214 from: '0x0000000000000000000000000000000000000000',215 to: receiver,216 tokenId: nextTokenId,217 },218 },219 ]);220221 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);126 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);222 });127 });223});128});224129225describe('Refungible: Plain calls', () => {130describe('Refungible: Plain calls', () => {131 let donor: IKeyringPair;132 let alice: IKeyringPair;133226 before(async function() {134 before(async function() {227 await requirePallets(this, [Pallets.ReFungible]);135 await usingEthPlaygrounds(async (helper, privateKey) => {136 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);137138 donor = privateKey('//Alice');139 [alice] = await helper.arrange.createAccounts([50n], donor);140 });228 });141 });229142230 itWeb3('Can perform approve()', async ({web3, api, privateKeyWrapper}) => {143 itEth('Can perform approve()', async ({helper}) => {231 const alice = privateKeyWrapper('//Alice');144 const owner = await helper.eth.createAccountWithBalance(donor);145 const spender = helper.eth.createAccount();146 const collection = await helper.rft.mintCollection(alice);147 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});232148233 const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;149 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);150 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);234151235 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);236237 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;238239 const address = tokenIdToAddress(collectionId, tokenId);240241 const spender = createEthAccount(web3);242243 const contract = uniqueRefungibleToken(web3, address, owner);244245 {152 {246 const result = await contract.methods.approve(spender, 100).send({from: owner});153 const result = await contract.methods.approve(spender, 100).send({from: owner});247 const events = normalizeEvents(result.events);154 const event = result.events.Approval;248249 expect(events).to.be.deep.equal([155 expect(event.address).to.be.equal(tokenAddress);250 {156 expect(event.returnValues.owner).to.be.equal(owner);251 address,252 event: 'Approval',253 args: {254 owner,255 spender,157 expect(event.returnValues.spender).to.be.equal(spender);256 value: '100',158 expect(event.returnValues.value).to.be.equal('100');257 },258 },259 ]);260 }159 }261160262 {161 {265 }164 }266 });165 });267166268 itWeb3('Can perform transferFrom()', async ({web3, api, privateKeyWrapper}) => {167 itEth('Can perform transferFrom()', async ({helper}) => {269 const alice = privateKeyWrapper('//Alice');168 const owner = await helper.eth.createAccountWithBalance(donor);169 const spender = await helper.eth.createAccountWithBalance(donor);170 const receiver = helper.eth.createAccount();171 const collection = await helper.rft.mintCollection(alice);172 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});270173271 const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;174 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);175 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);272176273 const owner = createEthAccount(web3);274 await transferBalanceToEth(api, alice, owner);275276 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;277278 const spender = createEthAccount(web3);279 await transferBalanceToEth(api, alice, spender);280281 const receiver = createEthAccount(web3);282283 const address = tokenIdToAddress(collectionId, tokenId);284 const contract = uniqueRefungibleToken(web3, address, owner);285286 await contract.methods.approve(spender, 100).send();177 await contract.methods.approve(spender, 100).send();287178288 {179 {289 const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});180 const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});290 const events = normalizeEvents(result.events);181 let event = result.events.Transfer;291 expect(events).to.include.deep.members([182 expect(event.address).to.be.equal(tokenAddress);292 {183 expect(event.returnValues.from).to.be.equal(owner);293 address,294 event: 'Transfer',295 args: {296 from: owner,297 to: receiver,184 expect(event.returnValues.to).to.be.equal(receiver);298 value: '49',185 expect(event.returnValues.value).to.be.equal('49');299 },186300 },187 event = result.events.Approval;301 {188 expect(event.address).to.be.equal(tokenAddress);302 address,303 event: 'Approval',189 expect(event.returnValues.owner).to.be.equal(owner);304 args: {305 owner,306 spender,190 expect(event.returnValues.spender).to.be.equal(spender);307 value: '51',191 expect(event.returnValues.value).to.be.equal('51');308 },309 },310 ]);311 }192 }312193313 {194 {321 }202 }322 });203 });323204324 itWeb3('Can perform transfer()', async ({web3, api, privateKeyWrapper}) => {205 itEth('Can perform transfer()', async ({helper}) => {325 const alice = privateKeyWrapper('//Alice');206 const owner = await helper.eth.createAccountWithBalance(donor);207 const receiver = helper.eth.createAccount();208 const collection = await helper.rft.mintCollection(alice);209 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});326210327 const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;211 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);212 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);328213329 const owner = createEthAccount(web3);330 await transferBalanceToEth(api, alice, owner);331332 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;333334 const receiver = createEthAccount(web3);335 await transferBalanceToEth(api, alice, receiver);336337 const address = tokenIdToAddress(collectionId, tokenId);338 const contract = uniqueRefungibleToken(web3, address, owner);339340 {214 {341 const result = await contract.methods.transfer(receiver, 50).send({from: owner});215 const result = await contract.methods.transfer(receiver, 50).send({from: owner});342 const events = normalizeEvents(result.events);216 const event = result.events.Transfer;343 expect(events).to.include.deep.members([217 expect(event.address).to.be.equal(tokenAddress);344 {218 expect(event.returnValues.from).to.be.equal(owner);345 address,346 event: 'Transfer',347 args: {348 from: owner,349 to: receiver,219 expect(event.returnValues.to).to.be.equal(receiver);350 value: '50',220 expect(event.returnValues.value).to.be.equal('50');351 },352 },353 ]);354 }221 }355222356 {223 {364 }231 }365 });232 });366233367 itWeb3('Can perform repartition()', async ({web3, api, privateKeyWrapper}) => {234 itEth('Can perform repartition()', async ({helper}) => {368 const alice = privateKeyWrapper('//Alice');235 const owner = await helper.eth.createAccountWithBalance(donor);236 const receiver = await helper.eth.createAccountWithBalance(donor);237 const collection = await helper.rft.mintCollection(alice);238 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});369239370 const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;240 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);241 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);371242372 const owner = createEthAccount(web3);373 await transferBalanceToEth(api, alice, owner);374375 const receiver = createEthAccount(web3);376 await transferBalanceToEth(api, alice, receiver);377378 const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;379380 const address = tokenIdToAddress(collectionId, tokenId);381 const contract = uniqueRefungibleToken(web3, address, owner);382383 await contract.methods.repartition(200).send({from: owner});243 await contract.methods.repartition(200).send({from: owner});384 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(200);244 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(200);385 await contract.methods.transfer(receiver, 110).send({from: owner});245 await contract.methods.transfer(receiver, 110).send({from: owner});386 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(90);246 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(90);387 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(110);247 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(110);388248389 await expect(contract.methods.repartition(80).send({from: owner})).to.eventually.be.rejected;249 await expect(contract.methods.repartition(80).send({from: owner})).to.eventually.be.rejected; // Transaction is reverted390250391 await contract.methods.transfer(receiver, 90).send({from: owner});251 await contract.methods.transfer(receiver, 90).send({from: owner});392 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(0);252 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(0);393 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(200);253 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(200);394254395 await contract.methods.repartition(150).send({from: receiver});255 await contract.methods.repartition(150).send({from: receiver});396 await expect(contract.methods.transfer(owner, 160).send({from: receiver})).to.eventually.be.rejected;256 await expect(contract.methods.transfer(owner, 160).send({from: receiver})).to.eventually.be.rejected; // Transaction is reverted397 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(150);257 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(150);398 });258 });399259400 itWeb3('Can repartition with increased amount', async ({web3, api, privateKeyWrapper}) => {260 itEth('Can repartition with increased amount', async ({helper}) => {401 const alice = privateKeyWrapper('//Alice');261 const owner = await helper.eth.createAccountWithBalance(donor);262 const collection = await helper.rft.mintCollection(alice);263 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});402264403 const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;265 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);266 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);404267405 const owner = createEthAccount(web3);406 await transferBalanceToEth(api, alice, owner);407408 const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;409410 const address = tokenIdToAddress(collectionId, tokenId);411 const contract = uniqueRefungibleToken(web3, address, owner);412413 const result = await contract.methods.repartition(200).send();268 const result = await contract.methods.repartition(200).send();414 const events = normalizeEvents(result.events);415269416 expect(events).to.deep.equal([270 const event = result.events.Transfer;271 expect(event.address).to.be.equal(tokenAddress);417 {272 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');418 address,419 event: 'Transfer',420 args: {421 from: '0x0000000000000000000000000000000000000000',422 to: owner,273 expect(event.returnValues.to).to.be.equal(owner);423 value: '100',274 expect(event.returnValues.value).to.be.equal('100');424 },425 },426 ]);427 });275 });428276429 itWeb3('Can repartition with decreased amount', async ({web3, api, privateKeyWrapper}) => {277 itEth('Can repartition with decreased amount', async ({helper}) => {430 const alice = privateKeyWrapper('//Alice');278 const owner = await helper.eth.createAccountWithBalance(donor);279 const collection = await helper.rft.mintCollection(alice);280 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});431281432 const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;282 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);283 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);433284434 const owner = createEthAccount(web3);435 await transferBalanceToEth(api, alice, owner);436437 const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;438439 const address = tokenIdToAddress(collectionId, tokenId);440 const contract = uniqueRefungibleToken(web3, address, owner);441442 const result = await contract.methods.repartition(50).send();285 const result = await contract.methods.repartition(50).send();443 const events = normalizeEvents(result.events);286 const event = result.events.Transfer;444 expect(events).to.deep.equal([287 expect(event.address).to.be.equal(tokenAddress);445 {288 expect(event.returnValues.from).to.be.equal(owner);446 address,447 event: 'Transfer',448 args: {449 from: owner,450 to: '0x0000000000000000000000000000000000000000',289 expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');451 value: '50',290 expect(event.returnValues.value).to.be.equal('50');452 },453 },454 ]);455 });291 });456292457 itWeb3('Receiving Transfer event on burning into full ownership', async ({web3, api, privateKeyWrapper}) => {293 itEth('Receiving Transfer event on burning into full ownership', async ({helper}) => {458 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);294 const caller = await helper.eth.createAccountWithBalance(donor);459 const receiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);295 const receiver = await helper.eth.createAccountWithBalance(donor);460 const helper = evmCollectionHelpers(web3, caller);296 const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Devastation', '6', '6');461 const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();462 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);297 const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);463 const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});464298465 const tokenId = await contract.methods.nextTokenId().call();299 const tokenId = await contract.methods.nextTokenId().call();466 await contract.methods.mint(caller, tokenId).send();300 await contract.methods.mint(caller, tokenId).send();301 const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);302 const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);467303468 const address = tokenIdToAddress(collectionId, tokenId);469470 const tokenContract = uniqueRefungibleToken(web3, address, caller);471 await tokenContract.methods.repartition(2).send();304 await tokenContract.methods.repartition(2).send();472 await tokenContract.methods.transfer(receiver, 1).send();305 await tokenContract.methods.transfer(receiver, 1).send();473306474 const events = await recordEvents(contract, async () =>307 const events: any = [];308 contract.events.allEvents((_: any, event: any) => {475 await tokenContract.methods.burnFrom(caller, 1).send());309 events.push(event);476 expect(events).to.deep.equal([310 });311 await tokenContract.methods.burnFrom(caller, 1).send();312477 {313 const event = events[0];478 address: collectionIdAddress,479 event: 'Transfer',314 expect(event.address).to.be.equal(collectionAddress);480 args: {315 expect(event.returnValues.from).to.be.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');481 from: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',482 to: receiver,316 expect(event.returnValues.to).to.be.equal(receiver);483 tokenId,317 expect(event.returnValues.tokenId).to.be.equal(tokenId);484 },485 },486 ]);487 });318 });488});319});489320490describe('Refungible: Fees', () => {321describe('Refungible: Fees', () => {322 let donor: IKeyringPair;323 let alice: IKeyringPair;324491 before(async function() {325 before(async function() {492 await requirePallets(this, [Pallets.ReFungible]);326 await usingEthPlaygrounds(async (helper, privateKey) => {327 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);328329 donor = privateKey('//Alice');330 [alice] = await helper.arrange.createAccounts([50n], donor);331 });493 });332 });494333495 itWeb3('approve() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {334 itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {496 const alice = privateKeyWrapper('//Alice');335 const owner = await helper.eth.createAccountWithBalance(donor);336 const spender = helper.eth.createAccount();337 const collection = await helper.rft.mintCollection(alice);338 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});497339498 const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;340 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);341 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);499342500 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);343 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, 100).send({from: owner}));501 const spender = createEthAccount(web3);502503 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;504505 const address = tokenIdToAddress(collectionId, tokenId);506 const contract = uniqueRefungibleToken(web3, address, owner);507508 const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, 100).send({from: owner}));509 expect(cost < BigInt(0.2 * Number(UNIQUE)));344 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));510 });345 });511346512 itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {347 itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {513 const alice = privateKeyWrapper('//Alice');348 const owner = await helper.eth.createAccountWithBalance(donor);349 const spender = await helper.eth.createAccountWithBalance(donor);350 const collection = await helper.rft.mintCollection(alice);351 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});514352515 const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;353 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);354 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);516355517 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);518 const spender = await createEthAccountWithBalance(api, web3, privateKeyWrapper);519520 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;521522 const address = tokenIdToAddress(collectionId, tokenId);523 const contract = uniqueRefungibleToken(web3, address, owner);524525 await contract.methods.approve(spender, 100).send({from: owner});356 await contract.methods.approve(spender, 100).send({from: owner});526357527 const cost = await recordEthFee(api, spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));358 const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));528 expect(cost < BigInt(0.2 * Number(UNIQUE)));359 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));529 });360 });530361531 itWeb3('transfer() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {362 itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {532 const alice = privateKeyWrapper('//Alice');363 const owner = await helper.eth.createAccountWithBalance(donor);364 const receiver = helper.eth.createAccount();365 const collection = await helper.rft.mintCollection(alice);366 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});533367534 const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;368 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);369 const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);535370536 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);371 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));537 const receiver = createEthAccount(web3);538539 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;540541 const address = tokenIdToAddress(collectionId, tokenId);542 const contract = uniqueRefungibleToken(web3, address, owner);543544 const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));545 expect(cost < BigInt(0.2 * Number(UNIQUE)));372 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));546 });373 });547});374});548375549describe('Refungible: Substrate calls', () => {376describe('Refungible: Substrate calls', () => {377 let donor: IKeyringPair;378 let alice: IKeyringPair;379550 before(async function() {380 before(async function() {551 await requirePallets(this, [Pallets.ReFungible]);381 await usingEthPlaygrounds(async (helper, privateKey) => {382 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);383384 donor = privateKey('//Alice');385 [alice] = await helper.arrange.createAccounts([50n], donor);386 });552 });387 });553388554 itWeb3('Events emitted for approve()', async ({web3, api, privateKeyWrapper}) => {389 itEth('Events emitted for approve()', async ({helper}) => {555 const alice = privateKeyWrapper('//Alice');390 const receiver = helper.eth.createAccount();391 const collection = await helper.rft.mintCollection(alice);392 const token = await collection.mintToken(alice, 200n);556393557 const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;394 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);395 const contract = helper.ethNativeContract.rftToken(tokenAddress);558396559 const receiver = createEthAccount(web3);397 const events: any = [];560561 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;562563 const address = tokenIdToAddress(collectionId, tokenId);398 contract.events.allEvents((_: any, event: any) => {564 const contract = uniqueRefungibleToken(web3, address);565566 const events = await recordEvents(contract, async () => {567 expect(await approve(api, collectionId, tokenId, alice, {Ethereum: receiver}, 100n)).to.be.true;399 events.push(event);568 });400 });401 expect(await token.approve(alice, {Ethereum: receiver}, 100n)).to.be.true;569402570 expect(events).to.be.deep.equal([403 const event = events[0];571 {572 address,573 event: 'Approval',404 expect(event.event).to.be.equal('Approval');574 args: {405 expect(event.address).to.be.equal(tokenAddress);575 owner: subToEth(alice.address),406 expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));576 spender: receiver,407 expect(event.returnValues.spender).to.be.equal(receiver);577 value: '100',408 expect(event.returnValues.value).to.be.equal('100');578 },579 },580 ]);581 });409 });582410583 itWeb3('Events emitted for transferFrom()', async ({web3, api, privateKeyWrapper}) => {411 itEth('Events emitted for transferFrom()', async ({helper}) => {584 const alice = privateKeyWrapper('//Alice');412 const [bob] = await helper.arrange.createAccounts([10n], donor);413 const receiver = helper.eth.createAccount();414 const collection = await helper.rft.mintCollection(alice);415 const token = await collection.mintToken(alice, 200n);416 await token.approve(alice, {Substrate: bob.address}, 100n);585417586 const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;418 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);587 const bob = privateKeyWrapper('//Bob');419 const contract = helper.ethNativeContract.rftToken(tokenAddress);588420589 const receiver = createEthAccount(web3);421 const events: any = [];422 contract.events.allEvents((_: any, event: any) => {423 events.push(event);424 });590425591 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;426 expect(await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n)).to.be.true;592 expect(await approve(api, collectionId, tokenId, alice, bob.address, 100n)).to.be.true;593427594 const address = tokenIdToAddress(collectionId, tokenId);428 let event = events[0];429 expect(event.event).to.be.equal('Transfer');430 expect(event.address).to.be.equal(tokenAddress);595 const contract = uniqueRefungibleToken(web3, address);431 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));432 expect(event.returnValues.to).to.be.equal(receiver);433 expect(event.returnValues.value).to.be.equal('51');596434597 const events = await recordEvents(contract, async () => {435 event = events[1];598 expect(await transferFrom(api, collectionId, tokenId, bob, alice, {Ethereum: receiver}, 51n)).to.be.true;436 expect(event.event).to.be.equal('Approval');599 });600601 expect(events).to.be.deep.equal([437 expect(event.address).to.be.equal(tokenAddress);602 {438 expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));603 address,604 event: 'Transfer',605 args: {606 from: subToEth(alice.address),607 to: receiver,608 value: '51',609 },610 },611 {612 address,613 event: 'Approval',614 args: {615 owner: subToEth(alice.address),616 spender: subToEth(bob.address),439 expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(bob.address));617 value: '49',440 expect(event.returnValues.value).to.be.equal('49');618 },619 },620 ]);621 });441 });622442623 itWeb3('Events emitted for transfer()', async ({web3, api, privateKeyWrapper}) => {443 itEth('Events emitted for transfer()', async ({helper}) => {624 const alice = privateKeyWrapper('//Alice');444 const receiver = helper.eth.createAccount();445 const collection = await helper.rft.mintCollection(alice);446 const token = await collection.mintToken(alice, 200n);625447626 const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;448 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);449 const contract = helper.ethNativeContract.rftToken(tokenAddress);627450628 const receiver = createEthAccount(web3);451 const events: any = [];629630 const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;631632 const address = tokenIdToAddress(collectionId, tokenId);452 contract.events.allEvents((_: any, event: any) => {633 const contract = uniqueRefungibleToken(web3, address);634635 const events = await recordEvents(contract, async () => {636 expect(await transfer(api, collectionId, tokenId, alice, {Ethereum: receiver}, 51n)).to.be.true;453 events.push(event);637 });454 });638455639 expect(events).to.be.deep.equal([456 expect(await token.transfer(alice, {Ethereum: receiver}, 51n)).to.be.true;640 {457641 address,458 const event = events[0];642 event: 'Transfer',459 expect(event.event).to.be.equal('Transfer');643 args: {460 expect(event.address).to.be.equal(tokenAddress);644 from: subToEth(alice.address),461 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));645 to: receiver,462 expect(event.returnValues.to).to.be.equal(receiver);646 value: '51',463 expect(event.returnValues.value).to.be.equal('51');647 },648 },649 ]);650 });464 });651});465});652466653describe('ERC 1633 implementation', () => {467describe('ERC 1633 implementation', () => {468 let donor: IKeyringPair;469654 before(async function() {470 before(async function() {655 await requirePallets(this, [Pallets.ReFungible]);471 await usingEthPlaygrounds(async (helper, privateKey) => {656 });472 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);657473658 itWeb3('Default parent token address and id', async ({api, web3, privateKeyWrapper}) => {474 donor = privateKey('//Alice');475 });659 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);476 });660477661 const {collectionIdAddress, collectionId} = await createRFTCollection(api, web3, owner);478 itEth('Default parent token address and id', async ({helper}) => {662 const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);663 const refungibleTokenId = await refungibleContract.methods.nextTokenId().call();479 const owner = await helper.eth.createAccountWithBalance(donor);664 await refungibleContract.methods.mint(owner, refungibleTokenId).send();665480666 const rftTokenAddress = tokenIdToAddress(collectionId, refungibleTokenId);481 const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Sands', '', 'GRAIN');667 const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);482 const collectionContract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);483 484 const tokenId = await collectionContract.methods.nextTokenId().call();485 await collectionContract.methods.mint(owner, tokenId).send();486 const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);487 const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, owner);668488669 const tokenAddress = await refungibleTokenContract.methods.parentToken().call();489 expect(await tokenContract.methods.parentToken().call()).to.be.equal(collectionAddress);670 const tokenId = await refungibleTokenContract.methods.parentTokenId().call();490 expect(await tokenContract.methods.parentTokenId().call()).to.be.equal(tokenId);671 expect(tokenAddress).to.be.equal(collectionIdAddress);672 expect(tokenId).to.be.equal(refungibleTokenId);673 });491 });674});492});675493tests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth121213import chai from 'chai';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';14import chaiAsPromised from 'chai-as-promised';15import {requirePalletsOrSkip} from '../../../util/playgrounds';15chai.use(chaiAsPromised);16chai.use(chaiAsPromised);16export const expect = chai.expect;17export const expect = chai.expect;171835 }36 }36};37};37 38 38export async function itEth(name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {39export async function itEth(name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {39 let i: any = it;40 (opts.only ? it.only : 40 if (opts.only) i = i.only;41 else if (opts.skip) i = i.skip;42 i(name, async () => {41 opts.skip ? it.skip : it)(name, async function() {43 await usingEthPlaygrounds(async (helper, privateKey) => {42 await usingEthPlaygrounds(async (helper, privateKey) => {43 if (opts.requiredPallets) {44 requirePalletsOrSkip(this, helper, opts.requiredPallets);45 }4644 await cb({helper, privateKey});47 await cb({helper, privateKey});45 });48 });46 });49 });47}50}5152export async function itEthIfWithPallet(name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {53 return itEth(name, cb, {requiredPallets: required, ...opts});54}5548itEth.only = (name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEth(name, cb, {only: true});56itEth.only = (name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEth(name, cb, {only: true});49itEth.skip = (name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEth(name, cb, {skip: true});57itEth.skip = (name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEth(name, cb, {skip: true});5859itEthIfWithPallet.only = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEthIfWithPallet(name, required, cb, {only: true});60itEthIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEthIfWithPallet(name, required, cb, {skip: true});61itEth.ifWithPallets = itEthIfWithPallet;62tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth27import refungibleAbi from '../../reFungibleAbi.json';27import refungibleAbi from '../../reFungibleAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';30import {TEthereumAccount} from '../../../util/playgrounds/types';303131class EthGroupBase {32class EthGroupBase {32 helper: EthUniqueHelper;33 helper: EthUniqueHelper;43 return {error: `File not found: ${path}`};44 return {error: `File not found: ${path}`};44 };45 };45 46 46 const knownImports = {} as any;47 const knownImports = {} as {[key: string]: string};47 for(const imp of imports) {48 for(const imp of imports) {48 knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();49 knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();49 }50 }50 51 51 return function(path: string) {52 return function(path: string) {52 if(knownImports.hasOwnPropertyDescriptor(path)) return {contents: knownImports[path]};53 if(path in knownImports) return {contents: knownImports[path]};53 return {error: `File not found: ${path}`};54 return {error: `File not found: ${path}`};54 };55 };55 }56 }116 return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});117 return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});117 }118 }119120 collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {121 return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);122 }118123119 rftTokenByAddress(address: string, caller?: string): Contract {124 rftToken(address: string, caller?: string): Contract {120 const web3 = this.helper.getWeb3();125 const web3 = this.helper.getWeb3();121 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});126 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});122 }127 }123128124 rftToken(collectionId: number, tokenId: number, caller?: string): Contract {129 rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {125 return this.rftTokenByAddress(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);130 return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);126 }131 }127}132}128133148 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));153 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));149 }154 }150155151 async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {156 async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {152 if(!gasLimit) gasLimit = this.DEFAULT_GAS;157 if(!gasLimit) gasLimit = this.DEFAULT_GAS;153 const web3 = this.helper.getWeb3();158 const web3 = this.helper.getWeb3();154 const gasPrice = await web3.eth.getGasPrice();159 const gasPrice = await web3.eth.getGasPrice();160 );165 );161 }166 }167 168 async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {169 return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);170 }162171163 async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {172 async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {164 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);173 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);171 return {collectionId, collectionAddress};180 return {collectionId, collectionAddress};172 }181 }182183 async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {184 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);185 186 const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send();187188 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);189 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);190191 return {collectionId, collectionAddress};192 }173193174 async deployCollectorContract(signer: string): Promise<Contract> {194 async deployCollectorContract(signer: string): Promise<Contract> {175 return await this.helper.ethContract.deployByCode(signer, 'Collector', `195 return await this.helper.ethContract.deployByCode(signer, 'Collector', `216 `);236 `);217 }237 }238239 async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {240 const before = await this.helper.balance.getEthereum(user);241 await call();242 // In dev mode, the transaction might not finish processing in time243 await this.helper.wait.newBlocks(1);244 const after = await this.helper.balance.getEthereum(user);245246 return before - after;247 }218} 248} 219 249 220class EthAddressGroup extends EthGroupBase {250class EthAddressGroup extends EthGroupBase {240 }270 }241271242 fromTokenId(collectionId: number, tokenId: number): string {272 fromTokenId(collectionId: number, tokenId: number): string {243 return this.helper.util.getNestingTokenAddress(collectionId, tokenId);273 return this.helper.util.getTokenAddress({collectionId, tokenId});244 }274 }245275246 normalizeAddress(address: string): string {276 normalizeAddress(address: string): string {tests/src/nesting/graphs.test.tsdiffbeforeafterboth1import {ApiPromise} from '@polkadot/api';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/>.162import {IKeyringPair} from '@polkadot/types/types';17import {IKeyringPair} from '@polkadot/types/types';3import {expect} from 'chai';18import {expect, itSub, usingPlaygrounds} from '../util/playgrounds';4import {tokenIdToCross} from '../eth/util/helpers';5import usingApi, {executeTransaction} from '../substrate/substrate-api';6import {getCreateCollectionResult, transferExpectSuccess, setCollectionLimitsExpectSuccess} from '../util/helpers';19import {UniqueHelper, UniqueNFToken} from '../util/playgrounds/unique';7208/**21/**9 * ```dot22 * ```dot12 * 8 -> 525 * 8 -> 513 * ```26 * ```14 */27 */15async function buildComplexObjectGraph(api: ApiPromise, sender: IKeyringPair): Promise<number> {28async function buildComplexObjectGraph(helper: UniqueHelper, sender: IKeyringPair): Promise<UniqueNFToken[]> {16 const events = await executeTransaction(api, sender, api.tx.unique.createCollectionEx({mode: 'NFT', permissions: {nesting: {tokenOwner: true}}}));29 const collection = await helper.nft.mintCollection(sender, {permissions: {nesting: {tokenOwner: true}}});17 const {collectionId} = getCreateCollectionResult(events);30 const tokens = await collection.mintMultipleTokens(sender, Array(8).fill({owner: {Substrate: sender.address}}));1819 await executeTransaction(api, sender, api.tx.unique.createMultipleItemsEx(collectionId, {NFT: Array(8).fill({owner: {Substrate: sender.address}})}));203121 await transferExpectSuccess(collectionId, 8, sender, tokenIdToCross(collectionId, 5));32 await tokens[7].nest(sender, tokens[4]);2223 await transferExpectSuccess(collectionId, 7, sender, tokenIdToCross(collectionId, 6));33 await tokens[6].nest(sender, tokens[5]);24 await transferExpectSuccess(collectionId, 6, sender, tokenIdToCross(collectionId, 5));34 await tokens[5].nest(sender, tokens[4]);25 await transferExpectSuccess(collectionId, 5, sender, tokenIdToCross(collectionId, 2));35 await tokens[4].nest(sender, tokens[1]);2627 await transferExpectSuccess(collectionId, 4, sender, tokenIdToCross(collectionId, 3));36 await tokens[3].nest(sender, tokens[2]);28 await transferExpectSuccess(collectionId, 3, sender, tokenIdToCross(collectionId, 2));37 await tokens[2].nest(sender, tokens[1]);29 await transferExpectSuccess(collectionId, 2, sender, tokenIdToCross(collectionId, 1));38 await tokens[1].nest(sender, tokens[0]);303931 return collectionId;40 return tokens;32}41}334234describe('Graphs', () => {43describe('Graphs', () => {44 let alice: IKeyringPair;4546 before(async () => {47 await usingPlaygrounds(async (helper, privateKey) => {48 const donor = privateKey('//Alice');49 [alice] = await helper.arrange.createAccounts([10n], donor);50 });51 });5235 it('Ouroboros can\'t be created in a complex graph', async () => {53 itSub('Ouroboros can\'t be created in a complex graph', async ({helper}) => {36 await usingApi(async (api, privateKeyWrapper) => {54 const tokens = await buildComplexObjectGraph(helper, alice);37 const alice = privateKeyWrapper('//Alice');38 const collection = await buildComplexObjectGraph(api, alice);39 const tokenTwoParent = tokenIdToCross(collection, 1);405541 // to self56 // to self42 await expect(57 await expect(43 executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 1), collection, 1, 1)),58 tokens[0].nest(alice, tokens[0]),44 'first transaction', 59 'first transaction', 45 ).to.be.rejectedWith(/structure\.OuroborosDetected/);60 ).to.be.rejectedWith(/structure\.OuroborosDetected/);46 // to nested part of graph61 // to nested part of graph47 await expect(62 await expect(48 executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 5), collection, 1, 1)),63 tokens[0].nest(alice, tokens[4]),49 'second transaction',64 'second transaction',50 ).to.be.rejectedWith(/structure\.OuroborosDetected/);65 ).to.be.rejectedWith(/structure\.OuroborosDetected/);51 await expect(66 await expect(52 executeTransaction(api, alice, api.tx.unique.transferFrom(tokenTwoParent, tokenIdToCross(collection, 8), collection, 2, 1)),67 tokens[1].transferFrom(alice, tokens[0].nestingAccount(), tokens[7].nestingAccount()),53 'third transaction',68 'third transaction',54 ).to.be.rejectedWith(/structure\.OuroborosDetected/);69 ).to.be.rejectedWith(/structure\.OuroborosDetected/);55 });56 });70 });57});71});5872tests/src/nesting/migration-check.test.tsdiffbeforeafterboth8import find from 'find-process';8import find from 'find-process';9910// todo un-skip for migrations10// todo un-skip for migrations11// todo:playgrounds skipped, this one is outdated. Probably to be deleted/replaced.11describe.skip('Migration testing', () => {12describe.skip('Migration testing: Properties', () => {12 let alice: IKeyringPair;13 let alice: IKeyringPair;131414 before(async() => {15 before(async() => {tests/src/nesting/nest.test.tsdiffbeforeafterboth1import {expect} from 'chai';1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2import {tokenIdToAddress} from '../eth/util/helpers';3import usingApi, {executeTransaction} from '../substrate/substrate-api';2// This file is part of Unique Network.4import {5 addCollectionAdminExpectSuccess,6 addToAllowListExpectSuccess,7 createCollectionExpectSuccess,8 createItemExpectSuccess,9 enableAllowListExpectSuccess,10 enablePublicMintingExpectSuccess,11 getTokenChildren,12 getTokenOwner,13 getTopmostTokenOwner,14 normalizeAccountId,15 setCollectionPermissionsExpectSuccess,16 transferExpectFailure,17 transferExpectSuccess,18 transferFromExpectSuccess,19 setCollectionLimitsExpectSuccess,20 requirePallets,21 Pallets,22} from '../util/helpers';23import {IKeyringPair} from '@polkadot/types/types';24325let alice: IKeyringPair;4// Unique Network is free software: you can redistribute it and/or modify26let bob: IKeyringPair;5// it under the terms of the GNU General Public License as published by27let charlie: IKeyringPair;6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.2889// 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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {expect, itSub, Pallets, usingPlaygrounds} from '../util/playgrounds';1929describe('Integration Test: Composite nesting tests', () => {20describe('Integration Test: Composite nesting tests', () => {21 let alice: IKeyringPair;22 let bob: IKeyringPair;2330 before(async () => {24 before(async () => {31 await usingApi(async (_, privateKeyWrapper) => {25 await usingPlaygrounds(async (helper, privateKey) => {32 alice = privateKeyWrapper('//Alice');26 const donor = privateKey('//Alice');33 bob = privateKeyWrapper('//Bob');27 [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);34 });28 });35 });29 });363037 it('Performs the full suite: bundles a token, transfers, and unnests', async () => {31 itSub('Performs the full suite: bundles a token, transfers, and unnests', async ({helper}) => {38 await usingApi(async api => {32 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});39 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});40 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});41 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');33 const targetToken = await collection.mintToken(alice);423443 // Create a nested token35 // Create an immediately nested token44 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});36 const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());45 expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});37 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});46 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});38 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());39 40 // Create a token to be nested41 const newToken = await collection.mintToken(alice);474248 // Create a token to be nested43 // Nest44 await newToken.nest(alice, targetToken);49 const newToken = await createItemExpectSuccess(alice, collection, 'NFT');45 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});46 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());504751 // Nest48 // Move bundle to different user52 await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});49 await targetToken.transfer(alice, {Substrate: bob.address});53 expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});50 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});54 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});51 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());52 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});53 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());555456 // Move bundle to different user55 // Unnest57 await transferExpectSuccess(collection, targetToken, alice, {Substrate: bob.address});56 await newToken.unnest(bob, targetToken, {Substrate: bob.address});58 expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: bob.address});57 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});59 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});58 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});6061 // Unnest62 await transferFromExpectSuccess(collection, newToken, bob, {Ethereum: tokenIdToAddress(collection, targetToken)}, {Substrate: bob.address});63 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});64 });65 });59 });666067 it('Transfers an already bundled token', async () => {61 itSub('Transfers an already bundled token', async ({helper}) => {68 await usingApi(async api => {62 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});69 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});70 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});63 const tokenA = await collection.mintToken(alice);64 const tokenB = await collection.mintToken(alice);716572 const tokenA = await createItemExpectSuccess(alice, collection, 'NFT');66 // Create a nested token73 const tokenB = await createItemExpectSuccess(alice, collection, 'NFT');7475 // Create a nested token76 const tokenC = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, tokenA)});67 const tokenC = await collection.mintToken(alice, tokenA.nestingAccount());77 expect(await getTopmostTokenOwner(api, collection, tokenC)).to.be.deep.equal({Substrate: alice.address});68 expect(await tokenC.getOwner()).to.be.deep.equal(tokenA.nestingAccount().toLowerCase());78 expect(await getTokenOwner(api, collection, tokenC)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, tokenA).toLowerCase()});7980 // Transfer the nested token to another token69 70 // Transfer the nested token to another token81 await expect(executeTransaction(71 await expect(tokenC.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount())).to.be.fulfilled;82 api,83 alice,84 api.tx.unique.transferFrom(85 normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenA)}),86 normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenB)}),87 collection,88 tokenC,89 1,90 ),91 )).to.not.be.rejected;92 expect(await getTopmostTokenOwner(api, collection, tokenC)).to.be.deep.equal({Substrate: alice.address});72 expect(await tokenC.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});93 expect(await getTokenOwner(api, collection, tokenC)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, tokenB).toLowerCase()});73 expect(await tokenC.getOwner()).to.be.deep.equal(tokenB.nestingAccount().toLowerCase());94 });95 });74 });967597 it('Checks token children', async () => {76 itSub('Checks token children', async ({helper}) => {98 await usingApi(async api => {77 const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});99 const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});100 await setCollectionLimitsExpectSuccess(alice, collectionA, {ownerCanTransfer: true});78 const collectionB = await helper.ft.mintCollection(alice);101 await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: {tokenOwner: true}});79 80 const targetToken = await collectionA.mintToken(alice);102 const collectionB = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});81 expect((await targetToken.getChildren()).length).to.be.equal(0, 'Children length check at creation');10382104 const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT');83 // Create a nested NFT token105 const targetAddress = {Ethereum: tokenIdToAddress(collectionA, targetToken)};84 const tokenA = await collectionA.mintToken(alice, targetToken.nestingAccount());106 let children = await getTokenChildren(api, collectionA, targetToken);85 expect(await targetToken.getChildren()).to.have.deep.members([86 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},107 expect(children.length).to.be.equal(0, 'Children length check at creation');87 ], 'Children contents check at nesting #1').and.be.length(1, 'Children length check at nesting #1');10888109 // Create a nested NFT token89 // Create then nest110 const tokenA = await createItemExpectSuccess(alice, collectionA, 'NFT', targetAddress);90 const tokenB = await collectionA.mintToken(alice);111 children = await getTokenChildren(api, collectionA, targetToken);91 await tokenB.nest(alice, targetToken);112 expect(children.length).to.be.equal(1, 'Children length check at nesting #1');92 expect(await targetToken.getChildren()).to.have.deep.members([113 expect(children).to.have.deep.members([114 {token: tokenA, collection: collectionA},93 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},115 ], 'Children contents check at nesting #1');94 {tokenId: tokenB.tokenId, collectionId: collectionA.collectionId},95 ], 'Children contents check at nesting #2').and.be.length(2, 'Children length check at nesting #2');11696117 // Create then nest97 // Move token B to a different user outside the nesting tree118 const tokenB = await createItemExpectSuccess(alice, collectionA, 'NFT');119 await transferExpectSuccess(collectionA, tokenB, alice, targetAddress);98 await tokenB.unnest(alice, targetToken, {Substrate: bob.address});120 children = await getTokenChildren(api, collectionA, targetToken);121 expect(children.length).to.be.equal(2, 'Children length check at nesting #2');99 expect(await targetToken.getChildren()).to.be.have.deep.members([122 expect(children).to.have.deep.members([123 {token: tokenA, collection: collectionA},100 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},124 {token: tokenB, collection: collectionA},101 ], 'Children contents check at nesting #3 (unnesting)').and.be.length(1, 'Children length check at nesting #3 (unnesting)');125 ], 'Children contents check at nesting #2');126102127 // Move token B to a different user outside the nesting tree103 // Create a fungible token in another collection and then nest104 await collectionB.mint(alice, 10n);128 await transferFromExpectSuccess(collectionA, tokenB, alice, targetAddress, bob);105 await collectionB.transfer(alice, targetToken.nestingAccount(), 2n);106 expect(await targetToken.getChildren()).to.be.have.deep.members([107 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},108 {tokenId: 0, collectionId: collectionB.collectionId},109 ], 'Children contents check at nesting #4 (from another collection)')110 .and.be.length(2, 'Children length check at nesting #4 (from another collection)');129 children = await getTokenChildren(api, collectionA, targetToken);111 112 // Move part of the fungible token inside token A deeper in the nesting tree113 await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);130 expect(children.length).to.be.equal(1, 'Children length check at unnesting');114 expect(await targetToken.getChildren()).to.be.have.deep.members([115 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},116 {tokenId: 0, collectionId: collectionB.collectionId},117 ], 'Children contents check at nesting #5 (deeper)').and.be.length(2, 'Children length check at nesting #5 (deeper)');131 expect(children).to.be.have.deep.members([118 expect(await tokenA.getChildren()).to.be.have.deep.members([132 {token: tokenA, collection: collectionA},119 {tokenId: 0, collectionId: collectionB.collectionId},133 ], 'Children contents check at unnesting');120 ], 'Children contents check at nesting #5.5 (deeper)').and.be.length(1, 'Children length check at nesting #5.5 (deeper)');134121135 // Create a fungible token in another collection and then nest122 // Move the remaining part of the fungible token inside token A deeper in the nesting tree136 const tokenC = await createItemExpectSuccess(alice, collectionB, 'Fungible');137 await transferExpectSuccess(collectionB, tokenC, alice, targetAddress, 1, 'Fungible');123 await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);138 children = await getTokenChildren(api, collectionA, targetToken);139 expect(children.length).to.be.equal(2, 'Children length check at nesting #3 (from another collection)');124 expect(await targetToken.getChildren()).to.be.have.deep.members([140 expect(children).to.be.have.deep.members([141 {token: tokenA, collection: collectionA},125 {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},142 {token: tokenC, collection: collectionB},126 ], 'Children contents check at nesting #6 (deeper)').and.be.length(1, 'Children length check at nesting #6 (deeper)');143 ], 'Children contents check at nesting #3 (from another collection)');144145 // Move the fungible token inside token A deeper in the nesting tree146 await transferFromExpectSuccess(collectionB, tokenC, alice, targetAddress, {Ethereum: tokenIdToAddress(collectionA, tokenA)}, 1, 'Fungible');147 children = await getTokenChildren(api, collectionA, targetToken);148 expect(children.length).to.be.equal(1, 'Children length check at deeper nesting');149 expect(children).to.be.have.deep.members([127 expect(await tokenA.getChildren()).to.be.have.deep.members([150 {token: tokenA, collection: collectionA},128 {tokenId: 0, collectionId: collectionB.collectionId},151 ], 'Children contents check at deeper nesting');129 ], 'Children contents check at nesting #6.5 (deeper)').and.be.length(1, 'Children length check at nesting #6.5 (deeper)');152 });153 });130 });154});131});155132156describe('Integration Test: Various token type nesting', async () => {133describe('Integration Test: Various token type nesting', () => {134 let alice: IKeyringPair;135 let bob: IKeyringPair;136 let charlie: IKeyringPair;137157 before(async () => {138 before(async () => {158 await usingApi(async (_, privateKeyWrapper) => {139 await usingPlaygrounds(async (helper, privateKey) => {159 alice = privateKeyWrapper('//Alice');140 const donor = privateKey('//Alice');160 bob = privateKeyWrapper('//Bob');141 [alice, bob, charlie] = await helper.arrange.createAccounts([50n, 10n, 10n], donor);161 charlie = privateKeyWrapper('//Charlie');162 });142 });163 });143 });164144165 it('Admin (NFT): allows an Admin to nest a token', async () => {145 itSub('Admin (NFT): allows an Admin to nest a token', async ({helper}) => {166 await usingApi(async api => {146 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true}}});167 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});168 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {collectionAdmin: true}});169 await addCollectionAdminExpectSuccess(alice, collection, bob.address);147 await collection.addAdmin(alice, {Substrate: bob.address});170 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT', charlie.address);148 const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});171149172 // Create a nested token150 // Create an immediately nested token173 const nestedToken = await createItemExpectSuccess(bob, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});151 const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());174 expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: charlie.address});152 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});175 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});153 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());176154177 // Create a token to be nested and nest155 // Create a token to be nested and nest178 const newToken = await createItemExpectSuccess(bob, collection, 'NFT');156 const newToken = await collection.mintToken(bob);179 await transferExpectSuccess(collection, newToken, bob, {Ethereum: tokenIdToAddress(collection, targetToken)});157 await newToken.nest(bob, targetToken);180 expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: charlie.address});158 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});181 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});159 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());182 });183 });160 });184161185 it('Admin (NFT): Admin and Token Owner can operate together', async () => {162 itSub('Admin (NFT): Admin and Token Owner can operate together', async ({helper}) => {186 await usingApi(async api => {163 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});187 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});188 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, collectionAdmin: true}});189 await addCollectionAdminExpectSuccess(alice, collection, bob.address);164 await collection.addAdmin(alice, {Substrate: bob.address});190 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT', charlie.address);165 const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});191166192 // Create a nested token by an administrator167 // Create an immediately nested token by an administrator193 const nestedToken = await createItemExpectSuccess(bob, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});168 const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());194 expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: charlie.address});169 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});195 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});170 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());196171197 // Create a token and allow the owner to nest too172 // Create a token to be nested and nest198 const newToken = await createItemExpectSuccess(alice, collection, 'NFT', charlie.address);173 const newToken = await collection.mintToken(alice, {Substrate: charlie.address});199 await transferExpectSuccess(collection, newToken, charlie, {Ethereum: tokenIdToAddress(collection, nestedToken)});174 await newToken.nest(charlie, targetToken);200 expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: charlie.address});175 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});201 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, nestedToken).toLowerCase()});176 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());202 });203 });177 });204178205 it('Admin (NFT): allows an Admin to nest a token (Restricted nesting)', async () => {179 itSub('Admin (NFT): allows an Admin to nest a token (Restricted nesting)', async ({helper}) => {206 await usingApi(async api => {180 const collectionA = await helper.nft.mintCollection(alice);207 const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});208 await addCollectionAdminExpectSuccess(alice, collectionA, bob.address);181 await collectionA.addAdmin(alice, {Substrate: bob.address});209 const collectionB = await createCollectionExpectSuccess({mode: {type: 'NFT'}});182 const collectionB = await helper.nft.mintCollection(alice);210 await addCollectionAdminExpectSuccess(alice, collectionB, bob.address);183 await collectionB.addAdmin(alice, {Substrate: bob.address});211 await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: {collectionAdmin: true, restricted:[collectionA, collectionB]}});184 await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted:[collectionB.collectionId]}});212 const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT', charlie.address);185 const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});213186214 // Create a nested token187 // Create an immediately nested token215 const nestedToken = await createItemExpectSuccess(bob, collectionB, 'NFT', {Ethereum: tokenIdToAddress(collectionA, targetToken)});188 const nestedToken = await collectionB.mintToken(bob, targetToken.nestingAccount());216 expect(await getTopmostTokenOwner(api, collectionB, nestedToken)).to.be.deep.equal({Substrate: charlie.address});189 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});217 expect(await getTokenOwner(api, collectionB, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collectionA, targetToken).toLowerCase()});190 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());218191219 // Create a token to be nested and nest192 // Create a token to be nested and nest220 const newToken = await createItemExpectSuccess(bob, collectionB, 'NFT');193 const newToken = await collectionB.mintToken(bob);221 await transferExpectSuccess(collectionB, newToken, bob, {Ethereum: tokenIdToAddress(collectionA, targetToken)});194 await newToken.nest(bob, targetToken);222 expect(await getTopmostTokenOwner(api, collectionB, newToken)).to.be.deep.equal({Substrate: charlie.address});195 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});223 expect(await getTokenOwner(api, collectionB, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collectionA, targetToken).toLowerCase()});196 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());224 });225 });197 });226198227 // ---------- Non-Fungible ----------199 // ---------- Non-Fungible ----------228200229 it('NFT: allows an Owner to nest/unnest their token', async () => {201 itSub('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {230 await usingApi(async api => {202 const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});231 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});232 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});203 await collection.addToAllowList(alice, {Substrate: charlie.address});233 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');204 const targetToken = await collection.mintToken(charlie);205 await collection.addToAllowList(alice, targetToken.nestingAccount());234206235 // Create a nested token207 // Create an immediately nested token236 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});208 const nestedToken = await collection.mintToken(charlie, targetToken.nestingAccount());237 expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});209 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});238 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});210 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());239211240 // Create a token to be nested and nest212 // Create a token to be nested and nest241 const newToken = await createItemExpectSuccess(alice, collection, 'NFT');213 const newToken = await collection.mintToken(charlie);242 await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});214 await newToken.nest(charlie, targetToken);243 expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});215 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});244 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});216 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());245 });246 });217 });247218248 it('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async () => {219 itSub('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {249 await usingApi(async api => {220 const collectionA = await helper.nft.mintCollection(alice);250 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});221 const collectionB = await helper.nft.mintCollection(alice);251 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, restricted:[collection]}});222 //await collectionB.addAdmin(alice, {Substrate: bob.address});252 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');223 const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});253224254 // Create a nested token225 await collectionA.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionB.collectionId]}});255 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});256 expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});226 await collectionA.addToAllowList(alice, {Substrate: charlie.address});257 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});227 await collectionA.addToAllowList(alice, targetToken.nestingAccount());258228259 // Create a token to be nested and nest229 await collectionB.setPermissions(alice, {access: 'AllowList', mintMode: true});260 const newToken = await createItemExpectSuccess(alice, collection, 'NFT');230 await collectionB.addToAllowList(alice, {Substrate: charlie.address});231 await collectionB.addToAllowList(alice, targetToken.nestingAccount());232261 await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});233 // Create an immediately nested token234 const nestedToken = await collectionB.mintToken(charlie, targetToken.nestingAccount());262 expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});235 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});263 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});236 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());237238 // Create a token to be nested and nest239 const newToken = await collectionB.mintToken(charlie);240 await newToken.nest(charlie, targetToken);241 expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});264 });242 expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());265 });243 });266244267 // ---------- Fungible ----------245 // ---------- Fungible ----------268246269 it('Fungible: allows an Owner to nest/unnest their token', async () => {247 itSub('Fungible: allows an Owner to nest/unnest their token', async ({helper}) => {270 await usingApi(async api => {248 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});271 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});272 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});273 const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});249 const collectionFT = await helper.ft.mintCollection(alice);274 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};250 const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});275251276 const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});252 await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});253 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());277254278 // Create a nested token255 await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});279 await expect(executeTransaction(api, alice, api.tx.unique.createItem(280 collectionFT,256 await collectionFT.addToAllowList(alice, {Substrate: charlie.address});281 targetAddress,282 {Fungible: {Value: 10}},283 ))).to.not.be.rejected;257 await collectionFT.addToAllowList(alice, targetToken.nestingAccount());284258285 // Nest a new token259 // Create an immediately nested token286 const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');260 await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());261 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);262287 await transferExpectSuccess(collectionFT, newToken, alice, targetAddress, 1, 'Fungible');263 // Create a token to be nested and nest264 await collectionFT.mint(charlie, 5n);265 await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);288 });266 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);289 });267 });290268291 it('Fungible: allows an Owner to nest/unnest their token (Restricted nesting)', async () => {269 itSub('Fungible: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {292 await usingApi(async api => {270 const collectionNFT = await helper.nft.mintCollection(alice);293 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});271 const collectionFT = await helper.ft.mintCollection(alice);294 const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});272 const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});295 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};296273297 const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});274 await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionFT.collectionId]}});275 await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});276 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());298277299 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted: [collectionFT]}});278 await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});279 await collectionFT.addToAllowList(alice, {Substrate: charlie.address});280 await collectionFT.addToAllowList(alice, targetToken.nestingAccount());300281301 // Create a nested token282 // Create an immediately nested token302 await expect(executeTransaction(api, alice, api.tx.unique.createItem(283 await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());303 collectionFT,284 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);304 targetAddress,305 {Fungible: {Value: 10}},306 ))).to.not.be.rejected;307285308 // Nest a new token286 // Create a token to be nested and nest309 const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');287 await collectionFT.mint(charlie, 5n);310 await transferExpectSuccess(collectionFT, newToken, alice, targetAddress, 1, 'Fungible');288 await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);311 });289 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);312 });290 });313291314 // ---------- Re-Fungible ----------292 // ---------- Re-Fungible ----------315293316 it('ReFungible: allows an Owner to nest/unnest their token', async function() {294 itSub.ifWithPallets('ReFungible: allows an Owner to nest/unnest their token', [Pallets.ReFungible], async ({helper}) => {317 await requirePallets(this, [Pallets.ReFungible]);295 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});296 const collectionRFT = await helper.rft.mintCollection(alice);297 const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});318298319 await usingApi(async api => {299 await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});320 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});321 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});322 const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});323 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};300 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());324301325 const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});302 await collectionRFT.setPermissions(alice, {access: 'AllowList', mintMode: true});303 await collectionRFT.addToAllowList(alice, {Substrate: charlie.address});304 await collectionRFT.addToAllowList(alice, targetToken.nestingAccount());326305327 // Create a nested token306 // Create an immediately nested token328 await expect(executeTransaction(api, alice, api.tx.unique.createItem(307 const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAccount());329 collectionRFT,308 expect(await nestedToken.getBalance(targetToken.nestingAccount())).to.be.equal(5n);330 targetAddress,331 {ReFungible: {pieces: 100}},332 ))).to.not.be.rejected;333309334 // Nest a new token310 // Create a token to be nested and nest335 const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');311 const newToken = await collectionRFT.mintToken(charlie, 5n);336 await transferExpectSuccess(collectionRFT, newToken, alice, targetAddress, 100, 'ReFungible');312 await newToken.transfer(charlie, targetToken.nestingAccount(), 2n);337 });313 expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(2n);338 });314 });339315340 it('ReFungible: allows an Owner to nest/unnest their token (Restricted nesting)', async function() {316 itSub.ifWithPallets('ReFungible: allows an Owner to nest/unnest their token (Restricted nesting)', [Pallets.ReFungible], async ({helper}) => {341 await requirePallets(this, [Pallets.ReFungible]);317 const collectionNFT = await helper.nft.mintCollection(alice);318 const collectionRFT = await helper.rft.mintCollection(alice);319 const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});342320343 await usingApi(async api => {321 await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionRFT.collectionId]}});344 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});345 const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});322 await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});346 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};323 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());347324348 const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});325 await collectionRFT.setPermissions(alice, {access: 'AllowList', mintMode: true});326 await collectionRFT.addToAllowList(alice, {Substrate: charlie.address});327 await collectionRFT.addToAllowList(alice, targetToken.nestingAccount());349328350 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionRFT]}});329 // Create an immediately nested token330 const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAccount());331 expect(await nestedToken.getBalance(targetToken.nestingAccount())).to.be.equal(5n);351332352 // Create a nested token333 // Create a token to be nested and nest353 await expect(executeTransaction(api, alice, api.tx.unique.createItem(354 collectionRFT,355 targetAddress,356 {ReFungible: {pieces: 100}},357 ))).to.not.be.rejected;358359 // Nest a new token360 const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');334 const newToken = await collectionRFT.mintToken(charlie, 5n);361 await transferExpectSuccess(collectionRFT, newToken, alice, targetAddress, 100, 'ReFungible');335 await newToken.transfer(charlie, targetToken.nestingAccount(), 2n);362 });336 expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(2n);363 });337 });364});338});365339366describe('Negative Test: Nesting', async() => {340describe('Negative Test: Nesting', () => {341 let alice: IKeyringPair;342 let bob: IKeyringPair;343367 before(async () => {344 before(async () => {368 await usingApi(async (_, privateKeyWrapper) => {345 await usingPlaygrounds(async (helper, privateKey) => {369 alice = privateKeyWrapper('//Alice');346 const donor = privateKey('//Alice');370 bob = privateKeyWrapper('//Bob');347 [alice, bob] = await helper.arrange.createAccounts([100n, 50n], donor);371 });348 });372 });349 });373350374 it('Disallows excessive token nesting', async () => {351 itSub('Disallows excessive token nesting', async ({helper}) => {375 await usingApi(async api => {352 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});376 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});377 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});378 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');353 let token = await collection.mintToken(alice);379354380 const maxNestingLevel = 5;355 const maxNestingLevel = 5;381 let prevToken = targetToken;382356383 // Create a nested-token matryoshka357 // Create a nested-token matryoshka384 for (let i = 0; i < maxNestingLevel; i++) {358 for (let i = 0; i < maxNestingLevel; i++) {385 const nestedToken = await createItemExpectSuccess(359 token = await collection.mintToken(alice, token.nestingAccount());386 alice,387 collection,388 'NFT',389 {Ethereum: tokenIdToAddress(collection, prevToken)},390 );360 }391361392 prevToken = nestedToken;362 // The nesting depth is limited by `maxNestingLevel`393 }394395 // The nesting depth is limited by `maxNestingLevel`396 await expect(executeTransaction(api, alice, api.tx.unique.createItem(363 await expect(collection.mintToken(alice, token.nestingAccount()))397 collection,398 {Ethereum: tokenIdToAddress(collection, prevToken)},399 {nft: {}} as any,364 .to.be.rejectedWith(/structure\.DepthLimit/);400 )), 'while creating nested token').to.be.rejectedWith(/^structure\.DepthLimit$/);401402 expect(await getTopmostTokenOwner(api, collection, prevToken)).to.be.deep.equal({Substrate: alice.address});365 expect(await token.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});403 });366 expect(await token.getChildren()).to.be.length(0);404 });367 });405368406 // ---------- Admin ------------369 // ---------- Admin ------------407370408 it('Admin (NFT): disallows an Admin to operate nesting when only TokenOwner is allowed', async () => {371 itSub('Admin (NFT): disallows an Admin to operate nesting when only TokenOwner is allowed', async ({helper}) => {409 await usingApi(async api => {372 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});410 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});411 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});412 await addCollectionAdminExpectSuccess(alice, collection, bob.address);373 await collection.addAdmin(alice, {Substrate: bob.address});413 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');374 const targetToken = await collection.mintToken(alice);414375415 // Try to create a nested token as collection admin when it's disallowed376 // Try to create an immediately nested token as collection admin when it's disallowed416 await expect(executeTransaction(api, bob, api.tx.unique.createItem(377 await expect(collection.mintToken(bob, targetToken.nestingAccount()))417 collection,418 {Ethereum: tokenIdToAddress(collection, targetToken)},419 {nft: {}} as any,378 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);420 )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);421379422 // Try to create and nest a token in the wrong collection380 // Try to create a token to be nested and nest423 const newToken = await createItemExpectSuccess(bob, collection, 'NFT');381 const newToken = await collection.mintToken(bob);424 await expect(executeTransaction(382 await expect(newToken.nest(bob, targetToken))425 api, 426 bob, 427 api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1),428 ), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);383 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);384429 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});385 expect(await targetToken.getChildren()).to.be.length(0);430 });386 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});431 });387 });432388433 it('Admin (NFT): disallows a Token Owner to operate nesting when only Admin is allowed', async () => {389 itSub('Admin (NFT): disallows a Token Owner to operate nesting when only Admin is allowed', async ({helper}) => {434 await usingApi(async api => {390 const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});435 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});436 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {collectionAdmin: true}});437 await addToAllowListExpectSuccess(alice, collection, bob.address);391 const targetToken = await collection.mintToken(alice, {Substrate: bob.address});438 await enableAllowListExpectSuccess(alice, collection);392 await collection.addToAllowList(alice, {Substrate: bob.address});439 await enablePublicMintingExpectSuccess(alice, collection);393 await collection.addToAllowList(alice, targetToken.nestingAccount());440 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');441394442 // Try to create a nested token as collection admin when it's disallowed395 // Try to create a nested token as token owner when it's disallowed443 await expect(executeTransaction(api, bob, api.tx.unique.createItem(396 await expect(collection.mintToken(bob, targetToken.nestingAccount()))444 collection,445 {Ethereum: tokenIdToAddress(collection, targetToken)},446 {nft: {}} as any,397 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);447 )), 'while creating nested token').to.be.rejectedWith(/common\.AddressNotInAllowlist/); 448398449 // Try to create and nest a token in the wrong collection399 // Try to create a token to be nested and nest450 const newToken = await createItemExpectSuccess(bob, collection, 'NFT');400 const newToken = await collection.mintToken(bob);451 await expect(executeTransaction(401 await expect(newToken.nest(bob, targetToken))452 api, 453 bob, 454 api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1),402 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);403455 ), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);404 expect(await targetToken.getChildren()).to.be.length(0);456 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});405 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});457 });458 });406 });459407460 it('Admin (NFT): disallows an Admin to nest and unnest someone else\'s token', async () => {408 itSub('Admin (NFT): disallows an Admin to unnest someone else\'s token', async ({helper}) => {461 await usingApi(async api => {409 const collection = await helper.nft.mintCollection(alice, {limits: {ownerCanTransfer: true}, permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});462 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});410 //await collection.addAdmin(alice, {Substrate: bob.address});463 await setCollectionLimitsExpectSuccess(alice, collection, {ownerCanTransfer: true});411 const targetToken = await collection.mintToken(alice, {Substrate: bob.address});464 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {collectionAdmin: true}});412 await collection.addToAllowList(alice, {Substrate: bob.address});413 await collection.addToAllowList(alice, targetToken.nestingAccount());465414466 await addToAllowListExpectSuccess(alice, collection, bob.address);415 // Try to nest somebody else's token416 const newToken = await collection.mintToken(bob);467 await enableAllowListExpectSuccess(alice, collection);417 await expect(newToken.nest(alice, targetToken))468 await enablePublicMintingExpectSuccess(alice, collection);418 .to.be.rejectedWith(/common\.NoPermission/);469419470 // Create a token to attempt to be nested into420 // Try to unnest a token belonging to someone else as collection admin471 const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');421 const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());472 const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()};422 await expect(nestedToken.unnest(alice, targetToken, {Substrate: bob.address}))423 .to.be.rejectedWith(/common\.AddressNotInAllowlist/);473424474 // Try to nest somebody else's token425 expect(await targetToken.getChildren()).to.be.length(1);475 const newToken = await createItemExpectSuccess(bob, collection, 'NFT');476 await expect(executeTransaction(477 api, 478 alice, 479 api.tx.unique.transferFrom(targetAddress, {Substrate: bob.address}, collection, newToken, 1),480 ), 'while nesting another\'s token token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);481 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});426 expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});482483 // Nest a token as admin and try to unnest it, now belonging to someone else427 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());484 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', targetAddress);485 await expect(executeTransaction(486 api, 487 alice, 488 api.tx.unique.transferFrom(targetAddress, normalizeAccountId(alice), collection, nestedToken, 1),489 ), 'while unnesting another\'s token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);490 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal(targetAddress);491 expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: bob.address});492 });493 });428 });494429495 it('Admin (NFT): disallows an Admin to nest a token from an unlisted collection (Restricted nesting)', async () => {430 itSub('Admin (NFT): disallows an Admin to nest a token from an unlisted collection (Restricted nesting)', async ({helper}) => {496 await usingApi(async api => {431 const collectionA = await helper.nft.mintCollection(alice);497 const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});498 const collectionB = await createCollectionExpectSuccess({mode: {type: 'NFT'}});432 const collectionB = await helper.nft.mintCollection(alice);499 await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: {collectionAdmin: true, restricted:[collectionA]}});433 await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted: [collectionA.collectionId]}});434 const targetToken = await collectionA.mintToken(alice);500435501 // Create a token to attempt to be nested into436 // Try to create a nested token from another collection502 const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT');437 await expect(collectionB.mintToken(alice, targetToken.nestingAccount()))438 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);503439504 // Try to create and nest a token in the wrong collection440 // Create a token in another collection yet to be nested and try to nest505 const newToken = await createItemExpectSuccess(alice, collectionB, 'NFT');441 const newToken = await collectionB.mintToken(alice);506 await expect(executeTransaction(442 await expect(newToken.nest(alice, targetToken))507 api, 508 alice, 509 api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionA, targetToken)}, collectionB, newToken, 1),510 ), 'while nesting a foreign token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);443 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);444511 expect(await getTokenOwner(api, collectionB, newToken)).to.be.deep.equal({Substrate: alice.address});445 expect(await targetToken.getChildren()).to.be.length(0);512 });446 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});513 });447 });514448515 // ---------- Non-Fungible ----------449 // ---------- Non-Fungible ----------516450517 it('NFT: disallows to nest token if nesting is disabled', async () => {451 itSub('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {518 await usingApi(async api => {452 // Collection is implicitly not allowed nesting at creation519 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});453 const collection = await helper.nft.mintCollection(alice);520 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {}});521 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');454 const targetToken = await collection.mintToken(alice);522455523 // Try to create a nested token456 // Try to create a nested token as token owner when it's disallowed524 await expect(executeTransaction(api, alice, api.tx.unique.createItem(525 collection,457 await expect(collection.mintToken(alice, targetToken.nestingAccount()))526 {Ethereum: tokenIdToAddress(collection, targetToken)},527 {nft: {}} as any,458 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);528 )), 'while creating nested token').to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);529459530 // Create a token to be nested460 // Try to create a token to be nested and nest531 const newToken = await createItemExpectSuccess(alice, collection, 'NFT');461 const newToken = await collection.mintToken(alice);532 // Try to nest462 await expect(newToken.nest(alice, targetToken))533 await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);463 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);464534 expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});465 expect(await targetToken.getChildren()).to.be.length(0);535 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});466 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});536 });537 });467 });538468539 it('NFT: disallows a non-Owner to nest someone else\'s token', async () => {469 itSub('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {540 await usingApi(async api => {470 const collection = await helper.nft.mintCollection(alice);541 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});542 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});471 const targetToken = await collection.mintToken(alice);543472544 await addToAllowListExpectSuccess(alice, collection, bob.address);473 await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});545 await enableAllowListExpectSuccess(alice, collection);474 await collection.addToAllowList(alice, {Substrate: bob.address});546 await enablePublicMintingExpectSuccess(alice, collection);475 await collection.addToAllowList(alice, targetToken.nestingAccount());547476548 // Create a token to attempt to be nested into477 // Try to create a token to be nested and nest549 const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');478 const newToken = await collection.mintToken(alice);479 await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);550480551 // Try to create a nested token in the wrong collection481 expect(await targetToken.getChildren()).to.be.length(0);552 await expect(executeTransaction(api, alice, api.tx.unique.createItem(553 collection,554 {Ethereum: tokenIdToAddress(collection, targetToken)},555 {nft: {}} as any,556 )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);557558 // Try to create and nest a token in the wrong collection482 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});559 const newToken = await createItemExpectSuccess(alice, collection, 'NFT');560 await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);561 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});562 });563 });483 });564484565 it('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async () => {485 itSub('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {566 await usingApi(async api => {486 const collection = await helper.nft.mintCollection(alice);567 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});568 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, restricted:[collection]}});487 const targetToken = await collection.mintToken(alice);569488570 await addToAllowListExpectSuccess(alice, collection, bob.address);489 await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});571 await enableAllowListExpectSuccess(alice, collection);490 await collection.addToAllowList(alice, {Substrate: bob.address});572 await enablePublicMintingExpectSuccess(alice, collection);491 await collection.addToAllowList(alice, targetToken.nestingAccount());573492574 // Create a token to attempt to be nested into493 const collectionB = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true}});575 const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');494 await collectionB.addToAllowList(alice, {Substrate: bob.address});495 await collectionB.addToAllowList(alice, targetToken.nestingAccount());576496577 // Try to create a nested token in the wrong collection497 // Try to create a token to be nested and nest578 await expect(executeTransaction(api, alice, api.tx.unique.createItem(498 const newToken = await collectionB.mintToken(alice);579 collection,499 await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);580 {Ethereum: tokenIdToAddress(collection, targetToken)},581 {nft: {}} as any,582 )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);583500584 // Try to create and nest a token in the wrong collection501 expect(await targetToken.getChildren()).to.be.length(0);585 const newToken = await createItemExpectSuccess(alice, collection, 'NFT');586 await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);587 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});502 expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});588 });589 });503 });590504591 it('NFT: disallows to nest token in an unlisted collection', async () => {505 itSub('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {592 await usingApi(async api => {506 // Create collection with restricted nesting -- even self is not allowed593 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});507 const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: []}}});594 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, restricted:[]}});508 const targetToken = await collection.mintToken(alice, {Substrate: bob.address});595509596 // Create a token to attempt to be nested into510 await collection.addToAllowList(alice, {Substrate: bob.address});597 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');511 await collection.addToAllowList(alice, targetToken.nestingAccount());598512599 // Try to create a nested token in the wrong collection513 // Try to mint in own collection after allowlisting the accounts600 await expect(executeTransaction(api, alice, api.tx.unique.createItem(514 await expect(collection.mintToken(bob, targetToken.nestingAccount()))601 collection,602 {Ethereum: tokenIdToAddress(collection, targetToken)},603 {nft: {}} as any,604 )), 'while creating nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);605606 // Try to create and nest a token in the wrong collection607 const newToken = await createItemExpectSuccess(alice, collection, 'NFT');608 await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);515 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);609 expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});610 });611 });516 });612517613 // ---------- Fungible ----------518 // ---------- Fungible ----------614519615 it('Fungible: disallows to nest token if nesting is disabled', async () => {520 itSub('Fungible: disallows to nest token if nesting is disabled', async ({helper}) => {616 await usingApi(async api => {521 const collectionNFT = await helper.nft.mintCollection(alice);617 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});618 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {}});619 const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');522 const collectionFT = await helper.ft.mintCollection(alice);620 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};523 const targetToken = await collectionNFT.mintToken(alice);621524622 const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});525 // Try to create an immediately nested token526 await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))527 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);623528624 // Try to create a nested token529 // Try to create a token to be nested and nest625 await expect(executeTransaction(api, alice, api.tx.unique.createItem(626 collectionFT,627 targetAddress,628 {Fungible: {Value: 10}},629 )), 'while creating nested token').to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);630631 // Create a token to be nested632 const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');530 await collectionFT.mint(alice, 5n);633 // Try to nest531 await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 2n))634 await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);532 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);635636 // Create another token to be nested533 expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);637 const newToken2 = await createItemExpectSuccess(alice, collectionFT, 'Fungible');638 // Try to nest inside a fungible token639 await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionFT, newToken)}, collectionFT, newToken2, 1)), 'while nesting new token inside fungible').to.be.rejectedWith(/fungible\.FungibleDisallowsNesting/);640 });641 });534 });642535643 it('Fungible: disallows a non-Owner to nest someone else\'s token', async () => {536 itSub('Fungible: disallows a non-Owner to unnest someone else\'s token', async ({helper}) => {644 await usingApi(async api => {537 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});645 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});538 const collectionFT = await helper.ft.mintCollection(alice);646 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});539 const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});647540648 await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);541 // Nest some tokens as Alice into Bob's token649 await enableAllowListExpectSuccess(alice, collectionNFT);650 await enablePublicMintingExpectSuccess(alice, collectionNFT);542 await collectionFT.mint(alice, 5n, targetToken.nestingAccount());651543652 // Create a token to attempt to be nested into544 // Try to pull it out653 const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');654 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};655656 const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});657658 // Try to create a nested token in the wrong collection659 await expect(executeTransaction(api, alice, api.tx.unique.createItem(545 await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))660 collectionFT,661 targetAddress,662 {Fungible: {Value: 10}},663 )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);546 .to.be.rejectedWith(/common\.ApprovedValueTooLow/);664665 // Try to create and nest a token in the wrong collection547 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);666 const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');667 await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);668 });669 });548 });670549671 it('Fungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async () => {550 itSub('Fungible: disallows a non-Owner to unnest someone else\'s token (Restricted nesting)', async ({helper}) => {672 await usingApi(async api => {551 const collectionNFT = await helper.nft.mintCollection(alice);673 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});674 await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);675 await enableAllowListExpectSuccess(alice, collectionNFT);552 const collectionFT = await helper.ft.mintCollection(alice);676 await enablePublicMintingExpectSuccess(alice, collectionNFT);553 const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});677554678 // Create a token to attempt to be nested into555 await collectionNFT.setPermissions(alice, {nesting: {collectionAdmin: true, tokenOwner: true, restricted: [collectionFT.collectionId]}});679 const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');680 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};681556682 const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});557 // Nest some tokens as Alice into Bob's token683 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionFT]}});558 await collectionFT.mint(alice, 5n, targetToken.nestingAccount());684559685 // Try to create a nested token in the wrong collection560 // Try to pull it out as Alice still686 await expect(executeTransaction(api, alice, api.tx.unique.createItem(561 await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))687 collectionFT,688 targetAddress,689 {Fungible: {Value: 10}},690 )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);562 .to.be.rejectedWith(/common\.ApprovedValueTooLow/);691692 // Try to create and nest a token in the wrong collection563 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);693 const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');694 await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);695 });696 });564 });697565698 it('Fungible: disallows to nest token in an unlisted collection', async () => {566 itSub('Fungible: disallows to nest token in an unlisted collection', async ({helper}) => {699 await usingApi(async api => {567 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true, restricted: []}}});700 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});701 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[]}});568 const collectionFT = await helper.ft.mintCollection(alice);569 const targetToken = await collectionNFT.mintToken(alice);702570703 // Create a token to attempt to be nested into571 // Try to mint an immediately nested token704 const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');572 await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))705 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};573 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);706574707 const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});575 // Mint a token and try to nest it576 await collectionFT.mint(alice, 5n);577 await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 1n))578 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);708579709 // Try to create a nested token in the wrong collection580 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);710 await expect(executeTransaction(api, alice, api.tx.unique.createItem(711 collectionFT,712 targetAddress,713 {Fungible: {Value: 10}},714 )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);715716 // Try to create and nest a token in the wrong collection581 expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);717 const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');718 await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);719 });720 });582 });721583722 // ---------- Re-Fungible ----------584 // ---------- Re-Fungible ----------723585724 it('ReFungible: disallows to nest token if nesting is disabled', async function() {586 itSub.ifWithPallets('ReFungible: disallows to nest token if nesting is disabled', [Pallets.ReFungible], async ({helper}) => {725 await requirePallets(this, [Pallets.ReFungible]);587 const collectionNFT = await helper.nft.mintCollection(alice);588 const collectionRFT = await helper.rft.mintCollection(alice);589 const targetToken = await collectionNFT.mintToken(alice);726590727 await usingApi(async api => {591 // Try to create an immediately nested token728 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});729 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {}});592 await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))730 const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');731 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};593 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);732594733 const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});595 // Try to create a token to be nested and nest734735 // Create a nested token736 await expect(executeTransaction(api, alice, api.tx.unique.createItem(737 collectionRFT,738 targetAddress,739 {ReFungible: {pieces: 100}},740 )), 'while creating a nested token').to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);741742 // Create a token to be nested743 const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');596 const token = await collectionRFT.mintToken(alice, 5n);744 // Try to nest745 await transferExpectFailure(collectionRFT, newToken, alice, targetAddress, 100);746 // Try to nest597 await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))747 await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);598 .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);748749 // Create another token to be nested599 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);750 const newToken2 = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');751 // Try to nest inside a fungible token752 await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionRFT, newToken)}, collectionRFT, newToken2, 1)), 'while nesting new token inside refungible').to.be.rejectedWith(/refungible\.RefungibleDisallowsNesting/);753 });754 });600 });755601756 it('ReFungible: disallows a non-Owner to nest someone else\'s token', async function() {602 itSub.ifWithPallets('ReFungible: disallows a non-Owner to nest someone else\'s token', [Pallets.ReFungible], async ({helper}) => {757 await requirePallets(this, [Pallets.ReFungible]);603 const collectionNFT = await helper.nft.mintCollection(alice);604 const collectionRFT = await helper.rft.mintCollection(alice);605 const targetToken = await collectionNFT.mintToken(alice);758606759 await usingApi(async api => {607 await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});760 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});608 await collectionNFT.addToAllowList(alice, {Substrate: bob.address});761 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});609 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());762610763 await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);611 // Try to create a token to be nested and nest764 await enableAllowListExpectSuccess(alice, collectionNFT);612 const newToken = await collectionRFT.mintToken(alice);765 await enablePublicMintingExpectSuccess(alice, collectionNFT);613 await expect(newToken.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.TokenValueTooLow/);766614767 // Create a token to attempt to be nested into615 expect(await targetToken.getChildren()).to.be.length(0);768 const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');769 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};616 expect(await newToken.getBalance({Substrate: alice.address})).to.be.equal(1n);770617771 const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});618 // Nest some tokens as Alice into Bob's token619 await newToken.transfer(alice, targetToken.nestingAccount());772620773 // Try to create a nested token in the wrong collection621 // Try to pull it out774 await expect(executeTransaction(api, alice, api.tx.unique.createItem(622 await expect(newToken.transferFrom(bob, targetToken.nestingAccount(), {Substrate: alice.address}, 1n))775 collectionRFT,776 targetAddress,777 {ReFungible: {pieces: 100}},778 )), 'while creating a nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);623 .to.be.rejectedWith(/common\.ApprovedValueTooLow/);779780 // Try to create and nest a token in the wrong collection624 expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(1n);781 const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');782 await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);783 });784 });625 });785626786 it('ReFungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async function() {627 itSub.ifWithPallets('ReFungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', [Pallets.ReFungible], async ({helper}) => {787 await requirePallets(this, [Pallets.ReFungible]);628 const collectionNFT = await helper.nft.mintCollection(alice);629 const collectionRFT = await helper.rft.mintCollection(alice);630 const targetToken = await collectionNFT.mintToken(alice);788631789 await usingApi(async api => {632 await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: [collectionRFT.collectionId]}});790 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});791 await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);633 await collectionNFT.addToAllowList(alice, {Substrate: bob.address});792 await enableAllowListExpectSuccess(alice, collectionNFT);634 await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());793 await enablePublicMintingExpectSuccess(alice, collectionNFT);794635795 // Create a token to attempt to be nested into636 // Try to create a token to be nested and nest796 const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');637 const newToken = await collectionRFT.mintToken(alice);797 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};638 await expect(newToken.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.TokenValueTooLow/);798639799 const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});640 expect(await targetToken.getChildren()).to.be.length(0);800 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionRFT]}});641 expect(await newToken.getBalance({Substrate: alice.address})).to.be.equal(1n);801642802 // Try to create a nested token in the wrong collection643 // Nest some tokens as Alice into Bob's token803 await expect(executeTransaction(api, alice, api.tx.unique.createItem(644 await newToken.transfer(alice, targetToken.nestingAccount());804 collectionRFT,805 targetAddress,806 {ReFungible: {pieces: 100}},807 )), 'while creating a nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);808645809 // Try to create and nest a token in the wrong collection646 // Try to pull it out810 const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');647 await expect(newToken.transferFrom(bob, targetToken.nestingAccount(), {Substrate: alice.address}, 1n))811 await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);648 .to.be.rejectedWith(/common\.ApprovedValueTooLow/);812 });649 expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(1n);813 });650 });814651815 it('ReFungible: disallows to nest token to an unlisted collection', async function() {652 itSub.ifWithPallets('ReFungible: disallows to nest token to an unlisted collection', [Pallets.ReFungible], async ({helper}) => {816 await requirePallets(this, [Pallets.ReFungible]);653 const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true, restricted: []}}});654 const collectionRFT = await helper.rft.mintCollection(alice);655 const targetToken = await collectionNFT.mintToken(alice);817656818 await usingApi(async api => {657 // Try to create an immediately nested token819 const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});658 await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))820 await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[]}});659 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);821660822 // Create a token to attempt to be nested into661 // Try to create a token to be nested and nest823 const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');662 const token = await collectionRFT.mintToken(alice, 5n);824 const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};663 await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))825826 const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});827828 // Try to create a nested token in the wrong collection829 await expect(executeTransaction(api, alice, api.tx.unique.createItem(830 collectionRFT,831 targetAddress,832 {ReFungible: {pieces: 100}},833 )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);664 .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);834835 // Try to create and nest a token in the wrong collection665 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);836 const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');837 await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);838 });839 });666 });840});667});841668tests/src/nesting/properties.test.tsdiffbeforeafterboth1import {expect} from 'chai';2import usingApi, {executeTransaction} from '../substrate/substrate-api';1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.3import {4 addCollectionAdminExpectSuccess,5 CollectionMode,6 createCollectionExpectSuccess,7 setCollectionPermissionsExpectSuccess,8 createItemExpectSuccess,9 getCreateCollectionResult,10 transferExpectSuccess,11 requirePallets,12 Pallets,13} from '../util/helpers';2// This file is part of Unique Network.14import {IKeyringPair} from '@polkadot/types/types';15import {tokenIdToAddress} from '../eth/util/helpers';16317let alice: IKeyringPair;4// Unique Network is free software: you can redistribute it and/or modify18let bob: IKeyringPair;5// it under the terms of the GNU General Public License as published by19let charlie: IKeyringPair;6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.20821describe('Composite Properties Test', () => {9// Unique Network is distributed in the hope that it will be useful,22 before(async () => {23 await usingApi(async (api, privateKeyWrapper) => {10// but WITHOUT ANY WARRANTY; without even the implied warranty of24 alice = privateKeyWrapper('//Alice');11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the25 bob = privateKeyWrapper('//Bob');12// GNU General Public License for more details.26 });27 });281329 async function testMakeSureSuppliesRequired(mode: CollectionMode) {14// You should have received a copy of the GNU General Public License30 await usingApi(async api => {31 const collectionId = await createCollectionExpectSuccess({mode: mode});15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.321633 const collectionOption = await api.rpc.unique.collectionById(collectionId);17import {IKeyringPair} from '@polkadot/types/types';34 expect(collectionOption.isSome).to.be.true;18import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from '../util/playgrounds';35 let collection = collectionOption.unwrap();36 expect(collection.tokenPropertyPermissions.toHuman()).to.be.empty;19import {UniqueHelper, UniqueBaseCollection, UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection, UniqueRFToken} from '../util/playgrounds/unique';37 expect(collection.properties.toHuman()).to.be.empty;382039 const propertyPermissions = [21// ---------- COLLECTION PROPERTIES40 {key: 'mindgame', permission: {collectionAdmin: true, mutable: false, tokenOwner: true}},41 {key: 'skullduggery', permission: {collectionAdmin: false, mutable: true, tokenOwner: false}},42 ];43 await expect(executeTransaction(44 api, 45 alice, 46 api.tx.unique.setTokenPropertyPermissions(collectionId, propertyPermissions), 47 )).to.not.be.rejected;482249 const collectionProperties = [50 {key: 'black_hole', value: 'LIGO'},23describe('Integration Test: Collection Properties', () => {51 {key: 'electron', value: 'come bond'}, 52 ];53 await expect(executeTransaction(54 api, 55 alice, 24 let alice: IKeyringPair;56 api.tx.unique.setCollectionProperties(collectionId, collectionProperties), 25 let bob: IKeyringPair;57 )).to.not.be.rejected;582659 collection = (await api.rpc.unique.collectionById(collectionId)).unwrap();27 before(async () => {28 await usingPlaygrounds(async (helper, privateKey) => {60 expect(collection.tokenPropertyPermissions.toHuman()).to.be.deep.equal(propertyPermissions);29 const donor = privateKey('//Alice');61 expect(collection.properties.toHuman()).to.be.deep.equal(collectionProperties);30 [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);62 });31 });63 }32 });643365 it('Makes sure collectionById supplies required fields for NFT', async () => {34 itSub('Properties are initially empty', async ({helper}) => {66 await testMakeSureSuppliesRequired({type: 'NFT'});35 const collection = await helper.nft.mintCollection(alice);36 expect(await collection.getProperties()).to.be.empty;67 });37 });683869 it('Makes sure collectionById supplies required fields for ReFungible', async function() {39 async function testSetsPropertiesForCollection(collection: UniqueBaseCollection) {40 // As owner70 await requirePallets(this, [Pallets.ReFungible]);41 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;714272 await testMakeSureSuppliesRequired({type: 'ReFungible'});43 await collection.addAdmin(alice, {Substrate: bob.address});73 });74});754476// ---------- COLLECTION PROPERTIES45 // As administrator46 await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;774778describe('Integration Test: Collection Properties', () => {48 const properties = await collection.getProperties();79 before(async () => {49 expect(properties).to.include.deep.members([80 await usingApi(async (api, privateKeyWrapper) => {50 {key: 'electron', value: 'come bond'},81 alice = privateKeyWrapper('//Alice');51 {key: 'black_hole', value: ''},52 ]);82 bob = privateKeyWrapper('//Bob');53 }5455 itSub('Sets properties for a NFT collection', async ({helper}) => {83 });56 await testSetsPropertiesForCollection(await helper.nft.mintCollection(alice));84 });57 });855886 it('Reads properties from a collection', async () => {59 itSub.ifWithPallets('Sets properties for a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {87 await usingApi(async api => {60 await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));88 const collection = await createCollectionExpectSuccess();89 const properties = (await api.query.common.collectionProperties(collection)).toJSON();90 expect(properties.map).to.be.empty;91 expect(properties.consumedSpace).to.equal(0);92 });93 });61 });946263 async function testCheckValidNames(collection: UniqueBaseCollection) {64 // alpha symbols65 await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;956696 async function testSetsPropertiesForCollection(mode: string) {67 // numeric symbols97 await usingApi(async api => {68 await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;98 const events = await executeTransaction(api, bob, api.tx.unique.createCollectionEx({mode: mode}));99 const {collectionId} = getCreateCollectionResult(events);10069101 // As owner70 // underscore symbol102 await expect(executeTransaction(71 await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;103 api, 104 bob, 105 api.tx.unique.setCollectionProperties(collectionId, [{key: 'electron', value: 'come bond'}]), 106 )).to.not.be.rejected;10772108 await addCollectionAdminExpectSuccess(bob, collectionId, alice.address);73 // dash symbol74 await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;10975110 // As administrator76 // dot symbol111 await expect(executeTransaction(77 await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;112 api, 113 alice, 114 api.tx.unique.setCollectionProperties(collectionId, [{key: 'black_hole'}]), 115 )).to.not.be.rejected;11678117 const properties = (await api.rpc.unique.collectionProperties(collectionId, ['electron', 'black_hole'])).toHuman();79 const properties = await collection.getProperties();118 expect(properties).to.be.deep.equal([80 expect(properties).to.include.deep.members([119 {key: 'electron', value: 'come bond'},81 {key: 'answer', value: ''},82 {key: '451', value: ''},120 {key: 'black_hole', value: ''},83 {key: 'black_hole', value: ''},84 {key: '-', value: ''},121 ]);85 {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},122 });86 ]);123 }87 }124 it('Sets properties for a NFT collection', async () => {125 await testSetsPropertiesForCollection('NFT');126 });127 it('Sets properties for a ReFungible collection', async function() {128 await requirePallets(this, [Pallets.ReFungible]);12988130 await testSetsPropertiesForCollection('ReFungible');89 itSub('Check valid names for NFT collection properties keys', async ({helper}) => {90 await testCheckValidNames(await helper.nft.mintCollection(alice));131 });91 });13292133 async function testCheckValidNames(mode: string) {93 itSub.ifWithPallets('Check valid names for ReFungible collection properties keys', [Pallets.ReFungible], async ({helper}) => {134 await usingApi(async api => {135 const events = await executeTransaction(api, bob, api.tx.unique.createCollectionEx({mode: mode}));136 const {collectionId} = getCreateCollectionResult(events);137 138 // alpha symbols139 await expect(executeTransaction(140 api, 141 bob, 142 api.tx.unique.setCollectionProperties(collectionId, [{key: 'alpha'}]), 143 )).to.not.be.rejected;144 145 // numeric symbols146 await expect(executeTransaction(147 api, 148 bob, 149 api.tx.unique.setCollectionProperties(collectionId, [{key: '123'}]), 150 )).to.not.be.rejected;151 152 // underscore symbol153 await expect(executeTransaction(154 api, 155 bob, 156 api.tx.unique.setCollectionProperties(collectionId, [{key: 'black_hole'}]), 157 )).to.not.be.rejected;158 159 // dash symbol160 await expect(executeTransaction(161 api, 162 bob, 163 api.tx.unique.setCollectionProperties(collectionId, [{key: 'semi-automatic'}]), 164 )).to.not.be.rejected;165 166 // underscore symbol167 await expect(executeTransaction(168 api, 169 bob, 170 api.tx.unique.setCollectionProperties(collectionId, [{key: 'build.rs'}]), 171 )).to.not.be.rejected;172 173 const propertyKeys = ['alpha', '123', 'black_hole', 'semi-automatic', 'build.rs'];174 const properties = (await api.rpc.unique.collectionProperties(collectionId, propertyKeys)).toHuman();94 await testCheckValidNames(await helper.rft.mintCollection(alice));175 expect(properties).to.be.deep.equal([176 {key: 'alpha', value: ''},177 {key: '123', value: ''},178 {key: 'black_hole', value: ''},179 {key: 'semi-automatic', value: ''},180 {key: 'build.rs', value: ''},181 ]);182 });183 }184 it('Check valid names for NFT collection properties keys', async () => {185 await testCheckValidNames('NFT');186 });95 });187 it('Check valid names for ReFungible collection properties keys', async function() {188 await requirePallets(this, [Pallets.ReFungible]);18996190 await testCheckValidNames('ReFungible');97 async function testChangesProperties(collection: UniqueBaseCollection) {191 });98 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;19299193 async function testChangesProperties(mode: CollectionMode) {100 // Mutate the properties194 await usingApi(async api => {195 const collection = await createCollectionExpectSuccess({mode: mode});196 197 await expect(executeTransaction(198 api, 199 alice, 200 api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole'}]), 201 )).to.not.be.rejected;202 203 // Mutate the properties204 await expect(executeTransaction(101 await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;205 api, 102206 alice, 207 api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'bonded'}, {key: 'black_hole', value: 'LIGO'}]), 208 )).to.not.be.rejected;209 210 const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black_hole'])).toHuman();103 const properties = await collection.getProperties();211 expect(properties).to.be.deep.equal([104 expect(properties).to.include.deep.members([212 {key: 'electron', value: 'bonded'},105 {key: 'electron', value: 'come bond'},213 {key: 'black_hole', value: 'LIGO'},106 {key: 'black_hole', value: 'LIGO'},214 ]);107 ]);215 });216 }108 }109217 it('Changes properties of a NFT collection', async () => {110 itSub('Changes properties of a NFT collection', async ({helper}) => {218 await testChangesProperties({type: 'NFT'});111 await testChangesProperties(await helper.nft.mintCollection(alice));219 });112 });220 it('Changes properties of a ReFungible collection', async function() {221 await requirePallets(this, [Pallets.ReFungible]);222113223 await testChangesProperties({type: 'ReFungible'});114 itSub.ifWithPallets('Changes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {115 await testChangesProperties(await helper.rft.mintCollection(alice));224 });116 });225117226 async function testDeleteProperties(mode: CollectionMode) {118 async function testDeleteProperties(collection: UniqueBaseCollection) {227 await usingApi(async api => {119 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;228 const collection = await createCollectionExpectSuccess({mode: mode});120229 230 await expect(executeTransaction(231 api, 232 alice, 233 api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]), 234 )).to.not.be.rejected;235 236 await expect(executeTransaction(121 await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;237 api, 122238 alice, 239 api.tx.unique.deleteCollectionProperties(collection, ['electron']), 240 )).to.not.be.rejected;241 242 const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black_hole'])).toHuman();123 const properties = await collection.getProperties(['black_hole', 'electron']);243 expect(properties).to.be.deep.equal([124 expect(properties).to.be.deep.equal([244 {key: 'black_hole', value: 'LIGO'},125 {key: 'black_hole', value: 'LIGO'},245 ]);126 ]);246 }); 247 }127 }128248 it('Deletes properties of a NFT collection', async () => {129 itSub('Deletes properties of a NFT collection', async ({helper}) => {249 await testDeleteProperties({type: 'NFT'});130 await testDeleteProperties(await helper.nft.mintCollection(alice));250 });131 });251 it('Deletes properties of a ReFungible collection', async function() {252 await requirePallets(this, [Pallets.ReFungible]);253132254 await testDeleteProperties({type: 'ReFungible'});133 itSub.ifWithPallets('Deletes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {134 await testDeleteProperties(await helper.rft.mintCollection(alice));255 });135 });256});136});257137258describe('Negative Integration Test: Collection Properties', () => {138describe('Negative Integration Test: Collection Properties', () => {139 let alice: IKeyringPair;140 let bob: IKeyringPair;141259 before(async () => {142 before(async () => {260 await usingApi(async (api, privateKeyWrapper) => {143 await usingPlaygrounds(async (helper, privateKey) => {261 alice = privateKeyWrapper('//Alice');144 const donor = privateKey('//Alice');262 bob = privateKeyWrapper('//Bob');145 [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);263 });146 });264 });147 });265 148 266 async function testFailsSetPropertiesIfNotOwnerOrAdmin(mode: CollectionMode) {149 async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueBaseCollection) { 267 await usingApi(async api => {268 const collection = await createCollectionExpectSuccess({mode: mode});150 await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))269 270 await expect(executeTransaction(271 api, 272 bob, 273 api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]), 274 )).to.be.rejectedWith(/common\.NoPermission/);151 .to.be.rejectedWith(/common\.NoPermission/);275 152276 const properties = (await api.query.common.collectionProperties(collection)).toJSON();153 expect(await collection.getProperties()).to.be.empty;277 expect(properties.map).to.be.empty;278 expect(properties.consumedSpace).to.equal(0);279 }); 280 }154 }155281 it('Fails to set properties in a NFT collection if not its onwer/administrator', async () => {156 itSub('Fails to set properties in a NFT collection if not its onwer/administrator', async ({helper}) => {282 await testFailsSetPropertiesIfNotOwnerOrAdmin({type: 'NFT'});157 await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.nft.mintCollection(alice));283 });158 });284 it('Fails to set properties in a ReFungible collection if not its onwer/administrator', async function() {285 await requirePallets(this, [Pallets.ReFungible]);286159287 await testFailsSetPropertiesIfNotOwnerOrAdmin({type: 'ReFungible'});160 itSub.ifWithPallets('Fails to set properties in a ReFungible collection if not its onwer/administrator', [Pallets.ReFungible], async ({helper}) => {161 await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));288 });162 });289 163 290 async function testFailsSetPropertiesThatExeedLimits(mode: CollectionMode) {164 async function testFailsSetPropertiesThatExeedLimits(collection: UniqueBaseCollection) {291 await usingApi(async api => {165 const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();292 const collection = await createCollectionExpectSuccess({mode: mode});293 const spaceLimit = (await api.query.common.collectionProperties(collection)).toJSON().spaceLimit as number; 294 166 295 // Mute the general tx parsing error, too many bytes to process167 // Mute the general tx parsing error, too many bytes to process296 {168 {297 console.error = () => {};169 console.error = () => {};298 await expect(executeTransaction(170 await expect(collection.setProperties(alice, [299 api, 300 alice, 301 api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))}]), 171 {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},302 )).to.be.rejected;172 ])).to.be.rejected;303 }173 }304 174305 let properties = (await api.rpc.unique.collectionProperties(collection, ['electron'])).toJSON();175 expect(await collection.getProperties(['electron'])).to.be.empty;306 expect(properties).to.be.empty;176307 308 await expect(executeTransaction(177 await expect(collection.setProperties(alice, [309 api, 310 alice, 311 api.tx.unique.setCollectionProperties(collection, [312 {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))}, 178 {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))}, 313 {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 179 {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 314 ]), 180 ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);315 )).to.be.rejectedWith(/common\.NoSpaceForProperty/);181316 317 properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black hole'])).toJSON();182 expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;318 expect(properties).to.be.empty;319 }); 320 }183 }184321 it('Fails to set properties that exceed the limits (NFT)', async () => {185 itSub('Fails to set properties that exceed the limits (NFT)', async ({helper}) => {322 await testFailsSetPropertiesThatExeedLimits({type: 'NFT'});186 await testFailsSetPropertiesThatExeedLimits(await helper.nft.mintCollection(alice));323 });187 });324 it('Fails to set properties that exceed the limits (ReFungible)', async function() {325 await requirePallets(this, [Pallets.ReFungible]);326188327 await testFailsSetPropertiesThatExeedLimits({type: 'ReFungible'});189 itSub.ifWithPallets('Fails to set properties that exceed the limits (ReFungible)', [Pallets.ReFungible], async ({helper}) => {190 await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));328 });191 });329 192 330 async function testFailsSetMorePropertiesThanAllowed(mode: CollectionMode) {193 async function testFailsSetMorePropertiesThanAllowed(collection: UniqueBaseCollection) {331 await usingApi(async api => {194 const propertiesToBeSet = [];332 const collection = await createCollectionExpectSuccess({mode: mode});333 334 const propertiesToBeSet = [];335 for (let i = 0; i < 65; i++) {195 for (let i = 0; i < 65; i++) {336 propertiesToBeSet.push({196 propertiesToBeSet.push({337 key: 'electron_' + i,197 key: 'electron_' + i,338 value: Math.random() > 0.5 ? 'high' : 'low',198 value: Math.random() > 0.5 ? 'high' : 'low',339 });199 });340 }200 }341 201342 await expect(executeTransaction(202 await expect(collection.setProperties(alice, propertiesToBeSet)).343 api, 344 alice, 345 api.tx.unique.setCollectionProperties(collection, propertiesToBeSet), 346 )).to.be.rejectedWith(/common\.PropertyLimitReached/);203 to.be.rejectedWith(/common\.PropertyLimitReached/);347 204348 const properties = (await api.query.common.collectionProperties(collection)).toJSON();205 expect(await collection.getProperties()).to.be.empty;349 expect(properties.map).to.be.empty;350 expect(properties.consumedSpace).to.equal(0);351 }); 352 }206 }207353 it('Fails to set more properties than it is allowed (NFT)', async () => {208 itSub('Fails to set more properties than it is allowed (NFT)', async ({helper}) => {354 await testFailsSetMorePropertiesThanAllowed({type: 'NFT'});209 await testFailsSetMorePropertiesThanAllowed(await helper.nft.mintCollection(alice));355 });210 });356 it('Fails to set more properties than it is allowed (ReFungible)', async function() {357 await requirePallets(this, [Pallets.ReFungible]);358211359 await testFailsSetMorePropertiesThanAllowed({type: 'ReFungible'});212 itSub.ifWithPallets('Fails to set more properties than it is allowed (ReFungible)', [Pallets.ReFungible], async ({helper}) => {213 await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));360 });214 });361 215 362 async function testFailsSetPropertiesWithInvalidNames(mode: CollectionMode) {216 async function testFailsSetPropertiesWithInvalidNames(collection: UniqueBaseCollection) {363 await usingApi(async api => {217 const invalidProperties = [364 const collection = await createCollectionExpectSuccess({mode: mode});365 366 const invalidProperties = [367 [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],218 [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],368 [{key: 'Mr/Sandman', value: 'Bring me a gene'}],219 [{key: 'Mr/Sandman', value: 'Bring me a gene'}],369 [{key: 'déjà vu', value: 'hmm...'}],220 [{key: 'déjà vu', value: 'hmm...'}],370 ];221 ];371 222372 for (let i = 0; i < invalidProperties.length; i++) {223 for (let i = 0; i < invalidProperties.length; i++) {373 await expect(executeTransaction(224 await expect(374 api, 225 collection.setProperties(alice, invalidProperties[i]), 375 alice, 376 api.tx.unique.setCollectionProperties(collection, invalidProperties[i]), 377 ), `on rejecting the new badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);226 `on rejecting the new badly-named property #${i}`,227 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);378 }228 }379 229380 await expect(executeTransaction(230 await expect(381 api, 231 collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]), 382 alice, 383 api.tx.unique.setCollectionProperties(collection, [{key: '', value: 'nothing must not exist'}]), 384 ), 'on rejecting an unnamed property').to.be.rejectedWith(/common\.EmptyPropertyKey/);232 'on rejecting an unnamed property',385 233 ).to.be.rejectedWith(/common\.EmptyPropertyKey/);234386 await expect(executeTransaction(235 await expect(387 api, 236 collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]), 388 alice, 389 api.tx.unique.setCollectionProperties(collection, [390 {key: 'CRISPR-Cas9', value: 'rewriting nature!'},391 ]), 392 ), 'on setting the correctly-but-still-badly-named property').to.not.be.rejected;237 'on setting the correctly-but-still-badly-named property',393 238 ).to.be.fulfilled;239394 const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');240 const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');395 241396 const properties = (await api.rpc.unique.collectionProperties(collection, keys)).toHuman();242 const properties = await collection.getProperties(keys);397 expect(properties).to.be.deep.equal([243 expect(properties).to.be.deep.equal([398 {key: 'CRISPR-Cas9', value: 'rewriting nature!'},244 {key: 'CRISPR-Cas9', value: 'rewriting nature!'},399 ]);245 ]);400 246401 for (let i = 0; i < invalidProperties.length; i++) {247 for (let i = 0; i < invalidProperties.length; i++) {402 await expect(executeTransaction(248 await expect(403 api, 249 collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)), 404 alice, 405 api.tx.unique.deleteCollectionProperties(collection, invalidProperties[i].map(propertySet => propertySet.key)), 406 ), `on trying to delete the non-existent badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);250 `on trying to delete the non-existent badly-named property #${i}`,251 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);407 }252 }408 });409 }253 }254410 it('Fails to set properties with invalid names (NFT)', async () => {255 itSub('Fails to set properties with invalid names (NFT)', async ({helper}) => {411 await testFailsSetPropertiesWithInvalidNames({type: 'NFT'});256 await testFailsSetPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));412 });257 });413 it('Fails to set properties with invalid names (ReFungible)', async function() {414 await requirePallets(this, [Pallets.ReFungible]);415258416 await testFailsSetPropertiesWithInvalidNames({type: 'ReFungible'});259 itSub.ifWithPallets('Fails to set properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {260 await testFailsSetPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));417 });261 });418});262});419263420// ---------- ACCESS RIGHTS264// ---------- ACCESS RIGHTS421265422describe('Integration Test: Access Rights to Token Properties', () => {266describe('Integration Test: Access Rights to Token Properties', () => {267 let alice: IKeyringPair;268 let bob: IKeyringPair;269423 before(async () => {270 before(async () => {424 await usingApi(async (api, privateKeyWrapper) => {271 await usingPlaygrounds(async (helper, privateKey) => {425 alice = privateKeyWrapper('//Alice');272 const donor = privateKey('//Alice');426 bob = privateKeyWrapper('//Bob');273 [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);427 });274 });428 });275 });429 276 430 it('Reads access rights to properties of a collection', async () => {277 itSub('Reads access rights to properties of a collection', async ({helper}) => {431 await usingApi(async api => {432 const collection = await createCollectionExpectSuccess();278 const collection = await helper.nft.mintCollection(alice);433 const propertyRights = (await api.query.common.collectionPropertyPermissions(collection)).toJSON();279 const propertyRights = (await helper.api!.query.common.collectionPropertyPermissions(collection.collectionId)).toJSON();434 expect(propertyRights).to.be.empty;280 expect(propertyRights).to.be.empty;435 });436 });281 });437 282 438 async function testSetsAccessRightsToProperties(mode: CollectionMode) {283 async function testSetsAccessRightsToProperties(collection: UniqueNFTCollection | UniqueRFTCollection) { 439 await usingApi(async api => {440 const collection = await createCollectionExpectSuccess({mode: mode});441 284 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true}}]))442 await expect(executeTransaction(443 api, 444 alice, 445 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: true}}]), 446 )).to.not.be.rejected;285 .to.be.fulfilled;447 286448 await addCollectionAdminExpectSuccess(alice, collection, bob.address);287 await collection.addAdmin(alice, {Substrate: bob.address});449 288450 await expect(executeTransaction(289 await expect(collection.setTokenPropertyPermissions(bob, [{key: 'mindgame', permission: {collectionAdmin: true, tokenOwner: false}}]))451 api, 452 alice, 453 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'mindgame', permission: {collectionAdmin: true, tokenOwner: false}}]), 454 )).to.not.be.rejected;290 .to.be.fulfilled;455 291456 const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery', 'mindgame'])).toHuman();292 const propertyRights = await collection.getPropertyPermissions(['skullduggery', 'mindgame']);457 expect(propertyRights).to.be.deep.equal([293 expect(propertyRights).to.include.deep.members([458 {key: 'skullduggery', permission: {'mutable': true, 'collectionAdmin': false, 'tokenOwner': false}},294 {key: 'skullduggery', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}},459 {key: 'mindgame', permission: {'mutable': false, 'collectionAdmin': true, 'tokenOwner': false}},295 {key: 'mindgame', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},460 ]);296 ]);461 }); 462 }297 }298463 it('Sets access rights to properties of a collection (NFT)', async () => {299 itSub('Sets access rights to properties of a collection (NFT)', async ({helper}) => {464 await testSetsAccessRightsToProperties({type: 'NFT'});300 await testSetsAccessRightsToProperties(await helper.nft.mintCollection(alice));465 });301 });466 it('Sets access rights to properties of a collection (ReFungible)', async function() {467 await requirePallets(this, [Pallets.ReFungible]);468302469 await testSetsAccessRightsToProperties({type: 'ReFungible'});303 itSub.ifWithPallets('Sets access rights to properties of a collection (ReFungible)', [Pallets.ReFungible], async ({helper}) => {304 await testSetsAccessRightsToProperties(await helper.rft.mintCollection(alice));470 });305 });471 306 472 async function testChangesAccessRightsToProperty(mode: CollectionMode) {307 async function testChangesAccessRightsToProperty(collection: UniqueNFTCollection | UniqueRFTCollection) {473 await usingApi(async api => {474 const collection = await createCollectionExpectSuccess({mode: mode});308 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true, collectionAdmin: true}}]))475 476 await expect(executeTransaction(477 api, 478 alice, 479 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: true, collectionAdmin: true}}]), 480 )).to.not.be.rejected;309 .to.be.fulfilled;481 310482 await expect(executeTransaction(311 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]))483 api, 484 alice, 485 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]), 486 )).to.not.be.rejected;312 .to.be.fulfilled;487 313488 const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toHuman();314 const propertyRights = await collection.getPropertyPermissions();489 expect(propertyRights).to.be.deep.equal([315 expect(propertyRights).to.be.deep.equal([490 {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},316 {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},491 ]);317 ]);492 });493 }318 }319494 it('Changes access rights to properties of a NFT collection', async () => {320 itSub('Changes access rights to properties of a NFT collection', async ({helper}) => {495 await testChangesAccessRightsToProperty({type: 'NFT'});321 await testChangesAccessRightsToProperty(await helper.nft.mintCollection(alice));496 });322 });497 it('Changes access rights to properties of a ReFungible collection', async function() {498 await requirePallets(this, [Pallets.ReFungible]);499323500 await testChangesAccessRightsToProperty({type: 'ReFungible'});324 itSub.ifWithPallets('Changes access rights to properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {325 await testChangesAccessRightsToProperty(await helper.rft.mintCollection(alice));501 });326 });502});327});503328504describe('Negative Integration Test: Access Rights to Token Properties', () => {329describe('Negative Integration Test: Access Rights to Token Properties', () => {330 let alice: IKeyringPair;331 let bob: IKeyringPair;332505 before(async () => {333 before(async () => {506 await usingApi(async (api, privateKeyWrapper) => {334 await usingPlaygrounds(async (helper, privateKey) => {507 alice = privateKeyWrapper('//Alice');335 const donor = privateKey('//Alice');508 bob = privateKeyWrapper('//Bob');336 [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);509 });337 });510 });338 });511339512 async function testPreventsFromSettingAccessRightsNotAdminOrOwner(mode: CollectionMode) {340 async function testPreventsFromSettingAccessRightsNotAdminOrOwner(collection: UniqueNFTCollection | UniqueRFTCollection) {513 await usingApi(async api => {514 const collection = await createCollectionExpectSuccess({mode: mode});341 await expect(collection.setTokenPropertyPermissions(bob, [{key: 'skullduggery', permission: {mutable: true, tokenOwner: true}}]))515 516 await expect(executeTransaction(517 api, 518 bob, 519 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: true, tokenOwner: true}}]), 520 )).to.be.rejectedWith(/common\.NoPermission/);342 .to.be.rejectedWith(/common\.NoPermission/);521 343522 const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toJSON();344 const propertyRights = await collection.getPropertyPermissions(['skullduggery']);523 expect(propertyRights).to.be.empty;345 expect(propertyRights).to.be.empty;524 });525 }346 }347526 it('Prevents from setting access rights to properties of a NFT collection if not an onwer/admin', async () => {348 itSub('Prevents from setting access rights to properties of a NFT collection if not an onwer/admin', async ({helper}) => {527 await testPreventsFromSettingAccessRightsNotAdminOrOwner({type: 'NFT'});349 await testPreventsFromSettingAccessRightsNotAdminOrOwner(await helper.nft.mintCollection(alice));528 });350 });529 it('Prevents from setting access rights to properties of a ReFungible collection if not an onwer/admin', async function() {530 await requirePallets(this, [Pallets.ReFungible]);531351532 await testPreventsFromSettingAccessRightsNotAdminOrOwner({type: 'ReFungible'});352 itSub.ifWithPallets('Prevents from setting access rights to properties of a ReFungible collection if not an onwer/admin', [Pallets.ReFungible], async ({helper}) => {353 await testPreventsFromSettingAccessRightsNotAdminOrOwner(await helper.rft.mintCollection(alice));533 });354 });534355535 async function testPreventFromAddingTooManyPossibleProperties(mode: CollectionMode) {356 async function testPreventFromAddingTooManyPossibleProperties(collection: UniqueNFTCollection | UniqueRFTCollection) { 536 await usingApi(async api => {537 const collection = await createCollectionExpectSuccess({mode: mode});538 357 const constitution = [];539 const constitution = [];540 for (let i = 0; i < 65; i++) {358 for (let i = 0; i < 65; i++) {541 constitution.push({359 constitution.push({542 key: 'property_' + i,360 key: 'property_' + i,543 permission: Math.random() > 0.5 ? {mutable: true, collectionAdmin: true, tokenOwner: true} : {},361 permission: Math.random() > 0.5 ? {mutable: true, collectionAdmin: true, tokenOwner: true} : {},544 });362 });545 }363 }546 364547 await expect(executeTransaction(365 await expect(collection.setTokenPropertyPermissions(alice, constitution))548 api, 549 alice, 550 api.tx.unique.setTokenPropertyPermissions(collection, constitution), 551 )).to.be.rejectedWith(/common\.PropertyLimitReached/);366 .to.be.rejectedWith(/common\.PropertyLimitReached/);552 367553 const propertyRights = (await api.query.common.collectionPropertyPermissions(collection)).toJSON();368 const propertyRights = await collection.getPropertyPermissions();554 expect(propertyRights).to.be.empty;369 expect(propertyRights).to.be.empty;555 }); 556 }370 }371557 it('Prevents from adding too many possible properties (NFT)', async () => {372 itSub('Prevents from adding too many possible properties (NFT)', async ({helper}) => {558 await testPreventFromAddingTooManyPossibleProperties({type: 'NFT'});373 await testPreventFromAddingTooManyPossibleProperties(await helper.nft.mintCollection(alice));559 });374 });560 it('Prevents from adding too many possible properties (ReFungible)', async function() {561 await requirePallets(this, [Pallets.ReFungible]);562375563 await testPreventFromAddingTooManyPossibleProperties({type: 'ReFungible'});376 itSub.ifWithPallets('Prevents from adding too many possible properties (ReFungible)', [Pallets.ReFungible], async ({helper}) => {377 await testPreventFromAddingTooManyPossibleProperties(await helper.rft.mintCollection(alice));564 });378 });565379566 async function testPreventAccessRightsModifiedIfConstant(mode: CollectionMode) {380 async function testPreventAccessRightsModifiedIfConstant(collection: UniqueNFTCollection | UniqueRFTCollection) {567 await usingApi(async api => {568 const collection = await createCollectionExpectSuccess({mode: mode});381 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]))569 570 await expect(executeTransaction(571 api, 572 alice, 573 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]), 574 )).to.not.be.rejected;382 .to.be.fulfilled;575 383576 await expect(executeTransaction(384 await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {collectionAdmin: true}}]))577 api, 578 alice, 579 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {}}]), 580 )).to.be.rejectedWith(/common\.NoPermission/);385 .to.be.rejectedWith(/common\.NoPermission/);581 386582 const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toHuman();387 const propertyRights = await collection.getPropertyPermissions(['skullduggery']);583 expect(propertyRights).to.deep.equal([388 expect(propertyRights).to.deep.equal([584 {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},389 {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},585 ]);390 ]);586 }); 587 }391 }392588 it('Prevents access rights to be modified if constant (NFT)', async () => {393 itSub('Prevents access rights to be modified if constant (NFT)', async ({helper}) => {589 await testPreventAccessRightsModifiedIfConstant({type: 'NFT'});394 await testPreventAccessRightsModifiedIfConstant(await helper.nft.mintCollection(alice));590 });395 });591 it('Prevents access rights to be modified if constant (ReFungible)', async function() {592 await requirePallets(this, [Pallets.ReFungible]);593396594 await testPreventAccessRightsModifiedIfConstant({type: 'ReFungible'});397 itSub.ifWithPallets('Prevents access rights to be modified if constant (ReFungible)', [Pallets.ReFungible], async ({helper}) => {398 await testPreventAccessRightsModifiedIfConstant(await helper.rft.mintCollection(alice));595 });399 });596400597 async function testPreventsAddingPropertiesWithInvalidNames(mode: CollectionMode) {401 async function testPreventsAddingPropertiesWithInvalidNames(collection: UniqueNFTCollection | UniqueRFTCollection) {598 await usingApi(async api => {599 const collection = await createCollectionExpectSuccess({mode: mode});402 const invalidProperties = [600 601 const invalidProperties = [602 [{key: 'skullduggery', permission: {tokenOwner: true}}, {key: 'im possible', permission: {collectionAdmin: true}}],403 [{key: 'skullduggery', permission: {tokenOwner: true}}, {key: 'im possible', permission: {collectionAdmin: true}}],603 [{key: 'G#4', permission: {tokenOwner: true}}],404 [{key: 'G#4', permission: {tokenOwner: true}}],604 [{key: 'HÆMILTON', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}],405 [{key: 'HÆMILTON', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}],605 ];406 ];606 407607 for (let i = 0; i < invalidProperties.length; i++) {408 for (let i = 0; i < invalidProperties.length; i++) {608 await expect(executeTransaction(409 await expect(609 api, 410 collection.setTokenPropertyPermissions(alice, invalidProperties[i]), 610 alice, 611 api.tx.unique.setTokenPropertyPermissions(collection, invalidProperties[i]), 612 ), `on setting the new badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);411 `on setting the new badly-named property #${i}`,412 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);613 }413 }614 414615 await expect(executeTransaction(415 await expect(616 api, 416 collection.setTokenPropertyPermissions(alice, [{key: '', permission: {}}]), 617 alice, 618 api.tx.unique.setTokenPropertyPermissions(collection, [{key: '', permission: {}}]), 619 ), 'on rejecting an unnamed property').to.be.rejectedWith(/common\.EmptyPropertyKey/);417 'on rejecting an unnamed property',620 418 ).to.be.rejectedWith(/common\.EmptyPropertyKey/);419621 const correctKey = '--0x03116e387820CA05'; // PolkadotJS would parse this as an already encoded hex-string420 const correctKey = '--0x03116e387820CA05'; // PolkadotJS would parse this as an already encoded hex-string622 await expect(executeTransaction(421 await expect(623 api, 422 collection.setTokenPropertyPermissions(alice, [624 alice, 625 api.tx.unique.setTokenPropertyPermissions(collection, [626 {key: correctKey, permission: {collectionAdmin: true}},423 {key: correctKey, permission: {collectionAdmin: true}},627 ]), 424 ]), 628 ), 'on setting the correctly-but-still-badly-named property').to.not.be.rejected;425 'on setting the correctly-but-still-badly-named property',629 426 ).to.be.fulfilled;427630 const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat(correctKey).concat('');428 const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat(correctKey).concat('');631 429632 const propertyRights = (await api.rpc.unique.propertyPermissions(collection, keys)).toHuman();430 const propertyRights = await collection.getPropertyPermissions(keys);633 expect(propertyRights).to.be.deep.equal([431 expect(propertyRights).to.be.deep.equal([634 {key: correctKey, permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},432 {key: correctKey, permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},635 ]);433 ]);636 });637 }434 }435638 it('Prevents adding properties with invalid names (NFT)', async () => {436 itSub('Prevents adding properties with invalid names (NFT)', async ({helper}) => {639 await testPreventsAddingPropertiesWithInvalidNames({type: 'NFT'});437 await testPreventsAddingPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));640 });438 });641 it('Prevents adding properties with invalid names (ReFungible)', async function() {642 await requirePallets(this, [Pallets.ReFungible]);643439644 await testPreventsAddingPropertiesWithInvalidNames({type: 'ReFungible'});440 itSub.ifWithPallets('Prevents adding properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {441 await testPreventsAddingPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));645 });442 });646});443});647444648// ---------- TOKEN PROPERTIES445// ---------- TOKEN PROPERTIES649446650describe('Integration Test: Token Properties', () => {447describe('Integration Test: Token Properties', () => {448 let alice: IKeyringPair; // collection owner449 let bob: IKeyringPair; // collection admin450 let charlie: IKeyringPair; // token owner451651 let permissions: {permission: any, signers: IKeyringPair[]}[];452 let permissions: {permission: any, signers: IKeyringPair[]}[];652453653 before(async () => {454 before(async () => {654 await usingApi(async (api, privateKeyWrapper) => {455 await usingPlaygrounds(async (helper, privateKey) => {655 alice = privateKeyWrapper('//Alice'); // collection owner456 const donor = privateKey('//Alice');656 bob = privateKeyWrapper('//Bob'); // collection admin457 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);657 charlie = privateKeyWrapper('//Charlie'); // token owner658659 permissions = [660 {permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob]},661 {permission: {mutable: false, collectionAdmin: true}, signers: [alice, bob]},662 {permission: {mutable: true, tokenOwner: true}, signers: [charlie]},663 {permission: {mutable: false, tokenOwner: true}, signers: [charlie]},664 {permission: {mutable: true, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},665 {permission: {mutable: false, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},666 ];667 });458 });459460 // todo:playgrounds probably separate these tests later461 permissions = [462 {permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob]},463 {permission: {mutable: false, collectionAdmin: true}, signers: [alice, bob]},464 {permission: {mutable: true, tokenOwner: true}, signers: [charlie]},465 {permission: {mutable: false, tokenOwner: true}, signers: [charlie]},466 {permission: {mutable: true, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},467 {permission: {mutable: false, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},468 ];668 });469 });669 470 670 async function testReadsYetEmptyProperties(mode: CollectionMode) {471 async function testReadsYetEmptyProperties(token: UniqueNFToken | UniqueRFToken) {671 await usingApi(async api => {672 const collection = await createCollectionExpectSuccess({mode: mode});472 const properties = await token.getProperties();673 const token = await createItemExpectSuccess(alice, collection, mode.type);674 675 const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();676 expect(properties.map).to.be.empty;473 expect(properties).to.be.empty;677 expect(properties.consumedSpace).to.be.equal(0);474678 475 const tokenData = await token.getData();679 const tokenData = (await api.rpc.unique.tokenData(collection, token, ['anything'])).toJSON().properties;680 expect(tokenData).to.be.empty;476 expect(tokenData!.properties).to.be.empty;681 });682 }477 }478683 it('Reads yet empty properties of a token (NFT)', async () => {479 itSub('Reads yet empty properties of a token (NFT)', async ({helper}) => {684 await testReadsYetEmptyProperties({type: 'NFT'});480 const collection = await helper.nft.mintCollection(alice);481 const token = await collection.mintToken(alice);482 await testReadsYetEmptyProperties(token);685 });483 });686 it('Reads yet empty properties of a token (ReFungible)', async function() {687 await requirePallets(this, [Pallets.ReFungible]);688484689 await testReadsYetEmptyProperties({type: 'ReFungible'});485 itSub.ifWithPallets('Reads yet empty properties of a token (ReFungible)', [Pallets.ReFungible], async ({helper}) => {486 const collection = await helper.rft.mintCollection(alice);487 const token = await collection.mintToken(alice);488 await testReadsYetEmptyProperties(token);690 });489 });691490692 async function testAssignPropertiesAccordingToPermissions(mode: CollectionMode, pieces: number) {491 async function testAssignPropertiesAccordingToPermissions(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {693 await usingApi(async api => {492 await token.collection.addAdmin(alice, {Substrate: bob.address});694 const collection = await createCollectionExpectSuccess({mode: mode});695 const token = await createItemExpectSuccess(alice, collection, mode.type);696 await addCollectionAdminExpectSuccess(alice, collection, bob.address);697 await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);493 await token.transfer(alice, {Substrate: charlie.address}, pieces);698494699 const propertyKeys: string[] = [];495 const propertyKeys: string[] = [];700 let i = 0;496 let i = 0;701 for (const permission of permissions) {497 for (const permission of permissions) {702 for (const signer of permission.signers) {498 i++;499 let j = 0;500 for (const signer of permission.signers) {703 const key = i + '_' + signer.address;501 j++;502 const key = i + '_' + signer.address;704 propertyKeys.push(key);503 propertyKeys.push(key);705504706 await expect(executeTransaction(505 await expect(707 api, 506 token.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 708 alice, 709 api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 710 ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;507 `on setting permission #${i} by alice`,508 ).to.be.fulfilled;711509712 await expect(executeTransaction(510 await expect(713 api, 511 token.setProperties(signer, [{key: key, value: 'Serotonin increase'}]), 714 signer, 715 api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin increase'}]), 716 ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;512 `on adding property #${i} by signer #${j}`,717 }513 ).to.be.fulfilled;718719 i++;720 }514 }515 }721516722 const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toHuman() as any[];517 const properties = await token.getProperties(propertyKeys);723 const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toHuman().properties as any[];518 const tokenData = await token.getData();724 for (let i = 0; i < properties.length; i++) {519 for (let i = 0; i < properties.length; i++) {725 expect(properties[i].value).to.be.equal('Serotonin increase');520 expect(properties[i].value).to.be.equal('Serotonin increase');726 expect(tokensData[i].value).to.be.equal('Serotonin increase');521 expect(tokenData!.properties[i].value).to.be.equal('Serotonin increase');727 }522 }728 });729 }523 }524730 it('Assigns properties to a token according to permissions (NFT)', async () => {525 itSub('Assigns properties to a token according to permissions (NFT)', async ({helper}) => {731 await testAssignPropertiesAccordingToPermissions({type: 'NFT'}, 1);526 const collection = await helper.nft.mintCollection(alice);527 const token = await collection.mintToken(alice);528 await testAssignPropertiesAccordingToPermissions(token, 1n);732 });529 });733 it('Assigns properties to a token according to permissions (ReFungible)', async function() {734 await requirePallets(this, [Pallets.ReFungible]);735530736 await testAssignPropertiesAccordingToPermissions({type: 'ReFungible'}, 100);531 itSub.ifWithPallets('Assigns properties to a token according to permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {532 const collection = await helper.rft.mintCollection(alice);533 const token = await collection.mintToken(alice, 100n);534 await testAssignPropertiesAccordingToPermissions(token, 100n);737 });535 });738536739 async function testChangesPropertiesAccordingPermission(mode: CollectionMode, pieces: number) {537 async function testChangesPropertiesAccordingPermission(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {740 await usingApi(async api => {538 await token.collection.addAdmin(alice, {Substrate: bob.address});741 const collection = await createCollectionExpectSuccess({mode: mode});742 const token = await createItemExpectSuccess(alice, collection, mode.type);743 await addCollectionAdminExpectSuccess(alice, collection, bob.address);744 await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);539 await token.transfer(alice, {Substrate: charlie.address}, pieces);745540746 const propertyKeys: string[] = [];541 const propertyKeys: string[] = [];747 let i = 0;542 let i = 0;748 for (const permission of permissions) {543 for (const permission of permissions) {749 if (!permission.permission.mutable) continue;544 i++;545 if (!permission.permission.mutable) continue;750 546 751 for (const signer of permission.signers) {547 let j = 0;548 for (const signer of permission.signers) {752 const key = i + '_' + signer.address;549 j++;550 const key = i + '_' + signer.address;753 propertyKeys.push(key);551 propertyKeys.push(key);754 552755 await expect(executeTransaction(553 await expect(756 api, 554 token.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 757 alice, 758 api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 759 ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;555 `on setting permission #${i} by alice`,760 556 ).to.be.fulfilled;557761 await expect(executeTransaction(558 await expect(762 api, 559 token.setProperties(signer, [{key, value: 'Serotonin increase'}]), 763 signer, 764 api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin increase'}]), 765 ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;560 `on adding property #${i} by signer #${j}`,766 561 ).to.be.fulfilled;562767 await expect(executeTransaction(563 await expect(768 api, 564 token.setProperties(signer, [{key, value: 'Serotonin stable'}]), 769 signer, 770 api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin stable'}]), 771 ), `on changing property ${i} by ${signer.address}`).to.not.be.rejected;565 `on changing property #${i} by signer #${j}`,772 }566 ).to.be.fulfilled;773 774 i++;775 }567 }776 568 }569777 const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toHuman() as any[];570 const properties = await token.getProperties(propertyKeys);778 const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toHuman().properties as any[];571 const tokenData = await token.getData();779 for (let i = 0; i < properties.length; i++) {572 for (let i = 0; i < properties.length; i++) {780 expect(properties[i].value).to.be.equal('Serotonin stable');573 expect(properties[i].value).to.be.equal('Serotonin stable');781 expect(tokensData[i].value).to.be.equal('Serotonin stable');574 expect(tokenData!.properties[i].value).to.be.equal('Serotonin stable');782 }575 }783 });784 }576 }577785 it('Changes properties of a token according to permissions (NFT)', async () => {578 itSub('Changes properties of a token according to permissions (NFT)', async ({helper}) => {786 await testChangesPropertiesAccordingPermission({type: 'NFT'}, 1);579 const collection = await helper.nft.mintCollection(alice);580 const token = await collection.mintToken(alice);581 await testChangesPropertiesAccordingPermission(token, 1n);787 });582 });788 it('Changes properties of a token according to permissions (ReFungible)', async function() {789 await requirePallets(this, [Pallets.ReFungible]);790583791 await testChangesPropertiesAccordingPermission({type: 'ReFungible'}, 100);584 itSub.ifWithPallets('Changes properties of a token according to permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {585 const collection = await helper.rft.mintCollection(alice);586 const token = await collection.mintToken(alice, 100n);587 await testChangesPropertiesAccordingPermission(token, 100n);792 });588 });793589794 async function testDeletePropertiesAccordingPermission(mode: CollectionMode, pieces: number) {590 async function testDeletePropertiesAccordingPermission(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {795 await usingApi(async api => {591 await token.collection.addAdmin(alice, {Substrate: bob.address});796 const collection = await createCollectionExpectSuccess({mode: mode});797 const token = await createItemExpectSuccess(alice, collection, mode.type);798 await addCollectionAdminExpectSuccess(alice, collection, bob.address);799 await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);592 await token.transfer(alice, {Substrate: charlie.address}, pieces);800593801 const propertyKeys: string[] = [];594 const propertyKeys: string[] = [];802 let i = 0;595 let i = 0;803 596804 for (const permission of permissions) {597 for (const permission of permissions) {805 if (!permission.permission.mutable) continue;598 i++;599 if (!permission.permission.mutable) continue;806 600 807 for (const signer of permission.signers) {601 let j = 0;602 for (const signer of permission.signers) {808 const key = i + '_' + signer.address;603 j++;604 const key = i + '_' + signer.address;809 propertyKeys.push(key);605 propertyKeys.push(key);810 606811 await expect(executeTransaction(607 await expect(812 api, 608 token.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 813 alice, 814 api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 815 ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;609 `on setting permission #${i} by alice`,816 610 ).to.be.fulfilled;611817 await expect(executeTransaction(612 await expect(818 api, 613 token.setProperties(signer, [{key, value: 'Serotonin increase'}]), 819 signer, 820 api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin increase'}]), 821 ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;614 `on adding property #${i} by signer #${j}`,822 615 ).to.be.fulfilled;616823 await expect(executeTransaction(617 await expect(824 api, 618 token.deleteProperties(signer, [key]), 825 signer, 826 api.tx.unique.deleteTokenProperties(collection, token, [key]), 827 ), `on deleting property ${i} by ${signer.address}`).to.not.be.rejected;619 `on deleting property #${i} by signer #${j}`,828 }620 ).to.be.fulfilled;829 830 i++;831 }621 }832 622 }833 const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toJSON() as any[];623834 expect(properties).to.be.empty;624 expect(await token.getProperties(propertyKeys)).to.be.empty;835 const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toJSON().properties as any[];836 expect(tokensData).to.be.empty;837 expect((await api.query.nonfungible.tokenProperties(collection, token)).toJSON().consumedSpace).to.be.equal(0);625 expect((await token.getData())!.properties).to.be.empty;838 });839 }626 }840 it('Deletes properties of a token according to permissions (NFT)', async () => {627 628 itSub('Deletes properties of a token according to permissions (NFT)', async ({helper}) => {841 await testDeletePropertiesAccordingPermission({type: 'NFT'}, 1);629 const collection = await helper.nft.mintCollection(alice);630 const token = await collection.mintToken(alice);631 await testDeletePropertiesAccordingPermission(token, 1n);842 });632 });843 it('Deletes properties of a token according to permissions (ReFungible)', async function() {844 await requirePallets(this, [Pallets.ReFungible]);845633846 await testDeletePropertiesAccordingPermission({type: 'ReFungible'}, 100);634 itSub.ifWithPallets('Deletes properties of a token according to permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {635 const collection = await helper.rft.mintCollection(alice);636 const token = await collection.mintToken(alice, 100n);637 await testDeletePropertiesAccordingPermission(token, 100n);847 });638 });848639849 it('Assigns properties to a nested token according to permissions', async () => {640 itSub('Assigns properties to a nested token according to permissions', async ({helper}) => {850 await usingApi(async api => {851 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});641 const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});852 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});853 const token = await createItemExpectSuccess(alice, collection, 'NFT');642 const collectionB = await helper.nft.mintCollection(alice);854 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});643 const targetToken = await collectionA.mintToken(alice);855 await addCollectionAdminExpectSuccess(alice, collection, bob.address);644 const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());856 await transferExpectSuccess(collection, token, alice, charlie);857645858 const propertyKeys: string[] = [];646 await collectionB.addAdmin(alice, {Substrate: bob.address});859 let i = 0;860 for (const permission of permissions) {861 for (const signer of permission.signers) {862 const key = i + '_' + signer.address;647 await targetToken.transfer(alice, {Substrate: charlie.address});863 propertyKeys.push(key);864648865 await expect(executeTransaction(649 const propertyKeys: string[] = [];650 let i = 0;651 for (const permission of permissions) {652 i++;653 let j = 0;654 for (const signer of permission.signers) {866 api, 655 j++;656 const key = i + '_' + signer.address;867 alice, 657 propertyKeys.push(key);658 868 api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 659 await expect(660 nestedToken.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 869 ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;661 `on setting permission #${i} by alice`,662 ).to.be.fulfilled;870663871 await expect(executeTransaction(664 await expect(872 api, 665 nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]), 873 signer, 874 api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin increase'}]), 875 ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;666 `on adding property #${i} by signer #${j}`,876 }667 ).to.be.fulfilled;877878 i++;879 }668 }880669881 const properties = (await api.rpc.unique.tokenProperties(collection, nestedToken, propertyKeys)).toHuman() as any[];670 }671672 const properties = await nestedToken.getProperties(propertyKeys);882 const tokensData = (await api.rpc.unique.tokenData(collection, nestedToken, propertyKeys)).toHuman().properties as any[];673 const tokenData = await nestedToken.getData();883 for (let i = 0; i < properties.length; i++) {674 for (let i = 0; i < properties.length; i++) {884 expect(properties[i].value).to.be.equal('Serotonin increase');675 expect(properties[i].value).to.be.equal('Serotonin increase');885 expect(tokensData[i].value).to.be.equal('Serotonin increase');676 expect(tokenData!.properties[i].value).to.be.equal('Serotonin increase');886 }677 }887 });678 expect(await targetToken.getProperties()).to.be.empty;888 });679 });889680890 it('Changes properties of a nested token according to permissions', async () => {681 itSub('Changes properties of a nested token according to permissions', async ({helper}) => {891 await usingApi(async api => {892 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});682 const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});893 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});894 const token = await createItemExpectSuccess(alice, collection, 'NFT');683 const collectionB = await helper.nft.mintCollection(alice);895 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});684 const targetToken = await collectionA.mintToken(alice);896 await addCollectionAdminExpectSuccess(alice, collection, bob.address);685 const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());897 await transferExpectSuccess(collection, token, alice, charlie);898686899 const propertyKeys: string[] = [];687 await collectionB.addAdmin(alice, {Substrate: bob.address});900 let i = 0;901 for (const permission of permissions) {902 if (!permission.permission.mutable) continue;903 688 await targetToken.transfer(alice, {Substrate: charlie.address});904 for (const signer of permission.signers) {905 const key = i + '_' + signer.address;906 propertyKeys.push(key);907689908 await expect(executeTransaction(690 const propertyKeys: string[] = [];691 let i = 0;909 api, 692 for (const permission of permissions) {693 i++;910 alice, 694 if (!permission.permission.mutable) continue;695 911 api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 696 let j = 0;697 for (const signer of permission.signers) {912 ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;698 j++;699 const key = i + '_' + signer.address;700 propertyKeys.push(key);913701914 await expect(executeTransaction(702 await expect(915 api, 703 nestedToken.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 916 signer, 917 api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin increase'}]), 918 ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;704 `on setting permission #${i} by alice`,705 ).to.be.fulfilled;919706920 await expect(executeTransaction(707 await expect(921 api, 708 nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]), 922 signer, 923 api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin stable'}]), 924 ), `on changing property ${i} by ${signer.address}`).to.not.be.rejected;709 `on adding property #${i} by signer #${j}`,925 }710 ).to.be.fulfilled;926711927 i++;712 await expect(713 nestedToken.setProperties(signer, [{key, value: 'Serotonin stable'}]), 714 `on changing property #${i} by signer #${j}`,715 ).to.be.fulfilled;928 }716 }717 }929718930 const properties = (await api.rpc.unique.tokenProperties(collection, nestedToken, propertyKeys)).toHuman() as any[];719 const properties = await nestedToken.getProperties(propertyKeys);931 const tokensData = (await api.rpc.unique.tokenData(collection, nestedToken, propertyKeys)).toHuman().properties as any[];720 const tokenData = await nestedToken.getData();932 for (let i = 0; i < properties.length; i++) {721 for (let i = 0; i < properties.length; i++) {933 expect(properties[i].value).to.be.equal('Serotonin stable');722 expect(properties[i].value).to.be.equal('Serotonin stable');934 expect(tokensData[i].value).to.be.equal('Serotonin stable');723 expect(tokenData!.properties[i].value).to.be.equal('Serotonin stable');935 }724 }936 });725 expect(await targetToken.getProperties()).to.be.empty;937 });726 });938727939 it('Deletes properties of a nested token according to permissions', async () => {728 itSub('Deletes properties of a nested token according to permissions', async ({helper}) => {940 await usingApi(async api => {941 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});729 const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});942 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});943 const token = await createItemExpectSuccess(alice, collection, 'NFT');730 const collectionB = await helper.nft.mintCollection(alice);944 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});731 const targetToken = await collectionA.mintToken(alice);945 await addCollectionAdminExpectSuccess(alice, collection, bob.address);732 const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());946 await transferExpectSuccess(collection, token, alice, charlie);947733948 const propertyKeys: string[] = [];734 await collectionB.addAdmin(alice, {Substrate: bob.address});949 let i = 0;735 await targetToken.transfer(alice, {Substrate: charlie.address});950736951 for (const permission of permissions) {737 const propertyKeys: string[] = [];738 let i = 0;739 for (const permission of permissions) {952 if (!permission.permission.mutable) continue;740 i++;741 if (!permission.permission.mutable) continue;953 742 954 for (const signer of permission.signers) {743 let j = 0;744 for (const signer of permission.signers) {955 const key = i + '_' + signer.address;745 j++;746 const key = i + '_' + signer.address;956 propertyKeys.push(key);747 propertyKeys.push(key);957748958 await expect(executeTransaction(749 await expect(959 api, 750 nestedToken.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 960 alice, 961 api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 962 ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;751 `on setting permission #${i} by alice`,752 ).to.be.fulfilled;963753964 await expect(executeTransaction(754 await expect(965 api, 755 nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]), 966 signer, 967 api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin increase'}]), 968 ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;756 `on adding property #${i} by signer #${j}`,757 ).to.be.fulfilled;969758970 await expect(executeTransaction(759 await expect(971 api, 760 nestedToken.deleteProperties(signer, [key]), 972 signer, 973 api.tx.unique.deleteTokenProperties(collection, nestedToken, [key]), 974 ), `on deleting property ${i} by ${signer.address}`).to.not.be.rejected;761 `on deleting property #${i} by signer #${j}`,975 }762 ).to.be.fulfilled;976 977 i++;978 }763 }764 }979765980 const properties = (await api.rpc.unique.tokenProperties(collection, nestedToken, propertyKeys)).toJSON() as any[];766 expect(await nestedToken.getProperties(propertyKeys)).to.be.empty;981 expect(properties).to.be.empty;982 const tokensData = (await api.rpc.unique.tokenData(collection, nestedToken, propertyKeys)).toJSON().properties as any[];767 expect((await nestedToken.getData())!.properties).to.be.empty;983 expect(tokensData).to.be.empty;984 expect((await api.query.nonfungible.tokenProperties(collection, nestedToken)).toJSON().consumedSpace).to.be.equal(0);768 expect(await targetToken.getProperties()).to.be.empty;985 });986 });769 });987});770});988771989describe('Negative Integration Test: Token Properties', () => {772describe('Negative Integration Test: Token Properties', () => {990 let collection: number;773 let alice: IKeyringPair; // collection owner991 let token: number;774 let bob: IKeyringPair; // collection admin992 let originalSpace: number;775 let charlie: IKeyringPair; // token owner776993 let constitution: {permission: any, signers: IKeyringPair[], sinner: IKeyringPair}[];777 let constitution: {permission: any, signers: IKeyringPair[], sinner: IKeyringPair}[];994778995 before(async () => {779 before(async () => {996 await usingApi(async (api, privateKeyWrapper) => {780 await usingPlaygrounds(async (helper, privateKey) => {997 alice = privateKeyWrapper('//Alice');781 const donor = privateKey('//Alice');998 bob = privateKeyWrapper('//Bob');782 let dave: IKeyringPair;999 charlie = privateKeyWrapper('//Charlie');783 [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);1000 const dave = privateKeyWrapper('//Dave');1001784785 // todo:playgrounds probably separate these tests later1002 constitution = [786 constitution = [1003 {permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob], sinner: charlie},787 {permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob], sinner: charlie},1004 {permission: {mutable: false, collectionAdmin: true}, signers: [alice, bob], sinner: charlie},788 {permission: {mutable: false, collectionAdmin: true}, signers: [alice, bob], sinner: charlie},1010 });794 });1011 });795 });10127961013 async function prepare(mode: CollectionMode, pieces: number) {797 async function getConsumedSpace(api: any, collectionId: number, tokenId: number, mode: 'NFT' | 'RFT'): Promise<number> {1014 collection = await createCollectionExpectSuccess({mode: mode});1015 token = await createItemExpectSuccess(alice, collection, mode.type);1016 await addCollectionAdminExpectSuccess(alice, collection, bob.address);1017 await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);1018 1019 await usingApi(async api => {1020 let i = 0;798 return (await (mode == 'NFT' ? api.query.nonfungible : api.query.refungible).tokenProperties(collectionId, tokenId)).toJSON().consumedSpace;1021 for (const passage of constitution) {1022 const signer = passage.signers[0];1023 1024 await expect(executeTransaction(1025 api, 1026 alice, 1027 api.tx.unique.setTokenPropertyPermissions(collection, [{key: `${i}`, permission: passage.permission}]), 1028 ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;1029 1030 await expect(executeTransaction(1031 api, 1032 signer, 1033 api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin increase'}]), 1034 ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;1035 1036 i++;1037 }1038 1039 originalSpace = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON().consumedSpace as number;1040 }); 1041 }799 }10428001043 async function testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(mode: CollectionMode, pieces: number) {801 async function prepare(token: UniqueNFToken | UniqueRFToken, pieces: bigint): Promise<number> {1044 await prepare(mode, pieces);802 await token.collection.addAdmin(alice, {Substrate: bob.address});1045 803 await token.transfer(alice, {Substrate: charlie.address}, pieces);1046 await usingApi(async api => {8041047 let i = -1;805 let i = 0;1048 for (const forbiddance of constitution) {806 for (const passage of constitution) {1049 i++;807 i++;1050 if (!forbiddance.permission.mutable) continue;808 const signer = passage.signers[0];1051 809 1052 await expect(executeTransaction(810 await expect(1053 api, 811 token.collection.setTokenPropertyPermissions(alice, [{key: `${i}`, permission: passage.permission}]), 1054 forbiddance.sinner, 1055 api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin down'}]), 1056 ), `on failing to change property ${i} by ${forbiddance.sinner.address}`).to.be.rejectedWith(/common\.NoPermission/);812 `on setting permission ${i} by alice`,1057 813 ).to.be.fulfilled;8141058 await expect(executeTransaction(815 await expect(1059 api, 816 token.setProperties(signer, [{key: `${i}`, value: 'Serotonin increase'}]), 1060 forbiddance.sinner, 1061 api.tx.unique.deleteTokenProperties(collection, token, [`${i}`]), 1062 ), `on failing to delete property ${i} by ${forbiddance.sinner.address}`).to.be.rejectedWith(/common\.NoPermission/);817 `on adding property ${i} by ${signer.address}`,818 ).to.be.fulfilled;1063 }819 }1064 8201065 const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();821 const originalSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 1066 expect(properties.consumedSpace).to.be.equal(originalSpace);1067 });822 return originalSpace;1068 }823 }8241069 it('Forbids changing/deleting properties of a token if the user is outside of permissions (NFT)', async () => {825 async function testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {826 const originalSpace = await prepare(token, pieces);827828 let i = 0;829 for (const forbiddance of constitution) {830 i++;831 if (!forbiddance.permission.mutable) continue;832833 await expect(834 token.setProperties(forbiddance.sinner, [{key: `${i}`, value: 'Serotonin down'}]), 835 `on failing to change property ${i} by the malefactor`,836 ).to.be.rejectedWith(/common\.NoPermission/);837838 await expect(839 token.deleteProperties(forbiddance.sinner, [`${i}`]), 840 `on failing to delete property ${i} by the malefactor`,841 ).to.be.rejectedWith(/common\.NoPermission/);842 }843844 const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 845 expect(consumedSpace).to.be.equal(originalSpace);846 }847848 itSub('Forbids changing/deleting properties of a token if the user is outside of permissions (NFT)', async ({helper}) => {1070 await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions({type: 'NFT'}, 1);849 const collection = await helper.nft.mintCollection(alice);850 const token = await collection.mintToken(alice);851 await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token, 1n);1071 });852 });1072 it('Forbids changing/deleting properties of a token if the user is outside of permissions (ReFungible)', async function() {1073 await requirePallets(this, [Pallets.ReFungible]);10748531075 await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions({type: 'ReFungible'}, 100);854 itSub.ifWithPallets('Forbids changing/deleting properties of a token if the user is outside of permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {855 const collection = await helper.rft.mintCollection(alice);856 const token = await collection.mintToken(alice, 100n);857 await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token, 100n);1076 });858 });10778591078 async function testForbidsChangingDeletingPropertiesIfPropertyImmutable(mode: CollectionMode, pieces: number) {860 async function testForbidsChangingDeletingPropertiesIfPropertyImmutable(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {1079 await prepare(mode, pieces);861 const originalSpace = await prepare(token, pieces);8621080 863 let i = 0;1081 await usingApi(async api => {864 for (const permission of constitution) {1082 let i = -1;865 i++;866 if (permission.permission.mutable) continue;8671083 for (const permission of constitution) {868 await expect(869 token.setProperties(permission.signers[0], [{key: `${i}`, value: 'Serotonin down'}]), 1084 i++;870 `on failing to change property ${i} by signer #0`,871 ).to.be.rejectedWith(/common\.NoPermission/);8721085 if (permission.permission.mutable) continue;873 await expect(874 token.deleteProperties(permission.signers[0], [i.toString()]), 875 `on failing to delete property ${i} by signer #0`,876 ).to.be.rejectedWith(/common\.NoPermission/);877 }1086 878 1087 await expect(executeTransaction(879 const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 1088 api, 1089 permission.signers[0], 1090 api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin down'}]), 1091 ), `on failing to change property ${i} by ${permission.signers[0].address}`).to.be.rejectedWith(/common\.NoPermission/);1092 1093 await expect(executeTransaction(1094 api, 1095 permission.signers[0], 1096 api.tx.unique.deleteTokenProperties(collection, token, [i.toString()]), 1097 ), `on failing to delete property ${i} by ${permission.signers[0].address}`).to.be.rejectedWith(/common\.NoPermission/);1098 }1099 880 expect(consumedSpace).to.be.equal(originalSpace);1100 const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();1101 expect(properties.consumedSpace).to.be.equal(originalSpace);1102 }); 1103 }881 }8821104 it('Forbids changing/deleting properties of a token if the property is permanent (immutable) (NFT)', async () => {883 itSub('Forbids changing/deleting properties of a token if the property is permanent (immutable) (NFT)', async ({helper}) => {1105 await testForbidsChangingDeletingPropertiesIfPropertyImmutable({type: 'NFT'}, 1);884 const collection = await helper.nft.mintCollection(alice);885 const token = await collection.mintToken(alice);886 await testForbidsChangingDeletingPropertiesIfPropertyImmutable(token, 1n);1106 });887 });1107 it('Forbids changing/deleting properties of a token if the property is permanent (immutable) (ReFungible)', async function() {1108 await requirePallets(this, [Pallets.ReFungible]);11098881110 await testForbidsChangingDeletingPropertiesIfPropertyImmutable({type: 'ReFungible'}, 100);889 itSub.ifWithPallets('Forbids changing/deleting properties of a token if the property is permanent (immutable) (ReFungible)', [Pallets.ReFungible], async ({helper}) => {890 const collection = await helper.rft.mintCollection(alice);891 const token = await collection.mintToken(alice, 100n);892 await testForbidsChangingDeletingPropertiesIfPropertyImmutable(token, 100n);1111 });893 });11128941113 async function testForbidsAddingPropertiesIfPropertyNotDeclared(mode: CollectionMode, pieces: number) {895 async function testForbidsAddingPropertiesIfPropertyNotDeclared(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {1114 await prepare(mode, pieces);896 const originalSpace = await prepare(token, pieces);11158971116 await usingApi(async api => {898 await expect(1117 await expect(executeTransaction(1118 api, 899 token.setProperties(alice, [{key: 'non-existent', value: 'I exist!'}]), 1119 alice, 1120 api.tx.unique.setTokenProperties(collection, token, [{key: 'non-existent', value: 'I exist!'}]), 1121 ), 'on failing to add a previously non-existent property').to.be.rejectedWith(/common\.NoPermission/);900 'on failing to add a previously non-existent property',901 ).to.be.rejectedWith(/common\.NoPermission/);1122 902 1123 await expect(executeTransaction(903 await expect(1124 api, 904 token.collection.setTokenPropertyPermissions(alice, [{key: 'now-existent', permission: {}}]), 1125 alice, 1126 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'now-existent', permission: {}}]), 1127 ), 'on setting a new non-permitted property').to.not.be.rejected;905 'on setting a new non-permitted property',1128 906 ).to.be.fulfilled;9071129 await expect(executeTransaction(908 await expect(1130 api, 909 token.setProperties(alice, [{key: 'now-existent', value: 'I exist!'}]), 1131 alice, 1132 api.tx.unique.setTokenProperties(collection, token, [{key: 'now-existent', value: 'I exist!'}]), 1133 ), 'on failing to add a property forbidden by the \'None\' permission').to.be.rejectedWith(/common\.NoPermission/);910 'on failing to add a property forbidden by the \'None\' permission',1134 911 ).to.be.rejectedWith(/common\.NoPermission/);9121135 expect((await api.rpc.unique.tokenProperties(collection, token, ['non-existent', 'now-existent'])).toJSON()).to.be.empty;913 expect(await token.getProperties(['non-existent', 'now-existent'])).to.be.empty;1136 const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();914 915 const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 1137 expect(properties.consumedSpace).to.be.equal(originalSpace);916 expect(consumedSpace).to.be.equal(originalSpace);1138 });1139 }917 }9181140 it('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (NFT)', async () => {919 itSub('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (NFT)', async ({helper}) => {1141 await testForbidsAddingPropertiesIfPropertyNotDeclared({type: 'NFT'}, 1);920 const collection = await helper.nft.mintCollection(alice);921 const token = await collection.mintToken(alice);922 await testForbidsAddingPropertiesIfPropertyNotDeclared(token, 1n);1142 });923 });1143 it('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (ReFungible)', async function() {1144 await requirePallets(this, [Pallets.ReFungible]);11459241146 await testForbidsAddingPropertiesIfPropertyNotDeclared({type: 'ReFungible'}, 100);925 itSub.ifWithPallets('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (ReFungible)', [Pallets.ReFungible], async ({helper}) => {926 const collection = await helper.rft.mintCollection(alice);927 const token = await collection.mintToken(alice, 100n);928 await testForbidsAddingPropertiesIfPropertyNotDeclared(token, 100n);1147 });929 });11489301149 async function testForbidsAddingTooManyProperties(mode: CollectionMode, pieces: number) {931 async function testForbidsAddingTooManyProperties(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {1150 await prepare(mode, pieces);932 const originalSpace = await prepare(token, pieces);11519331152 await usingApi(async api => {934 await expect(1153 await expect(executeTransaction(1154 api, 935 token.collection.setTokenPropertyPermissions(alice, [1155 alice, 1156 api.tx.unique.setTokenPropertyPermissions(collection, [1157 {key: 'a_holy_book', permission: {collectionAdmin: true, tokenOwner: true}}, 936 {key: 'a_holy_book', permission: {collectionAdmin: true, tokenOwner: true}}, 1158 {key: 'young_years', permission: {collectionAdmin: true, tokenOwner: true}},937 {key: 'young_years', permission: {collectionAdmin: true, tokenOwner: true}},1159 ]), 938 ]), 939 'on setting new permissions for properties',940 ).to.be.fulfilled;941942 // Mute the general tx parsing error943 {944 console.error = () => {};945 await expect(token.setProperties(alice, [{key: 'a_holy_book', value: 'word '.repeat(6554)}]))946 .to.be.rejected;947 }948949 await expect(token.setProperties(alice, [1160 ), 'on setting a new non-permitted property').to.not.be.rejected;950 {key: 'a_holy_book', value: 'word '.repeat(3277)}, 951 {key: 'young_years', value: 'neverending'.repeat(1490)},952 ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);1161 953 1162 // Mute the general tx parsing error954 expect(await token.getProperties(['a_holy_book', 'young_years'])).to.be.empty;1163 {1164 console.error = () => {};1165 await expect(executeTransaction(1166 api, 1167 alice, 1168 api.tx.unique.setCollectionProperties(collection, [{key: 'a_holy_book', value: 'word '.repeat(6554)}]), 1169 )).to.be.rejected;1170 }955 const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 1171 1172 await expect(executeTransaction(1173 api, 1174 alice, 1175 api.tx.unique.setTokenProperties(collection, token, [1176 {key: 'a_holy_book', value: 'word '.repeat(3277)}, 1177 {key: 'young_years', value: 'neverending'.repeat(1490)},1178 ]), 1179 )).to.be.rejectedWith(/common\.NoSpaceForProperty/);1180 1181 expect((await api.rpc.unique.tokenProperties(collection, token, ['a_holy_book', 'young_years'])).toJSON()).to.be.empty;956 expect(consumedSpace).to.be.equal(originalSpace);1182 const propertiesMap = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();1183 expect(propertiesMap.consumedSpace).to.be.equal(originalSpace);1184 });1185 }957 }9581186 it('Forbids adding too many properties to a token (NFT)', async () => {959 itSub('Forbids adding too many properties to a token (NFT)', async ({helper}) => {1187 await testForbidsAddingTooManyProperties({type: 'NFT'}, 1);960 const collection = await helper.nft.mintCollection(alice);961 const token = await collection.mintToken(alice);962 await testForbidsAddingTooManyProperties(token, 1n);1188 });963 });1189 it('Forbids adding too many properties to a token (ReFungible)', async function() {1190 await requirePallets(this, [Pallets.ReFungible]);11919641192 await testForbidsAddingTooManyProperties({type: 'ReFungible'}, 100);965 itSub.ifWithPallets('Forbids adding too many properties to a token (ReFungible)', [Pallets.ReFungible], async ({helper}) => {966 const collection = await helper.rft.mintCollection(alice);967 const token = await collection.mintToken(alice, 100n);968 await testForbidsAddingTooManyProperties(token, 100n);1193 });969 });1194});970});11959711196describe('ReFungible token properties permissions tests', () => {972describe('ReFungible token properties permissions tests', () => {1197 let collection: number;973 let alice: IKeyringPair;1198 let token: number;974 let bob: IKeyringPair;975 let charlie: IKeyringPair;11999761200 before(async function() {977 before(async function() {1201 await requirePallets(this, [Pallets.ReFungible]);978 await usingPlaygrounds(async (helper, privateKey) => {979 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);12029801203 await usingApi(async (api, privateKeyWrapper) => {981 const donor = privateKey('//Alice');1204 alice = privateKeyWrapper('//Alice');1205 bob = privateKeyWrapper('//Bob');982 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);1206 charlie = privateKeyWrapper('//Charlie');1207 });983 });1208 });984 });12099851210 beforeEach(async () => {986 async function prepare(helper: UniqueHelper): Promise<UniqueRFToken> {1211 await usingApi(async api => {987 const collection = await helper.rft.mintCollection(alice);988 const token = await collection.mintToken(alice, 100n);1212 collection = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});989 990 await collection.addAdmin(alice, {Substrate: bob.address});1213 token = await createItemExpectSuccess(alice, collection, 'ReFungible');991 await collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable: true, tokenOwner: true}}]);1214 await addCollectionAdminExpectSuccess(alice, collection, bob.address);992 993 return token;994 }12159951216 await expect(executeTransaction(996 itSub('Forbids adding token property with tokenOwner==true when signer doesn\'t have all pieces', async ({helper}) => {1217 api, 1218 alice, 997 const token = await prepare(helper);9981219 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'key', permission: {mutable:true, tokenOwner: true}}]), 999 await token.transfer(alice, {Substrate: charlie.address}, 33n);10001001 await expect(token.setProperties(alice, [1002 {key: 'fractals', value: 'multiverse'}, 1220 )).to.not.be.rejected;1003 ])).to.be.rejectedWith(/common\.NoPermission/);1221 });1222 });1004 });122310051224 it('Forbids add token property with tokenOwher==true but signer have\'t all pieces', async () => {1006 itSub('Forbids mutating token property with tokenOwher==true when signer doesn\'t have all pieces', async ({helper}) => {1225 await usingApi(async api => {1007 const token = await prepare(helper);10081226 await transferExpectSuccess(collection, token, alice, charlie, 33, 'ReFungible');1009 await expect(token.collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable:true, tokenOwner: true}}]))1227 1010 .to.be.fulfilled;10111228 await expect(executeTransaction(1012 await expect(token.setProperties(alice, [1229 api, 1013 {key: 'fractals', value: 'multiverse'}, 1230 alice, 1014 ])).to.be.fulfilled;10151231 api.tx.unique.setTokenProperties(collection, token, [1016 await token.transfer(alice, {Substrate: charlie.address}, 33n);10171018 await expect(token.setProperties(alice, [1232 {key: 'key', value: 'word'}, 1019 {key: 'fractals', value: 'want to rule the world'}, 1233 ]), 1234 )).to.be.rejectedWith(/common\.NoPermission/);1020 ])).to.be.rejectedWith(/common\.NoPermission/);1235 });1236 });1021 });123710221238 it('Forbids mutate token property with tokenOwher==true but signer have\'t all pieces', async () => {1023 itSub('Forbids deleting token property with tokenOwner==true when signer doesn\'t have all pieces', async ({helper}) => {1239 await usingApi(async api => {1024 const token = await prepare(helper);1240 await expect(executeTransaction(1241 api, 1242 alice, 1243 api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'key', permission: {mutable:true, tokenOwner: true}}]), 1244 )).to.not.be.rejected;1245 1246 await expect(executeTransaction(1247 api, 1248 alice, 1249 api.tx.unique.setTokenProperties(collection, token, [1250 {key: 'key', value: 'word'}, 1251 ]), 1252 )).to.be.not.rejected;125310251254 await transferExpectSuccess(collection, token, alice, charlie, 33, 'ReFungible');1026 await expect(token.setProperties(alice, [1255 1027 {key: 'fractals', value: 'one headline - why believe it'}, 1256 await expect(executeTransaction(1257 api, 1258 alice, 1259 api.tx.unique.setTokenProperties(collection, token, [1028 ])).to.be.fulfilled;10291260 {key: 'key', value: 'bad word'}, 1030 await token.transfer(alice, {Substrate: charlie.address}, 33n);10311261 ]), 1032 await expect(token.deleteProperties(alice, ['fractals'])).1262 )).to.be.rejectedWith(/common\.NoPermission/);1033 to.be.rejectedWith(/common\.NoPermission/);1263 });1264 });1034 });126510351266 it('Forbids delete token property with tokenOwher==true but signer have\'t all pieces', async () => {1036 itSub('Allows token property mutation with collectionOwner==true when admin doesn\'t have all pieces', async ({helper}) => {1267 await usingApi(async api => {1037 const token = await prepare(helper);1268 await expect(executeTransaction(1269 api, 1270 alice, 1271 api.tx.unique.setTokenProperties(collection, token, [1272 {key: 'key', value: 'word'}, 1273 ]), 1274 )).to.be.not.rejected;127510381276 await transferExpectSuccess(collection, token, alice, charlie, 33, 'ReFungible');1039 await token.transfer(alice, {Substrate: charlie.address}, 33n);1277 10401278 await expect(executeTransaction(1041 await expect(token.collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable:true, collectionAdmin: true}}]))1279 api, 1280 alice, 1042 .to.be.fulfilled;10431281 api.tx.unique.deleteTokenProperties(collection, token, [1044 await expect(token.setProperties(alice, [1282 'key',1045 {key: 'fractals', value: 'multiverse'}, 1283 ]), 1284 )).to.be.rejectedWith(/common\.NoPermission/);1046 ])).to.be.fulfilled;1285 });1286 });1047 });1287});1048});12881049tests/src/nesting/rules-smoke.test.tsdiffbeforeafterbothno changes
tests/src/nesting/unnest.test.tsdiffbeforeafterboth1import {expect} from 'chai';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/>.162import {tokenIdToAddress} from '../eth/util/helpers';17import {IKeyringPair} from '@polkadot/types/types';3import usingApi, {executeTransaction} from '../substrate/substrate-api';4import {18import {expect, itSub, Pallets, usingPlaygrounds} from '../util/playgrounds';5 createCollectionExpectSuccess,6 createItemExpectSuccess,7 getBalance,8 getTokenOwner,9 normalizeAccountId,10 setCollectionPermissionsExpectSuccess,11 transferExpectSuccess,12 transferFromExpectSuccess,13 requirePallets,14 Pallets,15} from '../util/helpers';16import {IKeyringPair} from '@polkadot/types/types';1718let alice: IKeyringPair;19let bob: IKeyringPair;201921describe('Integration Test: Unnesting', () => {20describe('Integration Test: Unnesting', () => {21 let alice: IKeyringPair;2222 before(async () => {23 before(async () => {23 await usingApi(async (api, privateKeyWrapper) => {24 await usingPlaygrounds(async (helper, privateKey) => {24 alice = privateKeyWrapper('//Alice');25 const donor = privateKey('//Alice');25 bob = privateKeyWrapper('//Bob');26 [alice] = await helper.arrange.createAccounts([50n], donor);26 });27 });27 });28 });282929 it('NFT: allows the owner to successfully unnest a token', async () => {30 itSub('NFT: allows the owner to successfully unnest a token', async ({helper}) => {30 await usingApi(async api => {31 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});31 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});32 const targetToken = await collection.mintToken(alice);32 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});33 33 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');34 const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};3536 // Create a nested token34 // Create a nested token37 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', targetAddress);35 const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());383639 // Unnest37 // Unnest40 await expect(executeTransaction(38 await expect(nestedToken.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}), 'while unnesting').to.be.fulfilled;41 api,42 alice,43 api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(alice), collection, nestedToken, 1),44 ), 'while unnesting').to.not.be.rejected;45 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});39 expect(await nestedToken.getOwner()).to.be.deep.equal({Substrate: alice.address});464047 // Nest and burn41 // Nest and burn48 await transferExpectSuccess(collection, nestedToken, alice, targetAddress);42 await nestedToken.nest(alice, targetToken);49 await expect(executeTransaction(43 await expect(nestedToken.burnFrom(alice, targetToken.nestingAccount()), 'while burning').to.be.fulfilled;50 api,51 alice,52 api.tx.unique.burnFrom(collection, normalizeAccountId(targetAddress), nestedToken, 1),53 ), 'while burning').to.not.be.rejected;54 await expect(getTokenOwner(api, collection, nestedToken)).to.be.rejected;44 await expect(nestedToken.getOwner()).to.be.rejected;55 });56 });45 });574658 it('Fungible: allows the owner to successfully unnest a token', async () => {47 itSub('Fungible: allows the owner to successfully unnest a token', async ({helper}) => {59 await usingApi(async api => {48 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});49 const targetToken = await collection.mintToken(alice);5051 const collectionFT = await helper.ft.mintCollection(alice);52 53 // Nest and unnest60 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});54 await collectionFT.mint(alice, 10n, targetToken.nestingAccount());61 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});62 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');55 await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;63 const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};6465 const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});56 expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(9n);66 const nestedToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');6768 // Nest and unnest69 await transferExpectSuccess(collectionFT, nestedToken, alice, targetAddress, 1, 'Fungible');57 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(1n);70 await transferFromExpectSuccess(collectionFT, nestedToken, alice, targetAddress, alice, 1, 'Fungible');715872 // Nest and burn59 // Nest and burn73 await transferExpectSuccess(collectionFT, nestedToken, alice, targetAddress, 1, 'Fungible');60 await collectionFT.transfer(alice, targetToken.nestingAccount(), 5n);74 const balanceBefore = await getBalance(api, collectionFT, normalizeAccountId(targetAddress), nestedToken);61 await expect(collectionFT.burnTokensFrom(alice, targetToken.nestingAccount(), 6n), 'while burning').to.be.fulfilled;75 await expect(executeTransaction(62 expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(4n);76 api,77 alice,78 api.tx.unique.burnFrom(collectionFT, normalizeAccountId(targetAddress), nestedToken, 1),79 ), 'while burning').to.not.be.rejected;80 const balanceAfter = await getBalance(api, collectionFT, normalizeAccountId(targetAddress), nestedToken);63 expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);81 expect(balanceAfter + BigInt(1)).to.be.equal(balanceBefore);64 expect(await targetToken.getChildren()).to.be.length(0);82 });83 });65 });846685 it('ReFungible: allows the owner to successfully unnest a token', async function() {67 itSub.ifWithPallets('ReFungible: allows the owner to successfully unnest a token', [Pallets.ReFungible], async ({helper}) => {86 await requirePallets(this, [Pallets.ReFungible]);8788 await usingApi(async api => {89 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});90 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});68 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});91 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');69 const targetToken = await collection.mintToken(alice);92 const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};937094 const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});71 const collectionRFT = await helper.rft.mintCollection(alice);72 73 // Nest and unnest95 const nestedToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');74 const token = await collectionRFT.mintToken(alice, 10n, targetToken.nestingAccount());9697 // Nest and unnest98 await transferExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, 1, 'ReFungible');75 await expect(token.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;99 await transferFromExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, alice, 1, 'ReFungible');76 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(9n);77 expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(1n);10078101 // Nest and burn79 // Nest and burn102 await transferExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, 1, 'ReFungible');80 await token.transfer(alice, targetToken.nestingAccount(), 5n);103 await expect(executeTransaction(81 await expect(token.burnFrom(alice, targetToken.nestingAccount(), 6n), 'while burning').to.be.fulfilled;104 api,105 alice,106 api.tx.unique.burnFrom(collectionRFT, normalizeAccountId(targetAddress), nestedToken, 1),107 ), 'while burning').to.not.be.rejected;108 const balance = await getBalance(api, collectionRFT, normalizeAccountId(targetAddress), nestedToken);82 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(4n);109 expect(balance).to.be.equal(0n);83 expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(0n);84 expect(await targetToken.getChildren()).to.be.length(0);110 });85 });111 });112});86});11387114describe('Negative Test: Unnesting', () => {88describe('Negative Test: Unnesting', () => {89 let alice: IKeyringPair;90 let bob: IKeyringPair;91115 before(async () => {92 before(async () => {116 await usingApi(async (api, privateKeyWrapper) => {93 await usingPlaygrounds(async (helper, privateKey) => {117 alice = privateKeyWrapper('//Alice');94 const donor = privateKey('//Alice');118 bob = privateKeyWrapper('//Bob');95 [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);119 });96 });120 });97 });12198122 it('Disallows a non-owner to unnest/burn a token', async () => {99 itSub('Disallows a non-owner to unnest/burn a token', async ({helper}) => {123 await usingApi(async api => {100 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});124 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});101 const targetToken = await collection.mintToken(alice);125 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});126 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');127 const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};128102129 // Create a nested token103 // Create a nested token130 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', targetAddress);104 const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());131105132 // Try to unnest106 // Try to unnest133 await expect(executeTransaction(107 await expect(nestedToken.unnest(bob, targetToken, {Substrate: alice.address})).to.be.rejectedWith(/common\.ApprovedValueTooLow/);134 api,135 bob,136 api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(bob), collection, nestedToken, 1),137 ), 'while unnesting').to.be.rejectedWith(/^common\.ApprovedValueTooLow$/);138 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});108 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());139109140 // Try to burn110 // Try to burn141 await expect(executeTransaction(111 await expect(nestedToken.burnFrom(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.ApprovedValueTooLow/);142 api,143 bob,144 api.tx.unique.burnFrom(collection, normalizeAccountId(bob.address), nestedToken, 1),145 ), 'while burning').to.not.be.rejectedWith(/^common\.ApprovedValueTooLow$/);146 expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});112 expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());147 });148 });113 });149114150 // todo another test for creating excessive depth matryoshka with Ethereum?115 // todo another test for creating excessive depth matryoshka with Ethereum?151116152 // Recursive nesting117 // Recursive nesting153 it('Prevents Ouroboros creation', async () => {118 itSub('Prevents Ouroboros creation', async ({helper}) => {154 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});119 const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});155 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});156 const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');120 const targetToken = await collection.mintToken(alice);157121158 // Create a nested token ouroboros122 // Fail to create a nested token ouroboros159 const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});123 const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());160 await expect(transferExpectSuccess(collection, targetToken, alice, {Ethereum: tokenIdToAddress(collection, nestedToken)})).to.be.rejectedWith(/^structure\.OuroborosDetected$/);124 await expect(targetToken.nest(alice, nestedToken)).to.be.rejectedWith(/^structure\.OuroborosDetected$/);161 });125 });162});126});163127tests/src/rpc.test.tsdiffbeforeafterboth161617import {IKeyringPair} from '@polkadot/types/types';17import {IKeyringPair} from '@polkadot/types/types';18import {usingPlaygrounds, itSub, expect} from './util/playgrounds';18import {usingPlaygrounds, itSub, expect} from './util/playgrounds';19import {crossAccountIdFromLower} from './util/playgrounds/unique';19import {CrossAccountId} from './util/playgrounds/unique';202021describe('integration test: RPC methods', () => {21describe('integration test: RPC methods', () => {22 let donor: IKeyringPair;22 let donor: IKeyringPair;55 // Set-up over55 // Set-up over565657 const owners = await helper.callRpc('api.rpc.unique.tokenOwners', [collection.collectionId, 0]);57 const owners = await helper.callRpc('api.rpc.unique.tokenOwners', [collection.collectionId, 0]);58 const ids = (owners.toJSON() as any[]).map(crossAccountIdFromLower);58 const ids = (owners.toJSON() as any[]).map(CrossAccountId.fromLowerCaseKeys);595960 expect(ids).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);60 expect(ids).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);61 expect(owners.length == 10).to.be.true;61 expect(owners.length == 10).to.be.true;tests/src/util/playgrounds/index.tsdiffbeforeafterboth63 });62 });64 });63 });65}64}65export async function itSubIfWithPallet(name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {66 return itSub(name, cb, {requiredPallets: required, ...opts});67}66itSub.only = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {only: true});68itSub.only = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {only: true});67itSub.skip = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {skip: true});69itSub.skip = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {skip: true});7068itSub.ifWithPallets = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {requiredPallets: required});71itSubIfWithPallet.only = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSubIfWithPallet(name, required, cb, {only: true});72itSubIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});73itSub.ifWithPallets = itSubIfWithPallet;6974tests/src/util/playgrounds/types.tsdiffbeforeafterboth949495export interface IProperty {95export interface IProperty {96 key: string;96 key: string;97 value: string;97 value?: string;98}98}9999100export interface ITokenPropertyPermission {100export interface ITokenPropertyPermission {101 key: string;101 key: string;102 permission: {102 permission: {103 mutable: boolean;103 mutable?: boolean;104 tokenOwner: boolean;104 tokenOwner?: boolean;105 collectionAdmin: boolean;105 collectionAdmin?: boolean;106 }106 }107}107}108108tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth6import {ApiPromise, WsProvider} from '@polkadot/api';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';8import {IKeyringPair} from '@polkadot/types/types';9import {ICrossAccountId} from './types';910101111export class SilentLogger {12export class SilentLogger {231 if(block2date! - block1date! < 9000) return true;232 if(block2date! - block1date! < 9000) return true;232 };233 };234 235 async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {236 const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);237 let balance = await this.helper.balance.getSubstrate(address); 238 239 await promise();240 241 balance -= await this.helper.balance.getSubstrate(address);242 243 return balance;244 }233}245}234246235class WaitGroup {247class WaitGroup {tests/src/util/playgrounds/unique.tsdiffbeforeafterboth11import {IKeyringPair} from '@polkadot/types/types';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';131314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {14export class CrossAccountId implements ICrossAccountId {15 const address = {} as ICrossAccountId;15 Substrate?: TSubstrateAccount;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;16 Ethereum?: TEthereumAccount;18 return address;19};201718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair) {24 return new CrossAccountId({Substrate: account.address});25 }2627 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {28 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});29 }3031 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {32 return encodeAddress(decodeAddress(address), ss58Format);33 }3435 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {36 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});37 }38 39 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {40 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);41 return this;42 }43 44 toLowerCase(): CrossAccountId {45 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();46 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();47 return this;48 }49}5021const nesting = {51const nesting = {22 toChecksumAddress(address: string): string {52 toChecksumAddress(address: string): string {23 if (typeof address === 'undefined') return '';53 if (typeof address === 'undefined') return '';55 RPC: 'rpc',85 RPC: 'rpc',56 };86 };578758 static getNestingTokenAddress(collectionId: number, tokenId: number) {88 static getTokenAccount(token: IToken): CrossAccountId {59 return nesting.tokenIdToAddress(collectionId, tokenId);89 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});60 }90 }619192 static getTokenAddress(token: IToken): string {93 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);94 }9562 static getDefaultLogger(): ILogger {96 static getDefaultLogger(): ILogger {63 return {97 return {64 log(msg: any, level = 'INFO') {98 log(msg: any, level = 'INFO') {86 return keyring.addFromUri(seed);120 return keyring.addFromUri(seed);87 }121 }8812289 static normalizeSubstrateAddress(address: string, ss58Format = 42) {90 return encodeAddress(decodeAddress(address), ss58Format);91 }9293 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {123 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {94 if (creationResult.status !== this.transactionStatus.SUCCESS) {124 if (creationResult.status !== this.transactionStatus.SUCCESS) {95 throw Error('Unable to create collection!');125 throw Error('Unable to create collection!');170 Object.keys(address).forEach(k => {200 Object.keys(address).forEach(k => {171 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];201 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];172 });202 });173 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};203 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);174 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};204 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();175 return address;205 return address;176 };206 };177 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;207 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;555 name: string;585 name: string;556 description: string;586 description: string;557 tokensCount: number;587 tokensCount: number;558 admins: ICrossAccountId[];588 admins: CrossAccountId[];559 normalizedOwner: TSubstrateAccount;589 normalizedOwner: TSubstrateAccount;560 raw: any590 raw: any561 } | null> {591 } | null> {588 * @example await getAdmins(1)618 * @example await getAdmins(1)589 * @returns array of administrators619 * @returns array of administrators590 */620 */591 async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {621 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {592 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();622 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();593623594 return normalize624 return normalize595 ? admins.map((address: any) => {625 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())596 return address.Substrate597 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}598 : address;599 })600 : admins;626 : admins;601 }627 }602628607 * @example await getAllowList(1)633 * @example await getAllowList(1)608 * @returns array of allow-listed addresses634 * @returns array of allow-listed addresses609 */635 */610 async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {636 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {611 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();637 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();612 return normalize638 return normalize613 ? allowListed.map((address: any) => {639 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())614 return address.Substrate615 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}616 : address;617 })618 : allowListed;640 : allowListed;619 }641 }620642897 }919 }898920899 /**921 /**922 * Get collection properties.923 * 924 * @param collectionId ID of collection925 * @param propertyKeys optionally filter the returned properties to only these keys926 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);927 * @returns array of key-value pairs928 */929 async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {930 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();931 }932933 /**900 * Deletes onchain properties from the collection.934 * Deletes onchain properties from the collection.901 *935 *902 * @param signer keyring of signer936 * @param signer keyring of signer988 *1022 *989 * @param signer keyring of signer1023 * @param signer keyring of signer990 * @param collectionId ID of collection1024 * @param collectionId ID of collection1025 * @param tokenId ID of token991 * @param fromAddressObj address on behalf of which the token will be burnt1026 * @param fromAddressObj address on behalf of which the token will be burnt992 * @param tokenId ID of token993 * @param amount amount of tokens to be burned. For NFT must be set to 1n1027 * @param amount amount of tokens to be burned. For NFT must be set to 1n994 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1028 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})995 * @returns ```true``` if extrinsic success, otherwise ```false```1029 * @returns ```true``` if extrinsic success, otherwise ```false```996 */1030 */997 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {1031 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {998 const burnResult = await this.helper.executeExtrinsic(1032 const burnResult = await this.helper.executeExtrinsic(999 signer,1033 signer,1000 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1034 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1087 */1121 */1088 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1122 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1089 properties: IProperty[];1123 properties: IProperty[];1090 owner: ICrossAccountId;1124 owner: CrossAccountId;1091 normalizedOwner: ICrossAccountId;1125 normalizedOwner: CrossAccountId;1092 }| null> {1126 }| null> {1093 let tokenData;1127 let tokenData;1094 if(typeof blockHashAt === 'undefined') {1128 if(typeof blockHashAt === 'undefined') {1106 if (tokenData === null || tokenData.owner === null) return null;1140 if (tokenData === null || tokenData.owner === null) return null;1107 const owner = {} as any;1141 const owner = {} as any;1108 for (const key of Object.keys(tokenData.owner)) {1142 for (const key of Object.keys(tokenData.owner)) {1109 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1143 owner[key.toLocaleLowerCase()] = new CrossAccountId(tokenData.owner[key]).withNormalizedSubstrate();1110 }1144 }1111 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1145 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1112 return tokenData;1146 return tokenData;1113 }1147 }111411481117 *1151 *1118 * @param signer keyring of signer1152 * @param signer keyring of signer1119 * @param collectionId ID of collection1153 * @param collectionId ID of collection1120 * @param permissions permissions to change a property by the collection owner or admin1154 * @param permissions permissions to change a property by the collection admin or token owner1121 * @example setTokenPropertyPermissions(1155 * @example setTokenPropertyPermissions(1122 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1156 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1123 * )1157 * )1134 }1168 }113511691136 /**1170 /**1171 * Get token property permissions.1172 * 1173 * @param collectionId ID of collection1174 * @param propertyKeys optionally filter the returned property permissions to only these keys1175 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1176 * @returns array of key-permission pairs1177 */1178 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1179 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1180 }11811182 /**1137 * Set token properties1183 * Set token properties1138 *1184 *1139 * @param signer keyring of signer1185 * @param signer keyring of signer1154 }1200 }115512011156 /**1202 /**1203 * Get properties, metadata assigned to a token.1204 * 1205 * @param collectionId ID of collection1206 * @param tokenId ID of token1207 * @param propertyKeys optionally filter the returned properties to only these keys1208 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1209 * @returns array of key-value pairs1210 */1211 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1212 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1213 }12141215 /**1157 * Delete the provided properties of a token1216 * Delete the provided properties of a token1158 * @param signer keyring of signer1217 * @param signer keyring of signer1159 * @param collectionId ID of collection1218 * @param collectionId ID of collection1181 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1240 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1182 * @returns object of the created collection1241 * @returns object of the created collection1183 */1242 */1184 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1243 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1185 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1244 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1186 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1245 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1187 for (const key of ['name', 'description', 'tokenPrefix']) {1246 for (const key of ['name', 'description', 'tokenPrefix']) {1223 * @example getTokenObject(10, 5);1282 * @example getTokenObject(10, 5);1224 * @returns instance of UniqueNFTToken1283 * @returns instance of UniqueNFTToken1225 */1284 */1226 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1285 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1227 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1286 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1228 }1287 }122912881230 /**1289 /**1235 * @example getTokenOwner(10, 5);1294 * @example getTokenOwner(10, 5);1236 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1295 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1237 */1296 */1238 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1297 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1239 let owner;1298 let owner;1240 if (typeof blockHashAt === 'undefined') {1299 if (typeof blockHashAt === 'undefined') {1241 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1300 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1242 } else {1301 } else {1243 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1302 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1244 }1303 }1245 return crossAccountIdFromLower(owner.toJSON());1304 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1246 }1305 }124713061248 /**1307 /**1294 * @example getTokenTopmostOwner(10, 5);1353 * @example getTokenTopmostOwner(10, 5);1295 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1354 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1296 */1355 */1297 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1356 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1298 let owner;1357 let owner;1299 if (typeof blockHashAt === 'undefined') {1358 if (typeof blockHashAt === 'undefined') {1300 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1359 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);130413631305 if (owner === null) return null;1364 if (owner === null) return null;130613651307 owner = owner.toHuman();1366 return owner.toHuman();13081309 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1310 }1367 }131113681312 /**1369 /**1339 * @returns ```true``` if extrinsic success, otherwise ```false```1396 * @returns ```true``` if extrinsic success, otherwise ```false```1340 */1397 */1341 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1398 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1342 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1399 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1343 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1400 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1344 if(!result) {1401 if(!result) {1345 throw Error('Unable to nest token!');1402 throw Error('Unable to nest token!');1357 * @returns ```true``` if extrinsic success, otherwise ```false```1414 * @returns ```true``` if extrinsic success, otherwise ```false```1358 */1415 */1359 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1416 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1360 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1417 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1361 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1418 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1362 if(!result) {1419 if(!result) {1363 throw Error('Unable to unnest token!');1420 throw Error('Unable to unnest token!');1377 * })1434 * })1378 * @returns object of the created collection1435 * @returns object of the created collection1379 */1436 */1380 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1437 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1381 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1438 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1382 }1439 }138314401387 * @param data token data1444 * @param data token data1388 * @returns created token object1445 * @returns created token object1389 */1446 */1390 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1447 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1391 const creationResult = await this.helper.executeExtrinsic(1448 const creationResult = await this.helper.executeExtrinsic(1392 signer,1449 signer,1393 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1450 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1418 * }]);1475 * }]);1419 * @returns ```true``` if extrinsic success, otherwise ```false```1476 * @returns ```true``` if extrinsic success, otherwise ```false```1420 */1477 */1421 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1478 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1422 const creationResult = await this.helper.executeExtrinsic(1479 const creationResult = await this.helper.executeExtrinsic(1423 signer,1480 signer,1424 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1481 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1446 * }]);1503 * }]);1447 * @returns array of newly created tokens1504 * @returns array of newly created tokens1448 */1505 */1449 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1506 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1450 const rawTokens = [];1507 const rawTokens = [];1451 for (const token of tokens) {1508 for (const token of tokens) {1452 const raw = {NFT: {properties: token.properties}};1509 const raw = {NFT: {properties: token.properties}};1495 * @example getTokenObject(10, 5);1552 * @example getTokenObject(10, 5);1496 * @returns instance of UniqueNFTToken1553 * @returns instance of UniqueNFTToken1497 */1554 */1498 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1555 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1499 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1556 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1500 }1557 }150115581502 /**1559 /**1506 * @example getTokenTop10Owners(10, 5);1563 * @example getTokenTop10Owners(10, 5);1507 * @returns array of top 10 owners1564 * @returns array of top 10 owners1508 */1565 */1509 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1566 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1510 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1567 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1511 }1568 }151215691513 /**1570 /**1563 * })1620 * })1564 * @returns object of the created collection1621 * @returns object of the created collection1565 */1622 */1566 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1623 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1567 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1624 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1568 }1625 }156916261574 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1631 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1575 * @returns created token object1632 * @returns created token object1576 */1633 */1577 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1634 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1578 const creationResult = await this.helper.executeExtrinsic(1635 const creationResult = await this.helper.executeExtrinsic(1579 signer,1636 signer,1580 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1637 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1591 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1648 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1592 }1649 }159316501594 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1651 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1595 throw Error('Not implemented');1652 throw Error('Not implemented');1596 const creationResult = await this.helper.executeExtrinsic(1653 const creationResult = await this.helper.executeExtrinsic(1597 signer,1654 signer,1611 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1668 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1612 * @returns array of newly created RFT tokens1669 * @returns array of newly created RFT tokens1613 */1670 */1614 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1671 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1615 const rawTokens = [];1672 const rawTokens = [];1616 for (const token of tokens) {1673 for (const token of tokens) {1617 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1674 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1633 * @param tokenId ID of token1690 * @param tokenId ID of token1634 * @param amount number of pieces to be burnt1691 * @param amount number of pieces to be burnt1635 * @example burnToken(aliceKeyring, 10, 5);1692 * @example burnToken(aliceKeyring, 10, 5);1636 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1693 * @returns ```true``` and burnt token number, if extrinsic is successful. Otherwise ```false``` and ```null```1637 */1694 */1638 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1695 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1639 return await super.burnToken(signer, collectionId, tokenId, amount);1696 return await super.burnToken(signer, collectionId, tokenId, amount);1640 }1697 }164116981642 /**1699 /**1700 * Destroys a concrete instance of RFT on behalf of the owner.1701 * @param signer keyring of signer1702 * @param collectionId ID of collection1703 * @param tokenId ID of token1704 * @param fromAddressObj address on behalf of which the token will be burnt1705 * @param amount number of pieces to be burnt1706 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1707 * @returns ```true``` if extrinsic success, otherwise ```false```1708 */1709 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1710 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1711 }17121713 /**1643 * Set, change, or remove approved address to transfer the ownership of the RFT.1714 * Set, change, or remove approved address to transfer the ownership of the RFT.1644 *1715 *1645 * @param signer keyring of signer1716 * @param signer keyring of signer1711 * }, 18)1782 * }, 18)1712 * @returns newly created fungible collection1783 * @returns newly created fungible collection1713 */1784 */1714 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1785 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1715 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1786 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1716 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1787 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1717 collectionOptions.mode = {fungible: decimalPoints};1788 collectionOptions.mode = {fungible: decimalPoints};1776 * @example getTop10Owners(10);1847 * @example getTop10Owners(10);1777 * @returns array of ```ICrossAccountId```1848 * @returns array of ```ICrossAccountId```1778 */1849 */1779 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1850 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1780 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1851 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1781 }1852 }178218531783 /**1854 /**1840 * @returns ```true``` if extrinsic success, otherwise ```false```1911 * @returns ```true``` if extrinsic success, otherwise ```false```1841 */1912 */1842 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1913 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1843 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1914 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1844 }1915 }184519161846 /**1917 /**193620071937class BalanceGroup extends HelperGroup {2008class BalanceGroup extends HelperGroup {1938 /**2009 /**1939 * Representation of the native token in the smallest unit2010 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).1940 * @example getOneTokenNominal()2011 * @example getOneTokenNominal()1941 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2012 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1942 */2013 */1996 };2067 };1997 }2068 }1998 });2069 });1999 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2070 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2000 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2071 && this.helper.address.normalizeSubstrate(address) === transfer.to 2001 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2072 && BigInt(amount) === transfer.amount;2002 return isSuccess;2073 return isSuccess;2003 }2074 }2004}2075}2013 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2084 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2014 */2085 */2015 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2086 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2016 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2087 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2017 }2088 }201820892019 /**2090 /**2161}2232}21622233216322342164class UniqueCollectionBase {2235export class UniqueBaseCollection {2165 helper: UniqueHelper;2236 helper: UniqueHelper;2166 collectionId: number;2237 collectionId: number;216722382194 return await this.helper.collection.getEffectiveLimits(this.collectionId);2265 return await this.helper.collection.getEffectiveLimits(this.collectionId);2195 }2266 }219622672268 async getProperties(propertyKeys: string[] | null = null) {2269 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2270 }22712272 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2273 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2274 }22752197 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2276 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2198 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2277 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2199 }2278 }2238 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2317 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2239 }2318 }224023192241 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2242 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2243 }22442245 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2320 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2246 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2321 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2247 }2322 }2260}2335}22612336226223372263class UniqueNFTCollection extends UniqueCollectionBase {2338export class UniqueNFTCollection extends UniqueBaseCollection {2264 getTokenObject(tokenId: number) {2339 getTokenObject(tokenId: number) {2265 return new UniqueNFTToken(tokenId, this);2340 return new UniqueNFToken(tokenId, this);2266 }2341 }226723422268 async getTokensByAddress(addressObj: ICrossAccountId) {2343 async getTokensByAddress(addressObj: ICrossAccountId) {2285 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2360 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2286 }2361 }228723622363 async getPropertyPermissions(propertyKeys: string[] | null = null) {2364 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2365 }23662367 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2368 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2369 }23702288 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2371 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2289 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2372 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2290 }2373 }2313 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2396 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2314 }2397 }231523982399 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2400 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2401 }24022316 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2403 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2317 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2404 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2318 }2405 }2335}2422}23362423233724242338class UniqueRFTCollection extends UniqueCollectionBase {2425export class UniqueRFTCollection extends UniqueBaseCollection {2339 getTokenObject(tokenId: number) {2426 getTokenObject(tokenId: number) {2340 return new UniqueRFTToken(tokenId, this);2427 return new UniqueRFToken(tokenId, this);2341 }2428 }234224292430 async getToken(tokenId: number, blockHashAt?: string) {2431 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2432 }24332343 async getTokensByAddress(addressObj: ICrossAccountId) {2434 async getTokensByAddress(addressObj: ICrossAccountId) {2344 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2435 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2345 }2436 }2356 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2447 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2357 }2448 }235824492450 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2451 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2452 }24532454 async getPropertyPermissions(propertyKeys: string[] | null = null) {2455 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2456 }24572458 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2459 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2460 }24612359 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2462 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2360 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2463 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2361 }2464 }2368 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2471 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2369 }2472 }237024732371 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2372 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2373 }23742375 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2474 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2376 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2475 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2377 }2476 }2388 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2487 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2389 }2488 }239024892490 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2491 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2492 }24932391 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2494 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2392 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2495 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2393 }2496 }2402}2505}24032506240425072405class UniqueFTCollection extends UniqueCollectionBase {2508export class UniqueFTCollection extends UniqueBaseCollection {2406 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2509 async getBalance(addressObj: ICrossAccountId) {2407 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2510 return await this.helper.ft.getBalance(this.collectionId, addressObj);2408 }2511 }240925122410 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2513 async getTotalPieces() {2411 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2514 return await this.helper.ft.getTotalPieces(this.collectionId);2412 }2515 }241325162414 async getBalance(addressObj: ICrossAccountId) {2517 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2415 return await this.helper.ft.getBalance(this.collectionId, addressObj);2518 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2416 }2519 }241725202418 async getTop10Owners() {2521 async getTop10Owners() {2419 return await this.helper.ft.getTop10Owners(this.collectionId);2522 return await this.helper.ft.getTop10Owners(this.collectionId);2420 }2523 }242125242525 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2526 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2527 }25282529 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2530 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2531 }25322422 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2533 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2423 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2534 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2424 }2535 }2435 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2546 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2436 }2547 }243725482438 async getTotalPieces() {2439 return await this.helper.ft.getTotalPieces(this.collectionId);2440 }24412442 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2549 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2443 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2550 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2444 }2551 }24452446 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2447 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2448 }2449}2552}24502553245125542452class UniqueTokenBase implements IToken {2555export class UniqueBaseToken {2453 collection: UniqueNFTCollection | UniqueRFTCollection;2556 collection: UniqueNFTCollection | UniqueRFTCollection;2454 collectionId: number;2557 collectionId: number;2455 tokenId: number;2558 tokenId: number;2464 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2567 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2465 }2568 }246625692570 async getProperties(propertyKeys: string[] | null = null) {2571 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2572 }25732467 async setProperties(signer: TSigner, properties: IProperty[]) {2574 async setProperties(signer: TSigner, properties: IProperty[]) {2468 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2575 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2469 }2576 }247025772471 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2578 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2472 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2579 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2473 }2580 }25812582 nestingAccount() {2583 return this.collection.helper.util.getTokenAccount(this);2584 }2474}2585}24752586247625872477class UniqueNFTToken extends UniqueTokenBase {2588export class UniqueNFToken extends UniqueBaseToken {2478 collection: UniqueNFTCollection;2589 collection: UniqueNFTCollection;247925902480 constructor(tokenId: number, collection: UniqueNFTCollection) {2591 constructor(tokenId: number, collection: UniqueNFTCollection) {2525 async burn(signer: TSigner) {2636 async burn(signer: TSigner) {2526 return await this.collection.burnToken(signer, this.tokenId);2637 return await this.collection.burnToken(signer, this.tokenId);2527 }2638 }26392640 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2641 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2642 }2528}2643}252926442530class UniqueRFTToken extends UniqueTokenBase {2645export class UniqueRFToken extends UniqueBaseToken {2531 collection: UniqueRFTCollection;2646 collection: UniqueRFTCollection;253226472533 constructor(tokenId: number, collection: UniqueRFTCollection) {2648 constructor(tokenId: number, collection: UniqueRFTCollection) {2534 super(tokenId, collection);2649 super(tokenId, collection);2535 this.collection = collection;2650 this.collection = collection;2536 }2651 }253726522653 async getData(blockHashAt?: string) {2654 return await this.collection.getToken(this.tokenId, blockHashAt);2655 }26562538 async getTop10Owners() {2657 async getTop10Owners() {2539 return await this.collection.getTop10TokenOwners(this.tokenId);2658 return await this.collection.getTop10TokenOwners(this.tokenId);2540 }2659 }2547 return await this.collection.getTokenTotalPieces(this.tokenId);2666 return await this.collection.getTokenTotalPieces(this.tokenId);2548 }2667 }254926682669 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2670 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2671 }26722550 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2673 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2551 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2674 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2552 }2675 }2559 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2682 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2560 }2683 }256126842562 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2563 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2564 }25652566 async repartition(signer: TSigner, amount: bigint) {2685 async repartition(signer: TSigner, amount: bigint) {2567 return await this.collection.repartitionToken(signer, this.tokenId, amount);2686 return await this.collection.repartitionToken(signer, this.tokenId, amount);2568 }2687 }256926882570 async burn(signer: TSigner, amount=1n) {2689 async burn(signer: TSigner, amount=1n) {2571 return await this.collection.burnToken(signer, this.tokenId, amount);2690 return await this.collection.burnToken(signer, this.tokenId, amount);2691 }26922693 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2694 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2572 }2695 }2573}2696}25742697