difftreelog
Merge pull request #343 from UniqueNetwork/feature/CORE-302
in: master
Feature/core 302
49 files changed
.maintain/scripts/generate_abi.shdiffbeforeafterboth--- /dev/null
+++ b/.maintain/scripts/generate_abi.sh
@@ -0,0 +1,13 @@
+#!/bin/sh
+set -eu
+
+dir=$PWD
+
+tmp=$(mktemp -d)
+cd $tmp
+cp $dir/$INPUT input.sol
+solcjs --abi -p input.sol
+
+NAME=input_sol_$(basename $INPUT .sol)
+mv $NAME.abi $NAME.json
+prettier $NAME.json > $dir/$OUTPUT
.maintain/scripts/generate_api.shdiffbeforeafterboth--- a/.maintain/scripts/generate_api.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/bin/sh
-set -eu
-
-tmp=$(mktemp)
-cargo test --package $PACKAGE -- $NAME --exact --nocapture --ignored | tee $tmp
-raw=$(mktemp --suffix .sol)
-sed -n '/=== SNIP START ===/, /=== SNIP END ===/{ /=== SNIP START ===/! { /=== SNIP END ===/! p } }' $tmp > $raw
-formatted=$(mktemp)
-prettier --use-tabs $raw > $formatted
-
-mv $formatted $OUTPUT
.maintain/scripts/generate_sol.shdiffbeforeafterboth--- /dev/null
+++ b/.maintain/scripts/generate_sol.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+set -eu
+
+tmp=$(mktemp)
+cargo test --package $PACKAGE -- $NAME --exact --nocapture --ignored | tee $tmp
+raw=$(mktemp --suffix .sol)
+sed -n '/=== SNIP START ===/, /=== SNIP END ===/{ /=== SNIP START ===/! { /=== SNIP END ===/! p } }' $tmp > $raw
+formatted=$(mktemp)
+prettier --use-tabs $raw > $formatted
+
+mv $formatted $OUTPUT
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4290,6 +4290,9 @@
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
+dependencies = [
+ "spin",
+]
[[package]]
name = "lazycell"
@@ -5467,9 +5470,9 @@
[[package]]
name = "once_cell"
-version = "1.11.0"
+version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7b10983b38c53aebdf33f542c6275b0f58a238129d00c4ae0e6fb59738d783ca"
+checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225"
[[package]]
name = "opal-runtime"
@@ -5917,6 +5920,7 @@
"frame-benchmarking",
"frame-support",
"frame-system",
+ "lazy_static",
"pallet-evm",
"pallet-evm-coder-substrate",
"parity-scale-codec 3.1.2",
@@ -6083,6 +6087,7 @@
"frame-support",
"frame-system",
"log",
+ "pallet-common",
"pallet-evm",
"pallet-evm-coder-substrate",
"parity-scale-codec 3.1.2",
@@ -6090,6 +6095,7 @@
"sp-core",
"sp-runtime",
"sp-std",
+ "up-data-structs",
"up-sponsorship",
]
@@ -6814,13 +6820,18 @@
name = "pallet-unique"
version = "0.1.0"
dependencies = [
+ "ethereum",
+ "evm-coder",
"frame-benchmarking",
"frame-support",
"frame-system",
"pallet-common",
"pallet-evm",
+ "pallet-evm-coder-substrate",
+ "pallet-nonfungible",
"parity-scale-codec 3.1.2",
"scale-info",
+ "serde",
"sp-core",
"sp-io",
"sp-runtime",
@@ -12005,9 +12016,9 @@
[[package]]
name = "target-lexicon"
-version = "0.12.3"
+version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d7fa7e55043acb85fca6b3c01485a2eeb6b69c5d21002e273c79e465f43b7ac1"
+checksum = "c02424087780c9b71cc96799eaeddff35af2bc513278cda5c99fc1f5d026d3c1"
[[package]]
name = "tempfile"
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -1,33 +1,61 @@
.PHONY: _help
_help:
@echo "regenerate_solidity - generate stubs/interfaces for contracts defined in native (via evm-coder)"
- @echo "evm_stubs - recompile contract stubs"
+ @echo "evm_stubs - recompile contract stubs and ABI"
@echo "bench - run frame-benchmarking"
@echo " bench-evm-migration"
@echo " bench-unique"
+FUNGIBLE_EVM_STUBS=./pallets/fungible/src/stubs
+FUNGIBLE_EVM_ABI=./tests/src/eth/fungibleAbi.json
+
+NONFUNGIBLE_EVM_STUBS=./pallets/nonfungible/src/stubs
+NONFUNGIBLE_EVM_ABI=./tests/src/eth/nonFungibleAbi.json
+
+CONTRACT_HELPERS_STUBS=./pallets/evm-contract-helpers/src/stubs/
+CONTRACT_HELPERS_ABI=./tests/src/eth/util/contractHelpersAbi.json
+
+COLLECTION_HELPER_STUBS=./pallets/unique/src/eth/stubs/
+COLLECTION_HELPER_ABI=./tests/src/eth/collectionHelperAbi.json
+
+TESTS_API=./tests/src/eth/api/
+
.PHONY: regenerate_solidity
-regenerate_solidity:
- PACKAGE=pallet-fungible NAME=erc::gen_iface OUTPUT=./tests/src/eth/api/UniqueFungible.sol ./.maintain/scripts/generate_api.sh
- PACKAGE=pallet-nonfungible NAME=erc::gen_iface OUTPUT=./tests/src/eth/api/UniqueNFT.sol ./.maintain/scripts/generate_api.sh
- PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_iface OUTPUT=./tests/src/eth/api/ContractHelpers.sol ./.maintain/scripts/generate_api.sh
+regenerate_solidity: UniqueFungible.sol UniqueNFT.sol ContractHelpers.sol CollectionHelper.sol
+
+UniqueFungible.sol:
+ PACKAGE=pallet-fungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-fungible NAME=erc::gen_impl OUTPUT=$(FUNGIBLE_EVM_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+
+UniqueNFT.sol:
+ PACKAGE=pallet-nonfungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-nonfungible NAME=erc::gen_impl OUTPUT=$(NONFUNGIBLE_EVM_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+
+ContractHelpers.sol:
+ PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=$(CONTRACT_HELPERS_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+
+CollectionHelper.sol:
+ PACKAGE=pallet-unique NAME=eth::collection_helper_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-unique NAME=eth::collection_helper_impl OUTPUT=$(COLLECTION_HELPER_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+
+UniqueFungible: UniqueFungible.sol
+ INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw ./.maintain/scripts/compile_stub.sh
+ INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_ABI) ./.maintain/scripts/generate_abi.sh
- PACKAGE=pallet-fungible NAME=erc::gen_impl OUTPUT=./pallets/fungible/src/stubs/UniqueFungible.sol ./.maintain/scripts/generate_api.sh
- PACKAGE=pallet-nonfungible NAME=erc::gen_impl OUTPUT=./pallets/nonfungible/src/stubs/UniqueNFT.sol ./.maintain/scripts/generate_api.sh
- PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=./pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol ./.maintain/scripts/generate_api.sh
+UniqueNFT: UniqueNFT.sol
+ INPUT=$(NONFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.raw ./.maintain/scripts/compile_stub.sh
+ INPUT=$(NONFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(NONFUNGIBLE_EVM_ABI) ./.maintain/scripts/generate_abi.sh
-FUNGIBLE_EVM_STUBS=./pallets/fungible/src/stubs
-NONFUNGIBLE_EVM_STUBS=./pallets/nonfungible/src/stubs
-CONTRACT_HELPERS_STUBS=./pallets/evm-contract-helpers/src/stubs/
+ContractHelpers: ContractHelpers.sol
+ INPUT=$(CONTRACT_HELPERS_STUBS)/$< OUTPUT=$(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw ./.maintain/scripts/compile_stub.sh
+ INPUT=$(CONTRACT_HELPERS_STUBS)/$< OUTPUT=$(CONTRACT_HELPERS_ABI) ./.maintain/scripts/generate_abi.sh
-$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw: $(FUNGIBLE_EVM_STUBS)/UniqueFungible.sol
- INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh
-$(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.raw: $(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.sol
- INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh
-$(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw: $(CONTRACT_HELPERS_STUBS)/ContractHelpers.sol
- INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh
+CollectionHelper: CollectionHelper.sol
+ INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_STUBS)/CollectionHelper.raw ./.maintain/scripts/compile_stub.sh
+ INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_ABI) ./.maintain/scripts/generate_abi.sh
-evm_stubs: $(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw $(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.raw $(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw
+evm_stubs: UniqueFungible UniqueNFT ContractHelpers CollectionHelper
.PHONY: _bench
_bench:
crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -327,7 +327,7 @@
}
}
-#[impl_for_tuples(1, 5)]
+#[impl_for_tuples(1, 12)]
impl SolidityArguments for Tuple {
for_tuples!( where #( Tuple: SolidityArguments ),* );
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -16,16 +16,18 @@
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
+
serde = { version = "1.0.130", default-features = false }
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
-frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+lazy_static = { version = "1.4.0", default-features = false, features = ["spin_no_std"] }
[features]
default = ["std"]
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -14,12 +14,17 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use evm_coder::{solidity_interface, types::*, execution::Result};
+use evm_coder::{
+ solidity_interface,
+ types::*,
+ execution::{Result, Error},
+};
pub use pallet_evm::{PrecompileOutput, PrecompileResult, account::CrossAccountId};
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
use sp_std::vec::Vec;
-use up_data_structs::Property;
+use up_data_structs::{Property, SponsoringRateLimit};
+use alloc::format;
use crate::{Pallet, CollectionHandle, Config, CollectionProperties};
@@ -31,7 +36,7 @@
fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult>;
}
-#[solidity_interface(name = "CollectionProperties")]
+#[solidity_interface(name = "Collection")]
impl<T: Config> CollectionHandle<T> {
fn set_collection_property(&mut self, caller: caller, key: string, value: bytes) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -64,4 +69,93 @@
Ok(prop.to_vec())
}
+
+ fn eth_set_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {
+ check_is_owner(caller, self)?;
+
+ let sponsor = T::CrossAccountId::from_eth(sponsor);
+ self.set_sponsor(sponsor.as_sub().clone());
+ save(self);
+ Ok(())
+ }
+
+ fn eth_confirm_sponsorship(&mut self, caller: caller) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ if !self.confirm_sponsorship(caller.as_sub()) {
+ return Err(Error::Revert("Caller is not set as sponsor".into()));
+ }
+ save(self);
+ Ok(())
+ }
+
+ fn set_limit(&mut self, caller: caller, limit: string, value: string) -> Result<void> {
+ check_is_owner(caller, self)?;
+ let mut limits = self.limits.clone();
+
+ match limit.as_str() {
+ "accountTokenOwnershipLimit" => {
+ limits.account_token_ownership_limit = parse_int(value)?;
+ }
+ "sponsoredDataSize" => {
+ limits.sponsored_data_size = parse_int(value)?;
+ }
+ "sponsoredDataRateLimit" => {
+ limits.sponsored_data_rate_limit =
+ Some(SponsoringRateLimit::Blocks(parse_int(value)?.unwrap()));
+ }
+ "tokenLimit" => {
+ limits.token_limit = parse_int(value)?;
+ }
+ "sponsorTransferTimeout" => {
+ limits.sponsor_transfer_timeout = parse_int(value)?;
+ }
+ "sponsorApproveTimeout" => {
+ limits.sponsor_approve_timeout = parse_int(value)?;
+ }
+ "ownerCanTransfer" => {
+ limits.owner_can_transfer = parse_bool(value)?;
+ }
+ "ownerCanDestroy" => {
+ limits.owner_can_destroy = parse_bool(value)?;
+ }
+ "transfersEnabled" => {
+ limits.transfers_enabled = parse_bool(value)?;
+ }
+ _ => return Err(Error::Revert(format!("Unknown limit \"{}\"", limit))),
+ }
+ self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)
+ .map_err(dispatch_to_evm::<T>)?;
+ save(self);
+ Ok(())
+ }
+
+ fn contract_address(&self, _caller: caller) -> Result<address> {
+ Ok(crate::eth::collection_id_to_address(self.id))
+ }
+}
+
+fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ collection
+ .check_is_owner(&caller)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ Ok(())
+}
+
+fn save<T: Config>(collection: &CollectionHandle<T>) {
+ <crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());
+}
+
+fn parse_int(value: string) -> Result<Option<u32>> {
+ value
+ .parse::<u32>()
+ .map_err(|e| Error::Revert(format!("Int value \"{}\" parse error: {}", value, e)))
+ .map(|value| Some(value))
+}
+
+fn parse_bool(value: string) -> Result<Option<bool>> {
+ value
+ .parse::<bool>()
+ .map_err(|e| Error::Revert(format!("Bool value \"{}\" parse error: {}", value, e)))
+ .map(|value| Some(value))
}
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -17,6 +17,14 @@
use up_data_structs::CollectionId;
use sp_core::H160;
+lazy_static::lazy_static! {
+ pub static ref KEY_TOKEN_URI: up_data_structs::PropertyKey = {
+ let key: evm_coder::types::string = "tokenURI".into(); //TODO: make static
+ let key: up_data_structs::PropertyKey = key.into_bytes().try_into().expect("Can't create \"tokenURI\" key");
+ key
+ };
+}
+
// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
// TODO: Unhardcode prefix
const ETH_COLLECTION_PREFIX: [u8; 16] = [
@@ -37,3 +45,7 @@
out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));
H160(out)
}
+
+pub fn is_collection(address: &H160) -> bool {
+ address[0..16] == ETH_COLLECTION_PREFIX
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -114,6 +114,15 @@
recorder: SubstrateRecorder::new(gas_limit),
})
}
+
+ pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {
+ <CollectionById<T>>::get(id).map(|collection| Self {
+ id,
+ collection,
+ recorder,
+ })
+ }
+
pub fn new(id: CollectionId) -> Option<Self> {
Self::new_with_gas_limit(id, u64::MAX)
}
@@ -140,6 +149,19 @@
<CollectionById<T>>::insert(self.id, self.collection);
Ok(())
}
+
+ pub fn set_sponsor(&mut self, sponsor: T::AccountId) {
+ self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);
+ }
+
+ pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> bool {
+ if self.collection.sponsorship.pending_sponsor() != Some(sender) {
+ return false;
+ };
+
+ self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());
+ true
+ }
}
impl<T: Config> Deref for CollectionHandle<T> {
type Target = Collection<T::AccountId>;
pallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-contract-helpers/Cargo.toml
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -8,18 +8,26 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
-frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-evm-coder = { default-features = false, path = '../../crates/evm-coder' }
-pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
+log = { default-features = false, version = "0.4.14" }
+
+# Substrate
+frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.21' }
+frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.21' }
+sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.21' }
+sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.21' }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.21' }
+
+# Unique
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.21" }
-log = "0.4.14"
+# Locals
+evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+pallet-common = { default-features = false, path = '../../pallets/common' }
+pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
+up-data-structs = { default-features = false, path = '../../primitives/data-structs', features = ['serde1'] }
+
[dependencies.codec]
default-features = false
features = ['derive']
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -24,7 +24,7 @@
use pallet_evm::account::CrossAccountId;
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
-use pallet_common::{CollectionHandle, erc::CollectionPropertiesCall};
+use pallet_common::{CollectionHandle, erc::CollectionCall};
use crate::{
Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,
@@ -150,7 +150,7 @@
is(
ERC20,
ERC20UniqueExtensions,
- via("CollectionHandle<T>", common_mut, CollectionProperties)
+ via("CollectionHandle<T>", common_mut, Collection)
)
)]
impl<T: Config> FungibleHandle<T> {}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -33,7 +33,7 @@
use pallet_evm_coder_substrate::WithRecorder;
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
-use sp_std::collections::btree_map::BTreeMap;
+use sp_std::{collections::btree_map::BTreeMap};
pub use pallet::*;
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -127,8 +127,8 @@
}
}
-// Selector: 9b5e29c5
-contract CollectionProperties is Dummy, ERC165 {
+// Selector: f5652829
+contract Collection is Dummy, ERC165 {
// Selector: setCollectionProperty(string,bytes) 2f073f66
function setCollectionProperty(string memory key, bytes memory value)
public
@@ -159,6 +159,34 @@
dummy;
return hex"";
}
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() public {
+ require(false, stub_error);
+ dummy = 0;
+ }
+
+ // Selector: setLimit(string,string) bf4d2014
+ function setLimit(string memory limit, string memory value) public {
+ require(false, stub_error);
+ limit;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() public view returns (address) {
+ require(false, stub_error);
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
}
contract UniqueFungible is
@@ -166,5 +194,5 @@
ERC165,
ERC20,
ERC20UniqueExtensions,
- CollectionProperties
+ Collection
{}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -22,7 +22,7 @@
PropertyKeyPermission, PropertyValue,
};
use pallet_common::{
- CommonCollectionOperations, CommonWeightInfo, with_weight, weights::WeightInfo as _,
+ CommonCollectionOperations, CommonWeightInfo, with_weight, weights::WeightInfo as _
};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -21,13 +21,16 @@
};
use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use frame_support::BoundedVec;
-use up_data_structs::{TokenId, SchemaVersion, PropertyPermission, PropertyKeyPermission, Property};
+use up_data_structs::{
+ TokenId, SchemaVersion, PropertyPermission, PropertyKeyPermission, Property, CollectionId,
+ PropertyKey, CollectionPropertiesVec,
+};
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
use sp_std::vec::Vec;
use pallet_common::{
- erc::{CommonEvmHandler, PrecompileResult, CollectionPropertiesCall},
- CollectionHandle,
+ erc::{CommonEvmHandler, PrecompileResult, CollectionCall},
+ CollectionHandle, CollectionPropertyPermissions,
};
use pallet_evm::account::CrossAccountId;
use pallet_evm_coder_substrate::call;
@@ -158,12 +161,21 @@
/// Returns token's const_metadata
#[solidity(rename_selector = "tokenURI")]
fn token_uri(&self, token_id: uint256) -> Result<string> {
+ let key = pallet_common::eth::KEY_TOKEN_URI.clone();
+ if !has_token_permission::<T>(self.id, &key) {
+ return Err("No tokenURI permission".into());
+ }
+
self.consume_store_reads(1)?;
- let _token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
- Ok(string::from_utf8_lossy(
- todo!()
- )
- .into())
+ let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
+
+ let properties = <TokenProperties<T>>::try_get((self.id, token_id))
+ .map_err(|_| Error::Revert("Token properties not found".into()))?;
+ if let Some(property) = properties.get(&key) {
+ return Ok(string::from_utf8_lossy(property).into());
+ }
+
+ Err("Property tokenURI not found".into())
}
}
@@ -350,6 +362,12 @@
token_id: uint256,
token_uri: string,
) -> Result<bool> {
+ let key = pallet_common::eth::KEY_TOKEN_URI.clone();
+ let permission = get_token_permission::<T>(self.id, &key)?;
+ if !permission.collection_admin {
+ return Err("Operation is not allowed".into());
+ }
+
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
@@ -365,13 +383,22 @@
return Err("item id should be next".into());
}
- todo!("token uri");
+ let mut properties = CollectionPropertiesVec::default();
+ properties
+ .try_push(Property {
+ key,
+ value: token_uri
+ .into_bytes()
+ .try_into()
+ .map_err(|_| "token uri is too long")?,
+ })
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
<Pallet<T>>::create_item(
self,
&caller,
CreateItemData::<T> {
- properties: BoundedVec::default(),
+ properties,
owner: to,
},
&budget,
@@ -386,6 +413,30 @@
}
}
+fn get_token_permission<T: Config>(
+ collection_id: CollectionId,
+ key: &PropertyKey,
+) -> Result<PropertyPermission> {
+ let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)
+ .map_err(|_| Error::Revert("No permissions for collection".into()))?;
+ let a = token_property_permissions
+ .get(key)
+ .map(|p| p.clone())
+ .ok_or_else(|| Error::Revert("No permission".into()))?;
+ Ok(a)
+}
+
+fn has_token_permission<T: Config>(
+ collection_id: CollectionId,
+ key: &PropertyKey,
+) -> bool {
+ if let Ok(token_property_permissions) = CollectionPropertyPermissions::<T>::try_get(collection_id) {
+ return token_property_permissions.contains_key(key);
+ }
+
+ false
+}
+
#[solidity_interface(name = "ERC721UniqueExtensions")]
impl<T: Config> NonfungibleHandle<T> {
#[weight(<SelfWeightOf<T>>::transfer())]
@@ -491,7 +542,6 @@
}
expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
- todo!("token uri");
data.push(CreateItemData::<T> {
properties: BoundedVec::default(),
owner: to.clone(),
@@ -513,7 +563,7 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
- via("CollectionHandle<T>", common_mut, CollectionProperties),
+ via("CollectionHandle<T>", common_mut, Collection),
TokenProperties,
)
)]
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};22use up_data_structs::{23 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25 PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30 dispatch::CollectionDispatch, eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};36use sp_std::{vec::Vec, vec, collections::btree_set::BTreeSet};37use core::ops::Deref;38use sp_std::collections::btree_map::BTreeMap;39use codec::{Encode, Decode, MaxEncodedLen};40use scale_info::TypeInfo;4142pub use pallet::*;43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod common;46pub mod erc;47pub mod weights;4849pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;50pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5152#[struct_versioning::versioned(version = 2, upper)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]54pub struct ItemData<CrossAccountId> {55 #[version(..2)]56 pub const_data: BoundedVec<u8, CustomDataLimit>,5758 #[version(..2)]59 pub variable_data: BoundedVec<u8, CustomDataLimit>,6061 pub owner: CrossAccountId,62}6364#[frame_support::pallet]65pub mod pallet {66 use super::*;67 use frame_support::{68 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,69 };70 use frame_system::pallet_prelude::*;71 use up_data_structs::{CollectionId, TokenId};72 use super::weights::WeightInfo;7374 #[pallet::error]75 pub enum Error<T> {76 /// Not Nonfungible item data used to mint in Nonfungible collection.77 NotNonfungibleDataUsedToMintFungibleCollectionToken,78 /// Used amount > 1 with NFT79 NonfungibleItemsHaveNoAmount,80 }8182 #[pallet::config]83 pub trait Config:84 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config85 {86 type WeightInfo: WeightInfo;87 }8889 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);9091 #[pallet::pallet]92 #[pallet::storage_version(STORAGE_VERSION)]93 #[pallet::generate_store(pub(super) trait Store)]94 pub struct Pallet<T>(_);9596 #[pallet::storage]97 pub type TokensMinted<T: Config> =98 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;99 #[pallet::storage]100 pub type TokensBurnt<T: Config> =101 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;102103 #[pallet::storage]104 pub type TokenData<T: Config> = StorageNMap<105 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),106 Value = ItemData<T::CrossAccountId>,107 QueryKind = OptionQuery,108 >;109110 #[pallet::storage]111 #[pallet::getter(fn token_properties)]112 pub type TokenProperties<T: Config> = StorageNMap<113 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),114 Value = Properties,115 QueryKind = ValueQuery,116 OnEmpty = up_data_structs::TokenProperties,117 >;118119 /// Used to enumerate tokens owned by account120 #[pallet::storage]121 pub type Owned<T: Config> = StorageNMap<122 Key = (123 Key<Twox64Concat, CollectionId>,124 Key<Blake2_128Concat, T::CrossAccountId>,125 Key<Twox64Concat, TokenId>,126 ),127 Value = bool,128 QueryKind = ValueQuery,129 >;130131 #[pallet::storage]132 pub type AccountBalance<T: Config> = StorageNMap<133 Key = (134 Key<Twox64Concat, CollectionId>,135 Key<Blake2_128Concat, T::CrossAccountId>,136 ),137 Value = u32,138 QueryKind = ValueQuery,139 >;140141 #[pallet::storage]142 pub type Allowance<T: Config> = StorageNMap<143 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),144 Value = T::CrossAccountId,145 QueryKind = OptionQuery,146 >;147148 #[pallet::hooks]149 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {150 fn on_runtime_upgrade() -> Weight {151 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {152 let mut had_consts = BTreeSet::new();153 <TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(|(collection, token), v| {154 let mut props = vec![];155 if !v.const_data.is_empty() {156 props.push(Property {157 key: b"_old_constData".to_vec().try_into().unwrap(),158 value: v.const_data.clone().into_inner().try_into().expect("const too long"),159 });160 had_consts.insert(collection);161 }162 if !v.variable_data.is_empty() {163 props.push(Property {164 key: b"_old_variableData".to_vec().try_into().unwrap(),165 value: v.variable_data.clone().into_inner().try_into().expect("variable too long"),166 })167 }168 if !props.is_empty() {169 Self::set_scoped_token_properties(170 collection,171 token,172 PropertyScope::None,173 props.into_iter(),174 ).expect("existing token data exceeds property storage");175 }176 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))177 });178 for collection in had_consts {179 <PalletCommon<T>>::set_property_permission_unchecked(180 collection,181 PropertyKeyPermission {182 key: b"_old_constData".to_vec().try_into().unwrap(),183 permission: PropertyPermission {184 mutable: false,185 collection_admin: true,186 token_owner: false,187 },188 }189 ).expect("failed to configure permission");190 }191 }192193 0194 }195 }196}197198pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);199impl<T: Config> NonfungibleHandle<T> {200 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {201 Self(inner)202 }203 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {204 self.0205 }206 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {207 &mut self.0208 }209}210impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {211 fn recorder(&self) -> &SubstrateRecorder<T> {212 self.0.recorder()213 }214 fn into_recorder(self) -> SubstrateRecorder<T> {215 self.0.into_recorder()216 }217}218impl<T: Config> Deref for NonfungibleHandle<T> {219 type Target = pallet_common::CollectionHandle<T>;220221 fn deref(&self) -> &Self::Target {222 &self.0223 }224}225226impl<T: Config> Pallet<T> {227 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {228 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)229 }230 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {231 <TokenData<T>>::contains_key((collection.id, token))232 }233234 pub fn set_scoped_token_property(235 collection_id: CollectionId,236 token_id: TokenId,237 scope: PropertyScope,238 property: Property,239 ) -> DispatchResult {240 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {241 properties.try_scoped_set(scope, property.key, property.value)242 })243 .map_err(<CommonError<T>>::from)?;244245 Ok(())246 }247248 pub fn set_scoped_token_properties(249 collection_id: CollectionId,250 token_id: TokenId,251 scope: PropertyScope,252 properties: impl Iterator<Item=Property>,253 ) -> DispatchResult {254 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {255 stored_properties.try_scoped_set_from_iter(scope, properties)256 })257 .map_err(<CommonError<T>>::from)?;258259 Ok(())260 }261262 pub fn current_token_id(collection_id: CollectionId) -> TokenId {263 TokenId(<TokensMinted<T>>::get(collection_id))264 }265}266267// unchecked calls skips any permission checks268impl<T: Config> Pallet<T> {269 pub fn init_collection(270 owner: T::AccountId,271 data: CreateCollectionData<T::AccountId>,272 ) -> Result<CollectionId, DispatchError> {273 <PalletCommon<T>>::init_collection(owner, data)274 }275 pub fn destroy_collection(276 collection: NonfungibleHandle<T>,277 sender: &T::CrossAccountId,278 ) -> DispatchResult {279 let id = collection.id;280281 // =========282283 PalletCommon::destroy_collection(collection.0, sender)?;284285 <TokenData<T>>::remove_prefix((id,), None);286 <Owned<T>>::remove_prefix((id,), None);287 <TokensMinted<T>>::remove(id);288 <TokensBurnt<T>>::remove(id);289 <Allowance<T>>::remove_prefix((id,), None);290 <AccountBalance<T>>::remove_prefix((id,), None);291 Ok(())292 }293294 pub fn burn(295 collection: &NonfungibleHandle<T>,296 sender: &T::CrossAccountId,297 token: TokenId,298 ) -> DispatchResult {299 let token_data =300 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;301 ensure!(302 &token_data.owner == sender303 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),304 <CommonError<T>>::NoPermission305 );306307 if collection.permissions.access() == AccessMode::AllowList {308 collection.check_allowlist(sender)?;309 }310311 let burnt = <TokensBurnt<T>>::get(collection.id)312 .checked_add(1)313 .ok_or(ArithmeticError::Overflow)?;314315 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))316 .checked_sub(1)317 .ok_or(ArithmeticError::Overflow)?;318319 if balance == 0 {320 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));321 } else {322 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);323 }324 // =========325326 <Owned<T>>::remove((collection.id, &token_data.owner, token));327 <TokensBurnt<T>>::insert(collection.id, burnt);328 <TokenData<T>>::remove((collection.id, token));329 <TokenProperties<T>>::remove((collection.id, token));330 let old_spender = <Allowance<T>>::take((collection.id, token));331332 if let Some(old_spender) = old_spender {333 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(334 collection.id,335 token,336 sender.clone(),337 old_spender,338 0,339 ));340 }341342 <PalletEvm<T>>::deposit_log(343 ERC721Events::Transfer {344 from: *token_data.owner.as_eth(),345 to: H160::default(),346 token_id: token.into(),347 }348 .to_log(collection_id_to_address(collection.id)),349 );350 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(351 collection.id,352 token,353 token_data.owner,354 1,355 ));356 Ok(())357 }358359 pub fn set_token_property(360 collection: &NonfungibleHandle<T>,361 sender: &T::CrossAccountId,362 token_id: TokenId,363 property: Property,364 ) -> DispatchResult {365 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;366367 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {368 let property = property.clone();369 properties.try_set(property.key, property.value)370 })371 .map_err(<CommonError<T>>::from)?;372373 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(374 collection.id,375 token_id,376 property.key,377 ));378379 Ok(())380 }381382 #[transactional]383 pub fn set_token_properties(384 collection: &NonfungibleHandle<T>,385 sender: &T::CrossAccountId,386 token_id: TokenId,387 properties: Vec<Property>,388 ) -> DispatchResult {389 for property in properties {390 Self::set_token_property(collection, sender, token_id, property)?;391 }392393 Ok(())394 }395396 pub fn delete_token_property(397 collection: &NonfungibleHandle<T>,398 sender: &T::CrossAccountId,399 token_id: TokenId,400 property_key: PropertyKey,401 ) -> DispatchResult {402 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;403404 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {405 properties.remove(&property_key)406 })407 .map_err(<CommonError<T>>::from)?;408409 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(410 collection.id,411 token_id,412 property_key,413 ));414415 Ok(())416 }417418 fn check_token_change_permission(419 collection: &NonfungibleHandle<T>,420 sender: &T::CrossAccountId,421 token_id: TokenId,422 property_key: &PropertyKey,423 ) -> DispatchResult {424 let permission = <PalletCommon<T>>::property_permissions(collection.id)425 .get(property_key)426 .cloned()427 .unwrap_or_else(PropertyPermission::none);428429 let token_data = <TokenData<T>>::get((collection.id, token_id))430 .ok_or(<CommonError<T>>::TokenNotFound)?;431432 let check_token_owner = || -> DispatchResult {433 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);434 Ok(())435 };436437 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))438 .get(property_key)439 .is_some();440441 match permission {442 PropertyPermission { mutable: false, .. } if is_property_exists => {443 Err(<CommonError<T>>::NoPermission.into())444 }445446 PropertyPermission {447 collection_admin,448 token_owner,449 ..450 } => {451 let mut check_result = Err(<CommonError<T>>::NoPermission.into());452453 if collection_admin {454 check_result = collection.check_is_owner_or_admin(sender);455 }456457 if token_owner {458 check_result.or_else(|_| check_token_owner())459 } else {460 check_result461 }462 }463 }464 }465466 #[transactional]467 pub fn delete_token_properties(468 collection: &NonfungibleHandle<T>,469 sender: &T::CrossAccountId,470 token_id: TokenId,471 property_keys: Vec<PropertyKey>,472 ) -> DispatchResult {473 for key in property_keys {474 Self::delete_token_property(collection, sender, token_id, key)?;475 }476477 Ok(())478 }479480 pub fn set_collection_properties(481 collection: &NonfungibleHandle<T>,482 sender: &T::CrossAccountId,483 properties: Vec<Property>,484 ) -> DispatchResult {485 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)486 }487488 pub fn delete_collection_properties(489 collection: &CollectionHandle<T>,490 sender: &T::CrossAccountId,491 property_keys: Vec<PropertyKey>,492 ) -> DispatchResult {493 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)494 }495496 pub fn set_property_permissions(497 collection: &CollectionHandle<T>,498 sender: &T::CrossAccountId,499 property_permissions: Vec<PropertyKeyPermission>,500 ) -> DispatchResult {501 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)502 }503504 pub fn set_property_permission(505 collection: &CollectionHandle<T>,506 sender: &T::CrossAccountId,507 permission: PropertyKeyPermission,508 ) -> DispatchResult {509 <PalletCommon<T>>::set_property_permission(collection, sender, permission)510 }511512 pub fn transfer(513 collection: &NonfungibleHandle<T>,514 from: &T::CrossAccountId,515 to: &T::CrossAccountId,516 token: TokenId,517 nesting_budget: &dyn Budget,518 ) -> DispatchResult {519 ensure!(520 collection.limits.transfers_enabled(),521 <CommonError<T>>::TransferNotAllowed522 );523524 let token_data =525 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;526 // TODO: require sender to be token, owner, require admins to go through transfer_from527 ensure!(528 &token_data.owner == from529 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),530 <CommonError<T>>::NoPermission531 );532533 if collection.permissions.access() == AccessMode::AllowList {534 collection.check_allowlist(from)?;535 collection.check_allowlist(to)?;536 }537 <PalletCommon<T>>::ensure_correct_receiver(to)?;538539 let balance_from = <AccountBalance<T>>::get((collection.id, from))540 .checked_sub(1)541 .ok_or(<CommonError<T>>::TokenValueTooLow)?;542 let balance_to = if from != to {543 let balance_to = <AccountBalance<T>>::get((collection.id, to))544 .checked_add(1)545 .ok_or(ArithmeticError::Overflow)?;546547 ensure!(548 balance_to < collection.limits.account_token_ownership_limit(),549 <CommonError<T>>::AccountTokenLimitExceeded,550 );551552 Some(balance_to)553 } else {554 None555 };556557 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {558 let handle = <CollectionHandle<T>>::try_get(target.0)?;559 let dispatch = T::CollectionDispatch::dispatch(handle);560 let dispatch = dispatch.as_dyn();561562 dispatch.check_nesting(563 from.clone(),564 (collection.id, token),565 target.1,566 nesting_budget,567 )?;568 }569570 // =========571572 <TokenData<T>>::insert(573 (collection.id, token),574 ItemData {575 owner: to.clone(),576 ..token_data577 },578 );579580 if let Some(balance_to) = balance_to {581 // from != to582 if balance_from == 0 {583 <AccountBalance<T>>::remove((collection.id, from));584 } else {585 <AccountBalance<T>>::insert((collection.id, from), balance_from);586 }587 <AccountBalance<T>>::insert((collection.id, to), balance_to);588 <Owned<T>>::remove((collection.id, from, token));589 <Owned<T>>::insert((collection.id, to, token), true);590 }591 Self::set_allowance_unchecked(collection, from, token, None, true);592593 <PalletEvm<T>>::deposit_log(594 ERC721Events::Transfer {595 from: *from.as_eth(),596 to: *to.as_eth(),597 token_id: token.into(),598 }599 .to_log(collection_id_to_address(collection.id)),600 );601 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(602 collection.id,603 token,604 from.clone(),605 to.clone(),606 1,607 ));608 Ok(())609 }610611 pub fn create_multiple_items(612 collection: &NonfungibleHandle<T>,613 sender: &T::CrossAccountId,614 data: Vec<CreateItemData<T>>,615 nesting_budget: &dyn Budget,616 ) -> DispatchResult {617 if !collection.is_owner_or_admin(sender) {618 ensure!(619 collection.permissions.mint_mode(),620 <CommonError<T>>::PublicMintingNotAllowed621 );622 collection.check_allowlist(sender)?;623624 for item in data.iter() {625 collection.check_allowlist(&item.owner)?;626 }627 }628629 for data in data.iter() {630 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;631 }632633 let first_token = <TokensMinted<T>>::get(collection.id);634 let tokens_minted = first_token635 .checked_add(data.len() as u32)636 .ok_or(ArithmeticError::Overflow)?;637 ensure!(638 tokens_minted <= collection.limits.token_limit(),639 <CommonError<T>>::CollectionTokenLimitExceeded640 );641642 let mut balances = BTreeMap::new();643 for data in &data {644 let balance = balances645 .entry(&data.owner)646 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));647 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;648649 ensure!(650 *balance <= collection.limits.account_token_ownership_limit(),651 <CommonError<T>>::AccountTokenLimitExceeded,652 );653 }654655 for (i, data) in data.iter().enumerate() {656 let token = TokenId(first_token + i as u32 + 1);657 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {658 let handle = <CollectionHandle<T>>::try_get(target.0)?;659 let dispatch = T::CollectionDispatch::dispatch(handle);660 let dispatch = dispatch.as_dyn();661 dispatch.check_nesting(662 sender.clone(),663 (collection.id, token),664 target.1,665 nesting_budget,666 )?;667 }668 }669670 // =========671672 with_transaction(|| {673 for (i, data) in data.iter().enumerate() {674 let token = first_token + i as u32 + 1;675676 <TokenData<T>>::insert(677 (collection.id, token),678 ItemData {679 // const_data: data.const_data.clone(),680 owner: data.owner.clone(),681 },682 );683684 if let Err(e) = Self::set_token_properties(685 collection,686 sender,687 TokenId(token),688 data.properties.clone().into_inner(),689 ) {690 return TransactionOutcome::Rollback(Err(e));691 }692 }693 TransactionOutcome::Commit(Ok(()))694 })?;695696 <TokensMinted<T>>::insert(collection.id, tokens_minted);697 for (account, balance) in balances {698 <AccountBalance<T>>::insert((collection.id, account), balance);699 }700 for (i, data) in data.into_iter().enumerate() {701 let token = first_token + i as u32 + 1;702 <Owned<T>>::insert((collection.id, &data.owner, token), true);703704 <PalletEvm<T>>::deposit_log(705 ERC721Events::Transfer {706 from: H160::default(),707 to: *data.owner.as_eth(),708 token_id: token.into(),709 }710 .to_log(collection_id_to_address(collection.id)),711 );712 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(713 collection.id,714 TokenId(token),715 data.owner.clone(),716 1,717 ));718 }719 Ok(())720 }721722 pub fn set_allowance_unchecked(723 collection: &NonfungibleHandle<T>,724 sender: &T::CrossAccountId,725 token: TokenId,726 spender: Option<&T::CrossAccountId>,727 assume_implicit_eth: bool,728 ) {729 if let Some(spender) = spender {730 let old_spender = <Allowance<T>>::get((collection.id, token));731 <Allowance<T>>::insert((collection.id, token), spender);732 // In ERC721 there is only one possible approved user of token, so we set733 // approved user to spender734 <PalletEvm<T>>::deposit_log(735 ERC721Events::Approval {736 owner: *sender.as_eth(),737 approved: *spender.as_eth(),738 token_id: token.into(),739 }740 .to_log(collection_id_to_address(collection.id)),741 );742 // In Unique chain, any token can have any amount of approved users, so we need to743 // set allowance of old owner to 0, and allowance of new owner to 1744 if old_spender.as_ref() != Some(spender) {745 if let Some(old_owner) = old_spender {746 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(747 collection.id,748 token,749 sender.clone(),750 old_owner,751 0,752 ));753 }754 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(755 collection.id,756 token,757 sender.clone(),758 spender.clone(),759 1,760 ));761 }762 } else {763 let old_spender = <Allowance<T>>::take((collection.id, token));764 if !assume_implicit_eth {765 // In ERC721 there is only one possible approved user of token, so we set766 // approved user to zero address767 <PalletEvm<T>>::deposit_log(768 ERC721Events::Approval {769 owner: *sender.as_eth(),770 approved: H160::default(),771 token_id: token.into(),772 }773 .to_log(collection_id_to_address(collection.id)),774 );775 }776 // In Unique chain, any token can have any amount of approved users, so we need to777 // set allowance of old owner to 0778 if let Some(old_spender) = old_spender {779 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(780 collection.id,781 token,782 sender.clone(),783 old_spender,784 0,785 ));786 }787 }788 }789790 pub fn set_allowance(791 collection: &NonfungibleHandle<T>,792 sender: &T::CrossAccountId,793 token: TokenId,794 spender: Option<&T::CrossAccountId>,795 ) -> DispatchResult {796 if collection.permissions.access() == AccessMode::AllowList {797 collection.check_allowlist(sender)?;798 if let Some(spender) = spender {799 collection.check_allowlist(spender)?;800 }801 }802803 if let Some(spender) = spender {804 <PalletCommon<T>>::ensure_correct_receiver(spender)?;805 }806 let token_data =807 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;808 if &token_data.owner != sender {809 ensure!(810 collection.ignores_owned_amount(sender),811 <CommonError<T>>::CantApproveMoreThanOwned812 );813 }814815 // =========816817 Self::set_allowance_unchecked(collection, sender, token, spender, false);818 Ok(())819 }820821 fn check_allowed(822 collection: &NonfungibleHandle<T>,823 spender: &T::CrossAccountId,824 from: &T::CrossAccountId,825 token: TokenId,826 nesting_budget: &dyn Budget,827 ) -> DispatchResult {828 if spender.conv_eq(from) {829 return Ok(());830 }831 if collection.permissions.access() == AccessMode::AllowList {832 // `from`, `to` checked in [`transfer`]833 collection.check_allowlist(spender)?;834 }835 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {836 // TODO: should collection owner be allowed to perform this transfer?837 ensure!(838 <PalletStructure<T>>::check_indirectly_owned(839 spender.clone(),840 source.0,841 source.1,842 None,843 nesting_budget844 )?,845 <CommonError<T>>::ApprovedValueTooLow,846 );847 return Ok(());848 }849 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {850 return Ok(());851 }852 ensure!(853 collection.ignores_allowance(spender),854 <CommonError<T>>::ApprovedValueTooLow855 );856 Ok(())857 }858859 pub fn transfer_from(860 collection: &NonfungibleHandle<T>,861 spender: &T::CrossAccountId,862 from: &T::CrossAccountId,863 to: &T::CrossAccountId,864 token: TokenId,865 nesting_budget: &dyn Budget,866 ) -> DispatchResult {867 Self::check_allowed(collection, spender, from, token, nesting_budget)?;868869 // =========870871 // Allowance is reset in [`transfer`]872 Self::transfer(collection, from, to, token, nesting_budget)873 }874875 pub fn burn_from(876 collection: &NonfungibleHandle<T>,877 spender: &T::CrossAccountId,878 from: &T::CrossAccountId,879 token: TokenId,880 nesting_budget: &dyn Budget,881 ) -> DispatchResult {882 Self::check_allowed(collection, spender, from, token, nesting_budget)?;883884 // =========885886 Self::burn(collection, from, token)887 }888889 pub fn check_nesting(890 handle: &NonfungibleHandle<T>,891 sender: T::CrossAccountId,892 from: (CollectionId, TokenId),893 under: TokenId,894 nesting_budget: &dyn Budget,895 ) -> DispatchResult {896 fn ensure_sender_allowed<T: Config>(897 collection: CollectionId,898 token: TokenId,899 for_nest: (CollectionId, TokenId),900 sender: T::CrossAccountId,901 budget: &dyn Budget,902 ) -> DispatchResult {903 ensure!(904 <PalletStructure<T>>::check_indirectly_owned(905 sender,906 collection,907 token,908 Some(for_nest),909 budget910 )?,911 <CommonError<T>>::OnlyOwnerAllowedToNest,912 );913 Ok(())914 }915 match handle.permissions.nesting() {916 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),917 NestingRule::Owner => {918 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?919 }920 NestingRule::OwnerRestricted(whitelist) => {921 ensure!(922 whitelist.contains(&from.0),923 <CommonError<T>>::SourceCollectionIsNotAllowedToNest924 );925 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?926 }927 }928 Ok(())929 }930931 /// Delegated to `create_multiple_items`932 pub fn create_item(933 collection: &NonfungibleHandle<T>,934 sender: &T::CrossAccountId,935 data: CreateItemData<T>,936 nesting_budget: &dyn Budget,937 ) -> DispatchResult {938 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)939 }940}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};22use up_data_structs::{23 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25 PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30 dispatch::CollectionDispatch, eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};36use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap, collections::btree_set::BTreeSet};37use core::ops::Deref;38use codec::{Encode, Decode, MaxEncodedLen};39use scale_info::TypeInfo;4041pub use pallet::*;42#[cfg(feature = "runtime-benchmarks")]43pub mod benchmarking;44pub mod common;45pub mod erc;46pub mod weights;4748pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;49pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5051#[struct_versioning::versioned(version = 2, upper)]52#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]53pub struct ItemData<CrossAccountId> {54 #[version(..2)]55 pub const_data: BoundedVec<u8, CustomDataLimit>,5657 #[version(..2)]58 pub variable_data: BoundedVec<u8, CustomDataLimit>,5960 pub owner: CrossAccountId,61}6263#[frame_support::pallet]64pub mod pallet {65 use super::*;66 use frame_support::{67 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,68 };69 use frame_system::pallet_prelude::*;70 use up_data_structs::{CollectionId, TokenId};71 use super::weights::WeightInfo;7273 #[pallet::error]74 pub enum Error<T> {75 /// Not Nonfungible item data used to mint in Nonfungible collection.76 NotNonfungibleDataUsedToMintFungibleCollectionToken,77 /// Used amount > 1 with NFT78 NonfungibleItemsHaveNoAmount,79 }8081 #[pallet::config]82 pub trait Config:83 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config84 {85 type WeightInfo: WeightInfo;86 }8788 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8990 #[pallet::pallet]91 #[pallet::storage_version(STORAGE_VERSION)]92 #[pallet::generate_store(pub(super) trait Store)]93 pub struct Pallet<T>(_);9495 #[pallet::storage]96 pub type TokensMinted<T: Config> =97 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;98 #[pallet::storage]99 pub type TokensBurnt<T: Config> =100 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;101102 #[pallet::storage]103 pub type TokenData<T: Config> = StorageNMap<104 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),105 Value = ItemData<T::CrossAccountId>,106 QueryKind = OptionQuery,107 >;108109 #[pallet::storage]110 #[pallet::getter(fn token_properties)]111 pub type TokenProperties<T: Config> = StorageNMap<112 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),113 Value = Properties,114 QueryKind = ValueQuery,115 OnEmpty = up_data_structs::TokenProperties,116 >;117118 /// Used to enumerate tokens owned by account119 #[pallet::storage]120 pub type Owned<T: Config> = StorageNMap<121 Key = (122 Key<Twox64Concat, CollectionId>,123 Key<Blake2_128Concat, T::CrossAccountId>,124 Key<Twox64Concat, TokenId>,125 ),126 Value = bool,127 QueryKind = ValueQuery,128 >;129130 #[pallet::storage]131 pub type AccountBalance<T: Config> = StorageNMap<132 Key = (133 Key<Twox64Concat, CollectionId>,134 Key<Blake2_128Concat, T::CrossAccountId>,135 ),136 Value = u32,137 QueryKind = ValueQuery,138 >;139140 #[pallet::storage]141 pub type Allowance<T: Config> = StorageNMap<142 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),143 Value = T::CrossAccountId,144 QueryKind = OptionQuery,145 >;146147 #[pallet::hooks]148 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {149 fn on_runtime_upgrade() -> Weight {150 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {151 let mut had_consts = BTreeSet::new();152 <TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(|(collection, token), v| {153 let mut props = vec![];154 if !v.const_data.is_empty() {155 props.push(Property {156 key: b"_old_constData".to_vec().try_into().unwrap(),157 value: v.const_data.clone().into_inner().try_into().expect("const too long"),158 });159 had_consts.insert(collection);160 }161 if !v.variable_data.is_empty() {162 props.push(Property {163 key: b"_old_variableData".to_vec().try_into().unwrap(),164 value: v.variable_data.clone().into_inner().try_into().expect("variable too long"),165 })166 }167 if !props.is_empty() {168 Self::set_scoped_token_properties(169 collection,170 token,171 PropertyScope::None,172 props.into_iter(),173 ).expect("existing token data exceeds property storage");174 }175 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))176 });177 for collection in had_consts {178 <PalletCommon<T>>::set_property_permission_unchecked(179 collection,180 PropertyKeyPermission {181 key: b"_old_constData".to_vec().try_into().unwrap(),182 permission: PropertyPermission {183 mutable: false,184 collection_admin: true,185 token_owner: false,186 },187 }188 ).expect("failed to configure permission");189 }190 }191192 0193 }194 }195}196197pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);198impl<T: Config> NonfungibleHandle<T> {199 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {200 Self(inner)201 }202 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {203 self.0204 }205 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {206 &mut self.0207 }208}209impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {210 fn recorder(&self) -> &SubstrateRecorder<T> {211 self.0.recorder()212 }213 fn into_recorder(self) -> SubstrateRecorder<T> {214 self.0.into_recorder()215 }216}217impl<T: Config> Deref for NonfungibleHandle<T> {218 type Target = pallet_common::CollectionHandle<T>;219220 fn deref(&self) -> &Self::Target {221 &self.0222 }223}224225impl<T: Config> Pallet<T> {226 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {227 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)228 }229 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {230 <TokenData<T>>::contains_key((collection.id, token))231 }232233 pub fn set_scoped_token_property(234 collection_id: CollectionId,235 token_id: TokenId,236 scope: PropertyScope,237 property: Property,238 ) -> DispatchResult {239 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {240 properties.try_scoped_set(scope, property.key, property.value)241 })242 .map_err(<CommonError<T>>::from)?;243244 Ok(())245 }246247 pub fn set_scoped_token_properties(248 collection_id: CollectionId,249 token_id: TokenId,250 scope: PropertyScope,251 properties: impl Iterator<Item=Property>,252 ) -> DispatchResult {253 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {254 stored_properties.try_scoped_set_from_iter(scope, properties)255 })256 .map_err(<CommonError<T>>::from)?;257258 Ok(())259 }260261 pub fn current_token_id(collection_id: CollectionId) -> TokenId {262 TokenId(<TokensMinted<T>>::get(collection_id))263 }264}265266// unchecked calls skips any permission checks267impl<T: Config> Pallet<T> {268 pub fn init_collection(269 owner: T::AccountId,270 data: CreateCollectionData<T::AccountId>,271 ) -> Result<CollectionId, DispatchError> {272 <PalletCommon<T>>::init_collection(owner, data)273 }274 pub fn destroy_collection(275 collection: NonfungibleHandle<T>,276 sender: &T::CrossAccountId,277 ) -> DispatchResult {278 let id = collection.id;279280 // =========281282 PalletCommon::destroy_collection(collection.0, sender)?;283284 <TokenData<T>>::remove_prefix((id,), None);285 <Owned<T>>::remove_prefix((id,), None);286 <TokensMinted<T>>::remove(id);287 <TokensBurnt<T>>::remove(id);288 <Allowance<T>>::remove_prefix((id,), None);289 <AccountBalance<T>>::remove_prefix((id,), None);290 Ok(())291 }292293 pub fn burn(294 collection: &NonfungibleHandle<T>,295 sender: &T::CrossAccountId,296 token: TokenId,297 ) -> DispatchResult {298 let token_data =299 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;300 ensure!(301 &token_data.owner == sender302 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),303 <CommonError<T>>::NoPermission304 );305306 if collection.permissions.access() == AccessMode::AllowList {307 collection.check_allowlist(sender)?;308 }309310 let burnt = <TokensBurnt<T>>::get(collection.id)311 .checked_add(1)312 .ok_or(ArithmeticError::Overflow)?;313314 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))315 .checked_sub(1)316 .ok_or(ArithmeticError::Overflow)?;317318 if balance == 0 {319 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));320 } else {321 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);322 }323 // =========324325 <Owned<T>>::remove((collection.id, &token_data.owner, token));326 <TokensBurnt<T>>::insert(collection.id, burnt);327 <TokenData<T>>::remove((collection.id, token));328 <TokenProperties<T>>::remove((collection.id, token));329 let old_spender = <Allowance<T>>::take((collection.id, token));330331 if let Some(old_spender) = old_spender {332 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(333 collection.id,334 token,335 sender.clone(),336 old_spender,337 0,338 ));339 }340341 <PalletEvm<T>>::deposit_log(342 ERC721Events::Transfer {343 from: *token_data.owner.as_eth(),344 to: H160::default(),345 token_id: token.into(),346 }347 .to_log(collection_id_to_address(collection.id)),348 );349 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(350 collection.id,351 token,352 token_data.owner,353 1,354 ));355 Ok(())356 }357358 pub fn set_token_property(359 collection: &NonfungibleHandle<T>,360 sender: &T::CrossAccountId,361 token_id: TokenId,362 property: Property,363 ) -> DispatchResult {364 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;365366 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {367 let property = property.clone();368 properties.try_set(property.key, property.value)369 })370 .map_err(<CommonError<T>>::from)?;371372 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(373 collection.id,374 token_id,375 property.key,376 ));377378 Ok(())379 }380381 #[transactional]382 pub fn set_token_properties(383 collection: &NonfungibleHandle<T>,384 sender: &T::CrossAccountId,385 token_id: TokenId,386 properties: Vec<Property>,387 ) -> DispatchResult {388 for property in properties {389 Self::set_token_property(collection, sender, token_id, property)?;390 }391392 Ok(())393 }394395 pub fn delete_token_property(396 collection: &NonfungibleHandle<T>,397 sender: &T::CrossAccountId,398 token_id: TokenId,399 property_key: PropertyKey,400 ) -> DispatchResult {401 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;402403 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {404 properties.remove(&property_key)405 })406 .map_err(<CommonError<T>>::from)?;407408 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(409 collection.id,410 token_id,411 property_key,412 ));413414 Ok(())415 }416417 fn check_token_change_permission(418 collection: &NonfungibleHandle<T>,419 sender: &T::CrossAccountId,420 token_id: TokenId,421 property_key: &PropertyKey,422 ) -> DispatchResult {423 let permission = <PalletCommon<T>>::property_permissions(collection.id)424 .get(property_key)425 .cloned()426 .unwrap_or_else(PropertyPermission::none);427428 let token_data = <TokenData<T>>::get((collection.id, token_id))429 .ok_or(<CommonError<T>>::TokenNotFound)?;430431 let check_token_owner = || -> DispatchResult {432 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);433 Ok(())434 };435436 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))437 .get(property_key)438 .is_some();439440 match permission {441 PropertyPermission { mutable: false, .. } if is_property_exists => {442 Err(<CommonError<T>>::NoPermission.into())443 }444445 PropertyPermission {446 collection_admin,447 token_owner,448 ..449 } => {450 let mut check_result = Err(<CommonError<T>>::NoPermission.into());451452 if collection_admin {453 check_result = collection.check_is_owner_or_admin(sender);454 }455456 if token_owner {457 check_result.or_else(|_| check_token_owner())458 } else {459 check_result460 }461 }462 }463 }464465 #[transactional]466 pub fn delete_token_properties(467 collection: &NonfungibleHandle<T>,468 sender: &T::CrossAccountId,469 token_id: TokenId,470 property_keys: Vec<PropertyKey>,471 ) -> DispatchResult {472 for key in property_keys {473 Self::delete_token_property(collection, sender, token_id, key)?;474 }475476 Ok(())477 }478479 pub fn set_collection_properties(480 collection: &NonfungibleHandle<T>,481 sender: &T::CrossAccountId,482 properties: Vec<Property>,483 ) -> DispatchResult {484 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)485 }486487 pub fn delete_collection_properties(488 collection: &CollectionHandle<T>,489 sender: &T::CrossAccountId,490 property_keys: Vec<PropertyKey>,491 ) -> DispatchResult {492 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)493 }494495 pub fn set_property_permissions(496 collection: &CollectionHandle<T>,497 sender: &T::CrossAccountId,498 property_permissions: Vec<PropertyKeyPermission>,499 ) -> DispatchResult {500 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)501 }502503 pub fn set_property_permission(504 collection: &CollectionHandle<T>,505 sender: &T::CrossAccountId,506 permission: PropertyKeyPermission,507 ) -> DispatchResult {508 <PalletCommon<T>>::set_property_permission(collection, sender, permission)509 }510511 pub fn transfer(512 collection: &NonfungibleHandle<T>,513 from: &T::CrossAccountId,514 to: &T::CrossAccountId,515 token: TokenId,516 nesting_budget: &dyn Budget,517 ) -> DispatchResult {518 ensure!(519 collection.limits.transfers_enabled(),520 <CommonError<T>>::TransferNotAllowed521 );522523 let token_data =524 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;525 // TODO: require sender to be token, owner, require admins to go through transfer_from526 ensure!(527 &token_data.owner == from528 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),529 <CommonError<T>>::NoPermission530 );531532 if collection.permissions.access() == AccessMode::AllowList {533 collection.check_allowlist(from)?;534 collection.check_allowlist(to)?;535 }536 <PalletCommon<T>>::ensure_correct_receiver(to)?;537538 let balance_from = <AccountBalance<T>>::get((collection.id, from))539 .checked_sub(1)540 .ok_or(<CommonError<T>>::TokenValueTooLow)?;541 let balance_to = if from != to {542 let balance_to = <AccountBalance<T>>::get((collection.id, to))543 .checked_add(1)544 .ok_or(ArithmeticError::Overflow)?;545546 ensure!(547 balance_to < collection.limits.account_token_ownership_limit(),548 <CommonError<T>>::AccountTokenLimitExceeded,549 );550551 Some(balance_to)552 } else {553 None554 };555556 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {557 let handle = <CollectionHandle<T>>::try_get(target.0)?;558 let dispatch = T::CollectionDispatch::dispatch(handle);559 let dispatch = dispatch.as_dyn();560561 dispatch.check_nesting(562 from.clone(),563 (collection.id, token),564 target.1,565 nesting_budget,566 )?;567 }568569 // =========570571 <TokenData<T>>::insert(572 (collection.id, token),573 ItemData {574 owner: to.clone(),575 ..token_data576 },577 );578579 if let Some(balance_to) = balance_to {580 // from != to581 if balance_from == 0 {582 <AccountBalance<T>>::remove((collection.id, from));583 } else {584 <AccountBalance<T>>::insert((collection.id, from), balance_from);585 }586 <AccountBalance<T>>::insert((collection.id, to), balance_to);587 <Owned<T>>::remove((collection.id, from, token));588 <Owned<T>>::insert((collection.id, to, token), true);589 }590 Self::set_allowance_unchecked(collection, from, token, None, true);591592 <PalletEvm<T>>::deposit_log(593 ERC721Events::Transfer {594 from: *from.as_eth(),595 to: *to.as_eth(),596 token_id: token.into(),597 }598 .to_log(collection_id_to_address(collection.id)),599 );600 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(601 collection.id,602 token,603 from.clone(),604 to.clone(),605 1,606 ));607 Ok(())608 }609610 pub fn create_multiple_items(611 collection: &NonfungibleHandle<T>,612 sender: &T::CrossAccountId,613 data: Vec<CreateItemData<T>>,614 nesting_budget: &dyn Budget,615 ) -> DispatchResult {616 if !collection.is_owner_or_admin(sender) {617 ensure!(618 collection.permissions.mint_mode(),619 <CommonError<T>>::PublicMintingNotAllowed620 );621 collection.check_allowlist(sender)?;622623 for item in data.iter() {624 collection.check_allowlist(&item.owner)?;625 }626 }627628 for data in data.iter() {629 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;630 }631632 let first_token = <TokensMinted<T>>::get(collection.id);633 let tokens_minted = first_token634 .checked_add(data.len() as u32)635 .ok_or(ArithmeticError::Overflow)?;636 ensure!(637 tokens_minted <= collection.limits.token_limit(),638 <CommonError<T>>::CollectionTokenLimitExceeded639 );640641 let mut balances = BTreeMap::new();642 for data in &data {643 let balance = balances644 .entry(&data.owner)645 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));646 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;647648 ensure!(649 *balance <= collection.limits.account_token_ownership_limit(),650 <CommonError<T>>::AccountTokenLimitExceeded,651 );652 }653654 for (i, data) in data.iter().enumerate() {655 let token = TokenId(first_token + i as u32 + 1);656 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {657 let handle = <CollectionHandle<T>>::try_get(target.0)?;658 let dispatch = T::CollectionDispatch::dispatch(handle);659 let dispatch = dispatch.as_dyn();660 dispatch.check_nesting(661 sender.clone(),662 (collection.id, token),663 target.1,664 nesting_budget,665 )?;666 }667 }668669 // =========670671 with_transaction(|| {672 for (i, data) in data.iter().enumerate() {673 let token = first_token + i as u32 + 1;674675 <TokenData<T>>::insert(676 (collection.id, token),677 ItemData {678 // const_data: data.const_data.clone(),679 owner: data.owner.clone(),680 },681 );682683 if let Err(e) = Self::set_token_properties(684 collection,685 sender,686 TokenId(token),687 data.properties.clone().into_inner(),688 ) {689 return TransactionOutcome::Rollback(Err(e));690 }691 }692 TransactionOutcome::Commit(Ok(()))693 })?;694695 <TokensMinted<T>>::insert(collection.id, tokens_minted);696 for (account, balance) in balances {697 <AccountBalance<T>>::insert((collection.id, account), balance);698 }699 for (i, data) in data.into_iter().enumerate() {700 let token = first_token + i as u32 + 1;701 <Owned<T>>::insert((collection.id, &data.owner, token), true);702703 <PalletEvm<T>>::deposit_log(704 ERC721Events::Transfer {705 from: H160::default(),706 to: *data.owner.as_eth(),707 token_id: token.into(),708 }709 .to_log(collection_id_to_address(collection.id)),710 );711 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(712 collection.id,713 TokenId(token),714 data.owner.clone(),715 1,716 ));717 }718 Ok(())719 }720721 pub fn set_allowance_unchecked(722 collection: &NonfungibleHandle<T>,723 sender: &T::CrossAccountId,724 token: TokenId,725 spender: Option<&T::CrossAccountId>,726 assume_implicit_eth: bool,727 ) {728 if let Some(spender) = spender {729 let old_spender = <Allowance<T>>::get((collection.id, token));730 <Allowance<T>>::insert((collection.id, token), spender);731 // In ERC721 there is only one possible approved user of token, so we set732 // approved user to spender733 <PalletEvm<T>>::deposit_log(734 ERC721Events::Approval {735 owner: *sender.as_eth(),736 approved: *spender.as_eth(),737 token_id: token.into(),738 }739 .to_log(collection_id_to_address(collection.id)),740 );741 // In Unique chain, any token can have any amount of approved users, so we need to742 // set allowance of old owner to 0, and allowance of new owner to 1743 if old_spender.as_ref() != Some(spender) {744 if let Some(old_owner) = old_spender {745 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(746 collection.id,747 token,748 sender.clone(),749 old_owner,750 0,751 ));752 }753 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(754 collection.id,755 token,756 sender.clone(),757 spender.clone(),758 1,759 ));760 }761 } else {762 let old_spender = <Allowance<T>>::take((collection.id, token));763 if !assume_implicit_eth {764 // In ERC721 there is only one possible approved user of token, so we set765 // approved user to zero address766 <PalletEvm<T>>::deposit_log(767 ERC721Events::Approval {768 owner: *sender.as_eth(),769 approved: H160::default(),770 token_id: token.into(),771 }772 .to_log(collection_id_to_address(collection.id)),773 );774 }775 // In Unique chain, any token can have any amount of approved users, so we need to776 // set allowance of old owner to 0777 if let Some(old_spender) = old_spender {778 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(779 collection.id,780 token,781 sender.clone(),782 old_spender,783 0,784 ));785 }786 }787 }788789 pub fn set_allowance(790 collection: &NonfungibleHandle<T>,791 sender: &T::CrossAccountId,792 token: TokenId,793 spender: Option<&T::CrossAccountId>,794 ) -> DispatchResult {795 if collection.permissions.access() == AccessMode::AllowList {796 collection.check_allowlist(sender)?;797 if let Some(spender) = spender {798 collection.check_allowlist(spender)?;799 }800 }801802 if let Some(spender) = spender {803 <PalletCommon<T>>::ensure_correct_receiver(spender)?;804 }805 let token_data =806 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;807 if &token_data.owner != sender {808 ensure!(809 collection.ignores_owned_amount(sender),810 <CommonError<T>>::CantApproveMoreThanOwned811 );812 }813814 // =========815816 Self::set_allowance_unchecked(collection, sender, token, spender, false);817 Ok(())818 }819820 fn check_allowed(821 collection: &NonfungibleHandle<T>,822 spender: &T::CrossAccountId,823 from: &T::CrossAccountId,824 token: TokenId,825 nesting_budget: &dyn Budget,826 ) -> DispatchResult {827 if spender.conv_eq(from) {828 return Ok(());829 }830 if collection.permissions.access() == AccessMode::AllowList {831 // `from`, `to` checked in [`transfer`]832 collection.check_allowlist(spender)?;833 }834 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {835 // TODO: should collection owner be allowed to perform this transfer?836 ensure!(837 <PalletStructure<T>>::check_indirectly_owned(838 spender.clone(),839 source.0,840 source.1,841 None,842 nesting_budget843 )?,844 <CommonError<T>>::ApprovedValueTooLow,845 );846 return Ok(());847 }848 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {849 return Ok(());850 }851 ensure!(852 collection.ignores_allowance(spender),853 <CommonError<T>>::ApprovedValueTooLow854 );855 Ok(())856 }857858 pub fn transfer_from(859 collection: &NonfungibleHandle<T>,860 spender: &T::CrossAccountId,861 from: &T::CrossAccountId,862 to: &T::CrossAccountId,863 token: TokenId,864 nesting_budget: &dyn Budget,865 ) -> DispatchResult {866 Self::check_allowed(collection, spender, from, token, nesting_budget)?;867868 // =========869870 // Allowance is reset in [`transfer`]871 Self::transfer(collection, from, to, token, nesting_budget)872 }873874 pub fn burn_from(875 collection: &NonfungibleHandle<T>,876 spender: &T::CrossAccountId,877 from: &T::CrossAccountId,878 token: TokenId,879 nesting_budget: &dyn Budget,880 ) -> DispatchResult {881 Self::check_allowed(collection, spender, from, token, nesting_budget)?;882883 // =========884885 Self::burn(collection, from, token)886 }887888 pub fn check_nesting(889 handle: &NonfungibleHandle<T>,890 sender: T::CrossAccountId,891 from: (CollectionId, TokenId),892 under: TokenId,893 nesting_budget: &dyn Budget,894 ) -> DispatchResult {895 fn ensure_sender_allowed<T: Config>(896 collection: CollectionId,897 token: TokenId,898 for_nest: (CollectionId, TokenId),899 sender: T::CrossAccountId,900 budget: &dyn Budget,901 ) -> DispatchResult {902 ensure!(903 <PalletStructure<T>>::check_indirectly_owned(904 sender,905 collection,906 token,907 Some(for_nest),908 budget909 )?,910 <CommonError<T>>::OnlyOwnerAllowedToNest,911 );912 Ok(())913 }914 match handle.permissions.nesting() {915 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),916 NestingRule::Owner => {917 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?918 }919 NestingRule::OwnerRestricted(whitelist) => {920 ensure!(921 whitelist.contains(&from.0),922 <CommonError<T>>::SourceCollectionIsNotAllowedToNest923 );924 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?925 }926 }927 Ok(())928 }929930 /// Delegated to `create_multiple_items`931 pub fn create_item(932 collection: &NonfungibleHandle<T>,933 sender: &T::CrossAccountId,934 data: CreateItemData<T>,935 nesting_budget: &dyn Budget,936 ) -> DispatchResult {937 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)938 }939}pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -330,40 +330,6 @@
}
}
-// Selector: 9b5e29c5
-contract CollectionProperties is Dummy, ERC165 {
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- public
- {
- require(false, stub_error);
- key;
- value;
- dummy = 0;
- }
-
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) public {
- require(false, stub_error);
- key;
- dummy = 0;
- }
-
- // Throws error if key not found
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- public
- view
- returns (bytes memory)
- {
- require(false, stub_error);
- key;
- dummy;
- return hex"";
- }
-}
-
// Selector: d74d154f
contract ERC721UniqueExtensions is Dummy, ERC165 {
// Selector: transfer(address,uint256) a9059cbb
@@ -414,6 +380,68 @@
}
}
+// Selector: f5652829
+contract Collection is Dummy, ERC165 {
+ // Selector: setCollectionProperty(string,bytes) 2f073f66
+ function setCollectionProperty(string memory key, bytes memory value)
+ public
+ {
+ require(false, stub_error);
+ key;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: deleteCollectionProperty(string) 7b7debce
+ function deleteCollectionProperty(string memory key) public {
+ require(false, stub_error);
+ key;
+ dummy = 0;
+ }
+
+ // Throws error if key not found
+ //
+ // Selector: collectionProperty(string) cf24fd6d
+ function collectionProperty(string memory key)
+ public
+ view
+ returns (bytes memory)
+ {
+ require(false, stub_error);
+ key;
+ dummy;
+ return hex"";
+ }
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() public {
+ require(false, stub_error);
+ dummy = 0;
+ }
+
+ // Selector: setLimit(string,string) bf4d2014
+ function setLimit(string memory limit, string memory value) public {
+ require(false, stub_error);
+ limit;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() public view returns (address) {
+ require(false, stub_error);
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+}
+
contract UniqueNFT is
Dummy,
ERC165,
@@ -423,6 +451,6 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
- CollectionProperties,
+ Collection,
TokenProperties
{}
pallets/unique/Cargo.tomldiffbeforeafterboth--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -19,6 +19,7 @@
runtime-benchmarks = ['frame-benchmarking', 'pallet-common/runtime-benchmarks']
std = [
'codec/std',
+ 'serde/std',
'frame-support/std',
'frame-system/std',
'pallet-evm/std',
@@ -27,10 +28,25 @@
'sp-std/std',
'sp-runtime/std',
'frame-benchmarking/std',
+ 'evm-coder/std',
+ 'pallet-evm-coder-substrate/std',
+ 'pallet-nonfungible/std',
]
limit-testing = ["up-data-structs/limit-testing"]
################################################################################
+# Standart Dependencies
+
+[dependencies.serde]
+default-features = false
+features = ['derive']
+version = '1.0.130'
+
+[dependencies.ethereum]
+version = "0.12.0"
+default-features = false
+
+################################################################################
# Substrate Dependencies
[dependencies.codec]
@@ -74,7 +90,6 @@
default-features = false
git = "https://github.com/paritytech/substrate"
branch = "polkadot-v0.9.21"
-
################################################################################
# Local Dependencies
@@ -85,3 +100,6 @@
] }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
pallet-common = { default-features = false, path = "../common" }
+evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
+pallet-nonfungible = { default-features = false, path = '../../pallets/nonfungible' }
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/unique/src/eth/mod.rs
@@ -0,0 +1,171 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use core::marker::PhantomData;
+use evm_coder::{execution::*, generate_stubgen, solidity_interface, types::*, ToLog};
+use ethereum as _;
+use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
+use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId, Pallet as PalletEvm};
+use up_data_structs::{
+ CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+ MAX_COLLECTION_NAME_LENGTH,
+};
+use frame_support::traits::Get;
+use sp_core::H160;
+use pallet_common::CollectionById;
+
+use sp_std::vec::Vec;
+use alloc::format;
+
+pub trait Config:
+ frame_system::Config
+ + pallet_evm_coder_substrate::Config
+ + pallet_evm::account::Config
+ + pallet_nonfungible::Config
+{
+ type ContractAddress: Get<H160>;
+}
+
+struct EvmCollectionHelper<T: Config>(SubstrateRecorder<T>);
+impl<T: Config> WithRecorder<T> for EvmCollectionHelper<T> {
+ fn recorder(&self) -> &SubstrateRecorder<T> {
+ &self.0
+ }
+
+ fn into_recorder(self) -> SubstrateRecorder<T> {
+ self.0
+ }
+}
+
+#[solidity_interface(name = "CollectionHelper")]
+impl<T: Config> EvmCollectionHelper<T> {
+ fn create_721_collection(
+ &self,
+ caller: caller,
+ name: string,
+ description: string,
+ token_prefix: string,
+ ) -> Result<address> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let name = name
+ .encode_utf16()
+ .collect::<Vec<u16>>()
+ .try_into()
+ .map_err(|_| error_feild_too_long(stringify!(name), MAX_COLLECTION_NAME_LENGTH))?;
+ let description = description
+ .encode_utf16()
+ .collect::<Vec<u16>>()
+ .try_into()
+ .map_err(|_| {
+ error_feild_too_long(stringify!(description), MAX_COLLECTION_DESCRIPTION_LENGTH)
+ })?;
+ let token_prefix = token_prefix
+ .into_bytes()
+ .try_into()
+ .map_err(|_| error_feild_too_long(stringify!(token_prefix), MAX_TOKEN_PREFIX_LENGTH))?;
+
+ let key = pallet_common::eth::KEY_TOKEN_URI.clone();
+ let permission = up_data_structs::PropertyPermission {
+ mutable: true,
+ collection_admin: true,
+ token_owner: false,
+ };
+ let mut token_property_permissions =
+ up_data_structs::CollectionPropertiesPermissionsVec::default();
+ token_property_permissions
+ .try_push(up_data_structs::PropertyKeyPermission { key, permission })
+ .map_err(|e| Error::Revert(format!("{:?}", e)))?;
+
+ let data = CreateCollectionData {
+ name,
+ description,
+ token_prefix,
+ token_property_permissions,
+ ..Default::default()
+ };
+
+ let collection_id =
+ <pallet_nonfungible::Pallet<T>>::init_collection(caller.as_sub().clone(), data)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+
+ let address = pallet_common::eth::collection_id_to_address(collection_id);
+ <PalletEvm<T>>::deposit_log(
+ EthCollectionEvent::CollectionCreated {
+ owner: *caller.as_eth(),
+ collection_id: address,
+ }
+ .to_log(address),
+ );
+ Ok(address)
+ }
+
+ fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {
+ if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {
+ let collection_id = id;
+ return Ok(<CollectionById<T>>::contains_key(collection_id));
+ }
+
+ Ok(false)
+ }
+}
+
+#[derive(ToLog)]
+pub enum EthCollectionEvent {
+ CollectionCreated {
+ #[indexed]
+ owner: address,
+ #[indexed]
+ collection_id: address,
+ },
+}
+
+pub struct CollectionHelperOnMethodCall<T: Config>(PhantomData<*const T>);
+impl<T: Config> OnMethodCall<T> for CollectionHelperOnMethodCall<T> {
+ fn is_reserved(contract: &sp_core::H160) -> bool {
+ contract == &T::ContractAddress::get()
+ }
+
+ fn is_used(contract: &sp_core::H160) -> bool {
+ contract == &T::ContractAddress::get()
+ }
+
+ fn call(
+ source: &sp_core::H160,
+ target: &sp_core::H160,
+ gas_left: u64,
+ input: &[u8],
+ value: sp_core::U256,
+ ) -> Option<PrecompileResult> {
+ if target != &T::ContractAddress::get() {
+ return None;
+ }
+
+ let helpers = EvmCollectionHelper::<T>(SubstrateRecorder::<T>::new(gas_left));
+ pallet_evm_coder_substrate::call(*source, helpers, value, input)
+ }
+
+ fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {
+ (contract == &T::ContractAddress::get())
+ .then(|| include_bytes!("./stubs/CollectionHelper.raw").to_vec())
+ }
+}
+
+generate_stubgen!(collection_helper_impl, CollectionHelperCall<()>, true);
+generate_stubgen!(collection_helper_iface, CollectionHelperCall<()>, false);
+
+fn error_feild_too_long(feild: &str, bound: u32) -> Error {
+ Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))
+}
pallets/unique/src/eth/stubs/CollectionHelper.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelper.soldiffbeforeafterboth--- /dev/null
+++ b/pallets/unique/src/eth/stubs/CollectionHelper.sol
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+contract Dummy {
+ uint8 dummy;
+ string stub_error = "this contract is implemented in native";
+}
+
+contract ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID)
+ external
+ view
+ returns (bool)
+ {
+ require(false, stub_error);
+ interfaceID;
+ return true;
+ }
+}
+
+// Selector: 56c215c5
+contract CollectionHelper is Dummy, ERC165 {
+ // Selector: create721Collection(string,string,string) 951c0151
+ function create721Collection(
+ string memory name,
+ string memory description,
+ string memory tokenPrefix
+ ) public view returns (address) {
+ require(false, stub_error);
+ name;
+ description;
+ tokenPrefix;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
+ // Selector: isCollectionExist(address) c3de1494
+ function isCollectionExist(address collectionAddress)
+ public
+ view
+ returns (bool)
+ {
+ require(false, stub_error);
+ collectionAddress;
+ dummy;
+ return false;
+ }
+}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -22,6 +22,8 @@
clippy::unused_unit
)]
+extern crate alloc;
+
use frame_support::{
decl_module, decl_storage, decl_error, decl_event,
dispatch::DispatchResult,
@@ -46,6 +48,7 @@
CollectionHandle, Pallet as PalletCommon, CommonWeightInfo, dispatch::dispatch_call,
dispatch::CollectionDispatch,
};
+pub mod eth;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
@@ -520,7 +523,7 @@
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
target_collection.check_is_owner(&sender)?;
- target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor.clone());
+ target_collection.set_sponsor(new_sponsor.clone());
<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(
collection_id,
@@ -544,11 +547,9 @@
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
ensure!(
- target_collection.sponsorship.pending_sponsor() == Some(&sender),
+ target_collection.confirm_sponsorship(&sender),
Error::<T>::ConfirmUnsetSponsorFail
);
-
- target_collection.sponsorship = SponsorshipState::Confirmed(sender.clone());
<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(
collection_id,
primitives/data-structs/Cargo.tomldiffbeforeafterboth--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -40,6 +40,6 @@
"sp-std/std",
"pallet-evm/std",
]
-serde1 = ["serde"]
+serde1 = ["serde/alloc"]
limit-testing = []
runtime-benchmarks = []
\ No newline at end of file
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -506,6 +506,7 @@
}
#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub enum MetaUpdatePermission {
ItemOwner,
Admin,
@@ -760,6 +761,10 @@
self.0.get(key)
}
+ pub fn contains_key(&self, key: &PropertyKey) -> bool {
+ self.0.contains_key(key)
+ }
+
fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {
if key.is_empty() {
return Err(PropertiesError::EmptyPropertyKey);
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -50,6 +50,7 @@
pub use pallet_balances::Call as BalancesCall;
pub use pallet_evm::{
EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,
+ OnMethodCall, Account as EVMAccount, FeeCalculator, GasWeightMapping,
};
pub use frame_support::{
construct_runtime, match_types,
@@ -79,7 +80,6 @@
};
use smallvec::smallvec;
use codec::{Encode, Decode};
-use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};
use fp_rpc::TransactionStatus;
use sp_runtime::{
traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
@@ -306,6 +306,7 @@
pallet_evm_migration::OnMethodCall<Self>,
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
+ pallet_unique::eth::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -974,6 +975,11 @@
pub const HelpersContractAddress: H160 = H160([
0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,
]);
+
+ // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
+ pub const EvmCollectionHelperAddress: H160 = H160([
+ 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
+ ]);
}
impl pallet_evm_contract_helpers::Config for Runtime {
@@ -981,6 +987,10 @@
type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;
}
+impl pallet_unique::eth::Config for Runtime {
+ type ContractAddress = EvmCollectionHelperAddress;
+}
+
construct_runtime!(
pub enum Runtime where
Block = Block,
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -66,7 +66,6 @@
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
},
};
-use unique_runtime_common::dispatch::{CollectionDispatchT, CollectionDispatch};
use up_data_structs::*;
// use pallet_contracts::weights::WeightInfo;
// #[cfg(any(feature = "std", test))]
@@ -116,7 +115,15 @@
//use xcm_executor::traits::MatchesFungible;
use sp_runtime::traits::CheckedConversion;
-use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};
+use unique_runtime_common::{
+ impl_common_runtime_apis,
+ types::*,
+ constants::*,
+ dispatch::{CollectionDispatchT, CollectionDispatch},
+ sponsoring::UniqueSponsorshipHandler,
+ eth_sponsoring::UniqueEthSponsorshipHandler,
+ weights::CommonWeights,
+};
pub const RUNTIME_NAME: &str = "quartz";
pub const TOKEN_SYMBOL: &str = "QTZ";
@@ -278,6 +285,7 @@
pallet_evm_migration::OnMethodCall<Self>,
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
+ pallet_unique::eth::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -891,6 +899,7 @@
impl pallet_unique::Config for Runtime {
type Event = Event;
type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
+ type CommonWeightInfo = CommonWeights<Self>;
}
parameter_types! {
@@ -912,11 +921,11 @@
// }
type EvmSponsorshipHandler = (
- pallet_unique::UniqueEthSponsorshipHandler<Runtime>,
+ UniqueEthSponsorshipHandler<Runtime>,
pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
);
type SponsorshipHandler = (
- pallet_unique::UniqueSponsorshipHandler<Runtime>,
+ UniqueSponsorshipHandler<Runtime>,
//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
);
@@ -951,6 +960,11 @@
pub const HelpersContractAddress: H160 = H160([
0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,
]);
+
+ // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
+ pub const EvmCollectionHelperAddress: H160 = H160([
+ 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
+ ]);
}
impl pallet_evm_contract_helpers::Config for Runtime {
@@ -958,6 +972,10 @@
type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;
}
+impl pallet_unique::eth::Config for Runtime {
+ type ContractAddress = EvmCollectionHelperAddress;
+}
+
construct_runtime!(
pub enum Runtime where
Block = Block,
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -49,7 +49,8 @@
// A few exports that help ease life for downstream crates.
pub use pallet_balances::Call as BalancesCall;
pub use pallet_evm::{
- EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,
+ EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _, OnMethodCall,
+ Account as EVMAccount, FeeCalculator, GasWeightMapping,
};
pub use frame_support::{
construct_runtime, match_types,
@@ -84,7 +85,6 @@
};
use smallvec::smallvec;
use codec::{Encode, Decode};
-use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};
use fp_rpc::TransactionStatus;
use sp_runtime::{
traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
@@ -120,7 +120,15 @@
//use xcm_executor::traits::MatchesFungible;
use sp_runtime::traits::CheckedConversion;
-use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};
+use unique_runtime_common::{
+ impl_common_runtime_apis,
+ types::*,
+ constants::*,
+ dispatch::{CollectionDispatchT, CollectionDispatch},
+ sponsoring::UniqueSponsorshipHandler,
+ eth_sponsoring::UniqueEthSponsorshipHandler,
+ weights::CommonWeights,
+};
pub const RUNTIME_NAME: &str = "unique";
pub const TOKEN_SYMBOL: &str = "UNQ";
@@ -282,6 +290,7 @@
pallet_evm_migration::OnMethodCall<Self>,
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
+ pallet_unique::eth::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -956,6 +965,11 @@
pub const HelpersContractAddress: H160 = H160([
0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,
]);
+
+ // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
+ pub const EvmCollectionHelperAddress: H160 = H160([
+ 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
+ ]);
}
impl pallet_evm_contract_helpers::Config for Runtime {
@@ -963,6 +977,10 @@
type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;
}
+impl pallet_unique::eth::Config for Runtime {
+ type ContractAddress = EvmCollectionHelperAddress;
+}
+
construct_runtime!(
pub enum Runtime where
Block = Block,
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -73,6 +73,7 @@
"testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
"testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",
"testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",
+ "testEthCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createCollection.test.ts",
"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",
"polkadot-types-from-defs": "ts-node ./node_modules/.bin/polkadot-types-from-defs --endpoint src/interfaces/metadata.json --input src/interfaces/ --package .",
"polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint src/interfaces/metadata.json --output src/interfaces/ --package .",
@@ -88,7 +89,7 @@
"bignumber.js": "^9.0.2",
"chai-as-promised": "^7.1.1",
"find-process": "^1.4.7",
- "solc": "^0.8.13",
+ "solc": "0.8.13",
"web3": "^1.7.3"
},
"standard": {
tests/src/eth/api/CollectionHelper.soldiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/api/CollectionHelper.sol
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+interface Dummy {
+
+}
+
+interface ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID) external view returns (bool);
+}
+
+// Selector: 56c215c5
+interface CollectionHelper is Dummy, ERC165 {
+ // Selector: create721Collection(string,string,string) 951c0151
+ function create721Collection(
+ string memory name,
+ string memory description,
+ string memory tokenPrefix
+ ) external view returns (address);
+
+ // Selector: isCollectionExist(address) c3de1494
+ function isCollectionExist(address collectionAddress)
+ external
+ view
+ returns (bool);
+}
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -65,8 +65,8 @@
returns (uint256);
}
-// Selector: 9b5e29c5
-interface CollectionProperties is Dummy, ERC165 {
+// Selector: f5652829
+interface Collection is Dummy, ERC165 {
// Selector: setCollectionProperty(string,bytes) 2f073f66
function setCollectionProperty(string memory key, bytes memory value)
external;
@@ -81,6 +81,18 @@
external
view
returns (bytes memory);
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) external;
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() external;
+
+ // Selector: setLimit(string,string) bf4d2014
+ function setLimit(string memory limit, string memory value) external;
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() external view returns (address);
}
interface UniqueFungible is
@@ -88,5 +100,5 @@
ERC165,
ERC20,
ERC20UniqueExtensions,
- CollectionProperties
+ Collection
{}
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -191,24 +191,6 @@
function totalSupply() external view returns (uint256);
}
-// Selector: 9b5e29c5
-interface CollectionProperties is Dummy, ERC165 {
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- external;
-
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) external;
-
- // Throws error if key not found
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- external
- view
- returns (bytes memory);
-}
-
// Selector: d74d154f
interface ERC721UniqueExtensions is Dummy, ERC165 {
// Selector: transfer(address,uint256) a9059cbb
@@ -231,6 +213,36 @@
returns (bool);
}
+// Selector: f5652829
+interface Collection is Dummy, ERC165 {
+ // Selector: setCollectionProperty(string,bytes) 2f073f66
+ function setCollectionProperty(string memory key, bytes memory value)
+ external;
+
+ // Selector: deleteCollectionProperty(string) 7b7debce
+ function deleteCollectionProperty(string memory key) external;
+
+ // Throws error if key not found
+ //
+ // Selector: collectionProperty(string) cf24fd6d
+ function collectionProperty(string memory key)
+ external
+ view
+ returns (bytes memory);
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) external;
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() external;
+
+ // Selector: setLimit(string,string) bf4d2014
+ function setLimit(string memory limit, string memory value) external;
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() external view returns (address);
+}
+
interface UniqueNFT is
Dummy,
ERC165,
@@ -240,6 +252,6 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
- CollectionProperties,
+ Collection,
TokenProperties
{}
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -14,7 +14,17 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, deployFlipper, ethBalanceViaSub, GAS_ARGS, itWeb3, recordEthFee, usingWeb3} from './util/helpers';
+import {
+ collectionIdToAddress,
+ createEthAccount,
+ createEthAccountWithBalance,
+ deployFlipper,
+ ethBalanceViaSub,
+ GAS_ARGS,
+ itWeb3,
+ recordEthFee,
+ usingWeb3,
+} from './util/helpers';
import {expect} from 'chai';
import {createCollectionExpectSuccess, createItemExpectSuccess, UNIQUE} from '../util/helpers';
import nonFungibleAbi from './nonFungibleAbi.json';
tests/src/eth/collectionHelperAbi.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/collectionHelperAbi.json
@@ -0,0 +1,35 @@
+[
+ {
+ "inputs": [
+ { "internalType": "string", "name": "name", "type": "string" },
+ { "internalType": "string", "name": "description", "type": "string" },
+ { "internalType": "string", "name": "tokenPrefix", "type": "string" }
+ ],
+ "name": "create721Collection",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "collectionAddress",
+ "type": "address"
+ }
+ ],
+ "name": "isCollectionExist",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
+ ],
+ "name": "supportsInterface",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ }
+]
tests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -29,19 +29,19 @@
normalizeEvents,
subToEth,
executeEthTxOnSub,
+ evmCollectionHelper,
+ getCollectionAddressFromResult,
+ evmCollection,
} from './util/helpers';
import {
addCollectionAdminExpectSuccess,
createCollectionExpectSuccess,
- getCreateCollectionResult,
+ getDetailedCollectionInfo,
transferBalanceTo,
} from '../util/helpers';
import nonFungibleAbi from './nonFungibleAbi.json';
-import {
- submitTransactionAsync,
-} from '../substrate/substrate-api';
import getBalance from '../substrate/get-balance';
-import {alicesPublicKey} from '../accounts';
+import {evmToAddress} from '@polkadot/util-crypto';
describe('Sponsoring EVM contracts', () => {
itWeb3('Sponsoring can be set by the address that has deployed the contract', async ({api, web3}) => {
@@ -221,89 +221,87 @@
expect(await helpers.methods.getSponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');
});
- itWeb3('Sponsoring evm address from substrate collection', async ({api, web3}) => {
- const owner = privateKey('//Alice');
- const userEth = createEthAccount(web3);
- const collectionId = await createCollectionExpectSuccess();
+ //TODO: CORE-302 add eth methods
+ itWeb3.skip('Sponsoring evm address from substrate collection', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ let result = await collectionHelper.methods.create721Collection('Sponsor collection', '1', '1').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const sponsor = await createEthAccountWithBalance(api, web3);
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ result = await collectionEvm.methods.ethSetSponsor(sponsor).send();
+ let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
+ expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ await expect(collectionEvm.methods.ethConfirmSponsorship().call()).to.be.rejectedWith('Caller is not set as sponsor');
- {
- const tx = api.tx.unique.setCollectionSponsor(collectionId, owner.address);
- const events = await submitTransactionAsync(owner, tx);
- const result = getCreateCollectionResult(events);
- expect(result.success).to.be.true;
- }
- {
- const tx = api.tx.unique.confirmSponsorship(collectionId);
- const events = await submitTransactionAsync(owner, tx);
- const result = getCreateCollectionResult(events);
- expect(result.success).to.be.true;
- }
+ const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+ await sponsorCollection.methods.ethConfirmSponsorship().send();
+ collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.sponsorship.isConfirmed).to.be.true;
+ expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
- const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: userEth, ...GAS_ARGS});
+ const user = createEthAccount(web3);
+ const userContract = evmCollection(web3, user, collectionIdAddress);
+ const nextTokenId = await userContract.methods.nextTokenId().call();
- { // This part should fail, because user not in access list and user have no money
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- await expect(contract.methods.mintWithTokenURI(
- userEth,
- nextTokenId,
- 'Test URI',
- ).call({from: userEth})).to.be.rejectedWith(/PublicMintingNotAllowed/);
- }
-
- {
- const tx = api.tx.unique.setPublicAccessMode(collectionId, 'AllowList');
- const events = await submitTransactionAsync(owner, tx);
- const result = getCreateCollectionResult(events);
- expect(result.success).to.be.true;
- }
- {
- const tx = api.tx.unique.addToAllowList(collectionId, {Ethereum: userEth});
- const events = await submitTransactionAsync(owner, tx);
- const result = getCreateCollectionResult(events);
- expect(result.success).to.be.true;
- }
- {
- const tx = api.tx.unique.setMintPermission(collectionId, true);
- const events = await submitTransactionAsync(owner, tx);
- const result = getCreateCollectionResult(events);
- expect(result.success).to.be.true;
- }
+ expect(nextTokenId).to.be.equal('1');
+ await expect(userContract.methods.mintWithTokenURI(
+ user,
+ nextTokenId,
+ 'Test URI',
+ ).call()).to.be.rejectedWith('PublicMintingNotAllowed');
+
+ // TODO: add this methods to eth
+ // {
+ // const tx = api.tx.unique.setPublicAccessMode(collectionId, 'AllowList');
+ // const events = await submitTransactionAsync(owner, tx);
+ // const result = getCreateCollectionResult(events);
+ // expect(result.success).to.be.true;
+ // }
+ // {
+ // const tx = api.tx.unique.addToAllowList(collectionId, {Ethereum: userEth});
+ // const events = await submitTransactionAsync(owner, tx);
+ // const result = getCreateCollectionResult(events);
+ // expect(result.success).to.be.true;
+ // }
+ // {
+ // const tx = api.tx.unique.setMintPermission(collectionId, true);
+ // const events = await submitTransactionAsync(owner, tx);
+ // const result = getCreateCollectionResult(events);
+ // expect(result.success).to.be.true;
+ // }
- const [alicesBalanceBefore] = await getBalance(api, [alicesPublicKey]);
+ // const [alicesBalanceBefore] = await getBalance(api, [alicesPublicKey]);
{
- const nextTokenId = await contract.methods.nextTokenId().call();
+ const nextTokenId = await userContract.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
- const result = await contract.methods.mintWithTokenURI(
- userEth,
+ const result = await userContract.methods.mintWithTokenURI(
+ user,
nextTokenId,
'Test URI',
- ).send({from: userEth});
+ ).send();
const events = normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
- address,
+ collectionIdAddress,
event: 'Transfer',
args: {
from: '0x0000000000000000000000000000000000000000',
- to: userEth,
+ to: user,
tokenId: nextTokenId,
},
},
]);
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(await userContract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
}
-
- const [alicesBalanceAfter] = await getBalance(api, [alicesPublicKey]);
- expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;
});
-
- itWeb3('Check that transaction via EVM spend money from substrate address', async ({api, web3}) => {
+ //TODO: CORE-302 add eth methods
+ itWeb3.skip('Check that transaction via EVM spend money from substrate address', async ({api, web3}) => {
const owner = privateKey('//Alice');
const user = privateKey(`//User/${Date.now()}`);
const userEth = subToEth(user.address);
tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/createCollection.test.ts
@@ -0,0 +1,236 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {evmToAddress} from '@polkadot/util-crypto';
+import {expect} from 'chai';
+import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';
+import {
+ evmCollectionHelper,
+ collectionIdToAddress,
+ createEthAccount,
+ createEthAccountWithBalance,
+ evmCollection,
+ itWeb3,
+ getCollectionAddressFromResult,
+} from './util/helpers';
+
+describe('Create collection from EVM', () => {
+ itWeb3('Create collection', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const helper = evmCollectionHelper(web3, owner);
+ const collectionName = 'CollectionEVM';
+ const description = 'Some description';
+ const tokenPrefix = 'token prefix';
+
+ const collectionCountBefore = await getCreatedCollectionCount(api);
+ const result = await helper.methods
+ .create721Collection(collectionName, description, tokenPrefix)
+ .send();
+ const collectionCountAfter = await getCreatedCollectionCount(api);
+
+ const {collectionId, collection} = await getCollectionAddressFromResult(api, result);
+ expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
+ expect(collectionId).to.be.eq(collectionCountAfter);
+ expect(collection.name.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(collectionName);
+ expect(collection.description.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(description);
+ expect(collection.tokenPrefix.toHuman()).to.be.eq(tokenPrefix);
+ expect(collection.schemaVersion.type).to.be.eq('ImageURL');
+ });
+
+ itWeb3('Check collection address exist', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const collectionHelper = evmCollectionHelper(web3, owner);
+
+ const expectedCollectionId = await getCreatedCollectionCount(api) + 1;
+ const expectedCollectionAddress = collectionIdToAddress(expectedCollectionId);
+ expect(await collectionHelper.methods
+ .isCollectionExist(expectedCollectionAddress)
+ .call()).to.be.false;
+
+ await collectionHelper.methods
+ .create721Collection('A', 'A', 'A')
+ .send();
+
+ expect(await collectionHelper.methods
+ .isCollectionExist(expectedCollectionAddress)
+ .call()).to.be.true;
+ });
+
+ itWeb3('Set sponsorship', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ let result = await collectionHelper.methods.create721Collection('Sponsor collection', '1', '1').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const sponsor = await createEthAccountWithBalance(api, web3);
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ result = await collectionEvm.methods.ethSetSponsor(sponsor).send();
+ let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
+ expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ await expect(collectionEvm.methods.ethConfirmSponsorship().call()).to.be.rejectedWith('Caller is not set as sponsor');
+ const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+ await sponsorCollection.methods.ethConfirmSponsorship().send();
+ collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.sponsorship.isConfirmed).to.be.true;
+ expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ });
+
+ itWeb3('Set limits', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ const result = await collectionHelper.methods.create721Collection('Const collection', '5', '5').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const limits = {
+ accountTokenOwnershipLimit: 1000,
+ sponsoredDataSize: 1024,
+ sponsoredDataRateLimit: 30,
+ tokenLimit: 1000000,
+ sponsorTransferTimeout: 6,
+ sponsorApproveTimeout: 6,
+ ownerCanTransfer: false,
+ ownerCanDestroy: false,
+ transfersEnabled: false,
+ };
+
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ await collectionEvm.methods.setLimit('accountTokenOwnershipLimit', limits.accountTokenOwnershipLimit.toString()).send();
+ await collectionEvm.methods.setLimit('sponsoredDataSize', limits.sponsoredDataSize.toString()).send();
+ await collectionEvm.methods.setLimit('sponsoredDataRateLimit', limits.sponsoredDataRateLimit.toString()).send();
+ await collectionEvm.methods.setLimit('tokenLimit', limits.tokenLimit.toString()).send();
+ await collectionEvm.methods.setLimit('sponsorTransferTimeout', limits.sponsorTransferTimeout.toString()).send();
+ await collectionEvm.methods.setLimit('sponsorApproveTimeout', limits.sponsorApproveTimeout.toString()).send();
+ await collectionEvm.methods.setLimit('ownerCanTransfer', limits.ownerCanTransfer.toString()).send();
+ await collectionEvm.methods.setLimit('ownerCanDestroy', limits.ownerCanDestroy.toString()).send();
+ await collectionEvm.methods.setLimit('transfersEnabled', limits.transfersEnabled.toString()).send();
+
+ const collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
+ expect(collectionSub.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);
+ expect(collectionSub.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit);
+ expect(collectionSub.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);
+ expect(collectionSub.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);
+ expect(collectionSub.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);
+ expect(collectionSub.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);
+ expect(collectionSub.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);
+ expect(collectionSub.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);
+ });
+
+ itWeb3('Collection address exist', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ expect(await collectionHelper.methods
+ .isCollectionExist(collectionAddressForNonexistentCollection).call())
+ .to.be.false;
+
+ const result = await collectionHelper.methods.create721Collection('Collection address exist', '7', '7').send();
+ const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+ expect(await collectionHelper.methods
+ .isCollectionExist(collectionIdAddress).call())
+ .to.be.true;
+ });
+});
+
+describe('(!negative tests!) Create collection from EVM', () => {
+ itWeb3('(!negative test!) Create collection (bad lengths)', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const helper = evmCollectionHelper(web3, owner);
+ {
+ const MAX_NAME_LENGHT = 64;
+ const collectionName = 'A'.repeat(MAX_NAME_LENGHT + 1);
+ const description = 'A';
+ const tokenPrefix = 'A';
+
+ await expect(helper.methods
+ .create721Collection(collectionName, description, tokenPrefix)
+ .call()).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGHT);
+
+ }
+ {
+ const MAX_DESCRIPTION_LENGHT = 256;
+ const collectionName = 'A';
+ const description = 'A'.repeat(MAX_DESCRIPTION_LENGHT + 1);
+ const tokenPrefix = 'A';
+ await expect(helper.methods
+ .create721Collection(collectionName, description, tokenPrefix)
+ .call()).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGHT);
+ }
+ {
+ const MAX_TOKEN_PREFIX_LENGHT = 16;
+ const collectionName = 'A';
+ const description = 'A';
+ const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGHT + 1);
+ await expect(helper.methods
+ .create721Collection(collectionName, description, tokenPrefix)
+ .call()).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGHT);
+ }
+ });
+
+ itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
+ const owner = await createEthAccount(web3);
+ const helper = evmCollectionHelper(web3, owner);
+ const collectionName = 'A';
+ const description = 'A';
+ const tokenPrefix = 'A';
+
+ await expect(helper.methods
+ .create721Collection(collectionName, description, tokenPrefix)
+ .call()).to.be.rejectedWith('NotSufficientFounds');
+ });
+
+ itWeb3('(!negative test!) Check owner', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const notOwner = await createEthAccount(web3);
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ const result = await collectionHelper.methods.create721Collection('A', 'A', 'A').send();
+ const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+ const contractEvmFromNotOwner = evmCollection(web3, notOwner, collectionIdAddress);
+ const EXPECTED_ERROR = 'NoPermission';
+ {
+ const sponsor = await createEthAccountWithBalance(api, web3);
+ await expect(contractEvmFromNotOwner.methods
+ .ethSetSponsor(sponsor)
+ .call()).to.be.rejectedWith(EXPECTED_ERROR);
+
+ const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+ await expect(sponsorCollection.methods
+ .ethConfirmSponsorship()
+ .call()).to.be.rejectedWith('Caller is not set as sponsor');
+ }
+ {
+ await expect(contractEvmFromNotOwner.methods
+ .setLimit('account_token_ownership_limit', '1000')
+ .call()).to.be.rejectedWith(EXPECTED_ERROR);
+ }
+ });
+
+ itWeb3('(!negative test!) Set limits', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ const result = await collectionHelper.methods.create721Collection('Schema collection', 'A', 'A').send();
+ const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ await expect(collectionEvm.methods
+ .setLimit('badLimit', 'true')
+ .call()).to.be.rejectedWith('Unknown limit "badLimit"');
+ await expect(collectionEvm.methods
+ .setLimit('sponsoredDataSize', 'badValue')
+ .call()).to.be.rejectedWith('Int value "badValue" parse error:');
+ await expect(collectionEvm.methods
+ .setLimit('ownerCanTransfer', 'badValue')
+ .call()).to.be.rejectedWith('Bool value "badValue" parse error:');
+ });
+});
\ No newline at end of file
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -1,175 +1,206 @@
[
- {
- "constant": false,
- "inputs": [
- {
- "name": "_spender",
- "type": "address"
- },
- {
- "name": "_value",
- "type": "uint256"
- }
- ],
- "name": "approve",
- "outputs": [
- {
- "name": "",
- "type": "bool"
- }
- ],
- "payable": false,
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "constant": true,
- "inputs": [],
- "name": "totalSupply",
- "outputs": [
- {
- "name": "",
- "type": "uint256"
- }
- ],
- "payable": false,
- "stateMutability": "view",
- "type": "function"
- },
- {
- "constant": false,
- "inputs": [
- {
- "name": "_from",
- "type": "address"
- },
- {
- "name": "_to",
- "type": "address"
- },
- {
- "name": "_value",
- "type": "uint256"
- }
- ],
- "name": "transferFrom",
- "outputs": [
- {
- "name": "",
- "type": "bool"
- }
- ],
- "payable": false,
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "constant": true,
- "inputs": [
- {
- "name": "_owner",
- "type": "address"
- }
- ],
- "name": "balanceOf",
- "outputs": [
- {
- "name": "balance",
- "type": "uint256"
- }
- ],
- "payable": false,
- "stateMutability": "view",
- "type": "function"
- },
- {
- "constant": false,
- "inputs": [
- {
- "name": "_to",
- "type": "address"
- },
- {
- "name": "_value",
- "type": "uint256"
- }
- ],
- "name": "transfer",
- "outputs": [
- {
- "name": "",
- "type": "bool"
- }
- ],
- "payable": false,
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "constant": true,
- "inputs": [
- {
- "name": "_owner",
- "type": "address"
- },
- {
- "name": "_spender",
- "type": "address"
- }
- ],
- "name": "allowance",
- "outputs": [
- {
- "name": "",
- "type": "uint256"
- }
- ],
- "payable": false,
- "stateMutability": "view",
- "type": "function"
- },
- {
- "anonymous": false,
- "inputs": [
- {
- "indexed": true,
- "name": "owner",
- "type": "address"
- },
- {
- "indexed": true,
- "name": "spender",
- "type": "address"
- },
- {
- "indexed": false,
- "name": "value",
- "type": "uint256"
- }
- ],
- "name": "Approval",
- "type": "event"
- },
- {
- "anonymous": false,
- "inputs": [
- {
- "indexed": true,
- "name": "from",
- "type": "address"
- },
- {
- "indexed": true,
- "name": "to",
- "type": "address"
- },
- {
- "indexed": false,
- "name": "value",
- "type": "uint256"
- }
- ],
- "name": "Transfer",
- "type": "event"
- }
-]
\ No newline at end of file
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "owner",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "spender",
+ "type": "address"
+ },
+ {
+ "indexed": false,
+ "internalType": "uint256",
+ "name": "value",
+ "type": "uint256"
+ }
+ ],
+ "name": "Approval",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "from",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "to",
+ "type": "address"
+ },
+ {
+ "indexed": false,
+ "internalType": "uint256",
+ "name": "value",
+ "type": "uint256"
+ }
+ ],
+ "name": "Transfer",
+ "type": "event"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "owner", "type": "address" },
+ { "internalType": "address", "name": "spender", "type": "address" }
+ ],
+ "name": "allowance",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "spender", "type": "address" },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "approve",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "owner", "type": "address" }
+ ],
+ "name": "balanceOf",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "burnFrom",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
+ "name": "collectionProperty",
+ "outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "contractAddress",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "decimals",
+ "outputs": [{ "internalType": "uint8", "name": "", "type": "uint8" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
+ "name": "deleteCollectionProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "ethConfirmSponsorship",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "sponsor", "type": "address" }
+ ],
+ "name": "ethSetSponsor",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "name",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+ ],
+ "name": "setCollectionProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "limit", "type": "string" },
+ { "internalType": "string", "name": "value", "type": "string" }
+ ],
+ "name": "setLimit",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
+ ],
+ "name": "supportsInterface",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "symbol",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "totalSupply",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "transfer",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "transferFrom",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ }
+]
tests/src/eth/fungibleMetadataAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleMetadataAbi.json
+++ /dev/null
@@ -1,41 +0,0 @@
-[
- {
- "inputs": [],
- "name": "name",
- "outputs": [
- {
- "internalType": "string",
- "name": "",
- "type": "string"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "symbol",
- "outputs": [
- {
- "internalType": "string",
- "name": "",
- "type": "string"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "decimals",
- "outputs": [
- {
- "internalType": "uint8",
- "name": "",
- "type": "uint8"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- }
-]
\ No newline at end of file
tests/src/eth/metadata.test.tsdiffbeforeafterboth--- a/tests/src/eth/metadata.test.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {expect} from 'chai';
-import {createCollectionExpectSuccess} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents} from './util/helpers';
-import fungibleMetadataAbi from './fungibleMetadataAbi.json';
-import privateKey from '../substrate/privateKey';
-import {submitTransactionAsync} from '../substrate/substrate-api';
-import nonFungibleAbi from './nonFungibleAbi.json';
-
-describe('Common metadata', () => {
- itWeb3('Returns collection name', async ({api, web3}) => {
- const collection = await createCollectionExpectSuccess({
- name: 'token name',
- mode: {type: 'NFT'},
- });
- const caller = await createEthAccountWithBalance(api, web3);
-
- const address = collectionIdToAddress(collection);
- const contract = new web3.eth.Contract(fungibleMetadataAbi as any, address, {from: caller, ...GAS_ARGS});
- const name = await contract.methods.name().call();
-
- expect(name).to.equal('token name');
- });
-
- itWeb3('Returns symbol name', async ({api, web3}) => {
- const collection = await createCollectionExpectSuccess({
- tokenPrefix: 'TOK',
- mode: {type: 'NFT'},
- });
- const caller = await createEthAccountWithBalance(api, web3);
-
- const address = collectionIdToAddress(collection);
- const contract = new web3.eth.Contract(fungibleMetadataAbi as any, address, {from: caller, ...GAS_ARGS});
- const symbol = await contract.methods.symbol().call();
-
- expect(symbol).to.equal('TOK');
- });
-});
-
-describe('Fungible metadata', () => {
- itWeb3('Returns fungible decimals', async ({api, web3}) => {
- const collection = await createCollectionExpectSuccess({
- mode: {type: 'Fungible', decimalPoints: 6},
- });
- const caller = await createEthAccountWithBalance(api, web3);
-
- const address = collectionIdToAddress(collection);
- const contract = new web3.eth.Contract(fungibleMetadataAbi as any, address, {from: caller, ...GAS_ARGS});
- const decimals = await contract.methods.decimals().call();
-
- expect(+decimals).to.equal(6);
- });
-});
-
-describe('Support ERC721Metadata', () => {
- itWeb3('Check unsupport ERC721Metadata SchemaVersion::Unique', async ({web3, api}) => {
- const collectionId = await createCollectionExpectSuccess({
- mode: {type: 'NFT'},
- schemaVersion: 'Unique',
- name: 'some_name',
- tokenPrefix: 'some_prefix',
- });
- const collection = await api.rpc.unique.collectionById(collectionId);
- expect(collection.isSome).to.be.true;
- expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('Unique');
-
- const alice = privateKey('//Alice');
-
- const caller = await createEthAccountWithBalance(api, web3);
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
- await submitTransactionAsync(alice, changeAdminTx);
-
- const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
-
- expect(await contract.methods.name().call()).to.be.eq('some_name');
- expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');
-
- const receiver = createEthAccount(web3);
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- await expect(contract.methods.mintWithTokenURI(
- receiver,
- nextTokenId,
- 'Test URI',
- ).call({from: caller})).to.be.rejectedWith('Unsupported schema version! Support only ImageURL');
-
- await expect(contract.methods.mintBulkWithTokenURI(
- receiver,
- [
- [nextTokenId, 'Test URI 0'],
- [+nextTokenId + 1, 'Test URI 1'],
- [+nextTokenId + 2, 'Test URI 2'],
- ],
- ).call({from: caller})).to.be.rejectedWith('Unsupported schema version! Support only ImageURL');
- });
-
- itWeb3('Check support ERC721Metadata for SchemaVersion::ImageURL', async ({web3, api}) => {
- const collectionId = await createCollectionExpectSuccess({
- mode: {type: 'NFT'},
- name: 'some_name',
- tokenPrefix: 'some_prefix',
- });
- const collection = await api.rpc.unique.collectionById(collectionId);
- expect(collection.isSome).to.be.true;
- expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('ImageURL');
-
- const alice = privateKey('//Alice');
-
- const caller = await createEthAccountWithBalance(api, web3);
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
- await submitTransactionAsync(alice, changeAdminTx);
-
- const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
-
- expect(await contract.methods.name().call()).to.be.eq('some_name');
- expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');
-
- const receiver = createEthAccount(web3);
- { // mintWithTokenURI
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- const result = await contract.methods.mintWithTokenURI(
- receiver,
- nextTokenId,
- 'Test URI',
- ).send({from: caller});
- const events = normalizeEvents(result.events);
-
- expect(events).to.be.deep.equal([
- {
- address,
- event: 'Transfer',
- args: {
- from: '0x0000000000000000000000000000000000000000',
- to: receiver,
- tokenId: nextTokenId,
- },
- },
- ]);
-
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
- }
-
- { // mintBulkWithTokenURI
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('2');
- const result = await contract.methods.mintBulkWithTokenURI(
- receiver,
- [
- [nextTokenId, 'Test URI 0'],
- [+nextTokenId + 1, 'Test URI 1'],
- [+nextTokenId + 2, 'Test URI 2'],
- ],
- ).send({from: caller});
- const events = normalizeEvents(result.events);
-
- expect(events).to.be.deep.equal([
- {
- address,
- event: 'Transfer',
- args: {
- from: '0x0000000000000000000000000000000000000000',
- to: receiver,
- tokenId: nextTokenId,
- },
- },
- {
- address,
- event: 'Transfer',
- args: {
- from: '0x0000000000000000000000000000000000000000',
- to: receiver,
- tokenId: String(+nextTokenId + 1),
- },
- },
- {
- address,
- event: 'Transfer',
- args: {
- from: '0x0000000000000000000000000000000000000000',
- to: receiver,
- tokenId: String(+nextTokenId + 2),
- },
- },
- ]);
-
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');
- expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');
- expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');
- }
- });
-});
-
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -16,7 +16,7 @@
import privateKey from '../substrate/privateKey';
import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelper, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';
import nonFungibleAbi from './nonFungibleAbi.json';
import {expect} from 'chai';
import {submitTransactionAsync} from '../substrate/substrate-api';
@@ -75,45 +75,46 @@
describe('NFT: Plain calls', () => {
itWeb3('Can perform mint()', async ({web3, api}) => {
- const collection = await createCollectionExpectSuccess({
- mode: {type: 'NFT'},
- });
- const alice = privateKey('//Alice');
-
- const caller = await createEthAccountWithBalance(api, web3);
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collection, {Ethereum: caller});
- await submitTransactionAsync(alice, changeAdminTx);
+ const owner = await createEthAccountWithBalance(api, web3);
+ const helper = evmCollectionHelper(web3, owner);
+ let result = await helper.methods.create721Collection('Mint collection', '6', '6').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const receiver = createEthAccount(web3);
+ const contract = evmCollection(web3, owner, collectionIdAddress);
+ const nextTokenId = await contract.methods.nextTokenId().call();
- const address = collectionIdToAddress(collection);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+ expect(nextTokenId).to.be.equal('1');
+ result = await contract.methods.mintWithTokenURI(
+ receiver,
+ nextTokenId,
+ 'Test URI',
+ ).send();
- {
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- const result = await contract.methods.mintWithTokenURI(
- receiver,
- nextTokenId,
- 'Test URI',
- ).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = normalizeEvents(result.events);
+ const address = collectionIdToAddress(collectionId);
- expect(events).to.be.deep.equal([
- {
- address,
- event: 'Transfer',
- args: {
- from: '0x0000000000000000000000000000000000000000',
- to: receiver,
- tokenId: nextTokenId,
- },
+ expect(events).to.be.deep.equal([
+ {
+ address,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: receiver,
+ tokenId: nextTokenId,
},
- ]);
+ },
+ ]);
+
+ expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
- }
+ // TODO: this wont work right now, need release 919000 first
+ // await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();
+ // const tokenUri = await contract.methods.tokenURI(nextTokenId).call();
+ // expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);
});
- itWeb3('Can perform mintBulk()', async ({web3, api}) => {
+
+ //TODO: CORE-302 add eth methods
+ itWeb3.skip('Can perform mintBulk()', async ({web3, api}) => {
const collection = await createCollectionExpectSuccess({
mode: {type: 'NFT'},
});
@@ -539,3 +540,33 @@
]);
});
});
+
+describe('Common metadata', () => {
+ itWeb3('Returns collection name', async ({api, web3}) => {
+ const collection = await createCollectionExpectSuccess({
+ name: 'token name',
+ mode: {type: 'NFT'},
+ });
+ const caller = await createEthAccountWithBalance(api, web3);
+
+ const address = collectionIdToAddress(collection);
+ const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+ const name = await contract.methods.name().call();
+
+ expect(name).to.equal('token name');
+ });
+
+ itWeb3('Returns symbol name', async ({api, web3}) => {
+ const collection = await createCollectionExpectSuccess({
+ tokenPrefix: 'TOK',
+ mode: {type: 'NFT'},
+ });
+ const caller = await createEthAccountWithBalance(api, web3);
+
+ const address = collectionIdToAddress(collection);
+ const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+ const symbol = await contract.methods.symbol().call();
+
+ expect(symbol).to.equal('TOK');
+ });
+});
\ No newline at end of file
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -1,738 +1,431 @@
[
- {
- "anonymous": false,
- "inputs": [
- {
- "indexed": true,
- "internalType": "address",
- "name": "owner",
- "type": "address"
- },
- {
- "indexed": true,
- "internalType": "address",
- "name": "approved",
- "type": "address"
- },
- {
- "indexed": true,
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "Approval",
- "type": "event"
- },
- {
- "anonymous": false,
- "inputs": [
- {
- "indexed": true,
- "internalType": "address",
- "name": "owner",
- "type": "address"
- },
- {
- "indexed": true,
- "internalType": "address",
- "name": "operator",
- "type": "address"
- },
- {
- "indexed": false,
- "internalType": "bool",
- "name": "approved",
- "type": "bool"
- }
- ],
- "name": "ApprovalForAll",
- "type": "event"
- },
- {
- "anonymous": false,
- "inputs": [],
- "name": "MintingFinished",
- "type": "event"
- },
- {
- "anonymous": false,
- "inputs": [
- {
- "indexed": true,
- "internalType": "address",
- "name": "from",
- "type": "address"
- },
- {
- "indexed": true,
- "internalType": "address",
- "name": "to",
- "type": "address"
- },
- {
- "indexed": true,
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "Transfer",
- "type": "event"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "approved",
- "type": "address"
- },
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "approve",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "owner",
- "type": "address"
- }
- ],
- "name": "balanceOf",
- "outputs": [
- {
- "internalType": "uint256",
- "name": "",
- "type": "uint256"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "burn",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "from",
- "type": "address"
- },
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "burnFrom",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "string",
- "name": "key",
- "type": "string"
- }
- ],
- "name": "collectionProperty",
- "outputs": [
- {
- "internalType": "bytes",
- "name": "",
- "type": "bytes"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "string",
- "name": "key",
- "type": "string"
- }
- ],
- "name": "deleteCollectionProperty",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- },
- {
- "internalType": "string",
- "name": "key",
- "type": "string"
- }
- ],
- "name": "deleteProperty",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "finishMinting",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "getApproved",
- "outputs": [
- {
- "internalType": "address",
- "name": "",
- "type": "address"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "owner",
- "type": "address"
- },
- {
- "internalType": "address",
- "name": "operator",
- "type": "address"
- }
- ],
- "name": "isApprovedForAll",
- "outputs": [
- {
- "internalType": "address",
- "name": "",
- "type": "address"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "to",
- "type": "address"
- },
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "mint",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "to",
- "type": "address"
- },
- {
- "internalType": "uint256[]",
- "name": "tokenIds",
- "type": "uint256[]"
- }
- ],
- "name": "mintBulk",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "to",
- "type": "address"
- },
- {
- "components": [
- {
- "internalType": "uint256",
- "name": "field_0",
- "type": "uint256"
- },
- {
- "internalType": "string",
- "name": "field_1",
- "type": "string"
- }
- ],
- "internalType": "struct Tuple0[]",
- "name": "tokens",
- "type": "tuple[]"
- }
- ],
- "name": "mintBulkWithTokenURI",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "to",
- "type": "address"
- },
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- },
- {
- "internalType": "string",
- "name": "tokenUri",
- "type": "string"
- }
- ],
- "name": "mintWithTokenURI",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "mintingFinished",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "name",
- "outputs": [
- {
- "internalType": "string",
- "name": "",
- "type": "string"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "nextTokenId",
- "outputs": [
- {
- "internalType": "uint256",
- "name": "",
- "type": "uint256"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "ownerOf",
- "outputs": [
- {
- "internalType": "address",
- "name": "",
- "type": "address"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- },
- {
- "internalType": "string",
- "name": "key",
- "type": "string"
- }
- ],
- "name": "property",
- "outputs": [
- {
- "internalType": "bytes",
- "name": "",
- "type": "bytes"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "from",
- "type": "address"
- },
- {
- "internalType": "address",
- "name": "to",
- "type": "address"
- },
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "safeTransferFrom",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "from",
- "type": "address"
- },
- {
- "internalType": "address",
- "name": "to",
- "type": "address"
- },
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- },
- {
- "internalType": "bytes",
- "name": "data",
- "type": "bytes"
- }
- ],
- "name": "safeTransferFromWithData",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "operator",
- "type": "address"
- },
- {
- "internalType": "bool",
- "name": "approved",
- "type": "bool"
- }
- ],
- "name": "setApprovalForAll",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "string",
- "name": "key",
- "type": "string"
- },
- {
- "internalType": "bytes",
- "name": "value",
- "type": "bytes"
- }
- ],
- "name": "setCollectionProperty",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- },
- {
- "internalType": "string",
- "name": "key",
- "type": "string"
- },
- {
- "internalType": "bytes",
- "name": "value",
- "type": "bytes"
- }
- ],
- "name": "setProperty",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "string",
- "name": "key",
- "type": "string"
- },
- {
- "internalType": "bool",
- "name": "isMutable",
- "type": "bool"
- },
- {
- "internalType": "bool",
- "name": "collectionAdmin",
- "type": "bool"
- },
- {
- "internalType": "bool",
- "name": "tokenOwner",
- "type": "bool"
- }
- ],
- "name": "setTokenPropertyPermission",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "bytes4",
- "name": "interfaceID",
- "type": "bytes4"
- }
- ],
- "name": "supportsInterface",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "symbol",
- "outputs": [
- {
- "internalType": "string",
- "name": "",
- "type": "string"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "uint256",
- "name": "index",
- "type": "uint256"
- }
- ],
- "name": "tokenByIndex",
- "outputs": [
- {
- "internalType": "uint256",
- "name": "",
- "type": "uint256"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "owner",
- "type": "address"
- },
- {
- "internalType": "uint256",
- "name": "index",
- "type": "uint256"
- }
- ],
- "name": "tokenOfOwnerByIndex",
- "outputs": [
- {
- "internalType": "uint256",
- "name": "",
- "type": "uint256"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "tokenURI",
- "outputs": [
- {
- "internalType": "string",
- "name": "",
- "type": "string"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "totalSupply",
- "outputs": [
- {
- "internalType": "uint256",
- "name": "",
- "type": "uint256"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "to",
- "type": "address"
- },
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "transfer",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "from",
- "type": "address"
- },
- {
- "internalType": "address",
- "name": "to",
- "type": "address"
- },
- {
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "transferFrom",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- }
-]
\ No newline at end of file
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "owner",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "approved",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "uint256",
+ "name": "tokenId",
+ "type": "uint256"
+ }
+ ],
+ "name": "Approval",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "owner",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "operator",
+ "type": "address"
+ },
+ {
+ "indexed": false,
+ "internalType": "bool",
+ "name": "approved",
+ "type": "bool"
+ }
+ ],
+ "name": "ApprovalForAll",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
+ "inputs": [],
+ "name": "MintingFinished",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "from",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "to",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "uint256",
+ "name": "tokenId",
+ "type": "uint256"
+ }
+ ],
+ "name": "Transfer",
+ "type": "event"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "approved", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "approve",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "owner", "type": "address" }
+ ],
+ "name": "balanceOf",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "burn",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "burnFrom",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
+ "name": "collectionProperty",
+ "outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "contractAddress",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
+ "name": "deleteCollectionProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "key", "type": "string" }
+ ],
+ "name": "deleteProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "ethConfirmSponsorship",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "sponsor", "type": "address" }
+ ],
+ "name": "ethSetSponsor",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "finishMinting",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "getApproved",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "owner", "type": "address" },
+ { "internalType": "address", "name": "operator", "type": "address" }
+ ],
+ "name": "isApprovedForAll",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "mint",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256[]", "name": "tokenIds", "type": "uint256[]" }
+ ],
+ "name": "mintBulk",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ {
+ "components": [
+ { "internalType": "uint256", "name": "field_0", "type": "uint256" },
+ { "internalType": "string", "name": "field_1", "type": "string" }
+ ],
+ "internalType": "struct Tuple0[]",
+ "name": "tokens",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "mintBulkWithTokenURI",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "tokenUri", "type": "string" }
+ ],
+ "name": "mintWithTokenURI",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "mintingFinished",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "name",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "nextTokenId",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "ownerOf",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "key", "type": "string" }
+ ],
+ "name": "property",
+ "outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "safeTransferFrom",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "bytes", "name": "data", "type": "bytes" }
+ ],
+ "name": "safeTransferFromWithData",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "operator", "type": "address" },
+ { "internalType": "bool", "name": "approved", "type": "bool" }
+ ],
+ "name": "setApprovalForAll",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+ ],
+ "name": "setCollectionProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "limit", "type": "string" },
+ { "internalType": "string", "name": "value", "type": "string" }
+ ],
+ "name": "setLimit",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+ ],
+ "name": "setProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bool", "name": "isMutable", "type": "bool" },
+ { "internalType": "bool", "name": "collectionAdmin", "type": "bool" },
+ { "internalType": "bool", "name": "tokenOwner", "type": "bool" }
+ ],
+ "name": "setTokenPropertyPermission",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
+ ],
+ "name": "supportsInterface",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "symbol",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "index", "type": "uint256" }
+ ],
+ "name": "tokenByIndex",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "owner", "type": "address" },
+ { "internalType": "uint256", "name": "index", "type": "uint256" }
+ ],
+ "name": "tokenOfOwnerByIndex",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "tokenURI",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "totalSupply",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "transfer",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "transferFrom",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ }
+]
tests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -88,7 +88,8 @@
});
describe('NFT (Via EVM proxy): Plain calls', () => {
- itWeb3('Can perform mint()', async ({web3, api}) => {
+ //TODO: CORE-302 add eth methods
+ itWeb3.skip('Can perform mint()', async ({web3, api}) => {
const collection = await createCollectionExpectSuccess({
mode: {type: 'NFT'},
});
@@ -127,7 +128,9 @@
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
}
});
- itWeb3('Can perform mintBulk()', async ({web3, api}) => {
+
+ //TODO: CORE-302 add eth methods
+ itWeb3.skip('Can perform mintBulk()', async ({web3, api}) => {
const collection = await createCollectionExpectSuccess({
mode: {type: 'NFT'},
});
tests/src/eth/util/contractHelpersAbi.jsondiffbeforeafterboth--- a/tests/src/eth/util/contractHelpersAbi.json
+++ b/tests/src/eth/util/contractHelpersAbi.json
@@ -1,216 +1,161 @@
[
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contract",
- "type": "address"
- }
- ],
- "name": "allowlistEnabled",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "target",
- "type": "address"
- },
- {
- "internalType": "address",
- "name": "caller",
- "type": "address"
- }
- ],
- "name": "allowed",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "target",
- "type": "address"
- }
- ],
- "name": "contractOwner",
- "outputs": [
- {
- "internalType": "address",
- "name": "",
- "type": "address"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "target",
- "type": "address"
- }
- ],
- "name": "sponsoringEnabled",
- "outputs": [
- {
- "internalType": "bool",
- "name": "",
- "type": "bool"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "target",
- "type": "address"
- },
- {
- "internalType": "address",
- "name": "user",
- "type": "address"
- },
- {
- "internalType": "bool",
- "name": "isAllowed",
- "type": "bool"
- }
- ],
- "name": "toggleAllowed",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "target",
- "type": "address"
- },
- {
- "internalType": "bool",
- "name": "enabled",
- "type": "bool"
- }
- ],
- "name": "toggleAllowlist",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "target",
- "type": "address"
- },
- {
- "internalType": "bool",
- "name": "enabled",
- "type": "bool"
- }
- ],
- "name": "toggleSponsoring",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "target",
- "type": "address"
- },
- {
- "internalType": "uint8",
- "name": "mode",
- "type": "uint8"
- }
- ],
- "name": "setSponsoringMode",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "target",
- "type": "address"
- }
- ],
- "name": "sponsoringMode",
- "outputs": [
- {
- "internalType": "uint8",
- "name": "",
- "type": "uint8"
- }
- ],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "target",
- "type": "address"
- },
- {
- "internalType": "uint32",
- "name": "limit",
- "type": "uint32"
- }
- ],
- "name": "setSponsoringRateLimit",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- }
- ],
- "name": "getSponsoringRateLimit",
- "outputs": [
- {
- "internalType": "uint32",
- "name": "",
- "type": "uint32"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- }
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ },
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "allowed",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ }
+ ],
+ "name": "allowlistEnabled",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ }
+ ],
+ "name": "contractOwner",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ }
+ ],
+ "name": "getSponsoringRateLimit",
+ "outputs": [{ "internalType": "uint32", "name": "", "type": "uint32" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ },
+ { "internalType": "uint8", "name": "mode", "type": "uint8" }
+ ],
+ "name": "setSponsoringMode",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ },
+ { "internalType": "uint32", "name": "rateLimit", "type": "uint32" }
+ ],
+ "name": "setSponsoringRateLimit",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ }
+ ],
+ "name": "sponsoringEnabled",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ }
+ ],
+ "name": "sponsoringMode",
+ "outputs": [{ "internalType": "uint8", "name": "", "type": "uint8" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
+ ],
+ "name": "supportsInterface",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ },
+ { "internalType": "address", "name": "user", "type": "address" },
+ { "internalType": "bool", "name": "allowed", "type": "bool" }
+ ],
+ "name": "toggleAllowed",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ },
+ { "internalType": "bool", "name": "enabled", "type": "bool" }
+ ],
+ "name": "toggleAllowlist",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "contractAddress",
+ "type": "address"
+ },
+ { "internalType": "bool", "name": "enabled", "type": "bool" }
+ ],
+ "name": "toggleSponsoring",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ }
]
tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -23,11 +23,13 @@
import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';
import {IKeyringPair} from '@polkadot/types/types';
import {expect} from 'chai';
-import {CrossAccountId, getGenericResult, UNIQUE} from '../../util/helpers';
+import {CrossAccountId, getDetailedCollectionInfo, getGenericResult, UNIQUE} from '../../util/helpers';
import * as solc from 'solc';
import config from '../../config';
import privateKey from '../../substrate/privateKey';
import contractHelpersAbi from './contractHelpersAbi.json';
+import nonFungibleAbi from '../nonFungibleAbi.json';
+import collectionHelperAbi from '../collectionHelperAbi.json';
import getBalance from '../../substrate/get-balance';
import waitNewBlocks from '../../substrate/wait-new-blocks';
@@ -66,12 +68,30 @@
];
}
+export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {
+ const collectionIdAddress = normalizeAddress(result.events[0].raw.topics[2]);
+ const collectionId = collectionIdFromAddress(collectionIdAddress);
+ const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ return {collectionIdAddress, collectionId, collection};
+}
+
export function collectionIdToAddress(collection: number): string {
const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
...encodeIntBE(collection),
]);
return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
}
+export function collectionIdFromAddress(address: string): number {
+ if (!address.startsWith('0x'))
+ throw 'address not starts with "0x"';
+ if (address.length > 42)
+ throw 'address length is more than 20 bytes';
+ return Number('0x' + address.substring(address.length - 8));
+}
+
+export function normalizeAddress(address: string): string {
+ return '0x' + address.substring(address.length - 40);
+}
export function tokenIdToAddress(collection: number, token: number): string {
const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
@@ -271,6 +291,26 @@
return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});
}
+/**
+ * evm collection helper
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function evmCollectionHelper(web3: Web3, caller: string) {
+ return new web3.eth.Contract(collectionHelperAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+}
+
+/**
+ * evm collection
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function evmCollection(web3: Web3, caller: string, collection: string) {
+ return new web3.eth.Contract(nonFungibleAbi as any, collection, {from: caller, ...GAS_ARGS});
+}
+
/**
* Execute ethereum method call using substrate account
* @param to target contract
tests/src/interfaces/augment-types.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -1,7 +1,6 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
-import type { CumulusPalletDmpQueueCall, CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueueError, CumulusPalletDmpQueueEvent, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemCall, CumulusPalletParachainSystemError, CumulusPalletParachainSystemEvent, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmCall, CumulusPalletXcmError, CumulusPalletXcmEvent, CumulusPalletXcmpQueueCall, CumulusPalletXcmpQueueError, CumulusPalletXcmpQueueEvent, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueInboundState, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueOutboundState, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, EthbloomBloom, EthereumBlock, EthereumHeader, EthereumLog, EthereumReceiptEip658ReceiptData, EthereumReceiptReceiptV3, EthereumTransactionAccessListItem, EthereumTransactionEip1559Transaction, EthereumTransactionEip2930Transaction, EthereumTransactionLegacyTransaction, EthereumTransactionTransactionAction, EthereumTransactionTransactionSignature, EthereumTransactionTransactionV2, EthereumTypesHashH64, EvmCoreErrorExitError, EvmCoreErrorExitFatal, EvmCoreErrorExitReason, EvmCoreErrorExitRevert, EvmCoreErrorExitSucceed, FpRpcTransactionStatus, FrameSupportPalletId, FrameSupportTokensMiscBalanceStatus, FrameSupportWeightsDispatchClass, FrameSupportWeightsDispatchInfo, FrameSupportWeightsPays, FrameSupportWeightsPerDispatchClassU32, FrameSupportWeightsPerDispatchClassU64, FrameSupportWeightsPerDispatchClassWeightsPerClass, FrameSupportWeightsRuntimeDbWeight, FrameSupportWeightsWeightToFeeCoefficient, FrameSystemAccountInfo, FrameSystemCall, FrameSystemError, FrameSystemEvent, FrameSystemEventRecord, FrameSystemExtensionsCheckGenesis, FrameSystemExtensionsCheckNonce, FrameSystemExtensionsCheckSpecVersion, FrameSystemExtensionsCheckWeight, FrameSystemLastRuntimeUpgradeInfo, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, FrameSystemLimitsWeightsPerClass, FrameSystemPhase, OpalRuntimeRuntime, OrmlVestingModuleCall, OrmlVestingModuleError, OrmlVestingModuleEvent, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesCall, PalletBalancesError, PalletBalancesEvent, PalletBalancesReasons, PalletBalancesReleases, PalletBalancesReserveData, PalletCommonError, PalletCommonEvent, PalletEthereumCall, PalletEthereumError, PalletEthereumEvent, PalletEthereumFakeTransactionFinalizer, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmCall, PalletEvmCoderSubstrateError, PalletEvmContractHelpersError, PalletEvmContractHelpersSponsoringModeT, PalletEvmError, PalletEvmEvent, PalletEvmMigrationCall, PalletEvmMigrationError, PalletFungibleError, PalletInflationCall, PalletNonfungibleError, PalletNonfungibleItemData, PalletRefungibleError, PalletRefungibleItemData, PalletRmrkCoreCall, PalletRmrkCoreError, PalletRmrkCoreEvent, PalletRmrkEquipCall, PalletRmrkEquipError, PalletRmrkEquipEvent, PalletStructureCall, PalletStructureError, PalletStructureEvent, PalletSudoCall, PalletSudoError, PalletSudoEvent, PalletTemplateTransactionPaymentCall, PalletTemplateTransactionPaymentChargeTransactionPayment, PalletTimestampCall, PalletTransactionPaymentReleases, PalletTreasuryCall, PalletTreasuryError, PalletTreasuryEvent, PalletTreasuryProposal, PalletUniqueCall, PalletUniqueError, PalletUniqueRawEvent, PalletXcmCall, PalletXcmError, PalletXcmEvent, PhantomTypeUpDataStructsBaseInfo, PhantomTypeUpDataStructsCollectionInfo, PhantomTypeUpDataStructsNftChild, PhantomTypeUpDataStructsNftInfo, PhantomTypeUpDataStructsPartType, PhantomTypeUpDataStructsPropertyInfo, PhantomTypeUpDataStructsResourceInfo, PhantomTypeUpDataStructsRpcCollection, PhantomTypeUpDataStructsTheme, PhantomTypeUpDataStructsTokenData, PolkadotCorePrimitivesInboundDownwardMessage, PolkadotCorePrimitivesInboundHrmpMessage, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2AbridgedHrmpChannel, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpCoreEcdsaSignature, SpCoreEd25519Signature, SpCoreSr25519Signature, SpRuntimeArithmeticError, SpRuntimeDigest, SpRuntimeDigestDigestItem, SpRuntimeDispatchError, SpRuntimeModuleError, SpRuntimeMultiSignature, SpRuntimeTokenError, SpRuntimeTransactionalError, SpTrieStorageProof, SpVersionRuntimeVersion, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionField, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionStats, UpDataStructsCreateCollectionData, UpDataStructsCreateFungibleData, UpDataStructsCreateItemData, UpDataStructsCreateItemExData, UpDataStructsCreateNftData, UpDataStructsCreateNftExData, UpDataStructsCreateReFungibleData, UpDataStructsCreateRefungibleExData, UpDataStructsNestingRule, UpDataStructsProperties, UpDataStructsPropertiesMapBoundedVec, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsProperty, UpDataStructsPropertyKeyPermission, UpDataStructsPropertyPermission, UpDataStructsRmrkAccountIdOrCollectionNftTuple, UpDataStructsRmrkBaseInfo, UpDataStructsRmrkBasicResource, UpDataStructsRmrkCollectionInfo, UpDataStructsRmrkComposableResource, UpDataStructsRmrkEquippableList, UpDataStructsRmrkFixedPart, UpDataStructsRmrkNftChild, UpDataStructsRmrkNftInfo, UpDataStructsRmrkPartType, UpDataStructsRmrkPropertyInfo, UpDataStructsRmrkResourceInfo, UpDataStructsRmrkResourceTypes, UpDataStructsRmrkRoyaltyInfo, UpDataStructsRmrkSlotPart, UpDataStructsRmrkSlotResource, UpDataStructsRmrkTheme, UpDataStructsRmrkThemeProperty, UpDataStructsRpcCollection, UpDataStructsSchemaVersion, UpDataStructsSponsoringRateLimit, UpDataStructsSponsorshipState, UpDataStructsTokenData, XcmDoubleEncoded, XcmV0Junction, XcmV0JunctionBodyId, XcmV0JunctionBodyPart, XcmV0JunctionNetworkId, XcmV0MultiAsset, XcmV0MultiLocation, XcmV0Order, XcmV0OriginKind, XcmV0Response, XcmV0Xcm, XcmV1Junction, XcmV1MultiAsset, XcmV1MultiLocation, XcmV1MultiassetAssetId, XcmV1MultiassetAssetInstance, XcmV1MultiassetFungibility, XcmV1MultiassetMultiAssetFilter, XcmV1MultiassetMultiAssets, XcmV1MultiassetWildFungibility, XcmV1MultiassetWildMultiAsset, XcmV1MultilocationJunctions, XcmV1Order, XcmV1Response, XcmV1Xcm, XcmV2Instruction, XcmV2Response, XcmV2TraitsError, XcmV2TraitsOutcome, XcmV2WeightLimit, XcmV2Xcm, XcmVersionedMultiAssets, XcmVersionedMultiLocation, XcmVersionedXcm } from './unique';
import type { Data, StorageKey } from '@polkadot/types';
import type { BitVec, Bool, Bytes, I128, I16, I256, I32, I64, I8, Json, Null, Raw, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types-codec';
import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';
@@ -291,27 +290,6 @@
CoreOccupied: CoreOccupied;
CrateVersion: CrateVersion;
CreatedBlock: CreatedBlock;
- CumulusPalletDmpQueueCall: CumulusPalletDmpQueueCall;
- CumulusPalletDmpQueueConfigData: CumulusPalletDmpQueueConfigData;
- CumulusPalletDmpQueueError: CumulusPalletDmpQueueError;
- CumulusPalletDmpQueueEvent: CumulusPalletDmpQueueEvent;
- CumulusPalletDmpQueuePageIndexData: CumulusPalletDmpQueuePageIndexData;
- CumulusPalletParachainSystemCall: CumulusPalletParachainSystemCall;
- CumulusPalletParachainSystemError: CumulusPalletParachainSystemError;
- CumulusPalletParachainSystemEvent: CumulusPalletParachainSystemEvent;
- CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot: CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot;
- CumulusPalletXcmCall: CumulusPalletXcmCall;
- CumulusPalletXcmError: CumulusPalletXcmError;
- CumulusPalletXcmEvent: CumulusPalletXcmEvent;
- CumulusPalletXcmpQueueCall: CumulusPalletXcmpQueueCall;
- CumulusPalletXcmpQueueError: CumulusPalletXcmpQueueError;
- CumulusPalletXcmpQueueEvent: CumulusPalletXcmpQueueEvent;
- CumulusPalletXcmpQueueInboundChannelDetails: CumulusPalletXcmpQueueInboundChannelDetails;
- CumulusPalletXcmpQueueInboundState: CumulusPalletXcmpQueueInboundState;
- CumulusPalletXcmpQueueOutboundChannelDetails: CumulusPalletXcmpQueueOutboundChannelDetails;
- CumulusPalletXcmpQueueOutboundState: CumulusPalletXcmpQueueOutboundState;
- CumulusPalletXcmpQueueQueueConfigData: CumulusPalletXcmpQueueQueueConfigData;
- CumulusPrimitivesParachainInherentParachainInherentData: CumulusPrimitivesParachainInherentParachainInherentData;
Data: Data;
DeferredOffenceOf: DeferredOffenceOf;
DefunctVoter: DefunctVoter;
@@ -378,25 +356,11 @@
EthAddress: EthAddress;
EthBlock: EthBlock;
EthBloom: EthBloom;
- EthbloomBloom: EthbloomBloom;
EthCallRequest: EthCallRequest;
EthereumAccountId: EthereumAccountId;
EthereumAddress: EthereumAddress;
- EthereumBlock: EthereumBlock;
- EthereumHeader: EthereumHeader;
- EthereumLog: EthereumLog;
EthereumLookupSource: EthereumLookupSource;
- EthereumReceiptEip658ReceiptData: EthereumReceiptEip658ReceiptData;
- EthereumReceiptReceiptV3: EthereumReceiptReceiptV3;
EthereumSignature: EthereumSignature;
- EthereumTransactionAccessListItem: EthereumTransactionAccessListItem;
- EthereumTransactionEip1559Transaction: EthereumTransactionEip1559Transaction;
- EthereumTransactionEip2930Transaction: EthereumTransactionEip2930Transaction;
- EthereumTransactionLegacyTransaction: EthereumTransactionLegacyTransaction;
- EthereumTransactionTransactionAction: EthereumTransactionTransactionAction;
- EthereumTransactionTransactionSignature: EthereumTransactionTransactionSignature;
- EthereumTransactionTransactionV2: EthereumTransactionTransactionV2;
- EthereumTypesHashH64: EthereumTypesHashH64;
EthFilter: EthFilter;
EthFilterAddress: EthFilterAddress;
EthFilterChanges: EthFilterChanges;
@@ -433,11 +397,6 @@
EventMetadataV9: EventMetadataV9;
EventRecord: EventRecord;
EvmAccount: EvmAccount;
- EvmCoreErrorExitError: EvmCoreErrorExitError;
- EvmCoreErrorExitFatal: EvmCoreErrorExitFatal;
- EvmCoreErrorExitReason: EvmCoreErrorExitReason;
- EvmCoreErrorExitRevert: EvmCoreErrorExitRevert;
- EvmCoreErrorExitSucceed: EvmCoreErrorExitSucceed;
EvmLog: EvmLog;
EvmVicinity: EvmVicinity;
ExecReturnValue: ExecReturnValue;
@@ -476,31 +435,6 @@
Forcing: Forcing;
ForkTreePendingChange: ForkTreePendingChange;
ForkTreePendingChangeNode: ForkTreePendingChangeNode;
- FpRpcTransactionStatus: FpRpcTransactionStatus;
- FrameSupportPalletId: FrameSupportPalletId;
- FrameSupportTokensMiscBalanceStatus: FrameSupportTokensMiscBalanceStatus;
- FrameSupportWeightsDispatchClass: FrameSupportWeightsDispatchClass;
- FrameSupportWeightsDispatchInfo: FrameSupportWeightsDispatchInfo;
- FrameSupportWeightsPays: FrameSupportWeightsPays;
- FrameSupportWeightsPerDispatchClassU32: FrameSupportWeightsPerDispatchClassU32;
- FrameSupportWeightsPerDispatchClassU64: FrameSupportWeightsPerDispatchClassU64;
- FrameSupportWeightsPerDispatchClassWeightsPerClass: FrameSupportWeightsPerDispatchClassWeightsPerClass;
- FrameSupportWeightsRuntimeDbWeight: FrameSupportWeightsRuntimeDbWeight;
- FrameSupportWeightsWeightToFeeCoefficient: FrameSupportWeightsWeightToFeeCoefficient;
- FrameSystemAccountInfo: FrameSystemAccountInfo;
- FrameSystemCall: FrameSystemCall;
- FrameSystemError: FrameSystemError;
- FrameSystemEvent: FrameSystemEvent;
- FrameSystemEventRecord: FrameSystemEventRecord;
- FrameSystemExtensionsCheckGenesis: FrameSystemExtensionsCheckGenesis;
- FrameSystemExtensionsCheckNonce: FrameSystemExtensionsCheckNonce;
- FrameSystemExtensionsCheckSpecVersion: FrameSystemExtensionsCheckSpecVersion;
- FrameSystemExtensionsCheckWeight: FrameSystemExtensionsCheckWeight;
- FrameSystemLastRuntimeUpgradeInfo: FrameSystemLastRuntimeUpgradeInfo;
- FrameSystemLimitsBlockLength: FrameSystemLimitsBlockLength;
- FrameSystemLimitsBlockWeights: FrameSystemLimitsBlockWeights;
- FrameSystemLimitsWeightsPerClass: FrameSystemLimitsWeightsPerClass;
- FrameSystemPhase: FrameSystemPhase;
FullIdentification: FullIdentification;
FunctionArgumentMetadataLatest: FunctionArgumentMetadataLatest;
FunctionArgumentMetadataV10: FunctionArgumentMetadataV10;
@@ -716,7 +650,6 @@
OffchainAccuracyCompact: OffchainAccuracyCompact;
OffenceDetails: OffenceDetails;
Offender: Offender;
- OpalRuntimeRuntime: OpalRuntimeRuntime;
OpaqueCall: OpaqueCall;
OpaqueMultiaddr: OpaqueMultiaddr;
OpaqueNetworkState: OpaqueNetworkState;
@@ -732,10 +665,6 @@
OriginKindV0: OriginKindV0;
OriginKindV1: OriginKindV1;
OriginKindV2: OriginKindV2;
- OrmlVestingModuleCall: OrmlVestingModuleCall;
- OrmlVestingModuleError: OrmlVestingModuleError;
- OrmlVestingModuleEvent: OrmlVestingModuleEvent;
- OrmlVestingVestingSchedule: OrmlVestingVestingSchedule;
OutboundHrmpMessage: OutboundHrmpMessage;
OutboundLaneData: OutboundLaneData;
OutboundMessageFee: OutboundMessageFee;
@@ -746,76 +675,21 @@
Owner: Owner;
PageCounter: PageCounter;
PageIndexData: PageIndexData;
- PalletBalancesAccountData: PalletBalancesAccountData;
- PalletBalancesBalanceLock: PalletBalancesBalanceLock;
- PalletBalancesCall: PalletBalancesCall;
- PalletBalancesError: PalletBalancesError;
- PalletBalancesEvent: PalletBalancesEvent;
- PalletBalancesReasons: PalletBalancesReasons;
- PalletBalancesReleases: PalletBalancesReleases;
- PalletBalancesReserveData: PalletBalancesReserveData;
PalletCallMetadataLatest: PalletCallMetadataLatest;
PalletCallMetadataV14: PalletCallMetadataV14;
- PalletCommonError: PalletCommonError;
- PalletCommonEvent: PalletCommonEvent;
PalletConstantMetadataLatest: PalletConstantMetadataLatest;
PalletConstantMetadataV14: PalletConstantMetadataV14;
PalletErrorMetadataLatest: PalletErrorMetadataLatest;
PalletErrorMetadataV14: PalletErrorMetadataV14;
- PalletEthereumCall: PalletEthereumCall;
- PalletEthereumError: PalletEthereumError;
- PalletEthereumEvent: PalletEthereumEvent;
- PalletEthereumFakeTransactionFinalizer: PalletEthereumFakeTransactionFinalizer;
PalletEventMetadataLatest: PalletEventMetadataLatest;
PalletEventMetadataV14: PalletEventMetadataV14;
- PalletEvmAccountBasicCrossAccountIdRepr: PalletEvmAccountBasicCrossAccountIdRepr;
- PalletEvmCall: PalletEvmCall;
- PalletEvmCoderSubstrateError: PalletEvmCoderSubstrateError;
- PalletEvmContractHelpersError: PalletEvmContractHelpersError;
- PalletEvmContractHelpersSponsoringModeT: PalletEvmContractHelpersSponsoringModeT;
- PalletEvmError: PalletEvmError;
- PalletEvmEvent: PalletEvmEvent;
- PalletEvmMigrationCall: PalletEvmMigrationCall;
- PalletEvmMigrationError: PalletEvmMigrationError;
- PalletFungibleError: PalletFungibleError;
PalletId: PalletId;
- PalletInflationCall: PalletInflationCall;
PalletMetadataLatest: PalletMetadataLatest;
PalletMetadataV14: PalletMetadataV14;
- PalletNonfungibleError: PalletNonfungibleError;
- PalletNonfungibleItemData: PalletNonfungibleItemData;
- PalletRefungibleError: PalletRefungibleError;
- PalletRefungibleItemData: PalletRefungibleItemData;
- PalletRmrkCoreCall: PalletRmrkCoreCall;
- PalletRmrkCoreError: PalletRmrkCoreError;
- PalletRmrkCoreEvent: PalletRmrkCoreEvent;
- PalletRmrkEquipCall: PalletRmrkEquipCall;
- PalletRmrkEquipError: PalletRmrkEquipError;
- PalletRmrkEquipEvent: PalletRmrkEquipEvent;
PalletsOrigin: PalletsOrigin;
PalletStorageMetadataLatest: PalletStorageMetadataLatest;
PalletStorageMetadataV14: PalletStorageMetadataV14;
- PalletStructureCall: PalletStructureCall;
- PalletStructureError: PalletStructureError;
- PalletStructureEvent: PalletStructureEvent;
- PalletSudoCall: PalletSudoCall;
- PalletSudoError: PalletSudoError;
- PalletSudoEvent: PalletSudoEvent;
- PalletTemplateTransactionPaymentCall: PalletTemplateTransactionPaymentCall;
- PalletTemplateTransactionPaymentChargeTransactionPayment: PalletTemplateTransactionPaymentChargeTransactionPayment;
- PalletTimestampCall: PalletTimestampCall;
- PalletTransactionPaymentReleases: PalletTransactionPaymentReleases;
- PalletTreasuryCall: PalletTreasuryCall;
- PalletTreasuryError: PalletTreasuryError;
- PalletTreasuryEvent: PalletTreasuryEvent;
- PalletTreasuryProposal: PalletTreasuryProposal;
- PalletUniqueCall: PalletUniqueCall;
- PalletUniqueError: PalletUniqueError;
- PalletUniqueRawEvent: PalletUniqueRawEvent;
PalletVersion: PalletVersion;
- PalletXcmCall: PalletXcmCall;
- PalletXcmError: PalletXcmError;
- PalletXcmEvent: PalletXcmEvent;
ParachainDispatchOrigin: ParachainDispatchOrigin;
ParachainInherentData: ParachainInherentData;
ParachainProposal: ParachainProposal;
@@ -855,27 +729,9 @@
PerU16: PerU16;
Phantom: Phantom;
PhantomData: PhantomData;
- PhantomTypeUpDataStructsBaseInfo: PhantomTypeUpDataStructsBaseInfo;
- PhantomTypeUpDataStructsCollectionInfo: PhantomTypeUpDataStructsCollectionInfo;
- PhantomTypeUpDataStructsNftChild: PhantomTypeUpDataStructsNftChild;
- PhantomTypeUpDataStructsNftInfo: PhantomTypeUpDataStructsNftInfo;
- PhantomTypeUpDataStructsPartType: PhantomTypeUpDataStructsPartType;
- PhantomTypeUpDataStructsPropertyInfo: PhantomTypeUpDataStructsPropertyInfo;
- PhantomTypeUpDataStructsResourceInfo: PhantomTypeUpDataStructsResourceInfo;
- PhantomTypeUpDataStructsRpcCollection: PhantomTypeUpDataStructsRpcCollection;
- PhantomTypeUpDataStructsTheme: PhantomTypeUpDataStructsTheme;
- PhantomTypeUpDataStructsTokenData: PhantomTypeUpDataStructsTokenData;
Phase: Phase;
PhragmenScore: PhragmenScore;
Points: Points;
- PolkadotCorePrimitivesInboundDownwardMessage: PolkadotCorePrimitivesInboundDownwardMessage;
- PolkadotCorePrimitivesInboundHrmpMessage: PolkadotCorePrimitivesInboundHrmpMessage;
- PolkadotCorePrimitivesOutboundHrmpMessage: PolkadotCorePrimitivesOutboundHrmpMessage;
- PolkadotParachainPrimitivesXcmpMessageFormat: PolkadotParachainPrimitivesXcmpMessageFormat;
- PolkadotPrimitivesV2AbridgedHostConfiguration: PolkadotPrimitivesV2AbridgedHostConfiguration;
- PolkadotPrimitivesV2AbridgedHrmpChannel: PolkadotPrimitivesV2AbridgedHrmpChannel;
- PolkadotPrimitivesV2PersistedValidationData: PolkadotPrimitivesV2PersistedValidationData;
- PolkadotPrimitivesV2UpgradeRestriction: PolkadotPrimitivesV2UpgradeRestriction;
PortableType: PortableType;
PortableTypeV14: PortableTypeV14;
Precommits: Precommits;
@@ -1071,20 +927,7 @@
SolutionSupports: SolutionSupports;
SpanIndex: SpanIndex;
SpanRecord: SpanRecord;
- SpCoreEcdsaSignature: SpCoreEcdsaSignature;
- SpCoreEd25519Signature: SpCoreEd25519Signature;
- SpCoreSr25519Signature: SpCoreSr25519Signature;
SpecVersion: SpecVersion;
- SpRuntimeArithmeticError: SpRuntimeArithmeticError;
- SpRuntimeDigest: SpRuntimeDigest;
- SpRuntimeDigestDigestItem: SpRuntimeDigestDigestItem;
- SpRuntimeDispatchError: SpRuntimeDispatchError;
- SpRuntimeModuleError: SpRuntimeModuleError;
- SpRuntimeMultiSignature: SpRuntimeMultiSignature;
- SpRuntimeTokenError: SpRuntimeTokenError;
- SpRuntimeTransactionalError: SpRuntimeTransactionalError;
- SpTrieStorageProof: SpTrieStorageProof;
- SpVersionRuntimeVersion: SpVersionRuntimeVersion;
Sr25519Signature: Sr25519Signature;
StakingLedger: StakingLedger;
StakingLedgerTo223: StakingLedgerTo223;
@@ -1181,50 +1024,6 @@
UnlockChunk: UnlockChunk;
UnrewardedRelayer: UnrewardedRelayer;
UnrewardedRelayersState: UnrewardedRelayersState;
- UpDataStructsAccessMode: UpDataStructsAccessMode;
- UpDataStructsCollection: UpDataStructsCollection;
- UpDataStructsCollectionField: UpDataStructsCollectionField;
- UpDataStructsCollectionLimits: UpDataStructsCollectionLimits;
- UpDataStructsCollectionMode: UpDataStructsCollectionMode;
- UpDataStructsCollectionStats: UpDataStructsCollectionStats;
- UpDataStructsCreateCollectionData: UpDataStructsCreateCollectionData;
- UpDataStructsCreateFungibleData: UpDataStructsCreateFungibleData;
- UpDataStructsCreateItemData: UpDataStructsCreateItemData;
- UpDataStructsCreateItemExData: UpDataStructsCreateItemExData;
- UpDataStructsCreateNftData: UpDataStructsCreateNftData;
- UpDataStructsCreateNftExData: UpDataStructsCreateNftExData;
- UpDataStructsCreateReFungibleData: UpDataStructsCreateReFungibleData;
- UpDataStructsCreateRefungibleExData: UpDataStructsCreateRefungibleExData;
- UpDataStructsNestingRule: UpDataStructsNestingRule;
- UpDataStructsProperties: UpDataStructsProperties;
- UpDataStructsPropertiesMapBoundedVec: UpDataStructsPropertiesMapBoundedVec;
- UpDataStructsPropertiesMapPropertyPermission: UpDataStructsPropertiesMapPropertyPermission;
- UpDataStructsProperty: UpDataStructsProperty;
- UpDataStructsPropertyKeyPermission: UpDataStructsPropertyKeyPermission;
- UpDataStructsPropertyPermission: UpDataStructsPropertyPermission;
- UpDataStructsRmrkAccountIdOrCollectionNftTuple: UpDataStructsRmrkAccountIdOrCollectionNftTuple;
- UpDataStructsRmrkBaseInfo: UpDataStructsRmrkBaseInfo;
- UpDataStructsRmrkBasicResource: UpDataStructsRmrkBasicResource;
- UpDataStructsRmrkCollectionInfo: UpDataStructsRmrkCollectionInfo;
- UpDataStructsRmrkComposableResource: UpDataStructsRmrkComposableResource;
- UpDataStructsRmrkEquippableList: UpDataStructsRmrkEquippableList;
- UpDataStructsRmrkFixedPart: UpDataStructsRmrkFixedPart;
- UpDataStructsRmrkNftChild: UpDataStructsRmrkNftChild;
- UpDataStructsRmrkNftInfo: UpDataStructsRmrkNftInfo;
- UpDataStructsRmrkPartType: UpDataStructsRmrkPartType;
- UpDataStructsRmrkPropertyInfo: UpDataStructsRmrkPropertyInfo;
- UpDataStructsRmrkResourceInfo: UpDataStructsRmrkResourceInfo;
- UpDataStructsRmrkResourceTypes: UpDataStructsRmrkResourceTypes;
- UpDataStructsRmrkRoyaltyInfo: UpDataStructsRmrkRoyaltyInfo;
- UpDataStructsRmrkSlotPart: UpDataStructsRmrkSlotPart;
- UpDataStructsRmrkSlotResource: UpDataStructsRmrkSlotResource;
- UpDataStructsRmrkTheme: UpDataStructsRmrkTheme;
- UpDataStructsRmrkThemeProperty: UpDataStructsRmrkThemeProperty;
- UpDataStructsRpcCollection: UpDataStructsRpcCollection;
- UpDataStructsSchemaVersion: UpDataStructsSchemaVersion;
- UpDataStructsSponsoringRateLimit: UpDataStructsSponsoringRateLimit;
- UpDataStructsSponsorshipState: UpDataStructsSponsorshipState;
- UpDataStructsTokenData: UpDataStructsTokenData;
UpgradeGoAhead: UpgradeGoAhead;
UpgradeRestriction: UpgradeRestriction;
UpwardMessage: UpwardMessage;
@@ -1296,7 +1095,6 @@
WithdrawReasons: WithdrawReasons;
Xcm: Xcm;
XcmAssetId: XcmAssetId;
- XcmDoubleEncoded: XcmDoubleEncoded;
XcmError: XcmError;
XcmErrorV0: XcmErrorV0;
XcmErrorV1: XcmErrorV1;
@@ -1309,41 +1107,8 @@
XcmOriginKind: XcmOriginKind;
XcmpMessageFormat: XcmpMessageFormat;
XcmV0: XcmV0;
- XcmV0Junction: XcmV0Junction;
- XcmV0JunctionBodyId: XcmV0JunctionBodyId;
- XcmV0JunctionBodyPart: XcmV0JunctionBodyPart;
- XcmV0JunctionNetworkId: XcmV0JunctionNetworkId;
- XcmV0MultiAsset: XcmV0MultiAsset;
- XcmV0MultiLocation: XcmV0MultiLocation;
- XcmV0Order: XcmV0Order;
- XcmV0OriginKind: XcmV0OriginKind;
- XcmV0Response: XcmV0Response;
- XcmV0Xcm: XcmV0Xcm;
XcmV1: XcmV1;
- XcmV1Junction: XcmV1Junction;
- XcmV1MultiAsset: XcmV1MultiAsset;
- XcmV1MultiassetAssetId: XcmV1MultiassetAssetId;
- XcmV1MultiassetAssetInstance: XcmV1MultiassetAssetInstance;
- XcmV1MultiassetFungibility: XcmV1MultiassetFungibility;
- XcmV1MultiassetMultiAssetFilter: XcmV1MultiassetMultiAssetFilter;
- XcmV1MultiassetMultiAssets: XcmV1MultiassetMultiAssets;
- XcmV1MultiassetWildFungibility: XcmV1MultiassetWildFungibility;
- XcmV1MultiassetWildMultiAsset: XcmV1MultiassetWildMultiAsset;
- XcmV1MultiLocation: XcmV1MultiLocation;
- XcmV1MultilocationJunctions: XcmV1MultilocationJunctions;
- XcmV1Order: XcmV1Order;
- XcmV1Response: XcmV1Response;
- XcmV1Xcm: XcmV1Xcm;
XcmV2: XcmV2;
- XcmV2Instruction: XcmV2Instruction;
- XcmV2Response: XcmV2Response;
- XcmV2TraitsError: XcmV2TraitsError;
- XcmV2TraitsOutcome: XcmV2TraitsOutcome;
- XcmV2WeightLimit: XcmV2WeightLimit;
- XcmV2Xcm: XcmV2Xcm;
XcmVersion: XcmVersion;
- XcmVersionedMultiAssets: XcmVersionedMultiAssets;
- XcmVersionedMultiLocation: XcmVersionedMultiLocation;
- XcmVersionedXcm: XcmVersionedXcm;
} // InterfaceTypes
} // declare module
tests/src/interfaces/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/types.ts
+++ b/tests/src/interfaces/types.ts
@@ -1,5 +1,3 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
-export * from './unique/types';
-export * from './rmrk/types';
tests/yarn.lockdiffbeforeafterboth--- a/tests/yarn.lock
+++ b/tests/yarn.lock
@@ -8615,7 +8615,7 @@
resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634"
integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==
-solc@^0.8.13:
+solc@0.8.13:
version "0.8.13"
resolved "https://registry.yarnpkg.com/solc/-/solc-0.8.13.tgz#bafc7fcc11a627e2281e489076b80497123bb704"
integrity sha512-C0yTN+rjEOGO6uVOXI8+EKa75SFMuZpQ2tryex4QxWIg0HRWZvCHKfVPuLZ5wx06Sb6GBp6uQA5yqQyXZnXOJw==