difftreelog
feat add ApproveFrom eth mirror
in: master
26 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -746,6 +746,8 @@
ApprovedValueTooLow,
/// Tried to approve more than owned
CantApproveMoreThanOwned,
+ /// Only spending from eth mirror could be approved
+ AddressIsNotEthMirror,
/// Can't transfer tokens to ethereum zero address
AddressIsZero,
@@ -1797,6 +1799,9 @@
/// The price of setting the permission of the operation from another user.
fn approve() -> Weight;
+ /// The price of setting the permission of the operation from another user for eth mirror.
+ fn approve_from() -> Weight;
+
/// Transfer price from another user.
fn transfer_from() -> Weight;
@@ -2008,6 +2013,22 @@
amount: u128,
) -> DispatchResultWithPostInfo;
+ /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].
+ ///
+ /// * `sender` - The user who grants access to the token.
+ /// * `from` - Spender's eth mirror.
+ /// * `to` - The user to whom the rights are granted.
+ /// * `token` - The token to which access is granted.
+ /// * `amount` - The amount of pieces that another user can dispose of.
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo;
+
/// Send parts of a token owned by another user.
///
/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].
pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -283,8 +283,8 @@
/// Ethereum representation of Optional value with CrossAddress.
struct OptionCrossAddress {
- /// TODO: field description
+ /// Whether or not this CrossAdress is valid and has meaning.
bool status;
- /// TODO: field description
+ /// The underlying CrossAddress value. If the status is false, can be set to whatever.
CrossAddress value;
}
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -82,6 +82,16 @@
<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, 100)?}
+ approve_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+
+ };
+ let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+ <Pallet<T>>::create_item(&collection, &owner, (owner_eth.clone(), 200), &Unlimited)?;
+ }: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, &spender, 100)?}
+
transfer_from {
bench_init!{
owner: sub; collection: collection(owner);
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -87,6 +87,10 @@
<SelfWeightOf<T>>::approve()
}
+ fn approve_from() -> Weight {
+ <SelfWeightOf<T>>::approve_from()
+ }
+
fn transfer_from() -> Weight {
<SelfWeightOf<T>>::transfer_from()
}
@@ -254,6 +258,25 @@
)
}
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(
+ token == TokenId::default(),
+ <Error<T>>::FungibleItemsHaveNoId
+ );
+
+ with_weight(
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, &to, amount),
+ <CommonWeights<T>>::approve_from(),
+ )
+ }
+
fn transfer_from(
&self,
sender: T::CrossAccountId,
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -613,6 +613,45 @@
Ok(())
}
+ /// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.
+ ///
+ /// - `collection`: Collection that contains the token
+ /// - `sender`: Owner of tokens that sets the allowance.
+ /// - `from`: Owner's eth mirror.
+ /// - `to`: Recipient of the allowance rights.
+ /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.
+ pub fn set_allowance_for(
+ collection: &FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ amount: u128,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(sender)?;
+ collection.check_allowlist(from)?;
+ collection.check_allowlist(to)?;
+ }
+
+ ensure!(
+ *sender.as_eth() == *from.as_eth(),
+ <CommonError<T>>::AddressIsNotEthMirror
+ );
+
+ if <Balance<T>>::get((collection.id, from)) < amount {
+ ensure!(
+ collection.limits.owner_can_transfer()
+ && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, from, to, amount);
+ Ok(())
+ }
+
/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.
/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.
///
pallets/fungible/src/weights.rsdiffbeforeafterboth--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -39,6 +39,7 @@
fn burn_item() -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
+ fn approve_from() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
}
@@ -84,6 +85,13 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Fungible Balance (r:1 w:0)
+ // Storage: Fungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(19_817_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
// Storage: Fungible Allowance (r:1 w:1)
// Storage: Fungible Balance (r:2 w:2)
fn transfer_from() -> Weight {
@@ -141,6 +149,13 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Fungible Balance (r:1 w:0)
+ // Storage: Fungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(19_817_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
// Storage: Fungible Allowance (r:1 w:1)
// Storage: Fungible Balance (r:2 w:2)
fn transfer_from() -> Weight {
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -134,6 +134,15 @@
let item = create_max_item(&collection, &owner, sender.clone())?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?}
+ approve_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+ let item = create_max_item(&collection, &owner, owner_eth.clone())?;
+ }: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, item, Some(&spender))?}
+
transfer_from {
bench_init!{
owner: sub; collection: collection(owner);
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -102,6 +102,10 @@
<SelfWeightOf<T>>::approve()
}
+ fn approve_from() -> Weight {
+ <SelfWeightOf<T>>::approve_from()
+ }
+
fn transfer_from() -> Weight {
<SelfWeightOf<T>>::transfer_from()
}
@@ -353,6 +357,26 @@
)
}
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+ with_weight(
+ if amount == 1 {
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, token, Some(&to))
+ } else {
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, token, None)
+ },
+ <CommonWeights<T>>::approve_from(),
+ )
+ }
+
fn transfer_from(
&self,
sender: T::CrossAccountId,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1171,6 +1171,51 @@
Ok(())
}
+ /// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.
+ ///
+ /// - `from`: Address of sender's eth mirror.
+ /// - `to`: Adress of spender.
+ /// - `token`: Token the spender is allowed to `transfer` or `burn`.
+ pub fn set_allowance_for(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ token: TokenId,
+ to: Option<&T::CrossAccountId>,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(sender)?;
+ collection.check_allowlist(from)?;
+ if let Some(to) = to {
+ collection.check_allowlist(to)?;
+ }
+ }
+
+ if let Some(to) = to {
+ <PalletCommon<T>>::ensure_correct_receiver(to)?;
+ }
+
+ ensure!(
+ *sender.as_eth() == *from.as_eth(),
+ <CommonError<T>>::AddressIsNotEthMirror
+ );
+
+ let token_data =
+ <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
+ if token_data.owner != *from {
+ ensure!(
+ collection.limits.owner_can_transfer()
+ && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, from, token, to, false);
+ Ok(())
+ }
+
/// Checks allowance for the spender to use the token.
fn check_allowed(
collection: &NonfungibleHandle<T>,
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -42,6 +42,7 @@
fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
+ fn approve_from() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
fn set_token_property_permissions(b: u32, ) -> Weight;
@@ -147,6 +148,13 @@
.saturating_add(T::DbWeight::get().reads(2 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(18_965_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(2 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
// Storage: Nonfungible Allowance (r:1 w:1)
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
@@ -310,6 +318,13 @@
.saturating_add(RocksDbWeight::get().reads(2 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(18_965_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(2 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
// Storage: Nonfungible Allowance (r:1 w:1)
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -163,6 +163,15 @@
let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?}
+ approve_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+ let item = create_max_item(&collection, &owner, [(owner_eth.clone(), 200)])?;
+ }: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, &spender, item, 100)?}
+
transfer_from_normal {
bench_init!{
owner: sub; collection: collection(owner);
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -127,6 +127,10 @@
<SelfWeightOf<T>>::approve()
}
+ fn approve_from() -> Weight {
+ <SelfWeightOf<T>>::approve_from()
+ }
+
fn transfer_from() -> Weight {
max_weight_of!(
transfer_from_normal(),
@@ -314,6 +318,20 @@
)
}
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token_id: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, &to, token_id, amount),
+ <CommonWeights<T>>::approve_from(),
+ )
+ }
+
fn transfer_from(
&self,
sender: T::CrossAccountId,
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1102,6 +1102,47 @@
Ok(())
}
+ /// Set allowance to spend from sender's eth mirror
+ ///
+ /// - `from`: Address of sender's eth mirror.
+ /// - `to`: Adress of spender.
+ /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.
+ pub fn set_allowance_for(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ token_id: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(sender)?;
+ collection.check_allowlist(from)?;
+ collection.check_allowlist(to)?;
+ }
+
+ <PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+ ensure!(
+ *sender.as_eth() == *from.as_eth(),
+ <CommonError<T>>::AddressIsNotEthMirror
+ );
+
+ if <Balance<T>>::get((collection.id, token_id, from)) < amount {
+ ensure!(
+ collection.limits.owner_can_transfer()
+ && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))
+ && Self::token_exists(collection, token_id),
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, from, to, token_id, amount);
+ Ok(())
+ }
+
/// Returns allowance, which should be set after transaction
fn check_allowed(
collection: &RefungibleHandle<T>,
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -45,6 +45,7 @@
fn transfer_removing() -> Weight;
fn transfer_creating_removing() -> Weight;
fn approve() -> Weight;
+ fn approve_from() -> Weight;
fn transfer_from_normal() -> Weight;
fn transfer_from_creating() -> Weight;
fn transfer_from_removing() -> Weight;
@@ -175,6 +176,13 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(20_649_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible CollectionAllowance (r:1 w:0)
// Storage: Refungible Balance (r:2 w:2)
@@ -400,6 +408,13 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(20_649_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible CollectionAllowance (r:1 w:0)
// Storage: Refungible Balance (r:2 w:2)
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -851,6 +851,29 @@
dispatch_tx::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))
}
+ /// Allow a non-permissioned address to transfer or burn an item from owner's eth mirror.
+ ///
+ /// # Permissions
+ ///
+ /// * Collection owner
+ /// * Collection admin
+ /// * Current item owner
+ ///
+ /// # Arguments
+ ///
+ /// * `from`: Owner's account eth mirror
+ /// * `to`: Account to be approved to make specific transactions on non-owned tokens.
+ /// * `collection_id`: ID of the collection the item belongs to.
+ /// * `item_id`: ID of the item transactions on which are now approved.
+ /// * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).
+ /// Set to 0 to revoke the approval.
+ #[weight = T::CommonWeightInfo::approve_from()]
+ pub fn approve_from(origin, from:T::CrossAccountId, to: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+ dispatch_tx::<T, _>(collection_id, |d| d.approve_from(sender, from, to, item_id, amount))
+ }
+
/// Change ownership of an item on behalf of the owner as a non-owner account.
///
/// See the [`approve`][`Pallet::approve`] method for additional information.
runtime/common/identity.rsdiffbeforeafterboth--- a/runtime/common/identity.rs
+++ b/runtime/common/identity.rs
@@ -21,9 +21,7 @@
use sp_runtime::{
traits::{DispatchInfoOf, SignedExtension},
- transaction_validity::{
- TransactionValidity, ValidTransaction, InvalidTransaction, TransactionValidityError,
- },
+ transaction_validity::{TransactionValidity, ValidTransaction, TransactionValidityError},
};
#[derive(Debug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
runtime/common/weights.rsdiffbeforeafterboth--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -101,6 +101,10 @@
dispatch_weight::<T>() + max_weight_of!(approve())
}
+ fn approve_from() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(approve_from())
+ }
+
fn transfer_from() -> Weight {
dispatch_weight::<T>() + max_weight_of!(transfer_from())
}
tests/src/approve.test.tsdiffbeforeafterboth1// 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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {expect, itSub, Pallets, usingPlaygrounds} from './util';192021describe('Integration Test approve(spender, collection_id, item_id, amount):', () => {22 let alice: IKeyringPair;23 let bob: IKeyringPair;24 let charlie: IKeyringPair;2526 before(async () => {27 await usingPlaygrounds(async (helper, privateKey) => {28 const donor = await privateKey({filename: __filename});29 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);30 });31 });3233 itSub('[nft] Execute the extrinsic and check approvedList', async ({helper}) => {34 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});35 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});36 await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});37 expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;38 });3940 itSub('[fungible] Execute the extrinsic and check approvedList', async ({helper}) => {41 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);42 await helper.ft.mintTokens(alice, collectionId, 10n, {Substrate: alice.address});43 const tokenId = await helper.ft.getLastTokenId(collectionId);44 await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});45 const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});46 expect(amount).to.be.equal(BigInt(1));47 });4849 itSub.ifWithPallets('[refungible] Execute the extrinsic and check approvedList', [Pallets.ReFungible], async ({helper}) => {50 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});51 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});52 await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});53 const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});54 expect(amount).to.be.equal(BigInt(1));55 });5657 itSub('[nft] Remove approval by using 0 amount', async ({helper}) => {58 const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});59 const collectionId = collection.collectionId;60 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});61 await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});62 expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;63 await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));64 expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;65 });6667 itSub('[fungible] Remove approval by using 0 amount', async ({helper}) => {68 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);69 await helper.ft.mintTokens(alice, collectionId, 10n, {Substrate: alice.address});70 const tokenId = await helper.ft.getLastTokenId(collectionId);71 await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});72 const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});73 expect(amountBefore).to.be.equal(BigInt(1));7475 await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);76 const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});77 expect(amountAfter).to.be.equal(BigInt(0));78 });7980 itSub.ifWithPallets('[refungible] Remove approval by using 0 amount', [Pallets.ReFungible], async ({helper}) => {81 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});82 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});83 await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});84 const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});85 expect(amountBefore).to.be.equal(BigInt(1));8687 await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);88 const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});89 expect(amountAfter).to.be.equal(BigInt(0));90 });9192 itSub('can`t be called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {93 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});94 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});95 const approveTokenTx = () => helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: charlie.address});96 await expect(approveTokenTx()).to.be.rejected;97 });98});99100describe('Normal user can approve other users to transfer:', () => {101 let alice: IKeyringPair;102 let bob: IKeyringPair;103 let charlie: IKeyringPair;104105 before(async () => {106 await usingPlaygrounds(async (helper, privateKey) => {107 const donor = await privateKey({filename: __filename});108 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);109 });110 });111112 itSub('NFT', async ({helper}) => {113 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});114 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});115 await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});116 expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.true;117 });118119 itSub('Fungible up to an approved amount', async ({helper}) => {120 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);121 await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);122 const tokenId = await helper.ft.getLastTokenId(collectionId);123 await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});124 const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, {Substrate: bob.address});125 expect(amount).to.be.equal(BigInt(1));126 });127128 itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {129 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});130 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});131 await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);132 const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, {Substrate: bob.address});133 expect(amount).to.be.equal(BigInt(100n));134 });135});136137describe('Approved users can transferFrom up to approved amount:', () => {138 let alice: IKeyringPair;139 let bob: IKeyringPair;140 let charlie: IKeyringPair;141142 before(async () => {143 await usingPlaygrounds(async (helper, privateKey) => {144 const donor = await privateKey({filename: __filename});145 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);146 });147 });148149 itSub('NFT', async ({helper}) => {150 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});151 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});152 await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});153 await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});154 const owner = await helper.nft.getTokenOwner(collectionId, tokenId);155 expect(owner.Substrate).to.be.equal(alice.address);156 });157158 itSub('Fungible up to an approved amount', async ({helper}) => {159 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);160 await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);161 const tokenId = await helper.ft.getLastTokenId(collectionId);162 await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});163 const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});164 await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);165 const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});166 expect(after - before).to.be.equal(BigInt(1));167 });168169 itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {170 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});171 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});172 await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});173 const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});174 await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);175 const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});176 expect(after - before).to.be.equal(BigInt(1));177 });178});179180describe('Approved users cannot use transferFrom to repeat transfers if approved amount was already transferred:', () => {181 let alice: IKeyringPair;182 let bob: IKeyringPair;183 let charlie: IKeyringPair;184185 before(async () => {186 await usingPlaygrounds(async (helper, privateKey) => {187 const donor = await privateKey({filename: __filename});188 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);189 });190 });191192 itSub('NFT', async ({helper}) => {193 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});194 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});195 await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});196 await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});197 const owner = await helper.nft.getTokenOwner(collectionId, tokenId);198 expect(owner.Substrate).to.be.equal(alice.address);199 const transferTokenFromTx = () => helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});200 await expect(transferTokenFromTx()).to.be.rejected;201 });202203 itSub('Fungible up to an approved amount', async ({helper}) => {204 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);205 await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);206 const tokenId = await helper.ft.getLastTokenId(collectionId);207 await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});208 const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});209 await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);210 const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});211 expect(after - before).to.be.equal(BigInt(1));212213 const transferTokenFromTx = () => helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);214 await expect(transferTokenFromTx()).to.be.rejected;215 });216217 itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {218 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});219 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});220 await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);221 const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});222 await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 100n);223 const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});224 expect(after - before).to.be.equal(BigInt(100));225 const transferTokenFromTx = () => helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 100n);226 await expect(transferTokenFromTx()).to.be.rejected;227 });228});229230describe('Approved amount decreases by the transferred amount:', () => {231 let alice: IKeyringPair;232 let bob: IKeyringPair;233 let charlie: IKeyringPair;234 let dave: IKeyringPair;235236 before(async () => {237 await usingPlaygrounds(async (helper, privateKey) => {238 const donor = await privateKey({filename: __filename});239 [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);240 });241 });242243 itSub('If a user B is approved to transfer 10 Fungible tokens from user A, they can transfer 2 tokens to user C, which will result in decreasing approval from 10 to 8. Then user B can transfer 8 tokens to user D.', async ({helper}) => {244 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);245 await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);246 const tokenId = await helper.ft.getLastTokenId(collectionId);247 await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 10n);248249 const charlieBefore = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});250 await helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: alice.address}, {Substrate: charlie.address}, 2n);251 const charlieAfter = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});252 expect(charlieAfter - charlieBefore).to.be.equal(BigInt(2));253254 const daveBefore = await helper.ft.getBalance(collectionId, {Substrate: dave.address});255 await helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: alice.address}, {Substrate: dave.address}, 8n);256 const daveAfter = await helper.ft.getBalance(collectionId, {Substrate: dave.address});257 expect(daveAfter - daveBefore).to.be.equal(BigInt(8));258 });259});260261describe('User may clear the approvals to approving for 0 amount:', () => {262 let alice: IKeyringPair;263 let bob: IKeyringPair;264 let charlie: IKeyringPair;265266 before(async () => {267 await usingPlaygrounds(async (helper, privateKey) => {268 const donor = await privateKey({filename: __filename});269 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);270 });271 });272273 itSub('NFT', async ({helper}) => {274 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});275 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});276 await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});277 expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;278 await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));279 expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;280 const transferTokenFromTx = () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});281 await expect(transferTokenFromTx()).to.be.rejected;282 });283284 itSub('Fungible', async ({helper}) => {285 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);286 await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);287 const tokenId = await helper.ft.getLastTokenId(collectionId);288 await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});289 const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});290 expect(amountBefore).to.be.equal(BigInt(1));291292 await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);293 const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});294 expect(amountAfter).to.be.equal(BigInt(0));295296 const transferTokenFromTx = () => helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 1n);297 await expect(transferTokenFromTx()).to.be.rejected;298 });299300 itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {301 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});302 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});303 await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});304 const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});305 expect(amountBefore).to.be.equal(BigInt(1));306307 await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);308 const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});309 expect(amountAfter).to.be.equal(BigInt(0));310311 const transferTokenFromTx = () => helper.rft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 100n);312 await expect(transferTokenFromTx()).to.be.rejected;313 });314});315316describe('User cannot approve for the amount greater than they own:', () => {317 let alice: IKeyringPair;318 let bob: IKeyringPair;319 let charlie: IKeyringPair;320321 before(async () => {322 await usingPlaygrounds(async (helper, privateKey) => {323 const donor = await privateKey({filename: __filename});324 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);325 });326 });327328 itSub('1 for NFT', async ({helper}) => {329 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});330 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});331 const approveTx = () => helper.signTransaction(bob, helper.constructApiCall('api.tx.unique.approve', [{Substrate: charlie.address}, collectionId, tokenId, 2]));332 await expect(approveTx()).to.be.rejected;333 expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;334 });335336 itSub('Fungible', async ({helper}) => {337 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);338 await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);339 const tokenId = await helper.ft.getLastTokenId(collectionId);340 const approveTx = () => helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 11n);341 await expect(approveTx()).to.be.rejected;342 });343344 itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {345 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});346 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});347 const approveTx = () => helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 101n);348 await expect(approveTx()).to.be.rejected;349 });350});351352describe('Administrator and collection owner do not need approval in order to execute TransferFrom (with owner_can_transfer_flag = true):', () => {353 let alice: IKeyringPair;354 let bob: IKeyringPair;355 let charlie: IKeyringPair;356 let dave: IKeyringPair;357358 before(async () => {359 await usingPlaygrounds(async (helper, privateKey) => {360 const donor = await privateKey({filename: __filename});361 [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);362 });363 });364365 itSub('NFT', async ({helper}) => {366 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});367 await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: true});368 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: charlie.address});369370 await helper.nft.transferTokenFrom(alice, collectionId, tokenId, {Substrate: charlie.address}, {Substrate: dave.address});371 const owner1 = await helper.nft.getTokenOwner(collectionId, tokenId);372 expect(owner1.Substrate).to.be.equal(dave.address);373374 await helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});375 await helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: dave.address}, {Substrate: alice.address});376 const owner2 = await helper.nft.getTokenOwner(collectionId, tokenId);377 expect(owner2.Substrate).to.be.equal(alice.address);378 });379380 itSub('Fungible up to an approved amount', async ({helper}) => {381 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);382 await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: true});383 await helper.ft.mintTokens(alice, collectionId, 10n, charlie.address);384 const tokenId = await helper.ft.getLastTokenId(collectionId);385386 const daveBalanceBefore = await helper.ft.getBalance(collectionId, {Substrate: dave.address});387 await helper.ft.transferTokenFrom(alice, collectionId, tokenId, {Substrate: charlie.address}, {Substrate: dave.address}, 1n);388 const daveBalanceAfter = await helper.ft.getBalance(collectionId, {Substrate: dave.address});389 expect(daveBalanceAfter - daveBalanceBefore).to.be.equal(BigInt(1));390391 await helper.collection.addAdmin(alice ,collectionId, {Substrate: bob.address});392393 const aliceBalanceBefore = await helper.ft.getBalance(collectionId, {Substrate: alice.address});394 await helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: dave.address}, {Substrate: alice.address}, 1n);395 const aliceBalanceAfter = await helper.ft.getBalance(collectionId, {Substrate: alice.address});396 expect(aliceBalanceAfter - aliceBalanceBefore).to.be.equal(BigInt(1));397 });398399 itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {400 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});401 await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: true});402 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: charlie.address, pieces: 100n});403404 const daveBefore = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: dave.address});405 await helper.rft.transferTokenFrom(alice, collectionId, tokenId, {Substrate: charlie.address}, {Substrate: dave.address}, 1n);406 const daveAfter = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: dave.address});407 expect(daveAfter - daveBefore).to.be.equal(BigInt(1));408409 await helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});410411 const aliceBefore = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});412 await helper.rft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: dave.address}, {Substrate: alice.address}, 1n);413 const aliceAfter = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});414 expect(aliceAfter - aliceBefore).to.be.equal(BigInt(1));415 });416});417418describe('Repeated approvals add up', () => {419 let alice: IKeyringPair;420 let bob: IKeyringPair;421 let charlie: IKeyringPair;422 let dave: IKeyringPair;423424 before(async () => {425 await usingPlaygrounds(async (helper, privateKey) => {426 const donor = await privateKey({filename: __filename});427 [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);428 });429 });430431 itSub.skip('Owned 10, approval 1: 1, approval 2: 1, resulting approved value: 2. Fungible', async ({helper}) => {432 const collection = await helper.ft.mintCollection(alice, {});433 await collection.mint(alice, 10n);434 await collection.approveTokens(alice, {Substrate: bob.address}, 1n);435 await collection.approveTokens(alice, {Substrate: charlie.address}, 1n);436 // const allowances1 = await getAllowance(collectionId, 0, Alice.address, Bob.address);437 // const allowances2 = await getAllowance(collectionId, 0, Alice.address, Charlie.address);438 // expect(allowances1 + allowances2).to.be.eq(BigInt(2));439 });440441 itSub.skip('Owned 10, approval 1: 1, approval 2: 1, resulting approved value: 2. ReFungible', async ({helper}) => {442 const collection = await helper.rft.mintCollection(alice, {});443 const token = await collection.mintToken(alice, 10n);444 await token.approve(alice, {Substrate: bob.address}, 1n);445 await token.approve(alice, {Substrate: charlie.address}, 1n);446 // const allowances1 = await getAllowance(collectionId, itemId, Alice.address, Bob.address);447 // const allowances2 = await getAllowance(collectionId, itemId, Alice.address, Charlie.address);448 // expect(allowances1 + allowances2).to.be.eq(BigInt(2));449 });450451 // Canceled by changing approve logic452 itSub.skip('Cannot approve for more than total user\'s amount (owned: 10, approval 1: 5 - should succeed, approval 2: 6 - should fail). Fungible', async ({helper}) => {453 const collection = await helper.ft.mintCollection(alice, {});454 await collection.mint(alice, 10n, {Substrate: dave.address});455 await collection.approveTokens(dave, {Substrate: bob.address}, 5n);456 await expect(collection.approveTokens(dave, {Substrate: charlie.address}, 6n))457 .to.be.rejectedWith('this test would fail (since it is skipped), replace this expecting message with what would have been received');458 });459460 // Canceled by changing approve logic461 itSub.skip('Cannot approve for more than total user\'s amount (owned: 100, approval 1: 50 - should succeed, approval 2: 51 - should fail). ReFungible', async ({helper}) => {462 const collection = await helper.rft.mintCollection(alice, {});463 const token = await collection.mintToken(alice, 100n, {Substrate: dave.address});464 await token.approve(dave, {Substrate: bob.address}, 50n);465 await expect(token.approve(dave, {Substrate: charlie.address}, 51n))466 .to.be.rejectedWith('this test would fail (since it is skipped), replace this expecting message with what would have been received');467 });468});469470describe('Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:', () => {471 let alice: IKeyringPair;472 let bob: IKeyringPair;473 let charlie: IKeyringPair;474475 before(async () => {476 await usingPlaygrounds(async (helper, privateKey) => {477 const donor = await privateKey({filename: __filename});478 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);479 });480 });481482 itSub('can be called by collection admin on non-owned item', async ({helper}) => {483 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});484 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});485 await helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});486 const approveTx = () => helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});487 await expect(approveTx()).to.be.rejected;488 });489});490491describe('Negative Integration Test approve(spender, collection_id, item_id, amount):', () => {492 let alice: IKeyringPair;493 let bob: IKeyringPair;494 let charlie: IKeyringPair;495496 before(async () => {497 await usingPlaygrounds(async (helper, privateKey) => {498 const donor = await privateKey({filename: __filename});499 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);500 });501 });502503 itSub('[nft] Approve for a collection that does not exist', async ({helper}) => {504 const collectionId = 1 << 32 - 1;505 const approveTx = () => helper.nft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});506 await expect(approveTx()).to.be.rejected;507 });508509 itSub('[fungible] Approve for a collection that does not exist', async ({helper}) => {510 const collectionId = 1 << 32 - 1;511 const approveTx = () => helper.ft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});512 await expect(approveTx()).to.be.rejected;513 });514515 itSub.ifWithPallets('[refungible] Approve for a collection that does not exist', [Pallets.ReFungible], async ({helper}) => {516 const collectionId = 1 << 32 - 1;517 const approveTx = () => helper.rft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});518 await expect(approveTx()).to.be.rejected;519 });520521 itSub('[nft] Approve for a collection that was destroyed', async ({helper}) => {522 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});523 await helper.nft.burn(alice, collectionId);524 const approveTx = () => helper.nft.approveToken(alice, collectionId, 1, {Substrate: bob.address});525 await expect(approveTx()).to.be.rejected;526 });527528 itSub('[fungible] Approve for a collection that was destroyed', async ({helper}) => {529 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});530 await helper.ft.burn(alice, collectionId);531 const approveTx = () => helper.ft.approveToken(alice, collectionId, 1, {Substrate: bob.address});532 await expect(approveTx()).to.be.rejected;533 });534535 itSub.ifWithPallets('[refungible] Approve for a collection that was destroyed', [Pallets.ReFungible], async ({helper}) => {536 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});537 await helper.rft.burn(alice, collectionId);538 const approveTx = () => helper.rft.approveToken(alice, collectionId, 1, {Substrate: bob.address});539 await expect(approveTx()).to.be.rejected;540 });541542 itSub('[nft] Approve transfer of a token that does not exist', async ({helper}) => {543 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});544 const approveTx = () => helper.nft.approveToken(alice, collectionId, 2, {Substrate: bob.address});545 await expect(approveTx()).to.be.rejected;546 });547548 itSub.ifWithPallets('[refungible] Approve transfer of a token that does not exist', [Pallets.ReFungible], async ({helper}) => {549 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});550 const approveTx = () => helper.rft.approveToken(alice, collectionId, 2, {Substrate: bob.address});551 await expect(approveTx()).to.be.rejected;552 });553554 itSub('[nft] Approve using the address that does not own the approved token', async ({helper}) => {555 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});556 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});557 const approveTx = () => helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});558 await expect(approveTx()).to.be.rejected;559 });560561 itSub('[fungible] Approve using the address that does not own the approved token', async ({helper}) => {562 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});563 await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);564 const tokenId = await helper.ft.getLastTokenId(collectionId);565 const approveTx = () => helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});566 await expect(approveTx()).to.be.rejected;567 });568569 itSub.ifWithPallets('[refungible] Approve using the address that does not own the approved token', [Pallets.ReFungible], async ({helper}) => {570 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});571 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});572 const approveTx = () => helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});573 await expect(approveTx()).to.be.rejected;574 });575576 itSub.ifWithPallets('should fail if approved more ReFungibles than owned', [Pallets.ReFungible], async ({helper}) => {577 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});578 const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});579 await helper.rft.transferToken(alice, collectionId, tokenId, {Substrate: bob.address}, 100n);580 await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 100n);581582 const approveTx = () => helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 101n);583 await expect(approveTx()).to.be.rejected;584 });585586 itSub('should fail if approved more Fungibles than owned', async ({helper}) => {587 const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});588 await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);589 const tokenId = await helper.ft.getLastTokenId(collectionId);590591 await helper.ft.transferToken(alice, collectionId, tokenId, {Substrate: bob.address}, 10n);592 await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 10n);593 const approveTx = () => helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 11n);594 await expect(approveTx()).to.be.rejected;595 });596597 itSub('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {598 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});599 const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});600 await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: false});601602 const approveTx = () => helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: charlie.address});603 await expect(approveTx()).to.be.rejected;604 });605});606607describe('Normal user can approve other users to be wallet operator:', () => {608 let alice: IKeyringPair;609 let bob: IKeyringPair;610611 before(async () => {612 await usingPlaygrounds(async (helper, privateKey) => {613 const donor = await privateKey({filename: __filename});614 [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);615 });616 });617618 itSub('[nft] Enable and disable approval', async ({helper}) => {619 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});620621 const checkBeforeApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});622 expect(checkBeforeApproval).to.be.false;623624 await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);625 const checkAfterApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});626 expect(checkAfterApproval).to.be.true;627628 await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);629 const checkAfterDisapproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});630 expect(checkAfterDisapproval).to.be.false;631 });632633 itSub.ifWithPallets('[rft] Enable and disable approval', [Pallets.ReFungible], async ({helper}) => {634 const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});635636 const checkBeforeApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});637 expect(checkBeforeApproval).to.be.false;638639 await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);640 const checkAfterApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});641 expect(checkAfterApproval).to.be.true;642643 await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);644 const checkAfterDisapproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});645 expect(checkAfterDisapproval).to.be.false;646 });647});tests/src/eth/api/ContractHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -183,9 +183,9 @@
/// Ethereum representation of Optional value with CrossAddress.
struct OptionCrossAddress {
- /// TODO: field description
+ /// Whether or not this CrossAdress is valid and has meaning.
bool status;
- /// TODO: field description
+ /// The underlying CrossAddress value. If the status is false, can be set to whatever.
CrossAddress value;
}
tests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -85,6 +85,10 @@
**/
AccountTokenLimitExceeded: AugmentedError<ApiType>;
/**
+ * Only spending from eth mirror could be approved
+ **/
+ AddressIsNotEthMirror: AugmentedError<ApiType>;
+ /**
* Can't transfer tokens to ethereum zero address
**/
AddressIsZero: AugmentedError<ApiType>;
tests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -1214,6 +1214,25 @@
**/
approve: AugmentedSubmittable<(spender: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, collectionId: u32 | AnyNumber | Uint8Array, itemId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr, u32, u32, u128]>;
/**
+ * Allow a non-permissioned address to transfer or burn an item from owner's eth mirror.
+ *
+ * # Permissions
+ *
+ * * Collection owner
+ * * Collection admin
+ * * Current item owner
+ *
+ * # Arguments
+ *
+ * * `from`: Owner's account eth mirror
+ * * `to`: Account to be approved to make specific transactions on non-owned tokens.
+ * * `collection_id`: ID of the collection the item belongs to.
+ * * `item_id`: ID of the item transactions on which are now approved.
+ * * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).
+ * Set to 0 to revoke the approval.
+ **/
+ approveFrom: AugmentedSubmittable<(from: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, to: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, collectionId: u32 | AnyNumber | Uint8Array, itemId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u32, u32, u128]>;
+ /**
* Destroy a token on behalf of the owner as a non-owner account.
*
* See also: [`approve`][`Pallet::approve`].
tests/src/interfaces/default/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -1216,6 +1216,7 @@
readonly isTokenValueTooLow: boolean;
readonly isApprovedValueTooLow: boolean;
readonly isCantApproveMoreThanOwned: boolean;
+ readonly isAddressIsNotEthMirror: boolean;
readonly isAddressIsZero: boolean;
readonly isUnsupportedOperation: boolean;
readonly isNotSufficientFounds: boolean;
@@ -1231,7 +1232,7 @@
readonly isCollectionIsInternal: boolean;
readonly isConfirmSponsorshipFail: boolean;
readonly isUserIsNotCollectionAdmin: boolean;
- readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
+ readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
}
/** @name PalletCommonEvent */
@@ -2306,6 +2307,14 @@
readonly itemId: u32;
readonly amount: u128;
} & Struct;
+ readonly isApproveFrom: boolean;
+ readonly asApproveFrom: {
+ readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly to: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly collectionId: u32;
+ readonly itemId: u32;
+ readonly amount: u128;
+ } & Struct;
readonly isTransferFrom: boolean;
readonly asTransferFrom: {
readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
@@ -2345,7 +2354,7 @@
readonly collectionId: u32;
readonly itemId: u32;
} & Struct;
- readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
+ readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'ApproveFrom' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
}
/** @name PalletUniqueError */
tests/src/interfaces/lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2264,6 +2264,13 @@
itemId: 'u32',
amount: 'u128',
},
+ approve_from: {
+ from: 'PalletEvmAccountBasicCrossAccountIdRepr',
+ to: 'PalletEvmAccountBasicCrossAccountIdRepr',
+ collectionId: 'u32',
+ itemId: 'u32',
+ amount: 'u128',
+ },
transfer_from: {
from: 'PalletEvmAccountBasicCrossAccountIdRepr',
recipient: 'PalletEvmAccountBasicCrossAccountIdRepr',
@@ -3280,7 +3287,7 @@
* Lookup423: pallet_common::pallet::Error<T>
**/
PalletCommonError: {
- _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
+ _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsNotEthMirror', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
},
/**
* Lookup425: pallet_fungible::pallet::Error<T>
tests/src/interfaces/types-lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -2493,6 +2493,14 @@
readonly itemId: u32;
readonly amount: u128;
} & Struct;
+ readonly isApproveFrom: boolean;
+ readonly asApproveFrom: {
+ readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly to: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly collectionId: u32;
+ readonly itemId: u32;
+ readonly amount: u128;
+ } & Struct;
readonly isTransferFrom: boolean;
readonly asTransferFrom: {
readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
@@ -2532,7 +2540,7 @@
readonly collectionId: u32;
readonly itemId: u32;
} & Struct;
- readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
+ readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'ApproveFrom' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
}
/** @name UpDataStructsCollectionMode (236) */
@@ -3564,6 +3572,7 @@
readonly isTokenValueTooLow: boolean;
readonly isApprovedValueTooLow: boolean;
readonly isCantApproveMoreThanOwned: boolean;
+ readonly isAddressIsNotEthMirror: boolean;
readonly isAddressIsZero: boolean;
readonly isUnsupportedOperation: boolean;
readonly isNotSufficientFounds: boolean;
@@ -3579,7 +3588,7 @@
readonly isCollectionIsInternal: boolean;
readonly isConfirmSponsorshipFail: boolean;
readonly isUserIsNotCollectionAdmin: boolean;
- readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
+ readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
}
/** @name PalletFungibleError (425) */
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -633,6 +633,10 @@
let call = this.getApi() as any;
for(const part of apiCall.slice(4).split('.')) {
call = call[part];
+ if (!call) {
+ const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';
+ throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);
+ }
}
return call(...params);
}
@@ -1259,6 +1263,42 @@
}
/**
+ * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.
+ *
+ * @param signer keyring of signer
+ * @param collectionId ID of collection
+ * @param tokenId ID of token
+ * @param fromAddressObj Signer's Ethereum address containing her tokens
+ * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens
+ * @param amount amount of token to be approved. For NFT must be set to 1n
+ * @returns ```true``` if extrinsic success, otherwise ```false```
+ */
+ async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
+ const approveResult = await this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],
+ true, // `Unable to approve token for ${label}`,
+ );
+
+ return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');
+ }
+
+ /**
+ * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.
+ *
+ * @param signer keyring of signer
+ * @param collectionId ID of collection
+ * @param tokenId ID of token
+ * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens
+ * @param amount amount of token to be approved. For NFT must be set to 1n
+ * @returns ```true``` if extrinsic success, otherwise ```false```
+ */
+ async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
+ const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();
+ return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);
+ }
+
+ /**
* Get the amount of token pieces approved to transfer or burn. Normally 0.
*
* @param collectionId ID of collection
@@ -1756,8 +1796,8 @@
* @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})
* @returns ```true``` if extrinsic success, otherwise ```false```
*/
- approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {
- return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);
+ approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
+ return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);
}
}