difftreelog
Merge pull request #1024 from UniqueNetwork/refactor/foreign-assets-as-thin-proxy
in: master
Refactor/foreign assets as thin proxy
50 files changed
.envdiffbeforeafterboth--- a/.env
+++ b/.env
@@ -16,7 +16,7 @@
KUSAMA_MAINNET_BRANCH=release-v1.0.0
STATEMINE_BUILD_BRANCH=release-parachains-v9430
-KARURA_BUILD_BRANCH=release-karura-2.21.0
+KARURA_BUILD_BRANCH=xnft-poc
MOONRIVER_BUILD_BRANCH=runtime-2500
SHIDEN_BUILD_BRANCH=v5.18.0
QUARTZ_MAINNET_BRANCH=release-v10010063
.github/workflows/ci-develop.ymldiffbeforeafterboth--- a/.github/workflows/ci-develop.yml
+++ b/.github/workflows/ci-develop.yml
@@ -35,6 +35,11 @@
if: github.event.pull_request.draft == false && contains(github.event.pull_request.labels.*.name, 'CI-xcm')
uses: ./.github/workflows/xcm.yml
secrets: inherit
+
+ xnft:
+ if: github.event.pull_request.draft == false && contains(github.event.pull_request.labels.*.name, 'CI-xnft')
+ uses: ./.github/workflows/xnft.yml
+ secrets: inherit
collator-selection:
if: github.event.pull_request.draft == false && contains(github.event.pull_request.labels.*.name, 'CI-collator-selection')
.github/workflows/ci-master.ymldiffbeforeafterboth--- a/.github/workflows/ci-master.yml
+++ b/.github/workflows/ci-master.yml
@@ -31,6 +31,10 @@
xcm:
uses: ./.github/workflows/xcm.yml
secrets: inherit # pass all secrets from initial workflow to nested
+
+ xnft:
+ uses: ./.github/workflows/xnft.yml
+ secrets: inherit # pass all secrets from initial workflow to nested
collator-selection:
uses: ./.github/workflows/collator-selection.yml
.github/workflows/xnft.ymldiffbeforeafterboth--- /dev/null
+++ b/.github/workflows/xnft.yml
@@ -0,0 +1,215 @@
+name: xnft-testnet
+
+# Controls when the action will run.
+on:
+ workflow_call:
+
+ # Allows you to run this workflow manually from the Actions tab
+ workflow_dispatch:
+
+#Define Workflow variables
+env:
+ REPO_URL: ${{ github.server_url }}/${{ github.repository }}
+
+# A workflow run is made up of one or more jobs that can run sequentially or in parallel
+jobs:
+ prepare-execution-marix:
+ name: Prepare execution matrix
+
+ runs-on: [self-hosted-ci]
+ outputs:
+ matrix: ${{ steps.create_matrix.outputs.matrix }}
+
+ steps:
+ - name: Clean Workspace
+ uses: AutoModality/action-clean@v1.1.0
+
+ # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
+ - uses: actions/checkout@v3.1.0
+ with:
+ ref: ${{ github.head_ref }} #Checking out head commit
+
+ - name: Read .env file
+ uses: xom9ikk/dotenv@v2
+
+ - name: Create Execution matrix
+ uses: CertainLach/create-matrix-action@v4
+ id: create_matrix
+ with:
+ matrix: |
+ network {quartz}, relay_branch {${{ env.KUSAMA_MAINNET_BRANCH }}}, acala_version {${{ env.KARURA_BUILD_BRANCH }}}, runtest {all-quartz}, runtime_features {quartz-runtime}
+
+ xnft:
+ needs: prepare-execution-marix
+ # The type of runner that the job will run on
+ runs-on: [XL]
+
+ timeout-minutes: 600
+
+ name: ${{ matrix.network }}
+
+ continue-on-error: true #Do not stop testing of matrix runs failed. As it decided during PR review - it required 50/50& Let's check it with false.
+
+ strategy:
+ matrix:
+ include: ${{fromJson(needs.prepare-execution-marix.outputs.matrix)}}
+
+ steps:
+ - name: Skip if pull request is in Draft
+ if: github.event.pull_request.draft == true
+ run: exit 1
+
+ - name: Clean Workspace
+ uses: AutoModality/action-clean@v1.1.0
+
+ # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
+ - uses: actions/checkout@v3.1.0
+ with:
+ ref: ${{ github.head_ref }} #Checking out head commit
+
+ # Prepare SHA
+ - name: Prepare SHA
+ uses: ./.github/actions/prepare
+
+ - name: Read .env file
+ uses: xom9ikk/dotenv@v2
+
+ - name: Log in to Docker Hub
+ uses: docker/login-action@v2.1.0
+ with:
+ username: ${{ secrets.CORE_DOCKERHUB_USERNAME }}
+ password: ${{ secrets.CORE_DOCKERHUB_TOKEN }}
+
+ # Check POLKADOT version and build it if it doesn't exist in repository
+ - name: Generate ENV related extend Dockerfile file for POLKADOT
+ uses: cuchi/jinja2-action@v1.2.0
+ with:
+ template: .docker/Dockerfile-polkadot.j2
+ output_file: .docker/Dockerfile-polkadot.${{ matrix.relay_branch }}.yml
+ variables: |
+ RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }}
+ POLKADOT_BUILD_BRANCH=${{ matrix.relay_branch }}
+
+ - name: Check if the dockerhub repository contains the needed version POLKADOT
+ run: |
+ # aquire token
+ TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'${{ secrets.CORE_DOCKERHUB_USERNAME }}'", "password": "'${{ secrets.CORE_DOCKERHUB_TOKEN }}'"}' https://hub.docker.com/v2/users/login/ | jq -r .token)
+ export TOKEN=$TOKEN
+
+ # Get TAGS from DOCKERHUB POLKADOT repository
+ POLKADOT_TAGS=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/uniquenetwork/builder-polkadot/tags/?page_size=100 | jq -r '."results"[]["name"]')
+ # Show TAGS
+ echo "POLKADOT TAGS:"
+ echo $POLKADOT_TAGS
+ # Check correct version POLKADOT and build it if it doesn't exist in POLKADOT TAGS
+ if [[ ${POLKADOT_TAGS[*]} =~ (^|[[:space:]])"${{ matrix.relay_branch }}"($|[[:space:]]) ]]; then
+ echo "Repository has needed POLKADOT version";
+ docker pull uniquenetwork/builder-polkadot:${{ matrix.relay_branch }}
+ else
+ echo "Repository has not needed POLKADOT version, so build it";
+ cd .docker/ && docker build --file ./Dockerfile-polkadot.${{ matrix.relay_branch }}.yml --tag uniquenetwork/builder-polkadot:${{ matrix.relay_branch }} .
+ echo "Push needed POLKADOT version to the repository";
+ docker push uniquenetwork/builder-polkadot:${{ matrix.relay_branch }}
+ fi
+ shell: bash
+
+ # Check ACALA version and build it if it doesn't exist in repository
+ - name: Generate ENV related extend Dockerfile file for ACALA
+ uses: cuchi/jinja2-action@v1.2.0
+ with:
+ template: .docker/Dockerfile-acala.j2
+ output_file: .docker/Dockerfile-acala.${{ matrix.acala_version }}.yml
+ variables: |
+ RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }}
+ ACALA_BUILD_BRANCH=${{ matrix.acala_version }}
+
+ - name: Check if the dockerhub repository contains the needed ACALA version
+ run: |
+ # aquire token
+ TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'${{ secrets.CORE_DOCKERHUB_USERNAME }}'", "password": "'${{ secrets.CORE_DOCKERHUB_TOKEN }}'"}' https://hub.docker.com/v2/users/login/ | jq -r .token)
+ export TOKEN=$TOKEN
+
+ # Get TAGS from DOCKERHUB repository
+ ACALA_TAGS=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/uniquenetwork/builder-acala/tags/?page_size=100 | jq -r '."results"[]["name"]')
+ # Show TAGS
+ echo "ACALA TAGS:"
+ echo $ACALA_TAGS
+ # Check correct version ACALA and build it if it doesn't exist in ACALA TAGS
+ if [[ ${ACALA_TAGS[*]} =~ (^|[[:space:]])"${{ matrix.acala_version }}"($|[[:space:]]) ]]; then
+ echo "Repository has needed ACALA version";
+ docker pull uniquenetwork/builder-acala:${{ matrix.acala_version }}
+ else
+ echo "Repository has not needed ACALA version, so build it";
+ cd .docker/ && docker build --file ./Dockerfile-acala.${{ matrix.acala_version }}.yml --tag uniquenetwork/builder-acala:${{ matrix.acala_version }} .
+ echo "Push needed ACALA version to the repository";
+ docker push uniquenetwork/builder-acala:${{ matrix.acala_version }}
+ fi
+ shell: bash
+
+ - name: Build unique-chain
+ run: |
+ docker build --file .docker/Dockerfile-unique \
+ --build-arg RUNTIME_FEATURES=${{ matrix.runtime_features }} \
+ --build-arg RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }} \
+ --tag uniquenetwork/ci-xnft-local:${{ matrix.network }}-${{ env.REF_SLUG }}-${{ env.BUILD_SHA }} \
+ .
+
+ - name: Push docker image version
+ run: docker push uniquenetwork/ci-xnft-local:${{ matrix.network }}-${{ env.REF_SLUG }}-${{ env.BUILD_SHA }}
+
+ - uses: actions/setup-node@v3.5.1
+ with:
+ node-version: 18
+
+ - name: Clone xnft-tests
+ run: git clone https://github.com/UniqueNetwork/xnft-tests.git
+
+ - name: Install baedeker
+ uses: UniqueNetwork/baedeker-action/setup@built
+
+ - name: Setup library
+ run: mkdir -p .baedeker/vendor/ && git clone https://github.com/UniqueNetwork/baedeker-library .baedeker/vendor/baedeker-library
+
+ - name: Start network
+ uses: UniqueNetwork/baedeker-action@built
+ id: bdk
+ with:
+ jpath: |
+ .baedeker/vendor
+ tla-str: |
+ relay_spec=rococo-local
+ inputs: |
+ xnft-tests/.baedeker/testnets.jsonnet
+ snippet:(import 'baedeker-library/ops/rewrites.libsonnet').rewriteNodePaths({'bin/polkadot':{dockerImage:'uniquenetwork/builder-polkadot:${{ matrix.relay_branch }}'}})
+ snippet:(import 'baedeker-library/ops/rewrites.libsonnet').rewriteNodePaths({'bin/quartz':{dockerImage:'uniquenetwork/ci-xnft-local:${{ matrix.network }}-${{ env.REF_SLUG }}-${{ env.BUILD_SHA }}'}})
+ snippet:(import 'baedeker-library/ops/rewrites.libsonnet').rewriteNodePaths({'bin/karura':{dockerImage:'uniquenetwork/builder-acala:${{ matrix.acala_version }}'}})
+
+ - name: Yarn install
+ working-directory: xnft-tests
+ run: |
+ yarn install
+ yarn add mochawesome
+
+ - name: Run XNFT Tests
+ working-directory: xnft-tests
+ run: |
+ NOW=$(date +%s) && yarn ${{ matrix.runtest }} --reporter mochawesome --reporter-options reportFilename=test-${NOW}
+
+ - name: XNFT Tests Report
+ uses: phoenix-actions/test-reporting@v10
+ id: test-report
+ if: success() || failure()
+ with:
+ name: XNFT Tests ${{ matrix.network }}
+ path: xnft-tests/mochawesome-report/test-*.json
+ reporter: mochawesome-json
+ fail-on-error: 'false'
+
+ - name: Clean Workspace
+ if: always()
+ uses: AutoModality/action-clean@v1.1.0
+
+ - name: Remove builder cache
+ if: always()
+ run: |
+ docker system prune -a -f
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2567,15 +2567,15 @@
[[package]]
name = "data-encoding"
-version = "2.4.0"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308"
+checksum = "7e962a19be5cfc3f3bf6dd8f61eb50107f356ad6270fbb3ed41476571db78be5"
[[package]]
name = "data-encoding-macro"
-version = "0.1.13"
+version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c904b33cc60130e1aeea4956ab803d08a3f4a0ca82d64ed757afac3891f2bb99"
+checksum = "20c01c06f5f429efdf2bae21eb67c28b3df3cf85b7dd2d8ef09c0838dac5d33e"
dependencies = [
"data-encoding",
"data-encoding-macro-internal",
@@ -2583,9 +2583,9 @@
[[package]]
name = "data-encoding-macro-internal"
-version = "0.1.11"
+version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8fdf3fce3ce863539ec1d7fd1b6dcc3c645663376b43ed376bbf887733e4f772"
+checksum = "0047d07f2c89b17dd631c80450d69841a6b5d7fb17278cbc43d7e4cfcf2576f3"
dependencies = [
"data-encoding",
"syn 1.0.109",
@@ -4678,21 +4678,21 @@
[[package]]
name = "if-addrs"
-version = "0.7.0"
+version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cbc0fa01ffc752e9dbc72818cdb072cd028b86be5e09dd04c5a643704fe101a9"
+checksum = "cabb0019d51a643781ff15c9c8a3e5dedc365c47211270f4e8f82812fedd8f0a"
dependencies = [
"libc",
- "winapi",
+ "windows-sys 0.48.0",
]
[[package]]
name = "if-watch"
-version = "3.1.0"
+version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bbb892e5777fe09e16f3d44de7802f4daa7267ecbe8c466f19d94e25bb0c303e"
+checksum = "d6b0422c86d7ce0e97169cc42e04ae643caf278874a7a3c87b8150a220dc7e1e"
dependencies = [
- "async-io 1.13.0",
+ "async-io 2.2.0",
"core-foundation",
"fnv",
"futures",
@@ -6557,7 +6557,6 @@
"impl-trait-for-tuples",
"log",
"num_enum",
- "orml-tokens",
"orml-traits",
"orml-vesting",
"orml-xcm-support",
@@ -6706,26 +6705,9 @@
]
[[package]]
-name = "orml-tokens"
-version = "0.5.0-dev"
-source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#6f36a9e79b75421ac56b259fd47d03db6c3e1603"
-dependencies = [
- "frame-support",
- "frame-system",
- "log",
- "orml-traits",
- "parity-scale-codec",
- "scale-info",
- "serde",
- "sp-arithmetic",
- "sp-runtime",
- "sp-std",
-]
-
-[[package]]
name = "orml-traits"
-version = "0.5.0-dev"
-source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#6f36a9e79b75421ac56b259fd47d03db6c3e1603"
+version = "0.6.1"
+source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#99604b000be6252597cfcb82eee82554f6a07a0e"
dependencies = [
"frame-support",
"impl-trait-for-tuples",
@@ -6744,8 +6726,8 @@
[[package]]
name = "orml-utilities"
-version = "0.5.0-dev"
-source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#6f36a9e79b75421ac56b259fd47d03db6c3e1603"
+version = "0.6.1"
+source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#99604b000be6252597cfcb82eee82554f6a07a0e"
dependencies = [
"frame-support",
"parity-scale-codec",
@@ -6759,8 +6741,8 @@
[[package]]
name = "orml-vesting"
-version = "0.5.0-dev"
-source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#6f36a9e79b75421ac56b259fd47d03db6c3e1603"
+version = "0.6.1"
+source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#99604b000be6252597cfcb82eee82554f6a07a0e"
dependencies = [
"frame-support",
"frame-system",
@@ -6774,8 +6756,8 @@
[[package]]
name = "orml-xcm-support"
-version = "0.5.0-dev"
-source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#6f36a9e79b75421ac56b259fd47d03db6c3e1603"
+version = "0.6.1"
+source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#99604b000be6252597cfcb82eee82554f6a07a0e"
dependencies = [
"frame-support",
"orml-traits",
@@ -6788,8 +6770,8 @@
[[package]]
name = "orml-xtokens"
-version = "0.5.0-dev"
-source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#6f36a9e79b75421ac56b259fd47d03db6c3e1603"
+version = "0.6.1"
+source = "git+https://github.com/uniquenetwork/open-runtime-module-library?branch=unique-polkadot-v1.3.0#99604b000be6252597cfcb82eee82554f6a07a0e"
dependencies = [
"cumulus-primitives-core",
"frame-support",
@@ -7446,7 +7428,6 @@
"frame-support",
"frame-system",
"log",
- "orml-tokens",
"pallet-balances",
"pallet-common",
"pallet-fungible",
@@ -10150,7 +10131,6 @@
"impl-trait-for-tuples",
"log",
"num_enum",
- "orml-tokens",
"orml-traits",
"orml-vesting",
"orml-xcm-support",
@@ -13695,9 +13675,9 @@
[[package]]
name = "spinners"
-version = "4.1.0"
+version = "4.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "08615eea740067d9899969bc2891c68a19c315cb1f66640af9a9ecb91b13bcab"
+checksum = "a0ef947f358b9c238923f764c72a4a9d42f2d637c46e059dbd319d6e7cfb4f82"
dependencies = [
"lazy_static",
"maplit",
@@ -15028,7 +15008,6 @@
"impl-trait-for-tuples",
"log",
"num_enum",
- "orml-tokens",
"orml-traits",
"orml-vesting",
"orml-xcm-support",
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -199,7 +199,6 @@
try-runtime-cli = "0.35.0"
# ORML
-orml-tokens = { default-features = false, git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "unique-polkadot-v1.3.0" }
orml-traits = { default-features = false, git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "unique-polkadot-v1.3.0" }
orml-vesting = { default-features = false, git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "unique-polkadot-v1.3.0" }
orml-xcm-support = { default-features = false, git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "unique-polkadot-v1.3.0" }
js-packages/playgrounds/types.tsdiffbeforeafterboth--- a/js-packages/playgrounds/types.ts
+++ b/js-packages/playgrounds/types.ts
@@ -160,7 +160,7 @@
External = 1,
/// Supports ERC721Metadata
Erc721metadata = 64,
- /// Tokens in foreign collections can be transferred, but not burnt
+ /// A collection of foreign assets
Foreign = 128,
}
js-packages/playgrounds/types.xcm.tsdiffbeforeafterboth--- a/js-packages/playgrounds/types.xcm.ts
+++ b/js-packages/playgrounds/types.xcm.ts
@@ -27,10 +27,3 @@
conviction: number,
},
}
-
-export interface IForeignAssetMetadata {
- name?: number | Uint8Array,
- symbol?: string,
- decimals?: number,
- minimalBalance?: bigint,
-}
\ No newline at end of file
js-packages/playgrounds/unique.xcm.tsdiffbeforeafterboth--- a/js-packages/playgrounds/unique.xcm.ts
+++ b/js-packages/playgrounds/unique.xcm.ts
@@ -2,7 +2,7 @@
import type {IKeyringPair} from '@polkadot/types/types';
import {ChainHelperBase, EthereumBalanceGroup, HelperGroup, SubstrateBalanceGroup, UniqueHelper} from './unique.js';
import type {ILogger, TSigner, TSubstrateAccount} from './types.js';
-import type {AcalaAssetMetadata, DemocracyStandardAccountVote, IForeignAssetMetadata, MoonbeamAssetInfo} from './types.xcm.js';
+import type {AcalaAssetMetadata, DemocracyStandardAccountVote, MoonbeamAssetInfo} from './types.xcm.js';
export class XcmChainHelper extends ChainHelperBase {
@@ -104,22 +104,17 @@
}
export class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {
- async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {
+ async register(signer: TSigner, assetId: any, name: string, tokenPrefix: string, mode: 'NFT' | { Fungible: number }) {
await this.helper.executeExtrinsic(
signer,
- 'api.tx.foreignAssets.registerForeignAsset',
- [ownerAddress, location, metadata],
+ 'api.tx.foreignAssets.forceRegisterForeignAsset',
+ [{V3: assetId}, this.helper.util.str2vec(name), tokenPrefix, mode],
true,
);
}
- async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {
- await this.helper.executeExtrinsic(
- signer,
- 'api.tx.foreignAssets.updateForeignAsset',
- [foreignAssetId, location, metadata],
- true,
- );
+ async foreignCollectionId(assetId: any) {
+ return (await this.helper.callRpc('api.query.foreignAssets.foreignAssetToCollection', [assetId])).toJSON();
}
}
@@ -256,6 +251,10 @@
await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);
}
+ async assetInfo(assetId: number | bigint) {
+ return (await this.helper.callRpc('api.query.assets.asset', [assetId])).toJSON();
+ }
+
async account(assetId: string | number | bigint, address: string) {
const accountAsset = (
await this.helper.callRpc('api.query.assets.account', [assetId, address])
js-packages/tests/eth/api/CollectionHelpers.soldiffbeforeafterboth--- a/js-packages/tests/eth/api/CollectionHelpers.sol
+++ b/js-packages/tests/eth/api/CollectionHelpers.sol
@@ -132,7 +132,7 @@
type CollectionFlags is uint8;
library CollectionFlagsLib {
- /// Tokens in foreign collections can be transferred, but not burnt
+ /// A collection of foreign assets
CollectionFlags constant foreignField = CollectionFlags.wrap(128);
/// Supports ERC721Metadata
CollectionFlags constant erc721metadataField = CollectionFlags.wrap(64);
js-packages/tests/pallet-presence.test.tsdiffbeforeafterboth--- a/js-packages/tests/pallet-presence.test.ts
+++ b/js-packages/tests/pallet-presence.test.ts
@@ -47,7 +47,6 @@
'nonfungible',
'charging',
'configuration',
- 'tokens',
'xtokens',
'maintenance',
];
js-packages/tests/xcm/xcm.types.tsdiffbeforeafterboth--- a/js-packages/tests/xcm/xcm.types.ts
+++ b/js-packages/tests/xcm/xcm.types.ts
@@ -505,4 +505,27 @@
await expectFailedToTransact(helper, messageSent);
});
}
+
+ async registerRelayNativeTokenOnUnique(alice: IKeyringPair) {
+ return await usingPlaygrounds(async (helper) => {
+ const relayLocation = {
+ parents: 1,
+ interior: 'Here',
+ };
+ const relayAssetId = {Concrete: relayLocation};
+
+ const relayCollectionId = await helper.foreignAssets.foreignCollectionId(relayAssetId);
+ if(relayCollectionId == null) {
+ const name = 'Relay Tokens';
+ const tokenPrefix = 'xDOT';
+ const decimals = 10;
+ await helper.getSudo().foreignAssets.register(alice, relayAssetId, name, tokenPrefix, {Fungible: decimals});
+
+ return await helper.foreignAssets.foreignCollectionId(relayAssetId);
+ } else {
+ console.log('Relay foreign collection is already registered');
+ return relayCollectionId;
+ }
+ });
+ }
}
js-packages/tests/xcm/xcmOpal.test.tsdiffbeforeafterboth--- a/js-packages/tests/xcm/xcmOpal.test.ts
+++ b/js-packages/tests/xcm/xcmOpal.test.ts
@@ -17,6 +17,7 @@
import type {IKeyringPair} from '@polkadot/types/types';
import config from '../config.js';
import {itSub, expect, describeXCM, usingPlaygrounds, usingWestmintPlaygrounds, usingRelayPlaygrounds} from '../util/index.js';
+import {XcmTestHelper} from './xcm.types.js';
const STATEMINE_CHAIN = +(process.env.RELAY_WESTMINT_ID || 1000);
const UNIQUE_CHAIN = +(process.env.RELAY_OPAL_ID || 2095);
@@ -25,11 +26,11 @@
const westmintUrl = config.westmintUrl;
const STATEMINE_PALLET_INSTANCE = 50;
-const ASSET_ID = 100;
-const ASSET_METADATA_DECIMALS = 18;
-const ASSET_METADATA_NAME = 'USDT';
-const ASSET_METADATA_DESCRIPTION = 'USDT';
-const ASSET_METADATA_MINIMAL_BALANCE = 1n;
+const USDT_ASSET_ID = 100;
+const USDT_ASSET_METADATA_DECIMALS = 18;
+const USDT_ASSET_METADATA_NAME = 'USDT';
+const USDT_ASSET_METADATA_DESCRIPTION = 'USDT';
+const USDT_ASSET_METADATA_MINIMAL_BALANCE = 1n;
const RELAY_DECIMALS = 12;
const WESTMINT_DECIMALS = 12;
@@ -37,7 +38,9 @@
const TRANSFER_AMOUNT = 1_000_000_000_000_000_000n;
// 10,000.00 (ten thousands) USDT
-const ASSET_AMOUNT = 1_000_000_000_000_000_000_000n;
+const USDT_ASSET_AMOUNT = 1_000_000_000_000_000_000_000n;
+
+const testHelper = new XcmTestHelper('opal');
describeXCM('[XCM] Integration test: Exchanging USDT with Westmint', () => {
let alice: IKeyringPair;
@@ -57,57 +60,85 @@
let balanceBobRelayTokenBefore: bigint;
let balanceBobRelayTokenAfter: bigint;
+ let usdtCollectionId: number;
+ let relayCollectionId: number;
before(async () => {
await usingPlaygrounds(async (_helper, privateKey) => {
alice = await privateKey('//Alice');
bob = await privateKey('//Bob'); // funds donor
+
+ relayCollectionId = await testHelper.registerRelayNativeTokenOnUnique(alice);
});
await usingWestmintPlaygrounds(westmintUrl, async (helper) => {
- // 350.00 (three hundred fifty) DOT
- const fundingAmount = 3_500_000_000_000n;
+ const assetInfo = await helper.assets.assetInfo(USDT_ASSET_ID);
+ if(assetInfo == null) {
+ await helper.assets.create(
+ alice,
+ USDT_ASSET_ID,
+ alice.address,
+ USDT_ASSET_METADATA_MINIMAL_BALANCE,
+ );
+ await helper.assets.setMetadata(
+ alice,
+ USDT_ASSET_ID,
+ USDT_ASSET_METADATA_NAME,
+ USDT_ASSET_METADATA_DESCRIPTION,
+ USDT_ASSET_METADATA_DECIMALS,
+ );
+ } else {
+ console.log('The USDT asset is already registered on AssetHub');
+ }
+
+ await helper.assets.mint(
+ alice,
+ USDT_ASSET_ID,
+ alice.address,
+ USDT_ASSET_AMOUNT,
+ );
- await helper.assets.create(alice, ASSET_ID, alice.address, ASSET_METADATA_MINIMAL_BALANCE);
- await helper.assets.setMetadata(alice, ASSET_ID, ASSET_METADATA_NAME, ASSET_METADATA_DESCRIPTION, ASSET_METADATA_DECIMALS);
- await helper.assets.mint(alice, ASSET_ID, alice.address, ASSET_AMOUNT);
+ const sovereignFundingAmount = 3_500_000_000n;
// funding parachain sovereing account (Parachain: 2095)
const parachainSovereingAccount = helper.address.paraSiblingSovereignAccount(UNIQUE_CHAIN);
- await helper.balance.transferToSubstrate(bob, parachainSovereingAccount, fundingAmount);
+ await helper.balance.transferToSubstrate(bob, parachainSovereingAccount, sovereignFundingAmount);
});
-
await usingPlaygrounds(async (helper) => {
const location = {
- V2: {
- parents: 1,
- interior: {X3: [
- {
- Parachain: STATEMINE_CHAIN,
- },
- {
- PalletInstance: STATEMINE_PALLET_INSTANCE,
- },
- {
- GeneralIndex: ASSET_ID,
- },
- ]},
- },
+ parents: 1,
+ interior: {X3: [
+ {
+ Parachain: STATEMINE_CHAIN,
+ },
+ {
+ PalletInstance: STATEMINE_PALLET_INSTANCE,
+ },
+ {
+ GeneralIndex: USDT_ASSET_ID,
+ },
+ ]},
};
+ const assetId = {Concrete: location};
- const metadata =
- {
- name: ASSET_ID,
- symbol: ASSET_METADATA_NAME,
- decimals: ASSET_METADATA_DECIMALS,
- minimalBalance: ASSET_METADATA_MINIMAL_BALANCE,
- };
- await helper.getSudo().foreignAssets.register(alice, alice.address, location, metadata);
+ if(await helper.foreignAssets.foreignCollectionId(assetId) == null) {
+ const tokenPrefix = USDT_ASSET_METADATA_NAME;
+ await helper.getSudo().foreignAssets.register(
+ alice,
+ assetId,
+ USDT_ASSET_METADATA_NAME,
+ tokenPrefix,
+ {Fungible: USDT_ASSET_METADATA_DECIMALS},
+ );
+ } else {
+ console.log('Foreign collection is already registered on Opal');
+ }
+
balanceOpalBefore = await helper.balance.getSubstrate(alice.address);
+ usdtCollectionId = await helper.foreignAssets.foreignCollectionId(assetId);
});
-
// Providing the relay currency to the unique sender account
await usingRelayPlaygrounds(relayUrl, async (helper) => {
const destination = {
@@ -189,7 +220,7 @@
PalletInstance: STATEMINE_PALLET_INSTANCE,
},
{
- GeneralIndex: ASSET_ID,
+ GeneralIndex: USDT_ASSET_ID,
},
]},
},
@@ -216,19 +247,17 @@
expect(balanceStmnBefore > balanceStmnAfter).to.be.true;
});
-
// ensure that asset has been delivered
await helper.wait.newBlocks(3);
- // expext collection id will be with id 1
- const free = await helper.ft.getBalance(1, {Substrate: alice.address});
+ const free = await helper.ft.getBalance(usdtCollectionId, {Substrate: alice.address});
balanceOpalAfter = await helper.balance.getSubstrate(alice.address);
console.log(
'[Westmint -> Opal] transaction fees on Opal: %s USDT',
- helper.util.bigIntToDecimals(TRANSFER_AMOUNT - free, ASSET_METADATA_DECIMALS),
+ helper.util.bigIntToDecimals(TRANSFER_AMOUNT - free, USDT_ASSET_METADATA_DECIMALS),
);
console.log(
'[Westmint -> Opal] transaction fees on Opal: %s OPL',
@@ -261,16 +290,11 @@
const currencies: [any, bigint][] = [
[
- {
- ForeignAssetId: 0,
- },
- //10_000_000_000_000_000n,
+ usdtCollectionId,
TRANSFER_AMOUNT,
],
[
- {
- NativeAssetId: 'Parent',
- },
+ relayCollectionId,
400_000_000_000_000n,
],
];
@@ -288,7 +312,7 @@
// The USDT token never paid fees. Its amount not changed from begin value.
// Also check that xcm transfer has been succeeded
- expect((await helper.assets.account(ASSET_ID, alice.address))! == ASSET_AMOUNT).to.be.true;
+ expect((await helper.assets.account(USDT_ASSET_ID, alice.address))! == USDT_ASSET_AMOUNT).to.be.true;
});
});
@@ -296,7 +320,7 @@
const TRANSFER_AMOUNT_RELAY = 50_000_000_000_000_000n;
balanceBobBefore = await helper.balance.getSubstrate(bob.address);
- balanceBobRelayTokenBefore = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
+ balanceBobRelayTokenBefore = await helper.ft.getBalance(relayCollectionId, {Substrate: bob.address});
// Providing the relay currency to the unique sender account
await usingRelayPlaygrounds(relayUrl, async (helper) => {
@@ -345,7 +369,7 @@
await helper.wait.newBlocks(3);
balanceBobAfter = await helper.balance.getSubstrate(bob.address);
- balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
+ balanceBobRelayTokenAfter = await helper.ft.getBalance(relayCollectionId, {Substrate: bob.address});
const wndFee = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;
console.log(
@@ -383,9 +407,7 @@
const currencies: any = [
[
- {
- NativeAssetId: 'Parent',
- },
+ relayCollectionId,
50_000_000_000_000_000n,
],
];
js-packages/tests/xcm/xcmQuartz.test.tsdiffbeforeafterboth--- a/js-packages/tests/xcm/xcmQuartz.test.ts
+++ b/js-packages/tests/xcm/xcmQuartz.test.ts
@@ -19,9 +19,8 @@
import {DevUniqueHelper, Event} from '@unique/playgrounds/unique.dev.js';
import {STATEMINE_CHAIN, QUARTZ_CHAIN, KARURA_CHAIN, MOONRIVER_CHAIN, SHIDEN_CHAIN, STATEMINE_DECIMALS, KARURA_DECIMALS, QTZ_DECIMALS, RELAY_DECIMALS, SHIDEN_DECIMALS, karuraUrl, moonriverUrl, relayUrl, shidenUrl, statemineUrl} from './xcm.types.js';
import {hexToString} from '@polkadot/util';
-
+import {XcmTestHelper} from './xcm.types.js';
-
const STATEMINE_PALLET_INSTANCE = 50;
const TRANSFER_AMOUNT = 2000000000000000000000000n;
@@ -39,6 +38,8 @@
const SAFE_XCM_VERSION = 2;
+const testHelper = new XcmTestHelper('quartz');
+
describeXCM('[XCM] Integration test: Exchanging USDT with Statemine', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -57,6 +58,8 @@
let balanceBobRelayTokenBefore: bigint;
let balanceBobRelayTokenAfter: bigint;
+ let usdtCollectionId: number;
+ let relayCollectionId: number;
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
@@ -65,6 +68,8 @@
// Set the default version to wrap the first message to other chains.
await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
+
+ relayCollectionId = await testHelper.registerRelayNativeTokenOnUnique(alice);
});
await usingRelayPlaygrounds(relayUrl, async (helper) => {
@@ -74,21 +79,25 @@
});
await usingStateminePlaygrounds(statemineUrl, async (helper) => {
- const sovereignFundingAmount = 3_500_000_000n;
+ const assetInfo = await helper.assets.assetInfo(USDT_ASSET_ID);
+ if(assetInfo == null) {
+ await helper.assets.create(
+ alice,
+ USDT_ASSET_ID,
+ alice.address,
+ USDT_ASSET_METADATA_MINIMAL_BALANCE,
+ );
+ await helper.assets.setMetadata(
+ alice,
+ USDT_ASSET_ID,
+ USDT_ASSET_METADATA_NAME,
+ USDT_ASSET_METADATA_DESCRIPTION,
+ USDT_ASSET_METADATA_DECIMALS,
+ );
+ } else {
+ console.log('The USDT asset is already registered on AssetHub');
+ }
- await helper.assets.create(
- alice,
- USDT_ASSET_ID,
- alice.address,
- USDT_ASSET_METADATA_MINIMAL_BALANCE,
- );
- await helper.assets.setMetadata(
- alice,
- USDT_ASSET_ID,
- USDT_ASSET_METADATA_NAME,
- USDT_ASSET_METADATA_DESCRIPTION,
- USDT_ASSET_METADATA_DECIMALS,
- );
await helper.assets.mint(
alice,
USDT_ASSET_ID,
@@ -96,6 +105,8 @@
USDT_ASSET_AMOUNT,
);
+ const sovereignFundingAmount = 3_500_000_000n;
+
// funding parachain sovereing account on Statemine(t).
// The sovereign account should be created before any action
// (the assets pallet on Statemine(t) check if the sovereign account exists)
@@ -106,31 +117,30 @@
await usingPlaygrounds(async (helper) => {
const location = {
- V2: {
- parents: 1,
- interior: {X3: [
- {
- Parachain: STATEMINE_CHAIN,
- },
- {
- PalletInstance: STATEMINE_PALLET_INSTANCE,
- },
- {
- GeneralIndex: USDT_ASSET_ID,
- },
- ]},
- },
+ parents: 1,
+ interior: {X3: [
+ {
+ Parachain: STATEMINE_CHAIN,
+ },
+ {
+ PalletInstance: STATEMINE_PALLET_INSTANCE,
+ },
+ {
+ GeneralIndex: USDT_ASSET_ID,
+ },
+ ]},
};
+ const assetId = {Concrete: location};
- const metadata =
- {
- name: USDT_ASSET_ID,
- symbol: USDT_ASSET_METADATA_NAME,
- decimals: USDT_ASSET_METADATA_DECIMALS,
- minimalBalance: USDT_ASSET_METADATA_MINIMAL_BALANCE,
- };
- await helper.getSudo().foreignAssets.register(alice, alice.address, location, metadata);
+ if(await helper.foreignAssets.foreignCollectionId(assetId) == null) {
+ const tokenPrefix = USDT_ASSET_METADATA_NAME;
+ await helper.getSudo().foreignAssets.register(alice, assetId, USDT_ASSET_METADATA_NAME, tokenPrefix, {Fungible: USDT_ASSET_METADATA_DECIMALS});
+ } else {
+ console.log('Foreign collection is already registered on Quartz');
+ }
+
balanceQuartzBefore = await helper.balance.getSubstrate(alice.address);
+ usdtCollectionId = await helper.foreignAssets.foreignCollectionId(assetId);
});
@@ -248,8 +258,7 @@
// ensure that asset has been delivered
await helper.wait.newBlocks(3);
- // expext collection id will be with id 1
- const free = await helper.ft.getBalance(1, {Substrate: alice.address});
+ const free = await helper.ft.getBalance(usdtCollectionId, {Substrate: alice.address});
balanceQuartzAfter = await helper.balance.getSubstrate(alice.address);
@@ -288,15 +297,11 @@
const relayFee = 400_000_000_000_000n;
const currencies: [any, bigint][] = [
[
- {
- ForeignAssetId: 0,
- },
+ usdtCollectionId,
TRANSFER_AMOUNT,
],
[
- {
- NativeAssetId: 'Parent',
- },
+ relayCollectionId,
relayFee,
],
];
@@ -321,7 +326,7 @@
itSub('Should connect and send Relay token to Quartz', async ({helper}) => {
balanceBobBefore = await helper.balance.getSubstrate(bob.address);
- balanceBobRelayTokenBefore = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
+ balanceBobRelayTokenBefore = await helper.ft.getBalance(relayCollectionId, {Substrate: bob.address});
await usingRelayPlaygrounds(relayUrl, async (helper) => {
const destination = {
@@ -369,7 +374,7 @@
await helper.wait.newBlocks(3);
balanceBobAfter = await helper.balance.getSubstrate(bob.address);
- balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
+ balanceBobRelayTokenAfter = await helper.ft.getBalance(relayCollectionId, {Substrate: bob.address});
const wndFeeOnQuartz = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;
const wndDiffOnQuartz = balanceBobRelayTokenAfter - balanceBobRelayTokenBefore;
@@ -409,9 +414,7 @@
const currencies: any = [
[
- {
- NativeAssetId: 'Parent',
- },
+ relayCollectionId,
TRANSFER_AMOUNT_RELAY,
],
];
@@ -1018,9 +1021,7 @@
});
itSub('Should connect and send QTZ to Moonriver', async ({helper}) => {
- const currencyId = {
- NativeAssetId: 'Here',
- };
+ const currencyId = 0;
const dest = {
V2: {
parents: 1,
js-packages/tests/xcm/xcmUnique.test.tsdiffbeforeafterboth--- a/js-packages/tests/xcm/xcmUnique.test.ts
+++ b/js-packages/tests/xcm/xcmUnique.test.ts
@@ -20,7 +20,7 @@
import {Event} from '@unique/playgrounds/unique.dev.js';
import {hexToString, nToBigInt} from '@polkadot/util';
import {ACALA_CHAIN, ASTAR_CHAIN, MOONBEAM_CHAIN, POLKADEX_CHAIN, SAFE_XCM_VERSION, STATEMINT_CHAIN, UNIQUE_CHAIN, expectFailedToTransact, expectUntrustedReserveLocationFail, uniqueAssetId, uniqueVersionedMultilocation} from './xcm.types.js';
-
+import {XcmTestHelper} from './xcm.types.js';
const STATEMINT_PALLET_INSTANCE = 50;
@@ -50,6 +50,8 @@
const USDT_ASSET_METADATA_MINIMAL_BALANCE = 1n;
const USDT_ASSET_AMOUNT = 10_000_000_000_000_000_000_000_000n;
+const testHelper = new XcmTestHelper('unique');
+
describeXCM('[XCM] Integration test: Exchanging USDT with Statemint', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -68,6 +70,8 @@
let balanceBobRelayTokenBefore: bigint;
let balanceBobRelayTokenAfter: bigint;
+ let usdtCollectionId: number;
+ let relayCollectionId: number;
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
@@ -76,6 +80,8 @@
// Set the default version to wrap the first message to other chains.
await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
+
+ relayCollectionId = await testHelper.registerRelayNativeTokenOnUnique(alice);
});
await usingRelayPlaygrounds(relayUrl, async (helper) => {
@@ -85,21 +91,25 @@
});
await usingStatemintPlaygrounds(statemintUrl, async (helper) => {
- const sovereignFundingAmount = 3_500_000_000n;
+ const assetInfo = await helper.assets.assetInfo(USDT_ASSET_ID);
+ if(assetInfo == null) {
+ await helper.assets.create(
+ alice,
+ USDT_ASSET_ID,
+ alice.address,
+ USDT_ASSET_METADATA_MINIMAL_BALANCE,
+ );
+ await helper.assets.setMetadata(
+ alice,
+ USDT_ASSET_ID,
+ USDT_ASSET_METADATA_NAME,
+ USDT_ASSET_METADATA_DESCRIPTION,
+ USDT_ASSET_METADATA_DECIMALS,
+ );
+ } else {
+ console.log('The USDT asset is already registered on AssetHub');
+ }
- await helper.assets.create(
- alice,
- USDT_ASSET_ID,
- alice.address,
- USDT_ASSET_METADATA_MINIMAL_BALANCE,
- );
- await helper.assets.setMetadata(
- alice,
- USDT_ASSET_ID,
- USDT_ASSET_METADATA_NAME,
- USDT_ASSET_METADATA_DESCRIPTION,
- USDT_ASSET_METADATA_DECIMALS,
- );
await helper.assets.mint(
alice,
USDT_ASSET_ID,
@@ -107,6 +117,8 @@
USDT_ASSET_AMOUNT,
);
+ const sovereignFundingAmount = 3_500_000_000n;
+
// funding parachain sovereing account on Statemint.
// The sovereign account should be created before any action
// (the assets pallet on Statemint check if the sovereign account exists)
@@ -117,31 +129,30 @@
await usingPlaygrounds(async (helper) => {
const location = {
- V2: {
- parents: 1,
- interior: {X3: [
- {
- Parachain: STATEMINT_CHAIN,
- },
- {
- PalletInstance: STATEMINT_PALLET_INSTANCE,
- },
- {
- GeneralIndex: USDT_ASSET_ID,
- },
- ]},
- },
+ parents: 1,
+ interior: {X3: [
+ {
+ Parachain: STATEMINT_CHAIN,
+ },
+ {
+ PalletInstance: STATEMINT_PALLET_INSTANCE,
+ },
+ {
+ GeneralIndex: USDT_ASSET_ID,
+ },
+ ]},
};
+ const assetId = {Concrete: location};
- const metadata =
- {
- name: USDT_ASSET_ID,
- symbol: USDT_ASSET_METADATA_NAME,
- decimals: USDT_ASSET_METADATA_DECIMALS,
- minimalBalance: USDT_ASSET_METADATA_MINIMAL_BALANCE,
- };
- await helper.getSudo().foreignAssets.register(alice, alice.address, location, metadata);
+ if(await helper.foreignAssets.foreignCollectionId(assetId) == null) {
+ const tokenPrefix = USDT_ASSET_METADATA_NAME;
+ await helper.getSudo().foreignAssets.register(alice, assetId, USDT_ASSET_METADATA_NAME, tokenPrefix, {Fungible: USDT_ASSET_METADATA_DECIMALS});
+ } else {
+ console.log('Foreign collection is already registered on Unique');
+ }
+
balanceUniqueBefore = await helper.balance.getSubstrate(alice.address);
+ usdtCollectionId = await helper.foreignAssets.foreignCollectionId(assetId);
});
@@ -259,8 +270,7 @@
// ensure that asset has been delivered
await helper.wait.newBlocks(3);
- // expext collection id will be with id 1
- const free = await helper.ft.getBalance(1, {Substrate: alice.address});
+ const free = await helper.ft.getBalance(usdtCollectionId, {Substrate: alice.address});
balanceUniqueAfter = await helper.balance.getSubstrate(alice.address);
@@ -299,15 +309,11 @@
const relayFee = 400_000_000_000_000n;
const currencies: [any, bigint][] = [
[
- {
- ForeignAssetId: 0,
- },
+ usdtCollectionId,
TRANSFER_AMOUNT,
],
[
- {
- NativeAssetId: 'Parent',
- },
+ relayCollectionId,
relayFee,
],
];
@@ -332,7 +338,7 @@
itSub('Should connect and send Relay token to Unique', async ({helper}) => {
balanceBobBefore = await helper.balance.getSubstrate(bob.address);
- balanceBobRelayTokenBefore = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
+ balanceBobRelayTokenBefore = await helper.ft.getBalance(relayCollectionId, {Substrate: bob.address});
await usingRelayPlaygrounds(relayUrl, async (helper) => {
const destination = {
@@ -380,7 +386,7 @@
await helper.wait.newBlocks(3);
balanceBobAfter = await helper.balance.getSubstrate(bob.address);
- balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
+ balanceBobRelayTokenAfter = await helper.ft.getBalance(relayCollectionId, {Substrate: bob.address});
const wndFeeOnUnique = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;
const wndDiffOnUnique = balanceBobRelayTokenAfter - balanceBobRelayTokenBefore;
@@ -420,9 +426,7 @@
const currencies: any = [
[
- {
- NativeAssetId: 'Parent',
- },
+ relayCollectionId,
TRANSFER_AMOUNT_RELAY,
],
];
@@ -1275,9 +1279,7 @@
});
itSub('Should connect and send UNQ to Moonbeam', async ({helper}) => {
- const currencyId = {
- NativeAssetId: 'Here',
- };
+ const currencyId = 0;
const dest = {
V2: {
parents: 1,
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -167,7 +167,6 @@
.map(|k| (k, 1 << 100))
.collect(),
},
- tokens: TokensConfig { balances: vec![] },
sudo: SudoConfig {
key: Some($root_key),
},
@@ -231,7 +230,6 @@
.map(|k| (k, 1 << 100))
.collect(),
},
- tokens: TokensConfig { balances: vec![] },
sudo: SudoConfig {
key: Some($root_key),
},
pallets/balances-adapter/src/common.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -1,10 +1,16 @@
use alloc::{vec, vec::Vec};
use core::marker::PhantomData;
-use frame_support::{ensure, fail, weights::Weight};
+use frame_support::{
+ ensure, fail,
+ traits::tokens::{fungible::Mutate, Fortitude, Precision},
+ weights::Weight,
+};
use pallet_balances::{weights::SubstrateWeight as BalancesWeight, WeightInfo};
-use pallet_common::{CommonCollectionOperations, CommonWeightInfo, Error as CommonError};
-use up_data_structs::TokenId;
+use pallet_common::{
+ erc::CrossAccountId, CommonCollectionOperations, CommonWeightInfo, Error as CommonError,
+};
+use up_data_structs::{budget::Budget, TokenId};
use crate::{Config, NativeFungibleHandle, Pallet};
@@ -332,8 +338,8 @@
0
}
- fn refungible_extensions(&self) -> Option<&dyn pallet_common::RefungibleExtensions<T>> {
- None
+ fn xcm_extensions(&self) -> Option<&dyn pallet_common::XcmExtensions<T>> {
+ Some(self)
}
fn set_allowance_for_all(
@@ -360,3 +366,72 @@
fail!(<CommonError<T>>::UnsupportedOperation);
}
}
+
+impl<T: Config> pallet_common::XcmExtensions<T> for NativeFungibleHandle<T> {
+ fn create_item_internal(
+ &self,
+ _depositor: &<T>::CrossAccountId,
+ to: <T>::CrossAccountId,
+ data: up_data_structs::CreateItemData,
+ _nesting_budget: &dyn Budget,
+ ) -> Result<TokenId, sp_runtime::DispatchError> {
+ match &data {
+ up_data_structs::CreateItemData::Fungible(fungible_data) => {
+ T::Mutate::mint_into(
+ to.as_sub(),
+ fungible_data
+ .value
+ .try_into()
+ .map_err(|_| sp_runtime::ArithmeticError::Overflow)?,
+ )?;
+
+ Ok(TokenId::default())
+ }
+ _ => {
+ fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken)
+ }
+ }
+ }
+
+ fn transfer_item_internal(
+ &self,
+ _depositor: &<T>::CrossAccountId,
+ from: &<T>::CrossAccountId,
+ to: &<T>::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ _nesting_budget: &dyn Budget,
+ ) -> sp_runtime::DispatchResult {
+ ensure!(
+ token == TokenId::default(),
+ <CommonError<T>>::FungibleItemsHaveNoId
+ );
+
+ <Pallet<T>>::transfer(from, to, amount)
+ .map(|_| ())
+ .map_err(|post_info| post_info.error)
+ }
+
+ fn burn_item_internal(
+ &self,
+ from: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> sp_runtime::DispatchResult {
+ ensure!(
+ token == TokenId::default(),
+ <CommonError<T>>::FungibleItemsHaveNoId
+ );
+
+ T::Mutate::burn_from(
+ from.as_sub(),
+ amount
+ .try_into()
+ .map_err(|_| sp_runtime::ArithmeticError::Overflow)?,
+ Precision::Exact,
+ Fortitude::Polite,
+ )?;
+
+ Ok(())
+ }
+}
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -33,7 +33,7 @@
MAX_COLLECTION_NAME_LENGTH, MAX_PROPERTIES_PER_ITEM, MAX_TOKEN_PREFIX_LENGTH,
};
-use crate::{BenchmarkPropertyWriter, CollectionHandle, Config, Pallet};
+use crate::{BenchmarkPropertyWriter, CollectionHandle, CollectionIssuer, Config, Pallet};
const SEED: u32 = 1;
@@ -120,7 +120,9 @@
create_collection_raw(
owner,
CollectionMode::NFT,
- |owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
+ |owner: T::CrossAccountId, data| {
+ <Pallet<T>>::init_collection(owner.clone(), CollectionIssuer::User(owner), data)
+ },
|h| h,
)
}
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -11,7 +11,7 @@
use sp_weights::Weight;
use up_data_structs::{CollectionId, CreateCollectionData};
-use crate::{pallet::Config, CommonCollectionOperations};
+use crate::{pallet::Config, CollectionIssuer, CommonCollectionOperations};
// TODO: move to benchmarking
/// Price of [`dispatch_tx`] call with noop `call` argument
@@ -69,13 +69,14 @@
/// Check if the collection is internal.
fn check_is_internal(&self) -> DispatchResult;
- /// Create a collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
+ /// Create a regular collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
///
/// * `sender` - The user who will become the owner of the collection.
+ /// * `issuer` - An entity that creates the collection.
/// * `data` - Description of the created collection.
fn create(
sender: T::CrossAccountId,
- payer: T::CrossAccountId,
+ issuer: CollectionIssuer<T::CrossAccountId>,
data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError>;
pallets/common/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use alloc::boxed::Box;57use core::{58 marker::PhantomData,59 ops::{Deref, DerefMut},60 slice::from_ref,61 unreachable,62};6364use evm_coder::ToLog;65use frame_support::{66 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Pays, PostDispatchInfo},67 ensure, fail,68 traits::{69 fungible::{Balanced, Debt, Inspect},70 tokens::{Imbalance, Precision, Preservation},71 Get,72 },73 transactional,74};75pub use pallet::*;76use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};77use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};78use sp_core::H160;79use sp_runtime::{traits::Zero, ArithmeticError, DispatchError, DispatchResult};80use sp_std::vec::Vec;81use sp_weights::Weight;82use up_data_structs::{83 budget::Budget, AccessMode, Collection, CollectionId, CollectionLimits, CollectionMode,84 CollectionPermissions, CollectionProperties as CollectionPropertiesT, CollectionStats,85 CreateCollectionData, CreateItemData, CreateItemExData, PhantomType, PropertiesError,86 PropertiesPermissionMap, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,87 PropertyScope, PropertyValue, RpcCollection, RpcCollectionFlags, SponsoringRateLimit,88 SponsorshipState, TokenChild, TokenData, TokenId, TokenOwnerError, TokenProperties,89 TrySetProperty, COLLECTION_ADMINS_LIMIT, COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT,90 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP,91 MAX_TOKEN_PREFIX_LENGTH, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,92};93use up_pov_estimate_rpc::PovInfo;9495#[cfg(feature = "runtime-benchmarks")]96pub mod benchmarking;97pub mod dispatch;98pub mod erc;99pub mod eth;100pub mod helpers;101#[allow(missing_docs)]102pub mod weights;103104use weights::WeightInfo;105106/// Weight info.107pub type SelfWeightOf<T> = <T as Config>::WeightInfo;108109/// Collection handle contains information about collection data and id.110/// Also provides functionality to count consumed gas.111///112/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).113/// It allows to perform common operations and queries on any collection type,114/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].115#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]116pub struct CollectionHandle<T: Config> {117 /// Collection id118 pub id: CollectionId,119 collection: Collection<T::AccountId>,120 /// Substrate recorder for counting consumed gas121 pub recorder: SubstrateRecorder<T>,122}123124impl<T: Config> WithRecorder<T> for CollectionHandle<T> {125 fn recorder(&self) -> &SubstrateRecorder<T> {126 &self.recorder127 }128 fn into_recorder(self) -> SubstrateRecorder<T> {129 self.recorder130 }131}132133impl<T: Config> CollectionHandle<T> {134 /// Same as [CollectionHandle::new] but with an explicit gas limit.135 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {136 Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))137 }138139 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].140 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {141 <CollectionById<T>>::get(id).map(|collection| Self {142 id,143 collection,144 recorder,145 })146 }147148 /// Retrives collection data from storage and creates collection handle with default parameters.149 /// If collection not found return `None`150 pub fn new(id: CollectionId) -> Option<Self> {151 Self::new_with_gas_limit(id, u64::MAX)152 }153154 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.155 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {156 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)157 }158159 /// Consume gas for reading.160 pub fn consume_store_reads(161 &self,162 reads: u64,163 ) -> pallet_evm_coder_substrate::execution::Result<()> {164 self.recorder().consume_store_reads(reads)165 }166167 /// Consume gas for writing.168 pub fn consume_store_writes(169 &self,170 writes: u64,171 ) -> pallet_evm_coder_substrate::execution::Result<()> {172 self.recorder().consume_store_writes(writes)173 }174175 /// Consume gas for reading and writing.176 pub fn consume_store_reads_and_writes(177 &self,178 reads: u64,179 writes: u64,180 ) -> pallet_evm_coder_substrate::execution::Result<()> {181 self.recorder()182 .consume_store_reads_and_writes(reads, writes)183 }184185 /// Save collection to storage.186 pub fn save(&self) -> DispatchResult {187 <CollectionById<T>>::insert(self.id, &self.collection);188 Ok(())189 }190191 /// Set collection sponsor.192 ///193 /// Unique collections allows sponsoring for certain actions.194 /// This method allows you to set the sponsor of the collection.195 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].196 pub fn set_sponsor(197 &mut self,198 sender: &T::CrossAccountId,199 sponsor: T::AccountId,200 ) -> DispatchResult {201 self.check_is_internal()?;202 self.check_is_owner_or_admin(sender)?;203204 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());205206 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));207 <PalletEvm<T>>::deposit_log(208 erc::CollectionHelpersEvents::CollectionChanged {209 collection_id: eth::collection_id_to_address(self.id),210 }211 .to_log(T::ContractAddress::get()),212 );213214 self.save()215 }216217 /// Force set `sponsor`.218 ///219 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation220 /// from the `sponsor` is not required.221 ///222 /// # Arguments223 ///224 /// * `sponsor`: ID of the account of the sponsor-to-be.225 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {226 self.check_is_internal()?;227228 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());229230 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));231 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));232 <PalletEvm<T>>::deposit_log(233 erc::CollectionHelpersEvents::CollectionChanged {234 collection_id: eth::collection_id_to_address(self.id),235 }236 .to_log(T::ContractAddress::get()),237 );238239 self.save()240 }241242 /// Confirm sponsorship243 ///244 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.245 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].246 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {247 self.check_is_internal()?;248 ensure!(249 self.collection.sponsorship.pending_sponsor() == Some(sender),250 Error::<T>::ConfirmSponsorshipFail251 );252253 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());254255 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));256 <PalletEvm<T>>::deposit_log(257 erc::CollectionHelpersEvents::CollectionChanged {258 collection_id: eth::collection_id_to_address(self.id),259 }260 .to_log(T::ContractAddress::get()),261 );262263 self.save()264 }265266 /// Remove collection sponsor.267 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {268 self.check_is_internal()?;269 self.check_is_owner_or_admin(sender)?;270271 self.collection.sponsorship = SponsorshipState::Disabled;272273 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));274 <PalletEvm<T>>::deposit_log(275 erc::CollectionHelpersEvents::CollectionChanged {276 collection_id: eth::collection_id_to_address(self.id),277 }278 .to_log(T::ContractAddress::get()),279 );280 self.save()281 }282283 /// Force remove `sponsor`.284 ///285 /// Differs from `remove_sponsor` in that286 /// it doesn't require consent from the `owner` of the collection.287 pub fn force_remove_sponsor(&mut self) -> DispatchResult {288 self.check_is_internal()?;289290 self.collection.sponsorship = SponsorshipState::Disabled;291292 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));293 <PalletEvm<T>>::deposit_log(294 erc::CollectionHelpersEvents::CollectionChanged {295 collection_id: eth::collection_id_to_address(self.id),296 }297 .to_log(T::ContractAddress::get()),298 );299 self.save()300 }301302 /// Checks that the collection was created with, and must be operated upon through **Unique API**.303 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.304 pub fn check_is_internal(&self) -> DispatchResult {305 if self.flags.external {306 return Err(<Error<T>>::CollectionIsExternal)?;307 }308309 Ok(())310 }311312 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.313 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.314 pub fn check_is_external(&self) -> DispatchResult {315 if !self.flags.external {316 return Err(<Error<T>>::CollectionIsInternal)?;317 }318319 Ok(())320 }321}322323impl<T: Config> Deref for CollectionHandle<T> {324 type Target = Collection<T::AccountId>;325326 fn deref(&self) -> &Self::Target {327 &self.collection328 }329}330331impl<T: Config> DerefMut for CollectionHandle<T> {332 fn deref_mut(&mut self) -> &mut Self::Target {333 &mut self.collection334 }335}336337impl<T: Config> CollectionHandle<T> {338 /// Checks if the `user` is the owner of the collection.339 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {340 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);341 Ok(())342 }343344 /// Returns **true** if the `user` is the owner or administrator of the collection.345 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {346 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))347 }348349 /// Checks if the `user` is the owner or administrator of the collection.350 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {351 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);352 Ok(())353 }354355 /// Returns **true** if356 /// * the `user`is a collection owner or admin357 /// * the collection limits allow the owner/admins to transfer/burn any collection token358 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {359 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)360 }361362 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.363 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {364 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)365 }366367 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.368 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {369 ensure!(370 <Allowlist<T>>::get((self.id, user)),371 <Error<T>>::AddressNotInAllowlist372 );373 Ok(())374 }375376 /// Changes collection owner to another account377 /// #### Store read/writes378 /// 1 writes379 pub fn change_owner(380 &mut self,381 caller: T::CrossAccountId,382 new_owner: T::CrossAccountId,383 ) -> DispatchResult {384 self.check_is_internal()?;385 self.check_is_owner(&caller)?;386 self.collection.owner = new_owner.as_sub().clone();387388 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(389 self.id,390 new_owner.as_sub().clone(),391 ));392 <PalletEvm<T>>::deposit_log(393 erc::CollectionHelpersEvents::CollectionChanged {394 collection_id: eth::collection_id_to_address(self.id),395 }396 .to_log(T::ContractAddress::get()),397 );398399 self.save()400 }401}402403#[frame_support::pallet]404pub mod pallet {405406 use dispatch::CollectionDispatch;407 use frame_support::{408 pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat,409 };410 use scale_info::TypeInfo;411 use up_data_structs::{mapping::TokenAddressMapping, TokenId};412 use weights::WeightInfo;413414 use super::*;415416 #[pallet::config]417 pub trait Config:418 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo419 {420 /// Weight information for functions of this pallet.421 type WeightInfo: WeightInfo;422423 /// Events compatible with [`frame_system::Config::Event`].424 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;425426 /// Handler of accounts and payment.427 type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;428429 /// Set price to create a collection.430 #[pallet::constant]431 type CollectionCreationPrice: Get<432 <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,433 >;434435 /// Dispatcher of operations on collections.436 type CollectionDispatch: CollectionDispatch<Self>;437438 /// Account which holds the chain's treasury.439 type TreasuryAccountId: Get<Self::AccountId>;440441 /// Address under which the CollectionHelper contract would be available.442 #[pallet::constant]443 type ContractAddress: Get<H160>;444445 /// Mapper for token addresses to Ethereum addresses.446 type EvmTokenAddressMapping: TokenAddressMapping<H160>;447448 /// Mapper for token addresses to [`CrossAccountId`].449 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;450 }451452 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);453 /// Collection id for native fungible collction.454 pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);455456 #[pallet::pallet]457 #[pallet::storage_version(STORAGE_VERSION)]458 pub struct Pallet<T>(_);459460 #[pallet::extra_constants]461 impl<T: Config> Pallet<T> {462 /// Maximum admins per collection.463 pub fn collection_admins_limit() -> u32 {464 COLLECTION_ADMINS_LIMIT465 }466 }467468 #[pallet::genesis_config]469 pub struct GenesisConfig<T>(PhantomData<T>);470471 impl<T: Config> Default for GenesisConfig<T> {472 fn default() -> Self {473 Self(Default::default())474 }475 }476477 #[pallet::genesis_build]478 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {479 fn build(&self) {480 StorageVersion::new(1).put::<Pallet<T>>();481 }482 }483484 impl<T: Config> Pallet<T> {485 /// Helper function that handles deposit events486 pub fn deposit_event(event: Event<T>) {487 let event = <T as Config>::RuntimeEvent::from(event);488 let event = event.into();489 <frame_system::Pallet<T>>::deposit_event(event)490 }491 }492493 #[pallet::event]494 pub enum Event<T: Config> {495 /// New collection was created496 CollectionCreated(497 /// Globally unique identifier of newly created collection.498 CollectionId,499 /// [`CollectionMode`] converted into _u8_.500 u8,501 /// Collection owner.502 T::AccountId,503 ),504505 /// New collection was destroyed506 CollectionDestroyed(507 /// Globally unique identifier of collection.508 CollectionId,509 ),510511 /// New item was created.512 ItemCreated(513 /// Id of the collection where item was created.514 CollectionId,515 /// Id of an item. Unique within the collection.516 TokenId,517 /// Owner of newly created item518 T::CrossAccountId,519 /// Always 1 for NFT520 u128,521 ),522523 /// Collection item was burned.524 ItemDestroyed(525 /// Id of the collection where item was destroyed.526 CollectionId,527 /// Identifier of burned NFT.528 TokenId,529 /// Which user has destroyed its tokens.530 T::CrossAccountId,531 /// Amount of token pieces destroed. Always 1 for NFT.532 u128,533 ),534535 /// Item was transferred536 Transfer(537 /// Id of collection to which item is belong.538 CollectionId,539 /// Id of an item.540 TokenId,541 /// Original owner of item.542 T::CrossAccountId,543 /// New owner of item.544 T::CrossAccountId,545 /// Amount of token pieces transfered. Always 1 for NFT.546 u128,547 ),548549 /// Amount pieces of token owned by `sender` was approved for `spender`.550 Approved(551 /// Id of collection to which item is belong.552 CollectionId,553 /// Id of an item.554 TokenId,555 /// Original owner of item.556 T::CrossAccountId,557 /// Id for which the approval was granted.558 T::CrossAccountId,559 /// Amount of token pieces transfered. Always 1 for NFT.560 u128,561 ),562563 /// A `sender` approves operations on all owned tokens for `spender`.564 ApprovedForAll(565 /// Id of collection to which item is belong.566 CollectionId,567 /// Owner of a wallet.568 T::CrossAccountId,569 /// Id for which operator status was granted or rewoked.570 T::CrossAccountId,571 /// Is operator status granted or revoked?572 bool,573 ),574575 /// The colletion property has been added or edited.576 CollectionPropertySet(577 /// Id of collection to which property has been set.578 CollectionId,579 /// The property that was set.580 PropertyKey,581 ),582583 /// The property has been deleted.584 CollectionPropertyDeleted(585 /// Id of collection to which property has been deleted.586 CollectionId,587 /// The property that was deleted.588 PropertyKey,589 ),590591 /// The token property has been added or edited.592 TokenPropertySet(593 /// Identifier of the collection whose token has the property set.594 CollectionId,595 /// The token for which the property was set.596 TokenId,597 /// The property that was set.598 PropertyKey,599 ),600601 /// The token property has been deleted.602 TokenPropertyDeleted(603 /// Identifier of the collection whose token has the property deleted.604 CollectionId,605 /// The token for which the property was deleted.606 TokenId,607 /// The property that was deleted.608 PropertyKey,609 ),610611 /// The token property permission of a collection has been set.612 PropertyPermissionSet(613 /// ID of collection to which property permission has been set.614 CollectionId,615 /// The property permission that was set.616 PropertyKey,617 ),618619 /// Address was added to the allow list.620 AllowListAddressAdded(621 /// ID of the affected collection.622 CollectionId,623 /// Address of the added account.624 T::CrossAccountId,625 ),626627 /// Address was removed from the allow list.628 AllowListAddressRemoved(629 /// ID of the affected collection.630 CollectionId,631 /// Address of the removed account.632 T::CrossAccountId,633 ),634635 /// Collection admin was added.636 CollectionAdminAdded(637 /// ID of the affected collection.638 CollectionId,639 /// Admin address.640 T::CrossAccountId,641 ),642643 /// Collection admin was removed.644 CollectionAdminRemoved(645 /// ID of the affected collection.646 CollectionId,647 /// Removed admin address.648 T::CrossAccountId,649 ),650651 /// Collection limits were set.652 CollectionLimitSet(653 /// ID of the affected collection.654 CollectionId,655 ),656657 /// Collection owned was changed.658 CollectionOwnerChanged(659 /// ID of the affected collection.660 CollectionId,661 /// New owner address.662 T::AccountId,663 ),664665 /// Collection permissions were set.666 CollectionPermissionSet(667 /// ID of the affected collection.668 CollectionId,669 ),670671 /// Collection sponsor was set.672 CollectionSponsorSet(673 /// ID of the affected collection.674 CollectionId,675 /// New sponsor address.676 T::AccountId,677 ),678679 /// New sponsor was confirm.680 SponsorshipConfirmed(681 /// ID of the affected collection.682 CollectionId,683 /// New sponsor address.684 T::AccountId,685 ),686687 /// Collection sponsor was removed.688 CollectionSponsorRemoved(689 /// ID of the affected collection.690 CollectionId,691 ),692 }693694 #[pallet::error]695 pub enum Error<T> {696 /// This collection does not exist.697 CollectionNotFound,698 /// Sender parameter and item owner must be equal.699 MustBeTokenOwner,700 /// No permission to perform action701 NoPermission,702 /// Destroying only empty collections is allowed703 CantDestroyNotEmptyCollection,704 /// Collection is not in mint mode.705 PublicMintingNotAllowed,706 /// Address is not in allow list.707 AddressNotInAllowlist,708709 /// Collection name can not be longer than 63 char.710 CollectionNameLimitExceeded,711 /// Collection description can not be longer than 255 char.712 CollectionDescriptionLimitExceeded,713 /// Token prefix can not be longer than 15 char.714 CollectionTokenPrefixLimitExceeded,715 /// Total collections bound exceeded.716 TotalCollectionsLimitExceeded,717 /// Exceeded max admin count718 CollectionAdminCountExceeded,719 /// Collection limit bounds per collection exceeded720 CollectionLimitBoundsExceeded,721 /// Tried to enable permissions which are only permitted to be disabled722 OwnerPermissionsCantBeReverted,723 /// Collection settings not allowing items transferring724 TransferNotAllowed,725 /// Account token limit exceeded per collection726 AccountTokenLimitExceeded,727 /// Collection token limit exceeded728 CollectionTokenLimitExceeded,729 /// Metadata flag frozen730 MetadataFlagFrozen,731732 /// Item does not exist733 TokenNotFound,734 /// Item is balance not enough735 TokenValueTooLow,736 /// Requested value is more than the approved737 ApprovedValueTooLow,738 /// Tried to approve more than owned739 CantApproveMoreThanOwned,740 /// Only spending from eth mirror could be approved741 AddressIsNotEthMirror,742743 /// Can't transfer tokens to ethereum zero address744 AddressIsZero,745746 /// The operation is not supported747 UnsupportedOperation,748749 /// Insufficient funds to perform an action750 NotSufficientFounds,751752 /// User does not satisfy the nesting rule753 UserIsNotAllowedToNest,754 /// Only tokens from specific collections may nest tokens under this one755 SourceCollectionIsNotAllowedToNest,756757 /// Tried to store more data than allowed in collection field758 CollectionFieldSizeExceeded,759760 /// Tried to store more property data than allowed761 NoSpaceForProperty,762763 /// Tried to store more property keys than allowed764 PropertyLimitReached,765766 /// Property key is too long767 PropertyKeyIsTooLong,768769 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed770 InvalidCharacterInPropertyKey,771772 /// Empty property keys are forbidden773 EmptyPropertyKey,774775 /// Tried to access an external collection with an internal API776 CollectionIsExternal,777778 /// Tried to access an internal collection with an external API779 CollectionIsInternal,780781 /// This address is not set as sponsor, use setCollectionSponsor first.782 ConfirmSponsorshipFail,783784 /// The user is not an administrator.785 UserIsNotCollectionAdmin,786787 /// Fungible tokens hold no ID, and the default value of TokenId for a fungible collection is 0.788 FungibleItemsHaveNoId,789 }790791 /// Storage of the count of created collections. Essentially contains the last collection ID.792 #[pallet::storage]793 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;794795 /// Storage of the count of deleted collections.796 #[pallet::storage]797 pub type DestroyedCollectionCount<T> =798 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;799800 /// Storage of collection info.801 #[pallet::storage]802 pub type CollectionById<T> = StorageMap<803 Hasher = Blake2_128Concat,804 Key = CollectionId,805 Value = Collection<<T as frame_system::Config>::AccountId>,806 QueryKind = OptionQuery,807 >;808809 /// Storage of collection properties.810 #[pallet::storage]811 #[pallet::getter(fn collection_properties)]812 pub type CollectionProperties<T> = StorageMap<813 Hasher = Blake2_128Concat,814 Key = CollectionId,815 Value = CollectionPropertiesT,816 QueryKind = ValueQuery,817 >;818819 /// Storage of token property permissions of a collection.820 #[pallet::storage]821 #[pallet::getter(fn property_permissions)]822 pub type CollectionPropertyPermissions<T> = StorageMap<823 Hasher = Blake2_128Concat,824 Key = CollectionId,825 Value = PropertiesPermissionMap,826 QueryKind = ValueQuery,827 >;828829 /// Storage of the amount of collection admins.830 #[pallet::storage]831 pub type AdminAmount<T> = StorageMap<832 Hasher = Blake2_128Concat,833 Key = CollectionId,834 Value = u32,835 QueryKind = ValueQuery,836 >;837838 /// List of collection admins.839 #[pallet::storage]840 pub type IsAdmin<T: Config> = StorageNMap<841 Key = (842 Key<Blake2_128Concat, CollectionId>,843 Key<Blake2_128Concat, T::CrossAccountId>,844 ),845 Value = bool,846 QueryKind = ValueQuery,847 >;848849 /// Allowlisted collection users.850 #[pallet::storage]851 pub type Allowlist<T: Config> = StorageNMap<852 Key = (853 Key<Blake2_128Concat, CollectionId>,854 Key<Blake2_128Concat, T::CrossAccountId>,855 ),856 Value = bool,857 QueryKind = ValueQuery,858 >;859860 /// Not used by code, exists only to provide some types to metadata.861 #[pallet::storage]862 pub type DummyStorageValue<T: Config> = StorageValue<863 Value = (864 CollectionStats,865 CollectionId,866 TokenId,867 TokenChild,868 PhantomType<(869 TokenData<T::CrossAccountId>,870 RpcCollection<T::AccountId>,871 // PoV Estimate Info872 PovInfo,873 )>,874 ),875 QueryKind = OptionQuery,876 >;877}878879enum LazyValueState<'a, T> {880 Pending(Box<dyn FnOnce() -> T + 'a>),881 InProgress,882 Computed(T),883}884885/// Value representation with delayed initialization time.886pub struct LazyValue<'a, T> {887 state: LazyValueState<'a, T>,888}889890impl<'a, T> LazyValue<'a, T> {891 /// Create a new LazyValue.892 pub fn new(f: impl FnOnce() -> T + 'a) -> Self {893 Self {894 state: LazyValueState::Pending(Box::new(f)),895 }896 }897898 /// Get the value. If it is called the first time, the value will be initialized.899 pub fn value(&mut self) -> &T {900 self.force_value();901 self.value_mut()902 }903904 /// Get the value. If it is called the first time, the value will be initialized.905 pub fn value_mut(&mut self) -> &mut T {906 self.force_value();907908 if let LazyValueState::Computed(value) = &mut self.state {909 value910 } else {911 unreachable!()912 }913 }914915 fn into_inner(mut self) -> T {916 self.force_value();917 if let LazyValueState::Computed(value) = self.state {918 value919 } else {920 unreachable!()921 }922 }923924 /// Is value initialized?925 pub fn has_value(&self) -> bool {926 matches!(self.state, LazyValueState::Computed(_))927 }928929 fn force_value(&mut self) {930 use LazyValueState::*;931932 if self.has_value() {933 return;934 }935936 match sp_std::mem::replace(&mut self.state, InProgress) {937 Pending(f) => self.state = Computed(f()),938 _ => panic!("recursion isn't supported"),939 }940 }941}942943fn check_token_permissions<T: Config>(944 collection_admin_permitted: bool,945 token_owner_permitted: bool,946 is_collection_admin: &mut LazyValue<bool>,947 is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,948 is_token_exist: &mut LazyValue<bool>,949) -> DispatchResult {950 if !(collection_admin_permitted && *is_collection_admin.value()951 || token_owner_permitted && (*is_token_owner.value())?)952 {953 fail!(<Error<T>>::NoPermission);954 }955956 let token_exist_due_to_owner_check_success =957 is_token_owner.has_value() && (*is_token_owner.value())?;958959 // If the token owner check has occurred and succeeded,960 // we know the token exists (otherwise, the owner check must fail).961 if !token_exist_due_to_owner_check_success {962 // If the token owner check didn't occur,963 // we must check the token's existence ourselves.964 if !is_token_exist.value() {965 fail!(<Error<T>>::TokenNotFound);966 }967 }968969 Ok(())970}971972impl<T: Config> Pallet<T> {973 /// Enshure that receiver address is correct.974 ///975 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.976 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {977 ensure!(978 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,979 <Error<T>>::AddressIsZero980 );981 Ok(())982 }983984 /// Get a vector of collection admins.985 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {986 <IsAdmin<T>>::iter_prefix((collection,))987 .map(|(a, _)| a)988 .collect()989 }990991 /// Get a vector of users allowed to mint tokens.992 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {993 <Allowlist<T>>::iter_prefix((collection,))994 .map(|(a, _)| a)995 .collect()996 }997998 /// Is `user` allowed to mint token in `collection`.999 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1000 <Allowlist<T>>::get((collection, user))1001 }10021003 /// Get statistics of collections.1004 pub fn collection_stats() -> CollectionStats {1005 let created = <CreatedCollectionCount<T>>::get();1006 let destroyed = <DestroyedCollectionCount<T>>::get();1007 CollectionStats {1008 created: created.0,1009 destroyed: destroyed.0,1010 alive: created.0 - destroyed.0,1011 }1012 }10131014 /// Get the effective limits for the collection.1015 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1016 let collection = <CollectionById<T>>::get(collection)?;1017 let limits = collection.limits;1018 let effective_limits = CollectionLimits {1019 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1020 sponsored_data_size: Some(limits.sponsored_data_size()),1021 sponsored_data_rate_limit: Some(1022 limits1023 .sponsored_data_rate_limit1024 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),1025 ),1026 token_limit: Some(limits.token_limit()),1027 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1028 match collection.mode {1029 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1030 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1031 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1032 },1033 )),1034 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1035 owner_can_transfer: Some(limits.owner_can_transfer()),1036 owner_can_destroy: Some(limits.owner_can_destroy()),1037 transfers_enabled: Some(limits.transfers_enabled()),1038 };10391040 Some(effective_limits)1041 }10421043 /// Returns information about the `collection` adapted for rpc.1044 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1045 let Collection {1046 name,1047 description,1048 owner,1049 mode,1050 token_prefix,1051 sponsorship,1052 limits,1053 permissions,1054 flags,1055 } = <CollectionById<T>>::get(collection)?;10561057 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1058 .into_iter()1059 .map(|(key, permission)| PropertyKeyPermission { key, permission })1060 .collect();10611062 let properties = <CollectionProperties<T>>::get(collection)1063 .into_iter()1064 .map(|(key, value)| Property { key, value })1065 .collect();10661067 let permissions = CollectionPermissions {1068 access: Some(permissions.access()),1069 mint_mode: Some(permissions.mint_mode()),1070 nesting: Some(permissions.nesting().clone()),1071 };10721073 Some(RpcCollection {1074 name: name.into_inner(),1075 description: description.into_inner(),1076 owner,1077 mode,1078 token_prefix: token_prefix.into_inner(),1079 sponsorship,1080 limits,1081 permissions,1082 token_property_permissions,1083 properties,1084 read_only: flags.external,10851086 flags: RpcCollectionFlags {1087 foreign: flags.foreign,1088 erc721metadata: flags.erc721metadata,1089 },1090 })1091 }1092}10931094macro_rules! limit_default {1095 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1096 $(1097 if let Some($new) = $new.$field {1098 let $old = $old.$field($($arg)?);1099 let _ = $new;1100 let _ = $old;1101 $check1102 } else {1103 $new.$field = $old.$field1104 }1105 )*1106 }};1107}1108macro_rules! limit_default_clone {1109 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1110 $(1111 if let Some($new) = $new.$field.clone() {1112 let $old = $old.$field($($arg)?);1113 let _ = $new;1114 let _ = $old;1115 $check1116 } else {1117 $new.$field = $old.$field.clone()1118 }1119 )*1120 }};1121}11221123impl<T: Config> Pallet<T> {1124 /// Create new collection.1125 ///1126 /// * `owner` - The owner of the collection.1127 /// * `data` - Description of the created collection.1128 /// * `flags` - Extra flags to store.1129 pub fn init_collection(1130 owner: T::CrossAccountId,1131 payer: T::CrossAccountId,1132 data: CreateCollectionData<T::CrossAccountId>,1133 ) -> Result<CollectionId, DispatchError> {1134 ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1135 Self::init_collection_internal(owner, payer, data)1136 }11371138 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.1139 pub fn init_foreign_collection(1140 owner: T::CrossAccountId,1141 payer: T::CrossAccountId,1142 mut data: CreateCollectionData<T::CrossAccountId>,1143 ) -> Result<CollectionId, DispatchError> {1144 data.flags.foreign = true;1145 let id = Self::init_collection_internal(owner, payer, data)?;1146 Ok(id)1147 }11481149 fn init_collection_internal(1150 owner: T::CrossAccountId,1151 payer: T::CrossAccountId,1152 data: CreateCollectionData<T::CrossAccountId>,1153 ) -> Result<CollectionId, DispatchError> {1154 {1155 ensure!(1156 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1157 Error::<T>::CollectionTokenPrefixLimitExceeded1158 );1159 }11601161 let created_count = <CreatedCollectionCount<T>>::get()1162 .01163 .checked_add(1)1164 .ok_or(ArithmeticError::Overflow)?;1165 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1166 let id = CollectionId(created_count);11671168 // bound Total number of collections1169 ensure!(1170 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1171 <Error<T>>::TotalCollectionsLimitExceeded1172 );11731174 // =========11751176 let collection = Collection {1177 owner: owner.as_sub().clone(),1178 name: data.name,1179 mode: data.mode.clone(),1180 description: data.description,1181 token_prefix: data.token_prefix,1182 sponsorship: data1183 .pending_sponsor1184 .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1185 .unwrap_or_default(),1186 limits: data1187 .limits1188 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1189 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1190 permissions: data1191 .permissions1192 .map(|permissions| {1193 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1194 })1195 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1196 flags: data.flags,1197 };11981199 let mut collection_properties = CollectionPropertiesT::new();1200 collection_properties1201 .try_set_from_iter(data.properties.into_iter())1202 .map_err(<Error<T>>::from)?;12031204 CollectionProperties::<T>::insert(id, collection_properties);12051206 let mut token_props_permissions = PropertiesPermissionMap::new();1207 token_props_permissions1208 .try_set_from_iter(data.token_property_permissions.into_iter())1209 .map_err(<Error<T>>::from)?;12101211 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12121213 let mut admin_amount = 0u32;1214 for admin in data.admin_list.iter() {1215 if !<IsAdmin<T>>::get((id, admin)) {1216 <IsAdmin<T>>::insert((id, admin), true);1217 admin_amount = admin_amount1218 .checked_add(1)1219 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1220 }1221 }1222 ensure!(1223 admin_amount <= Self::collection_admins_limit(),1224 <Error<T>>::CollectionAdminCountExceeded,1225 );1226 <AdminAmount<T>>::insert(id, admin_amount);12271228 // Take a (non-refundable) deposit of collection creation1229 {1230 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1231 imbalance.subsume(<T as Config>::Currency::deposit(1232 &T::TreasuryAccountId::get(),1233 T::CollectionCreationPrice::get(),1234 Precision::Exact,1235 )?);1236 let credit =1237 <T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1238 .map_err(|_| Error::<T>::NotSufficientFounds)?;12391240 debug_assert!(credit.peek().is_zero())1241 }12421243 <CreatedCollectionCount<T>>::put(created_count);1244 <Pallet<T>>::deposit_event(Event::CollectionCreated(1245 id,1246 data.mode.id(),1247 owner.as_sub().clone(),1248 ));1249 <PalletEvm<T>>::deposit_log(1250 erc::CollectionHelpersEvents::CollectionCreated {1251 owner: *owner.as_eth(),1252 collection_id: eth::collection_id_to_address(id),1253 }1254 .to_log(T::ContractAddress::get()),1255 );1256 <CollectionById<T>>::insert(id, collection);1257 Ok(id)1258 }12591260 /// Destroy collection.1261 ///1262 /// * `collection` - Collection handler.1263 /// * `sender` - The owner or administrator of the collection.1264 pub fn destroy_collection(1265 collection: CollectionHandle<T>,1266 sender: &T::CrossAccountId,1267 ) -> DispatchResult {1268 ensure!(1269 collection.limits.owner_can_destroy(),1270 <Error<T>>::NoPermission,1271 );1272 collection.check_is_owner(sender)?;12731274 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1275 .01276 .checked_add(1)1277 .ok_or(ArithmeticError::Overflow)?;12781279 // =========12801281 <DestroyedCollectionCount<T>>::put(destroyed_collections);1282 <CollectionById<T>>::remove(collection.id);1283 <AdminAmount<T>>::remove(collection.id);1284 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1285 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1286 <CollectionProperties<T>>::remove(collection.id);12871288 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12891290 <PalletEvm<T>>::deposit_log(1291 erc::CollectionHelpersEvents::CollectionDestroyed {1292 collection_id: eth::collection_id_to_address(collection.id),1293 }1294 .to_log(T::ContractAddress::get()),1295 );1296 Ok(())1297 }12981299 /// This function sets or removes a collection properties according to1300 /// `properties_updates` contents:1301 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1302 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1303 ///1304 /// This function fires an event for each property change.1305 /// In case of an error, all the changes (including the events) will be reverted1306 /// since the function is transactional.1307 #[transactional]1308 fn modify_collection_properties(1309 collection: &CollectionHandle<T>,1310 sender: &T::CrossAccountId,1311 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1312 ) -> DispatchResult {1313 collection.check_is_owner_or_admin(sender)?;13141315 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13161317 for (key, value) in properties_updates {1318 match value {1319 Some(value) => {1320 stored_properties1321 .try_set(key.clone(), value)1322 .map_err(<Error<T>>::from)?;13231324 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1325 <PalletEvm<T>>::deposit_log(1326 erc::CollectionHelpersEvents::CollectionChanged {1327 collection_id: eth::collection_id_to_address(collection.id),1328 }1329 .to_log(T::ContractAddress::get()),1330 );1331 }1332 None => {1333 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13341335 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1336 <PalletEvm<T>>::deposit_log(1337 erc::CollectionHelpersEvents::CollectionChanged {1338 collection_id: eth::collection_id_to_address(collection.id),1339 }1340 .to_log(T::ContractAddress::get()),1341 );1342 }1343 }1344 }13451346 <CollectionProperties<T>>::set(collection.id, stored_properties);13471348 Ok(())1349 }13501351 /// Sets or unsets the approval of a given operator.1352 ///1353 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1354 /// - `owner`: Token owner1355 /// - `operator`: Operator1356 /// - `approve`: Should operator status be granted or revoked?1357 pub fn set_allowance_for_all(1358 collection: &CollectionHandle<T>,1359 owner: &T::CrossAccountId,1360 operator: &T::CrossAccountId,1361 approve: bool,1362 set_allowance: impl FnOnce(),1363 log: evm_coder::ethereum::Log,1364 ) -> DispatchResult {1365 if collection.permissions.access() == AccessMode::AllowList {1366 collection.check_allowlist(owner)?;1367 collection.check_allowlist(operator)?;1368 }13691370 Self::ensure_correct_receiver(operator)?;13711372 set_allowance();13731374 <PalletEvm<T>>::deposit_log(log);1375 Self::deposit_event(Event::ApprovedForAll(1376 collection.id,1377 owner.clone(),1378 operator.clone(),1379 approve,1380 ));1381 Ok(())1382 }13831384 /// Set collection property.1385 ///1386 /// * `collection` - Collection handler.1387 /// * `sender` - The owner or administrator of the collection.1388 /// * `property` - The property to set.1389 pub fn set_collection_property(1390 collection: &CollectionHandle<T>,1391 sender: &T::CrossAccountId,1392 property: Property,1393 ) -> DispatchResult {1394 Self::set_collection_properties(collection, sender, [property].into_iter())1395 }13961397 /// Set a scoped collection property, where the scope is a special prefix1398 /// prohibiting a user access to change the property directly.1399 ///1400 /// * `collection_id` - ID of the collection for which the property is being set.1401 /// * `scope` - Property scope.1402 /// * `property` - The property to set.1403 pub fn set_scoped_collection_property(1404 collection_id: CollectionId,1405 scope: PropertyScope,1406 property: Property,1407 ) -> DispatchResult {1408 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1409 properties.try_scoped_set(scope, property.key, property.value)1410 })1411 .map_err(<Error<T>>::from)?;14121413 Ok(())1414 }14151416 /// Set scoped collection properties, where the scope is a special prefix1417 /// prohibiting a user access to change the properties directly.1418 ///1419 /// * `collection_id` - ID of the collection for which the properties is being set.1420 /// * `scope` - Property scope.1421 /// * `properties` - The properties to set.1422 pub fn set_scoped_collection_properties(1423 collection_id: CollectionId,1424 scope: PropertyScope,1425 properties: impl Iterator<Item = Property>,1426 ) -> DispatchResult {1427 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1428 stored_properties.try_scoped_set_from_iter(scope, properties)1429 })1430 .map_err(<Error<T>>::from)?;14311432 Ok(())1433 }14341435 /// Set collection properties.1436 ///1437 /// * `collection` - Collection handler.1438 /// * `sender` - The owner or administrator of the collection.1439 /// * `properties` - The properties to set.1440 pub fn set_collection_properties(1441 collection: &CollectionHandle<T>,1442 sender: &T::CrossAccountId,1443 properties: impl Iterator<Item = Property>,1444 ) -> DispatchResult {1445 Self::modify_collection_properties(1446 collection,1447 sender,1448 properties.map(|property| (property.key, Some(property.value))),1449 )1450 }14511452 /// Delete collection property.1453 ///1454 /// * `collection` - Collection handler.1455 /// * `sender` - The owner or administrator of the collection.1456 /// * `property` - The property to delete.1457 pub fn delete_collection_property(1458 collection: &CollectionHandle<T>,1459 sender: &T::CrossAccountId,1460 property_key: PropertyKey,1461 ) -> DispatchResult {1462 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1463 }14641465 /// Delete collection properties.1466 ///1467 /// * `collection` - Collection handler.1468 /// * `sender` - The owner or administrator of the collection.1469 /// * `properties` - The properties to delete.1470 pub fn delete_collection_properties(1471 collection: &CollectionHandle<T>,1472 sender: &T::CrossAccountId,1473 property_keys: impl Iterator<Item = PropertyKey>,1474 ) -> DispatchResult {1475 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1476 }14771478 /// Set collection propetry permission without any checks.1479 ///1480 /// Used for migrations.1481 ///1482 /// * `collection` - Collection handler.1483 /// * `property_permissions` - Property permissions.1484 pub fn set_property_permission_unchecked(1485 collection: CollectionId,1486 property_permission: PropertyKeyPermission,1487 ) -> DispatchResult {1488 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1489 permissions.try_set(property_permission.key, property_permission.permission)1490 })1491 .map_err(<Error<T>>::from)?;1492 Ok(())1493 }14941495 /// Set collection property permission.1496 ///1497 /// * `collection` - Collection handler.1498 /// * `sender` - The owner or administrator of the collection.1499 /// * `property_permission` - Property permission.1500 pub fn set_property_permission(1501 collection: &CollectionHandle<T>,1502 sender: &T::CrossAccountId,1503 property_permission: PropertyKeyPermission,1504 ) -> DispatchResult {1505 Self::set_scoped_property_permission(1506 collection,1507 sender,1508 PropertyScope::None,1509 property_permission,1510 )1511 }15121513 /// Set collection property permission with scope.1514 ///1515 /// * `collection` - Collection handler.1516 /// * `sender` - The owner or administrator of the collection.1517 /// * `scope` - Property scope.1518 /// * `property_permission` - Property permission.1519 pub fn set_scoped_property_permission(1520 collection: &CollectionHandle<T>,1521 sender: &T::CrossAccountId,1522 scope: PropertyScope,1523 property_permission: PropertyKeyPermission,1524 ) -> DispatchResult {1525 collection.check_is_owner_or_admin(sender)?;15261527 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1528 let current_permission = all_permissions.get(&property_permission.key);1529 if matches![1530 current_permission,1531 Some(PropertyPermission { mutable: false, .. })1532 ] {1533 return Err(<Error<T>>::NoPermission.into());1534 }15351536 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1537 let property_permission = property_permission.clone();1538 permissions.try_scoped_set(1539 scope,1540 property_permission.key,1541 property_permission.permission,1542 )1543 })1544 .map_err(<Error<T>>::from)?;15451546 Self::deposit_event(Event::PropertyPermissionSet(1547 collection.id,1548 property_permission.key,1549 ));1550 <PalletEvm<T>>::deposit_log(1551 erc::CollectionHelpersEvents::CollectionChanged {1552 collection_id: eth::collection_id_to_address(collection.id),1553 }1554 .to_log(T::ContractAddress::get()),1555 );15561557 Ok(())1558 }15591560 /// Set token property permission.1561 ///1562 /// * `collection` - Collection handler.1563 /// * `sender` - The owner or administrator of the collection.1564 /// * `property_permissions` - Property permissions.1565 #[transactional]1566 pub fn set_token_property_permissions(1567 collection: &CollectionHandle<T>,1568 sender: &T::CrossAccountId,1569 property_permissions: Vec<PropertyKeyPermission>,1570 ) -> DispatchResult {1571 Self::set_scoped_token_property_permissions(1572 collection,1573 sender,1574 PropertyScope::None,1575 property_permissions,1576 )1577 }15781579 /// Set token property permission with scope.1580 ///1581 /// * `collection` - Collection handler.1582 /// * `sender` - The owner or administrator of the collection.1583 /// * `scope` - Property scope.1584 /// * `property_permissions` - Property permissions.1585 #[transactional]1586 pub fn set_scoped_token_property_permissions(1587 collection: &CollectionHandle<T>,1588 sender: &T::CrossAccountId,1589 scope: PropertyScope,1590 property_permissions: Vec<PropertyKeyPermission>,1591 ) -> DispatchResult {1592 for prop_pemission in property_permissions {1593 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1594 }15951596 Ok(())1597 }15981599 /// Get collection property.1600 pub fn get_collection_property(1601 collection_id: CollectionId,1602 key: &PropertyKey,1603 ) -> Option<PropertyValue> {1604 Self::collection_properties(collection_id).get(key).cloned()1605 }16061607 /// Convert byte vector to property key vector.1608 pub fn bytes_keys_to_property_keys(1609 keys: Vec<Vec<u8>>,1610 ) -> Result<Vec<PropertyKey>, DispatchError> {1611 keys.into_iter()1612 .map(|key| -> Result<PropertyKey, DispatchError> {1613 key.try_into()1614 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1615 })1616 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1617 }16181619 /// Get properties according to given keys.1620 pub fn filter_collection_properties(1621 collection_id: CollectionId,1622 keys: Option<Vec<PropertyKey>>,1623 ) -> Result<Vec<Property>, DispatchError> {1624 let properties = Self::collection_properties(collection_id);16251626 let properties = keys1627 .map(|keys| {1628 keys.into_iter()1629 .filter_map(|key| {1630 properties.get(&key).map(|value| Property {1631 key,1632 value: value.clone(),1633 })1634 })1635 .collect()1636 })1637 .unwrap_or_else(|| {1638 properties1639 .into_iter()1640 .map(|(key, value)| Property { key, value })1641 .collect()1642 });16431644 Ok(properties)1645 }16461647 /// Get property permissions according to given keys.1648 pub fn filter_property_permissions(1649 collection_id: CollectionId,1650 keys: Option<Vec<PropertyKey>>,1651 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1652 let permissions = Self::property_permissions(collection_id);16531654 let key_permissions = keys1655 .map(|keys| {1656 keys.into_iter()1657 .filter_map(|key| {1658 permissions1659 .get(&key)1660 .map(|permission| PropertyKeyPermission {1661 key,1662 permission: permission.clone(),1663 })1664 })1665 .collect()1666 })1667 .unwrap_or_else(|| {1668 permissions1669 .into_iter()1670 .map(|(key, permission)| PropertyKeyPermission { key, permission })1671 .collect()1672 });16731674 Ok(key_permissions)1675 }16761677 /// Toggle `user` participation in the `collection`'s allow list.1678 /// #### Store read/writes1679 /// 1 writes1680 pub fn toggle_allowlist(1681 collection: &CollectionHandle<T>,1682 sender: &T::CrossAccountId,1683 user: &T::CrossAccountId,1684 allowed: bool,1685 ) -> DispatchResult {1686 collection.check_is_owner_or_admin(sender)?;16871688 // =========16891690 if allowed {1691 <Allowlist<T>>::insert((collection.id, user), true);1692 Self::deposit_event(Event::<T>::AllowListAddressAdded(1693 collection.id,1694 user.clone(),1695 ));1696 } else {1697 <Allowlist<T>>::remove((collection.id, user));1698 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1699 collection.id,1700 user.clone(),1701 ));1702 }17031704 <PalletEvm<T>>::deposit_log(1705 erc::CollectionHelpersEvents::CollectionChanged {1706 collection_id: eth::collection_id_to_address(collection.id),1707 }1708 .to_log(T::ContractAddress::get()),1709 );17101711 Ok(())1712 }17131714 /// Toggle `user` participation in the `collection`'s admin list.1715 /// #### Store read/writes1716 /// 2 reads, 2 writes1717 pub fn toggle_admin(1718 collection: &CollectionHandle<T>,1719 sender: &T::CrossAccountId,1720 user: &T::CrossAccountId,1721 admin: bool,1722 ) -> DispatchResult {1723 collection.check_is_internal()?;1724 collection.check_is_owner(sender)?;17251726 let is_admin = <IsAdmin<T>>::get((collection.id, user));1727 if is_admin == admin {1728 if admin {1729 return Ok(());1730 } else {1731 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1732 }1733 }1734 let amount = <AdminAmount<T>>::get(collection.id);17351736 // =========17371738 if admin {1739 let amount = amount1740 .checked_add(1)1741 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1742 ensure!(1743 amount <= Self::collection_admins_limit(),1744 <Error<T>>::CollectionAdminCountExceeded,1745 );17461747 <AdminAmount<T>>::insert(collection.id, amount);1748 <IsAdmin<T>>::insert((collection.id, user), true);17491750 Self::deposit_event(Event::<T>::CollectionAdminAdded(1751 collection.id,1752 user.clone(),1753 ));1754 } else {1755 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1756 <IsAdmin<T>>::remove((collection.id, user));17571758 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1759 collection.id,1760 user.clone(),1761 ));1762 }17631764 <PalletEvm<T>>::deposit_log(1765 erc::CollectionHelpersEvents::CollectionChanged {1766 collection_id: eth::collection_id_to_address(collection.id),1767 }1768 .to_log(T::ContractAddress::get()),1769 );17701771 Ok(())1772 }17731774 /// Update collection limits.1775 pub fn update_limits(1776 user: &T::CrossAccountId,1777 collection: &mut CollectionHandle<T>,1778 new_limit: CollectionLimits,1779 ) -> DispatchResult {1780 collection.check_is_internal()?;1781 collection.check_is_owner_or_admin(user)?;17821783 collection.limits =1784 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17851786 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1787 <PalletEvm<T>>::deposit_log(1788 erc::CollectionHelpersEvents::CollectionChanged {1789 collection_id: eth::collection_id_to_address(collection.id),1790 }1791 .to_log(T::ContractAddress::get()),1792 );17931794 collection.save()1795 }17961797 /// Merge set fields from `new_limit` to `old_limit`.1798 fn clamp_limits(1799 mode: CollectionMode,1800 old_limit: &CollectionLimits,1801 mut new_limit: CollectionLimits,1802 ) -> Result<CollectionLimits, DispatchError> {1803 let limits = old_limit;1804 limit_default!(old_limit, new_limit,1805 account_token_ownership_limit => ensure!(1806 new_limit <= MAX_TOKEN_OWNERSHIP,1807 <Error<T>>::CollectionLimitBoundsExceeded,1808 ),1809 sponsored_data_size => ensure!(1810 new_limit <= CUSTOM_DATA_LIMIT,1811 <Error<T>>::CollectionLimitBoundsExceeded,1812 ),18131814 sponsored_data_rate_limit => {},1815 token_limit => ensure!(1816 old_limit >= new_limit && new_limit > 0,1817 <Error<T>>::CollectionTokenLimitExceeded1818 ),18191820 sponsor_transfer_timeout(match mode {1821 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1822 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1823 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1824 }) => ensure!(1825 new_limit <= MAX_SPONSOR_TIMEOUT,1826 <Error<T>>::CollectionLimitBoundsExceeded,1827 ),1828 sponsor_approve_timeout => {},1829 owner_can_transfer => ensure!(1830 !limits.owner_can_transfer_instaled() ||1831 old_limit || !new_limit,1832 <Error<T>>::OwnerPermissionsCantBeReverted,1833 ),1834 owner_can_destroy => ensure!(1835 old_limit || !new_limit,1836 <Error<T>>::OwnerPermissionsCantBeReverted,1837 ),1838 transfers_enabled => {},1839 );1840 Ok(new_limit)1841 }18421843 /// Update collection permissions.1844 pub fn update_permissions(1845 user: &T::CrossAccountId,1846 collection: &mut CollectionHandle<T>,1847 new_permission: CollectionPermissions,1848 ) -> DispatchResult {1849 collection.check_is_internal()?;1850 collection.check_is_owner_or_admin(user)?;1851 collection.permissions = Self::clamp_permissions(1852 collection.mode.clone(),1853 &collection.permissions,1854 new_permission,1855 )?;18561857 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1858 <PalletEvm<T>>::deposit_log(1859 erc::CollectionHelpersEvents::CollectionChanged {1860 collection_id: eth::collection_id_to_address(collection.id),1861 }1862 .to_log(T::ContractAddress::get()),1863 );18641865 collection.save()1866 }18671868 /// Merge set fields from `new_permission` to `old_permission`.1869 fn clamp_permissions(1870 _mode: CollectionMode,1871 old_permission: &CollectionPermissions,1872 mut new_permission: CollectionPermissions,1873 ) -> Result<CollectionPermissions, DispatchError> {1874 limit_default_clone!(old_permission, new_permission,1875 access => {},1876 mint_mode => {},1877 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1878 );1879 Ok(new_permission)1880 }18811882 /// Repair possibly broken properties of a collection.1883 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1884 CollectionProperties::<T>::mutate(collection_id, |properties| {1885 properties.recompute_consumed_space();1886 });18871888 Ok(())1889 }1890}18911892/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1893#[macro_export]1894macro_rules! unsupported {1895 ($runtime:path) => {1896 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1897 };1898}18991900/// Return weights for various worst-case operations.1901pub trait CommonWeightInfo<CrossAccountId> {1902 /// Weight of item creation.1903 fn create_item(data: &CreateItemData) -> Weight {1904 Self::create_multiple_items(from_ref(data))1905 }19061907 /// Weight of items creation.1908 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19091910 /// Weight of items creation.1911 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19121913 /// The weight of the burning item.1914 fn burn_item() -> Weight;19151916 /// Property setting weight.1917 ///1918 /// * `amount`- The number of properties to set.1919 fn set_collection_properties(amount: u32) -> Weight;19201921 /// Collection property deletion weight.1922 ///1923 /// * `amount`- The number of properties to set.1924 fn delete_collection_properties(amount: u32) -> Weight {1925 Self::set_collection_properties(amount)1926 }19271928 /// Token property setting weight.1929 ///1930 /// * `amount`- The number of properties to set.1931 fn set_token_properties(amount: u32) -> Weight;19321933 /// Token property deletion weight.1934 ///1935 /// * `amount`- The number of properties to delete.1936 fn delete_token_properties(amount: u32) -> Weight {1937 Self::set_token_properties(amount)1938 }19391940 /// Token property permissions set weight.1941 ///1942 /// * `amount`- The number of property permissions to set.1943 fn set_token_property_permissions(amount: u32) -> Weight;19441945 /// Transfer price of the token or its parts.1946 fn transfer() -> Weight;19471948 /// The price of setting the permission of the operation from another user.1949 fn approve() -> Weight;19501951 /// The price of setting the permission of the operation from another user for eth mirror.1952 fn approve_from() -> Weight;19531954 /// Transfer price from another user.1955 fn transfer_from() -> Weight;19561957 /// The price of burning a token from another user.1958 fn burn_from() -> Weight;19591960 /// The price of setting approval for all1961 fn set_allowance_for_all() -> Weight;19621963 /// The price of repairing an item.1964 fn force_repair_item() -> Weight;1965}19661967/// Weight info extension trait for refungible pallet.1968pub trait RefungibleExtensionsWeightInfo {1969 /// Weight of token repartition.1970 fn repartition() -> Weight;1971}19721973/// Common collection operations.1974///1975/// It wraps methods in Fungible, Nonfungible and Refungible pallets1976/// and adds weight info.1977pub trait CommonCollectionOperations<T: Config> {1978 /// Create token.1979 ///1980 /// * `sender` - The user who mint the token and pays for the transaction.1981 /// * `to` - The user who will own the token.1982 /// * `data` - Token data.1983 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1984 fn create_item(1985 &self,1986 sender: T::CrossAccountId,1987 to: T::CrossAccountId,1988 data: CreateItemData,1989 nesting_budget: &dyn Budget,1990 ) -> DispatchResultWithPostInfo;19911992 /// Create multiple tokens.1993 ///1994 /// * `sender` - The user who mint the token and pays for the transaction.1995 /// * `to` - The user who will own the token.1996 /// * `data` - Token data.1997 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1998 fn create_multiple_items(1999 &self,2000 sender: T::CrossAccountId,2001 to: T::CrossAccountId,2002 data: Vec<CreateItemData>,2003 nesting_budget: &dyn Budget,2004 ) -> DispatchResultWithPostInfo;20052006 /// Create multiple tokens.2007 ///2008 /// * `sender` - The user who mint the token and pays for the transaction.2009 /// * `to` - The user who will own the token.2010 /// * `data` - Token data.2011 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2012 fn create_multiple_items_ex(2013 &self,2014 sender: T::CrossAccountId,2015 data: CreateItemExData<T::CrossAccountId>,2016 nesting_budget: &dyn Budget,2017 ) -> DispatchResultWithPostInfo;20182019 /// Burn token.2020 ///2021 /// * `sender` - The user who owns the token.2022 /// * `token` - Token id that will burned.2023 /// * `amount` - The number of parts of the token that will be burned.2024 fn burn_item(2025 &self,2026 sender: T::CrossAccountId,2027 token: TokenId,2028 amount: u128,2029 ) -> DispatchResultWithPostInfo;20302031 /// Set collection properties.2032 ///2033 /// * `sender` - Must be either the owner of the collection or its admin.2034 /// * `properties` - Properties to be set.2035 fn set_collection_properties(2036 &self,2037 sender: T::CrossAccountId,2038 properties: Vec<Property>,2039 ) -> DispatchResultWithPostInfo;20402041 /// Delete collection properties.2042 ///2043 /// * `sender` - Must be either the owner of the collection or its admin.2044 /// * `properties` - The properties to be removed.2045 fn delete_collection_properties(2046 &self,2047 sender: &T::CrossAccountId,2048 property_keys: Vec<PropertyKey>,2049 ) -> DispatchResultWithPostInfo;20502051 /// Set token properties.2052 ///2053 /// The appropriate [`PropertyPermission`] for the token property2054 /// must be set with [`Self::set_token_property_permissions`].2055 ///2056 /// * `sender` - Must be either the owner of the token or its admin.2057 /// * `token_id` - The token for which the properties are being set.2058 /// * `properties` - Properties to be set.2059 /// * `budget` - Budget for setting properties.2060 fn set_token_properties(2061 &self,2062 sender: T::CrossAccountId,2063 token_id: TokenId,2064 properties: Vec<Property>,2065 budget: &dyn Budget,2066 ) -> DispatchResultWithPostInfo;20672068 /// Remove token properties.2069 ///2070 /// The appropriate [`PropertyPermission`] for the token property2071 /// must be set with [`Self::set_token_property_permissions`].2072 ///2073 /// * `sender` - Must be either the owner of the token or its admin.2074 /// * `token_id` - The token for which the properties are being remove.2075 /// * `property_keys` - Keys to remove corresponding properties.2076 /// * `budget` - Budget for removing properties.2077 fn delete_token_properties(2078 &self,2079 sender: T::CrossAccountId,2080 token_id: TokenId,2081 property_keys: Vec<PropertyKey>,2082 budget: &dyn Budget,2083 ) -> DispatchResultWithPostInfo;20842085 /// Get token properties raw map.2086 ///2087 /// * `token_id` - The token which properties are needed.2088 fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20892090 /// Set token properties raw map.2091 ///2092 /// * `token_id` - The token for which the properties are being set.2093 /// * `map` - The raw map containing the token's properties.2094 fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20952096 /// Set token property permissions.2097 ///2098 /// * `sender` - Must be either the owner of the token or its admin.2099 /// * `token_id` - The token for which the properties are being set.2100 /// * `property_permissions` - Property permissions to be set.2101 /// * `budget` - Budget for setting properties.2102 fn set_token_property_permissions(2103 &self,2104 sender: &T::CrossAccountId,2105 property_permissions: Vec<PropertyKeyPermission>,2106 ) -> DispatchResultWithPostInfo;21072108 /// Transfer amount of token pieces.2109 ///2110 /// * `sender` - Donor user.2111 /// * `to` - Recepient user.2112 /// * `token` - The token of which parts are being sent.2113 /// * `amount` - The number of parts of the token that will be transferred.2114 /// * `budget` - The maximum budget that can be spent on the transfer.2115 fn transfer(2116 &self,2117 sender: T::CrossAccountId,2118 to: T::CrossAccountId,2119 token: TokenId,2120 amount: u128,2121 budget: &dyn Budget,2122 ) -> DispatchResultWithPostInfo;21232124 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2125 ///2126 /// * `sender` - The user who grants access to the token.2127 /// * `spender` - The user to whom the rights are granted.2128 /// * `token` - The token to which access is granted.2129 /// * `amount` - The amount of pieces that another user can dispose of.2130 fn approve(2131 &self,2132 sender: T::CrossAccountId,2133 spender: T::CrossAccountId,2134 token: TokenId,2135 amount: u128,2136 ) -> DispatchResultWithPostInfo;21372138 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2139 ///2140 /// * `sender` - The user who grants access to the token.2141 /// * `from` - Spender's eth mirror.2142 /// * `to` - The user to whom the rights are granted.2143 /// * `token` - The token to which access is granted.2144 /// * `amount` - The amount of pieces that another user can dispose of.2145 fn approve_from(2146 &self,2147 sender: T::CrossAccountId,2148 from: T::CrossAccountId,2149 to: T::CrossAccountId,2150 token: TokenId,2151 amount: u128,2152 ) -> DispatchResultWithPostInfo;21532154 /// Send parts of a token owned by another user.2155 ///2156 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2157 ///2158 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2159 /// * `from` - The user who owns the token.2160 /// * `to` - Recepient user.2161 /// * `token` - The token of which parts are being sent.2162 /// * `amount` - The number of parts of the token that will be transferred.2163 /// * `budget` - The maximum budget that can be spent on the transfer.2164 fn transfer_from(2165 &self,2166 sender: T::CrossAccountId,2167 from: T::CrossAccountId,2168 to: T::CrossAccountId,2169 token: TokenId,2170 amount: u128,2171 budget: &dyn Budget,2172 ) -> DispatchResultWithPostInfo;21732174 /// Burn parts of a token owned by another user.2175 ///2176 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2177 ///2178 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2179 /// * `from` - The user who owns the token.2180 /// * `token` - The token of which parts are being sent.2181 /// * `amount` - The number of parts of the token that will be transferred.2182 /// * `budget` - The maximum budget that can be spent on the burn.2183 fn burn_from(2184 &self,2185 sender: T::CrossAccountId,2186 from: T::CrossAccountId,2187 token: TokenId,2188 amount: u128,2189 budget: &dyn Budget,2190 ) -> DispatchResultWithPostInfo;21912192 /// Check permission to nest token.2193 ///2194 /// * `sender` - The user who initiated the check.2195 /// * `from` - The token that is checked for embedding.2196 /// * `under` - Token under which to check.2197 /// * `budget` - The maximum budget that can be spent on the check.2198 fn check_nesting(2199 &self,2200 sender: &T::CrossAccountId,2201 from: (CollectionId, TokenId),2202 under: TokenId,2203 budget: &dyn Budget,2204 ) -> DispatchResult;22052206 /// Nest one token into another.2207 ///2208 /// * `under` - Token holder.2209 /// * `to_nest` - Nested token.2210 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22112212 /// Unnest token.2213 ///2214 /// * `under` - Token holder.2215 /// * `to_nest` - Token to unnest.2216 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22172218 /// Get all user tokens.2219 ///2220 /// * `account` - Account for which you need to get tokens.2221 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22222223 /// Get all the tokens in the collection.2224 fn collection_tokens(&self) -> Vec<TokenId>;22252226 /// Check if the token exists.2227 ///2228 /// * `token` - Id token to check.2229 fn token_exists(&self, token: TokenId) -> bool;22302231 /// Get the id of the last minted token.2232 fn last_token_id(&self) -> TokenId;22332234 /// Get the owner of the token.2235 ///2236 /// * `token` - The token for which you need to find out the owner.2237 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22382239 /// Checks if the `maybe_owner` is the indirect owner of the `token`.2240 ///2241 /// * `token` - Id token to check.2242 /// * `maybe_owner` - The account to check.2243 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2244 fn check_token_indirect_owner(2245 &self,2246 token: TokenId,2247 maybe_owner: &T::CrossAccountId,2248 nesting_budget: &dyn Budget,2249 ) -> Result<bool, DispatchError>;22502251 /// Returns 10 tokens owners in no particular order.2252 ///2253 /// * `token` - The token for which you need to find out the owners.2254 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22552256 /// Get the value of the token property by key.2257 ///2258 /// * `token` - Token with the property to get.2259 /// * `key` - Property name.2260 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22612262 /// Get a set of token properties by key vector.2263 ///2264 /// * `token` - Token with the property to get.2265 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2266 /// then all properties are returned.2267 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22682269 /// Amount of unique collection tokens2270 fn total_supply(&self) -> u32;22712272 /// Amount of different tokens account has.2273 ///2274 /// * `account` - The account for which need to get the balance.2275 fn account_balance(&self, account: T::CrossAccountId) -> u32;22762277 /// Amount of specific token account have.2278 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22792280 /// Amount of token pieces2281 fn total_pieces(&self, token: TokenId) -> Option<u128>;22822283 /// Get the number of parts of the token that a trusted user can manage.2284 ///2285 /// * `sender` - Trusted user.2286 /// * `spender` - Owner of the token.2287 /// * `token` - The token for which to get the value.2288 fn allowance(2289 &self,2290 sender: T::CrossAccountId,2291 spender: T::CrossAccountId,2292 token: TokenId,2293 ) -> u128;22942295 /// Get extension for RFT collection.2296 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22972298 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2299 /// * `owner` - Token owner2300 /// * `operator` - Operator2301 /// * `approve` - Should operator status be granted or revoked?2302 fn set_allowance_for_all(2303 &self,2304 owner: T::CrossAccountId,2305 operator: T::CrossAccountId,2306 approve: bool,2307 ) -> DispatchResultWithPostInfo;23082309 /// Tells whether the given `owner` approves the `operator`.2310 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23112312 /// Repairs a possibly broken item.2313 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2314}23152316/// Extension for RFT collection.2317pub trait RefungibleExtensions<T>2318where2319 T: Config,2320{2321 /// Change the number of parts of the token.2322 ///2323 /// When the value changes down, this function is equivalent to burning parts of the token.2324 ///2325 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2326 /// * `token` - The token for which you want to change the number of parts.2327 /// * `amount` - The new value of the parts of the token.2328 fn repartition(2329 &self,2330 sender: &T::CrossAccountId,2331 token: TokenId,2332 amount: u128,2333 ) -> DispatchResultWithPostInfo;2334}23352336/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2337///2338/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2339pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2340 let post_info = PostDispatchInfo {2341 actual_weight: Some(weight),2342 pays_fee: Pays::Yes,2343 };2344 match res {2345 Ok(()) => Ok(post_info),2346 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2347 }2348}23492350impl<T: Config> From<PropertiesError> for Error<T> {2351 fn from(error: PropertiesError) -> Self {2352 match error {2353 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2354 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2355 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2356 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2357 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2358 }2359 }2360}23612362/// The type-safe interface for writing properties (setting or deleting) to tokens.2363/// It has two distinct implementations for newly created tokens and existing ones.2364///2365/// This type utilizes the lazy evaluation to avoid repeating the computation2366/// of several performance-heavy or PoV-heavy tasks,2367/// such as checking the indirect ownership or reading the token property permissions.2368pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2369 collection: &'a Handle,2370 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2371 _phantom: PhantomData<(T, WriterVariant)>,2372}23732374impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2375where2376 T: Config,2377 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2378{2379 fn internal_write_token_properties(2380 &mut self,2381 token_id: TokenId,2382 mut token_lazy_info: PropertyWriterLazyTokenInfo,2383 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2384 log: evm_coder::ethereum::Log,2385 ) -> DispatchResult {2386 for (key, value) in properties_updates {2387 let permission = self2388 .collection_lazy_info2389 .property_permissions2390 .value()2391 .get(&key)2392 .cloned()2393 .unwrap_or_else(PropertyPermission::none);23942395 match permission {2396 PropertyPermission { mutable: false, .. }2397 if token_lazy_info2398 .stored_properties2399 .value()2400 .get(&key)2401 .is_some() =>2402 {2403 return Err(<Error<T>>::NoPermission.into());2404 }24052406 PropertyPermission {2407 collection_admin,2408 token_owner,2409 ..2410 } => check_token_permissions::<T>(2411 collection_admin,2412 token_owner,2413 &mut self.collection_lazy_info.is_collection_admin,2414 &mut token_lazy_info.is_token_owner,2415 &mut token_lazy_info.is_token_exist,2416 )?,2417 }24182419 match value {2420 Some(value) => {2421 token_lazy_info2422 .stored_properties2423 .value_mut()2424 .try_set(key.clone(), value)2425 .map_err(<Error<T>>::from)?;24262427 <Pallet<T>>::deposit_event(Event::TokenPropertySet(2428 self.collection.id,2429 token_id,2430 key,2431 ));2432 }2433 None => {2434 token_lazy_info2435 .stored_properties2436 .value_mut()2437 .remove(&key)2438 .map_err(<Error<T>>::from)?;24392440 <Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2441 self.collection.id,2442 token_id,2443 key,2444 ));2445 }2446 }2447 }24482449 let properties_changed = token_lazy_info.stored_properties.has_value();2450 if properties_changed {2451 <PalletEvm<T>>::deposit_log(log);24522453 self.collection2454 .set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2455 }24562457 Ok(())2458 }2459}24602461/// A helper structure for the [`PropertyWriter`] that holds2462/// the collection-related info. The info is loaded using lazy evaluation.2463/// This info is common for any token for which we write properties.2464pub struct PropertyWriterLazyCollectionInfo<'a> {2465 is_collection_admin: LazyValue<'a, bool>,2466 property_permissions: LazyValue<'a, PropertiesPermissionMap>,2467}24682469/// A helper structure for the [`PropertyWriter`] that holds2470/// the token-related info. The info is loaded using lazy evaluation.2471pub struct PropertyWriterLazyTokenInfo<'a> {2472 is_token_exist: LazyValue<'a, bool>,2473 is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2474 stored_properties: LazyValue<'a, TokenProperties>,2475}24762477impl<'a> PropertyWriterLazyTokenInfo<'a> {2478 /// Create a lazy token info.2479 pub fn new(2480 check_token_exist: impl FnOnce() -> bool + 'a,2481 check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2482 get_token_properties: impl FnOnce() -> TokenProperties + 'a,2483 ) -> Self {2484 Self {2485 is_token_exist: LazyValue::new(check_token_exist),2486 is_token_owner: LazyValue::new(check_token_owner),2487 stored_properties: LazyValue::new(get_token_properties),2488 }2489 }2490}24912492/// A marker structure that enables the writer implementation2493/// to provide the interface to write properties to **newly created** tokens.2494pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2495impl<T: Config> NewTokenPropertyWriter<T> {2496 /// Creates a [`PropertyWriter`] for **newly created** tokens.2497 pub fn new<'a, Handle>(2498 collection: &'a Handle,2499 sender: &'a T::CrossAccountId,2500 ) -> PropertyWriter<'a, Self, T, Handle>2501 where2502 T: Config,2503 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2504 {2505 PropertyWriter {2506 collection,2507 collection_lazy_info: PropertyWriterLazyCollectionInfo {2508 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2509 property_permissions: LazyValue::new(|| {2510 <Pallet<T>>::property_permissions(collection.id)2511 }),2512 },2513 _phantom: PhantomData,2514 }2515 }2516}25172518impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2519where2520 T: Config,2521 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2522{2523 /// A function to write properties to a **newly created** token.2524 pub fn write_token_properties(2525 &mut self,2526 mint_target_is_sender: bool,2527 token_id: TokenId,2528 properties_updates: impl Iterator<Item = Property>,2529 log: evm_coder::ethereum::Log,2530 ) -> DispatchResult {2531 let check_token_exist = || {2532 debug_assert!(self.collection.token_exists(token_id));2533 true2534 };25352536 let check_token_owner = || Ok(mint_target_is_sender);25372538 let get_token_properties = || {2539 debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2540 TokenProperties::new()2541 };25422543 self.internal_write_token_properties(2544 token_id,2545 PropertyWriterLazyTokenInfo::new(2546 check_token_exist,2547 check_token_owner,2548 get_token_properties,2549 ),2550 properties_updates.map(|p| (p.key, Some(p.value))),2551 log,2552 )2553 }2554}25552556/// A marker structure that enables the writer implementation2557/// to provide the interface to write properties to **already existing** tokens.2558pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2559impl<T: Config> ExistingTokenPropertyWriter<T> {2560 /// Creates a [`PropertyWriter`] for **already existing** tokens.2561 pub fn new<'a, Handle>(2562 collection: &'a Handle,2563 sender: &'a T::CrossAccountId,2564 ) -> PropertyWriter<'a, Self, T, Handle>2565 where2566 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2567 {2568 PropertyWriter {2569 collection,2570 collection_lazy_info: PropertyWriterLazyCollectionInfo {2571 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2572 property_permissions: LazyValue::new(|| {2573 <Pallet<T>>::property_permissions(collection.id)2574 }),2575 },2576 _phantom: PhantomData,2577 }2578 }2579}25802581impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2582where2583 T: Config,2584 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2585{2586 /// A function to write properties to an **already existing** token.2587 pub fn write_token_properties(2588 &mut self,2589 sender: &T::CrossAccountId,2590 token_id: TokenId,2591 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2592 nesting_budget: &dyn Budget,2593 log: evm_coder::ethereum::Log,2594 ) -> DispatchResult {2595 let check_token_exist = || self.collection.token_exists(token_id);2596 let check_token_owner = || {2597 self.collection2598 .check_token_indirect_owner(token_id, sender, nesting_budget)2599 };2600 let get_token_properties = || {2601 self.collection2602 .get_token_properties_raw(token_id)2603 .unwrap_or_default()2604 };26052606 self.internal_write_token_properties(2607 token_id,2608 PropertyWriterLazyTokenInfo::new(2609 check_token_exist,2610 check_token_owner,2611 get_token_properties,2612 ),2613 properties_updates,2614 log,2615 )2616 }2617}26182619/// A marker structure that enables the writer implementation2620/// to benchmark the token properties writing.2621#[cfg(feature = "runtime-benchmarks")]2622pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);26232624#[cfg(feature = "runtime-benchmarks")]2625impl<T: Config> BenchmarkPropertyWriter<T> {2626 /// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2627 pub fn new<'a, Handle>(2628 collection: &'a Handle,2629 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2630 ) -> PropertyWriter<'a, Self, T, Handle>2631 where2632 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2633 {2634 PropertyWriter {2635 collection,2636 collection_lazy_info,2637 _phantom: PhantomData,2638 }2639 }26402641 /// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2642 pub fn load_collection_info<Handle>(2643 collection_handle: &Handle,2644 sender: &T::CrossAccountId,2645 ) -> PropertyWriterLazyCollectionInfo<'static>2646 where2647 Handle: Deref<Target = CollectionHandle<T>>,2648 {2649 let is_collection_admin = collection_handle.is_owner_or_admin(sender);2650 let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);26512652 PropertyWriterLazyCollectionInfo {2653 is_collection_admin: LazyValue::new(move || is_collection_admin),2654 property_permissions: LazyValue::new(move || property_permissions),2655 }2656 }26572658 /// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2659 pub fn load_token_properties<Handle>(2660 collection: &Handle,2661 token_id: TokenId,2662 ) -> PropertyWriterLazyTokenInfo2663 where2664 Handle: CommonCollectionOperations<T>,2665 {2666 let stored_properties = collection2667 .get_token_properties_raw(token_id)2668 .unwrap_or_default();26692670 PropertyWriterLazyTokenInfo {2671 is_token_exist: LazyValue::new(|| true),2672 is_token_owner: LazyValue::new(|| Ok(true)),2673 stored_properties: LazyValue::new(move || stored_properties),2674 }2675 }2676}26772678#[cfg(feature = "runtime-benchmarks")]2679impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2680where2681 T: Config,2682 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2683{2684 /// A function to benchmark the writing of token properties.2685 pub fn write_token_properties(2686 &mut self,2687 token_id: TokenId,2688 properties_updates: impl Iterator<Item = Property>,2689 log: evm_coder::ethereum::Log,2690 ) -> DispatchResult {2691 let check_token_exist = || true;2692 let check_token_owner = || Ok(true);2693 let get_token_properties = TokenProperties::new;26942695 self.internal_write_token_properties(2696 token_id,2697 PropertyWriterLazyTokenInfo::new(2698 check_token_exist,2699 check_token_owner,2700 get_token_properties,2701 ),2702 properties_updates.map(|p| (p.key, Some(p.value))),2703 log,2704 )2705 }2706}27072708/// Computes the weight of writing properties to tokens.2709/// * `properties_nums` - The properties num of each created token.2710/// * `per_token_weight_weight` - The function to obtain the weight2711/// of writing properties from a token's properties num.2712pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2713 properties_nums: impl Iterator<Item = u32>,2714 per_token_weight: I,2715) -> Weight {2716 let mut weight = properties_nums2717 .filter_map(|properties_num| {2718 if properties_num > 0 {2719 Some(per_token_weight(properties_num))2720 } else {2721 None2722 }2723 })2724 .fold(Weight::zero(), |a, b| a.saturating_add(b));27252726 if !weight.is_zero() {2727 // If we are here, it means the token properties were written at least once.2728 // Because of that, some common collection data was also loaded; we must add this weight.2729 // However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.27302731 weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2732 }27332734 weight2735}27362737#[cfg(any(feature = "tests", test))]2738#[allow(missing_docs)]2739pub mod tests {2740 use crate::{Config, DispatchError, DispatchResult, LazyValue};27412742 const fn to_bool(u: u8) -> bool {2743 u != 02744 }27452746 #[derive(Debug)]2747 pub struct TestCase {2748 pub collection_admin: bool,2749 pub is_collection_admin: bool,2750 pub token_owner: bool,2751 pub is_token_owner: bool,2752 pub no_permission: bool,2753 }27542755 impl TestCase {2756 const fn new(2757 collection_admin: u8,2758 is_collection_admin: u8,2759 token_owner: u8,2760 is_token_owner: u8,2761 no_permission: u8,2762 ) -> Self {2763 Self {2764 collection_admin: to_bool(collection_admin),2765 is_collection_admin: to_bool(is_collection_admin),2766 token_owner: to_bool(token_owner),2767 is_token_owner: to_bool(is_token_owner),2768 no_permission: to_bool(no_permission),2769 }2770 }2771 }27722773 #[rustfmt::skip]2774 pub const TABLE: [TestCase; 16] = [2775 // ┌╴collection_admin2776 // │ ┌╴is_collection_admin2777 // │ │ ┌╴token_owner2778 // │ │ │ ┌╴is_token_ownership2779 // │ │ │ │ ┌╴no_permission2780 /* 0*/ TestCase::new(0, 0, 0, 0, 1),2781 /* 1*/ TestCase::new(0, 0, 0, 1, 1),2782 /* 2*/ TestCase::new(0, 0, 1, 0, 1),2783 /* 3*/ TestCase::new(0, 0, 1, 1, 0),2784 /* 4*/ TestCase::new(0, 1, 0, 0, 1),2785 /* 5*/ TestCase::new(0, 1, 0, 1, 1),2786 /* 6*/ TestCase::new(0, 1, 1, 0, 1),2787 /* 7*/ TestCase::new(0, 1, 1, 1, 0),2788 /* 8*/ TestCase::new(1, 0, 0, 0, 1),2789 /* 9*/ TestCase::new(1, 0, 0, 1, 1),2790 /* 10*/ TestCase::new(1, 0, 1, 0, 1),2791 /* 11*/ TestCase::new(1, 0, 1, 1, 0),2792 /* 12*/ TestCase::new(1, 1, 0, 0, 0),2793 /* 13*/ TestCase::new(1, 1, 0, 1, 0),2794 /* 14*/ TestCase::new(1, 1, 1, 0, 0),2795 /* 15*/ TestCase::new(1, 1, 1, 1, 0),2796 ];27972798 pub fn check_token_permissions<T: Config>(2799 collection_admin_permitted: bool,2800 token_owner_permitted: bool,2801 is_collection_admin: &mut LazyValue<bool>,2802 check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2803 check_token_existence: &mut LazyValue<bool>,2804 ) -> DispatchResult {2805 crate::check_token_permissions::<T>(2806 collection_admin_permitted,2807 token_owner_permitted,2808 is_collection_admin,2809 check_token_ownership,2810 check_token_existence,2811 )2812 }2813}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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use alloc::boxed::Box;57use core::{58 marker::PhantomData,59 ops::{Deref, DerefMut},60 slice::from_ref,61 unreachable,62};6364use evm_coder::ToLog;65use frame_support::{66 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Pays, PostDispatchInfo},67 ensure, fail,68 traits::{69 fungible::{Balanced, Debt, Inspect},70 tokens::{Imbalance, Precision, Preservation},71 Get,72 },73 transactional,74};75pub use pallet::*;76use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};77use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};78use sp_core::H160;79use sp_runtime::{traits::Zero, ArithmeticError, DispatchError, DispatchResult};80use sp_std::vec::Vec;81use sp_weights::Weight;82use up_data_structs::{83 budget::Budget, mapping::TokenAddressMapping, AccessMode, Collection, CollectionId,84 CollectionLimits, CollectionMode, CollectionPermissions,85 CollectionProperties as CollectionPropertiesT, CollectionStats, CreateCollectionData,86 CreateItemData, CreateItemExData, PhantomType, PropertiesError, PropertiesPermissionMap,87 Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,88 RpcCollection, RpcCollectionFlags, SponsoringRateLimit, SponsorshipState, TokenChild,89 TokenData, TokenId, TokenOwnerError, TokenProperties, TrySetProperty, COLLECTION_ADMINS_LIMIT,90 COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,91 MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_TOKEN_PREFIX_LENGTH,92 NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,93};94use up_pov_estimate_rpc::PovInfo;9596#[cfg(feature = "runtime-benchmarks")]97pub mod benchmarking;98pub mod dispatch;99pub mod erc;100pub mod eth;101pub mod helpers;102#[allow(missing_docs)]103pub mod weights;104105use weights::WeightInfo;106107/// Weight info.108pub type SelfWeightOf<T> = <T as Config>::WeightInfo;109110/// Collection handle contains information about collection data and id.111/// Also provides functionality to count consumed gas.112///113/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).114/// It allows to perform common operations and queries on any collection type,115/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].116#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]117pub struct CollectionHandle<T: Config> {118 /// Collection id119 pub id: CollectionId,120 collection: Collection<T::AccountId>,121 /// Substrate recorder for counting consumed gas122 pub recorder: SubstrateRecorder<T>,123}124125impl<T: Config> WithRecorder<T> for CollectionHandle<T> {126 fn recorder(&self) -> &SubstrateRecorder<T> {127 &self.recorder128 }129 fn into_recorder(self) -> SubstrateRecorder<T> {130 self.recorder131 }132}133134impl<T: Config> CollectionHandle<T> {135 /// Same as [CollectionHandle::new] but with an explicit gas limit.136 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {137 Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))138 }139140 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].141 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {142 <CollectionById<T>>::get(id).map(|collection| Self {143 id,144 collection,145 recorder,146 })147 }148149 /// Retrives collection data from storage and creates collection handle with default parameters.150 /// If collection not found return `None`151 pub fn new(id: CollectionId) -> Option<Self> {152 Self::new_with_gas_limit(id, u64::MAX)153 }154155 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.156 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {157 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)158 }159160 /// Consume gas for reading.161 pub fn consume_store_reads(162 &self,163 reads: u64,164 ) -> pallet_evm_coder_substrate::execution::Result<()> {165 self.recorder().consume_store_reads(reads)166 }167168 /// Consume gas for writing.169 pub fn consume_store_writes(170 &self,171 writes: u64,172 ) -> pallet_evm_coder_substrate::execution::Result<()> {173 self.recorder().consume_store_writes(writes)174 }175176 /// Consume gas for reading and writing.177 pub fn consume_store_reads_and_writes(178 &self,179 reads: u64,180 writes: u64,181 ) -> pallet_evm_coder_substrate::execution::Result<()> {182 self.recorder()183 .consume_store_reads_and_writes(reads, writes)184 }185186 /// Save collection to storage.187 pub fn save(&self) -> DispatchResult {188 <CollectionById<T>>::insert(self.id, &self.collection);189 Ok(())190 }191192 /// Set collection sponsor.193 ///194 /// Unique collections allows sponsoring for certain actions.195 /// This method allows you to set the sponsor of the collection.196 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].197 pub fn set_sponsor(198 &mut self,199 sender: &T::CrossAccountId,200 sponsor: T::AccountId,201 ) -> DispatchResult {202 self.check_is_internal()?;203 self.check_is_owner_or_admin(sender)?;204205 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());206207 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));208 <PalletEvm<T>>::deposit_log(209 erc::CollectionHelpersEvents::CollectionChanged {210 collection_id: eth::collection_id_to_address(self.id),211 }212 .to_log(T::ContractAddress::get()),213 );214215 self.save()216 }217218 /// Force set `sponsor`.219 ///220 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation221 /// from the `sponsor` is not required.222 ///223 /// # Arguments224 ///225 /// * `sponsor`: ID of the account of the sponsor-to-be.226 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {227 self.check_is_internal()?;228229 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());230231 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));232 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));233 <PalletEvm<T>>::deposit_log(234 erc::CollectionHelpersEvents::CollectionChanged {235 collection_id: eth::collection_id_to_address(self.id),236 }237 .to_log(T::ContractAddress::get()),238 );239240 self.save()241 }242243 /// Confirm sponsorship244 ///245 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.246 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].247 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {248 self.check_is_internal()?;249 ensure!(250 self.collection.sponsorship.pending_sponsor() == Some(sender),251 Error::<T>::ConfirmSponsorshipFail252 );253254 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());255256 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));257 <PalletEvm<T>>::deposit_log(258 erc::CollectionHelpersEvents::CollectionChanged {259 collection_id: eth::collection_id_to_address(self.id),260 }261 .to_log(T::ContractAddress::get()),262 );263264 self.save()265 }266267 /// Remove collection sponsor.268 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {269 self.check_is_internal()?;270 self.check_is_owner_or_admin(sender)?;271272 self.collection.sponsorship = SponsorshipState::Disabled;273274 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));275 <PalletEvm<T>>::deposit_log(276 erc::CollectionHelpersEvents::CollectionChanged {277 collection_id: eth::collection_id_to_address(self.id),278 }279 .to_log(T::ContractAddress::get()),280 );281 self.save()282 }283284 /// Force remove `sponsor`.285 ///286 /// Differs from `remove_sponsor` in that287 /// it doesn't require consent from the `owner` of the collection.288 pub fn force_remove_sponsor(&mut self) -> DispatchResult {289 self.check_is_internal()?;290291 self.collection.sponsorship = SponsorshipState::Disabled;292293 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));294 <PalletEvm<T>>::deposit_log(295 erc::CollectionHelpersEvents::CollectionChanged {296 collection_id: eth::collection_id_to_address(self.id),297 }298 .to_log(T::ContractAddress::get()),299 );300 self.save()301 }302303 /// Checks that the collection was created with, and must be operated upon through **Unique API**.304 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.305 pub fn check_is_internal(&self) -> DispatchResult {306 if self.flags.external {307 return Err(<Error<T>>::CollectionIsExternal)?;308 }309310 Ok(())311 }312313 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.314 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.315 pub fn check_is_external(&self) -> DispatchResult {316 if !self.flags.external {317 return Err(<Error<T>>::CollectionIsInternal)?;318 }319320 Ok(())321 }322}323324impl<T: Config> Deref for CollectionHandle<T> {325 type Target = Collection<T::AccountId>;326327 fn deref(&self) -> &Self::Target {328 &self.collection329 }330}331332impl<T: Config> DerefMut for CollectionHandle<T> {333 fn deref_mut(&mut self) -> &mut Self::Target {334 &mut self.collection335 }336}337338impl<T: Config> CollectionHandle<T> {339 /// Checks if the `user` is the owner of the collection.340 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {341 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);342 Ok(())343 }344345 /// Returns **true** if the `user` is the owner or administrator of the collection.346 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {347 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))348 }349350 /// Checks if the `user` is the owner or administrator of the collection.351 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {352 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);353 Ok(())354 }355356 /// Returns **true** if357 /// * the `user`is a collection owner or admin358 /// * the collection limits allow the owner/admins to transfer/burn any collection token359 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {360 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)361 }362363 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.364 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {365 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)366 }367368 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.369 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {370 ensure!(371 <Allowlist<T>>::get((self.id, user)),372 <Error<T>>::AddressNotInAllowlist373 );374 Ok(())375 }376377 /// Changes collection owner to another account378 /// #### Store read/writes379 /// 1 writes380 pub fn change_owner(381 &mut self,382 caller: T::CrossAccountId,383 new_owner: T::CrossAccountId,384 ) -> DispatchResult {385 self.check_is_internal()?;386 self.check_is_owner(&caller)?;387 self.collection.owner = new_owner.as_sub().clone();388389 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(390 self.id,391 new_owner.as_sub().clone(),392 ));393 <PalletEvm<T>>::deposit_log(394 erc::CollectionHelpersEvents::CollectionChanged {395 collection_id: eth::collection_id_to_address(self.id),396 }397 .to_log(T::ContractAddress::get()),398 );399400 self.save()401 }402}403404#[frame_support::pallet]405pub mod pallet {406407 use dispatch::CollectionDispatch;408 use frame_support::{409 pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat,410 };411 use scale_info::TypeInfo;412 use up_data_structs::{mapping::TokenAddressMapping, TokenId};413 use weights::WeightInfo;414415 use super::*;416417 #[pallet::config]418 pub trait Config:419 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo420 {421 /// Weight information for functions of this pallet.422 type WeightInfo: WeightInfo;423424 /// Events compatible with [`frame_system::Config::Event`].425 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;426427 /// Handler of accounts and payment.428 type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;429430 /// Set price to create a collection.431 #[pallet::constant]432 type CollectionCreationPrice: Get<433 <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,434 >;435436 /// Dispatcher of operations on collections.437 type CollectionDispatch: CollectionDispatch<Self>;438439 /// Account which holds the chain's treasury.440 type TreasuryAccountId: Get<Self::AccountId>;441442 /// Address under which the CollectionHelper contract would be available.443 #[pallet::constant]444 type ContractAddress: Get<H160>;445446 /// Mapper for token addresses to Ethereum addresses.447 type EvmTokenAddressMapping: TokenAddressMapping<H160>;448449 /// Mapper for token addresses to [`CrossAccountId`].450 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;451 }452453 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);454 /// Collection id for native fungible collction.455 pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);456457 #[pallet::pallet]458 #[pallet::storage_version(STORAGE_VERSION)]459 pub struct Pallet<T>(_);460461 #[pallet::extra_constants]462 impl<T: Config> Pallet<T> {463 /// Maximum admins per collection.464 pub fn collection_admins_limit() -> u32 {465 COLLECTION_ADMINS_LIMIT466 }467 }468469 #[pallet::genesis_config]470 pub struct GenesisConfig<T>(PhantomData<T>);471472 impl<T: Config> Default for GenesisConfig<T> {473 fn default() -> Self {474 Self(Default::default())475 }476 }477478 #[pallet::genesis_build]479 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {480 fn build(&self) {481 StorageVersion::new(1).put::<Pallet<T>>();482 }483 }484485 impl<T: Config> Pallet<T> {486 /// Helper function that handles deposit events487 pub fn deposit_event(event: Event<T>) {488 let event = <T as Config>::RuntimeEvent::from(event);489 let event = event.into();490 <frame_system::Pallet<T>>::deposit_event(event)491 }492 }493494 #[pallet::event]495 pub enum Event<T: Config> {496 /// New collection was created497 CollectionCreated(498 /// Globally unique identifier of newly created collection.499 CollectionId,500 /// [`CollectionMode`] converted into _u8_.501 u8,502 /// Collection owner.503 T::AccountId,504 ),505506 /// New collection was destroyed507 CollectionDestroyed(508 /// Globally unique identifier of collection.509 CollectionId,510 ),511512 /// New item was created.513 ItemCreated(514 /// Id of the collection where item was created.515 CollectionId,516 /// Id of an item. Unique within the collection.517 TokenId,518 /// Owner of newly created item519 T::CrossAccountId,520 /// Always 1 for NFT521 u128,522 ),523524 /// Collection item was burned.525 ItemDestroyed(526 /// Id of the collection where item was destroyed.527 CollectionId,528 /// Identifier of burned NFT.529 TokenId,530 /// Which user has destroyed its tokens.531 T::CrossAccountId,532 /// Amount of token pieces destroed. Always 1 for NFT.533 u128,534 ),535536 /// Item was transferred537 Transfer(538 /// Id of collection to which item is belong.539 CollectionId,540 /// Id of an item.541 TokenId,542 /// Original owner of item.543 T::CrossAccountId,544 /// New owner of item.545 T::CrossAccountId,546 /// Amount of token pieces transfered. Always 1 for NFT.547 u128,548 ),549550 /// Amount pieces of token owned by `sender` was approved for `spender`.551 Approved(552 /// Id of collection to which item is belong.553 CollectionId,554 /// Id of an item.555 TokenId,556 /// Original owner of item.557 T::CrossAccountId,558 /// Id for which the approval was granted.559 T::CrossAccountId,560 /// Amount of token pieces transfered. Always 1 for NFT.561 u128,562 ),563564 /// A `sender` approves operations on all owned tokens for `spender`.565 ApprovedForAll(566 /// Id of collection to which item is belong.567 CollectionId,568 /// Owner of a wallet.569 T::CrossAccountId,570 /// Id for which operator status was granted or rewoked.571 T::CrossAccountId,572 /// Is operator status granted or revoked?573 bool,574 ),575576 /// The colletion property has been added or edited.577 CollectionPropertySet(578 /// Id of collection to which property has been set.579 CollectionId,580 /// The property that was set.581 PropertyKey,582 ),583584 /// The property has been deleted.585 CollectionPropertyDeleted(586 /// Id of collection to which property has been deleted.587 CollectionId,588 /// The property that was deleted.589 PropertyKey,590 ),591592 /// The token property has been added or edited.593 TokenPropertySet(594 /// Identifier of the collection whose token has the property set.595 CollectionId,596 /// The token for which the property was set.597 TokenId,598 /// The property that was set.599 PropertyKey,600 ),601602 /// The token property has been deleted.603 TokenPropertyDeleted(604 /// Identifier of the collection whose token has the property deleted.605 CollectionId,606 /// The token for which the property was deleted.607 TokenId,608 /// The property that was deleted.609 PropertyKey,610 ),611612 /// The token property permission of a collection has been set.613 PropertyPermissionSet(614 /// ID of collection to which property permission has been set.615 CollectionId,616 /// The property permission that was set.617 PropertyKey,618 ),619620 /// Address was added to the allow list.621 AllowListAddressAdded(622 /// ID of the affected collection.623 CollectionId,624 /// Address of the added account.625 T::CrossAccountId,626 ),627628 /// Address was removed from the allow list.629 AllowListAddressRemoved(630 /// ID of the affected collection.631 CollectionId,632 /// Address of the removed account.633 T::CrossAccountId,634 ),635636 /// Collection admin was added.637 CollectionAdminAdded(638 /// ID of the affected collection.639 CollectionId,640 /// Admin address.641 T::CrossAccountId,642 ),643644 /// Collection admin was removed.645 CollectionAdminRemoved(646 /// ID of the affected collection.647 CollectionId,648 /// Removed admin address.649 T::CrossAccountId,650 ),651652 /// Collection limits were set.653 CollectionLimitSet(654 /// ID of the affected collection.655 CollectionId,656 ),657658 /// Collection owned was changed.659 CollectionOwnerChanged(660 /// ID of the affected collection.661 CollectionId,662 /// New owner address.663 T::AccountId,664 ),665666 /// Collection permissions were set.667 CollectionPermissionSet(668 /// ID of the affected collection.669 CollectionId,670 ),671672 /// Collection sponsor was set.673 CollectionSponsorSet(674 /// ID of the affected collection.675 CollectionId,676 /// New sponsor address.677 T::AccountId,678 ),679680 /// New sponsor was confirm.681 SponsorshipConfirmed(682 /// ID of the affected collection.683 CollectionId,684 /// New sponsor address.685 T::AccountId,686 ),687688 /// Collection sponsor was removed.689 CollectionSponsorRemoved(690 /// ID of the affected collection.691 CollectionId,692 ),693 }694695 #[pallet::error]696 pub enum Error<T> {697 /// This collection does not exist.698 CollectionNotFound,699 /// Sender parameter and item owner must be equal.700 MustBeTokenOwner,701 /// No permission to perform action702 NoPermission,703 /// Destroying only empty collections is allowed704 CantDestroyNotEmptyCollection,705 /// Collection is not in mint mode.706 PublicMintingNotAllowed,707 /// Address is not in allow list.708 AddressNotInAllowlist,709710 /// Collection name can not be longer than 63 char.711 CollectionNameLimitExceeded,712 /// Collection description can not be longer than 255 char.713 CollectionDescriptionLimitExceeded,714 /// Token prefix can not be longer than 15 char.715 CollectionTokenPrefixLimitExceeded,716 /// Total collections bound exceeded.717 TotalCollectionsLimitExceeded,718 /// Exceeded max admin count719 CollectionAdminCountExceeded,720 /// Collection limit bounds per collection exceeded721 CollectionLimitBoundsExceeded,722 /// Tried to enable permissions which are only permitted to be disabled723 OwnerPermissionsCantBeReverted,724 /// Collection settings not allowing items transferring725 TransferNotAllowed,726 /// Account token limit exceeded per collection727 AccountTokenLimitExceeded,728 /// Collection token limit exceeded729 CollectionTokenLimitExceeded,730 /// Metadata flag frozen731 MetadataFlagFrozen,732733 /// Item does not exist734 TokenNotFound,735 /// Item is balance not enough736 TokenValueTooLow,737 /// Requested value is more than the approved738 ApprovedValueTooLow,739 /// Tried to approve more than owned740 CantApproveMoreThanOwned,741 /// Only spending from eth mirror could be approved742 AddressIsNotEthMirror,743744 /// Can't transfer tokens to ethereum zero address745 AddressIsZero,746747 /// The operation is not supported748 UnsupportedOperation,749750 /// Insufficient funds to perform an action751 NotSufficientFounds,752753 /// User does not satisfy the nesting rule754 UserIsNotAllowedToNest,755 /// Only tokens from specific collections may nest tokens under this one756 SourceCollectionIsNotAllowedToNest,757758 /// Tried to store more data than allowed in collection field759 CollectionFieldSizeExceeded,760761 /// Tried to store more property data than allowed762 NoSpaceForProperty,763764 /// Tried to store more property keys than allowed765 PropertyLimitReached,766767 /// Property key is too long768 PropertyKeyIsTooLong,769770 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed771 InvalidCharacterInPropertyKey,772773 /// Empty property keys are forbidden774 EmptyPropertyKey,775776 /// Tried to access an external collection with an internal API777 CollectionIsExternal,778779 /// Tried to access an internal collection with an external API780 CollectionIsInternal,781782 /// This address is not set as sponsor, use setCollectionSponsor first.783 ConfirmSponsorshipFail,784785 /// The user is not an administrator.786 UserIsNotCollectionAdmin,787788 /// Fungible tokens hold no ID, and the default value of TokenId for a fungible collection is 0.789 FungibleItemsHaveNoId,790791 /// Not Fungible item data used to mint in Fungible collection.792 NotFungibleDataUsedToMintFungibleCollectionToken,793 }794795 /// Storage of the count of created collections. Essentially contains the last collection ID.796 #[pallet::storage]797 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;798799 /// Storage of the count of deleted collections.800 #[pallet::storage]801 pub type DestroyedCollectionCount<T> =802 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;803804 /// Storage of collection info.805 #[pallet::storage]806 pub type CollectionById<T> = StorageMap<807 Hasher = Blake2_128Concat,808 Key = CollectionId,809 Value = Collection<<T as frame_system::Config>::AccountId>,810 QueryKind = OptionQuery,811 >;812813 /// Storage of collection properties.814 #[pallet::storage]815 #[pallet::getter(fn collection_properties)]816 pub type CollectionProperties<T> = StorageMap<817 Hasher = Blake2_128Concat,818 Key = CollectionId,819 Value = CollectionPropertiesT,820 QueryKind = ValueQuery,821 >;822823 /// Storage of token property permissions of a collection.824 #[pallet::storage]825 #[pallet::getter(fn property_permissions)]826 pub type CollectionPropertyPermissions<T> = StorageMap<827 Hasher = Blake2_128Concat,828 Key = CollectionId,829 Value = PropertiesPermissionMap,830 QueryKind = ValueQuery,831 >;832833 /// Storage of the amount of collection admins.834 #[pallet::storage]835 pub type AdminAmount<T> = StorageMap<836 Hasher = Blake2_128Concat,837 Key = CollectionId,838 Value = u32,839 QueryKind = ValueQuery,840 >;841842 /// List of collection admins.843 #[pallet::storage]844 pub type IsAdmin<T: Config> = StorageNMap<845 Key = (846 Key<Blake2_128Concat, CollectionId>,847 Key<Blake2_128Concat, T::CrossAccountId>,848 ),849 Value = bool,850 QueryKind = ValueQuery,851 >;852853 /// Allowlisted collection users.854 #[pallet::storage]855 pub type Allowlist<T: Config> = StorageNMap<856 Key = (857 Key<Blake2_128Concat, CollectionId>,858 Key<Blake2_128Concat, T::CrossAccountId>,859 ),860 Value = bool,861 QueryKind = ValueQuery,862 >;863864 /// Not used by code, exists only to provide some types to metadata.865 #[pallet::storage]866 pub type DummyStorageValue<T: Config> = StorageValue<867 Value = (868 CollectionStats,869 CollectionId,870 TokenId,871 TokenChild,872 PhantomType<(873 TokenData<T::CrossAccountId>,874 RpcCollection<T::AccountId>,875 // PoV Estimate Info876 PovInfo,877 )>,878 ),879 QueryKind = OptionQuery,880 >;881}882883enum LazyValueState<'a, T> {884 Pending(Box<dyn FnOnce() -> T + 'a>),885 InProgress,886 Computed(T),887}888889/// Value representation with delayed initialization time.890pub struct LazyValue<'a, T> {891 state: LazyValueState<'a, T>,892}893894impl<'a, T> LazyValue<'a, T> {895 /// Create a new LazyValue.896 pub fn new(f: impl FnOnce() -> T + 'a) -> Self {897 Self {898 state: LazyValueState::Pending(Box::new(f)),899 }900 }901902 /// Get the value. If it is called the first time, the value will be initialized.903 pub fn value(&mut self) -> &T {904 self.force_value();905 self.value_mut()906 }907908 /// Get the value. If it is called the first time, the value will be initialized.909 pub fn value_mut(&mut self) -> &mut T {910 self.force_value();911912 if let LazyValueState::Computed(value) = &mut self.state {913 value914 } else {915 unreachable!()916 }917 }918919 fn into_inner(mut self) -> T {920 self.force_value();921 if let LazyValueState::Computed(value) = self.state {922 value923 } else {924 unreachable!()925 }926 }927928 /// Is value initialized?929 pub fn has_value(&self) -> bool {930 matches!(self.state, LazyValueState::Computed(_))931 }932933 fn force_value(&mut self) {934 use LazyValueState::*;935936 if self.has_value() {937 return;938 }939940 match sp_std::mem::replace(&mut self.state, InProgress) {941 Pending(f) => self.state = Computed(f()),942 _ => panic!("recursion isn't supported"),943 }944 }945}946947/// An issuer of a collection.948pub enum CollectionIssuer<CrossAccountId> {949 /// A user who creates the collection.950 User(CrossAccountId),951952 /// The internal mechanisms are creating the collection.953 Internals,954}955956fn check_token_permissions<T: Config>(957 collection_admin_permitted: bool,958 token_owner_permitted: bool,959 is_collection_admin: &mut LazyValue<bool>,960 is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,961 is_token_exist: &mut LazyValue<bool>,962) -> DispatchResult {963 if !(collection_admin_permitted && *is_collection_admin.value()964 || token_owner_permitted && (*is_token_owner.value())?)965 {966 fail!(<Error<T>>::NoPermission);967 }968969 let token_exist_due_to_owner_check_success =970 is_token_owner.has_value() && (*is_token_owner.value())?;971972 // If the token owner check has occurred and succeeded,973 // we know the token exists (otherwise, the owner check must fail).974 if !token_exist_due_to_owner_check_success {975 // If the token owner check didn't occur,976 // we must check the token's existence ourselves.977 if !is_token_exist.value() {978 fail!(<Error<T>>::TokenNotFound);979 }980 }981982 Ok(())983}984985impl<T: Config> Pallet<T> {986 /// Enshure that receiver address is correct.987 ///988 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.989 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {990 ensure!(991 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,992 <Error<T>>::AddressIsZero993 );994 Ok(())995 }996997 /// Get a vector of collection admins.998 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {999 <IsAdmin<T>>::iter_prefix((collection,))1000 .map(|(a, _)| a)1001 .collect()1002 }10031004 /// Get a vector of users allowed to mint tokens.1005 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {1006 <Allowlist<T>>::iter_prefix((collection,))1007 .map(|(a, _)| a)1008 .collect()1009 }10101011 /// Is `user` allowed to mint token in `collection`.1012 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1013 <Allowlist<T>>::get((collection, user))1014 }10151016 /// Get statistics of collections.1017 pub fn collection_stats() -> CollectionStats {1018 let created = <CreatedCollectionCount<T>>::get();1019 let destroyed = <DestroyedCollectionCount<T>>::get();1020 CollectionStats {1021 created: created.0,1022 destroyed: destroyed.0,1023 alive: created.0 - destroyed.0,1024 }1025 }10261027 /// Get the effective limits for the collection.1028 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1029 let collection = <CollectionById<T>>::get(collection)?;1030 let limits = collection.limits;1031 let effective_limits = CollectionLimits {1032 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1033 sponsored_data_size: Some(limits.sponsored_data_size()),1034 sponsored_data_rate_limit: Some(1035 limits1036 .sponsored_data_rate_limit1037 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),1038 ),1039 token_limit: Some(limits.token_limit()),1040 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1041 match collection.mode {1042 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1043 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1044 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1045 },1046 )),1047 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1048 owner_can_transfer: Some(limits.owner_can_transfer()),1049 owner_can_destroy: Some(limits.owner_can_destroy()),1050 transfers_enabled: Some(limits.transfers_enabled()),1051 };10521053 Some(effective_limits)1054 }10551056 /// Returns information about the `collection` adapted for rpc.1057 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1058 let Collection {1059 name,1060 description,1061 owner,1062 mode,1063 token_prefix,1064 sponsorship,1065 limits,1066 permissions,1067 flags,1068 } = <CollectionById<T>>::get(collection)?;10691070 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1071 .into_iter()1072 .map(|(key, permission)| PropertyKeyPermission { key, permission })1073 .collect();10741075 let properties = <CollectionProperties<T>>::get(collection)1076 .into_iter()1077 .map(|(key, value)| Property { key, value })1078 .collect();10791080 let permissions = CollectionPermissions {1081 access: Some(permissions.access()),1082 mint_mode: Some(permissions.mint_mode()),1083 nesting: Some(permissions.nesting().clone()),1084 };10851086 Some(RpcCollection {1087 name: name.into_inner(),1088 description: description.into_inner(),1089 owner,1090 mode,1091 token_prefix: token_prefix.into_inner(),1092 sponsorship,1093 limits,1094 permissions,1095 token_property_permissions,1096 properties,1097 read_only: flags.external,10981099 flags: RpcCollectionFlags {1100 foreign: flags.foreign,1101 erc721metadata: flags.erc721metadata,1102 },1103 })1104 }1105}11061107macro_rules! limit_default {1108 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1109 $(1110 if let Some($new) = $new.$field {1111 let $old = $old.$field($($arg)?);1112 let _ = $new;1113 let _ = $old;1114 $check1115 } else {1116 $new.$field = $old.$field1117 }1118 )*1119 }};1120}1121macro_rules! limit_default_clone {1122 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1123 $(1124 if let Some($new) = $new.$field.clone() {1125 let $old = $old.$field($($arg)?);1126 let _ = $new;1127 let _ = $old;1128 $check1129 } else {1130 $new.$field = $old.$field.clone()1131 }1132 )*1133 }};1134}11351136impl<T: Config> Pallet<T> {1137 /// Create new collection.1138 ///1139 /// * `owner` - The owner of the collection.1140 /// * `issuer` - An entity that creates the collection.1141 /// * `is_special_collection` -- Whether this collection is a special one, i.e. can have special flags set.1142 pub fn init_collection(1143 owner: T::CrossAccountId,1144 issuer: CollectionIssuer<T::CrossAccountId>,1145 data: CreateCollectionData<T::CrossAccountId>,1146 ) -> Result<CollectionId, DispatchError> {1147 match issuer {1148 CollectionIssuer::User(payer) => {1149 ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);11501151 // Take a (non-refundable) deposit of collection creation1152 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1153 imbalance.subsume(<T as Config>::Currency::deposit(1154 &T::TreasuryAccountId::get(),1155 T::CollectionCreationPrice::get(),1156 Precision::Exact,1157 )?);1158 let credit = <T as Config>::Currency::settle(1159 payer.as_sub(),1160 imbalance,1161 Preservation::Preserve,1162 )1163 .map_err(|_| Error::<T>::NotSufficientFounds)?;11641165 debug_assert!(credit.peek().is_zero());1166 }1167 CollectionIssuer::Internals => {}1168 }11691170 {1171 ensure!(1172 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1173 Error::<T>::CollectionTokenPrefixLimitExceeded1174 );1175 }11761177 let created_count = <CreatedCollectionCount<T>>::get()1178 .01179 .checked_add(1)1180 .ok_or(ArithmeticError::Overflow)?;1181 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1182 let id = CollectionId(created_count);11831184 // bound Total number of collections1185 ensure!(1186 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1187 <Error<T>>::TotalCollectionsLimitExceeded1188 );11891190 // =========11911192 let collection = Collection {1193 owner: owner.as_sub().clone(),1194 name: data.name,1195 mode: data.mode.clone(),1196 description: data.description,1197 token_prefix: data.token_prefix,1198 sponsorship: data1199 .pending_sponsor1200 .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1201 .unwrap_or_default(),1202 limits: data1203 .limits1204 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1205 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1206 permissions: data1207 .permissions1208 .map(|permissions| {1209 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1210 })1211 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1212 flags: data.flags,1213 };12141215 let mut collection_properties = CollectionPropertiesT::new();1216 collection_properties1217 .try_set_from_iter(data.properties.into_iter())1218 .map_err(<Error<T>>::from)?;12191220 CollectionProperties::<T>::insert(id, collection_properties);12211222 let mut token_props_permissions = PropertiesPermissionMap::new();1223 token_props_permissions1224 .try_set_from_iter(data.token_property_permissions.into_iter())1225 .map_err(<Error<T>>::from)?;12261227 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12281229 let mut admin_amount = 0u32;1230 for admin in data.admin_list.iter() {1231 if !<IsAdmin<T>>::get((id, admin)) {1232 <IsAdmin<T>>::insert((id, admin), true);1233 admin_amount = admin_amount1234 .checked_add(1)1235 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1236 }1237 }1238 ensure!(1239 admin_amount <= Self::collection_admins_limit(),1240 <Error<T>>::CollectionAdminCountExceeded,1241 );1242 <AdminAmount<T>>::insert(id, admin_amount);12431244 <CreatedCollectionCount<T>>::put(created_count);1245 <Pallet<T>>::deposit_event(Event::CollectionCreated(1246 id,1247 data.mode.id(),1248 owner.as_sub().clone(),1249 ));1250 <PalletEvm<T>>::deposit_log(1251 erc::CollectionHelpersEvents::CollectionCreated {1252 owner: *owner.as_eth(),1253 collection_id: eth::collection_id_to_address(id),1254 }1255 .to_log(T::ContractAddress::get()),1256 );1257 <CollectionById<T>>::insert(id, collection);1258 Ok(id)1259 }12601261 /// Destroy collection.1262 ///1263 /// * `collection` - Collection handler.1264 /// * `sender` - The owner or administrator of the collection.1265 pub fn destroy_collection(1266 collection: CollectionHandle<T>,1267 sender: &T::CrossAccountId,1268 ) -> DispatchResult {1269 ensure!(1270 collection.limits.owner_can_destroy(),1271 <Error<T>>::NoPermission,1272 );1273 collection.check_is_owner(sender)?;12741275 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1276 .01277 .checked_add(1)1278 .ok_or(ArithmeticError::Overflow)?;12791280 // =========12811282 <DestroyedCollectionCount<T>>::put(destroyed_collections);1283 <CollectionById<T>>::remove(collection.id);1284 <AdminAmount<T>>::remove(collection.id);1285 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1286 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1287 <CollectionProperties<T>>::remove(collection.id);12881289 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12901291 <PalletEvm<T>>::deposit_log(1292 erc::CollectionHelpersEvents::CollectionDestroyed {1293 collection_id: eth::collection_id_to_address(collection.id),1294 }1295 .to_log(T::ContractAddress::get()),1296 );1297 Ok(())1298 }12991300 /// This function sets or removes a collection properties according to1301 /// `properties_updates` contents:1302 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1303 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1304 ///1305 /// This function fires an event for each property change.1306 /// In case of an error, all the changes (including the events) will be reverted1307 /// since the function is transactional.1308 #[transactional]1309 fn modify_collection_properties(1310 collection: &CollectionHandle<T>,1311 sender: &T::CrossAccountId,1312 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1313 ) -> DispatchResult {1314 collection.check_is_owner_or_admin(sender)?;13151316 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13171318 for (key, value) in properties_updates {1319 match value {1320 Some(value) => {1321 stored_properties1322 .try_set(key.clone(), value)1323 .map_err(<Error<T>>::from)?;13241325 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1326 <PalletEvm<T>>::deposit_log(1327 erc::CollectionHelpersEvents::CollectionChanged {1328 collection_id: eth::collection_id_to_address(collection.id),1329 }1330 .to_log(T::ContractAddress::get()),1331 );1332 }1333 None => {1334 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13351336 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1337 <PalletEvm<T>>::deposit_log(1338 erc::CollectionHelpersEvents::CollectionChanged {1339 collection_id: eth::collection_id_to_address(collection.id),1340 }1341 .to_log(T::ContractAddress::get()),1342 );1343 }1344 }1345 }13461347 <CollectionProperties<T>>::set(collection.id, stored_properties);13481349 Ok(())1350 }13511352 /// Sets or unsets the approval of a given operator.1353 ///1354 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1355 /// - `owner`: Token owner1356 /// - `operator`: Operator1357 /// - `approve`: Should operator status be granted or revoked?1358 pub fn set_allowance_for_all(1359 collection: &CollectionHandle<T>,1360 owner: &T::CrossAccountId,1361 operator: &T::CrossAccountId,1362 approve: bool,1363 set_allowance: impl FnOnce(),1364 log: evm_coder::ethereum::Log,1365 ) -> DispatchResult {1366 if collection.permissions.access() == AccessMode::AllowList {1367 collection.check_allowlist(owner)?;1368 collection.check_allowlist(operator)?;1369 }13701371 Self::ensure_correct_receiver(operator)?;13721373 set_allowance();13741375 <PalletEvm<T>>::deposit_log(log);1376 Self::deposit_event(Event::ApprovedForAll(1377 collection.id,1378 owner.clone(),1379 operator.clone(),1380 approve,1381 ));1382 Ok(())1383 }13841385 /// Set collection property.1386 ///1387 /// * `collection` - Collection handler.1388 /// * `sender` - The owner or administrator of the collection.1389 /// * `property` - The property to set.1390 pub fn set_collection_property(1391 collection: &CollectionHandle<T>,1392 sender: &T::CrossAccountId,1393 property: Property,1394 ) -> DispatchResult {1395 Self::set_collection_properties(collection, sender, [property].into_iter())1396 }13971398 /// Set a scoped collection property, where the scope is a special prefix1399 /// prohibiting a user access to change the property directly.1400 ///1401 /// * `collection_id` - ID of the collection for which the property is being set.1402 /// * `scope` - Property scope.1403 /// * `property` - The property to set.1404 pub fn set_scoped_collection_property(1405 collection_id: CollectionId,1406 scope: PropertyScope,1407 property: Property,1408 ) -> DispatchResult {1409 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1410 properties.try_scoped_set(scope, property.key, property.value)1411 })1412 .map_err(<Error<T>>::from)?;14131414 Ok(())1415 }14161417 /// Set scoped collection properties, where the scope is a special prefix1418 /// prohibiting a user access to change the properties directly.1419 ///1420 /// * `collection_id` - ID of the collection for which the properties is being set.1421 /// * `scope` - Property scope.1422 /// * `properties` - The properties to set.1423 pub fn set_scoped_collection_properties(1424 collection_id: CollectionId,1425 scope: PropertyScope,1426 properties: impl Iterator<Item = Property>,1427 ) -> DispatchResult {1428 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1429 stored_properties.try_scoped_set_from_iter(scope, properties)1430 })1431 .map_err(<Error<T>>::from)?;14321433 Ok(())1434 }14351436 /// Set collection properties.1437 ///1438 /// * `collection` - Collection handler.1439 /// * `sender` - The owner or administrator of the collection.1440 /// * `properties` - The properties to set.1441 pub fn set_collection_properties(1442 collection: &CollectionHandle<T>,1443 sender: &T::CrossAccountId,1444 properties: impl Iterator<Item = Property>,1445 ) -> DispatchResult {1446 Self::modify_collection_properties(1447 collection,1448 sender,1449 properties.map(|property| (property.key, Some(property.value))),1450 )1451 }14521453 /// Delete collection property.1454 ///1455 /// * `collection` - Collection handler.1456 /// * `sender` - The owner or administrator of the collection.1457 /// * `property` - The property to delete.1458 pub fn delete_collection_property(1459 collection: &CollectionHandle<T>,1460 sender: &T::CrossAccountId,1461 property_key: PropertyKey,1462 ) -> DispatchResult {1463 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1464 }14651466 /// Delete collection properties.1467 ///1468 /// * `collection` - Collection handler.1469 /// * `sender` - The owner or administrator of the collection.1470 /// * `properties` - The properties to delete.1471 pub fn delete_collection_properties(1472 collection: &CollectionHandle<T>,1473 sender: &T::CrossAccountId,1474 property_keys: impl Iterator<Item = PropertyKey>,1475 ) -> DispatchResult {1476 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1477 }14781479 /// Set collection propetry permission without any checks.1480 ///1481 /// Used for migrations.1482 ///1483 /// * `collection` - Collection handler.1484 /// * `property_permissions` - Property permissions.1485 pub fn set_property_permission_unchecked(1486 collection: CollectionId,1487 property_permission: PropertyKeyPermission,1488 ) -> DispatchResult {1489 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1490 permissions.try_set(property_permission.key, property_permission.permission)1491 })1492 .map_err(<Error<T>>::from)?;1493 Ok(())1494 }14951496 /// Set collection property permission.1497 ///1498 /// * `collection` - Collection handler.1499 /// * `sender` - The owner or administrator of the collection.1500 /// * `property_permission` - Property permission.1501 pub fn set_property_permission(1502 collection: &CollectionHandle<T>,1503 sender: &T::CrossAccountId,1504 property_permission: PropertyKeyPermission,1505 ) -> DispatchResult {1506 Self::set_scoped_property_permission(1507 collection,1508 sender,1509 PropertyScope::None,1510 property_permission,1511 )1512 }15131514 /// Set collection property permission with scope.1515 ///1516 /// * `collection` - Collection handler.1517 /// * `sender` - The owner or administrator of the collection.1518 /// * `scope` - Property scope.1519 /// * `property_permission` - Property permission.1520 pub fn set_scoped_property_permission(1521 collection: &CollectionHandle<T>,1522 sender: &T::CrossAccountId,1523 scope: PropertyScope,1524 property_permission: PropertyKeyPermission,1525 ) -> DispatchResult {1526 collection.check_is_owner_or_admin(sender)?;15271528 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1529 let current_permission = all_permissions.get(&property_permission.key);1530 if matches![1531 current_permission,1532 Some(PropertyPermission { mutable: false, .. })1533 ] {1534 return Err(<Error<T>>::NoPermission.into());1535 }15361537 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1538 let property_permission = property_permission.clone();1539 permissions.try_scoped_set(1540 scope,1541 property_permission.key,1542 property_permission.permission,1543 )1544 })1545 .map_err(<Error<T>>::from)?;15461547 Self::deposit_event(Event::PropertyPermissionSet(1548 collection.id,1549 property_permission.key,1550 ));1551 <PalletEvm<T>>::deposit_log(1552 erc::CollectionHelpersEvents::CollectionChanged {1553 collection_id: eth::collection_id_to_address(collection.id),1554 }1555 .to_log(T::ContractAddress::get()),1556 );15571558 Ok(())1559 }15601561 /// Set token property permission.1562 ///1563 /// * `collection` - Collection handler.1564 /// * `sender` - The owner or administrator of the collection.1565 /// * `property_permissions` - Property permissions.1566 #[transactional]1567 pub fn set_token_property_permissions(1568 collection: &CollectionHandle<T>,1569 sender: &T::CrossAccountId,1570 property_permissions: Vec<PropertyKeyPermission>,1571 ) -> DispatchResult {1572 Self::set_scoped_token_property_permissions(1573 collection,1574 sender,1575 PropertyScope::None,1576 property_permissions,1577 )1578 }15791580 /// Set token property permission with scope.1581 ///1582 /// * `collection` - Collection handler.1583 /// * `sender` - The owner or administrator of the collection.1584 /// * `scope` - Property scope.1585 /// * `property_permissions` - Property permissions.1586 #[transactional]1587 pub fn set_scoped_token_property_permissions(1588 collection: &CollectionHandle<T>,1589 sender: &T::CrossAccountId,1590 scope: PropertyScope,1591 property_permissions: Vec<PropertyKeyPermission>,1592 ) -> DispatchResult {1593 for prop_pemission in property_permissions {1594 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1595 }15961597 Ok(())1598 }15991600 /// Get collection property.1601 pub fn get_collection_property(1602 collection_id: CollectionId,1603 key: &PropertyKey,1604 ) -> Option<PropertyValue> {1605 Self::collection_properties(collection_id).get(key).cloned()1606 }16071608 /// Convert byte vector to property key vector.1609 pub fn bytes_keys_to_property_keys(1610 keys: Vec<Vec<u8>>,1611 ) -> Result<Vec<PropertyKey>, DispatchError> {1612 keys.into_iter()1613 .map(|key| -> Result<PropertyKey, DispatchError> {1614 key.try_into()1615 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1616 })1617 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1618 }16191620 /// Get properties according to given keys.1621 pub fn filter_collection_properties(1622 collection_id: CollectionId,1623 keys: Option<Vec<PropertyKey>>,1624 ) -> Result<Vec<Property>, DispatchError> {1625 let properties = Self::collection_properties(collection_id);16261627 let properties = keys1628 .map(|keys| {1629 keys.into_iter()1630 .filter_map(|key| {1631 properties.get(&key).map(|value| Property {1632 key,1633 value: value.clone(),1634 })1635 })1636 .collect()1637 })1638 .unwrap_or_else(|| {1639 properties1640 .into_iter()1641 .map(|(key, value)| Property { key, value })1642 .collect()1643 });16441645 Ok(properties)1646 }16471648 /// Get property permissions according to given keys.1649 pub fn filter_property_permissions(1650 collection_id: CollectionId,1651 keys: Option<Vec<PropertyKey>>,1652 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1653 let permissions = Self::property_permissions(collection_id);16541655 let key_permissions = keys1656 .map(|keys| {1657 keys.into_iter()1658 .filter_map(|key| {1659 permissions1660 .get(&key)1661 .map(|permission| PropertyKeyPermission {1662 key,1663 permission: permission.clone(),1664 })1665 })1666 .collect()1667 })1668 .unwrap_or_else(|| {1669 permissions1670 .into_iter()1671 .map(|(key, permission)| PropertyKeyPermission { key, permission })1672 .collect()1673 });16741675 Ok(key_permissions)1676 }16771678 /// Toggle `user` participation in the `collection`'s allow list.1679 /// #### Store read/writes1680 /// 1 writes1681 pub fn toggle_allowlist(1682 collection: &CollectionHandle<T>,1683 sender: &T::CrossAccountId,1684 user: &T::CrossAccountId,1685 allowed: bool,1686 ) -> DispatchResult {1687 collection.check_is_owner_or_admin(sender)?;16881689 // =========16901691 if allowed {1692 <Allowlist<T>>::insert((collection.id, user), true);1693 Self::deposit_event(Event::<T>::AllowListAddressAdded(1694 collection.id,1695 user.clone(),1696 ));1697 } else {1698 <Allowlist<T>>::remove((collection.id, user));1699 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1700 collection.id,1701 user.clone(),1702 ));1703 }17041705 <PalletEvm<T>>::deposit_log(1706 erc::CollectionHelpersEvents::CollectionChanged {1707 collection_id: eth::collection_id_to_address(collection.id),1708 }1709 .to_log(T::ContractAddress::get()),1710 );17111712 Ok(())1713 }17141715 /// Toggle `user` participation in the `collection`'s admin list.1716 /// #### Store read/writes1717 /// 2 reads, 2 writes1718 pub fn toggle_admin(1719 collection: &CollectionHandle<T>,1720 sender: &T::CrossAccountId,1721 user: &T::CrossAccountId,1722 admin: bool,1723 ) -> DispatchResult {1724 collection.check_is_internal()?;1725 collection.check_is_owner(sender)?;17261727 let is_admin = <IsAdmin<T>>::get((collection.id, user));1728 if is_admin == admin {1729 if admin {1730 return Ok(());1731 } else {1732 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1733 }1734 }1735 let amount = <AdminAmount<T>>::get(collection.id);17361737 // =========17381739 if admin {1740 let amount = amount1741 .checked_add(1)1742 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1743 ensure!(1744 amount <= Self::collection_admins_limit(),1745 <Error<T>>::CollectionAdminCountExceeded,1746 );17471748 <AdminAmount<T>>::insert(collection.id, amount);1749 <IsAdmin<T>>::insert((collection.id, user), true);17501751 Self::deposit_event(Event::<T>::CollectionAdminAdded(1752 collection.id,1753 user.clone(),1754 ));1755 } else {1756 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1757 <IsAdmin<T>>::remove((collection.id, user));17581759 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1760 collection.id,1761 user.clone(),1762 ));1763 }17641765 <PalletEvm<T>>::deposit_log(1766 erc::CollectionHelpersEvents::CollectionChanged {1767 collection_id: eth::collection_id_to_address(collection.id),1768 }1769 .to_log(T::ContractAddress::get()),1770 );17711772 Ok(())1773 }17741775 /// Update collection limits.1776 pub fn update_limits(1777 user: &T::CrossAccountId,1778 collection: &mut CollectionHandle<T>,1779 new_limit: CollectionLimits,1780 ) -> DispatchResult {1781 collection.check_is_internal()?;1782 collection.check_is_owner_or_admin(user)?;17831784 collection.limits =1785 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17861787 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1788 <PalletEvm<T>>::deposit_log(1789 erc::CollectionHelpersEvents::CollectionChanged {1790 collection_id: eth::collection_id_to_address(collection.id),1791 }1792 .to_log(T::ContractAddress::get()),1793 );17941795 collection.save()1796 }17971798 /// Merge set fields from `new_limit` to `old_limit`.1799 fn clamp_limits(1800 mode: CollectionMode,1801 old_limit: &CollectionLimits,1802 mut new_limit: CollectionLimits,1803 ) -> Result<CollectionLimits, DispatchError> {1804 let limits = old_limit;1805 limit_default!(old_limit, new_limit,1806 account_token_ownership_limit => ensure!(1807 new_limit <= MAX_TOKEN_OWNERSHIP,1808 <Error<T>>::CollectionLimitBoundsExceeded,1809 ),1810 sponsored_data_size => ensure!(1811 new_limit <= CUSTOM_DATA_LIMIT,1812 <Error<T>>::CollectionLimitBoundsExceeded,1813 ),18141815 sponsored_data_rate_limit => {},1816 token_limit => ensure!(1817 old_limit >= new_limit && new_limit > 0,1818 <Error<T>>::CollectionTokenLimitExceeded1819 ),18201821 sponsor_transfer_timeout(match mode {1822 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1823 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1824 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1825 }) => ensure!(1826 new_limit <= MAX_SPONSOR_TIMEOUT,1827 <Error<T>>::CollectionLimitBoundsExceeded,1828 ),1829 sponsor_approve_timeout => {},1830 owner_can_transfer => ensure!(1831 !limits.owner_can_transfer_instaled() ||1832 old_limit || !new_limit,1833 <Error<T>>::OwnerPermissionsCantBeReverted,1834 ),1835 owner_can_destroy => ensure!(1836 old_limit || !new_limit,1837 <Error<T>>::OwnerPermissionsCantBeReverted,1838 ),1839 transfers_enabled => {},1840 );1841 Ok(new_limit)1842 }18431844 /// Update collection permissions.1845 pub fn update_permissions(1846 user: &T::CrossAccountId,1847 collection: &mut CollectionHandle<T>,1848 new_permission: CollectionPermissions,1849 ) -> DispatchResult {1850 collection.check_is_internal()?;1851 collection.check_is_owner_or_admin(user)?;1852 collection.permissions = Self::clamp_permissions(1853 collection.mode.clone(),1854 &collection.permissions,1855 new_permission,1856 )?;18571858 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1859 <PalletEvm<T>>::deposit_log(1860 erc::CollectionHelpersEvents::CollectionChanged {1861 collection_id: eth::collection_id_to_address(collection.id),1862 }1863 .to_log(T::ContractAddress::get()),1864 );18651866 collection.save()1867 }18681869 /// Merge set fields from `new_permission` to `old_permission`.1870 fn clamp_permissions(1871 _mode: CollectionMode,1872 old_permission: &CollectionPermissions,1873 mut new_permission: CollectionPermissions,1874 ) -> Result<CollectionPermissions, DispatchError> {1875 limit_default_clone!(old_permission, new_permission,1876 access => {},1877 mint_mode => {},1878 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1879 );1880 Ok(new_permission)1881 }18821883 /// Repair possibly broken properties of a collection.1884 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1885 CollectionProperties::<T>::mutate(collection_id, |properties| {1886 properties.recompute_consumed_space();1887 });18881889 Ok(())1890 }1891}18921893/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1894#[macro_export]1895macro_rules! unsupported {1896 ($runtime:path) => {1897 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1898 };1899}19001901/// Return weights for various worst-case operations.1902pub trait CommonWeightInfo<CrossAccountId> {1903 /// Weight of item creation.1904 fn create_item(data: &CreateItemData) -> Weight {1905 Self::create_multiple_items(from_ref(data))1906 }19071908 /// Weight of items creation.1909 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19101911 /// Weight of items creation.1912 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19131914 /// The weight of the burning item.1915 fn burn_item() -> Weight;19161917 /// Property setting weight.1918 ///1919 /// * `amount`- The number of properties to set.1920 fn set_collection_properties(amount: u32) -> Weight;19211922 /// Collection property deletion weight.1923 ///1924 /// * `amount`- The number of properties to set.1925 fn delete_collection_properties(amount: u32) -> Weight {1926 Self::set_collection_properties(amount)1927 }19281929 /// Token property setting weight.1930 ///1931 /// * `amount`- The number of properties to set.1932 fn set_token_properties(amount: u32) -> Weight;19331934 /// Token property deletion weight.1935 ///1936 /// * `amount`- The number of properties to delete.1937 fn delete_token_properties(amount: u32) -> Weight {1938 Self::set_token_properties(amount)1939 }19401941 /// Token property permissions set weight.1942 ///1943 /// * `amount`- The number of property permissions to set.1944 fn set_token_property_permissions(amount: u32) -> Weight;19451946 /// Transfer price of the token or its parts.1947 fn transfer() -> Weight;19481949 /// The price of setting the permission of the operation from another user.1950 fn approve() -> Weight;19511952 /// The price of setting the permission of the operation from another user for eth mirror.1953 fn approve_from() -> Weight;19541955 /// Transfer price from another user.1956 fn transfer_from() -> Weight;19571958 /// The price of burning a token from another user.1959 fn burn_from() -> Weight;19601961 /// The price of setting approval for all1962 fn set_allowance_for_all() -> Weight;19631964 /// The price of repairing an item.1965 fn force_repair_item() -> Weight;1966}19671968/// Weight info extension trait for refungible pallet.1969pub trait RefungibleExtensionsWeightInfo {1970 /// Weight of token repartition.1971 fn repartition() -> Weight;1972}19731974/// Common collection operations.1975///1976/// It wraps methods in Fungible, Nonfungible and Refungible pallets1977/// and adds weight info.1978pub trait CommonCollectionOperations<T: Config> {1979 /// Create token.1980 ///1981 /// * `sender` - The user who mint the token and pays for the transaction.1982 /// * `to` - The user who will own the token.1983 /// * `data` - Token data.1984 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1985 fn create_item(1986 &self,1987 sender: T::CrossAccountId,1988 to: T::CrossAccountId,1989 data: CreateItemData,1990 nesting_budget: &dyn Budget,1991 ) -> DispatchResultWithPostInfo;19921993 /// Create multiple tokens.1994 ///1995 /// * `sender` - The user who mint the token and pays for the transaction.1996 /// * `to` - The user who will own the token.1997 /// * `data` - Token data.1998 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1999 fn create_multiple_items(2000 &self,2001 sender: T::CrossAccountId,2002 to: T::CrossAccountId,2003 data: Vec<CreateItemData>,2004 nesting_budget: &dyn Budget,2005 ) -> DispatchResultWithPostInfo;20062007 /// Create multiple tokens.2008 ///2009 /// * `sender` - The user who mint the token and pays for the transaction.2010 /// * `to` - The user who will own the token.2011 /// * `data` - Token data.2012 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2013 fn create_multiple_items_ex(2014 &self,2015 sender: T::CrossAccountId,2016 data: CreateItemExData<T::CrossAccountId>,2017 nesting_budget: &dyn Budget,2018 ) -> DispatchResultWithPostInfo;20192020 /// Burn token.2021 ///2022 /// * `sender` - The user who owns the token.2023 /// * `token` - Token id that will burned.2024 /// * `amount` - The number of parts of the token that will be burned.2025 fn burn_item(2026 &self,2027 sender: T::CrossAccountId,2028 token: TokenId,2029 amount: u128,2030 ) -> DispatchResultWithPostInfo;20312032 /// Set collection properties.2033 ///2034 /// * `sender` - Must be either the owner of the collection or its admin.2035 /// * `properties` - Properties to be set.2036 fn set_collection_properties(2037 &self,2038 sender: T::CrossAccountId,2039 properties: Vec<Property>,2040 ) -> DispatchResultWithPostInfo;20412042 /// Delete collection properties.2043 ///2044 /// * `sender` - Must be either the owner of the collection or its admin.2045 /// * `properties` - The properties to be removed.2046 fn delete_collection_properties(2047 &self,2048 sender: &T::CrossAccountId,2049 property_keys: Vec<PropertyKey>,2050 ) -> DispatchResultWithPostInfo;20512052 /// Set token properties.2053 ///2054 /// The appropriate [`PropertyPermission`] for the token property2055 /// must be set with [`Self::set_token_property_permissions`].2056 ///2057 /// * `sender` - Must be either the owner of the token or its admin.2058 /// * `token_id` - The token for which the properties are being set.2059 /// * `properties` - Properties to be set.2060 /// * `budget` - Budget for setting properties.2061 fn set_token_properties(2062 &self,2063 sender: T::CrossAccountId,2064 token_id: TokenId,2065 properties: Vec<Property>,2066 budget: &dyn Budget,2067 ) -> DispatchResultWithPostInfo;20682069 /// Remove token properties.2070 ///2071 /// The appropriate [`PropertyPermission`] for the token property2072 /// must be set with [`Self::set_token_property_permissions`].2073 ///2074 /// * `sender` - Must be either the owner of the token or its admin.2075 /// * `token_id` - The token for which the properties are being remove.2076 /// * `property_keys` - Keys to remove corresponding properties.2077 /// * `budget` - Budget for removing properties.2078 fn delete_token_properties(2079 &self,2080 sender: T::CrossAccountId,2081 token_id: TokenId,2082 property_keys: Vec<PropertyKey>,2083 budget: &dyn Budget,2084 ) -> DispatchResultWithPostInfo;20852086 /// Get token properties raw map.2087 ///2088 /// * `token_id` - The token which properties are needed.2089 fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20902091 /// Set token properties raw map.2092 ///2093 /// * `token_id` - The token for which the properties are being set.2094 /// * `map` - The raw map containing the token's properties.2095 fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20962097 /// Set token property permissions.2098 ///2099 /// * `sender` - Must be either the owner of the token or its admin.2100 /// * `token_id` - The token for which the properties are being set.2101 /// * `property_permissions` - Property permissions to be set.2102 /// * `budget` - Budget for setting properties.2103 fn set_token_property_permissions(2104 &self,2105 sender: &T::CrossAccountId,2106 property_permissions: Vec<PropertyKeyPermission>,2107 ) -> DispatchResultWithPostInfo;21082109 /// Transfer amount of token pieces.2110 ///2111 /// * `sender` - Donor user.2112 /// * `to` - Recepient user.2113 /// * `token` - The token of which parts are being sent.2114 /// * `amount` - The number of parts of the token that will be transferred.2115 /// * `budget` - The maximum budget that can be spent on the transfer.2116 fn transfer(2117 &self,2118 sender: T::CrossAccountId,2119 to: T::CrossAccountId,2120 token: TokenId,2121 amount: u128,2122 budget: &dyn Budget,2123 ) -> DispatchResultWithPostInfo;21242125 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2126 ///2127 /// * `sender` - The user who grants access to the token.2128 /// * `spender` - The user to whom the rights are granted.2129 /// * `token` - The token to which access is granted.2130 /// * `amount` - The amount of pieces that another user can dispose of.2131 fn approve(2132 &self,2133 sender: T::CrossAccountId,2134 spender: T::CrossAccountId,2135 token: TokenId,2136 amount: u128,2137 ) -> DispatchResultWithPostInfo;21382139 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2140 ///2141 /// * `sender` - The user who grants access to the token.2142 /// * `from` - Spender's eth mirror.2143 /// * `to` - The user to whom the rights are granted.2144 /// * `token` - The token to which access is granted.2145 /// * `amount` - The amount of pieces that another user can dispose of.2146 fn approve_from(2147 &self,2148 sender: T::CrossAccountId,2149 from: T::CrossAccountId,2150 to: T::CrossAccountId,2151 token: TokenId,2152 amount: u128,2153 ) -> DispatchResultWithPostInfo;21542155 /// Send parts of a token owned by another user.2156 ///2157 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2158 ///2159 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2160 /// * `from` - The user who owns the token.2161 /// * `to` - Recepient user.2162 /// * `token` - The token of which parts are being sent.2163 /// * `amount` - The number of parts of the token that will be transferred.2164 /// * `budget` - The maximum budget that can be spent on the transfer.2165 fn transfer_from(2166 &self,2167 sender: T::CrossAccountId,2168 from: T::CrossAccountId,2169 to: T::CrossAccountId,2170 token: TokenId,2171 amount: u128,2172 budget: &dyn Budget,2173 ) -> DispatchResultWithPostInfo;21742175 /// Burn parts of a token owned by another user.2176 ///2177 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2178 ///2179 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2180 /// * `from` - The user who owns the token.2181 /// * `token` - The token of which parts are being sent.2182 /// * `amount` - The number of parts of the token that will be transferred.2183 /// * `budget` - The maximum budget that can be spent on the burn.2184 fn burn_from(2185 &self,2186 sender: T::CrossAccountId,2187 from: T::CrossAccountId,2188 token: TokenId,2189 amount: u128,2190 budget: &dyn Budget,2191 ) -> DispatchResultWithPostInfo;21922193 /// Check permission to nest token.2194 ///2195 /// * `sender` - The user who initiated the check.2196 /// * `from` - The token that is checked for embedding.2197 /// * `under` - Token under which to check.2198 /// * `budget` - The maximum budget that can be spent on the check.2199 fn check_nesting(2200 &self,2201 sender: &T::CrossAccountId,2202 from: (CollectionId, TokenId),2203 under: TokenId,2204 budget: &dyn Budget,2205 ) -> DispatchResult;22062207 /// Nest one token into another.2208 ///2209 /// * `under` - Token holder.2210 /// * `to_nest` - Nested token.2211 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22122213 /// Unnest token.2214 ///2215 /// * `under` - Token holder.2216 /// * `to_nest` - Token to unnest.2217 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22182219 /// Get all user tokens.2220 ///2221 /// * `account` - Account for which you need to get tokens.2222 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22232224 /// Get all the tokens in the collection.2225 fn collection_tokens(&self) -> Vec<TokenId>;22262227 /// Check if the token exists.2228 ///2229 /// * `token` - Id token to check.2230 fn token_exists(&self, token: TokenId) -> bool;22312232 /// Get the id of the last minted token.2233 fn last_token_id(&self) -> TokenId;22342235 /// Get the owner of the token.2236 ///2237 /// * `token` - The token for which you need to find out the owner.2238 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22392240 /// Checks if the `maybe_owner` is the indirect owner of the `token`.2241 ///2242 /// * `token` - Id token to check.2243 /// * `maybe_owner` - The account to check.2244 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2245 fn check_token_indirect_owner(2246 &self,2247 token: TokenId,2248 maybe_owner: &T::CrossAccountId,2249 nesting_budget: &dyn Budget,2250 ) -> Result<bool, DispatchError>;22512252 /// Returns 10 tokens owners in no particular order.2253 ///2254 /// * `token` - The token for which you need to find out the owners.2255 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22562257 /// Get the value of the token property by key.2258 ///2259 /// * `token` - Token with the property to get.2260 /// * `key` - Property name.2261 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22622263 /// Get a set of token properties by key vector.2264 ///2265 /// * `token` - Token with the property to get.2266 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2267 /// then all properties are returned.2268 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22692270 /// Amount of unique collection tokens2271 fn total_supply(&self) -> u32;22722273 /// Amount of different tokens account has.2274 ///2275 /// * `account` - The account for which need to get the balance.2276 fn account_balance(&self, account: T::CrossAccountId) -> u32;22772278 /// Amount of specific token account have.2279 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22802281 /// Amount of token pieces2282 fn total_pieces(&self, token: TokenId) -> Option<u128>;22832284 /// Get the number of parts of the token that a trusted user can manage.2285 ///2286 /// * `sender` - Trusted user.2287 /// * `spender` - Owner of the token.2288 /// * `token` - The token for which to get the value.2289 fn allowance(2290 &self,2291 sender: T::CrossAccountId,2292 spender: T::CrossAccountId,2293 token: TokenId,2294 ) -> u128;22952296 /// Get extension for RFT collection.2297 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {2298 None2299 }23002301 /// Get XCM extensions.2302 fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {2303 None2304 }23052306 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2307 /// * `owner` - Token owner2308 /// * `operator` - Operator2309 /// * `approve` - Should operator status be granted or revoked?2310 fn set_allowance_for_all(2311 &self,2312 owner: T::CrossAccountId,2313 operator: T::CrossAccountId,2314 approve: bool,2315 ) -> DispatchResultWithPostInfo;23162317 /// Tells whether the given `owner` approves the `operator`.2318 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23192320 /// Repairs a possibly broken item.2321 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2322}23232324/// Extension for RFT collection.2325pub trait RefungibleExtensions<T>2326where2327 T: Config,2328{2329 /// Change the number of parts of the token.2330 ///2331 /// When the value changes down, this function is equivalent to burning parts of the token.2332 ///2333 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2334 /// * `token` - The token for which you want to change the number of parts.2335 /// * `amount` - The new value of the parts of the token.2336 fn repartition(2337 &self,2338 sender: &T::CrossAccountId,2339 token: TokenId,2340 amount: u128,2341 ) -> DispatchResultWithPostInfo;2342}23432344/// XCM extensions for fungible and NFT collections2345pub trait XcmExtensions<T>2346where2347 T: Config,2348{2349 /// Does the token have children?2350 fn token_has_children(&self, _token: TokenId) -> bool {2351 false2352 }23532354 /// Create a collection's item using a transaction.2355 ///2356 /// This function performs additional XCM-related checks before the actual creation.2357 ///2358 /// The `transactional` attribute is needed because the inbound XCM messages2359 /// are processed in a non-transactional context.2360 /// To perform the needed logic, we use the internal pallets' functions2361 /// that are not inherently safe to use outside a transaction.2362 ///2363 /// This requirement is temporary until XCM message processing becomes transactional:2364 /// https://github.com/paritytech/polkadot-sdk/issues/4902365 #[transactional]2366 fn create_item(2367 &self,2368 depositor: &T::CrossAccountId,2369 to: T::CrossAccountId,2370 data: CreateItemData,2371 nesting_budget: &dyn Budget,2372 ) -> Result<TokenId, DispatchError> {2373 if T::CrossTokenAddressMapping::is_token_address(&to) {2374 return unsupported!(T);2375 }23762377 self.create_item_internal(depositor, to, data, nesting_budget)2378 }23792380 /// Create a collection's item.2381 fn create_item_internal(2382 &self,2383 depositor: &T::CrossAccountId,2384 to: T::CrossAccountId,2385 data: CreateItemData,2386 nesting_budget: &dyn Budget,2387 ) -> Result<TokenId, DispatchError>;23882389 /// Transfer an item from the `from` account to the `to` account using a transaction.2390 ///2391 /// This function performs additional XCM-related checks before the actual transfer.2392 ///2393 /// The `transactional` attribute is needed because the inbound XCM messages2394 /// are processed in a non-transactional context.2395 /// To perform the needed logic, we use the internal pallets' functions2396 /// that are not inherently safe to use outside a transaction.2397 ///2398 /// This requirement is temporary until XCM message processing becomes transactional:2399 /// https://github.com/paritytech/polkadot-sdk/issues/4902400 #[transactional]2401 fn transfer_item(2402 &self,2403 depositor: &T::CrossAccountId,2404 from: &T::CrossAccountId,2405 to: &T::CrossAccountId,2406 token: TokenId,2407 amount: u128,2408 nesting_budget: &dyn Budget,2409 ) -> DispatchResult {2410 if T::CrossTokenAddressMapping::is_token_address(to) {2411 return unsupported!(T);2412 }24132414 if self.token_has_children(token) {2415 return unsupported!(T);2416 }24172418 self.transfer_item_internal(depositor, from, to, token, amount, nesting_budget)2419 }24202421 /// Transfer an item from the `from` account to the `to` account.2422 fn transfer_item_internal(2423 &self,2424 depositor: &T::CrossAccountId,2425 from: &T::CrossAccountId,2426 to: &T::CrossAccountId,2427 token: TokenId,2428 amount: u128,2429 nesting_budget: &dyn Budget,2430 ) -> DispatchResult;24312432 /// Burn a collection's item using a transaction.2433 ///2434 /// The `transactional` attribute is needed because the inbound XCM messages2435 /// are processed in a non-transactional context.2436 /// To perform the needed logic, we use the internal pallets' functions2437 /// that are not inherently safe to use outside a transaction.2438 ///2439 /// This requirement is temporary until XCM message processing becomes transactional:2440 /// https://github.com/paritytech/polkadot-sdk/issues/4902441 #[transactional]2442 fn burn_item(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult {2443 self.burn_item_internal(from, token, amount)2444 }24452446 /// Burn a collection's item.2447 fn burn_item_internal(2448 &self,2449 from: T::CrossAccountId,2450 token: TokenId,2451 amount: u128,2452 ) -> DispatchResult;2453}24542455/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2456///2457/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2458pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2459 let post_info = PostDispatchInfo {2460 actual_weight: Some(weight),2461 pays_fee: Pays::Yes,2462 };2463 match res {2464 Ok(()) => Ok(post_info),2465 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2466 }2467}24682469impl<T: Config> From<PropertiesError> for Error<T> {2470 fn from(error: PropertiesError) -> Self {2471 match error {2472 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2473 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2474 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2475 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2476 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2477 }2478 }2479}24802481/// The type-safe interface for writing properties (setting or deleting) to tokens.2482/// It has two distinct implementations for newly created tokens and existing ones.2483///2484/// This type utilizes the lazy evaluation to avoid repeating the computation2485/// of several performance-heavy or PoV-heavy tasks,2486/// such as checking the indirect ownership or reading the token property permissions.2487pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2488 collection: &'a Handle,2489 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2490 _phantom: PhantomData<(T, WriterVariant)>,2491}24922493impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2494where2495 T: Config,2496 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2497{2498 fn internal_write_token_properties(2499 &mut self,2500 token_id: TokenId,2501 mut token_lazy_info: PropertyWriterLazyTokenInfo,2502 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2503 log: evm_coder::ethereum::Log,2504 ) -> DispatchResult {2505 for (key, value) in properties_updates {2506 let permission = self2507 .collection_lazy_info2508 .property_permissions2509 .value()2510 .get(&key)2511 .cloned()2512 .unwrap_or_else(PropertyPermission::none);25132514 match permission {2515 PropertyPermission { mutable: false, .. }2516 if token_lazy_info2517 .stored_properties2518 .value()2519 .get(&key)2520 .is_some() =>2521 {2522 return Err(<Error<T>>::NoPermission.into());2523 }25242525 PropertyPermission {2526 collection_admin,2527 token_owner,2528 ..2529 } => check_token_permissions::<T>(2530 collection_admin,2531 token_owner,2532 &mut self.collection_lazy_info.is_collection_admin,2533 &mut token_lazy_info.is_token_owner,2534 &mut token_lazy_info.is_token_exist,2535 )?,2536 }25372538 match value {2539 Some(value) => {2540 token_lazy_info2541 .stored_properties2542 .value_mut()2543 .try_set(key.clone(), value)2544 .map_err(<Error<T>>::from)?;25452546 <Pallet<T>>::deposit_event(Event::TokenPropertySet(2547 self.collection.id,2548 token_id,2549 key,2550 ));2551 }2552 None => {2553 token_lazy_info2554 .stored_properties2555 .value_mut()2556 .remove(&key)2557 .map_err(<Error<T>>::from)?;25582559 <Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2560 self.collection.id,2561 token_id,2562 key,2563 ));2564 }2565 }2566 }25672568 let properties_changed = token_lazy_info.stored_properties.has_value();2569 if properties_changed {2570 <PalletEvm<T>>::deposit_log(log);25712572 self.collection2573 .set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2574 }25752576 Ok(())2577 }2578}25792580/// A helper structure for the [`PropertyWriter`] that holds2581/// the collection-related info. The info is loaded using lazy evaluation.2582/// This info is common for any token for which we write properties.2583pub struct PropertyWriterLazyCollectionInfo<'a> {2584 is_collection_admin: LazyValue<'a, bool>,2585 property_permissions: LazyValue<'a, PropertiesPermissionMap>,2586}25872588/// A helper structure for the [`PropertyWriter`] that holds2589/// the token-related info. The info is loaded using lazy evaluation.2590pub struct PropertyWriterLazyTokenInfo<'a> {2591 is_token_exist: LazyValue<'a, bool>,2592 is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2593 stored_properties: LazyValue<'a, TokenProperties>,2594}25952596impl<'a> PropertyWriterLazyTokenInfo<'a> {2597 /// Create a lazy token info.2598 pub fn new(2599 check_token_exist: impl FnOnce() -> bool + 'a,2600 check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2601 get_token_properties: impl FnOnce() -> TokenProperties + 'a,2602 ) -> Self {2603 Self {2604 is_token_exist: LazyValue::new(check_token_exist),2605 is_token_owner: LazyValue::new(check_token_owner),2606 stored_properties: LazyValue::new(get_token_properties),2607 }2608 }2609}26102611/// A marker structure that enables the writer implementation2612/// to provide the interface to write properties to **newly created** tokens.2613pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2614impl<T: Config> NewTokenPropertyWriter<T> {2615 /// Creates a [`PropertyWriter`] for **newly created** tokens.2616 pub fn new<'a, Handle>(2617 collection: &'a Handle,2618 sender: &'a T::CrossAccountId,2619 ) -> PropertyWriter<'a, Self, T, Handle>2620 where2621 T: Config,2622 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2623 {2624 PropertyWriter {2625 collection,2626 collection_lazy_info: PropertyWriterLazyCollectionInfo {2627 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2628 property_permissions: LazyValue::new(|| {2629 <Pallet<T>>::property_permissions(collection.id)2630 }),2631 },2632 _phantom: PhantomData,2633 }2634 }2635}26362637impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2638where2639 T: Config,2640 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2641{2642 /// A function to write properties to a **newly created** token.2643 pub fn write_token_properties(2644 &mut self,2645 mint_target_is_sender: bool,2646 token_id: TokenId,2647 properties_updates: impl Iterator<Item = Property>,2648 log: evm_coder::ethereum::Log,2649 ) -> DispatchResult {2650 let check_token_exist = || {2651 debug_assert!(self.collection.token_exists(token_id));2652 true2653 };26542655 let check_token_owner = || Ok(mint_target_is_sender);26562657 let get_token_properties = || {2658 debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2659 TokenProperties::new()2660 };26612662 self.internal_write_token_properties(2663 token_id,2664 PropertyWriterLazyTokenInfo::new(2665 check_token_exist,2666 check_token_owner,2667 get_token_properties,2668 ),2669 properties_updates.map(|p| (p.key, Some(p.value))),2670 log,2671 )2672 }2673}26742675/// A marker structure that enables the writer implementation2676/// to provide the interface to write properties to **already existing** tokens.2677pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2678impl<T: Config> ExistingTokenPropertyWriter<T> {2679 /// Creates a [`PropertyWriter`] for **already existing** tokens.2680 pub fn new<'a, Handle>(2681 collection: &'a Handle,2682 sender: &'a T::CrossAccountId,2683 ) -> PropertyWriter<'a, Self, T, Handle>2684 where2685 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2686 {2687 PropertyWriter {2688 collection,2689 collection_lazy_info: PropertyWriterLazyCollectionInfo {2690 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2691 property_permissions: LazyValue::new(|| {2692 <Pallet<T>>::property_permissions(collection.id)2693 }),2694 },2695 _phantom: PhantomData,2696 }2697 }2698}26992700impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2701where2702 T: Config,2703 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2704{2705 /// A function to write properties to an **already existing** token.2706 pub fn write_token_properties(2707 &mut self,2708 sender: &T::CrossAccountId,2709 token_id: TokenId,2710 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2711 nesting_budget: &dyn Budget,2712 log: evm_coder::ethereum::Log,2713 ) -> DispatchResult {2714 let check_token_exist = || self.collection.token_exists(token_id);2715 let check_token_owner = || {2716 self.collection2717 .check_token_indirect_owner(token_id, sender, nesting_budget)2718 };2719 let get_token_properties = || {2720 self.collection2721 .get_token_properties_raw(token_id)2722 .unwrap_or_default()2723 };27242725 self.internal_write_token_properties(2726 token_id,2727 PropertyWriterLazyTokenInfo::new(2728 check_token_exist,2729 check_token_owner,2730 get_token_properties,2731 ),2732 properties_updates,2733 log,2734 )2735 }2736}27372738/// A marker structure that enables the writer implementation2739/// to benchmark the token properties writing.2740#[cfg(feature = "runtime-benchmarks")]2741pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);27422743#[cfg(feature = "runtime-benchmarks")]2744impl<T: Config> BenchmarkPropertyWriter<T> {2745 /// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2746 pub fn new<'a, Handle>(2747 collection: &'a Handle,2748 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2749 ) -> PropertyWriter<'a, Self, T, Handle>2750 where2751 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2752 {2753 PropertyWriter {2754 collection,2755 collection_lazy_info,2756 _phantom: PhantomData,2757 }2758 }27592760 /// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2761 pub fn load_collection_info<Handle>(2762 collection_handle: &Handle,2763 sender: &T::CrossAccountId,2764 ) -> PropertyWriterLazyCollectionInfo<'static>2765 where2766 Handle: Deref<Target = CollectionHandle<T>>,2767 {2768 let is_collection_admin = collection_handle.is_owner_or_admin(sender);2769 let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);27702771 PropertyWriterLazyCollectionInfo {2772 is_collection_admin: LazyValue::new(move || is_collection_admin),2773 property_permissions: LazyValue::new(move || property_permissions),2774 }2775 }27762777 /// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2778 pub fn load_token_properties<Handle>(2779 collection: &Handle,2780 token_id: TokenId,2781 ) -> PropertyWriterLazyTokenInfo2782 where2783 Handle: CommonCollectionOperations<T>,2784 {2785 let stored_properties = collection2786 .get_token_properties_raw(token_id)2787 .unwrap_or_default();27882789 PropertyWriterLazyTokenInfo {2790 is_token_exist: LazyValue::new(|| true),2791 is_token_owner: LazyValue::new(|| Ok(true)),2792 stored_properties: LazyValue::new(move || stored_properties),2793 }2794 }2795}27962797#[cfg(feature = "runtime-benchmarks")]2798impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2799where2800 T: Config,2801 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2802{2803 /// A function to benchmark the writing of token properties.2804 pub fn write_token_properties(2805 &mut self,2806 token_id: TokenId,2807 properties_updates: impl Iterator<Item = Property>,2808 log: evm_coder::ethereum::Log,2809 ) -> DispatchResult {2810 let check_token_exist = || true;2811 let check_token_owner = || Ok(true);2812 let get_token_properties = TokenProperties::new;28132814 self.internal_write_token_properties(2815 token_id,2816 PropertyWriterLazyTokenInfo::new(2817 check_token_exist,2818 check_token_owner,2819 get_token_properties,2820 ),2821 properties_updates.map(|p| (p.key, Some(p.value))),2822 log,2823 )2824 }2825}28262827/// Computes the weight of writing properties to tokens.2828/// * `properties_nums` - The properties num of each created token.2829/// * `per_token_weight_weight` - The function to obtain the weight2830/// of writing properties from a token's properties num.2831pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2832 properties_nums: impl Iterator<Item = u32>,2833 per_token_weight: I,2834) -> Weight {2835 let mut weight = properties_nums2836 .filter_map(|properties_num| {2837 if properties_num > 0 {2838 Some(per_token_weight(properties_num))2839 } else {2840 None2841 }2842 })2843 .fold(Weight::zero(), |a, b| a.saturating_add(b));28442845 if !weight.is_zero() {2846 // If we are here, it means the token properties were written at least once.2847 // Because of that, some common collection data was also loaded; we must add this weight.2848 // However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.28492850 weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2851 }28522853 weight2854}28552856#[cfg(any(feature = "tests", test))]2857#[allow(missing_docs)]2858pub mod tests {2859 use crate::{Config, DispatchError, DispatchResult, LazyValue};28602861 const fn to_bool(u: u8) -> bool {2862 u != 02863 }28642865 #[derive(Debug)]2866 pub struct TestCase {2867 pub collection_admin: bool,2868 pub is_collection_admin: bool,2869 pub token_owner: bool,2870 pub is_token_owner: bool,2871 pub no_permission: bool,2872 }28732874 impl TestCase {2875 const fn new(2876 collection_admin: u8,2877 is_collection_admin: u8,2878 token_owner: u8,2879 is_token_owner: u8,2880 no_permission: u8,2881 ) -> Self {2882 Self {2883 collection_admin: to_bool(collection_admin),2884 is_collection_admin: to_bool(is_collection_admin),2885 token_owner: to_bool(token_owner),2886 is_token_owner: to_bool(is_token_owner),2887 no_permission: to_bool(no_permission),2888 }2889 }2890 }28912892 #[rustfmt::skip]2893 pub const TABLE: [TestCase; 16] = [2894 // ┌╴collection_admin2895 // │ ┌╴is_collection_admin2896 // │ │ ┌╴token_owner2897 // │ │ │ ┌╴is_token_ownership2898 // │ │ │ │ ┌╴no_permission2899 /* 0*/ TestCase::new(0, 0, 0, 0, 1),2900 /* 1*/ TestCase::new(0, 0, 0, 1, 1),2901 /* 2*/ TestCase::new(0, 0, 1, 0, 1),2902 /* 3*/ TestCase::new(0, 0, 1, 1, 0),2903 /* 4*/ TestCase::new(0, 1, 0, 0, 1),2904 /* 5*/ TestCase::new(0, 1, 0, 1, 1),2905 /* 6*/ TestCase::new(0, 1, 1, 0, 1),2906 /* 7*/ TestCase::new(0, 1, 1, 1, 0),2907 /* 8*/ TestCase::new(1, 0, 0, 0, 1),2908 /* 9*/ TestCase::new(1, 0, 0, 1, 1),2909 /* 10*/ TestCase::new(1, 0, 1, 0, 1),2910 /* 11*/ TestCase::new(1, 0, 1, 1, 0),2911 /* 12*/ TestCase::new(1, 1, 0, 0, 0),2912 /* 13*/ TestCase::new(1, 1, 0, 1, 0),2913 /* 14*/ TestCase::new(1, 1, 1, 0, 0),2914 /* 15*/ TestCase::new(1, 1, 1, 1, 0),2915 ];29162917 pub fn check_token_permissions<T: Config>(2918 collection_admin_permitted: bool,2919 token_owner_permitted: bool,2920 is_collection_admin: &mut LazyValue<bool>,2921 check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2922 check_token_existence: &mut LazyValue<bool>,2923 ) -> DispatchResult {2924 crate::check_token_permissions::<T>(2925 collection_admin_permitted,2926 token_owner_permitted,2927 is_collection_admin,2928 check_token_ownership,2929 check_token_existence,2930 )2931 }2932}pallets/foreign-assets/Cargo.tomldiffbeforeafterboth--- a/pallets/foreign-assets/Cargo.toml
+++ b/pallets/foreign-assets/Cargo.toml
@@ -12,7 +12,6 @@
frame-support = { workspace = true }
frame-system = { workspace = true }
log = { workspace = true }
-orml-tokens = { workspace = true }
pallet-balances = { features = ["insecure_zero_ed"], workspace = true }
pallet-common = { workspace = true }
pallet-fungible = { workspace = true }
@@ -30,7 +29,6 @@
"frame-support/std",
"frame-system/std",
"log/std",
- "orml-tokens/std",
"pallet-balances/std",
"pallet-common/std",
"pallet-fungible/std",
pallets/foreign-assets/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/benchmarking.rs
+++ b/pallets/foreign-assets/src/benchmarking.rs
@@ -16,88 +16,36 @@
#![allow(missing_docs)]
-use frame_benchmarking::{account, v2::*};
-use frame_support::traits::Currency;
+use frame_benchmarking::v2::*;
use frame_system::RawOrigin;
-use sp_std::{boxed::Box, vec, vec::Vec};
-use staging_xcm::{opaque::latest::Junction::Parachain, v3::Junctions::X1, VersionedMultiLocation};
+use pallet_common::benchmarking::{create_data, create_u16_data};
+use sp_std::{boxed::Box, vec};
+use staging_xcm::prelude::*;
+use up_data_structs::{MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH};
-use super::{Call, Config, Pallet};
-use crate::AssetMetadata;
+use super::{Call, Config, ForeignCollectionMode, Pallet};
-fn bounded<T: TryFrom<Vec<u8>>>(slice: &[u8]) -> T {
- T::try_from(slice.to_vec())
- .map_err(|_| "slice doesn't fit")
- .unwrap()
-}
-
#[benchmarks]
mod benchmarks {
+
use super::*;
#[benchmark]
- fn register_foreign_asset() -> Result<(), BenchmarkError> {
- let owner: T::AccountId = account("user", 0, 1);
- let location: VersionedMultiLocation = VersionedMultiLocation::from(X1(Parachain(1000)));
- let metadata: AssetMetadata<
- <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance,
- > = AssetMetadata {
- name: bounded(b"name"),
- symbol: bounded(b"symbol"),
- decimals: 18,
- minimal_balance: 1u32.into(),
- };
- let mut balance: <<T as Config>::Currency as Currency<
- <T as frame_system::Config>::AccountId,
- >>::Balance = 4_000_000_000u32.into();
- balance = balance * balance;
- <T as Config>::Currency::make_free_balance_be(&owner, balance);
+ fn force_register_foreign_asset() -> Result<(), BenchmarkError> {
+ let location =
+ MultiLocation::from(X3(Parachain(1000), PalletInstance(42), GeneralIndex(1)));
+ let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
+ let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
+ let mode = ForeignCollectionMode::NFT;
#[extrinsic_call]
_(
RawOrigin::Root,
- owner,
- Box::new(location),
- Box::new(metadata),
+ Box::new(location.into()),
+ name,
+ token_prefix,
+ mode,
);
-
- Ok(())
- }
-
- #[benchmark]
- fn update_foreign_asset() -> Result<(), BenchmarkError> {
- let owner: T::AccountId = account("user", 0, 1);
- let location: VersionedMultiLocation = VersionedMultiLocation::from(X1(Parachain(2000)));
- let metadata: AssetMetadata<
- <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance,
- > = AssetMetadata {
- name: bounded(b"name"),
- symbol: bounded(b"symbol"),
- decimals: 18,
- minimal_balance: 1u32.into(),
- };
- let metadata2: AssetMetadata<
- <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance,
- > = AssetMetadata {
- name: bounded(b"name2"),
- symbol: bounded(b"symbol2"),
- decimals: 18,
- minimal_balance: 1u32.into(),
- };
- let mut balance: <<T as Config>::Currency as Currency<
- <T as frame_system::Config>::AccountId,
- >>::Balance = 4_000_000_000u32.into();
- balance = balance * balance;
- <T as Config>::Currency::make_free_balance_be(&owner, balance);
- Pallet::<T>::register_foreign_asset(
- RawOrigin::Root.into(),
- owner,
- Box::new(location.clone()),
- Box::new(metadata),
- )?;
-
- #[extrinsic_call]
- _(RawOrigin::Root, 0, Box::new(location), Box::new(metadata2));
Ok(())
}
pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ /dev/null
@@ -1,499 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-//! Implementations for fungibles trait.
-
-use frame_support::traits::tokens::{
- DepositConsequence, Fortitude, Precision, Preservation, Provenance, WithdrawConsequence,
-};
-use frame_system::Config as SystemConfig;
-use pallet_common::{CollectionHandle, CommonCollectionOperations};
-use pallet_fungible::FungibleHandle;
-use sp_runtime::traits::{CheckedAdd, CheckedSub};
-use up_data_structs::budget;
-
-use super::*;
-
-impl<T: Config> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T>
-where
- T: orml_tokens::Config<CurrencyId = AssetId>,
- BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
- BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
- <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
- <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
-{
- type AssetId = AssetId;
- type Balance = BalanceOf<T>;
-
- fn total_issuance(asset: Self::AssetId) -> Self::Balance {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible total_issuance");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::total_issuance()
- .into()
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- )
- .into()
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => return Zero::zero(),
- };
- let collection_handle = match <CollectionHandle<T>>::try_get(target_collection_id) {
- Ok(v) => v,
- Err(_) => return Zero::zero(),
- };
- let collection = FungibleHandle::cast(collection_handle);
- Self::Balance::try_from(collection.total_supply()).unwrap_or(Zero::zero())
- }
- }
- }
-
- fn minimum_balance(asset: Self::AssetId) -> Self::Balance {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible minimum_balance");
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::minimum_balance()
- .into()
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- )
- .into()
- }
- AssetId::ForeignAssetId(fid) => AssetMetadatas::<T>::get(AssetId::ForeignAssetId(fid))
- .map(|x| x.minimal_balance)
- .unwrap_or_else(Zero::zero),
- }
- }
-
- fn balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible balance");
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who).into()
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- )
- .into()
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => return Zero::zero(),
- };
- let collection_handle = match <CollectionHandle<T>>::try_get(target_collection_id) {
- Ok(v) => v,
- Err(_) => return Zero::zero(),
- };
- let collection = FungibleHandle::cast(collection_handle);
- Self::Balance::try_from(
- collection.balance(T::CrossAccountId::from_sub(who.clone()), TokenId(0)),
- )
- .unwrap_or(Zero::zero())
- }
- }
- }
-
- fn total_balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
- Self::balance(asset, who)
- }
-
- fn reducible_balance(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- preservation: Preservation,
- fortitude: Fortitude,
- ) -> Self::Balance {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible reducible_balance");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::reducible_balance(
- who,
- preservation,
- fortitude,
- )
- .into()
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- preservation,
- fortitude,
- )
- .into()
- }
- _ => Self::balance(asset, who),
- }
- }
-
- fn can_deposit(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- provenance: Provenance,
- ) -> DepositConsequence {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_deposit");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_deposit(
- who,
- amount.into(),
- provenance,
- )
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_deposit(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- amount.into(),
- provenance,
- )
- }
- _ => {
- if amount.is_zero() {
- return DepositConsequence::Success;
- }
-
- let extential_deposit_value = T::ExistentialDeposit::get();
- let ed_value: u128 = match extential_deposit_value.try_into() {
- Ok(val) => val,
- Err(_) => return DepositConsequence::CannotCreate,
- };
- let extential_deposit: Self::Balance = match ed_value.try_into() {
- Ok(val) => val,
- Err(_) => return DepositConsequence::CannotCreate,
- };
-
- let new_total_balance = match Self::balance(asset, who).checked_add(&amount) {
- Some(x) => x,
- None => return DepositConsequence::Overflow,
- };
-
- if new_total_balance < extential_deposit {
- return DepositConsequence::BelowMinimum;
- }
-
- DepositConsequence::Success
- }
- }
- }
-
- fn can_withdraw(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- ) -> WithdrawConsequence<Self::Balance> {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_withdraw");
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return WithdrawConsequence::UnknownAsset,
- };
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return WithdrawConsequence::UnknownAsset;
- }
- };
- match <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_withdraw(
- who,
- this_amount,
- ) {
- WithdrawConsequence::BalanceLow => WithdrawConsequence::BalanceLow,
- WithdrawConsequence::WouldDie => WithdrawConsequence::WouldDie,
- WithdrawConsequence::UnknownAsset => WithdrawConsequence::UnknownAsset,
- WithdrawConsequence::Underflow => WithdrawConsequence::Underflow,
- WithdrawConsequence::Overflow => WithdrawConsequence::Overflow,
- WithdrawConsequence::Frozen => WithdrawConsequence::Frozen,
- WithdrawConsequence::Success => WithdrawConsequence::Success,
- _ => WithdrawConsequence::BalanceLow,
- }
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return WithdrawConsequence::UnknownAsset;
- }
- };
- match <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_withdraw(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- parent_amount,
- ) {
- WithdrawConsequence::BalanceLow => WithdrawConsequence::BalanceLow,
- WithdrawConsequence::WouldDie => WithdrawConsequence::WouldDie,
- WithdrawConsequence::UnknownAsset => WithdrawConsequence::UnknownAsset,
- WithdrawConsequence::Underflow => WithdrawConsequence::Underflow,
- WithdrawConsequence::Overflow => WithdrawConsequence::Overflow,
- WithdrawConsequence::Frozen => WithdrawConsequence::Frozen,
- WithdrawConsequence::Success => WithdrawConsequence::Success,
- _ => WithdrawConsequence::BalanceLow,
- }
- }
- _ => match Self::balance(asset, who).checked_sub(&amount) {
- Some(_) => WithdrawConsequence::Success,
- None => WithdrawConsequence::BalanceLow,
- },
- }
- }
-
- fn asset_exists(asset: AssetId) -> bool {
- match asset {
- AssetId::NativeAssetId(_) => true,
- AssetId::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),
- }
- }
-}
-
-impl<T: Config> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T>
-where
- T: orml_tokens::Config<CurrencyId = AssetId>,
- BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
- BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
- <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
- <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
- u128: From<BalanceOf<T>>,
-{
- fn mint_into(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- ) -> Result<BalanceOf<T>, DispatchError> {
- //Self::do_mint(asset, who, amount, None)
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible mint_into {:?}", asset);
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::mint_into(
- who,
- amount.into(),
- )
- .map(Into::into)
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::mint_into(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- amount.into(),
- )
- .map(Into::into)
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => {
- return Err(DispatchError::Other(
- "Associated collection not found for asset",
- ))
- }
- };
- let collection =
- FungibleHandle::cast(<CollectionHandle<T>>::try_get(target_collection_id)?);
- let account = T::CrossAccountId::from_sub(who.clone());
-
- let amount_data: pallet_fungible::CreateItemData<T> =
- (account.clone(), amount.into());
-
- pallet_fungible::Pallet::<T>::create_item_foreign(
- &collection,
- &account,
- amount_data,
- &budget::Value::new(0),
- )?;
-
- Ok(amount)
- }
- }
- }
-
- fn burn_from(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- precision: Precision,
- fortitude: Fortitude,
- ) -> Result<Self::Balance, DispatchError> {
- // let f = DebitFlags { keep_alive: false, best_effort: false };
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible burn_from");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::burn_from(
- who,
- amount.into(),
- precision,
- fortitude,
- )
- .map(Into::into)
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::burn_from(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- amount.into(),
- precision,
- fortitude,
- )
- .map(Into::into)
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => {
- return Err(DispatchError::Other(
- "Associated collection not found for asset",
- ))
- }
- };
- let collection =
- FungibleHandle::cast(<CollectionHandle<T>>::try_get(target_collection_id)?);
- pallet_fungible::Pallet::<T>::burn_foreign(
- &collection,
- &T::CrossAccountId::from_sub(who.clone()),
- amount.into(),
- )?;
-
- Ok(amount)
- }
- }
- }
-
- fn transfer(
- asset: Self::AssetId,
- source: &<T as SystemConfig>::AccountId,
- dest: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- preservation: Preservation,
- ) -> Result<Self::Balance, DispatchError> {
- // let f = TransferFlags { keep_alive, best_effort: false, burn_dust: false };
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible transfer");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- match <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::transfer(
- source,
- dest,
- amount.into(),
- preservation,
- ) {
- Ok(_) => Ok(amount),
- Err(_) => Err(DispatchError::Other(
- "Bad amount to relay chain value conversion",
- )),
- }
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- match <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::transfer(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- source,
- dest,
- amount.into(),
- preservation,
- ) {
- Ok(_) => Ok(amount),
- Err(e) => Err(e),
- }
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => {
- return Err(DispatchError::Other(
- "Associated collection not found for asset",
- ))
- }
- };
- let collection =
- FungibleHandle::cast(<CollectionHandle<T>>::try_get(target_collection_id)?);
-
- pallet_fungible::Pallet::<T>::transfer(
- &collection,
- &T::CrossAccountId::from_sub(source.clone()),
- &T::CrossAccountId::from_sub(dest.clone()),
- amount.into(),
- &budget::Value::new(0),
- )
- .map_err(|e| e.error)?;
-
- Ok(amount)
- }
- }
- }
-}
-
-#[cfg(not(debug_assertions))]
-extern "C" {
- // This function does not exists, thus compilation will fail, if its call is
- // not optimized away, which is only possible if it's not called at all.
- //
- // not(debug_assertions) is used to ensure compiler is dropping unused functions, as
- // this option is enabled in release by defailt
- //
- // FIXME: maybe use build.rs, to ensure it will fail even in release with debug_assertions
- // enabled?
- fn unbalanced_fungible_is_called();
-}
-macro_rules! ensure_balanced {
- () => {{
- #[cfg(debug_assertions)]
- panic!("unbalanced fungible methods should not be used");
- #[cfg(not(debug_assertions))]
- {
- unsafe { unbalanced_fungible_is_called() };
- unreachable!();
- }
- }};
-}
-
-impl<T: Config> fungibles::Unbalanced<<T as SystemConfig>::AccountId> for Pallet<T>
-where
- T: orml_tokens::Config<CurrencyId = AssetId>,
- BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
- BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
- <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
- <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
- u128: From<BalanceOf<T>>,
-{
- fn handle_dust(_dust: fungibles::Dust<<T as SystemConfig>::AccountId, Self>) {
- ensure_balanced!();
- }
- fn write_balance(
- _asset: Self::AssetId,
- _who: &<T as SystemConfig>::AccountId,
- _amount: Self::Balance,
- ) -> Result<Option<Self::Balance>, DispatchError> {
- ensure_balanced!();
- }
- fn set_total_issuance(_asset: Self::AssetId, _amount: Self::Balance) {
- ensure_balanced!();
- }
-}
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -14,113 +14,38 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-//! # Foreign assets
-//!
-//! - [`Config`]
-//! - [`Call`]
-//! - [`Pallet`]
+//! # Foreign Assets
//!
//! ## Overview
//!
-//! The foreign assests pallet provides functions for:
-//!
-//! - Local and foreign assets management. The foreign assets can be updated without runtime upgrade.
-//! - Bounds between asset and target collection for cross chain transfer and inner transfers.
-//!
-//! ## Overview
-//!
-//! Under construction
+//! The Foreign Assets is a proxy that maps XCM operations to the Unique Network's pallets logic.
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
-use frame_support::{
- dispatch::DispatchResult,
- ensure,
- pallet_prelude::*,
- traits::{fungible, fungibles, Currency, EnsureOrigin},
-};
+use core::ops::Deref;
+
+use frame_support::{dispatch::DispatchResult, pallet_prelude::*, traits::EnsureOrigin, PalletId};
use frame_system::pallet_prelude::*;
-use pallet_common::erc::CrossAccountId;
-use pallet_fungible::Pallet as PalletFungible;
-use scale_info::TypeInfo;
-use serde::{Deserialize, Serialize};
-use sp_runtime::{
- traits::{One, Zero},
- ArithmeticError,
+use pallet_common::{
+ dispatch::CollectionDispatch, erc::CrossAccountId, XcmExtensions, NATIVE_FUNGIBLE_COLLECTION_ID,
};
-use sp_std::{boxed::Box, vec::Vec};
-use staging_xcm::{latest::MultiLocation, VersionedMultiLocation};
-// NOTE: MultiLocation is used in storages, we will need to do migration if upgrade the
-// MultiLocation to the XCM v3.
+use sp_runtime::traits::AccountIdConversion;
+use sp_std::{boxed::Box, vec, vec::Vec};
use staging_xcm::{
opaque::latest::{prelude::XcmError, Weight},
- v3::XcmContext,
+ v3::{prelude::*, MultiAsset, XcmContext},
+ VersionedAssetId,
};
-use staging_xcm_executor::{traits::WeightTrader, Assets};
-use up_data_structs::{CollectionId, CollectionMode, CreateCollectionData, TokenId};
-
-// TODO: Move to primitives
-// Id of native currency.
-// 0 - QTZ\UNQ
-// 1 - KSM\DOT
-#[derive(
- Clone,
- Copy,
- Eq,
- PartialEq,
- PartialOrd,
- Ord,
- MaxEncodedLen,
- RuntimeDebug,
- Encode,
- Decode,
- TypeInfo,
- Serialize,
- Deserialize,
-)]
-pub enum NativeCurrency {
- Here = 0,
- Parent = 1,
-}
-
-#[derive(
- Clone,
- Copy,
- Eq,
- PartialEq,
- PartialOrd,
- Ord,
- MaxEncodedLen,
- RuntimeDebug,
- Encode,
- Decode,
- TypeInfo,
- Serialize,
- Deserialize,
-)]
-pub enum AssetId {
- ForeignAssetId(ForeignAssetId),
- NativeAssetId(NativeCurrency),
-}
-
-pub trait TryAsForeign<T, F> {
- fn try_as_foreign(asset: T) -> Option<F>;
-}
-
-impl TryAsForeign<AssetId, ForeignAssetId> for AssetId {
- fn try_as_foreign(asset: AssetId) -> Option<ForeignAssetId> {
- match asset {
- Self::ForeignAssetId(id) => Some(id),
- _ => None,
- }
- }
-}
-
-pub type ForeignAssetId = u32;
-pub type CurrencyId = AssetId;
+use staging_xcm_executor::{
+ traits::{ConvertLocation, Error as XcmExecutorError, TransactAsset, WeightTrader},
+ Assets,
+};
+use up_data_structs::{
+ budget::ZeroBudget, CollectionId, CollectionMode, CollectionName, CollectionTokenPrefix,
+ CreateCollectionData, CreateFungibleData, CreateItemData, TokenId,
+};
-mod impl_fungibles;
pub mod weights;
#[cfg(feature = "runtime-benchmarks")]
@@ -128,44 +53,12 @@
pub use module::*;
pub use weights::WeightInfo;
-
-/// Type alias for currency balance.
-pub type BalanceOf<T> =
- <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
-
-/// A mapping between ForeignAssetId and AssetMetadata.
-pub trait AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata> {
- /// Returns the AssetMetadata associated with a given ForeignAssetId.
- fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata>;
- /// Returns the MultiLocation associated with a given ForeignAssetId.
- fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation>;
- /// Returns the CurrencyId associated with a given MultiLocation.
- fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId>;
-}
-
-pub struct XcmForeignAssetIdMapping<T>(sp_std::marker::PhantomData<T>);
-
-impl<T: Config> AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata<BalanceOf<T>>>
- for XcmForeignAssetIdMapping<T>
-{
- fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {
- log::trace!(target: "fassets::asset_metadatas", "call");
- Pallet::<T>::asset_metadatas(AssetId::ForeignAssetId(foreign_asset_id))
- }
-
- fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {
- log::trace!(target: "fassets::get_multi_location", "call");
- Pallet::<T>::foreign_asset_locations(foreign_asset_id)
- }
-
- fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
- log::trace!(target: "fassets::get_currency_id", "call");
- Pallet::<T>::location_to_currency_ids(multi_location).map(AssetId::ForeignAssetId)
- }
-}
#[frame_support::pallet]
pub mod module {
+ use pallet_common::CollectionIssuer;
+ use up_data_structs::CollectionDescription;
+
use super::*;
#[pallet::config]
@@ -173,44 +66,34 @@
frame_system::Config
+ pallet_common::Config
+ pallet_fungible::Config
- + orml_tokens::Config
+ pallet_balances::Config
{
/// The overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
- /// Currency type for withdraw and balance storage.
- type Currency: Currency<Self::AccountId>;
+ /// Origin for force registering of a foreign asset.
+ type ForceRegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;
- /// Required origin for registering asset.
- type RegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;
+ /// The ID of the foreign assets pallet.
+ type PalletId: Get<PalletId>;
+
+ /// Self-location of this parachain.
+ type SelfLocation: Get<MultiLocation>;
+
+ /// The converter from a MultiLocation to a CrossAccountId.
+ type LocationToAccountId: ConvertLocation<Self::CrossAccountId>;
/// Weight information for the extrinsics in this module.
type WeightInfo: WeightInfo;
- }
-
- pub type AssetName = BoundedVec<u8, ConstU32<32>>;
- pub type AssetSymbol = BoundedVec<u8, ConstU32<7>>;
-
- #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]
- pub struct AssetMetadata<Balance> {
- pub name: AssetName,
- pub symbol: AssetSymbol,
- pub decimals: u8,
- pub minimal_balance: Balance,
}
#[pallet::error]
pub enum Error<T> {
- /// The given location could not be used (e.g. because it cannot be expressed in the
- /// desired version of XCM).
- BadLocation,
- /// MultiLocation existed
- MultiLocationExisted,
- /// AssetId not exists
- AssetIdNotExists,
- /// AssetId exists
- AssetIdExisted,
+ /// The foreign asset is already registered.
+ ForeignAssetAlreadyRegistered,
+
+ /// The given asset ID could not be converted into the current XCM version.
+ BadForeignAssetId,
}
#[pallet::event]
@@ -218,64 +101,46 @@
pub enum Event<T: Config> {
/// The foreign asset registered.
ForeignAssetRegistered {
- asset_id: ForeignAssetId,
- asset_address: MultiLocation,
- metadata: AssetMetadata<BalanceOf<T>>,
- },
- /// The foreign asset updated.
- ForeignAssetUpdated {
- asset_id: ForeignAssetId,
- asset_address: MultiLocation,
- metadata: AssetMetadata<BalanceOf<T>>,
- },
- /// The asset registered.
- AssetRegistered {
- asset_id: AssetId,
- metadata: AssetMetadata<BalanceOf<T>>,
- },
- /// The asset updated.
- AssetUpdated {
- asset_id: AssetId,
- metadata: AssetMetadata<BalanceOf<T>>,
+ collection_id: CollectionId,
+ asset_id: Box<VersionedAssetId>,
},
}
- /// Next available Foreign AssetId ID.
- ///
- /// NextForeignAssetId: ForeignAssetId
+ /// The corresponding collections of foreign assets.
#[pallet::storage]
- #[pallet::getter(fn next_foreign_asset_id)]
- pub type NextForeignAssetId<T: Config> = StorageValue<_, ForeignAssetId, ValueQuery>;
- /// The storages for MultiLocations.
- ///
- /// ForeignAssetLocations: map ForeignAssetId => Option<MultiLocation>
- #[pallet::storage]
- #[pallet::getter(fn foreign_asset_locations)]
- pub type ForeignAssetLocations<T: Config> =
- StorageMap<_, Twox64Concat, ForeignAssetId, staging_xcm::v3::MultiLocation, OptionQuery>;
+ #[pallet::getter(fn foreign_asset_to_collection)]
+ pub type ForeignAssetToCollection<T: Config> =
+ StorageMap<_, Twox64Concat, staging_xcm::v3::AssetId, CollectionId, OptionQuery>;
- /// The storages for CurrencyIds.
- ///
- /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>
+ /// The corresponding foreign assets of collections.
#[pallet::storage]
- #[pallet::getter(fn location_to_currency_ids)]
- pub type LocationToCurrencyIds<T: Config> =
- StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;
+ #[pallet::getter(fn collection_to_foreign_asset)]
+ pub type CollectionToForeignAsset<T: Config> =
+ StorageMap<_, Twox64Concat, CollectionId, staging_xcm::v3::AssetId, OptionQuery>;
- /// The storages for AssetMetadatas.
- ///
- /// AssetMetadatas: map AssetIds => Option<AssetMetadata>
+ /// The correponding NFT token id of reserve NFTs
#[pallet::storage]
- #[pallet::getter(fn asset_metadatas)]
- pub type AssetMetadatas<T: Config> =
- StorageMap<_, Twox64Concat, AssetId, AssetMetadata<BalanceOf<T>>, OptionQuery>;
+ #[pallet::getter(fn foreign_reserve_asset_instance_to_token_id)]
+ pub type ForeignReserveAssetInstanceToTokenId<T: Config> = StorageDoubleMap<
+ Hasher1 = Twox64Concat,
+ Key1 = CollectionId,
+ Hasher2 = Blake2_128Concat,
+ Key2 = staging_xcm::v3::AssetInstance,
+ Value = TokenId,
+ QueryKind = OptionQuery,
+ >;
- /// The storages for assets to fungible collection binding
- ///
+ /// The correponding reserve NFT of a token ID
#[pallet::storage]
- #[pallet::getter(fn asset_binding)]
- pub type AssetBinding<T: Config> =
- StorageMap<_, Twox64Concat, ForeignAssetId, CollectionId, OptionQuery>;
+ #[pallet::getter(fn token_id_to_foreign_reserve_asset_instance)]
+ pub type TokenIdToForeignReserveAssetInstance<T: Config> = StorageDoubleMap<
+ Hasher1 = Twox64Concat,
+ Key1 = CollectionId,
+ Hasher2 = Blake2_128Concat,
+ Key2 = TokenId,
+ Value = staging_xcm::v3::AssetInstance,
+ QueryKind = OptionQuery,
+ >;
#[pallet::pallet]
pub struct Pallet<T>(_);
@@ -284,196 +149,432 @@
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::register_foreign_asset())]
- pub fn register_foreign_asset(
+ pub fn force_register_foreign_asset(
origin: OriginFor<T>,
- owner: T::AccountId,
- location: Box<VersionedMultiLocation>,
- metadata: Box<AssetMetadata<BalanceOf<T>>>,
+ versioned_asset_id: Box<VersionedAssetId>,
+ name: CollectionName,
+ token_prefix: CollectionTokenPrefix,
+ mode: ForeignCollectionMode,
) -> DispatchResult {
- T::RegisterOrigin::ensure_origin(origin.clone())?;
+ T::ForceRegisterOrigin::ensure_origin(origin.clone())?;
- let location: MultiLocation = (*location)
+ let asset_id: AssetId = versioned_asset_id
+ .as_ref()
+ .clone()
.try_into()
- .map_err(|()| Error::<T>::BadLocation)?;
+ .map_err(|()| Error::<T>::BadForeignAssetId)?;
- let md = metadata.clone();
- let name: Vec<u16> = md.name.into_iter().map(|x| x as u16).collect::<Vec<u16>>();
- let mut description: Vec<u16> = "Foreign assets collection for "
+ ensure!(
+ !<ForeignAssetToCollection<T>>::contains_key(asset_id),
+ <Error<T>>::ForeignAssetAlreadyRegistered,
+ );
+
+ let foreign_collection_owner = Self::pallet_account();
+
+ let description: CollectionDescription = "Foreign Assets Collection"
.encode_utf16()
- .collect::<Vec<u16>>();
- description.append(&mut name.clone());
+ .collect::<Vec<_>>()
+ .try_into()
+ .expect("description length < max description length; qed");
+
+ let collection_id = T::CollectionDispatch::create(
+ foreign_collection_owner,
+ CollectionIssuer::Internals,
+ CreateCollectionData {
+ name,
+ token_prefix,
+ description,
+ mode: mode.into(),
+ ..Default::default()
+ },
+ )?;
- let data: CreateCollectionData<T::CrossAccountId> = CreateCollectionData {
- name: name.try_into().unwrap(),
- description: description.try_into().unwrap(),
- mode: CollectionMode::Fungible(md.decimals),
- ..Default::default()
- };
- let owner = T::CrossAccountId::from_sub(owner);
- let bounded_collection_id =
- <PalletFungible<T>>::init_foreign_collection(owner.clone(), owner, data)?;
- let foreign_asset_id =
- Self::do_register_foreign_asset(&location, &metadata, bounded_collection_id)?;
+ <ForeignAssetToCollection<T>>::insert(asset_id, collection_id);
+ <CollectionToForeignAsset<T>>::insert(collection_id, asset_id);
Self::deposit_event(Event::<T>::ForeignAssetRegistered {
- asset_id: foreign_asset_id,
- asset_address: location,
- metadata: *metadata,
+ collection_id,
+ asset_id: versioned_asset_id,
});
- Ok(())
- }
-
- #[pallet::call_index(1)]
- #[pallet::weight(<T as Config>::WeightInfo::update_foreign_asset())]
- pub fn update_foreign_asset(
- origin: OriginFor<T>,
- foreign_asset_id: ForeignAssetId,
- location: Box<VersionedMultiLocation>,
- metadata: Box<AssetMetadata<BalanceOf<T>>>,
- ) -> DispatchResult {
- T::RegisterOrigin::ensure_origin(origin)?;
-
- let location: MultiLocation = (*location)
- .try_into()
- .map_err(|()| Error::<T>::BadLocation)?;
- Self::do_update_foreign_asset(foreign_asset_id, &location, &metadata)?;
- Self::deposit_event(Event::<T>::ForeignAssetUpdated {
- asset_id: foreign_asset_id,
- asset_address: location,
- metadata: *metadata,
- });
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
- fn get_next_foreign_asset_id() -> Result<ForeignAssetId, DispatchError> {
- NextForeignAssetId::<T>::try_mutate(|current| -> Result<ForeignAssetId, DispatchError> {
- let id = *current;
- *current = current
- .checked_add(One::one())
- .ok_or(ArithmeticError::Overflow)?;
- Ok(id)
- })
+ fn pallet_account() -> T::CrossAccountId {
+ let owner: T::AccountId = T::PalletId::get().into_account_truncating();
+ T::CrossAccountId::from_sub(owner)
}
- fn do_register_foreign_asset(
- location: &MultiLocation,
- metadata: &AssetMetadata<BalanceOf<T>>,
- bounded_collection_id: CollectionId,
- ) -> Result<ForeignAssetId, DispatchError> {
- let foreign_asset_id = Self::get_next_foreign_asset_id()?;
- LocationToCurrencyIds::<T>::try_mutate(location, |maybe_currency_ids| -> DispatchResult {
- ensure!(
- maybe_currency_ids.is_none(),
- Error::<T>::MultiLocationExisted
- );
- *maybe_currency_ids = Some(foreign_asset_id);
- // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));
+ /// Converts a concrete asset ID (the asset multilocation) to a local collection on Unique Network.
+ ///
+ /// The multilocation corresponds to a local collection if:
+ /// * It is `Here` location that corresponds to the native token of this parachain.
+ /// * It is `../Parachain(<Unique Network Para ID>)` that also corresponds to the native token of this parachain.
+ /// * It is `../Parachain(<Unique Network Para ID>)/GeneralIndex(<Collection ID>)` that corresponds
+ /// to the collection with the ID equal to `<Collection ID>`. The `<Collection ID>` must be in the valid range,
+ /// otherwise `None` is returned.
+ /// * It is `GeneralIndex(<Collection ID>)`. Same as the last one above.
+ ///
+ /// If the multilocation doesn't match the patterns listed above,
+ /// or the `<Collection ID>` points to a foreign collection,
+ /// `None` is returned, identifying that the given multilocation doesn't correspond to a local collection.
+ fn local_asset_id_to_collection(asset_id: &AssetId) -> Option<CollectionLocality> {
+ let AssetId::Concrete(asset_location) = asset_id else {
+ return None;
+ };
- ForeignAssetLocations::<T>::try_mutate(
- foreign_asset_id,
- |maybe_location| -> DispatchResult {
- ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);
- *maybe_location = Some(*location);
+ let self_location = T::SelfLocation::get();
- AssetMetadatas::<T>::try_mutate(
- AssetId::ForeignAssetId(foreign_asset_id),
- |maybe_asset_metadatas| -> DispatchResult {
- ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);
- *maybe_asset_metadatas = Some(metadata.clone());
- Ok(())
- },
- )
- },
- )?;
+ if *asset_location == Here.into() || *asset_location == self_location {
+ return Some(CollectionLocality::Local(NATIVE_FUNGIBLE_COLLECTION_ID));
+ }
+
+ let prefix = if asset_location.parents == 0 {
+ &Here
+ } else if asset_location.parents == self_location.parents {
+ &self_location.interior
+ } else {
+ return None;
+ };
+
+ let GeneralIndex(collection_id) = asset_location.interior.match_and_split(prefix)? else {
+ return None;
+ };
- AssetBinding::<T>::try_mutate(foreign_asset_id, |collection_id| -> DispatchResult {
- *collection_id = Some(bounded_collection_id);
- Ok(())
- })
- })?;
+ let collection_id = CollectionId((*collection_id).try_into().ok()?);
- Ok(foreign_asset_id)
+ Self::collection_to_foreign_asset(collection_id)
+ .is_none()
+ .then_some(CollectionLocality::Local(collection_id))
+ }
+
+ /// Converts an asset ID to a Unique Network's collection locality (either foreign or a local one).
+ ///
+ /// The function will check if the asset's reserve location has the corresponding
+ /// foreign collection on Unique Network,
+ /// and will return the "foreign" locality containing the collection ID if found.
+ ///
+ /// If no corresponding foreign collection is found, the function will check
+ /// if the asset's reserve location corresponds to a local collection.
+ /// If the local collection is found, the "local" locality with the collection ID is returned.
+ ///
+ /// If all of the above have failed, the `AssetIdConversionFailed` error will be returned.
+ fn asset_to_collection(asset_id: &AssetId) -> Result<CollectionLocality, XcmError> {
+ Self::foreign_asset_to_collection(asset_id)
+ .map(CollectionLocality::Foreign)
+ .or_else(|| Self::local_asset_id_to_collection(asset_id))
+ .ok_or_else(|| XcmExecutorError::AssetIdConversionFailed.into())
}
- fn do_update_foreign_asset(
- foreign_asset_id: ForeignAssetId,
- location: &MultiLocation,
- metadata: &AssetMetadata<BalanceOf<T>>,
+ /// Converts an XCM asset instance of local collection to the Unique Network's token ID.
+ ///
+ /// The asset instance corresponds to the Unique Network's token ID if it is in the following format:
+ /// `AssetInstance::Index(<token ID>)`.
+ ///
+ /// If the asset instance is not in the valid format or the `<token ID>` can't fit into the valid token ID,
+ /// `None` will be returned.
+ ///
+ /// Note: this function can return `Some` containing the token ID of a non-existing NFT.
+ /// It returns `None` when it failed to convert the `asset_instance` to a local ID.
+ fn local_asset_instance_to_token_id(asset_instance: &AssetInstance) -> Option<TokenId> {
+ match asset_instance {
+ AssetInstance::Index(token_id) => Some(TokenId((*token_id).try_into().ok()?)),
+ _ => None,
+ }
+ }
+
+ /// Obtains the token ID of the `asset_instance` in the collection.
+ ///
+ /// Note: this function can return `Some` containing the token ID of a non-existing NFT.
+ /// It returns `None` when it failed to convert the `asset_instance` to a local ID.
+ fn asset_instance_to_token_id(
+ collection_locality: CollectionLocality,
+ asset_instance: &AssetInstance,
+ ) -> Option<TokenId> {
+ match collection_locality {
+ CollectionLocality::Local(_) => Self::local_asset_instance_to_token_id(asset_instance),
+ CollectionLocality::Foreign(collection_id) => {
+ Self::foreign_reserve_asset_instance_to_token_id(collection_id, asset_instance)
+ }
+ }
+ }
+
+ /// Creates a foreign item in the the collection.
+ fn create_foreign_asset_instance(
+ xcm_ext: &dyn XcmExtensions<T>,
+ collection_id: CollectionId,
+ asset_instance: &AssetInstance,
+ to: T::CrossAccountId,
) -> DispatchResult {
- ForeignAssetLocations::<T>::try_mutate(
- foreign_asset_id,
- |maybe_multi_locations| -> DispatchResult {
- let old_multi_locations = maybe_multi_locations
- .as_mut()
- .ok_or(Error::<T>::AssetIdNotExists)?;
+ let derivative_token_id = xcm_ext.create_item(
+ &Self::pallet_account(),
+ to,
+ CreateItemData::NFT(Default::default()),
+ &ZeroBudget,
+ )?;
+
+ <ForeignReserveAssetInstanceToTokenId<T>>::insert(
+ collection_id,
+ asset_instance,
+ derivative_token_id,
+ );
+
+ <TokenIdToForeignReserveAssetInstance<T>>::insert(
+ collection_id,
+ derivative_token_id,
+ asset_instance,
+ );
+
+ Ok(())
+ }
+
+ /// Deposits an asset instance to the `to` account.
+ ///
+ /// Either transfers an existing item from the pallet's account
+ /// or creates a foreign item.
+ fn deposit_asset_instance(
+ xcm_ext: &dyn XcmExtensions<T>,
+ collection_locality: CollectionLocality,
+ asset_instance: &AssetInstance,
+ to: T::CrossAccountId,
+ ) -> XcmResult {
+ let token_id = Self::asset_instance_to_token_id(collection_locality, asset_instance);
+
+ let deposit_result = match (collection_locality, token_id) {
+ (_, Some(token_id)) => {
+ let depositor = &Self::pallet_account();
+ let from = depositor;
+ let amount = 1;
+
+ xcm_ext.transfer_item(depositor, from, &to, token_id, amount, &ZeroBudget)
+ }
+ (CollectionLocality::Foreign(collection_id), None) => {
+ Self::create_foreign_asset_instance(xcm_ext, collection_id, asset_instance, to)
+ }
+ (CollectionLocality::Local(_), None) => {
+ return Err(XcmExecutorError::InstanceConversionFailed.into());
+ }
+ };
+
+ deposit_result
+ .map_err(|_| XcmError::FailedToTransactAsset("non-fungible item deposit failed"))
+ }
- AssetMetadatas::<T>::try_mutate(
- AssetId::ForeignAssetId(foreign_asset_id),
- |maybe_asset_metadatas| -> DispatchResult {
- ensure!(
- maybe_asset_metadatas.is_some(),
- Error::<T>::AssetIdNotExists
- );
+ /// Withdraws an asset instance from the `from` account.
+ ///
+ /// Transfers the asset instance to the pallet's account.
+ fn withdraw_asset_instance(
+ xcm_ext: &dyn XcmExtensions<T>,
+ collection_locality: CollectionLocality,
+ asset_instance: &AssetInstance,
+ from: T::CrossAccountId,
+ ) -> XcmResult {
+ let token_id = Self::asset_instance_to_token_id(collection_locality, asset_instance)
+ .ok_or(XcmExecutorError::InstanceConversionFailed)?;
+
+ let depositor = &from;
+ let to = Self::pallet_account();
+ let amount = 1;
+ xcm_ext
+ .transfer_item(depositor, &from, &to, token_id, amount, &ZeroBudget)
+ .map_err(|_| XcmError::FailedToTransactAsset("non-fungible item withdraw failed"))?;
+
+ Ok(())
+ }
+}
+
+impl<T: Config> TransactAsset for Pallet<T> {
+ fn can_check_in(
+ _origin: &MultiLocation,
+ _what: &MultiAsset,
+ _context: &XcmContext,
+ ) -> XcmResult {
+ Err(XcmError::Unimplemented)
+ }
+
+ fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
+
+ fn can_check_out(
+ _dest: &MultiLocation,
+ _what: &MultiAsset,
+ _context: &XcmContext,
+ ) -> XcmResult {
+ Err(XcmError::Unimplemented)
+ }
+
+ fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
+
+ fn deposit_asset(
+ what: &MultiAsset,
+ to: &MultiLocation,
+ _context: Option<&XcmContext>,
+ ) -> XcmResult {
+ let to = T::LocationToAccountId::convert_location(to)
+ .ok_or(XcmExecutorError::AccountIdConversionFailed)?;
+
+ let collection_locality = Self::asset_to_collection(&what.id)?;
+ let dispatch = T::CollectionDispatch::dispatch(*collection_locality)
+ .map_err(|_| XcmExecutorError::AssetIdConversionFailed)?;
+
+ let collection = dispatch.as_dyn();
+ let xcm_ext = collection.xcm_extensions().ok_or(XcmError::Unimplemented)?;
- // modify location
- if location != old_multi_locations {
- LocationToCurrencyIds::<T>::remove(*old_multi_locations);
- LocationToCurrencyIds::<T>::try_mutate(
- location,
- |maybe_currency_ids| -> DispatchResult {
- ensure!(
- maybe_currency_ids.is_none(),
- Error::<T>::MultiLocationExisted
- );
- // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));
- *maybe_currency_ids = Some(foreign_asset_id);
- Ok(())
- },
- )?;
- }
- *maybe_asset_metadatas = Some(metadata.clone());
- *old_multi_locations = *location;
- Ok(())
- },
+ match what.fun {
+ Fungibility::Fungible(amount) => xcm_ext
+ .create_item(
+ &Self::pallet_account(),
+ to,
+ CreateItemData::Fungible(CreateFungibleData { value: amount }),
+ &ZeroBudget,
)
- },
- )
+ .map(|_| ())
+ .map_err(|_| XcmError::FailedToTransactAsset("fungible item deposit failed")),
+
+ Fungibility::NonFungible(asset_instance) => {
+ Self::deposit_asset_instance(xcm_ext, collection_locality, &asset_instance, to)
+ }
+ }
+ }
+
+ fn withdraw_asset(
+ what: &MultiAsset,
+ from: &MultiLocation,
+ _maybe_context: Option<&XcmContext>,
+ ) -> Result<staging_xcm_executor::Assets, XcmError> {
+ let from = T::LocationToAccountId::convert_location(from)
+ .ok_or(XcmExecutorError::AccountIdConversionFailed)?;
+
+ let collection_locality = Self::asset_to_collection(&what.id)?;
+ let dispatch = T::CollectionDispatch::dispatch(*collection_locality)
+ .map_err(|_| XcmExecutorError::AssetIdConversionFailed)?;
+
+ let collection = dispatch.as_dyn();
+ let xcm_ext = collection.xcm_extensions().ok_or(XcmError::NoPermission)?;
+
+ match what.fun {
+ Fungibility::Fungible(amount) => xcm_ext
+ .burn_item(from, TokenId::default(), amount)
+ .map_err(|_| XcmError::FailedToTransactAsset("fungible item withdraw failed"))?,
+
+ Fungibility::NonFungible(asset_instance) => {
+ Self::withdraw_asset_instance(xcm_ext, collection_locality, &asset_instance, from)?;
+ }
+ }
+
+ Ok(what.clone().into())
+ }
+
+ fn internal_transfer_asset(
+ what: &MultiAsset,
+ from: &MultiLocation,
+ to: &MultiLocation,
+ _context: &XcmContext,
+ ) -> Result<staging_xcm_executor::Assets, XcmError> {
+ let from = T::LocationToAccountId::convert_location(from)
+ .ok_or(XcmExecutorError::AccountIdConversionFailed)?;
+
+ let to = T::LocationToAccountId::convert_location(to)
+ .ok_or(XcmExecutorError::AccountIdConversionFailed)?;
+
+ let collection_locality = Self::asset_to_collection(&what.id)?;
+
+ let dispatch = T::CollectionDispatch::dispatch(*collection_locality)
+ .map_err(|_| XcmExecutorError::AssetIdConversionFailed)?;
+ let collection = dispatch.as_dyn();
+ let xcm_ext = collection.xcm_extensions().ok_or(XcmError::NoPermission)?;
+
+ let depositor = &from;
+
+ let token_id;
+ let amount;
+ let map_error: fn(DispatchError) -> XcmError;
+
+ match what.fun {
+ Fungibility::Fungible(fungible_amount) => {
+ token_id = TokenId::default();
+ amount = fungible_amount;
+ map_error = |_| XcmError::FailedToTransactAsset("fungible item transfer failed");
+ }
+
+ Fungibility::NonFungible(asset_instance) => {
+ token_id = Self::asset_instance_to_token_id(collection_locality, &asset_instance)
+ .ok_or(XcmExecutorError::InstanceConversionFailed)?;
+
+ amount = 1;
+ map_error = |_| XcmError::FailedToTransactAsset("non-fungible item transfer failed")
+ }
+ }
+
+ xcm_ext
+ .transfer_item(depositor, &from, &to, token_id, amount, &ZeroBudget)
+ .map_err(map_error)?;
+
+ Ok(what.clone().into())
}
}
-pub use frame_support::{
- traits::{
- fungibles::Balanced, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT,
- },
- weights::{WeightToFee, WeightToFeePolynomial},
-};
+#[derive(Clone, Copy)]
+pub enum CollectionLocality {
+ Local(CollectionId),
+ Foreign(CollectionId),
+}
+
+impl Deref for CollectionLocality {
+ type Target = CollectionId;
-pub struct FreeForAll<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
->(
- Weight,
- Currency::Balance,
- PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,
-);
+ fn deref(&self) -> &Self::Target {
+ match self {
+ Self::Local(id) => id,
+ Self::Foreign(id) => id,
+ }
+ }
+}
-impl<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
- > WeightTrader for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
+pub struct CurrencyIdConvert<T: Config>(PhantomData<T>);
+impl<T: Config> sp_runtime::traits::Convert<CollectionId, Option<MultiLocation>>
+ for CurrencyIdConvert<T>
{
+ fn convert(collection_id: CollectionId) -> Option<MultiLocation> {
+ if collection_id == NATIVE_FUNGIBLE_COLLECTION_ID {
+ Some(T::SelfLocation::get())
+ } else {
+ <Pallet<T>>::collection_to_foreign_asset(collection_id)
+ .and_then(|asset_id| match asset_id {
+ AssetId::Concrete(location) => Some(location),
+ _ => None,
+ })
+ .or_else(|| {
+ T::SelfLocation::get()
+ .pushed_with_interior(GeneralIndex(collection_id.0.into()))
+ .ok()
+ })
+ }
+ }
+}
+
+#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
+pub enum ForeignCollectionMode {
+ NFT,
+ Fungible(u8),
+}
+
+impl From<ForeignCollectionMode> for CollectionMode {
+ fn from(value: ForeignCollectionMode) -> Self {
+ match value {
+ ForeignCollectionMode::NFT => Self::NFT,
+ ForeignCollectionMode::Fungible(decimals) => Self::Fungible(decimals),
+ }
+ }
+}
+
+pub struct FreeForAll;
+
+impl WeightTrader for FreeForAll {
fn new() -> Self {
- Self(Weight::default(), Zero::zero(), PhantomData)
+ Self
}
fn buy_weight(
@@ -484,17 +585,5 @@
) -> Result<Assets, XcmError> {
log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);
Ok(payment)
- }
-}
-impl<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced> Drop
- for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
-where
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
-{
- fn drop(&mut self) {
- OnUnbalanced::on_unbalanced(Currency::issue(self.1));
}
}
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -15,7 +15,9 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use frame_benchmarking::{account, v2::*};
-use pallet_common::{bench_init, benchmarking::create_collection_raw};
+use pallet_common::{
+ bench_init, benchmarking::create_collection_raw, CollectionIssuer, Pallet as PalletCommon,
+};
use sp_std::prelude::*;
use up_data_structs::{budget::Unlimited, CollectionMode, MAX_ITEMS_PER_BATCH};
@@ -30,7 +32,9 @@
create_collection_raw(
owner,
CollectionMode::Fungible(0),
- |owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
+ |owner: T::CrossAccountId, data| {
+ <PalletCommon<T>>::init_collection(owner.clone(), CollectionIssuer::User(owner), data)
+ },
FungibleHandle::cast,
)
}
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -19,7 +19,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use pallet_common::{
weights::WeightInfo as _, with_weight, CommonCollectionOperations, CommonWeightInfo,
- Error as CommonError, RefungibleExtensions, SelfWeightOf as PalletCommonWeightOf,
+ Error as CommonError, SelfWeightOf as PalletCommonWeightOf, XcmExtensions,
};
use sp_runtime::{ArithmeticError, DispatchError};
use sp_std::{vec, vec::Vec};
@@ -114,7 +114,7 @@
<Pallet<T>>::create_item(self, &sender, (to, fungible_data.value), nesting_budget),
<CommonWeights<T>>::create_item(&data),
),
- _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ _ => fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
}
}
@@ -133,7 +133,7 @@
.checked_add(data.value)
.ok_or(ArithmeticError::Overflow)?;
}
- _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ _ => fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
}
}
@@ -152,7 +152,7 @@
let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
let data = match data {
up_data_structs::CreateItemExData::Fungible(f) => f,
- _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ _ => fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
};
with_weight(
@@ -426,10 +426,6 @@
return 0;
}
<Allowance<T>>::get((self.id, sender, spender))
- }
-
- fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {
- None
}
fn total_pieces(&self, token: TokenId) -> Option<u128> {
@@ -439,6 +435,10 @@
<TotalSupply<T>>::try_get(self.id).ok()
}
+ fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {
+ Some(self)
+ }
+
fn set_allowance_for_all(
&self,
_owner: T::CrossAccountId,
@@ -457,3 +457,57 @@
fail!(<Error<T>>::FungibleTokensAreAlwaysValid)
}
}
+
+impl<T: Config> XcmExtensions<T> for FungibleHandle<T> {
+ fn create_item_internal(
+ &self,
+ depositor: &<T>::CrossAccountId,
+ to: <T>::CrossAccountId,
+ data: CreateItemData,
+ nesting_budget: &dyn Budget,
+ ) -> Result<TokenId, sp_runtime::DispatchError> {
+ match &data {
+ up_data_structs::CreateItemData::Fungible(fungible_data) => {
+ <Pallet<T>>::create_multiple_items(
+ self,
+ depositor,
+ [(to, fungible_data.value)].into_iter().collect(),
+ nesting_budget,
+ )?
+ }
+ _ => fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ }
+
+ Ok(TokenId::default())
+ }
+
+ fn transfer_item_internal(
+ &self,
+ depositor: &<T>::CrossAccountId,
+ from: &<T>::CrossAccountId,
+ to: &<T>::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ nesting_budget: &dyn Budget,
+ ) -> sp_runtime::DispatchResult {
+ ensure!(
+ token == TokenId::default(),
+ <CommonError<T>>::FungibleItemsHaveNoId
+ );
+
+ <Pallet<T>>::transfer_internal(self, depositor, from, to, amount, nesting_budget)
+ .map(|_| ())
+ .map_err(|post_info| post_info.error)
+ }
+
+ fn burn_item_internal(
+ &self,
+ from: <T>::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> sp_runtime::DispatchResult {
+ <Self as CommonCollectionOperations<T>>::burn_item(self, from, token, amount)
+ .map(|_| ())
+ .map_err(|post_info| post_info.error)
+ }
+}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -95,8 +95,8 @@
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
use sp_std::{collections::btree_map::BTreeMap, vec::Vec};
use up_data_structs::{
- budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId, CreateCollectionData,
- Property, PropertyKey, TokenId,
+ budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId, Property, PropertyKey,
+ TokenId,
};
use weights::WeightInfo;
@@ -121,8 +121,6 @@
#[pallet::error]
pub enum Error<T> {
- /// Not Fungible item data used to mint in Fungible collection.
- NotFungibleDataUsedToMintFungibleCollectionToken,
/// Tried to set data for fungible item.
FungibleItemsDontHaveData,
/// Fungible token does not support nesting.
@@ -212,24 +210,6 @@
/// Pallet implementation for fungible assets
impl<T: Config> Pallet<T> {
- /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.
- pub fn init_collection(
- owner: T::CrossAccountId,
- payer: T::CrossAccountId,
- data: CreateCollectionData<T::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data)
- }
-
- /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
- pub fn init_foreign_collection(
- owner: T::CrossAccountId,
- payer: T::CrossAccountId,
- data: CreateCollectionData<T::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_foreign_collection(owner, payer, data)
- }
-
/// Destroys a collection.
pub fn destroy_collection(
collection: FungibleHandle<T>,
@@ -293,54 +273,11 @@
let balance = <Balance<T>>::get((collection.id, owner))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
-
- // Foreign collection check
- ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);
if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(owner)?;
- }
-
- // =========
-
- if balance == 0 {
- <Balance<T>>::remove((collection.id, owner));
- <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());
- } else {
- <Balance<T>>::insert((collection.id, owner), balance);
}
- <TotalSupply<T>>::insert(collection.id, total_supply);
-
- <PalletEvm<T>>::deposit_log(
- ERC20Events::Transfer {
- from: *owner.as_eth(),
- to: H160::default(),
- value: amount.into(),
- }
- .to_log(collection_id_to_address(collection.id)),
- );
- <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
- collection.id,
- TokenId::default(),
- owner.clone(),
- amount,
- ));
- Ok(())
- }
- /// Burns the specified amount of the token.
- pub fn burn_foreign(
- collection: &FungibleHandle<T>,
- owner: &T::CrossAccountId,
- amount: u128,
- ) -> DispatchResult {
- let total_supply = <TotalSupply<T>>::get(collection.id)
- .checked_sub(amount)
- .ok_or(<CommonError<T>>::TokenValueTooLow)?;
-
- let balance = <Balance<T>>::get((collection.id, owner))
- .checked_sub(amount)
- .ok_or(<CommonError<T>>::TokenValueTooLow)?;
// =========
if balance == 0 {
@@ -468,14 +405,25 @@
}
/// Minting tokens for multiple IDs.
- /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]
- /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]
- pub fn create_multiple_items_common(
+ /// See [`create_item`][`Pallet::create_item`] for more details.
+ pub fn create_multiple_items(
collection: &FungibleHandle<T>,
- sender: &T::CrossAccountId,
+ depositor: &T::CrossAccountId,
data: BTreeMap<T::CrossAccountId, u128>,
nesting_budget: &dyn Budget,
) -> DispatchResult {
+ if !collection.is_owner_or_admin(depositor) {
+ ensure!(
+ collection.permissions.mint_mode(),
+ <CommonError<T>>::PublicMintingNotAllowed
+ );
+ collection.check_allowlist(depositor)?;
+
+ for (owner, _) in data.iter() {
+ collection.check_allowlist(owner)?;
+ }
+ }
+
let total_supply = data
.values()
.copied()
@@ -486,7 +434,7 @@
for (to, _) in data.iter() {
<PalletStructure<T>>::check_nesting(
- sender,
+ depositor,
to,
collection.id,
TokenId::default(),
@@ -532,44 +480,7 @@
Ok(())
}
-
- /// Minting tokens for multiple IDs.
- /// See [`create_item`][`Pallet::create_item`] for more details.
- pub fn create_multiple_items(
- collection: &FungibleHandle<T>,
- sender: &T::CrossAccountId,
- data: BTreeMap<T::CrossAccountId, u128>,
- nesting_budget: &dyn Budget,
- ) -> DispatchResult {
- // Foreign collection check
- ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);
- if !collection.is_owner_or_admin(sender) {
- ensure!(
- collection.permissions.mint_mode(),
- <CommonError<T>>::PublicMintingNotAllowed
- );
- collection.check_allowlist(sender)?;
-
- for (owner, _) in data.iter() {
- collection.check_allowlist(owner)?;
- }
- }
-
- Self::create_multiple_items_common(collection, sender, data, nesting_budget)
- }
-
- /// Minting tokens for multiple IDs.
- /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.
- pub fn create_multiple_items_foreign(
- collection: &FungibleHandle<T>,
- sender: &T::CrossAccountId,
- data: BTreeMap<T::CrossAccountId, u128>,
- nesting_budget: &dyn Budget,
- ) -> DispatchResult {
- Self::create_multiple_items_common(collection, sender, data, nesting_budget)
- }
-
fn set_allowance_unchecked(
collection: &FungibleHandle<T>,
owner: &T::CrossAccountId,
@@ -795,24 +706,6 @@
nesting_budget: &dyn Budget,
) -> DispatchResult {
Self::create_multiple_items(
- collection,
- sender,
- [(data.0, data.1)].into_iter().collect(),
- nesting_budget,
- )
- }
-
- /// Creates fungible token.
- ///
- /// - `data`: Contains user who will become the owners of the tokens and amount
- /// of tokens he will receive.
- pub fn create_item_foreign(
- collection: &FungibleHandle<T>,
- sender: &T::CrossAccountId,
- data: CreateItemData<T>,
- nesting_budget: &dyn Budget,
- ) -> DispatchResult {
- Self::create_multiple_items_foreign(
collection,
sender,
[(data.0, data.1)].into_iter().collect(),
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -18,6 +18,7 @@
use pallet_common::{
bench_init,
benchmarking::{create_collection_raw, property_key, property_value},
+ CollectionIssuer, Pallet as PalletCommon,
};
use sp_std::prelude::*;
use up_data_structs::{
@@ -56,7 +57,9 @@
create_collection_raw(
owner,
CollectionMode::NFT,
- |owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
+ |owner: T::CrossAccountId, data| {
+ <PalletCommon<T>>::init_collection(owner.clone(), CollectionIssuer::User(owner), data)
+ },
NonfungibleHandle::cast,
)
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -19,8 +19,8 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use pallet_common::{
weights::WeightInfo as _, with_weight, write_token_properties_total_weight,
- CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions,
- SelfWeightOf as PalletCommonWeightOf,
+ CommonCollectionOperations, CommonWeightInfo, SelfWeightOf as PalletCommonWeightOf,
+ XcmExtensions,
};
use pallet_structure::Pallet as PalletStructure;
use sp_runtime::DispatchError;
@@ -533,10 +533,6 @@
} else {
0
}
- }
-
- fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {
- None
}
fn total_pieces(&self, token: TokenId) -> Option<u128> {
@@ -547,6 +543,10 @@
}
}
+ fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {
+ Some(self)
+ }
+
fn set_allowance_for_all(
&self,
owner: T::CrossAccountId,
@@ -570,3 +570,53 @@
)
}
}
+
+impl<T: Config> XcmExtensions<T> for NonfungibleHandle<T> {
+ fn token_has_children(&self, token: TokenId) -> bool {
+ <Pallet<T>>::token_has_children(self.id, token)
+ }
+
+ fn create_item_internal(
+ &self,
+ depositor: &<T>::CrossAccountId,
+ to: <T>::CrossAccountId,
+ data: up_data_structs::CreateItemData,
+ nesting_budget: &dyn Budget,
+ ) -> Result<TokenId, sp_runtime::DispatchError> {
+ <Pallet<T>>::create_multiple_items(
+ self,
+ depositor,
+ vec![map_create_data::<T>(data, &to)?],
+ nesting_budget,
+ )?;
+
+ Ok(self.last_token_id())
+ }
+
+ fn transfer_item_internal(
+ &self,
+ depositor: &<T>::CrossAccountId,
+ from: &<T>::CrossAccountId,
+ to: &<T>::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ nesting_budget: &dyn Budget,
+ ) -> sp_runtime::DispatchResult {
+ ensure!(amount == 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+ <Pallet<T>>::transfer_internal(self, depositor, from, to, token, nesting_budget)
+ .map(|_| ())
+ .map_err(|post_info| post_info.error)
+ }
+
+ fn burn_item_internal(
+ &self,
+ from: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> sp_runtime::DispatchResult {
+ ensure!(amount == 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+ <Pallet<T>>::burn(self, &from, token)
+ }
+}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -117,8 +117,8 @@
use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
use up_data_structs::{
budget::Budget, mapping::TokenAddressMapping, AccessMode, AuxPropertyValue, CollectionId,
- CreateCollectionData, CreateNftExData, CustomDataLimit, PropertiesPermissionMap, Property,
- PropertyKey, PropertyKeyPermission, PropertyScope, PropertyValue, TokenChild, TokenId,
+ CreateNftExData, CustomDataLimit, PropertiesPermissionMap, Property, PropertyKey,
+ PropertyKeyPermission, PropertyScope, PropertyValue, TokenChild, TokenId,
TokenProperties as TokenPropertiesT,
};
use weights::WeightInfo;
@@ -383,19 +383,6 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- /// Create NFT collection
- ///
- /// `init_collection` will take non-refundable deposit for collection creation.
- ///
- /// - `data`: Contains settings for collection limits and permissions.
- pub fn init_collection(
- owner: T::CrossAccountId,
- payer: T::CrossAccountId,
- data: CreateCollectionData<T::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data)
- }
-
/// Destroy NFT collection
///
/// `destroy_collection` will throw error if collection contains any tokens.
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -20,6 +20,7 @@
use pallet_common::{
bench_init,
benchmarking::{create_collection_raw, property_key, property_value},
+ CollectionIssuer, Pallet as PalletCommon,
};
use sp_std::prelude::*;
use up_data_structs::{
@@ -61,7 +62,9 @@
create_collection_raw(
owner,
CollectionMode::ReFungible,
- |owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
+ |owner: T::CrossAccountId, data| {
+ <PalletCommon<T>>::init_collection(owner.clone(), CollectionIssuer::User(owner), data)
+ },
RefungibleHandle::cast,
)
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -103,7 +103,7 @@
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
use up_data_structs::{
- budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId, CreateCollectionData,
+ budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId,
CreateRefungibleExMultipleOwners, PropertiesPermissionMap, Property, PropertyKey,
PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TokenOwnerError,
TokenProperties as TokenPropertiesT, MAX_REFUNGIBLE_PIECES,
@@ -296,19 +296,6 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- /// Create RFT collection
- ///
- /// `init_collection` will take non-refundable deposit for collection creation.
- ///
- /// - `data`: Contains settings for collection limits and permissions.
- pub fn init_collection(
- owner: T::CrossAccountId,
- payer: T::CrossAccountId,
- data: CreateCollectionData<T::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data)
- }
-
/// Destroy RFT collection
///
/// `destroy_collection` will throw error if collection contains any tokens.
pallets/structure/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -16,7 +16,7 @@
use frame_benchmarking::v2::{account, benchmarks, BenchmarkError};
use frame_support::traits::{fungible::Balanced, tokens::Precision, Get};
-use pallet_common::Config as CommonConfig;
+use pallet_common::{CollectionIssuer, Config as CommonConfig};
use pallet_evm::account::CrossAccountId;
use sp_std::vec;
use up_data_structs::{
@@ -44,7 +44,7 @@
.unwrap();
T::CollectionDispatch::create(
caller_cross.clone(),
- caller_cross.clone(),
+ CollectionIssuer::User(caller_cross.clone()),
CreateCollectionData {
mode: CollectionMode::NFT,
..Default::default()
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -26,7 +26,7 @@
dispatch::CollectionDispatch,
erc::{static_property::key, CollectionHelpersEvents},
eth::{self, collection_id_to_address, map_eth_to_id},
- CollectionById, CollectionHandle, Pallet as PalletCommon,
+ CollectionById, CollectionHandle, CollectionIssuer, Pallet as PalletCommon,
};
use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
use pallet_evm_coder_substrate::{
@@ -110,8 +110,12 @@
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(
+ caller,
+ CollectionIssuer::User(collection_helpers_address),
+ data,
+ )
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
@@ -240,8 +244,12 @@
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
- .map_err(dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(
+ caller,
+ CollectionIssuer::User(collection_helpers_address),
+ data,
+ )
+ .map_err(dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
@@ -274,8 +282,12 @@
check_sent_amount_equals_collection_creation_price::<T>(value)?;
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
- .map_err(dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(
+ caller,
+ CollectionIssuer::User(collection_helpers_address),
+ data,
+ )
+ .map_err(dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -199,7 +199,7 @@
type CollectionFlags is uint8;
library CollectionFlagsLib {
- /// Tokens in foreign collections can be transferred, but not burnt
+ /// A collection of foreign assets
CollectionFlags constant foreignField = CollectionFlags.wrap(128);
/// Supports ERC721Metadata
CollectionFlags constant erc721metadataField = CollectionFlags.wrap(64);
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -93,7 +93,8 @@
use frame_system::{ensure_root, ensure_signed};
use pallet_common::{
dispatch::{dispatch_tx, CollectionDispatch},
- CollectionHandle, CommonWeightInfo, Pallet as PalletCommon, RefungibleExtensionsWeightInfo,
+ CollectionHandle, CollectionIssuer, CommonWeightInfo, Pallet as PalletCommon,
+ RefungibleExtensionsWeightInfo,
};
use pallet_evm::account::CrossAccountId;
use pallet_structure::weights::WeightInfo as StructureWeightInfo;
@@ -401,7 +402,11 @@
// =========
let sender = T::CrossAccountId::from_sub(sender);
- let _id = T::CollectionDispatch::create(sender.clone(), sender, data)?;
+ let _id = T::CollectionDispatch::create(
+ sender.clone(),
+ CollectionIssuer::User(sender),
+ data,
+ )?;
Ok(())
}
primitives/data-structs/src/budget.rsdiffbeforeafterboth--- a/primitives/data-structs/src/budget.rs
+++ b/primitives/data-structs/src/budget.rs
@@ -36,3 +36,10 @@
true
}
}
+
+pub struct ZeroBudget;
+impl Budget for ZeroBudget {
+ fn consume_custom(&self, _calls: u32) -> bool {
+ false
+ }
+}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -378,7 +378,7 @@
#[derive(AbiCoderFlags, Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]
#[bondrewd(enforce_bytes = 1)]
pub struct CollectionFlags {
- /// Tokens in foreign collections can be transferred, but not burnt
+ /// A collection of foreign assets
#[bondrewd(bits = "0..1")]
pub foreign: bool,
/// Supports ERC721Metadata
runtime/common/config/orml.rsdiffbeforeafterboth--- a/runtime/common/config/orml.rs
+++ b/runtime/common/config/orml.rs
@@ -14,31 +14,21 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use frame_support::{
- parameter_types,
- traits::{Contains, Everything},
-};
+use frame_support::{parameter_types, traits::Everything};
use frame_system::EnsureSigned;
use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key};
-use pallet_foreign_assets::{CurrencyId, NativeCurrency};
+use pallet_foreign_assets::CurrencyIdConvert;
use sp_runtime::traits::Convert;
-use sp_std::{vec, vec::Vec};
use staging_xcm::latest::{Junction::*, Junctions::*, MultiLocation, Weight};
use staging_xcm_executor::XcmExecutor;
use up_common::{
constants::*,
types::{AccountId, Balance},
};
+use up_data_structs::CollectionId;
use crate::{
- runtime_common::config::{
- pallets::TreasuryAccountId,
- substrate::{MaxLocks, MaxReserves},
- xcm::{
- xcm_assets::CurrencyIdConvert, SelfLocation, UniversalLocation, Weigher,
- XcmExecutorConfig,
- },
- },
+ runtime_common::config::xcm::{SelfLocation, UniversalLocation, Weigher, XcmExecutorConfig},
RelayChainBlockNumberProvider, Runtime, RuntimeEvent,
};
@@ -59,29 +49,6 @@
};
}
-parameter_type_with_key! {
- pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance {
- match currency_id {
- CurrencyId::NativeAssetId(symbol) => match symbol {
- NativeCurrency::Here => 0,
- NativeCurrency::Parent=> 0,
- },
- _ => 100_000
- }
- };
-}
-
-pub fn get_all_module_accounts() -> Vec<AccountId> {
- vec![TreasuryAccountId::get()]
-}
-
-pub struct DustRemovalWhitelist;
-impl Contains<AccountId> for DustRemovalWhitelist {
- fn contains(a: &AccountId) -> bool {
- get_all_module_accounts().contains(a)
- }
-}
-
pub struct AccountIdToMultiLocation;
impl Convert<AccountId, MultiLocation> for AccountIdToMultiLocation {
fn convert(account: AccountId) -> MultiLocation {
@@ -91,18 +58,6 @@
})
.into()
}
-}
-
-pub struct CurrencyHooks;
-impl orml_traits::currency::MutationHooks<AccountId, CurrencyId, Balance> for CurrencyHooks {
- type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;
- type OnSlash = ();
- type PreTransfer = ();
- type PostTransfer = ();
- type PreDeposit = ();
- type PostDeposit = ();
- type OnNewTokenAccount = ();
- type OnKilledTokenAccount = ();
}
impl orml_vesting::Config for Runtime {
@@ -113,29 +68,13 @@
type WeightInfo = ();
type MaxVestingSchedules = MaxVestingSchedules;
type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
-}
-
-impl orml_tokens::Config for Runtime {
- type RuntimeEvent = RuntimeEvent;
- type Balance = Balance;
- type Amount = Amount;
- type CurrencyId = CurrencyId;
- type WeightInfo = ();
- type ExistentialDeposits = ExistentialDeposits;
- type CurrencyHooks = CurrencyHooks;
- type MaxLocks = MaxLocks;
- type MaxReserves = MaxReserves;
- // TODO: Add all module accounts
- type DustRemovalWhitelist = DustRemovalWhitelist;
- /// The id type for named reserves.
- type ReserveIdentifier = ();
}
impl orml_xtokens::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
- type CurrencyId = CurrencyId;
- type CurrencyIdConvert = CurrencyIdConvert;
+ type CurrencyId = CollectionId;
+ type CurrencyIdConvert = CurrencyIdConvert<Self>;
type AccountIdToMultiLocation = AccountIdToMultiLocation;
type SelfLocation = SelfLocation;
type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
runtime/common/config/pallets/foreign_asset.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/foreign_asset.rs
+++ b/runtime/common/config/pallets/foreign_asset.rs
@@ -1,10 +1,52 @@
-use up_common::types::AccountId;
+use frame_support::{parameter_types, PalletId};
+#[cfg(not(feature = "governance"))]
+use frame_system::EnsureRoot;
+use pallet_evm::account::CrossAccountId;
+use sp_core::H160;
+use staging_xcm::prelude::*;
+use staging_xcm_builder::AccountKey20Aliases;
+
+#[cfg(feature = "governance")]
+use crate::runtime_common::config::governance;
+use crate::{
+ runtime_common::config::{
+ ethereum::CrossAccountId as ConfigCrossAccountId,
+ xcm::{LocationToAccountId, SelfLocation},
+ },
+ RelayNetwork, Runtime, RuntimeEvent,
+};
+
+parameter_types! {
+ pub ForeignAssetPalletId: PalletId = PalletId(*b"frgnasts");
+}
+
+pub struct LocationToCrossAccountId;
+impl staging_xcm_executor::traits::ConvertLocation<ConfigCrossAccountId>
+ for LocationToCrossAccountId
+{
+ fn convert_location(location: &MultiLocation) -> Option<ConfigCrossAccountId> {
+ LocationToAccountId::convert_location(location)
+ .map(ConfigCrossAccountId::from_sub)
+ .or_else(|| {
+ let eth_address =
+ AccountKey20Aliases::<RelayNetwork, H160>::convert_location(location)?;
-use crate::{Balances, Runtime, RuntimeEvent};
+ Some(ConfigCrossAccountId::from_eth(eth_address))
+ })
+ }
+}
impl pallet_foreign_assets::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
- type Currency = Balances;
- type RegisterOrigin = frame_system::EnsureRoot<AccountId>;
+
+ #[cfg(feature = "governance")]
+ type ForceRegisterOrigin = governance::RootOrTechnicalCommitteeMember;
+
+ #[cfg(not(feature = "governance"))]
+ type ForceRegisterOrigin = EnsureRoot<Self::AccountId>;
+
+ type PalletId = ForeignAssetPalletId;
+ type SelfLocation = SelfLocation;
+ type LocationToAccountId = LocationToCrossAccountId;
type WeightInfo = pallet_foreign_assets::weights::SubstrateWeight<Self>;
}
runtime/common/config/xcm.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/config/xcm.rs
@@ -0,0 +1,254 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use cumulus_primitives_core::ParaId;
+use frame_support::{
+ parameter_types,
+ traits::{ConstU32, Everything, Get, Nothing, ProcessMessageError},
+};
+use frame_system::EnsureRoot;
+use orml_traits::location::AbsoluteReserveProvider;
+use orml_xcm_support::MultiNativeAsset;
+use pallet_foreign_assets::FreeForAll;
+use pallet_xcm::XcmPassthrough;
+use polkadot_parachain_primitives::primitives::Sibling;
+use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery;
+use sp_std::marker::PhantomData;
+use staging_xcm::{
+ latest::{prelude::*, MultiLocation, Weight},
+ v3::Instruction,
+};
+use staging_xcm_builder::{
+ AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, ParentIsPreset, RelayChainAsNative,
+ SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
+ SignedToAccountId32, SovereignSignedViaLocation,
+};
+use staging_xcm_executor::{
+ traits::{Properties, ShouldExecute},
+ XcmExecutor,
+};
+use up_common::types::AccountId;
+
+#[cfg(feature = "governance")]
+use crate::runtime_common::config::governance;
+use crate::{
+ xcm_barrier::Barrier, AllPalletsWithSystem, Balances, ForeignAssets, ParachainInfo,
+ ParachainSystem, PolkadotXcm, RelayNetwork, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
+ XcmpQueue,
+};
+
+parameter_types! {
+ pub const RelayLocation: MultiLocation = MultiLocation::parent();
+ pub RelayOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
+ pub UniversalLocation: InteriorMultiLocation = (
+ GlobalConsensus(crate::RelayNetwork::get()),
+ Parachain(ParachainInfo::get().into()),
+ ).into();
+ pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
+
+ // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.
+ pub UnitWeightCost: Weight = Weight::from_parts(1_000_000, 1000); // ?
+ pub const MaxInstructions: u32 = 100;
+}
+
+/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
+/// when determining ownership of accounts for asset transacting and when attempting to use XCM
+/// `Transact` in order to determine the dispatch Origin.
+pub type LocationToAccountId = (
+ // The parent (Relay-chain) origin converts to the default `AccountId`.
+ ParentIsPreset<AccountId>,
+ // Sibling parachain origins convert to AccountId via the `ParaId::into`.
+ SiblingParachainConvertsVia<Sibling, AccountId>,
+ // Straight up local `AccountId32` origins just alias directly to `AccountId`.
+ AccountId32Aliases<RelayNetwork, AccountId>,
+);
+
+/// No local origins on this chain are allowed to dispatch XCM sends/executions.
+pub type LocalOriginToLocation = (SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>,);
+
+/// The means for routing XCM messages which are not for local execution into the right message
+/// queues.
+pub type XcmRouter = (
+ // Two routers - use UMP to communicate with the relay chain:
+ cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
+ // ..and XCMP to communicate with the sibling chains.
+ XcmpQueue,
+);
+
+/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
+/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
+/// biases the kind of local `Origin` it will become.
+pub type XcmOriginToTransactDispatchOrigin = (
+ // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
+ // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
+ // foreign chains who want to have a local sovereign account on this chain which they control.
+ SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
+ // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
+ // recognised.
+ RelayChainAsNative<RelayOrigin, RuntimeOrigin>,
+ // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
+ // recognised.
+ SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
+ // Native signed account converter; this just converts an `AccountId32` origin into a normal
+ // `Origin::Signed` origin of the same 32-byte value.
+ SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
+ // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
+ XcmPassthrough<RuntimeOrigin>,
+);
+
+pub trait TryPass {
+ fn try_pass<Call>(
+ origin: &MultiLocation,
+ message: &mut [Instruction<Call>],
+ ) -> Result<(), ProcessMessageError>;
+}
+
+#[impl_trait_for_tuples::impl_for_tuples(30)]
+impl TryPass for Tuple {
+ fn try_pass<Call>(
+ origin: &MultiLocation,
+ message: &mut [Instruction<Call>],
+ ) -> Result<(), ProcessMessageError> {
+ for_tuples!( #(
+ Tuple::try_pass(origin, message)?;
+ )* );
+
+ Ok(())
+ }
+}
+
+/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.
+/// If it passes the Deny, and matches one of the Allow cases then it is let through.
+pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)
+where
+ Deny: TryPass,
+ Allow: ShouldExecute;
+
+impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>
+where
+ Deny: TryPass,
+ Allow: ShouldExecute,
+{
+ fn should_execute<Call>(
+ origin: &MultiLocation,
+ message: &mut [Instruction<Call>],
+ max_weight: Weight,
+ properties: &mut Properties,
+ ) -> Result<(), ProcessMessageError> {
+ Deny::try_pass(origin, message)?;
+ Allow::should_execute(origin, message, max_weight, properties)
+ }
+}
+
+pub type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
+
+pub type IsReserve = MultiNativeAsset<AbsoluteReserveProvider>;
+
+pub type Trader = FreeForAll;
+
+pub struct XcmExecutorConfig<T>(PhantomData<T>);
+impl<T> staging_xcm_executor::Config for XcmExecutorConfig<T>
+where
+ T: pallet_configuration::Config,
+{
+ type RuntimeCall = RuntimeCall;
+ type XcmSender = XcmRouter;
+ // How to withdraw and deposit an asset.
+ type AssetTransactor = ForeignAssets;
+ type OriginConverter = XcmOriginToTransactDispatchOrigin;
+ type IsReserve = IsReserve;
+ type IsTeleporter = (); // Teleportation is disabled
+ type UniversalLocation = UniversalLocation;
+ type Barrier = Barrier;
+ type Weigher = Weigher;
+ type Trader = Trader;
+ type ResponseHandler = PolkadotXcm;
+ type SubscriptionService = PolkadotXcm;
+ type PalletInstancesInfo = AllPalletsWithSystem;
+ type MaxAssetsIntoHolding = ConstU32<8>;
+
+ type AssetTrap = PolkadotXcm;
+ type AssetClaims = PolkadotXcm;
+ type AssetLocker = ();
+ type AssetExchanger = ();
+ type FeeManager = ();
+ type MessageExporter = ();
+ type UniversalAliases = Nothing;
+ type CallDispatcher = RuntimeCall;
+ type SafeCallFilter = Nothing;
+ type Aliasers = Nothing;
+}
+
+#[cfg(feature = "runtime-benchmarks")]
+parameter_types! {
+ pub ReachableDest: Option<MultiLocation> = Some(Parent.into());
+}
+
+impl pallet_xcm::Config for Runtime {
+ type RuntimeEvent = RuntimeEvent;
+ type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, ()>;
+ type XcmRouter = XcmRouter;
+ type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
+ type XcmExecuteFilter = Everything;
+ type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
+ type XcmTeleportFilter = Everything;
+ type XcmReserveTransferFilter = Everything;
+ type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
+ type RuntimeOrigin = RuntimeOrigin;
+ type RuntimeCall = RuntimeCall;
+ const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
+ type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
+ type UniversalLocation = UniversalLocation;
+ type Currency = Balances;
+ type CurrencyMatcher = ();
+ type TrustedLockers = ();
+ type SovereignAccountOf = LocationToAccountId;
+ type MaxLockers = ConstU32<8>;
+ type WeightInfo = crate::weights::xcm::SubstrateWeight<Runtime>;
+ type AdminOrigin = EnsureRoot<AccountId>;
+ type MaxRemoteLockConsumers = ConstU32<0>;
+ type RemoteLockConsumerIdentifier = ();
+ #[cfg(feature = "runtime-benchmarks")]
+ type ReachableDest = ReachableDest;
+}
+
+impl cumulus_pallet_xcm::Config for Runtime {
+ type RuntimeEvent = RuntimeEvent;
+ type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
+}
+impl cumulus_pallet_xcmp_queue::Config for Runtime {
+ type WeightInfo = ();
+ type RuntimeEvent = RuntimeEvent;
+ type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
+ type ChannelInfo = ParachainSystem;
+ type VersionWrapper = PolkadotXcm;
+ type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
+
+ #[cfg(feature = "governance")]
+ type ControllerOrigin = governance::RootOrTechnicalCommitteeMember;
+
+ #[cfg(not(feature = "governance"))]
+ type ControllerOrigin = frame_system::EnsureRoot<AccountId>;
+
+ type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
+ type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
+}
+
+impl cumulus_pallet_dmp_queue::Config for Runtime {
+ type RuntimeEvent = RuntimeEvent;
+ type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
+ type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
+}
runtime/common/config/xcm/foreignassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/foreignassets.rs
+++ /dev/null
@@ -1,205 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-use frame_support::{parameter_types, traits::Get};
-use orml_traits::location::AbsoluteReserveProvider;
-use orml_xcm_support::MultiNativeAsset;
-use pallet_foreign_assets::{
- AssetId, AssetIdMapping, CurrencyId, ForeignAssetId, FreeForAll, NativeCurrency, TryAsForeign,
- XcmForeignAssetIdMapping,
-};
-use sp_runtime::traits::{Convert, MaybeEquivalence};
-use sp_std::marker::PhantomData;
-use staging_xcm::latest::{prelude::*, MultiAsset, MultiLocation};
-use staging_xcm_builder::{ConvertedConcreteId, FungiblesAdapter, NoChecking};
-use staging_xcm_executor::traits::{JustTry, TransactAsset};
-use up_common::types::{AccountId, Balance};
-
-use super::{LocationToAccountId, RelayLocation};
-use crate::{Balances, ForeignAssets, ParachainInfo, PolkadotXcm, Runtime};
-
-parameter_types! {
- pub CheckingAccount: AccountId = PolkadotXcm::check_account();
-}
-
-pub struct AsInnerId<ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
-impl<ConvertAssetId: MaybeEquivalence<AssetId, AssetId>> MaybeEquivalence<MultiLocation, AssetId>
- for AsInnerId<ConvertAssetId>
-{
- fn convert(id: &MultiLocation) -> Option<AssetId> {
- log::trace!(
- target: "xcm::AsInnerId::Convert",
- "AsInnerId {:?}",
- id
- );
-
- let parent = MultiLocation::parent();
- let here = MultiLocation::here();
- let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
-
- if *id == parent {
- return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent));
- }
-
- if *id == here || *id == self_location {
- return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here));
- }
-
- match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
- Some(AssetId::ForeignAssetId(foreign_asset_id)) => {
- ConvertAssetId::convert(&AssetId::ForeignAssetId(foreign_asset_id))
- }
- _ => None,
- }
- }
-
- fn convert_back(asset_id: &AssetId) -> Option<MultiLocation> {
- log::trace!(
- target: "xcm::AsInnerId::Reverse",
- "AsInnerId",
- );
-
- let parent_id =
- ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent)).unwrap();
- let here_id =
- ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here)).unwrap();
-
- if *asset_id == parent_id {
- return Some(MultiLocation::parent());
- }
-
- if *asset_id == here_id {
- return Some(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- ));
- }
-
- let fid = <AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(*asset_id)?;
- XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid)
- }
-}
-
-/// Means for transacting assets besides the native currency on this chain.
-pub type FungiblesTransactor = FungiblesAdapter<
- // Use this fungibles implementation:
- ForeignAssets,
- // Use this currency when it is a fungible asset matching the given location or name:
- ConvertedConcreteId<AssetId, Balance, AsInnerId<JustTry>, JustTry>,
- // Convert an XCM MultiLocation into a local account id:
- LocationToAccountId,
- // Our chain's account ID type (we can't get away without mentioning it explicitly):
- AccountId,
- // No Checking for teleported assets since we disallow teleports at all.
- NoChecking,
- // The account to use for tracking teleports.
- CheckingAccount,
->;
-
-/// Means for transacting assets on this chain.
-pub struct AssetTransactor;
-impl TransactAsset for AssetTransactor {
- fn can_check_in(
- _origin: &MultiLocation,
- _what: &MultiAsset,
- _context: &XcmContext,
- ) -> XcmResult {
- Err(XcmError::Unimplemented)
- }
-
- fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
-
- fn can_check_out(
- _dest: &MultiLocation,
- _what: &MultiAsset,
- _context: &XcmContext,
- ) -> XcmResult {
- Err(XcmError::Unimplemented)
- }
-
- fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
-
- fn deposit_asset(
- what: &MultiAsset,
- who: &MultiLocation,
- context: Option<&XcmContext>,
- ) -> XcmResult {
- FungiblesTransactor::deposit_asset(what, who, context)
- }
-
- fn withdraw_asset(
- what: &MultiAsset,
- who: &MultiLocation,
- maybe_context: Option<&XcmContext>,
- ) -> Result<staging_xcm_executor::Assets, XcmError> {
- FungiblesTransactor::withdraw_asset(what, who, maybe_context)
- }
-
- fn internal_transfer_asset(
- what: &MultiAsset,
- from: &MultiLocation,
- to: &MultiLocation,
- context: &XcmContext,
- ) -> Result<staging_xcm_executor::Assets, XcmError> {
- FungiblesTransactor::internal_transfer_asset(what, from, to, context)
- }
-}
-
-pub type IsReserve = MultiNativeAsset<AbsoluteReserveProvider>;
-
-pub type Trader<T> = FreeForAll<
- pallet_configuration::WeightToFee<T, Balance>,
- RelayLocation,
- AccountId,
- Balances,
- (),
->;
-
-pub struct CurrencyIdConvert;
-impl Convert<AssetId, Option<MultiLocation>> for CurrencyIdConvert {
- fn convert(id: AssetId) -> Option<MultiLocation> {
- match id {
- AssetId::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- )),
- AssetId::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
- AssetId::ForeignAssetId(foreign_asset_id) => {
- XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)
- }
- }
- }
-}
-
-impl Convert<MultiLocation, Option<CurrencyId>> for CurrencyIdConvert {
- fn convert(location: MultiLocation) -> Option<CurrencyId> {
- if location == MultiLocation::here()
- || location == MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())))
- {
- return Some(AssetId::NativeAssetId(NativeCurrency::Here));
- }
-
- if location == MultiLocation::parent() {
- return Some(AssetId::NativeAssetId(NativeCurrency::Parent));
- }
-
- if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
- return Some(currency_id);
- }
-
- None
- }
-}
runtime/common/config/xcm/mod.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/mod.rs
+++ /dev/null
@@ -1,259 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-use cumulus_primitives_core::ParaId;
-use frame_support::{
- parameter_types,
- traits::{ConstU32, Everything, Get, Nothing, ProcessMessageError},
-};
-use frame_system::EnsureRoot;
-use pallet_xcm::XcmPassthrough;
-use polkadot_parachain_primitives::primitives::Sibling;
-use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery;
-use sp_std::marker::PhantomData;
-use staging_xcm::{
- latest::{prelude::*, MultiLocation, Weight},
- v3::Instruction,
-};
-use staging_xcm_builder::{
- AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, ParentIsPreset, RelayChainAsNative,
- SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
- SignedToAccountId32, SovereignSignedViaLocation,
-};
-use staging_xcm_executor::{
- traits::{Properties, ShouldExecute},
- XcmExecutor,
-};
-use up_common::types::AccountId;
-
-use crate::{
- xcm_barrier::Barrier, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem,
- PolkadotXcm, RelayNetwork, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, XcmpQueue,
-};
-
-#[cfg(feature = "foreign-assets")]
-pub mod foreignassets;
-
-#[cfg(not(feature = "foreign-assets"))]
-pub mod nativeassets;
-
-#[cfg(feature = "foreign-assets")]
-pub use foreignassets as xcm_assets;
-#[cfg(not(feature = "foreign-assets"))]
-pub use nativeassets as xcm_assets;
-use xcm_assets::{AssetTransactor, IsReserve, Trader};
-
-#[cfg(feature = "governance")]
-use crate::runtime_common::config::governance;
-
-parameter_types! {
- pub const RelayLocation: MultiLocation = MultiLocation::parent();
- pub RelayOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
- pub UniversalLocation: InteriorMultiLocation = (
- GlobalConsensus(crate::RelayNetwork::get()),
- Parachain(ParachainInfo::get().into()),
- ).into();
- pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
-
- // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.
- pub UnitWeightCost: Weight = Weight::from_parts(1_000_000, 1000); // ?
- pub const MaxInstructions: u32 = 100;
-}
-
-/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
-/// when determining ownership of accounts for asset transacting and when attempting to use XCM
-/// `Transact` in order to determine the dispatch Origin.
-pub type LocationToAccountId = (
- // The parent (Relay-chain) origin converts to the default `AccountId`.
- ParentIsPreset<AccountId>,
- // Sibling parachain origins convert to AccountId via the `ParaId::into`.
- SiblingParachainConvertsVia<Sibling, AccountId>,
- // Straight up local `AccountId32` origins just alias directly to `AccountId`.
- AccountId32Aliases<RelayNetwork, AccountId>,
-);
-
-/// No local origins on this chain are allowed to dispatch XCM sends/executions.
-pub type LocalOriginToLocation = (SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>,);
-
-/// The means for routing XCM messages which are not for local execution into the right message
-/// queues.
-pub type XcmRouter = (
- // Two routers - use UMP to communicate with the relay chain:
- cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
- // ..and XCMP to communicate with the sibling chains.
- XcmpQueue,
-);
-
-/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
-/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
-/// biases the kind of local `Origin` it will become.
-pub type XcmOriginToTransactDispatchOrigin = (
- // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
- // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
- // foreign chains who want to have a local sovereign account on this chain which they control.
- SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
- // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
- // recognised.
- RelayChainAsNative<RelayOrigin, RuntimeOrigin>,
- // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
- // recognised.
- SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
- // Native signed account converter; this just converts an `AccountId32` origin into a normal
- // `Origin::Signed` origin of the same 32-byte value.
- SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
- // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
- XcmPassthrough<RuntimeOrigin>,
-);
-
-pub trait TryPass {
- fn try_pass<Call>(
- origin: &MultiLocation,
- message: &mut [Instruction<Call>],
- ) -> Result<(), ProcessMessageError>;
-}
-
-#[impl_trait_for_tuples::impl_for_tuples(30)]
-impl TryPass for Tuple {
- fn try_pass<Call>(
- origin: &MultiLocation,
- message: &mut [Instruction<Call>],
- ) -> Result<(), ProcessMessageError> {
- for_tuples!( #(
- Tuple::try_pass(origin, message)?;
- )* );
-
- Ok(())
- }
-}
-
-/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.
-/// If it passes the Deny, and matches one of the Allow cases then it is let through.
-pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)
-where
- Deny: TryPass,
- Allow: ShouldExecute;
-
-impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>
-where
- Deny: TryPass,
- Allow: ShouldExecute,
-{
- fn should_execute<Call>(
- origin: &MultiLocation,
- message: &mut [Instruction<Call>],
- max_weight: Weight,
- properties: &mut Properties,
- ) -> Result<(), ProcessMessageError> {
- Deny::try_pass(origin, message)?;
- Allow::should_execute(origin, message, max_weight, properties)
- }
-}
-
-pub type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
-
-pub struct XcmExecutorConfig<T>(PhantomData<T>);
-impl<T> staging_xcm_executor::Config for XcmExecutorConfig<T>
-where
- T: pallet_configuration::Config,
-{
- type RuntimeCall = RuntimeCall;
- type XcmSender = XcmRouter;
- // How to withdraw and deposit an asset.
- type AssetTransactor = AssetTransactor;
- type OriginConverter = XcmOriginToTransactDispatchOrigin;
- type IsReserve = IsReserve;
- type IsTeleporter = (); // Teleportation is disabled
- type UniversalLocation = UniversalLocation;
- type Barrier = Barrier;
- type Weigher = Weigher;
- type Trader = Trader<T>;
- type ResponseHandler = PolkadotXcm;
- type SubscriptionService = PolkadotXcm;
- type PalletInstancesInfo = AllPalletsWithSystem;
- type MaxAssetsIntoHolding = ConstU32<8>;
-
- type AssetTrap = PolkadotXcm;
- type AssetClaims = PolkadotXcm;
- type AssetLocker = ();
- type AssetExchanger = ();
- type FeeManager = ();
- type MessageExporter = ();
- type UniversalAliases = Nothing;
- type CallDispatcher = RuntimeCall;
- type SafeCallFilter = Nothing;
- type Aliasers = Nothing;
-}
-
-#[cfg(feature = "runtime-benchmarks")]
-parameter_types! {
- pub ReachableDest: Option<MultiLocation> = Some(Parent.into());
-}
-
-impl pallet_xcm::Config for Runtime {
- type RuntimeEvent = RuntimeEvent;
- type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, ()>;
- type XcmRouter = XcmRouter;
- type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
- type XcmExecuteFilter = Everything;
- type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
- type XcmTeleportFilter = Everything;
- type XcmReserveTransferFilter = Everything;
- type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
- type RuntimeOrigin = RuntimeOrigin;
- type RuntimeCall = RuntimeCall;
- const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
- type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
- type UniversalLocation = UniversalLocation;
- type Currency = Balances;
- type CurrencyMatcher = ();
- type TrustedLockers = ();
- type SovereignAccountOf = LocationToAccountId;
- type MaxLockers = ConstU32<8>;
- type WeightInfo = crate::weights::xcm::SubstrateWeight<Runtime>;
- type AdminOrigin = EnsureRoot<AccountId>;
- type MaxRemoteLockConsumers = ConstU32<0>;
- type RemoteLockConsumerIdentifier = ();
- #[cfg(feature = "runtime-benchmarks")]
- type ReachableDest = ReachableDest;
-}
-
-impl cumulus_pallet_xcm::Config for Runtime {
- type RuntimeEvent = RuntimeEvent;
- type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
-}
-impl cumulus_pallet_xcmp_queue::Config for Runtime {
- type WeightInfo = ();
- type RuntimeEvent = RuntimeEvent;
- type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
- type ChannelInfo = ParachainSystem;
- type VersionWrapper = PolkadotXcm;
- type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
-
- #[cfg(feature = "governance")]
- type ControllerOrigin = governance::RootOrTechnicalCommitteeMember;
-
- #[cfg(not(feature = "governance"))]
- type ControllerOrigin = frame_system::EnsureRoot<AccountId>;
-
- type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
- type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
-}
-
-impl cumulus_pallet_dmp_queue::Config for Runtime {
- type RuntimeEvent = RuntimeEvent;
- type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
- type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
-}
runtime/common/config/xcm/nativeassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/nativeassets.rs
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-use cumulus_primitives_core::XcmContext;
-use frame_support::{
- traits::{tokens::currency::Currency as CurrencyT, Get, OnUnbalanced as OnUnbalancedT},
- weights::WeightToFeePolynomial,
-};
-use pallet_foreign_assets::{AssetIds, NativeCurrency};
-use sp_runtime::traits::{CheckedConversion, Convert, Zero};
-use sp_std::marker::PhantomData;
-use staging_xcm::latest::{
- AssetId::Concrete, Error as XcmError, Fungibility::Fungible as XcmFungible, Junction::*,
- Junctions::*, MultiAsset, MultiLocation, Weight,
-};
-use staging_xcm_builder::{CurrencyAdapter, NativeAsset};
-use staging_xcm_executor::{
- traits::{MatchesFungible, WeightTrader},
- Assets,
-};
-use up_common::types::{AccountId, Balance};
-
-use super::{LocationToAccountId, RelayLocation};
-use crate::{Balances, ParachainInfo};
-
-pub struct OnlySelfCurrency;
-impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {
- fn matches_fungible(a: &MultiAsset) -> Option<B> {
- let paraid = Parachain(ParachainInfo::parachain_id().into());
- match (&a.id, &a.fun) {
- (
- Concrete(MultiLocation {
- parents: 1,
- interior: X1(loc),
- }),
- XcmFungible(ref amount),
- ) if paraid == *loc => CheckedConversion::checked_from(*amount),
- (
- Concrete(MultiLocation {
- parents: 0,
- interior: Here,
- }),
- XcmFungible(ref amount),
- ) => CheckedConversion::checked_from(*amount),
- _ => None,
- }
- }
-}
-
-/// Means for transacting assets on this chain.
-pub type LocalAssetTransactor = CurrencyAdapter<
- // Use this currency:
- Balances,
- // Use this currency when it is a fungible asset matching the given location or name:
- OnlySelfCurrency,
- // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
- LocationToAccountId,
- // Our chain's account ID type (we can't get away without mentioning it explicitly):
- AccountId,
- // We don't track any teleports.
- (),
->;
-
-pub type AssetTransactor = LocalAssetTransactor;
-
-pub type IsReserve = NativeAsset;
-
-pub struct UsingOnlySelfCurrencyComponents<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
->(
- Weight,
- Currency::Balance,
- PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,
-);
-impl<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
- > WeightTrader
- for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
-{
- fn new() -> Self {
- // FIXME: benchmark
- Self(Weight::from_parts(0, 0), Zero::zero(), PhantomData)
- }
-
- fn buy_weight(
- &mut self,
- _weight: Weight,
- payment: Assets,
- _xcm: &XcmContext,
- ) -> Result<Assets, XcmError> {
- Ok(payment)
- }
-}
-impl<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
- > Drop
- for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
-{
- fn drop(&mut self) {
- OnUnbalanced::on_unbalanced(Currency::issue(self.1));
- }
-}
-
-pub type Trader<T> = UsingOnlySelfCurrencyComponents<
- pallet_configuration::WeightToFee<T, Balance>,
- RelayLocation,
- AccountId,
- Balances,
- (),
->;
-
-pub struct CurrencyIdConvert;
-impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
- fn convert(id: AssetIds) -> Option<MultiLocation> {
- match id {
- AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- )),
- _ => None,
- }
- }
-}
runtime/common/construct_runtime.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime.rs
+++ b/runtime/common/construct_runtime.rs
@@ -47,7 +47,7 @@
Vesting: orml_vesting = 37,
XTokens: orml_xtokens = 38,
- Tokens: orml_tokens = 39,
+ // [REMOVED] Tokens: orml_tokens = 39,
// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,
#[cfg(feature = "governance")]
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -17,11 +17,9 @@
use frame_support::{dispatch::DispatchResult, ensure, fail};
use pallet_balances_adapter::NativeFungibleHandle;
pub use pallet_common::dispatch::CollectionDispatch;
-#[cfg(not(feature = "refungible"))]
-use pallet_common::unsupported;
use pallet_common::{
- erc::CommonEvmHandler, eth::map_eth_to_id, CollectionById, CollectionHandle,
- CommonCollectionOperations,
+ erc::CommonEvmHandler, eth::map_eth_to_id, CollectionById, CollectionHandle, CollectionIssuer,
+ CommonCollectionOperations, Pallet as PalletCommon,
};
use pallet_evm::{PrecompileHandle, PrecompileResult};
use pallet_fungible::{FungibleHandle, Pallet as PalletFungible};
@@ -70,27 +68,25 @@
fn create(
sender: T::CrossAccountId,
- payer: T::CrossAccountId,
+ issuer: CollectionIssuer<T::CrossAccountId>,
data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
- let id = match data.mode {
- CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, payer, data)?,
+ match data.mode {
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(
decimal_points <= MAX_DECIMAL_POINTS,
pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
);
- <PalletFungible<T>>::init_collection(sender, payer, data)?
}
-
- #[cfg(feature = "refungible")]
- CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, payer, data)?,
#[cfg(not(feature = "refungible"))]
CollectionMode::ReFungible => return unsupported!(T),
+
+ _ => {}
};
- Ok(id)
+
+ <PalletCommon<T>>::init_collection(sender, issuer, data)
}
fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult {
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -151,7 +151,6 @@
'up-rpc/std',
'up-sponsorship/std',
- "orml-tokens/std",
"orml-traits/std",
"orml-vesting/std",
"orml-xcm-support/std",
@@ -179,7 +178,6 @@
'frame-system/try-runtime',
'frame-try-runtime',
'frame-try-runtime?/try-runtime',
- 'orml-tokens/try-runtime',
'orml-vesting/try-runtime',
'orml-xtokens/try-runtime',
'pallet-app-promotion/try-runtime',
@@ -254,7 +252,6 @@
frame-support = { workspace = true }
frame-system = { workspace = true }
frame-system-rpc-runtime-api = { workspace = true }
-orml-tokens = { workspace = true }
orml-traits = { workspace = true }
orml-vesting = { workspace = true }
orml-xcm-support = { workspace = true }
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -150,7 +150,6 @@
'up-rpc/std',
'up-sponsorship/std',
- "orml-tokens/std",
"orml-traits/std",
"orml-vesting/std",
"orml-xcm-support/std",
@@ -175,7 +174,6 @@
'frame-support/try-runtime',
'frame-system/try-runtime',
'frame-try-runtime',
- 'orml-tokens/try-runtime',
'orml-vesting/try-runtime',
'orml-xtokens/try-runtime',
'pallet-app-promotion/try-runtime',
@@ -242,7 +240,6 @@
frame-support = { workspace = true }
frame-system = { workspace = true }
frame-system-rpc-runtime-api = { workspace = true }
-orml-tokens = { workspace = true }
orml-traits = { workspace = true }
orml-vesting = { workspace = true }
orml-xcm-support = { workspace = true }
runtime/tests/src/tests.rsdiffbeforeafterboth--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -2357,7 +2357,8 @@
#[test]
fn total_number_collections_bound_neg() {
new_test_ext().execute_with(|| {
- let origin1 = RuntimeOrigin::signed(1);
+ let user = 1;
+ let origin1 = RuntimeOrigin::signed(user);
for i in 1..=COLLECTION_NUMBER_LIMIT {
create_test_collection(&CollectionMode::NFT, CollectionId(i));
@@ -2376,6 +2377,7 @@
};
// 11-th collection in chain. Expects error
+ add_balance(user, CollectionCreationPrice::get() as u64 + 1);
assert_noop!(
Unique::create_collection_ex(origin1, data),
CommonError::<Test>::TotalCollectionsLimitExceeded
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -147,7 +147,6 @@
'up-rpc/std',
'up-sponsorship/std',
- "orml-tokens/std",
"orml-traits/std",
"orml-vesting/std",
"orml-xcm-support/std",
@@ -173,7 +172,6 @@
'frame-support/try-runtime',
'frame-system/try-runtime',
'frame-try-runtime',
- 'orml-tokens/try-runtime',
'orml-vesting/try-runtime',
'orml-xtokens/try-runtime',
'pallet-app-promotion/try-runtime',
@@ -245,7 +243,6 @@
frame-support = { workspace = true }
frame-system = { workspace = true }
frame-system-rpc-runtime-api = { workspace = true }
-orml-tokens = { workspace = true }
orml-traits = { workspace = true }
orml-vesting = { workspace = true }
orml-xcm-support = { workspace = true }