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.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -86,7 +86,6 @@
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
-use crate::erc::CollectionHelpersEvents;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
pub mod dispatch;
@@ -1250,6 +1249,7 @@
mut stored_properties: Properties,
is_token_owner: impl Fn() -> Result<bool, DispatchError>,
set_token_properties: impl FnOnce(Properties),
+ log: evm_coder::ethereum::Log,
) -> DispatchResult {
let is_collection_admin = collection.is_owner_or_admin(sender);
let permissions = Self::property_permissions(collection.id);
@@ -1304,13 +1304,7 @@
}
}
- <PalletEvm<T>>::deposit_log(
- CollectionHelpersEvents::TokenChanged {
- collection_id: eth::collection_id_to_address(collection.id),
- token_id: token_id.into(),
- }
- .to_log(T::ContractAddress::get()),
- );
+ <PalletEvm<T>>::deposit_log(log.clone());
}
set_token_properties(stored_properties);
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.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//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//! of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//! Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//! transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//! an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//! with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//! collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//! Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{ensure, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99 CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,100 Event as CommonEvent, Pallet as PalletCommon,101};102use pallet_structure::Pallet as PalletStructure;103use sp_core::H160;104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107 AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,108 mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,109 PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TrySetProperty,110 PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120121pub type CreateItemData<T> =122 CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;123pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;124125#[frame_support::pallet]126pub mod pallet {127 use super::*;128 use frame_support::{129 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,130 traits::StorageVersion,131 };132 use up_data_structs::{CollectionId, TokenId};133 use super::weights::WeightInfo;134135 #[pallet::error]136 pub enum Error<T> {137 /// Not Refungible item data used to mint in Refungible collection.138 NotRefungibleDataUsedToMintFungibleCollectionToken,139 /// Maximum refungibility exceeded.140 WrongRefungiblePieces,141 /// Refungible token can't be repartitioned by user who isn't owns all pieces.142 RepartitionWhileNotOwningAllPieces,143 /// Refungible token can't nest other tokens.144 RefungibleDisallowsNesting,145 /// Setting item properties is not allowed.146 SettingPropertiesNotAllowed,147 }148149 #[pallet::config]150 pub trait Config:151 frame_system::Config + pallet_common::Config + pallet_structure::Config152 {153 type WeightInfo: WeightInfo;154 }155156 const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);157158 #[pallet::pallet]159 #[pallet::storage_version(STORAGE_VERSION)]160 #[pallet::generate_store(pub(super) trait Store)]161 pub struct Pallet<T>(_);162163 /// Total amount of minted tokens in a collection.164 #[pallet::storage]165 pub type TokensMinted<T: Config> =166 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;167168 /// Amount of tokens burnt in a collection.169 #[pallet::storage]170 pub type TokensBurnt<T: Config> =171 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;172173 /// Amount of pieces a refungible token is split into.174 #[pallet::storage]175 #[pallet::getter(fn token_properties)]176 pub type TokenProperties<T: Config> = StorageNMap<177 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),178 Value = up_data_structs::Properties,179 QueryKind = ValueQuery,180 OnEmpty = up_data_structs::TokenProperties,181 >;182183 /// Total amount of pieces for token184 #[pallet::storage]185 pub type TotalSupply<T: Config> = StorageNMap<186 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),187 Value = u128,188 QueryKind = ValueQuery,189 >;190191 /// Used to enumerate tokens owned by account.192 #[pallet::storage]193 pub type Owned<T: Config> = StorageNMap<194 Key = (195 Key<Twox64Concat, CollectionId>,196 Key<Blake2_128Concat, T::CrossAccountId>,197 Key<Twox64Concat, TokenId>,198 ),199 Value = bool,200 QueryKind = ValueQuery,201 >;202203 /// Amount of tokens (not pieces) partially owned by an account within a collection.204 #[pallet::storage]205 pub type AccountBalance<T: Config> = StorageNMap<206 Key = (207 Key<Twox64Concat, CollectionId>,208 // Owner209 Key<Blake2_128Concat, T::CrossAccountId>,210 ),211 Value = u32,212 QueryKind = ValueQuery,213 >;214215 /// Amount of token pieces owned by account.216 #[pallet::storage]217 pub type Balance<T: Config> = StorageNMap<218 Key = (219 Key<Twox64Concat, CollectionId>,220 Key<Twox64Concat, TokenId>,221 // Owner222 Key<Blake2_128Concat, T::CrossAccountId>,223 ),224 Value = u128,225 QueryKind = ValueQuery,226 >;227228 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.229 #[pallet::storage]230 pub type Allowance<T: Config> = StorageNMap<231 Key = (232 Key<Twox64Concat, CollectionId>,233 Key<Twox64Concat, TokenId>,234 // Owner235 Key<Blake2_128, T::CrossAccountId>,236 // Spender237 Key<Blake2_128Concat, T::CrossAccountId>,238 ),239 Value = u128,240 QueryKind = ValueQuery,241 >;242243 /// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.244 #[pallet::storage]245 pub type CollectionAllowance<T: Config> = StorageNMap<246 Key = (247 Key<Twox64Concat, CollectionId>,248 Key<Blake2_128Concat, T::CrossAccountId>, // Owner249 Key<Blake2_128Concat, T::CrossAccountId>, // Spender250 ),251 Value = bool,252 QueryKind = ValueQuery,253 >;254}255256pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);257impl<T: Config> RefungibleHandle<T> {258 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {259 Self(inner)260 }261 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {262 self.0263 }264 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {265 &mut self.0266 }267}268269impl<T: Config> Deref for RefungibleHandle<T> {270 type Target = pallet_common::CollectionHandle<T>;271272 fn deref(&self) -> &Self::Target {273 &self.0274 }275}276277impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {278 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {279 self.0.recorder()280 }281 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {282 self.0.into_recorder()283 }284}285286impl<T: Config> Pallet<T> {287 /// Get number of RFT tokens in collection288 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {289 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)290 }291292 /// Check that RFT token exists293 ///294 /// - `token`: Token ID.295 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {296 <TotalSupply<T>>::contains_key((collection.id, token))297 }298299 pub fn set_scoped_token_property(300 collection_id: CollectionId,301 token_id: TokenId,302 scope: PropertyScope,303 property: Property,304 ) -> DispatchResult {305 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {306 properties.try_scoped_set(scope, property.key, property.value)307 })308 .map_err(<CommonError<T>>::from)?;309310 Ok(())311 }312313 pub fn set_scoped_token_properties(314 collection_id: CollectionId,315 token_id: TokenId,316 scope: PropertyScope,317 properties: impl Iterator<Item = Property>,318 ) -> DispatchResult {319 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {320 stored_properties.try_scoped_set_from_iter(scope, properties)321 })322 .map_err(<CommonError<T>>::from)?;323324 Ok(())325 }326}327328// unchecked calls skips any permission checks329impl<T: Config> Pallet<T> {330 /// Create RFT collection331 ///332 /// `init_collection` will take non-refundable deposit for collection creation.333 ///334 /// - `data`: Contains settings for collection limits and permissions.335 pub fn init_collection(336 owner: T::CrossAccountId,337 payer: T::CrossAccountId,338 data: CreateCollectionData<T::AccountId>,339 flags: CollectionFlags,340 ) -> Result<CollectionId, DispatchError> {341 <PalletCommon<T>>::init_collection(owner, payer, data, flags)342 }343344 /// Destroy RFT collection345 ///346 /// `destroy_collection` will throw error if collection contains any tokens.347 /// Only owner can destroy collection.348 pub fn destroy_collection(349 collection: RefungibleHandle<T>,350 sender: &T::CrossAccountId,351 ) -> DispatchResult {352 let id = collection.id;353354 if Self::collection_has_tokens(id) {355 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());356 }357358 // =========359360 PalletCommon::destroy_collection(collection.0, sender)?;361362 <TokensMinted<T>>::remove(id);363 <TokensBurnt<T>>::remove(id);364 let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);365 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);366 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);367 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);368 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);369 Ok(())370 }371372 fn collection_has_tokens(collection_id: CollectionId) -> bool {373 <TotalSupply<T>>::iter_prefix((collection_id,))374 .next()375 .is_some()376 }377378 pub fn burn_token_unchecked(379 collection: &RefungibleHandle<T>,380 owner: &T::CrossAccountId,381 token_id: TokenId,382 ) -> DispatchResult {383 let burnt = <TokensBurnt<T>>::get(collection.id)384 .checked_add(1)385 .ok_or(ArithmeticError::Overflow)?;386387 <TokensBurnt<T>>::insert(collection.id, burnt);388 <TokenProperties<T>>::remove((collection.id, token_id));389 <TotalSupply<T>>::remove((collection.id, token_id));390 let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);391 let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);392 <PalletEvm<T>>::deposit_log(393 ERC721Events::Transfer {394 from: *owner.as_eth(),395 to: H160::default(),396 token_id: token_id.into(),397 }398 .to_log(collection_id_to_address(collection.id)),399 );400 Ok(())401 }402403 /// Burn RFT token pieces404 ///405 /// `burn` will decrease total amount of token pieces and amount owned by sender.406 /// `burn` can be called even if there are multiple owners of the RFT token.407 /// If sender wouldn't have any pieces left after `burn` than she will stop being408 /// one of the owners of the token. If there is no account that owns any pieces of409 /// the token than token will be burned too.410 ///411 /// - `amount`: Amount of token pieces to burn.412 /// - `token`: Token who's pieces should be burned413 /// - `collection`: Collection that contains the token414 pub fn burn(415 collection: &RefungibleHandle<T>,416 owner: &T::CrossAccountId,417 token: TokenId,418 amount: u128,419 ) -> DispatchResult {420 if <Balance<T>>::get((collection.id, token, owner)) == 0 {421 return Err(<CommonError<T>>::TokenValueTooLow.into());422 }423424 let total_supply = <TotalSupply<T>>::get((collection.id, token))425 .checked_sub(amount)426 .ok_or(<CommonError<T>>::TokenValueTooLow)?;427428 // This was probally last owner of this token?429 if total_supply == 0 {430 // Ensure user actually owns this amount431 ensure!(432 <Balance<T>>::get((collection.id, token, owner)) == amount,433 <CommonError<T>>::TokenValueTooLow434 );435 let account_balance = <AccountBalance<T>>::get((collection.id, owner))436 .checked_sub(1)437 // Should not occur438 .ok_or(ArithmeticError::Underflow)?;439440 // =========441442 <Owned<T>>::remove((collection.id, owner, token));443 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);444 <AccountBalance<T>>::insert((collection.id, owner), account_balance);445 Self::burn_token_unchecked(collection, owner, token)?;446 <PalletEvm<T>>::deposit_log(447 ERC20Events::Transfer {448 from: *owner.as_eth(),449 to: H160::default(),450 value: amount.into(),451 }452 .to_log(collection_id_to_address(collection.id)),453 );454 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(455 collection.id,456 token,457 owner.clone(),458 amount,459 ));460 return Ok(());461 }462463 let balance = <Balance<T>>::get((collection.id, token, owner))464 .checked_sub(amount)465 .ok_or(<CommonError<T>>::TokenValueTooLow)?;466 let account_balance = if balance == 0 {467 <AccountBalance<T>>::get((collection.id, owner))468 .checked_sub(1)469 // Should not occur470 .ok_or(ArithmeticError::Underflow)?471 } else {472 0473 };474475 // =========476477 if balance == 0 {478 <Owned<T>>::remove((collection.id, owner, token));479 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);480 <Balance<T>>::remove((collection.id, token, owner));481 <AccountBalance<T>>::insert((collection.id, owner), account_balance);482483 if let Ok(user) = Self::token_owner(collection.id, token) {484 <PalletEvm<T>>::deposit_log(485 ERC721Events::Transfer {486 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,487 to: *user.as_eth(),488 token_id: token.into(),489 }490 .to_log(collection_id_to_address(collection.id)),491 );492 }493 } else {494 <Balance<T>>::insert((collection.id, token, owner), balance);495 }496 <TotalSupply<T>>::insert((collection.id, token), total_supply);497498 <PalletEvm<T>>::deposit_log(499 ERC20Events::Transfer {500 from: *owner.as_eth(),501 to: H160::default(),502 value: amount.into(),503 }504 .to_log(T::EvmTokenAddressMapping::token_to_address(505 collection.id,506 token,507 )),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510 collection.id,511 token,512 owner.clone(),513 amount,514 ));515 Ok(())516 }517518 /// A batch operation to add, edit or remove properties for a token.519 /// It sets or removes a token's properties according to520 /// `properties_updates` contents:521 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`522 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.523 ///524 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.525 /// - `is_token_create`: Indicates that method is called during token initialization.526 /// Allows to bypass ownership check.527 ///528 /// All affected properties should have `mutable` permission529 /// to be **deleted** or to be **set more than once**,530 /// and the sender should have permission to edit those properties.531 ///532 /// This function fires an event for each property change.533 /// In case of an error, all the changes (including the events) will be reverted534 /// since the function is transactional.535 #[transactional]536 fn modify_token_properties(537 collection: &RefungibleHandle<T>,538 sender: &T::CrossAccountId,539 token_id: TokenId,540 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,541 is_token_create: bool,542 nesting_budget: &dyn Budget,543 ) -> DispatchResult {544 let is_token_owner = || -> Result<bool, DispatchError> {545 let balance = collection.balance(sender.clone(), token_id);546 let total_pieces: u128 =547 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);548 if balance != total_pieces {549 return Ok(false);550 }551552 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(553 sender.clone(),554 collection.id,555 token_id,556 None,557 nesting_budget,558 )?;559560 Ok(is_bundle_owner)561 };562563 let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));564565 <PalletCommon<T>>::modify_token_properties(566 collection,567 sender,568 token_id,569 properties_updates,570 is_token_create,571 stored_properties,572 is_token_owner,573 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),574 )575 }576577 pub fn set_token_properties(578 collection: &RefungibleHandle<T>,579 sender: &T::CrossAccountId,580 token_id: TokenId,581 properties: impl Iterator<Item = Property>,582 is_token_create: bool,583 nesting_budget: &dyn Budget,584 ) -> DispatchResult {585 Self::modify_token_properties(586 collection,587 sender,588 token_id,589 properties.map(|p| (p.key, Some(p.value))),590 is_token_create,591 nesting_budget,592 )593 }594595 pub fn set_token_property(596 collection: &RefungibleHandle<T>,597 sender: &T::CrossAccountId,598 token_id: TokenId,599 property: Property,600 nesting_budget: &dyn Budget,601 ) -> DispatchResult {602 let is_token_create = false;603604 Self::set_token_properties(605 collection,606 sender,607 token_id,608 [property].into_iter(),609 is_token_create,610 nesting_budget,611 )612 }613614 pub fn delete_token_properties(615 collection: &RefungibleHandle<T>,616 sender: &T::CrossAccountId,617 token_id: TokenId,618 property_keys: impl Iterator<Item = PropertyKey>,619 nesting_budget: &dyn Budget,620 ) -> DispatchResult {621 let is_token_create = false;622623 Self::modify_token_properties(624 collection,625 sender,626 token_id,627 property_keys.into_iter().map(|key| (key, None)),628 is_token_create,629 nesting_budget,630 )631 }632633 pub fn delete_token_property(634 collection: &RefungibleHandle<T>,635 sender: &T::CrossAccountId,636 token_id: TokenId,637 property_key: PropertyKey,638 nesting_budget: &dyn Budget,639 ) -> DispatchResult {640 Self::delete_token_properties(641 collection,642 sender,643 token_id,644 [property_key].into_iter(),645 nesting_budget,646 )647 }648649 /// Transfer RFT token pieces from one account to another.650 ///651 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.652 ///653 /// - `from`: Owner of token pieces to transfer.654 /// - `to`: Recepient of transfered token pieces.655 /// - `amount`: Amount of token pieces to transfer.656 /// - `token`: Token whos pieces should be transfered657 /// - `collection`: Collection that contains the token658 pub fn transfer(659 collection: &RefungibleHandle<T>,660 from: &T::CrossAccountId,661 to: &T::CrossAccountId,662 token: TokenId,663 amount: u128,664 nesting_budget: &dyn Budget,665 ) -> DispatchResult {666 ensure!(667 collection.limits.transfers_enabled(),668 <CommonError<T>>::TransferNotAllowed669 );670671 if collection.permissions.access() == AccessMode::AllowList {672 collection.check_allowlist(from)?;673 collection.check_allowlist(to)?;674 }675 <PalletCommon<T>>::ensure_correct_receiver(to)?;676677 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));678679 if initial_balance_from == 0 {680 return Err(<CommonError<T>>::TokenValueTooLow.into());681 }682683 let updated_balance_from = initial_balance_from684 .checked_sub(amount)685 .ok_or(<CommonError<T>>::TokenValueTooLow)?;686 let mut create_target = false;687 let from_to_differ = from != to;688 let updated_balance_to = if from != to && amount != 0 {689 let old_balance = <Balance<T>>::get((collection.id, token, to));690 if old_balance == 0 {691 create_target = true;692 }693 Some(694 old_balance695 .checked_add(amount)696 .ok_or(ArithmeticError::Overflow)?,697 )698 } else {699 None700 };701702 let account_balance_from = if updated_balance_from == 0 {703 Some(704 <AccountBalance<T>>::get((collection.id, from))705 .checked_sub(1)706 // Should not occur707 .ok_or(ArithmeticError::Underflow)?,708 )709 } else {710 None711 };712 // Account data is created in token, AccountBalance should be increased713 // But only if from != to as we shouldn't check overflow in this case714 let account_balance_to = if create_target && from_to_differ {715 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))716 .checked_add(1)717 .ok_or(ArithmeticError::Overflow)?;718 ensure!(719 account_balance_to < collection.limits.account_token_ownership_limit(),720 <CommonError<T>>::AccountTokenLimitExceeded,721 );722723 Some(account_balance_to)724 } else {725 None726 };727728 // =========729730 if let Some(updated_balance_to) = updated_balance_to {731 // from != to && amount != 0732733 <PalletStructure<T>>::nest_if_sent_to_token(734 from.clone(),735 to,736 collection.id,737 token,738 nesting_budget,739 )?;740741 if updated_balance_from == 0 {742 <Balance<T>>::remove((collection.id, token, from));743 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);744 } else {745 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);746 }747 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);748 if let Some(account_balance_from) = account_balance_from {749 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);750 <Owned<T>>::remove((collection.id, from, token));751 }752 if let Some(account_balance_to) = account_balance_to {753 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);754 <Owned<T>>::insert((collection.id, to, token), true);755 }756 }757758 <PalletEvm<T>>::deposit_log(759 ERC20Events::Transfer {760 from: *from.as_eth(),761 to: *to.as_eth(),762 value: amount.into(),763 }764 .to_log(T::EvmTokenAddressMapping::token_to_address(765 collection.id,766 token,767 )),768 );769770 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(771 collection.id,772 token,773 from.clone(),774 to.clone(),775 amount,776 ));777778 let total_supply = <TotalSupply<T>>::get((collection.id, token));779780 if amount == total_supply {781 // if token was fully owned by `from` and will be fully owned by `to` after transfer782 <PalletEvm<T>>::deposit_log(783 ERC721Events::Transfer {784 from: *from.as_eth(),785 to: *to.as_eth(),786 token_id: token.into(),787 }788 .to_log(collection_id_to_address(collection.id)),789 );790 } else if let Some(updated_balance_to) = updated_balance_to {791 // if `from` not equals `to`. This condition is needed to avoid sending event792 // when `from` fully owns token and sends part of token pieces to itself.793 if initial_balance_from == total_supply {794 // if token was fully owned by `from` and will be only partially owned by `to`795 // and `from` after transfer796 <PalletEvm<T>>::deposit_log(797 ERC721Events::Transfer {798 from: *from.as_eth(),799 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,800 token_id: token.into(),801 }802 .to_log(collection_id_to_address(collection.id)),803 );804 } else if updated_balance_to == total_supply {805 // if token was partially owned by `from` and will be fully owned by `to` after transfer806 <PalletEvm<T>>::deposit_log(807 ERC721Events::Transfer {808 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,809 to: *to.as_eth(),810 token_id: token.into(),811 }812 .to_log(collection_id_to_address(collection.id)),813 );814 }815 }816817 Ok(())818 }819820 /// Batched operation to create multiple RFT tokens.821 ///822 /// Same as `create_item` but creates multiple tokens.823 ///824 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.825 pub fn create_multiple_items(826 collection: &RefungibleHandle<T>,827 sender: &T::CrossAccountId,828 data: Vec<CreateItemData<T>>,829 nesting_budget: &dyn Budget,830 ) -> DispatchResult {831 if !collection.is_owner_or_admin(sender) {832 ensure!(833 collection.permissions.mint_mode(),834 <CommonError<T>>::PublicMintingNotAllowed835 );836 collection.check_allowlist(sender)?;837838 for item in data.iter() {839 for user in item.users.keys() {840 collection.check_allowlist(user)?;841 }842 }843 }844845 for item in data.iter() {846 for (owner, _) in item.users.iter() {847 <PalletCommon<T>>::ensure_correct_receiver(owner)?;848 }849 }850851 // Total pieces per tokens852 let totals = data853 .iter()854 .map(|data| {855 Ok(data856 .users857 .iter()858 .map(|u| u.1)859 .try_fold(0u128, |acc, v| acc.checked_add(*v))860 .ok_or(ArithmeticError::Overflow)?)861 })862 .collect::<Result<Vec<_>, DispatchError>>()?;863 for total in &totals {864 ensure!(865 *total <= MAX_REFUNGIBLE_PIECES,866 <Error<T>>::WrongRefungiblePieces867 );868 }869870 let first_token_id = <TokensMinted<T>>::get(collection.id);871 let tokens_minted = first_token_id872 .checked_add(data.len() as u32)873 .ok_or(ArithmeticError::Overflow)?;874 ensure!(875 tokens_minted < collection.limits.token_limit(),876 <CommonError<T>>::CollectionTokenLimitExceeded877 );878879 let mut balances = BTreeMap::new();880 for data in &data {881 for owner in data.users.keys() {882 let balance = balances883 .entry(owner)884 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));885 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;886887 ensure!(888 *balance <= collection.limits.account_token_ownership_limit(),889 <CommonError<T>>::AccountTokenLimitExceeded,890 );891 }892 }893894 for (i, token) in data.iter().enumerate() {895 let token_id = TokenId(first_token_id + i as u32 + 1);896 for (to, _) in token.users.iter() {897 <PalletStructure<T>>::check_nesting(898 sender.clone(),899 to,900 collection.id,901 token_id,902 nesting_budget,903 )?;904 }905 }906907 // =========908909 with_transaction(|| {910 for (i, data) in data.iter().enumerate() {911 let token_id = first_token_id + i as u32 + 1;912 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);913914 for (user, amount) in data.users.iter() {915 if *amount == 0 {916 continue;917 }918 <Balance<T>>::insert((collection.id, token_id, &user), amount);919 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);920 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(921 user,922 collection.id,923 TokenId(token_id),924 );925 }926927 if let Err(e) = Self::set_token_properties(928 collection,929 sender,930 TokenId(token_id),931 data.properties.clone().into_iter(),932 true,933 nesting_budget,934 ) {935 return TransactionOutcome::Rollback(Err(e));936 }937 }938 TransactionOutcome::Commit(Ok(()))939 })?;940941 <TokensMinted<T>>::insert(collection.id, tokens_minted);942943 for (account, balance) in balances {944 <AccountBalance<T>>::insert((collection.id, account), balance);945 }946947 for (i, token) in data.into_iter().enumerate() {948 let token_id = first_token_id + i as u32 + 1;949950 let receivers = token951 .users952 .into_iter()953 .filter(|(_, amount)| *amount > 0)954 .collect::<Vec<_>>();955956 if let [(user, _)] = receivers.as_slice() {957 // if there is exactly one receiver958 <PalletEvm<T>>::deposit_log(959 ERC721Events::Transfer {960 from: H160::default(),961 to: *user.as_eth(),962 token_id: token_id.into(),963 }964 .to_log(collection_id_to_address(collection.id)),965 );966 } else if let [_, ..] = receivers.as_slice() {967 // if there is more than one receiver968 <PalletEvm<T>>::deposit_log(969 ERC721Events::Transfer {970 from: H160::default(),971 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,972 token_id: token_id.into(),973 }974 .to_log(collection_id_to_address(collection.id)),975 );976 }977978 for (user, amount) in receivers.into_iter() {979 <PalletEvm<T>>::deposit_log(980 ERC20Events::Transfer {981 from: H160::default(),982 to: *user.as_eth(),983 value: amount.into(),984 }985 .to_log(T::EvmTokenAddressMapping::token_to_address(986 collection.id,987 TokenId(token_id),988 )),989 );990 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(991 collection.id,992 TokenId(token_id),993 user,994 amount,995 ));996 }997 }998 Ok(())999 }10001001 pub fn set_allowance_unchecked(1002 collection: &RefungibleHandle<T>,1003 sender: &T::CrossAccountId,1004 spender: &T::CrossAccountId,1005 token: TokenId,1006 amount: u128,1007 ) {1008 if amount == 0 {1009 <Allowance<T>>::remove((collection.id, token, sender, spender));1010 } else {1011 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1012 }10131014 <PalletEvm<T>>::deposit_log(1015 ERC20Events::Approval {1016 owner: *sender.as_eth(),1017 spender: *spender.as_eth(),1018 value: amount.into(),1019 }1020 .to_log(T::EvmTokenAddressMapping::token_to_address(1021 collection.id,1022 token,1023 )),1024 );1025 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1026 collection.id,1027 token,1028 sender.clone(),1029 spender.clone(),1030 amount,1031 ))1032 }10331034 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1035 ///1036 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1037 pub fn set_allowance(1038 collection: &RefungibleHandle<T>,1039 sender: &T::CrossAccountId,1040 spender: &T::CrossAccountId,1041 token: TokenId,1042 amount: u128,1043 ) -> DispatchResult {1044 if collection.permissions.access() == AccessMode::AllowList {1045 collection.check_allowlist(sender)?;1046 collection.check_allowlist(spender)?;1047 }10481049 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10501051 if <Balance<T>>::get((collection.id, token, sender)) < amount {1052 ensure!(1053 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1054 <CommonError<T>>::CantApproveMoreThanOwned1055 );1056 }10571058 // =========10591060 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1061 Ok(())1062 }10631064 /// Set allowance to spend from sender's eth mirror1065 ///1066 /// - `from`: Address of sender's eth mirror.1067 /// - `to`: Adress of spender.1068 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1069 pub fn set_allowance_from(1070 collection: &RefungibleHandle<T>,1071 sender: &T::CrossAccountId,1072 from: &T::CrossAccountId,1073 to: &T::CrossAccountId,1074 token_id: TokenId,1075 amount: u128,1076 ) -> DispatchResult {1077 if collection.permissions.access() == AccessMode::AllowList {1078 collection.check_allowlist(sender)?;1079 collection.check_allowlist(from)?;1080 collection.check_allowlist(to)?;1081 }10821083 <PalletCommon<T>>::ensure_correct_receiver(to)?;10841085 ensure!(1086 sender.conv_eq(from),1087 <CommonError<T>>::AddressIsNotEthMirror1088 );10891090 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1091 ensure!(1092 collection.limits.owner_can_transfer()1093 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1094 && Self::token_exists(collection, token_id),1095 <CommonError<T>>::CantApproveMoreThanOwned1096 );1097 }10981099 // =========11001101 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1102 Ok(())1103 }11041105 /// Returns allowance, which should be set after transaction1106 fn check_allowed(1107 collection: &RefungibleHandle<T>,1108 spender: &T::CrossAccountId,1109 from: &T::CrossAccountId,1110 token: TokenId,1111 amount: u128,1112 nesting_budget: &dyn Budget,1113 ) -> Result<Option<u128>, DispatchError> {1114 if spender.conv_eq(from) {1115 return Ok(None);1116 }1117 if collection.permissions.access() == AccessMode::AllowList {1118 // `from`, `to` checked in [`transfer`]1119 collection.check_allowlist(spender)?;1120 }11211122 if collection.ignores_token_restrictions(spender) {1123 return Ok(Self::compute_allowance_decrease(1124 collection, token, from, &spender, amount,1125 ));1126 }11271128 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1129 // TODO: should collection owner be allowed to perform this transfer?1130 ensure!(1131 <PalletStructure<T>>::check_indirectly_owned(1132 spender.clone(),1133 source.0,1134 source.1,1135 None,1136 nesting_budget1137 )?,1138 <CommonError<T>>::ApprovedValueTooLow,1139 );1140 return Ok(None);1141 }11421143 let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);1144 if allowance.is_some() {1145 return Ok(allowance);1146 }11471148 // Allowance (if any) would be reduced if spender is also wallet operator1149 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1150 return Ok(allowance);1151 }11521153 Err(<CommonError<T>>::ApprovedValueTooLow.into())1154 }11551156 /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1157 /// Otherwise, it returns `None`.1158 fn compute_allowance_decrease(1159 collection: &RefungibleHandle<T>,1160 token: TokenId,1161 from: &T::CrossAccountId,1162 spender: &T::CrossAccountId,1163 amount: u128,1164 ) -> Option<u128> {1165 <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1166 }11671168 /// Transfer RFT token pieces from one account to another.1169 ///1170 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1171 /// The owner should set allowance for the spender to transfer pieces.1172 ///1173 /// [`transfer`]: struct.Pallet.html#method.transfer1174 pub fn transfer_from(1175 collection: &RefungibleHandle<T>,1176 spender: &T::CrossAccountId,1177 from: &T::CrossAccountId,1178 to: &T::CrossAccountId,1179 token: TokenId,1180 amount: u128,1181 nesting_budget: &dyn Budget,1182 ) -> DispatchResult {1183 let allowance =1184 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11851186 // =========11871188 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1189 if let Some(allowance) = allowance {1190 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1191 }1192 Ok(())1193 }11941195 /// Burn RFT token pieces from the account.1196 ///1197 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1198 /// set allowance for the spender to burn pieces1199 ///1200 /// [`burn`]: struct.Pallet.html#method.burn1201 pub fn burn_from(1202 collection: &RefungibleHandle<T>,1203 spender: &T::CrossAccountId,1204 from: &T::CrossAccountId,1205 token: TokenId,1206 amount: u128,1207 nesting_budget: &dyn Budget,1208 ) -> DispatchResult {1209 let allowance =1210 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12111212 // =========12131214 Self::burn(collection, from, token, amount)?;1215 if let Some(allowance) = allowance {1216 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1217 }1218 Ok(())1219 }12201221 /// Create RFT token.1222 ///1223 /// The sender should be the owner/admin of the collection or collection should be configured1224 /// to allow public minting.1225 ///1226 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1227 /// of token pieces they will receive.1228 pub fn create_item(1229 collection: &RefungibleHandle<T>,1230 sender: &T::CrossAccountId,1231 data: CreateItemData<T>,1232 nesting_budget: &dyn Budget,1233 ) -> DispatchResult {1234 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1235 }12361237 /// Repartition RFT token.1238 ///1239 /// `repartition` will set token balance of the sender and total amount of token pieces.1240 /// Sender should own all of the token pieces. `repartition' could be done even if some1241 /// token pieces were burned before.1242 ///1243 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1244 pub fn repartition(1245 collection: &RefungibleHandle<T>,1246 owner: &T::CrossAccountId,1247 token: TokenId,1248 amount: u128,1249 ) -> DispatchResult {1250 ensure!(1251 amount <= MAX_REFUNGIBLE_PIECES,1252 <Error<T>>::WrongRefungiblePieces1253 );1254 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1255 // Ensure user owns all pieces1256 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1257 let balance = <Balance<T>>::get((collection.id, token, owner));1258 ensure!(1259 total_pieces == balance,1260 <Error<T>>::RepartitionWhileNotOwningAllPieces1261 );12621263 <Balance<T>>::insert((collection.id, token, owner), amount);1264 <TotalSupply<T>>::insert((collection.id, token), amount);12651266 if amount > total_pieces {1267 let mint_amount = amount - total_pieces;1268 <PalletEvm<T>>::deposit_log(1269 ERC20Events::Transfer {1270 from: H160::default(),1271 to: *owner.as_eth(),1272 value: mint_amount.into(),1273 }1274 .to_log(T::EvmTokenAddressMapping::token_to_address(1275 collection.id,1276 token,1277 )),1278 );1279 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1280 collection.id,1281 token,1282 owner.clone(),1283 mint_amount,1284 ));1285 } else if total_pieces > amount {1286 let burn_amount = total_pieces - amount;1287 <PalletEvm<T>>::deposit_log(1288 ERC20Events::Transfer {1289 from: *owner.as_eth(),1290 to: H160::default(),1291 value: burn_amount.into(),1292 }1293 .to_log(T::EvmTokenAddressMapping::token_to_address(1294 collection.id,1295 token,1296 )),1297 );1298 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1299 collection.id,1300 token,1301 owner.clone(),1302 burn_amount,1303 ));1304 }13051306 Ok(())1307 }13081309 fn token_owner(1310 collection_id: CollectionId,1311 token_id: TokenId,1312 ) -> Result<T::CrossAccountId, TokenOwnerError> {1313 let mut owner = None;1314 let mut count = 0;1315 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1316 count += 1;1317 if count > 1 {1318 return Err(TokenOwnerError::MultipleOwners);1319 }1320 owner = Some(key);1321 }1322 owner.ok_or(TokenOwnerError::NotFound)1323 }13241325 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1326 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1327 }13281329 pub fn set_collection_properties(1330 collection: &RefungibleHandle<T>,1331 sender: &T::CrossAccountId,1332 properties: Vec<Property>,1333 ) -> DispatchResult {1334 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1335 }13361337 pub fn delete_collection_properties(1338 collection: &RefungibleHandle<T>,1339 sender: &T::CrossAccountId,1340 property_keys: Vec<PropertyKey>,1341 ) -> DispatchResult {1342 <PalletCommon<T>>::delete_collection_properties(1343 collection,1344 sender,1345 property_keys.into_iter(),1346 )1347 }13481349 pub fn set_token_property_permissions(1350 collection: &RefungibleHandle<T>,1351 sender: &T::CrossAccountId,1352 property_permissions: Vec<PropertyKeyPermission>,1353 ) -> DispatchResult {1354 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1355 }13561357 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1358 <PalletCommon<T>>::property_permissions(collection_id)1359 }13601361 pub fn set_scoped_token_property_permissions(1362 collection: &RefungibleHandle<T>,1363 sender: &T::CrossAccountId,1364 scope: PropertyScope,1365 property_permissions: Vec<PropertyKeyPermission>,1366 ) -> DispatchResult {1367 <PalletCommon<T>>::set_scoped_token_property_permissions(1368 collection,1369 sender,1370 scope,1371 property_permissions,1372 )1373 }13741375 /// Returns 10 token in no particular order.1376 ///1377 /// There is no direct way to get token holders in ascending order,1378 /// since `iter_prefix` returns values in no particular order.1379 /// Therefore, getting the 10 largest holders with a large value of holders1380 /// can lead to impact memory allocation + sorting with `n * log (n)`.1381 pub fn token_owners(1382 collection_id: CollectionId,1383 token: TokenId,1384 ) -> Option<Vec<T::CrossAccountId>> {1385 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1386 .map(|(owner, _amount)| owner)1387 .take(10)1388 .collect();13891390 if res.is_empty() {1391 None1392 } else {1393 Some(res)1394 }1395 }13961397 /// Sets or unsets the approval of a given operator.1398 ///1399 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1400 /// - `owner`: Token owner1401 /// - `operator`: Operator1402 /// - `approve`: Should operator status be granted or revoked?1403 pub fn set_allowance_for_all(1404 collection: &RefungibleHandle<T>,1405 owner: &T::CrossAccountId,1406 spender: &T::CrossAccountId,1407 approve: bool,1408 ) -> DispatchResult {1409 <PalletCommon<T>>::set_allowance_for_all(1410 collection,1411 owner,1412 spender,1413 approve,1414 || <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1415 ERC721Events::ApprovalForAll {1416 owner: *owner.as_eth(),1417 operator: *spender.as_eth(),1418 approved: approve,1419 }1420 .to_log(collection_id_to_address(collection.id)),1421 )1422 }14231424 /// Tells whether the given `owner` approves the `operator`.1425 pub fn allowance_for_all(1426 collection: &RefungibleHandle<T>,1427 owner: &T::CrossAccountId,1428 spender: &T::CrossAccountId,1429 ) -> bool {1430 <CollectionAllowance<T>>::get((collection.id, owner, spender))1431 }14321433 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1434 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1435 properties.recompute_consumed_space();1436 });14371438 Ok(())1439 }1440}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//! of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//! Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//! transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//! an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//! with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//! collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//! Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{ensure, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99 CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,100 Event as CommonEvent, Pallet as PalletCommon,101};102use pallet_structure::Pallet as PalletStructure;103use sp_core::{Get, H160};104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107 AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,108 mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,109 PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TrySetProperty,110 PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120121pub type CreateItemData<T> =122 CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;123pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;124125#[frame_support::pallet]126pub mod pallet {127 use super::*;128 use frame_support::{129 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,130 traits::StorageVersion,131 };132 use up_data_structs::{CollectionId, TokenId};133 use super::weights::WeightInfo;134135 #[pallet::error]136 pub enum Error<T> {137 /// Not Refungible item data used to mint in Refungible collection.138 NotRefungibleDataUsedToMintFungibleCollectionToken,139 /// Maximum refungibility exceeded.140 WrongRefungiblePieces,141 /// Refungible token can't be repartitioned by user who isn't owns all pieces.142 RepartitionWhileNotOwningAllPieces,143 /// Refungible token can't nest other tokens.144 RefungibleDisallowsNesting,145 /// Setting item properties is not allowed.146 SettingPropertiesNotAllowed,147 }148149 #[pallet::config]150 pub trait Config:151 frame_system::Config + pallet_common::Config + pallet_structure::Config152 {153 type WeightInfo: WeightInfo;154 }155156 const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);157158 #[pallet::pallet]159 #[pallet::storage_version(STORAGE_VERSION)]160 #[pallet::generate_store(pub(super) trait Store)]161 pub struct Pallet<T>(_);162163 /// Total amount of minted tokens in a collection.164 #[pallet::storage]165 pub type TokensMinted<T: Config> =166 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;167168 /// Amount of tokens burnt in a collection.169 #[pallet::storage]170 pub type TokensBurnt<T: Config> =171 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;172173 /// Amount of pieces a refungible token is split into.174 #[pallet::storage]175 #[pallet::getter(fn token_properties)]176 pub type TokenProperties<T: Config> = StorageNMap<177 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),178 Value = up_data_structs::Properties,179 QueryKind = ValueQuery,180 OnEmpty = up_data_structs::TokenProperties,181 >;182183 /// Total amount of pieces for token184 #[pallet::storage]185 pub type TotalSupply<T: Config> = StorageNMap<186 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),187 Value = u128,188 QueryKind = ValueQuery,189 >;190191 /// Used to enumerate tokens owned by account.192 #[pallet::storage]193 pub type Owned<T: Config> = StorageNMap<194 Key = (195 Key<Twox64Concat, CollectionId>,196 Key<Blake2_128Concat, T::CrossAccountId>,197 Key<Twox64Concat, TokenId>,198 ),199 Value = bool,200 QueryKind = ValueQuery,201 >;202203 /// Amount of tokens (not pieces) partially owned by an account within a collection.204 #[pallet::storage]205 pub type AccountBalance<T: Config> = StorageNMap<206 Key = (207 Key<Twox64Concat, CollectionId>,208 // Owner209 Key<Blake2_128Concat, T::CrossAccountId>,210 ),211 Value = u32,212 QueryKind = ValueQuery,213 >;214215 /// Amount of token pieces owned by account.216 #[pallet::storage]217 pub type Balance<T: Config> = StorageNMap<218 Key = (219 Key<Twox64Concat, CollectionId>,220 Key<Twox64Concat, TokenId>,221 // Owner222 Key<Blake2_128Concat, T::CrossAccountId>,223 ),224 Value = u128,225 QueryKind = ValueQuery,226 >;227228 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.229 #[pallet::storage]230 pub type Allowance<T: Config> = StorageNMap<231 Key = (232 Key<Twox64Concat, CollectionId>,233 Key<Twox64Concat, TokenId>,234 // Owner235 Key<Blake2_128, T::CrossAccountId>,236 // Spender237 Key<Blake2_128Concat, T::CrossAccountId>,238 ),239 Value = u128,240 QueryKind = ValueQuery,241 >;242243 /// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.244 #[pallet::storage]245 pub type CollectionAllowance<T: Config> = StorageNMap<246 Key = (247 Key<Twox64Concat, CollectionId>,248 Key<Blake2_128Concat, T::CrossAccountId>, // Owner249 Key<Blake2_128Concat, T::CrossAccountId>, // Spender250 ),251 Value = bool,252 QueryKind = ValueQuery,253 >;254}255256pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);257impl<T: Config> RefungibleHandle<T> {258 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {259 Self(inner)260 }261 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {262 self.0263 }264 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {265 &mut self.0266 }267}268269impl<T: Config> Deref for RefungibleHandle<T> {270 type Target = pallet_common::CollectionHandle<T>;271272 fn deref(&self) -> &Self::Target {273 &self.0274 }275}276277impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {278 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {279 self.0.recorder()280 }281 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {282 self.0.into_recorder()283 }284}285286impl<T: Config> Pallet<T> {287 /// Get number of RFT tokens in collection288 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {289 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)290 }291292 /// Check that RFT token exists293 ///294 /// - `token`: Token ID.295 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {296 <TotalSupply<T>>::contains_key((collection.id, token))297 }298299 pub fn set_scoped_token_property(300 collection_id: CollectionId,301 token_id: TokenId,302 scope: PropertyScope,303 property: Property,304 ) -> DispatchResult {305 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {306 properties.try_scoped_set(scope, property.key, property.value)307 })308 .map_err(<CommonError<T>>::from)?;309310 Ok(())311 }312313 pub fn set_scoped_token_properties(314 collection_id: CollectionId,315 token_id: TokenId,316 scope: PropertyScope,317 properties: impl Iterator<Item = Property>,318 ) -> DispatchResult {319 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {320 stored_properties.try_scoped_set_from_iter(scope, properties)321 })322 .map_err(<CommonError<T>>::from)?;323324 Ok(())325 }326}327328// unchecked calls skips any permission checks329impl<T: Config> Pallet<T> {330 /// Create RFT collection331 ///332 /// `init_collection` will take non-refundable deposit for collection creation.333 ///334 /// - `data`: Contains settings for collection limits and permissions.335 pub fn init_collection(336 owner: T::CrossAccountId,337 payer: T::CrossAccountId,338 data: CreateCollectionData<T::AccountId>,339 flags: CollectionFlags,340 ) -> Result<CollectionId, DispatchError> {341 <PalletCommon<T>>::init_collection(owner, payer, data, flags)342 }343344 /// Destroy RFT collection345 ///346 /// `destroy_collection` will throw error if collection contains any tokens.347 /// Only owner can destroy collection.348 pub fn destroy_collection(349 collection: RefungibleHandle<T>,350 sender: &T::CrossAccountId,351 ) -> DispatchResult {352 let id = collection.id;353354 if Self::collection_has_tokens(id) {355 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());356 }357358 // =========359360 PalletCommon::destroy_collection(collection.0, sender)?;361362 <TokensMinted<T>>::remove(id);363 <TokensBurnt<T>>::remove(id);364 let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);365 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);366 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);367 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);368 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);369 Ok(())370 }371372 fn collection_has_tokens(collection_id: CollectionId) -> bool {373 <TotalSupply<T>>::iter_prefix((collection_id,))374 .next()375 .is_some()376 }377378 pub fn burn_token_unchecked(379 collection: &RefungibleHandle<T>,380 owner: &T::CrossAccountId,381 token_id: TokenId,382 ) -> DispatchResult {383 let burnt = <TokensBurnt<T>>::get(collection.id)384 .checked_add(1)385 .ok_or(ArithmeticError::Overflow)?;386387 <TokensBurnt<T>>::insert(collection.id, burnt);388 <TokenProperties<T>>::remove((collection.id, token_id));389 <TotalSupply<T>>::remove((collection.id, token_id));390 let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);391 let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);392 <PalletEvm<T>>::deposit_log(393 ERC721Events::Transfer {394 from: *owner.as_eth(),395 to: H160::default(),396 token_id: token_id.into(),397 }398 .to_log(collection_id_to_address(collection.id)),399 );400 Ok(())401 }402403 /// Burn RFT token pieces404 ///405 /// `burn` will decrease total amount of token pieces and amount owned by sender.406 /// `burn` can be called even if there are multiple owners of the RFT token.407 /// If sender wouldn't have any pieces left after `burn` than she will stop being408 /// one of the owners of the token. If there is no account that owns any pieces of409 /// the token than token will be burned too.410 ///411 /// - `amount`: Amount of token pieces to burn.412 /// - `token`: Token who's pieces should be burned413 /// - `collection`: Collection that contains the token414 pub fn burn(415 collection: &RefungibleHandle<T>,416 owner: &T::CrossAccountId,417 token: TokenId,418 amount: u128,419 ) -> DispatchResult {420 if <Balance<T>>::get((collection.id, token, owner)) == 0 {421 return Err(<CommonError<T>>::TokenValueTooLow.into());422 }423424 let total_supply = <TotalSupply<T>>::get((collection.id, token))425 .checked_sub(amount)426 .ok_or(<CommonError<T>>::TokenValueTooLow)?;427428 // This was probally last owner of this token?429 if total_supply == 0 {430 // Ensure user actually owns this amount431 ensure!(432 <Balance<T>>::get((collection.id, token, owner)) == amount,433 <CommonError<T>>::TokenValueTooLow434 );435 let account_balance = <AccountBalance<T>>::get((collection.id, owner))436 .checked_sub(1)437 // Should not occur438 .ok_or(ArithmeticError::Underflow)?;439440 // =========441442 <Owned<T>>::remove((collection.id, owner, token));443 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);444 <AccountBalance<T>>::insert((collection.id, owner), account_balance);445 Self::burn_token_unchecked(collection, owner, token)?;446 <PalletEvm<T>>::deposit_log(447 ERC20Events::Transfer {448 from: *owner.as_eth(),449 to: H160::default(),450 value: amount.into(),451 }452 .to_log(collection_id_to_address(collection.id)),453 );454 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(455 collection.id,456 token,457 owner.clone(),458 amount,459 ));460 return Ok(());461 }462463 let balance = <Balance<T>>::get((collection.id, token, owner))464 .checked_sub(amount)465 .ok_or(<CommonError<T>>::TokenValueTooLow)?;466 let account_balance = if balance == 0 {467 <AccountBalance<T>>::get((collection.id, owner))468 .checked_sub(1)469 // Should not occur470 .ok_or(ArithmeticError::Underflow)?471 } else {472 0473 };474475 // =========476477 if balance == 0 {478 <Owned<T>>::remove((collection.id, owner, token));479 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);480 <Balance<T>>::remove((collection.id, token, owner));481 <AccountBalance<T>>::insert((collection.id, owner), account_balance);482483 if let Ok(user) = Self::token_owner(collection.id, token) {484 <PalletEvm<T>>::deposit_log(485 ERC721Events::Transfer {486 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,487 to: *user.as_eth(),488 token_id: token.into(),489 }490 .to_log(collection_id_to_address(collection.id)),491 );492 }493 } else {494 <Balance<T>>::insert((collection.id, token, owner), balance);495 }496 <TotalSupply<T>>::insert((collection.id, token), total_supply);497498 <PalletEvm<T>>::deposit_log(499 ERC20Events::Transfer {500 from: *owner.as_eth(),501 to: H160::default(),502 value: amount.into(),503 }504 .to_log(T::EvmTokenAddressMapping::token_to_address(505 collection.id,506 token,507 )),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510 collection.id,511 token,512 owner.clone(),513 amount,514 ));515 Ok(())516 }517518 /// A batch operation to add, edit or remove properties for a token.519 /// It sets or removes a token's properties according to520 /// `properties_updates` contents:521 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`522 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.523 ///524 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.525 /// - `is_token_create`: Indicates that method is called during token initialization.526 /// Allows to bypass ownership check.527 ///528 /// All affected properties should have `mutable` permission529 /// to be **deleted** or to be **set more than once**,530 /// and the sender should have permission to edit those properties.531 ///532 /// This function fires an event for each property change.533 /// In case of an error, all the changes (including the events) will be reverted534 /// since the function is transactional.535 #[transactional]536 fn modify_token_properties(537 collection: &RefungibleHandle<T>,538 sender: &T::CrossAccountId,539 token_id: TokenId,540 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,541 is_token_create: bool,542 nesting_budget: &dyn Budget,543 ) -> DispatchResult {544 let is_token_owner = || -> Result<bool, DispatchError> {545 let balance = collection.balance(sender.clone(), token_id);546 let total_pieces: u128 =547 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);548 if balance != total_pieces {549 return Ok(false);550 }551552 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(553 sender.clone(),554 collection.id,555 token_id,556 None,557 nesting_budget,558 )?;559560 Ok(is_bundle_owner)561 };562563 let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));564565 <PalletCommon<T>>::modify_token_properties(566 collection,567 sender,568 token_id,569 properties_updates,570 is_token_create,571 stored_properties,572 is_token_owner,573 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),574 erc::ERC721TokenEvent::TokenChanged {575 token_id: token_id.into(),576 }577 .to_log(T::ContractAddress::get()),578 )579 }580581 pub fn set_token_properties(582 collection: &RefungibleHandle<T>,583 sender: &T::CrossAccountId,584 token_id: TokenId,585 properties: impl Iterator<Item = Property>,586 is_token_create: bool,587 nesting_budget: &dyn Budget,588 ) -> DispatchResult {589 Self::modify_token_properties(590 collection,591 sender,592 token_id,593 properties.map(|p| (p.key, Some(p.value))),594 is_token_create,595 nesting_budget,596 )597 }598599 pub fn set_token_property(600 collection: &RefungibleHandle<T>,601 sender: &T::CrossAccountId,602 token_id: TokenId,603 property: Property,604 nesting_budget: &dyn Budget,605 ) -> DispatchResult {606 let is_token_create = false;607608 Self::set_token_properties(609 collection,610 sender,611 token_id,612 [property].into_iter(),613 is_token_create,614 nesting_budget,615 )616 }617618 pub fn delete_token_properties(619 collection: &RefungibleHandle<T>,620 sender: &T::CrossAccountId,621 token_id: TokenId,622 property_keys: impl Iterator<Item = PropertyKey>,623 nesting_budget: &dyn Budget,624 ) -> DispatchResult {625 let is_token_create = false;626627 Self::modify_token_properties(628 collection,629 sender,630 token_id,631 property_keys.into_iter().map(|key| (key, None)),632 is_token_create,633 nesting_budget,634 )635 }636637 pub fn delete_token_property(638 collection: &RefungibleHandle<T>,639 sender: &T::CrossAccountId,640 token_id: TokenId,641 property_key: PropertyKey,642 nesting_budget: &dyn Budget,643 ) -> DispatchResult {644 Self::delete_token_properties(645 collection,646 sender,647 token_id,648 [property_key].into_iter(),649 nesting_budget,650 )651 }652653 /// Transfer RFT token pieces from one account to another.654 ///655 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.656 ///657 /// - `from`: Owner of token pieces to transfer.658 /// - `to`: Recepient of transfered token pieces.659 /// - `amount`: Amount of token pieces to transfer.660 /// - `token`: Token whos pieces should be transfered661 /// - `collection`: Collection that contains the token662 pub fn transfer(663 collection: &RefungibleHandle<T>,664 from: &T::CrossAccountId,665 to: &T::CrossAccountId,666 token: TokenId,667 amount: u128,668 nesting_budget: &dyn Budget,669 ) -> DispatchResult {670 ensure!(671 collection.limits.transfers_enabled(),672 <CommonError<T>>::TransferNotAllowed673 );674675 if collection.permissions.access() == AccessMode::AllowList {676 collection.check_allowlist(from)?;677 collection.check_allowlist(to)?;678 }679 <PalletCommon<T>>::ensure_correct_receiver(to)?;680681 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));682683 if initial_balance_from == 0 {684 return Err(<CommonError<T>>::TokenValueTooLow.into());685 }686687 let updated_balance_from = initial_balance_from688 .checked_sub(amount)689 .ok_or(<CommonError<T>>::TokenValueTooLow)?;690 let mut create_target = false;691 let from_to_differ = from != to;692 let updated_balance_to = if from != to && amount != 0 {693 let old_balance = <Balance<T>>::get((collection.id, token, to));694 if old_balance == 0 {695 create_target = true;696 }697 Some(698 old_balance699 .checked_add(amount)700 .ok_or(ArithmeticError::Overflow)?,701 )702 } else {703 None704 };705706 let account_balance_from = if updated_balance_from == 0 {707 Some(708 <AccountBalance<T>>::get((collection.id, from))709 .checked_sub(1)710 // Should not occur711 .ok_or(ArithmeticError::Underflow)?,712 )713 } else {714 None715 };716 // Account data is created in token, AccountBalance should be increased717 // But only if from != to as we shouldn't check overflow in this case718 let account_balance_to = if create_target && from_to_differ {719 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))720 .checked_add(1)721 .ok_or(ArithmeticError::Overflow)?;722 ensure!(723 account_balance_to < collection.limits.account_token_ownership_limit(),724 <CommonError<T>>::AccountTokenLimitExceeded,725 );726727 Some(account_balance_to)728 } else {729 None730 };731732 // =========733734 if let Some(updated_balance_to) = updated_balance_to {735 // from != to && amount != 0736737 <PalletStructure<T>>::nest_if_sent_to_token(738 from.clone(),739 to,740 collection.id,741 token,742 nesting_budget,743 )?;744745 if updated_balance_from == 0 {746 <Balance<T>>::remove((collection.id, token, from));747 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);748 } else {749 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);750 }751 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);752 if let Some(account_balance_from) = account_balance_from {753 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);754 <Owned<T>>::remove((collection.id, from, token));755 }756 if let Some(account_balance_to) = account_balance_to {757 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);758 <Owned<T>>::insert((collection.id, to, token), true);759 }760 }761762 <PalletEvm<T>>::deposit_log(763 ERC20Events::Transfer {764 from: *from.as_eth(),765 to: *to.as_eth(),766 value: amount.into(),767 }768 .to_log(T::EvmTokenAddressMapping::token_to_address(769 collection.id,770 token,771 )),772 );773774 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(775 collection.id,776 token,777 from.clone(),778 to.clone(),779 amount,780 ));781782 let total_supply = <TotalSupply<T>>::get((collection.id, token));783784 if amount == total_supply {785 // if token was fully owned by `from` and will be fully owned by `to` after transfer786 <PalletEvm<T>>::deposit_log(787 ERC721Events::Transfer {788 from: *from.as_eth(),789 to: *to.as_eth(),790 token_id: token.into(),791 }792 .to_log(collection_id_to_address(collection.id)),793 );794 } else if let Some(updated_balance_to) = updated_balance_to {795 // if `from` not equals `to`. This condition is needed to avoid sending event796 // when `from` fully owns token and sends part of token pieces to itself.797 if initial_balance_from == total_supply {798 // if token was fully owned by `from` and will be only partially owned by `to`799 // and `from` after transfer800 <PalletEvm<T>>::deposit_log(801 ERC721Events::Transfer {802 from: *from.as_eth(),803 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,804 token_id: token.into(),805 }806 .to_log(collection_id_to_address(collection.id)),807 );808 } else if updated_balance_to == total_supply {809 // if token was partially owned by `from` and will be fully owned by `to` after transfer810 <PalletEvm<T>>::deposit_log(811 ERC721Events::Transfer {812 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,813 to: *to.as_eth(),814 token_id: token.into(),815 }816 .to_log(collection_id_to_address(collection.id)),817 );818 }819 }820821 Ok(())822 }823824 /// Batched operation to create multiple RFT tokens.825 ///826 /// Same as `create_item` but creates multiple tokens.827 ///828 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.829 pub fn create_multiple_items(830 collection: &RefungibleHandle<T>,831 sender: &T::CrossAccountId,832 data: Vec<CreateItemData<T>>,833 nesting_budget: &dyn Budget,834 ) -> DispatchResult {835 if !collection.is_owner_or_admin(sender) {836 ensure!(837 collection.permissions.mint_mode(),838 <CommonError<T>>::PublicMintingNotAllowed839 );840 collection.check_allowlist(sender)?;841842 for item in data.iter() {843 for user in item.users.keys() {844 collection.check_allowlist(user)?;845 }846 }847 }848849 for item in data.iter() {850 for (owner, _) in item.users.iter() {851 <PalletCommon<T>>::ensure_correct_receiver(owner)?;852 }853 }854855 // Total pieces per tokens856 let totals = data857 .iter()858 .map(|data| {859 Ok(data860 .users861 .iter()862 .map(|u| u.1)863 .try_fold(0u128, |acc, v| acc.checked_add(*v))864 .ok_or(ArithmeticError::Overflow)?)865 })866 .collect::<Result<Vec<_>, DispatchError>>()?;867 for total in &totals {868 ensure!(869 *total <= MAX_REFUNGIBLE_PIECES,870 <Error<T>>::WrongRefungiblePieces871 );872 }873874 let first_token_id = <TokensMinted<T>>::get(collection.id);875 let tokens_minted = first_token_id876 .checked_add(data.len() as u32)877 .ok_or(ArithmeticError::Overflow)?;878 ensure!(879 tokens_minted < collection.limits.token_limit(),880 <CommonError<T>>::CollectionTokenLimitExceeded881 );882883 let mut balances = BTreeMap::new();884 for data in &data {885 for owner in data.users.keys() {886 let balance = balances887 .entry(owner)888 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));889 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;890891 ensure!(892 *balance <= collection.limits.account_token_ownership_limit(),893 <CommonError<T>>::AccountTokenLimitExceeded,894 );895 }896 }897898 for (i, token) in data.iter().enumerate() {899 let token_id = TokenId(first_token_id + i as u32 + 1);900 for (to, _) in token.users.iter() {901 <PalletStructure<T>>::check_nesting(902 sender.clone(),903 to,904 collection.id,905 token_id,906 nesting_budget,907 )?;908 }909 }910911 // =========912913 with_transaction(|| {914 for (i, data) in data.iter().enumerate() {915 let token_id = first_token_id + i as u32 + 1;916 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);917918 for (user, amount) in data.users.iter() {919 if *amount == 0 {920 continue;921 }922 <Balance<T>>::insert((collection.id, token_id, &user), amount);923 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);924 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(925 user,926 collection.id,927 TokenId(token_id),928 );929 }930931 if let Err(e) = Self::set_token_properties(932 collection,933 sender,934 TokenId(token_id),935 data.properties.clone().into_iter(),936 true,937 nesting_budget,938 ) {939 return TransactionOutcome::Rollback(Err(e));940 }941 }942 TransactionOutcome::Commit(Ok(()))943 })?;944945 <TokensMinted<T>>::insert(collection.id, tokens_minted);946947 for (account, balance) in balances {948 <AccountBalance<T>>::insert((collection.id, account), balance);949 }950951 for (i, token) in data.into_iter().enumerate() {952 let token_id = first_token_id + i as u32 + 1;953954 let receivers = token955 .users956 .into_iter()957 .filter(|(_, amount)| *amount > 0)958 .collect::<Vec<_>>();959960 if let [(user, _)] = receivers.as_slice() {961 // if there is exactly one receiver962 <PalletEvm<T>>::deposit_log(963 ERC721Events::Transfer {964 from: H160::default(),965 to: *user.as_eth(),966 token_id: token_id.into(),967 }968 .to_log(collection_id_to_address(collection.id)),969 );970 } else if let [_, ..] = receivers.as_slice() {971 // if there is more than one receiver972 <PalletEvm<T>>::deposit_log(973 ERC721Events::Transfer {974 from: H160::default(),975 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,976 token_id: token_id.into(),977 }978 .to_log(collection_id_to_address(collection.id)),979 );980 }981982 for (user, amount) in receivers.into_iter() {983 <PalletEvm<T>>::deposit_log(984 ERC20Events::Transfer {985 from: H160::default(),986 to: *user.as_eth(),987 value: amount.into(),988 }989 .to_log(T::EvmTokenAddressMapping::token_to_address(990 collection.id,991 TokenId(token_id),992 )),993 );994 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(995 collection.id,996 TokenId(token_id),997 user,998 amount,999 ));1000 }1001 }1002 Ok(())1003 }10041005 pub fn set_allowance_unchecked(1006 collection: &RefungibleHandle<T>,1007 sender: &T::CrossAccountId,1008 spender: &T::CrossAccountId,1009 token: TokenId,1010 amount: u128,1011 ) {1012 if amount == 0 {1013 <Allowance<T>>::remove((collection.id, token, sender, spender));1014 } else {1015 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1016 }10171018 <PalletEvm<T>>::deposit_log(1019 ERC20Events::Approval {1020 owner: *sender.as_eth(),1021 spender: *spender.as_eth(),1022 value: amount.into(),1023 }1024 .to_log(T::EvmTokenAddressMapping::token_to_address(1025 collection.id,1026 token,1027 )),1028 );1029 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1030 collection.id,1031 token,1032 sender.clone(),1033 spender.clone(),1034 amount,1035 ))1036 }10371038 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1039 ///1040 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1041 pub fn set_allowance(1042 collection: &RefungibleHandle<T>,1043 sender: &T::CrossAccountId,1044 spender: &T::CrossAccountId,1045 token: TokenId,1046 amount: u128,1047 ) -> DispatchResult {1048 if collection.permissions.access() == AccessMode::AllowList {1049 collection.check_allowlist(sender)?;1050 collection.check_allowlist(spender)?;1051 }10521053 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10541055 if <Balance<T>>::get((collection.id, token, sender)) < amount {1056 ensure!(1057 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1058 <CommonError<T>>::CantApproveMoreThanOwned1059 );1060 }10611062 // =========10631064 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1065 Ok(())1066 }10671068 /// Set allowance to spend from sender's eth mirror1069 ///1070 /// - `from`: Address of sender's eth mirror.1071 /// - `to`: Adress of spender.1072 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1073 pub fn set_allowance_from(1074 collection: &RefungibleHandle<T>,1075 sender: &T::CrossAccountId,1076 from: &T::CrossAccountId,1077 to: &T::CrossAccountId,1078 token_id: TokenId,1079 amount: u128,1080 ) -> DispatchResult {1081 if collection.permissions.access() == AccessMode::AllowList {1082 collection.check_allowlist(sender)?;1083 collection.check_allowlist(from)?;1084 collection.check_allowlist(to)?;1085 }10861087 <PalletCommon<T>>::ensure_correct_receiver(to)?;10881089 ensure!(1090 sender.conv_eq(from),1091 <CommonError<T>>::AddressIsNotEthMirror1092 );10931094 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1095 ensure!(1096 collection.limits.owner_can_transfer()1097 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1098 && Self::token_exists(collection, token_id),1099 <CommonError<T>>::CantApproveMoreThanOwned1100 );1101 }11021103 // =========11041105 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1106 Ok(())1107 }11081109 /// Returns allowance, which should be set after transaction1110 fn check_allowed(1111 collection: &RefungibleHandle<T>,1112 spender: &T::CrossAccountId,1113 from: &T::CrossAccountId,1114 token: TokenId,1115 amount: u128,1116 nesting_budget: &dyn Budget,1117 ) -> Result<Option<u128>, DispatchError> {1118 if spender.conv_eq(from) {1119 return Ok(None);1120 }1121 if collection.permissions.access() == AccessMode::AllowList {1122 // `from`, `to` checked in [`transfer`]1123 collection.check_allowlist(spender)?;1124 }11251126 if collection.ignores_token_restrictions(spender) {1127 return Ok(Self::compute_allowance_decrease(1128 collection, token, from, &spender, amount,1129 ));1130 }11311132 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1133 // TODO: should collection owner be allowed to perform this transfer?1134 ensure!(1135 <PalletStructure<T>>::check_indirectly_owned(1136 spender.clone(),1137 source.0,1138 source.1,1139 None,1140 nesting_budget1141 )?,1142 <CommonError<T>>::ApprovedValueTooLow,1143 );1144 return Ok(None);1145 }11461147 let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);1148 if allowance.is_some() {1149 return Ok(allowance);1150 }11511152 // Allowance (if any) would be reduced if spender is also wallet operator1153 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1154 return Ok(allowance);1155 }11561157 Err(<CommonError<T>>::ApprovedValueTooLow.into())1158 }11591160 /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1161 /// Otherwise, it returns `None`.1162 fn compute_allowance_decrease(1163 collection: &RefungibleHandle<T>,1164 token: TokenId,1165 from: &T::CrossAccountId,1166 spender: &T::CrossAccountId,1167 amount: u128,1168 ) -> Option<u128> {1169 <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1170 }11711172 /// Transfer RFT token pieces from one account to another.1173 ///1174 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1175 /// The owner should set allowance for the spender to transfer pieces.1176 ///1177 /// [`transfer`]: struct.Pallet.html#method.transfer1178 pub fn transfer_from(1179 collection: &RefungibleHandle<T>,1180 spender: &T::CrossAccountId,1181 from: &T::CrossAccountId,1182 to: &T::CrossAccountId,1183 token: TokenId,1184 amount: u128,1185 nesting_budget: &dyn Budget,1186 ) -> DispatchResult {1187 let allowance =1188 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11891190 // =========11911192 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1193 if let Some(allowance) = allowance {1194 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1195 }1196 Ok(())1197 }11981199 /// Burn RFT token pieces from the account.1200 ///1201 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1202 /// set allowance for the spender to burn pieces1203 ///1204 /// [`burn`]: struct.Pallet.html#method.burn1205 pub fn burn_from(1206 collection: &RefungibleHandle<T>,1207 spender: &T::CrossAccountId,1208 from: &T::CrossAccountId,1209 token: TokenId,1210 amount: u128,1211 nesting_budget: &dyn Budget,1212 ) -> DispatchResult {1213 let allowance =1214 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12151216 // =========12171218 Self::burn(collection, from, token, amount)?;1219 if let Some(allowance) = allowance {1220 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1221 }1222 Ok(())1223 }12241225 /// Create RFT token.1226 ///1227 /// The sender should be the owner/admin of the collection or collection should be configured1228 /// to allow public minting.1229 ///1230 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1231 /// of token pieces they will receive.1232 pub fn create_item(1233 collection: &RefungibleHandle<T>,1234 sender: &T::CrossAccountId,1235 data: CreateItemData<T>,1236 nesting_budget: &dyn Budget,1237 ) -> DispatchResult {1238 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1239 }12401241 /// Repartition RFT token.1242 ///1243 /// `repartition` will set token balance of the sender and total amount of token pieces.1244 /// Sender should own all of the token pieces. `repartition' could be done even if some1245 /// token pieces were burned before.1246 ///1247 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1248 pub fn repartition(1249 collection: &RefungibleHandle<T>,1250 owner: &T::CrossAccountId,1251 token: TokenId,1252 amount: u128,1253 ) -> DispatchResult {1254 ensure!(1255 amount <= MAX_REFUNGIBLE_PIECES,1256 <Error<T>>::WrongRefungiblePieces1257 );1258 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1259 // Ensure user owns all pieces1260 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1261 let balance = <Balance<T>>::get((collection.id, token, owner));1262 ensure!(1263 total_pieces == balance,1264 <Error<T>>::RepartitionWhileNotOwningAllPieces1265 );12661267 <Balance<T>>::insert((collection.id, token, owner), amount);1268 <TotalSupply<T>>::insert((collection.id, token), amount);12691270 if amount > total_pieces {1271 let mint_amount = amount - total_pieces;1272 <PalletEvm<T>>::deposit_log(1273 ERC20Events::Transfer {1274 from: H160::default(),1275 to: *owner.as_eth(),1276 value: mint_amount.into(),1277 }1278 .to_log(T::EvmTokenAddressMapping::token_to_address(1279 collection.id,1280 token,1281 )),1282 );1283 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1284 collection.id,1285 token,1286 owner.clone(),1287 mint_amount,1288 ));1289 } else if total_pieces > amount {1290 let burn_amount = total_pieces - amount;1291 <PalletEvm<T>>::deposit_log(1292 ERC20Events::Transfer {1293 from: *owner.as_eth(),1294 to: H160::default(),1295 value: burn_amount.into(),1296 }1297 .to_log(T::EvmTokenAddressMapping::token_to_address(1298 collection.id,1299 token,1300 )),1301 );1302 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1303 collection.id,1304 token,1305 owner.clone(),1306 burn_amount,1307 ));1308 }13091310 Ok(())1311 }13121313 fn token_owner(1314 collection_id: CollectionId,1315 token_id: TokenId,1316 ) -> Result<T::CrossAccountId, TokenOwnerError> {1317 let mut owner = None;1318 let mut count = 0;1319 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1320 count += 1;1321 if count > 1 {1322 return Err(TokenOwnerError::MultipleOwners);1323 }1324 owner = Some(key);1325 }1326 owner.ok_or(TokenOwnerError::NotFound)1327 }13281329 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1330 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1331 }13321333 pub fn set_collection_properties(1334 collection: &RefungibleHandle<T>,1335 sender: &T::CrossAccountId,1336 properties: Vec<Property>,1337 ) -> DispatchResult {1338 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1339 }13401341 pub fn delete_collection_properties(1342 collection: &RefungibleHandle<T>,1343 sender: &T::CrossAccountId,1344 property_keys: Vec<PropertyKey>,1345 ) -> DispatchResult {1346 <PalletCommon<T>>::delete_collection_properties(1347 collection,1348 sender,1349 property_keys.into_iter(),1350 )1351 }13521353 pub fn set_token_property_permissions(1354 collection: &RefungibleHandle<T>,1355 sender: &T::CrossAccountId,1356 property_permissions: Vec<PropertyKeyPermission>,1357 ) -> DispatchResult {1358 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1359 }13601361 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1362 <PalletCommon<T>>::property_permissions(collection_id)1363 }13641365 pub fn set_scoped_token_property_permissions(1366 collection: &RefungibleHandle<T>,1367 sender: &T::CrossAccountId,1368 scope: PropertyScope,1369 property_permissions: Vec<PropertyKeyPermission>,1370 ) -> DispatchResult {1371 <PalletCommon<T>>::set_scoped_token_property_permissions(1372 collection,1373 sender,1374 scope,1375 property_permissions,1376 )1377 }13781379 /// Returns 10 token in no particular order.1380 ///1381 /// There is no direct way to get token holders in ascending order,1382 /// since `iter_prefix` returns values in no particular order.1383 /// Therefore, getting the 10 largest holders with a large value of holders1384 /// can lead to impact memory allocation + sorting with `n * log (n)`.1385 pub fn token_owners(1386 collection_id: CollectionId,1387 token: TokenId,1388 ) -> Option<Vec<T::CrossAccountId>> {1389 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1390 .map(|(owner, _amount)| owner)1391 .take(10)1392 .collect();13931394 if res.is_empty() {1395 None1396 } else {1397 Some(res)1398 }1399 }14001401 /// Sets or unsets the approval of a given operator.1402 ///1403 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1404 /// - `owner`: Token owner1405 /// - `operator`: Operator1406 /// - `approve`: Should operator status be granted or revoked?1407 pub fn set_allowance_for_all(1408 collection: &RefungibleHandle<T>,1409 owner: &T::CrossAccountId,1410 spender: &T::CrossAccountId,1411 approve: bool,1412 ) -> DispatchResult {1413 <PalletCommon<T>>::set_allowance_for_all(1414 collection,1415 owner,1416 spender,1417 approve,1418 || <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1419 ERC721Events::ApprovalForAll {1420 owner: *owner.as_eth(),1421 operator: *spender.as_eth(),1422 approved: approve,1423 }1424 .to_log(collection_id_to_address(collection.id)),1425 )1426 }14271428 /// Tells whether the given `owner` approves the `operator`.1429 pub fn allowance_for_all(1430 collection: &RefungibleHandle<T>,1431 owner: &T::CrossAccountId,1432 spender: &T::CrossAccountId,1433 ) -> bool {1434 <CollectionAllowance<T>>::get((collection.id, owner, spender))1435 }14361437 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1438 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1439 properties.recompute_consumed_space();1440 });14411442 Ok(())1443 }1444}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();