difftreelog
Merge pull request #871 from UniqueNetwork/feature/move_TokenChanged_event
in: master
21 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2445,8 +2445,8 @@
[[package]]
name = "evm-coder"
-version = "0.3.0"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.0#c4bfdf39d84fbe74c6178417177f2a7f81d92bdd"
+version = "0.3.1"
+source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.1#21e61c627f71337d6b8a03899fe8de14bfbf67aa"
dependencies = [
"ethereum",
"evm-coder-procedural",
@@ -2457,8 +2457,8 @@
[[package]]
name = "evm-coder-procedural"
-version = "0.3.0"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.0#c4bfdf39d84fbe74c6178417177f2a7f81d92bdd"
+version = "0.3.1"
+source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.1#21e61c627f71337d6b8a03899fe8de14bfbf67aa"
dependencies = [
"Inflector",
"hex",
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -19,16 +19,9 @@
[workspace.dependencies]
# Unique
-evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.0", default-features = false }
-struct-versioning = { path = "crates/struct-versioning" }
-precompile-utils-macro = { path = "runtime/common/ethereum/precompiles/utils/macro" }
-up-common = { path = "primitives/common", default-features = false }
-up-data-structs = { path = "primitives/data-structs", default-features = false }
-up-pov-estimate-rpc = { path = "primitives/pov-estimate-rpc", default-features = false }
-up-rpc = { path = "primitives/rpc", default-features = false }
-up-sponsorship = { default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.37" }
-uc-rpc = { path = "client/rpc" }
-unique-rpc = { path = "node/rpc" }
+app-promotion-rpc = { path = "primitives/app_promotion_rpc", default-features = false }
+evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.1", default-features = false }
+pallet-app-promotion = { path = "pallets/app-promotion", default-features = false }
pallet-charge-transaction = { package = "pallet-template-transaction-payment", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.37" }
pallet-collator-selection = { default-features = false, path = "pallets/collator-selection" }
pallet-common = { default-features = false, path = "pallets/common" }
@@ -45,56 +38,59 @@
pallet-nonfungible = { default-features = false, path = "pallets/nonfungible" }
pallet-refungible = { default-features = false, path = "pallets/refungible" }
pallet-structure = { default-features = false, path = "pallets/structure" }
+pallet-test-utils = { default-features = false, path = "test-pallets/utils" }
pallet-unique = { path = "pallets/unique", default-features = false }
pallet-unique-scheduler-v2 = { path = "pallets/scheduler-v2", default-features = false }
-pallet-test-utils = { default-features = false, path = "test-pallets/utils" }
-pallet-app-promotion = { path = "pallets/app-promotion", default-features = false }
-app-promotion-rpc = { path = "primitives/app_promotion_rpc", default-features = false }
+precompile-utils-macro = { path = "runtime/common/ethereum/precompiles/utils/macro" }
+struct-versioning = { path = "crates/struct-versioning" }
+uc-rpc = { path = "client/rpc" }
+unique-rpc = { path = "node/rpc" }
+up-common = { path = "primitives/common", default-features = false }
+up-data-structs = { path = "primitives/data-structs", default-features = false }
+up-pov-estimate-rpc = { path = "primitives/pov-estimate-rpc", default-features = false }
+up-rpc = { path = "primitives/rpc", default-features = false }
+up-sponsorship = { default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.37" }
# Unique: Runtimes
+opal-runtime = { path = "runtime/opal" }
+quartz-runtime = { path = "runtime/quartz" }
unique-runtime = { path = "runtime/unique" }
-quartz-runtime = { path = "runtime/quartz" }
-opal-runtime = { path = "runtime/opal" }
# Frontier (Unique patches over the Parity version)
+fc-consensus = { git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
+fc-db = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
+fc-mapping-sync = { git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
+fc-rpc = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
+fc-rpc-core = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
-fc-db = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
-fc-rpc = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
-fc-rpc-core = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
fp-storage = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
-fc-consensus = { git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
-fc-mapping-sync = { git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
+pallet-base-fee = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
-pallet-base-fee = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
pallet-evm-precompile-simple = { default-features = false, git = "https://github.com/uniquenetwork/unique-frontier", branch = "unique-polkadot-v0.9.37" }
# Parity
codec = { default-features = false, features = ['derive'], package = 'parity-scale-codec', version = "3.2.2" }
-scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
-polkadot-cli = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37" }
-polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37" }
-polkadot-service = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37" }
cumulus-client-cli = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
cumulus-client-consensus-aura = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
cumulus-client-consensus-common = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
cumulus-client-network = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
cumulus-client-service = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
-cumulus-primitives-parachain-inherent = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
-cumulus-relay-chain-inprocess-interface = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
-cumulus-relay-chain-interface = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
-cumulus-relay-chain-minimal-node = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
cumulus-pallet-aura-ext = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37", default-features = false }
cumulus-pallet-dmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37", default-features = false }
cumulus-pallet-parachain-system = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37", default-features = false }
cumulus-pallet-xcm = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37", default-features = false }
cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37", default-features = false }
cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37", default-features = false }
+cumulus-primitives-parachain-inherent = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
cumulus-primitives-timestamp = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37", default-features = false }
cumulus-primitives-utility = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37", default-features = false }
+cumulus-relay-chain-inprocess-interface = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
+cumulus-relay-chain-interface = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
+cumulus-relay-chain-minimal-node = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
frame-executive = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
@@ -107,67 +103,71 @@
pallet-sudo = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
pallet-timestamp = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
pallet-transaction-payment = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
pallet-transaction-payment-rpc-runtime-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
pallet-treasury = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
pallet-xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37", default-features = false }
-pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
parachain-info = { default-features = false, git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.37" }
+polkadot-cli = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37" }
polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37", default-features = false }
+polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37" }
+polkadot-service = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37" }
+sc-basic-authorship = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-chain-spec = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-consensus-manual-seal = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-executor = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-network = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-rpc-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-service = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-sysinfo = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-telemetry = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-tracing = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-arithmetic = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-block-builder = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-consensus-aura = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sp-externalities = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-inherents = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-offchain = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-session = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sp-transaction-pool = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sp-version = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-staking = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sp-state-machine = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sp-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-tracing = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sp-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sp-externalities = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sp-state-machine = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sp-transaction-pool = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-substrate-prometheus-endpoint = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-network = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-rpc-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-service = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-basic-authorship = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-chain-spec = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-consensus-manual-seal = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-executor = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-sysinfo = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-telemetry = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-sc-tracing = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+sp-version = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
substrate-frame-rpc-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
+substrate-prometheus-endpoint = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37", default-features = false }
xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37", default-features = false }
xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.37", default-features = false }
# Parity: Build utils
+substrate-build-script-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
substrate-wasm-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-substrate-build-script-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
# Parity: Benchmarking
+frame-benchmarking = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
frame-system-benchmarking = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-frame-benchmarking = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
# Parity: Try Runtime
+frame-try-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
try-runtime-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
-frame-try-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37" }
# ORML
orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", branch = "polkadot-v0.9.37", default-features = false }
@@ -176,15 +176,15 @@
orml-xtokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", branch = "polkadot-v0.9.37", default-features = false }
# Other
-smallvec = "1.6.1"
derivative = { version = "2.2.0", features = ["use_core"] }
-serde = { default-features = false, features = ['derive'], version = "1.0.136" }
-log = { version = "0.4.16", default-features = false }
-num_enum = { version = "0.5.3", default-features = false }
+ethereum = { version = "0.14.0", default-features = false }
+evm-core = { default-features = false, version = "0.37.0" }
hex-literal = "0.3.4"
impl-trait-for-tuples = "0.2.2"
+jsonrpsee = { version = "0.16.2", features = ["macros", "server"] }
+log = { version = "0.4.16", default-features = false }
logtest = "2.0.0"
-ethereum = { version = "0.14.0", default-features = false }
-evm-core = { default-features = false, version = "0.37.0" }
+num_enum = { version = "0.5.3", default-features = false }
primitive-types = { version = "0.12.1", default-features = false }
-jsonrpsee = { version = "0.16.2", features = ["macros", "server"] }
+serde = { default-features = false, features = ['derive'], version = "1.0.136" }
+smallvec = "1.6.1"
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -26,7 +26,6 @@
};
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_std::{vec, vec::Vec};
-use sp_core::U256;
use up_data_structs::{
CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property, SponsoringRateLimit,
SponsorshipState,
@@ -62,18 +61,9 @@
},
/// The collection has been changed.
CollectionChanged {
- /// Collection ID.
- #[indexed]
- collection_id: Address,
- },
-
- /// The token has been changed.
- TokenChanged {
/// Collection ID.
#[indexed]
collection_id: Address,
- /// Token ID.
- token_id: U256,
},
}
pallets/common/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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57 ops::{Deref, DerefMut},58 slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66 ensure,67 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68 dispatch::Pays,69 transactional, fail,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73 AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionFlags,74 RpcCollectionFlags, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,75 COLLECTION_ADMINS_LIMIT, TokenId, TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP,76 CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,77 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,78 CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,79 PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyValue,80 PropertyPermission, PropertiesError, TokenOwnerError, PropertyKeyPermission, TokenData,81 TrySetProperty, PropertyScope, CollectionPermissions,82};83use up_pov_estimate_rpc::PovInfo;8485pub use pallet::*;86use sp_core::H160;87use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};8889use crate::erc::CollectionHelpersEvents;90#[cfg(feature = "runtime-benchmarks")]91pub mod benchmarking;92pub mod dispatch;93pub mod erc;94pub mod eth;95pub mod weights;9697/// Weight info.98pub type SelfWeightOf<T> = <T as Config>::WeightInfo;99100/// Collection handle contains information about collection data and id.101/// Also provides functionality to count consumed gas.102///103/// CollectionHandle is used as a generic wrapper for collections of all types.104/// It allows to perform common operations and queries on any collection type,105/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].106#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]107pub struct CollectionHandle<T: Config> {108 /// Collection id109 pub id: CollectionId,110 collection: Collection<T::AccountId>,111 /// Substrate recorder for counting consumed gas112 pub recorder: SubstrateRecorder<T>,113}114115impl<T: Config> WithRecorder<T> for CollectionHandle<T> {116 fn recorder(&self) -> &SubstrateRecorder<T> {117 &self.recorder118 }119 fn into_recorder(self) -> SubstrateRecorder<T> {120 self.recorder121 }122}123124impl<T: Config> CollectionHandle<T> {125 /// Same as [CollectionHandle::new] but with an explicit gas limit.126 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {127 <CollectionById<T>>::get(id).map(|collection| Self {128 id,129 collection,130 recorder: SubstrateRecorder::new(gas_limit),131 })132 }133134 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].135 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {136 <CollectionById<T>>::get(id).map(|collection| Self {137 id,138 collection,139 recorder,140 })141 }142143 /// Retrives collection data from storage and creates collection handle with default parameters.144 /// If collection not found return `None`145 pub fn new(id: CollectionId) -> Option<Self> {146 Self::new_with_gas_limit(id, u64::MAX)147 }148149 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.150 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {151 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)152 }153154 /// Consume gas for reading.155 pub fn consume_store_reads(156 &self,157 reads: u64,158 ) -> pallet_evm_coder_substrate::execution::Result<()> {159 self.recorder160 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(161 <T as frame_system::Config>::DbWeight::get()162 .read163 .saturating_mul(reads),164 )))165 }166167 /// Consume gas for writing.168 pub fn consume_store_writes(169 &self,170 writes: u64,171 ) -> pallet_evm_coder_substrate::execution::Result<()> {172 self.recorder173 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(174 <T as frame_system::Config>::DbWeight::get()175 .write176 .saturating_mul(writes),177 )))178 }179180 /// Consume gas for reading and writing.181 pub fn consume_store_reads_and_writes(182 &self,183 reads: u64,184 writes: u64,185 ) -> pallet_evm_coder_substrate::execution::Result<()> {186 let weight = <T as frame_system::Config>::DbWeight::get();187 let reads = weight.read.saturating_mul(reads);188 let writes = weight.read.saturating_mul(writes);189 self.recorder190 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(191 reads.saturating_add(writes),192 )))193 }194195 /// Save collection to storage.196 pub fn save(&self) -> DispatchResult {197 <CollectionById<T>>::insert(self.id, &self.collection);198 Ok(())199 }200201 /// Set collection sponsor.202 ///203 /// Unique collections allows sponsoring for certain actions.204 /// This method allows you to set the sponsor of the collection.205 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].206 pub fn set_sponsor(207 &mut self,208 sender: &T::CrossAccountId,209 sponsor: T::AccountId,210 ) -> DispatchResult {211 self.check_is_internal()?;212 self.check_is_owner_or_admin(sender)?;213214 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());215216 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));217 <PalletEvm<T>>::deposit_log(218 erc::CollectionHelpersEvents::CollectionChanged {219 collection_id: eth::collection_id_to_address(self.id),220 }221 .to_log(T::ContractAddress::get()),222 );223224 self.save()225 }226227 /// Force set `sponsor`.228 ///229 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation230 /// from the `sponsor` is not required.231 ///232 /// # Arguments233 ///234 /// * `sender`: Caller's account.235 /// * `sponsor`: ID of the account of the sponsor-to-be.236 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {237 self.check_is_internal()?;238239 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());240241 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));242 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));243 <PalletEvm<T>>::deposit_log(244 erc::CollectionHelpersEvents::CollectionChanged {245 collection_id: eth::collection_id_to_address(self.id),246 }247 .to_log(T::ContractAddress::get()),248 );249250 self.save()251 }252253 /// Confirm sponsorship254 ///255 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.256 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].257 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {258 self.check_is_internal()?;259 ensure!(260 self.collection.sponsorship.pending_sponsor() == Some(sender),261 Error::<T>::ConfirmSponsorshipFail262 );263264 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());265266 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));267 <PalletEvm<T>>::deposit_log(268 erc::CollectionHelpersEvents::CollectionChanged {269 collection_id: eth::collection_id_to_address(self.id),270 }271 .to_log(T::ContractAddress::get()),272 );273274 self.save()275 }276277 /// Remove collection sponsor.278 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {279 self.check_is_internal()?;280 self.check_is_owner_or_admin(sender)?;281282 self.collection.sponsorship = SponsorshipState::Disabled;283284 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));285 <PalletEvm<T>>::deposit_log(286 erc::CollectionHelpersEvents::CollectionChanged {287 collection_id: eth::collection_id_to_address(self.id),288 }289 .to_log(T::ContractAddress::get()),290 );291 self.save()292 }293294 /// Force remove `sponsor`.295 ///296 /// Differs from `remove_sponsor` in that297 /// it doesn't require consent from the `owner` of the collection.298 pub fn force_remove_sponsor(&mut self) -> DispatchResult {299 self.check_is_internal()?;300301 self.collection.sponsorship = SponsorshipState::Disabled;302303 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));304 <PalletEvm<T>>::deposit_log(305 erc::CollectionHelpersEvents::CollectionChanged {306 collection_id: eth::collection_id_to_address(self.id),307 }308 .to_log(T::ContractAddress::get()),309 );310 self.save()311 }312313 /// Checks that the collection was created with, and must be operated upon through **Unique API**.314 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.315 pub fn check_is_internal(&self) -> DispatchResult {316 if self.flags.external {317 return Err(<Error<T>>::CollectionIsExternal)?;318 }319320 Ok(())321 }322323 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.324 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.325 pub fn check_is_external(&self) -> DispatchResult {326 if !self.flags.external {327 return Err(<Error<T>>::CollectionIsInternal)?;328 }329330 Ok(())331 }332}333334impl<T: Config> Deref for CollectionHandle<T> {335 type Target = Collection<T::AccountId>;336337 fn deref(&self) -> &Self::Target {338 &self.collection339 }340}341342impl<T: Config> DerefMut for CollectionHandle<T> {343 fn deref_mut(&mut self) -> &mut Self::Target {344 &mut self.collection345 }346}347348impl<T: Config> CollectionHandle<T> {349 /// Checks if the `user` is the owner of the collection.350 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {351 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);352 Ok(())353 }354355 /// Returns **true** if the `user` is the owner or administrator of the collection.356 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {357 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))358 }359360 /// Checks if the `user` is the owner or administrator of the collection.361 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {362 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);363 Ok(())364 }365366 /// Returns **true** if367 /// * the `user`is a collection owner or admin368 /// * the collection limits allow the owner/admins to transfer/burn any collection token369 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {370 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)371 }372373 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.374 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {375 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)376 }377378 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.379 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {380 ensure!(381 <Allowlist<T>>::get((self.id, user)),382 <Error<T>>::AddressNotInAllowlist383 );384 Ok(())385 }386387 /// Changes collection owner to another account388 /// #### Store read/writes389 /// 1 writes390 pub fn change_owner(391 &mut self,392 caller: T::CrossAccountId,393 new_owner: T::CrossAccountId,394 ) -> DispatchResult {395 self.check_is_internal()?;396 self.check_is_owner(&caller)?;397 self.collection.owner = new_owner.as_sub().clone();398399 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(400 self.id,401 new_owner.as_sub().clone(),402 ));403 <PalletEvm<T>>::deposit_log(404 erc::CollectionHelpersEvents::CollectionChanged {405 collection_id: eth::collection_id_to_address(self.id),406 }407 .to_log(T::ContractAddress::get()),408 );409410 self.save()411 }412}413414#[frame_support::pallet]415pub mod pallet {416 use super::*;417 use dispatch::CollectionDispatch;418 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};419 use frame_system::pallet_prelude::*;420 use frame_support::traits::Currency;421 use up_data_structs::{TokenId, mapping::TokenAddressMapping};422 use scale_info::TypeInfo;423 use weights::WeightInfo;424425 #[pallet::config]426 pub trait Config:427 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo428 {429 /// Weight information for functions of this pallet.430 type WeightInfo: WeightInfo;431432 /// Events compatible with [`frame_system::Config::Event`].433 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;434435 /// Handler of accounts and payment.436 type Currency: Currency<Self::AccountId>;437438 /// Set price to create a collection.439 #[pallet::constant]440 type CollectionCreationPrice: Get<441 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,442 >;443444 /// Dispatcher of operations on collections.445 type CollectionDispatch: CollectionDispatch<Self>;446447 /// Account which holds the chain's treasury.448 type TreasuryAccountId: Get<Self::AccountId>;449450 /// Address under which the CollectionHelper contract would be available.451 #[pallet::constant]452 type ContractAddress: Get<H160>;453454 /// Mapper for token addresses to Ethereum addresses.455 type EvmTokenAddressMapping: TokenAddressMapping<H160>;456457 /// Mapper for token addresses to [`CrossAccountId`].458 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;459 }460461 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);462463 #[pallet::pallet]464 #[pallet::storage_version(STORAGE_VERSION)]465 #[pallet::generate_store(pub(super) trait Store)]466 pub struct Pallet<T>(_);467468 #[pallet::extra_constants]469 impl<T: Config> Pallet<T> {470 /// Maximum admins per collection.471 pub fn collection_admins_limit() -> u32 {472 COLLECTION_ADMINS_LIMIT473 }474 }475476 impl<T: Config> Pallet<T> {477 /// Helper function that handles deposit events478 pub fn deposit_event(event: Event<T>) {479 let event = <T as Config>::RuntimeEvent::from(event);480 let event = event.into();481 <frame_system::Pallet<T>>::deposit_event(event)482 }483 }484485 #[pallet::event]486 pub enum Event<T: Config> {487 /// New collection was created488 CollectionCreated(489 /// Globally unique identifier of newly created collection.490 CollectionId,491 /// [`CollectionMode`] converted into _u8_.492 u8,493 /// Collection owner.494 T::AccountId,495 ),496497 /// New collection was destroyed498 CollectionDestroyed(499 /// Globally unique identifier of collection.500 CollectionId,501 ),502503 /// New item was created.504 ItemCreated(505 /// Id of the collection where item was created.506 CollectionId,507 /// Id of an item. Unique within the collection.508 TokenId,509 /// Owner of newly created item510 T::CrossAccountId,511 /// Always 1 for NFT512 u128,513 ),514515 /// Collection item was burned.516 ItemDestroyed(517 /// Id of the collection where item was destroyed.518 CollectionId,519 /// Identifier of burned NFT.520 TokenId,521 /// Which user has destroyed its tokens.522 T::CrossAccountId,523 /// Amount of token pieces destroed. Always 1 for NFT.524 u128,525 ),526527 /// Item was transferred528 Transfer(529 /// Id of collection to which item is belong.530 CollectionId,531 /// Id of an item.532 TokenId,533 /// Original owner of item.534 T::CrossAccountId,535 /// New owner of item.536 T::CrossAccountId,537 /// Amount of token pieces transfered. Always 1 for NFT.538 u128,539 ),540541 /// Amount pieces of token owned by `sender` was approved for `spender`.542 Approved(543 /// Id of collection to which item is belong.544 CollectionId,545 /// Id of an item.546 TokenId,547 /// Original owner of item.548 T::CrossAccountId,549 /// Id for which the approval was granted.550 T::CrossAccountId,551 /// Amount of token pieces transfered. Always 1 for NFT.552 u128,553 ),554555 /// A `sender` approves operations on all owned tokens for `spender`.556 ApprovedForAll(557 /// Id of collection to which item is belong.558 CollectionId,559 /// Owner of a wallet.560 T::CrossAccountId,561 /// Id for which operator status was granted or rewoked.562 T::CrossAccountId,563 /// Is operator status granted or revoked?564 bool,565 ),566567 /// The colletion property has been added or edited.568 CollectionPropertySet(569 /// Id of collection to which property has been set.570 CollectionId,571 /// The property that was set.572 PropertyKey,573 ),574575 /// The property has been deleted.576 CollectionPropertyDeleted(577 /// Id of collection to which property has been deleted.578 CollectionId,579 /// The property that was deleted.580 PropertyKey,581 ),582583 /// The token property has been added or edited.584 TokenPropertySet(585 /// Identifier of the collection whose token has the property set.586 CollectionId,587 /// The token for which the property was set.588 TokenId,589 /// The property that was set.590 PropertyKey,591 ),592593 /// The token property has been deleted.594 TokenPropertyDeleted(595 /// Identifier of the collection whose token has the property deleted.596 CollectionId,597 /// The token for which the property was deleted.598 TokenId,599 /// The property that was deleted.600 PropertyKey,601 ),602603 /// The token property permission of a collection has been set.604 PropertyPermissionSet(605 /// ID of collection to which property permission has been set.606 CollectionId,607 /// The property permission that was set.608 PropertyKey,609 ),610611 /// Address was added to the allow list.612 AllowListAddressAdded(613 /// ID of the affected collection.614 CollectionId,615 /// Address of the added account.616 T::CrossAccountId,617 ),618619 /// Address was removed from the allow list.620 AllowListAddressRemoved(621 /// ID of the affected collection.622 CollectionId,623 /// Address of the removed account.624 T::CrossAccountId,625 ),626627 /// Collection admin was added.628 CollectionAdminAdded(629 /// ID of the affected collection.630 CollectionId,631 /// Admin address.632 T::CrossAccountId,633 ),634635 /// Collection admin was removed.636 CollectionAdminRemoved(637 /// ID of the affected collection.638 CollectionId,639 /// Removed admin address.640 T::CrossAccountId,641 ),642643 /// Collection limits were set.644 CollectionLimitSet(645 /// ID of the affected collection.646 CollectionId,647 ),648649 /// Collection owned was changed.650 CollectionOwnerChanged(651 /// ID of the affected collection.652 CollectionId,653 /// New owner address.654 T::AccountId,655 ),656657 /// Collection permissions were set.658 CollectionPermissionSet(659 /// ID of the affected collection.660 CollectionId,661 ),662663 /// Collection sponsor was set.664 CollectionSponsorSet(665 /// ID of the affected collection.666 CollectionId,667 /// New sponsor address.668 T::AccountId,669 ),670671 /// New sponsor was confirm.672 SponsorshipConfirmed(673 /// ID of the affected collection.674 CollectionId,675 /// New sponsor address.676 T::AccountId,677 ),678679 /// Collection sponsor was removed.680 CollectionSponsorRemoved(681 /// ID of the affected collection.682 CollectionId,683 ),684 }685686 #[pallet::error]687 pub enum Error<T> {688 /// This collection does not exist.689 CollectionNotFound,690 /// Sender parameter and item owner must be equal.691 MustBeTokenOwner,692 /// No permission to perform action693 NoPermission,694 /// Destroying only empty collections is allowed695 CantDestroyNotEmptyCollection,696 /// Collection is not in mint mode.697 PublicMintingNotAllowed,698 /// Address is not in allow list.699 AddressNotInAllowlist,700701 /// Collection name can not be longer than 63 char.702 CollectionNameLimitExceeded,703 /// Collection description can not be longer than 255 char.704 CollectionDescriptionLimitExceeded,705 /// Token prefix can not be longer than 15 char.706 CollectionTokenPrefixLimitExceeded,707 /// Total collections bound exceeded.708 TotalCollectionsLimitExceeded,709 /// Exceeded max admin count710 CollectionAdminCountExceeded,711 /// Collection limit bounds per collection exceeded712 CollectionLimitBoundsExceeded,713 /// Tried to enable permissions which are only permitted to be disabled714 OwnerPermissionsCantBeReverted,715 /// Collection settings not allowing items transferring716 TransferNotAllowed,717 /// Account token limit exceeded per collection718 AccountTokenLimitExceeded,719 /// Collection token limit exceeded720 CollectionTokenLimitExceeded,721 /// Metadata flag frozen722 MetadataFlagFrozen,723724 /// Item does not exist725 TokenNotFound,726 /// Item is balance not enough727 TokenValueTooLow,728 /// Requested value is more than the approved729 ApprovedValueTooLow,730 /// Tried to approve more than owned731 CantApproveMoreThanOwned,732 /// Only spending from eth mirror could be approved733 AddressIsNotEthMirror,734735 /// Can't transfer tokens to ethereum zero address736 AddressIsZero,737738 /// The operation is not supported739 UnsupportedOperation,740741 /// Insufficient funds to perform an action742 NotSufficientFounds,743744 /// User does not satisfy the nesting rule745 UserIsNotAllowedToNest,746 /// Only tokens from specific collections may nest tokens under this one747 SourceCollectionIsNotAllowedToNest,748749 /// Tried to store more data than allowed in collection field750 CollectionFieldSizeExceeded,751752 /// Tried to store more property data than allowed753 NoSpaceForProperty,754755 /// Tried to store more property keys than allowed756 PropertyLimitReached,757758 /// Property key is too long759 PropertyKeyIsTooLong,760761 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed762 InvalidCharacterInPropertyKey,763764 /// Empty property keys are forbidden765 EmptyPropertyKey,766767 /// Tried to access an external collection with an internal API768 CollectionIsExternal,769770 /// Tried to access an internal collection with an external API771 CollectionIsInternal,772773 /// This address is not set as sponsor, use setCollectionSponsor first.774 ConfirmSponsorshipFail,775776 /// The user is not an administrator.777 UserIsNotCollectionAdmin,778 }779780 /// Storage of the count of created collections. Essentially contains the last collection ID.781 #[pallet::storage]782 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;783784 /// Storage of the count of deleted collections.785 #[pallet::storage]786 pub type DestroyedCollectionCount<T> =787 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;788789 /// Storage of collection info.790 #[pallet::storage]791 pub type CollectionById<T> = StorageMap<792 Hasher = Blake2_128Concat,793 Key = CollectionId,794 Value = Collection<<T as frame_system::Config>::AccountId>,795 QueryKind = OptionQuery,796 >;797798 /// Storage of collection properties.799 #[pallet::storage]800 #[pallet::getter(fn collection_properties)]801 pub type CollectionProperties<T> = StorageMap<802 Hasher = Blake2_128Concat,803 Key = CollectionId,804 Value = Properties,805 QueryKind = ValueQuery,806 OnEmpty = up_data_structs::CollectionProperties,807 >;808809 /// Storage of token property permissions of a collection.810 #[pallet::storage]811 #[pallet::getter(fn property_permissions)]812 pub type CollectionPropertyPermissions<T> = StorageMap<813 Hasher = Blake2_128Concat,814 Key = CollectionId,815 Value = PropertiesPermissionMap,816 QueryKind = ValueQuery,817 >;818819 /// Storage of the amount of collection admins.820 #[pallet::storage]821 pub type AdminAmount<T> = StorageMap<822 Hasher = Blake2_128Concat,823 Key = CollectionId,824 Value = u32,825 QueryKind = ValueQuery,826 >;827828 /// List of collection admins.829 #[pallet::storage]830 pub type IsAdmin<T: Config> = StorageNMap<831 Key = (832 Key<Blake2_128Concat, CollectionId>,833 Key<Blake2_128Concat, T::CrossAccountId>,834 ),835 Value = bool,836 QueryKind = ValueQuery,837 >;838839 /// Allowlisted collection users.840 #[pallet::storage]841 pub type Allowlist<T: Config> = StorageNMap<842 Key = (843 Key<Blake2_128Concat, CollectionId>,844 Key<Blake2_128Concat, T::CrossAccountId>,845 ),846 Value = bool,847 QueryKind = ValueQuery,848 >;849850 /// Not used by code, exists only to provide some types to metadata.851 #[pallet::storage]852 pub type DummyStorageValue<T: Config> = StorageValue<853 Value = (854 CollectionStats,855 CollectionId,856 TokenId,857 TokenChild,858 PhantomType<(859 TokenData<T::CrossAccountId>,860 RpcCollection<T::AccountId>,861 // PoV Estimate Info862 PovInfo,863 )>,864 ),865 QueryKind = OptionQuery,866 >;867868 #[pallet::hooks]869 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {870 fn on_runtime_upgrade() -> Weight {871 StorageVersion::new(1).put::<Pallet<T>>();872873 Weight::zero()874 }875 }876}877878impl<T: Config> Pallet<T> {879 /// Enshure that receiver address is correct.880 ///881 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.882 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {883 ensure!(884 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,885 <Error<T>>::AddressIsZero886 );887 Ok(())888 }889890 /// Get a vector of collection admins.891 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {892 <IsAdmin<T>>::iter_prefix((collection,))893 .map(|(a, _)| a)894 .collect()895 }896897 /// Get a vector of users allowed to mint tokens.898 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {899 <Allowlist<T>>::iter_prefix((collection,))900 .map(|(a, _)| a)901 .collect()902 }903904 /// Is `user` allowed to mint token in `collection`.905 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {906 <Allowlist<T>>::get((collection, user))907 }908909 /// Get statistics of collections.910 pub fn collection_stats() -> CollectionStats {911 let created = <CreatedCollectionCount<T>>::get();912 let destroyed = <DestroyedCollectionCount<T>>::get();913 CollectionStats {914 created: created.0,915 destroyed: destroyed.0,916 alive: created.0 - destroyed.0,917 }918 }919920 /// Get the effective limits for the collection.921 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {922 let collection = <CollectionById<T>>::get(collection)?;923 let limits = collection.limits;924 let effective_limits = CollectionLimits {925 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),926 sponsored_data_size: Some(limits.sponsored_data_size()),927 sponsored_data_rate_limit: Some(928 limits929 .sponsored_data_rate_limit930 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),931 ),932 token_limit: Some(limits.token_limit()),933 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(934 match collection.mode {935 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,936 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,937 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,938 },939 )),940 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),941 owner_can_transfer: Some(limits.owner_can_transfer()),942 owner_can_destroy: Some(limits.owner_can_destroy()),943 transfers_enabled: Some(limits.transfers_enabled()),944 };945946 Some(effective_limits)947 }948949 /// Returns information about the `collection` adapted for rpc.950 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {951 let Collection {952 name,953 description,954 owner,955 mode,956 token_prefix,957 sponsorship,958 limits,959 permissions,960 flags,961 } = <CollectionById<T>>::get(collection)?;962963 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)964 .into_iter()965 .map(|(key, permission)| PropertyKeyPermission { key, permission })966 .collect();967968 let properties = <CollectionProperties<T>>::get(collection)969 .into_iter()970 .map(|(key, value)| Property { key, value })971 .collect();972973 let permissions = CollectionPermissions {974 access: Some(permissions.access()),975 mint_mode: Some(permissions.mint_mode()),976 nesting: Some(permissions.nesting().clone()),977 };978979 Some(RpcCollection {980 name: name.into_inner(),981 description: description.into_inner(),982 owner,983 mode,984 token_prefix: token_prefix.into_inner(),985 sponsorship,986 limits,987 permissions,988 token_property_permissions,989 properties,990 read_only: flags.external,991992 flags: RpcCollectionFlags {993 foreign: flags.foreign,994 erc721metadata: flags.erc721metadata,995 },996 })997 }998}9991000macro_rules! limit_default {1001 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1002 $(1003 if let Some($new) = $new.$field {1004 let $old = $old.$field($($arg)?);1005 let _ = $new;1006 let _ = $old;1007 $check1008 } else {1009 $new.$field = $old.$field1010 }1011 )*1012 }};1013}1014macro_rules! limit_default_clone {1015 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1016 $(1017 if let Some($new) = $new.$field.clone() {1018 let $old = $old.$field($($arg)?);1019 let _ = $new;1020 let _ = $old;1021 $check1022 } else {1023 $new.$field = $old.$field.clone()1024 }1025 )*1026 }};1027}10281029impl<T: Config> Pallet<T> {1030 /// Create new collection.1031 ///1032 /// * `owner` - The owner of the collection.1033 /// * `data` - Description of the created collection.1034 /// * `flags` - Extra flags to store.1035 pub fn init_collection(1036 owner: T::CrossAccountId,1037 payer: T::CrossAccountId,1038 data: CreateCollectionData<T::AccountId>,1039 flags: CollectionFlags,1040 ) -> Result<CollectionId, DispatchError> {1041 {1042 ensure!(1043 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1044 Error::<T>::CollectionTokenPrefixLimitExceeded1045 );1046 }10471048 let created_count = <CreatedCollectionCount<T>>::get()1049 .01050 .checked_add(1)1051 .ok_or(ArithmeticError::Overflow)?;1052 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1053 let id = CollectionId(created_count);10541055 // bound Total number of collections1056 ensure!(1057 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1058 <Error<T>>::TotalCollectionsLimitExceeded1059 );10601061 // =========10621063 let collection = Collection {1064 owner: owner.as_sub().clone(),1065 name: data.name,1066 mode: data.mode.clone(),1067 description: data.description,1068 token_prefix: data.token_prefix,1069 sponsorship: data1070 .pending_sponsor1071 .map(SponsorshipState::Unconfirmed)1072 .unwrap_or_default(),1073 limits: data1074 .limits1075 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1076 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1077 permissions: data1078 .permissions1079 .map(|permissions| {1080 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1081 })1082 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1083 flags,1084 };10851086 let mut collection_properties = up_data_structs::CollectionProperties::get();1087 collection_properties1088 .try_set_from_iter(data.properties.into_iter())1089 .map_err(<Error<T>>::from)?;10901091 CollectionProperties::<T>::insert(id, collection_properties);10921093 let mut token_props_permissions = PropertiesPermissionMap::new();1094 token_props_permissions1095 .try_set_from_iter(data.token_property_permissions.into_iter())1096 .map_err(<Error<T>>::from)?;10971098 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);10991100 // Take a (non-refundable) deposit of collection creation1101 {1102 let mut imbalance =1103 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1104 imbalance.subsume(1105 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1106 &T::TreasuryAccountId::get(),1107 T::CollectionCreationPrice::get(),1108 ),1109 );1110 <T as Config>::Currency::settle(1111 payer.as_sub(),1112 imbalance,1113 WithdrawReasons::TRANSFER,1114 ExistenceRequirement::KeepAlive,1115 )1116 .map_err(|_| Error::<T>::NotSufficientFounds)?;1117 }11181119 <CreatedCollectionCount<T>>::put(created_count);1120 <Pallet<T>>::deposit_event(Event::CollectionCreated(1121 id,1122 data.mode.id(),1123 owner.as_sub().clone(),1124 ));1125 <PalletEvm<T>>::deposit_log(1126 erc::CollectionHelpersEvents::CollectionCreated {1127 owner: *owner.as_eth(),1128 collection_id: eth::collection_id_to_address(id),1129 }1130 .to_log(T::ContractAddress::get()),1131 );1132 <CollectionById<T>>::insert(id, collection);1133 Ok(id)1134 }11351136 /// Destroy collection.1137 ///1138 /// * `collection` - Collection handler.1139 /// * `sender` - The owner or administrator of the collection.1140 pub fn destroy_collection(1141 collection: CollectionHandle<T>,1142 sender: &T::CrossAccountId,1143 ) -> DispatchResult {1144 ensure!(1145 collection.limits.owner_can_destroy(),1146 <Error<T>>::NoPermission,1147 );1148 collection.check_is_owner(sender)?;11491150 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1151 .01152 .checked_add(1)1153 .ok_or(ArithmeticError::Overflow)?;11541155 // =========11561157 <DestroyedCollectionCount<T>>::put(destroyed_collections);1158 <CollectionById<T>>::remove(collection.id);1159 <AdminAmount<T>>::remove(collection.id);1160 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1161 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1162 <CollectionProperties<T>>::remove(collection.id);11631164 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11651166 <PalletEvm<T>>::deposit_log(1167 erc::CollectionHelpersEvents::CollectionDestroyed {1168 collection_id: eth::collection_id_to_address(collection.id),1169 }1170 .to_log(T::ContractAddress::get()),1171 );1172 Ok(())1173 }11741175 /// This function sets or removes a collection properties according to1176 /// `properties_updates` contents:1177 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1178 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1179 ///1180 /// This function fires an event for each property change.1181 /// In case of an error, all the changes (including the events) will be reverted1182 /// since the function is transactional.1183 #[transactional]1184 fn modify_collection_properties(1185 collection: &CollectionHandle<T>,1186 sender: &T::CrossAccountId,1187 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1188 ) -> DispatchResult {1189 collection.check_is_owner_or_admin(sender)?;11901191 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);11921193 for (key, value) in properties_updates {1194 match value {1195 Some(value) => {1196 stored_properties1197 .try_set(key.clone(), value)1198 .map_err(<Error<T>>::from)?;11991200 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1201 <PalletEvm<T>>::deposit_log(1202 erc::CollectionHelpersEvents::CollectionChanged {1203 collection_id: eth::collection_id_to_address(collection.id),1204 }1205 .to_log(T::ContractAddress::get()),1206 );1207 }1208 None => {1209 stored_properties.remove(&key).map_err(<Error<T>>::from)?;12101211 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1212 <PalletEvm<T>>::deposit_log(1213 erc::CollectionHelpersEvents::CollectionChanged {1214 collection_id: eth::collection_id_to_address(collection.id),1215 }1216 .to_log(T::ContractAddress::get()),1217 );1218 }1219 }1220 }12211222 <CollectionProperties<T>>::set(collection.id, stored_properties);12231224 Ok(())1225 }12261227 /// A batch operation to add, edit or remove properties for a token.1228 /// It sets or removes a token's properties according to1229 /// `properties_updates` contents:1230 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1231 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1232 ///1233 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1234 /// - `is_token_create`: Indicates that method is called during token initialization.1235 /// Allows to bypass ownership check.1236 ///1237 /// All affected properties should have `mutable` permission1238 /// to be **deleted** or to be **set more than once**,1239 /// and the sender should have permission to edit those properties.1240 ///1241 /// This function fires an event for each property change.1242 /// In case of an error, all the changes (including the events) will be reverted1243 /// since the function is transactional.1244 pub fn modify_token_properties(1245 collection: &CollectionHandle<T>,1246 sender: &T::CrossAccountId,1247 token_id: TokenId,1248 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1249 is_token_create: bool,1250 mut stored_properties: Properties,1251 is_token_owner: impl Fn() -> Result<bool, DispatchError>,1252 set_token_properties: impl FnOnce(Properties),1253 ) -> DispatchResult {1254 let is_collection_admin = collection.is_owner_or_admin(sender);1255 let permissions = Self::property_permissions(collection.id);12561257 let mut token_owner_result = None;1258 let mut is_token_owner = || -> Result<bool, DispatchError> {1259 *token_owner_result.get_or_insert_with(&is_token_owner)1260 };12611262 for (key, value) in properties_updates {1263 let permission = permissions1264 .get(&key)1265 .cloned()1266 .unwrap_or_else(PropertyPermission::none);12671268 let is_property_exists = stored_properties.get(&key).is_some();12691270 match permission {1271 PropertyPermission { mutable: false, .. } if is_property_exists => {1272 return Err(<Error<T>>::NoPermission.into());1273 }12741275 PropertyPermission {1276 collection_admin,1277 token_owner,1278 ..1279 } => {1280 //TODO: investigate threats during public minting.1281 let is_token_create =1282 is_token_create && (collection_admin || token_owner) && value.is_some();1283 if !(is_token_create1284 || (collection_admin && is_collection_admin)1285 || (token_owner && is_token_owner()?))1286 {1287 fail!(<Error<T>>::NoPermission);1288 }1289 }1290 }12911292 match value {1293 Some(value) => {1294 stored_properties1295 .try_set(key.clone(), value)1296 .map_err(<Error<T>>::from)?;12971298 Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1299 }1300 None => {1301 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13021303 Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1304 }1305 }13061307 <PalletEvm<T>>::deposit_log(1308 CollectionHelpersEvents::TokenChanged {1309 collection_id: eth::collection_id_to_address(collection.id),1310 token_id: token_id.into(),1311 }1312 .to_log(T::ContractAddress::get()),1313 );1314 }13151316 set_token_properties(stored_properties);13171318 Ok(())1319 }13201321 /// Sets or unsets the approval of a given operator.1322 ///1323 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1324 /// - `owner`: Token owner1325 /// - `operator`: Operator1326 /// - `approve`: Should operator status be granted or revoked?1327 pub fn set_allowance_for_all(1328 collection: &CollectionHandle<T>,1329 owner: &T::CrossAccountId,1330 operator: &T::CrossAccountId,1331 approve: bool,1332 set_allowance: impl FnOnce(),1333 log: evm_coder::ethereum::Log,1334 ) -> DispatchResult {1335 if collection.permissions.access() == AccessMode::AllowList {1336 collection.check_allowlist(owner)?;1337 collection.check_allowlist(operator)?;1338 }13391340 Self::ensure_correct_receiver(operator)?;13411342 set_allowance();13431344 <PalletEvm<T>>::deposit_log(log);1345 Self::deposit_event(Event::ApprovedForAll(1346 collection.id,1347 owner.clone(),1348 operator.clone(),1349 approve,1350 ));1351 Ok(())1352 }13531354 /// Set collection property.1355 ///1356 /// * `collection` - Collection handler.1357 /// * `sender` - The owner or administrator of the collection.1358 /// * `property` - The property to set.1359 pub fn set_collection_property(1360 collection: &CollectionHandle<T>,1361 sender: &T::CrossAccountId,1362 property: Property,1363 ) -> DispatchResult {1364 Self::set_collection_properties(collection, sender, [property].into_iter())1365 }13661367 /// Set a scoped collection property, where the scope is a special prefix1368 /// prohibiting a user access to change the property directly.1369 ///1370 /// * `collection_id` - ID of the collection for which the property is being set.1371 /// * `scope` - Property scope.1372 /// * `property` - The property to set.1373 pub fn set_scoped_collection_property(1374 collection_id: CollectionId,1375 scope: PropertyScope,1376 property: Property,1377 ) -> DispatchResult {1378 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1379 properties.try_scoped_set(scope, property.key, property.value)1380 })1381 .map_err(<Error<T>>::from)?;13821383 Ok(())1384 }13851386 /// Set scoped collection properties, where the scope is a special prefix1387 /// prohibiting a user access to change the properties directly.1388 ///1389 /// * `collection_id` - ID of the collection for which the properties is being set.1390 /// * `scope` - Property scope.1391 /// * `properties` - The properties to set.1392 pub fn set_scoped_collection_properties(1393 collection_id: CollectionId,1394 scope: PropertyScope,1395 properties: impl Iterator<Item = Property>,1396 ) -> DispatchResult {1397 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1398 stored_properties.try_scoped_set_from_iter(scope, properties)1399 })1400 .map_err(<Error<T>>::from)?;14011402 Ok(())1403 }14041405 /// Set collection properties.1406 ///1407 /// * `collection` - Collection handler.1408 /// * `sender` - The owner or administrator of the collection.1409 /// * `properties` - The properties to set.1410 pub fn set_collection_properties(1411 collection: &CollectionHandle<T>,1412 sender: &T::CrossAccountId,1413 properties: impl Iterator<Item = Property>,1414 ) -> DispatchResult {1415 Self::modify_collection_properties(1416 collection,1417 sender,1418 properties.map(|property| (property.key, Some(property.value))),1419 )1420 }14211422 /// Delete collection property.1423 ///1424 /// * `collection` - Collection handler.1425 /// * `sender` - The owner or administrator of the collection.1426 /// * `property` - The property to delete.1427 pub fn delete_collection_property(1428 collection: &CollectionHandle<T>,1429 sender: &T::CrossAccountId,1430 property_key: PropertyKey,1431 ) -> DispatchResult {1432 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1433 }14341435 /// Delete collection properties.1436 ///1437 /// * `collection` - Collection handler.1438 /// * `sender` - The owner or administrator of the collection.1439 /// * `properties` - The properties to delete.1440 pub fn delete_collection_properties(1441 collection: &CollectionHandle<T>,1442 sender: &T::CrossAccountId,1443 property_keys: impl Iterator<Item = PropertyKey>,1444 ) -> DispatchResult {1445 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1446 }14471448 /// Set collection propetry permission without any checks.1449 ///1450 /// Used for migrations.1451 ///1452 /// * `collection` - Collection handler.1453 /// * `property_permissions` - Property permissions.1454 pub fn set_property_permission_unchecked(1455 collection: CollectionId,1456 property_permission: PropertyKeyPermission,1457 ) -> DispatchResult {1458 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1459 permissions.try_set(property_permission.key, property_permission.permission)1460 })1461 .map_err(<Error<T>>::from)?;1462 Ok(())1463 }14641465 /// Set collection property permission.1466 ///1467 /// * `collection` - Collection handler.1468 /// * `sender` - The owner or administrator of the collection.1469 /// * `property_permission` - Property permission.1470 pub fn set_property_permission(1471 collection: &CollectionHandle<T>,1472 sender: &T::CrossAccountId,1473 property_permission: PropertyKeyPermission,1474 ) -> DispatchResult {1475 Self::set_scoped_property_permission(1476 collection,1477 sender,1478 PropertyScope::None,1479 property_permission,1480 )1481 }14821483 /// Set collection property permission with scope.1484 ///1485 /// * `collection` - Collection handler.1486 /// * `sender` - The owner or administrator of the collection.1487 /// * `scope` - Property scope.1488 /// * `property_permission` - Property permission.1489 pub fn set_scoped_property_permission(1490 collection: &CollectionHandle<T>,1491 sender: &T::CrossAccountId,1492 scope: PropertyScope,1493 property_permission: PropertyKeyPermission,1494 ) -> DispatchResult {1495 collection.check_is_owner_or_admin(sender)?;14961497 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1498 let current_permission = all_permissions.get(&property_permission.key);1499 if matches![1500 current_permission,1501 Some(PropertyPermission { mutable: false, .. })1502 ] {1503 return Err(<Error<T>>::NoPermission.into());1504 }15051506 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1507 let property_permission = property_permission.clone();1508 permissions.try_scoped_set(1509 scope,1510 property_permission.key,1511 property_permission.permission,1512 )1513 })1514 .map_err(<Error<T>>::from)?;15151516 Self::deposit_event(Event::PropertyPermissionSet(1517 collection.id,1518 property_permission.key,1519 ));1520 <PalletEvm<T>>::deposit_log(1521 erc::CollectionHelpersEvents::CollectionChanged {1522 collection_id: eth::collection_id_to_address(collection.id),1523 }1524 .to_log(T::ContractAddress::get()),1525 );15261527 Ok(())1528 }15291530 /// Set token property permission.1531 ///1532 /// * `collection` - Collection handler.1533 /// * `sender` - The owner or administrator of the collection.1534 /// * `property_permissions` - Property permissions.1535 #[transactional]1536 pub fn set_token_property_permissions(1537 collection: &CollectionHandle<T>,1538 sender: &T::CrossAccountId,1539 property_permissions: Vec<PropertyKeyPermission>,1540 ) -> DispatchResult {1541 Self::set_scoped_token_property_permissions(1542 collection,1543 sender,1544 PropertyScope::None,1545 property_permissions,1546 )1547 }15481549 /// Set token property permission with scope.1550 ///1551 /// * `collection` - Collection handler.1552 /// * `sender` - The owner or administrator of the collection.1553 /// * `scope` - Property scope.1554 /// * `property_permissions` - Property permissions.1555 #[transactional]1556 pub fn set_scoped_token_property_permissions(1557 collection: &CollectionHandle<T>,1558 sender: &T::CrossAccountId,1559 scope: PropertyScope,1560 property_permissions: Vec<PropertyKeyPermission>,1561 ) -> DispatchResult {1562 for prop_pemission in property_permissions {1563 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1564 }15651566 Ok(())1567 }15681569 /// Get collection property.1570 pub fn get_collection_property(1571 collection_id: CollectionId,1572 key: &PropertyKey,1573 ) -> Option<PropertyValue> {1574 Self::collection_properties(collection_id).get(key).cloned()1575 }15761577 /// Convert byte vector to property key vector.1578 pub fn bytes_keys_to_property_keys(1579 keys: Vec<Vec<u8>>,1580 ) -> Result<Vec<PropertyKey>, DispatchError> {1581 keys.into_iter()1582 .map(|key| -> Result<PropertyKey, DispatchError> {1583 key.try_into()1584 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1585 })1586 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1587 }15881589 /// Get properties according to given keys.1590 pub fn filter_collection_properties(1591 collection_id: CollectionId,1592 keys: Option<Vec<PropertyKey>>,1593 ) -> Result<Vec<Property>, DispatchError> {1594 let properties = Self::collection_properties(collection_id);15951596 let properties = keys1597 .map(|keys| {1598 keys.into_iter()1599 .filter_map(|key| {1600 properties.get(&key).map(|value| Property {1601 key,1602 value: value.clone(),1603 })1604 })1605 .collect()1606 })1607 .unwrap_or_else(|| {1608 properties1609 .into_iter()1610 .map(|(key, value)| Property { key, value })1611 .collect()1612 });16131614 Ok(properties)1615 }16161617 /// Get property permissions according to given keys.1618 pub fn filter_property_permissions(1619 collection_id: CollectionId,1620 keys: Option<Vec<PropertyKey>>,1621 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1622 let permissions = Self::property_permissions(collection_id);16231624 let key_permissions = keys1625 .map(|keys| {1626 keys.into_iter()1627 .filter_map(|key| {1628 permissions1629 .get(&key)1630 .map(|permission| PropertyKeyPermission {1631 key,1632 permission: permission.clone(),1633 })1634 })1635 .collect()1636 })1637 .unwrap_or_else(|| {1638 permissions1639 .into_iter()1640 .map(|(key, permission)| PropertyKeyPermission { key, permission })1641 .collect()1642 });16431644 Ok(key_permissions)1645 }16461647 /// Toggle `user` participation in the `collection`'s allow list.1648 /// #### Store read/writes1649 /// 1 writes1650 pub fn toggle_allowlist(1651 collection: &CollectionHandle<T>,1652 sender: &T::CrossAccountId,1653 user: &T::CrossAccountId,1654 allowed: bool,1655 ) -> DispatchResult {1656 collection.check_is_owner_or_admin(sender)?;16571658 // =========16591660 if allowed {1661 <Allowlist<T>>::insert((collection.id, user), true);1662 Self::deposit_event(Event::<T>::AllowListAddressAdded(1663 collection.id,1664 user.clone(),1665 ));1666 } else {1667 <Allowlist<T>>::remove((collection.id, user));1668 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1669 collection.id,1670 user.clone(),1671 ));1672 }16731674 <PalletEvm<T>>::deposit_log(1675 erc::CollectionHelpersEvents::CollectionChanged {1676 collection_id: eth::collection_id_to_address(collection.id),1677 }1678 .to_log(T::ContractAddress::get()),1679 );16801681 Ok(())1682 }16831684 /// Toggle `user` participation in the `collection`'s admin list.1685 /// #### Store read/writes1686 /// 2 reads, 2 writes1687 pub fn toggle_admin(1688 collection: &CollectionHandle<T>,1689 sender: &T::CrossAccountId,1690 user: &T::CrossAccountId,1691 admin: bool,1692 ) -> DispatchResult {1693 collection.check_is_internal()?;1694 collection.check_is_owner(sender)?;16951696 let is_admin = <IsAdmin<T>>::get((collection.id, user));1697 if is_admin == admin {1698 if admin {1699 return Ok(());1700 } else {1701 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1702 }1703 }1704 let amount = <AdminAmount<T>>::get(collection.id);17051706 // =========17071708 if admin {1709 let amount = amount1710 .checked_add(1)1711 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1712 ensure!(1713 amount <= Self::collection_admins_limit(),1714 <Error<T>>::CollectionAdminCountExceeded,1715 );17161717 <AdminAmount<T>>::insert(collection.id, amount);1718 <IsAdmin<T>>::insert((collection.id, user), true);17191720 Self::deposit_event(Event::<T>::CollectionAdminAdded(1721 collection.id,1722 user.clone(),1723 ));1724 } else {1725 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1726 <IsAdmin<T>>::remove((collection.id, user));17271728 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1729 collection.id,1730 user.clone(),1731 ));1732 }17331734 <PalletEvm<T>>::deposit_log(1735 erc::CollectionHelpersEvents::CollectionChanged {1736 collection_id: eth::collection_id_to_address(collection.id),1737 }1738 .to_log(T::ContractAddress::get()),1739 );17401741 Ok(())1742 }17431744 /// Update collection limits.1745 pub fn update_limits(1746 user: &T::CrossAccountId,1747 collection: &mut CollectionHandle<T>,1748 new_limit: CollectionLimits,1749 ) -> DispatchResult {1750 collection.check_is_internal()?;1751 collection.check_is_owner_or_admin(user)?;17521753 collection.limits =1754 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17551756 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1757 <PalletEvm<T>>::deposit_log(1758 erc::CollectionHelpersEvents::CollectionChanged {1759 collection_id: eth::collection_id_to_address(collection.id),1760 }1761 .to_log(T::ContractAddress::get()),1762 );17631764 collection.save()1765 }17661767 /// Merge set fields from `new_limit` to `old_limit`.1768 fn clamp_limits(1769 mode: CollectionMode,1770 old_limit: &CollectionLimits,1771 mut new_limit: CollectionLimits,1772 ) -> Result<CollectionLimits, DispatchError> {1773 let limits = old_limit;1774 limit_default!(old_limit, new_limit,1775 account_token_ownership_limit => ensure!(1776 new_limit <= MAX_TOKEN_OWNERSHIP,1777 <Error<T>>::CollectionLimitBoundsExceeded,1778 ),1779 sponsored_data_size => ensure!(1780 new_limit <= CUSTOM_DATA_LIMIT,1781 <Error<T>>::CollectionLimitBoundsExceeded,1782 ),17831784 sponsored_data_rate_limit => {},1785 token_limit => ensure!(1786 old_limit >= new_limit && new_limit > 0,1787 <Error<T>>::CollectionTokenLimitExceeded1788 ),17891790 sponsor_transfer_timeout(match mode {1791 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1792 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1793 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1794 }) => ensure!(1795 new_limit <= MAX_SPONSOR_TIMEOUT,1796 <Error<T>>::CollectionLimitBoundsExceeded,1797 ),1798 sponsor_approve_timeout => {},1799 owner_can_transfer => ensure!(1800 !limits.owner_can_transfer_instaled() ||1801 old_limit || !new_limit,1802 <Error<T>>::OwnerPermissionsCantBeReverted,1803 ),1804 owner_can_destroy => ensure!(1805 old_limit || !new_limit,1806 <Error<T>>::OwnerPermissionsCantBeReverted,1807 ),1808 transfers_enabled => {},1809 );1810 Ok(new_limit)1811 }18121813 /// Update collection permissions.1814 pub fn update_permissions(1815 user: &T::CrossAccountId,1816 collection: &mut CollectionHandle<T>,1817 new_permission: CollectionPermissions,1818 ) -> DispatchResult {1819 collection.check_is_internal()?;1820 collection.check_is_owner_or_admin(user)?;1821 collection.permissions = Self::clamp_permissions(1822 collection.mode.clone(),1823 &collection.permissions,1824 new_permission,1825 )?;18261827 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1828 <PalletEvm<T>>::deposit_log(1829 erc::CollectionHelpersEvents::CollectionChanged {1830 collection_id: eth::collection_id_to_address(collection.id),1831 }1832 .to_log(T::ContractAddress::get()),1833 );18341835 collection.save()1836 }18371838 /// Merge set fields from `new_permission` to `old_permission`.1839 fn clamp_permissions(1840 _mode: CollectionMode,1841 old_permission: &CollectionPermissions,1842 mut new_permission: CollectionPermissions,1843 ) -> Result<CollectionPermissions, DispatchError> {1844 limit_default_clone!(old_permission, new_permission,1845 access => {},1846 mint_mode => {},1847 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1848 );1849 Ok(new_permission)1850 }18511852 /// Repair possibly broken properties of a collection.1853 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1854 CollectionProperties::<T>::mutate(collection_id, |properties| {1855 properties.recompute_consumed_space();1856 });18571858 Ok(())1859 }1860}18611862/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1863#[macro_export]1864macro_rules! unsupported {1865 ($runtime:path) => {1866 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1867 };1868}18691870/// Return weights for various worst-case operations.1871pub trait CommonWeightInfo<CrossAccountId> {1872 /// Weight of item creation.1873 fn create_item(data: &CreateItemData) -> Weight {1874 Self::create_multiple_items(from_ref(data))1875 }18761877 /// Weight of items creation.1878 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18791880 /// Weight of items creation.1881 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18821883 /// The weight of the burning item.1884 fn burn_item() -> Weight;18851886 /// Property setting weight.1887 ///1888 /// * `amount`- The number of properties to set.1889 fn set_collection_properties(amount: u32) -> Weight;18901891 /// Collection property deletion weight.1892 ///1893 /// * `amount`- The number of properties to set.1894 fn delete_collection_properties(amount: u32) -> Weight;18951896 /// Token property setting weight.1897 ///1898 /// * `amount`- The number of properties to set.1899 fn set_token_properties(amount: u32) -> Weight;19001901 /// Token property deletion weight.1902 ///1903 /// * `amount`- The number of properties to delete.1904 fn delete_token_properties(amount: u32) -> Weight;19051906 /// Token property permissions set weight.1907 ///1908 /// * `amount`- The number of property permissions to set.1909 fn set_token_property_permissions(amount: u32) -> Weight;19101911 /// Transfer price of the token or its parts.1912 fn transfer() -> Weight;19131914 /// The price of setting the permission of the operation from another user.1915 fn approve() -> Weight;19161917 /// The price of setting the permission of the operation from another user for eth mirror.1918 fn approve_from() -> Weight;19191920 /// Transfer price from another user.1921 fn transfer_from() -> Weight;19221923 /// The price of burning a token from another user.1924 fn burn_from() -> Weight;19251926 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1927 /// whole users's balance.1928 ///1929 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1930 fn burn_recursively_self_raw() -> Weight;19311932 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1933 ///1934 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1935 fn burn_recursively_breadth_raw(amount: u32) -> Weight;19361937 /// The price of recursive burning a token.1938 ///1939 /// `max_selfs` - The maximum burning weight of the token itself.1940 /// `max_breadth` - The maximum number of nested tokens to burn.1941 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1942 Self::burn_recursively_self_raw()1943 .saturating_mul(max_selfs.max(1) as u64)1944 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1945 }19461947 /// The price of retrieving token owner1948 fn token_owner() -> Weight;19491950 /// The price of setting approval for all1951 fn set_allowance_for_all() -> Weight;19521953 /// The price of repairing an item.1954 fn force_repair_item() -> Weight;1955}19561957/// Weight info extension trait for refungible pallet.1958pub trait RefungibleExtensionsWeightInfo {1959 /// Weight of token repartition.1960 fn repartition() -> Weight;1961}19621963/// Common collection operations.1964///1965/// It wraps methods in Fungible, Nonfungible and Refungible pallets1966/// and adds weight info.1967pub trait CommonCollectionOperations<T: Config> {1968 /// Create token.1969 ///1970 /// * `sender` - The user who mint the token and pays for the transaction.1971 /// * `to` - The user who will own the token.1972 /// * `data` - Token data.1973 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1974 fn create_item(1975 &self,1976 sender: T::CrossAccountId,1977 to: T::CrossAccountId,1978 data: CreateItemData,1979 nesting_budget: &dyn Budget,1980 ) -> DispatchResultWithPostInfo;19811982 /// Create multiple tokens.1983 ///1984 /// * `sender` - The user who mint the token and pays for the transaction.1985 /// * `to` - The user who will own the token.1986 /// * `data` - Token data.1987 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1988 fn create_multiple_items(1989 &self,1990 sender: T::CrossAccountId,1991 to: T::CrossAccountId,1992 data: Vec<CreateItemData>,1993 nesting_budget: &dyn Budget,1994 ) -> DispatchResultWithPostInfo;19951996 /// Create multiple tokens.1997 ///1998 /// * `sender` - The user who mint the token and pays for the transaction.1999 /// * `to` - The user who will own the token.2000 /// * `data` - Token data.2001 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2002 fn create_multiple_items_ex(2003 &self,2004 sender: T::CrossAccountId,2005 data: CreateItemExData<T::CrossAccountId>,2006 nesting_budget: &dyn Budget,2007 ) -> DispatchResultWithPostInfo;20082009 /// Burn token.2010 ///2011 /// * `sender` - The user who owns the token.2012 /// * `token` - Token id that will burned.2013 /// * `amount` - The number of parts of the token that will be burned.2014 fn burn_item(2015 &self,2016 sender: T::CrossAccountId,2017 token: TokenId,2018 amount: u128,2019 ) -> DispatchResultWithPostInfo;20202021 /// Burn token and all nested tokens recursievly.2022 ///2023 /// * `sender` - The user who owns the token.2024 /// * `token` - Token id that will burned.2025 /// * `self_budget` - The budget that can be spent on burning tokens.2026 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.2027 fn burn_item_recursively(2028 &self,2029 sender: T::CrossAccountId,2030 token: TokenId,2031 self_budget: &dyn Budget,2032 breadth_budget: &dyn Budget,2033 ) -> DispatchResultWithPostInfo;20342035 /// Set collection properties.2036 ///2037 /// * `sender` - Must be either the owner of the collection or its admin.2038 /// * `properties` - Properties to be set.2039 fn set_collection_properties(2040 &self,2041 sender: T::CrossAccountId,2042 properties: Vec<Property>,2043 ) -> DispatchResultWithPostInfo;20442045 /// Delete collection properties.2046 ///2047 /// * `sender` - Must be either the owner of the collection or its admin.2048 /// * `properties` - The properties to be removed.2049 fn delete_collection_properties(2050 &self,2051 sender: &T::CrossAccountId,2052 property_keys: Vec<PropertyKey>,2053 ) -> DispatchResultWithPostInfo;20542055 /// Set token properties.2056 ///2057 /// The appropriate [`PropertyPermission`] for the token property2058 /// must be set with [`Self::set_token_property_permissions`].2059 ///2060 /// * `sender` - Must be either the owner of the token or its admin.2061 /// * `token_id` - The token for which the properties are being set.2062 /// * `properties` - Properties to be set.2063 /// * `budget` - Budget for setting properties.2064 fn set_token_properties(2065 &self,2066 sender: T::CrossAccountId,2067 token_id: TokenId,2068 properties: Vec<Property>,2069 budget: &dyn Budget,2070 ) -> DispatchResultWithPostInfo;20712072 /// Remove token properties.2073 ///2074 /// The appropriate [`PropertyPermission`] for the token property2075 /// must be set with [`Self::set_token_property_permissions`].2076 ///2077 /// * `sender` - Must be either the owner of the token or its admin.2078 /// * `token_id` - The token for which the properties are being remove.2079 /// * `property_keys` - Keys to remove corresponding properties.2080 /// * `budget` - Budget for removing properties.2081 fn delete_token_properties(2082 &self,2083 sender: T::CrossAccountId,2084 token_id: TokenId,2085 property_keys: Vec<PropertyKey>,2086 budget: &dyn Budget,2087 ) -> DispatchResultWithPostInfo;20882089 /// Set token property permissions.2090 ///2091 /// * `sender` - Must be either the owner of the token or its admin.2092 /// * `token_id` - The token for which the properties are being set.2093 /// * `property_permissions` - Property permissions to be set.2094 /// * `budget` - Budget for setting properties.2095 fn set_token_property_permissions(2096 &self,2097 sender: &T::CrossAccountId,2098 property_permissions: Vec<PropertyKeyPermission>,2099 ) -> DispatchResultWithPostInfo;21002101 /// Transfer amount of token pieces.2102 ///2103 /// * `sender` - Donor user.2104 /// * `to` - Recepient user.2105 /// * `token` - The token of which parts are being sent.2106 /// * `amount` - The number of parts of the token that will be transferred.2107 /// * `budget` - The maximum budget that can be spent on the transfer.2108 fn transfer(2109 &self,2110 sender: T::CrossAccountId,2111 to: T::CrossAccountId,2112 token: TokenId,2113 amount: u128,2114 budget: &dyn Budget,2115 ) -> DispatchResultWithPostInfo;21162117 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2118 ///2119 /// * `sender` - The user who grants access to the token.2120 /// * `spender` - The user to whom the rights are granted.2121 /// * `token` - The token to which access is granted.2122 /// * `amount` - The amount of pieces that another user can dispose of.2123 fn approve(2124 &self,2125 sender: T::CrossAccountId,2126 spender: T::CrossAccountId,2127 token: TokenId,2128 amount: u128,2129 ) -> DispatchResultWithPostInfo;21302131 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2132 ///2133 /// * `sender` - The user who grants access to the token.2134 /// * `from` - Spender's eth mirror.2135 /// * `to` - The user to whom the rights are granted.2136 /// * `token` - The token to which access is granted.2137 /// * `amount` - The amount of pieces that another user can dispose of.2138 fn approve_from(2139 &self,2140 sender: T::CrossAccountId,2141 from: T::CrossAccountId,2142 to: T::CrossAccountId,2143 token: TokenId,2144 amount: u128,2145 ) -> DispatchResultWithPostInfo;21462147 /// Send parts of a token owned by another user.2148 ///2149 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2150 ///2151 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2152 /// * `from` - The user who owns the token.2153 /// * `to` - Recepient user.2154 /// * `token` - The token of which parts are being sent.2155 /// * `amount` - The number of parts of the token that will be transferred.2156 /// * `budget` - The maximum budget that can be spent on the transfer.2157 fn transfer_from(2158 &self,2159 sender: T::CrossAccountId,2160 from: T::CrossAccountId,2161 to: T::CrossAccountId,2162 token: TokenId,2163 amount: u128,2164 budget: &dyn Budget,2165 ) -> DispatchResultWithPostInfo;21662167 /// Burn parts of a token owned by another user.2168 ///2169 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2170 ///2171 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2172 /// * `from` - The user who owns the token.2173 /// * `token` - The token of which parts are being sent.2174 /// * `amount` - The number of parts of the token that will be transferred.2175 /// * `budget` - The maximum budget that can be spent on the burn.2176 fn burn_from(2177 &self,2178 sender: T::CrossAccountId,2179 from: T::CrossAccountId,2180 token: TokenId,2181 amount: u128,2182 budget: &dyn Budget,2183 ) -> DispatchResultWithPostInfo;21842185 /// Check permission to nest token.2186 ///2187 /// * `sender` - The user who initiated the check.2188 /// * `from` - The token that is checked for embedding.2189 /// * `under` - Token under which to check.2190 /// * `budget` - The maximum budget that can be spent on the check.2191 fn check_nesting(2192 &self,2193 sender: T::CrossAccountId,2194 from: (CollectionId, TokenId),2195 under: TokenId,2196 budget: &dyn Budget,2197 ) -> DispatchResult;21982199 /// Nest one token into another.2200 ///2201 /// * `under` - Token holder.2202 /// * `to_nest` - Nested token.2203 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22042205 /// Unnest token.2206 ///2207 /// * `under` - Token holder.2208 /// * `to_nest` - Token to unnest.2209 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22102211 /// Get all user tokens.2212 ///2213 /// * `account` - Account for which you need to get tokens.2214 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22152216 /// Get all the tokens in the collection.2217 fn collection_tokens(&self) -> Vec<TokenId>;22182219 /// Check if the token exists.2220 ///2221 /// * `token` - Id token to check.2222 fn token_exists(&self, token: TokenId) -> bool;22232224 /// Get the id of the last minted token.2225 fn last_token_id(&self) -> TokenId;22262227 /// Get the owner of the token.2228 ///2229 /// * `token` - The token for which you need to find out the owner.2230 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22312232 /// Returns 10 tokens owners in no particular order.2233 ///2234 /// * `token` - The token for which you need to find out the owners.2235 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22362237 /// Get the value of the token property by key.2238 ///2239 /// * `token` - Token with the property to get.2240 /// * `key` - Property name.2241 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22422243 /// Get a set of token properties by key vector.2244 ///2245 /// * `token` - Token with the property to get.2246 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2247 /// then all properties are returned.2248 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22492250 /// Amount of unique collection tokens2251 fn total_supply(&self) -> u32;22522253 /// Amount of different tokens account has.2254 ///2255 /// * `account` - The account for which need to get the balance.2256 fn account_balance(&self, account: T::CrossAccountId) -> u32;22572258 /// Amount of specific token account have.2259 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22602261 /// Amount of token pieces2262 fn total_pieces(&self, token: TokenId) -> Option<u128>;22632264 /// Get the number of parts of the token that a trusted user can manage.2265 ///2266 /// * `sender` - Trusted user.2267 /// * `spender` - Owner of the token.2268 /// * `token` - The token for which to get the value.2269 fn allowance(2270 &self,2271 sender: T::CrossAccountId,2272 spender: T::CrossAccountId,2273 token: TokenId,2274 ) -> u128;22752276 /// Get extension for RFT collection.2277 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22782279 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2280 /// * `owner` - Token owner2281 /// * `operator` - Operator2282 /// * `approve` - Should operator status be granted or revoked?2283 fn set_allowance_for_all(2284 &self,2285 owner: T::CrossAccountId,2286 operator: T::CrossAccountId,2287 approve: bool,2288 ) -> DispatchResultWithPostInfo;22892290 /// Tells whether the given `owner` approves the `operator`.2291 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;22922293 /// Repairs a possibly broken item.2294 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2295}22962297/// Extension for RFT collection.2298pub trait RefungibleExtensions<T>2299where2300 T: Config,2301{2302 /// Change the number of parts of the token.2303 ///2304 /// When the value changes down, this function is equivalent to burning parts of the token.2305 ///2306 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2307 /// * `token` - The token for which you want to change the number of parts.2308 /// * `amount` - The new value of the parts of the token.2309 fn repartition(2310 &self,2311 sender: &T::CrossAccountId,2312 token: TokenId,2313 amount: u128,2314 ) -> DispatchResultWithPostInfo;2315}23162317/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2318///2319/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2320pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2321 let post_info = PostDispatchInfo {2322 actual_weight: Some(weight),2323 pays_fee: Pays::Yes,2324 };2325 match res {2326 Ok(()) => Ok(post_info),2327 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2328 }2329}23302331impl<T: Config> From<PropertiesError> for Error<T> {2332 fn from(error: PropertiesError) -> Self {2333 match error {2334 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2335 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2336 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2337 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2338 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2339 }2340 }2341}pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -50,13 +50,24 @@
TokenProperties, SelfWeightOf, weights::WeightInfo,
};
+/// Nft events.
+#[derive(ToLog)]
+pub enum ERC721TokenEvent {
+ /// The token has been changed.
+ TokenChanged {
+ /// Token ID.
+ #[indexed]
+ token_id: U256,
+ },
+}
+
frontier_contract! {
macro_rules! NonfungibleHandle_result {...}
impl<T: Config> Contract for NonfungibleHandle<T> {...}
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-#[solidity_interface(name = TokenProperties, enum(derive(PreDispatch)), enum_attr(weight))]
+#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]
impl<T: Config> NonfungibleHandle<T> {
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -112,7 +112,7 @@
};
use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use sp_core::H160;
+use sp_core::{Get, H160};
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use core::ops::Deref;
@@ -622,6 +622,10 @@
stored_properties,
is_token_owner,
|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
+ erc::ERC721TokenEvent::TokenChanged {
+ token_id: token_id.into(),
+ }
+ .to_log(T::ContractAddress::get()),
)
}
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
@@ -17,9 +17,14 @@
}
}
+/// @dev inlined interface
+contract ERC721TokenEvent {
+ event TokenChanged(uint256 indexed tokenId);
+}
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
/// @dev the ERC-165 identifier for this interface is 0xde0695c2
-contract TokenProperties is Dummy, ERC165 {
+contract TokenProperties is Dummy, ERC165, ERC721TokenEvent {
// /// @notice Set permissions for token property.
// /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
// /// @param key Property key.
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -59,8 +59,19 @@
pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);
+/// Rft events.
+#[derive(ToLog)]
+pub enum ERC721TokenEvent {
+ /// The token has been changed.
+ TokenChanged {
+ /// Token ID.
+ #[indexed]
+ token_id: U256,
+ },
+}
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
-#[solidity_interface(name = TokenProperties, enum(derive(PreDispatch)), enum_attr(weight))]
+#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]
impl<T: Config> RefungibleHandle<T> {
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -100,7 +100,7 @@
Event as CommonEvent, Pallet as PalletCommon,
};
use pallet_structure::Pallet as PalletStructure;
-use sp_core::H160;
+use sp_core::{Get, H160};
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use up_data_structs::{
@@ -571,6 +571,10 @@
stored_properties,
is_token_owner,
|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
+ erc::ERC721TokenEvent::TokenChanged {
+ token_id: token_id.into(),
+ }
+ .to_log(T::ContractAddress::get()),
)
}
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -17,9 +17,14 @@
}
}
+/// @dev inlined interface
+contract ERC721TokenEvent {
+ event TokenChanged(uint256 indexed tokenId);
+}
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
/// @dev the ERC-165 identifier for this interface is 0xde0695c2
-contract TokenProperties is Dummy, ERC165 {
+contract TokenProperties is Dummy, ERC165, ERC721TokenEvent {
// /// @notice Set permissions for token property.
// /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
// /// @param key Property key.
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -22,7 +22,6 @@
event CollectionCreated(address indexed owner, address indexed collectionId);
event CollectionDestroyed(address indexed collectionId);
event CollectionChanged(address indexed collectionId);
- event TokenChanged(address indexed collectionId, uint256 tokenId);
}
/// @title Contract, which allows users to operate with collections
tests/src/eth/abi/collectionHelpers.jsondiffbeforeafterboth--- a/tests/src/eth/abi/collectionHelpers.json
+++ b/tests/src/eth/abi/collectionHelpers.json
@@ -45,25 +45,6 @@
"type": "event"
},
{
- "anonymous": false,
- "inputs": [
- {
- "indexed": true,
- "internalType": "address",
- "name": "collectionId",
- "type": "address"
- },
- {
- "indexed": false,
- "internalType": "uint256",
- "name": "tokenId",
- "type": "uint256"
- }
- ],
- "name": "TokenChanged",
- "type": "event"
- },
- {
"inputs": [
{ "internalType": "uint32", "name": "collectionId", "type": "uint32" }
],
tests/src/eth/abi/nonFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -54,6 +54,19 @@
"inputs": [
{
"indexed": true,
+ "internalType": "uint256",
+ "name": "tokenId",
+ "type": "uint256"
+ }
+ ],
+ "name": "TokenChanged",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
"internalType": "address",
"name": "from",
"type": "address"
tests/src/eth/abi/reFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -54,6 +54,19 @@
"inputs": [
{
"indexed": true,
+ "internalType": "uint256",
+ "name": "tokenId",
+ "type": "uint256"
+ }
+ ],
+ "name": "TokenChanged",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
"internalType": "address",
"name": "from",
"type": "address"
tests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -17,7 +17,6 @@
event CollectionCreated(address indexed owner, address indexed collectionId);
event CollectionDestroyed(address indexed collectionId);
event CollectionChanged(address indexed collectionId);
- event TokenChanged(address indexed collectionId, uint256 tokenId);
}
/// @title Contract, which allows users to operate with collections
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -12,9 +12,14 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
+/// @dev inlined interface
+interface ERC721TokenEvent {
+ event TokenChanged(uint256 indexed tokenId);
+}
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
/// @dev the ERC-165 identifier for this interface is 0xde0695c2
-interface TokenProperties is Dummy, ERC165 {
+interface TokenProperties is Dummy, ERC165, ERC721TokenEvent {
// /// @notice Set permissions for token property.
// /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
// /// @param key Property key.
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -12,9 +12,14 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
+/// @dev inlined interface
+interface ERC721TokenEvent {
+ event TokenChanged(uint256 indexed tokenId);
+}
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
/// @dev the ERC-165 identifier for this interface is 0xde0695c2
-interface TokenProperties is Dummy, ERC165 {
+interface TokenProperties is Dummy, ERC165, ERC721TokenEvent {
// /// @notice Set permissions for token property.
// /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
// /// @param key Property key.
tests/src/eth/events.test.tsdiffbeforeafterboth--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -29,8 +29,10 @@
});
});
-function clearEvents(ethEvents: NormalizedEvent[], subEvents: IEvent[]) {
- ethEvents.splice(0);
+function clearEvents(ethEvents: NormalizedEvent[] | null, subEvents: IEvent[]) {
+ if (ethEvents !== null) {
+ ethEvents.splice(0);
+ }
subEvents.splice(0);
}
@@ -374,7 +376,6 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
- const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
const result = await collection.methods.mint(owner).send({from: owner});
const tokenId = result.events.Transfer.returnValues.tokenId;
await collection.methods.setTokenPropertyPermissions([
@@ -384,38 +385,29 @@
[TokenPermissionField.CollectionAdmin, true]],
],
]).send({from: owner});
-
- const ethEvents: any = [];
- collectionHelper.events.allEvents((_: any, event: any) => {
- ethEvents.push(event);
- });
const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['TokenPropertySet', 'TokenPropertyDeleted']}]);
{
- await collection.methods.setProperties(tokenId, [{key: 'A', value: [1,2,3]}]).send({from: owner});
+ const result = await collection.methods.setProperties(tokenId, [{key: 'A', value: [1,2,3]}]).send({from: owner});
await helper.wait.newBlocks(1);
- expect(ethEvents).to.containSubset([
- {
- event: 'TokenChanged',
- returnValues: {
- collectionId: collectionAddress,
- },
+ expect(result.events.TokenChanged).to.be.like({
+ event: 'TokenChanged',
+ returnValues: {
+ tokenId: tokenId,
},
- ]);
+ });
expect(subEvents).to.containSubset([{method: 'TokenPropertySet'}]);
- clearEvents(ethEvents, subEvents);
+ clearEvents(null, subEvents);
}
{
- await collection.methods.deleteProperties(tokenId, ['A']).send({from: owner});
+ const result = await collection.methods.deleteProperties(tokenId, ['A']).send({from: owner});
await helper.wait.newBlocks(1);
- expect(ethEvents).to.containSubset([
- {
- event: 'TokenChanged',
- returnValues: {
- collectionId: collectionAddress,
- },
+ expect(result.events.TokenChanged).to.be.like({
+ event: 'TokenChanged',
+ returnValues: {
+ tokenId: tokenId,
},
- ]);
+ });
expect(subEvents).to.containSubset([{method: 'TokenPropertyDeleted'}]);
}
unsubscribe();