Skip to content

Commit fd076a1

Browse files
mrshiposhafranciscoaguirre
authored andcommitted
New NFT traits: granular and abstract interface (paritytech#5620)
This PR introduces a new set of traits that represent different asset operations in a granular and abstract way. The new abstractions provide an interface for collections and tokens for use in general and XCM contexts. To make the review easier and the point clearer, this PR's code was extracted from paritytech#4300 (which contains the new XCM adapters). The paritytech#4300 is now meant to become a follow-up to this one. Note: Thanks to @franciscoaguirre for a very productive discussion in Matrix. His questions are used in the Q&A notes. ## Motivation: issues of the existing traits v1 and v2 This PR is meant to solve several issues and limitations of the existing frame-support nonfungible traits (both v1 and v2). ### Derivative NFTs limitations The existing v1 and v2 nonfungible traits (both collection-less—"nonfungible.rs", singular; and in-collection—"nonfungible**s**.rs", plural) can create a new token only if its ID is already known. Combined with the corresponding XCM adapters implementation for v1 [collection-less](https://github.com/paritytech/polkadot-sdk/blob/4057ccd7a37396bc1c6d1742f418415af61b2787/polkadot/xcm/xcm-builder/src/nonfungible_adapter.rs#L208-L212), [in-collection](https://github.com/paritytech/polkadot-sdk/blob/4057ccd7a37396bc1c6d1742f418415af61b2787/polkadot/xcm/xcm-builder/src/nonfungibles_adapter.rs#L225-L229) (and [the unfinished one for v2](https://github.com/paritytech/polkadot-sdk/blob/3b401b02115e08f38f33ce8f3b3825e773a6113e/polkadot/xcm/xcm-builder/src/nonfungibles_v2_adapter.rs#L249-L254)), this means that, in general, _**the only**_ supported derivative NFTs are those whose chain-local IDs can be derived by the `Matcher` and the NFT engine can mint the token with the provided ID. It is presumed the chain-local ID is derived without the use of storage (i.e., statelessly) because all the standard matcher's implementations aren't meant to look into the storage. To implement an alternative approach where chain-local derivative IDs are derived statefully, workarounds are needed. In this case, a custom stateful Matcher is required, or the NFT engine must be modified if it doesn't support predefined IDs for new tokens. It is a valid use case if a chain has exactly one NFT engine, and its team wants to provide NFT derivatives in a way consistent with the rest of the NFTs on this chain. Usually, if a chain already supports NFTs (Unique Network, Acala, Aventus, Moonbeam, etc.), they use their own chain-local NFT IDs. Of course, it is possible to introduce a separate NFT engine just for derivatives and use XCM IDs as chain-local IDs there. However, if the chain has a related logic to the NFT engine (e.g., fractionalizing), introducing a separate NFT engine for derivatives would require changing the related logic or limiting it to originals. Also, in this case, the clients would need to treat originals and derivatives differently, increasing their maintenance burden. **The more related logic for a given NFT engine exists on-chain, the more changes will be required to support another instance of the NFT engine for derivatives.** <details> <summary><i>Q&A: AssetHub uses the two pallets approach local and foreign assets. Why is this not an issue there?</i></summary> >Since the primary goal of AssetHub (as far as I understand) is to host assets and not provide rich functionality around them (which is the task of other parachains), having a specialized NFT engine instance for derivatives is okay. Even if AssetHub would provide NFT-related operations (e.g., fractionalization), I think the number of different kinds of such operations would be limited, so it would be pretty easy to maintain them for two NFT engines. I even believe that supporting chain-local derivative IDs on AssetHub would be needlessly more complicated than having two NFT engines. </details> <details> <summary><i>Q&A: New traits open an opportunity for keeping derivatives on the same pallet. Thus, things like NFT fractionalization are reused without effort. Does it make sense to fractionalize a derivative?</i></summary> >I think it makes sense. Moreover, it could be one of the reasons for employing reserve-based transfer for an NFT. Imagine a chain with no such functionality, and you have an NFT on that chain. And you want to fractionalize that NFT. You can transfer the NFT to another chain that provides NFT fractionalization. This way, you can model shared ownership of the original asset via its derivative. The same would be true for any NFT operation not provided by the chain where the NFT is located, while another chain can provide the needed functionality. </details> Another thing about chain-local NFT IDs is that an NFT engine could provide some guarantees about its NFT IDs, such as that they are always sequential or convey some information. The chain's team might want to do the same for derivatives. In this case, it might be impossible to derive the derivative ID from the XCM ID statelessly (so the workarounds would be needed). The existing adapters and traits don't directly support all of these cases. Workarounds could exist, but using them will increase the integration cost, the review process, and maintenance efforts. The Polkadot SDK tries to provide general interfaces and tools, so it would be good to provide NFT interfaces/tools that are consistent and easily cover more use cases. ### Design issues #### Lack of generality The existing traits (v1 and v2) are too concrete, leading to code duplication and inconvenience. For example, two distinct sets of traits exist for collection-less and in-collection NFTs. The two sets are nearly the same. However, having two sets of traits necessitates providing two different XCM adapters. For instance, [this PR](paritytech#2924) introduced the `NonFungibleAdapter` (collection-less). The description states that the `NonFungibleAdapter` "will be useful for enabling cross-chain Coretime region transfers, as the existing `NonFungiblesAdapter`[^1] is unsuitable for this purpose", which is true. It is unsuitable (without workarounds, at least). The same will happen with any on-chain entity that wants to use NFTs via these interfaces. Hence, the very structure of the interfaces makes using NFTs as first-class citizens harder (due to code duplication). This is sad since NFTs could be utility objects similar to CoreTime regions. For instance, they could be various capability tokens, on-chain shared variables, in-game characters and objects, and all of that could interoperate. Another example of this issue is the methods of collections, which are very similar to the corresponding methods of tokens: `create_collection` / `mint_into`, `collection_attribute` / `attribute`, and so on. In many ways, a collection could be considered a variant of a non-fungible token, so it shouldn't be surprising that the methods are analogous. Therefore, there could be a universal interface for these things. <details> <summary><i>Q&A: there's a lot of duplication between nonfungible and nonfungibles. The SDK has the same with fungible and fungibles. Is this also a problem with fungible tokens?</i></summary> >I could argue that it is also a problem for fungibles, but I believe they are okay as they are. Firstly, fungible tokens are a simpler concept since, in one way or another, they represent the money-like value abstraction. It seems the number of different kinds of related operations is bound (in contrast to NFTs, which could be various utility objects with different related operations, just like objects in OOP). >Also, not all things that induce duplication apply to fungible(s) traits. For example, "a fungible collection" can not be viewed as a "fungible asset"—that's impossible, so having additional methods for "fungible collections" is okay. But at the same time, any collection (fungible or not) **can** be viewed as an NFT. It's not a "token" in the strict sense, but it is a unique object. This is precisely what NFTs represent. An NFT collection often has a similar interface to NFTs: create/transfer/destroy/metadata-related operations, etc. Of course, collections can have more methods that make sense only for collections but not their tokens, but this doesn't cancel the fact that collections can be viewed as another "kind" of NFTs. >Secondly, the fungible(s) trait sets are already granular. For example, multiple Inspect and Mutate traits are categorized by operation kind. Here is the Inspect/Mutate for [metadata](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/support/src/traits/tokens/fungibles/metadata.rs) and here is the separate traits for [holds](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/support/src/traits/tokens/fungibles/hold.rs). For comparison, the nonfungible(_v2)(s) trait sets have all the kinds of operations in uncategorized Inspect/Mutate/Transfer traits. >The fungible(s) traits are granular but not too abstract. I believe it is a good thing. Using the abstract traits from this PR, even for fungibles, is possible, but I see no reason to do so. A more concrete interface for fungibles seems even better because the very notion of fungibles outlines the possible related operations. </details> <details> <summary><i>Q&A: If it is not an issue for fungibles, why would this be an issue for NFTs?</i></summary> >Unlike fungibles, different NFTs could represent any object-like thing. Just like with objects in OOP, it is natural to expect them to have different inherent operations (e.g., different kinds of attributes, permission-based/role-based modification, etc.). The more abstract traits should help maintain interoperability between any NFT engine and other pallets. Even if we'd need some "adapters," they could be made easily because of the abstract traits. </details> #### An opinionated interface Both v1 and v2 trait sets are opinionated. The v1 set is less opinionated than v2, yet it also has some issues. For instance, why does the `burn` method provide a way to check if the operation is permitted, but `transfer` and `set_attribute` do not? In the `transfer` case, there is already an induced [mistake](paritytech#4073) in the XCM adapter. Even if we add an ownership check to all the methods, why should it be only the ownership check? There could be different permission checks. Even in this trait set, we can see that, for example, the `destroy` method for a collection [takes](https://github.com/paritytech/polkadot-sdk/blob/4057ccd7a37396bc1c6d1742f418415af61b2787/substrate/frame/support/src/traits/tokens/nonfungibles.rs#L161-L165) a witness parameter additional to the ownership check. The same goes for v2 and even more. For instance, the v2 `mint_into`, among other things, [takes](https://github.com/paritytech/polkadot-sdk/blob/7e7c33453eeb14f47c6c4d0f98cc982e485edc77/substrate/frame/support/src/traits/tokens/nonfungibles_v2.rs#L249) `deposit_collection_owner`, which is an implementation detail of pallet-nfts that shouldn't be part of a general interface. It also introduces four different attribute kinds: metadata, regular attributes, custom attributes, and system attributes. The motivation of why these particular attribute kinds are selected to be included in the general interface is unclear. Moreover, it is unclear why not all attribute kinds are mutable (not all have the corresponding methods in the `Mutate` trait). And even those that can be modified (`attribute` and `metadata`) have inconsistent interfaces: * `set_attribute` sets the attribute without any permission checks. * [in-collection](https://github.com/paritytech/polkadot-sdk/blob/7e7c33453eeb14f47c6c4d0f98cc982e485edc77/substrate/frame/support/src/traits/tokens/nonfungibles_v2.rs#L265-L273) * [collection-less](https://github.com/paritytech/polkadot-sdk/blob/7e7c33453eeb14f47c6c4d0f98cc982e485edc77/substrate/frame/support/src/traits/tokens/nonfungible_v2.rs#L143-L146) * [`set_metadata`](https://github.com/paritytech/polkadot-sdk/blob/7e7c33453eeb14f47c6c4d0f98cc982e485edc77/substrate/frame/support/src/traits/tokens/nonfungible_v2.rs#L161-L164) sets the metadata using the `who: AccountId` parameter for a permission check. * `set_metadata` is a collection-less variant of [`set_item_metadata`](https://github.com/paritytech/polkadot-sdk/blob/7e7c33453eeb14f47c6c4d0f98cc982e485edc77/substrate/frame/support/src/traits/tokens/nonfungibles_v2.rs#L313-L316), while `set_attribute` has the same name in both trait sets. * In contrast to `set_metadata`, other methods (even the `set_item_metadata`!) that do the permission check use `Option<AccountId>` instead of `AccountId`. * The same goes for the corresponding `clear_*` methods. This is all very confusing. I believe this confusion has already led to many inconsistencies in implementation and may one day lead to bugs. For example, if you look at the implementation of v2 traits in pallet-nfts, you can see that `attribute` [returns](https://github.com/paritytech/polkadot-sdk/blob/8d81f1e648a21d7d14f94bc86503d3c77ead5807/substrate/frame/nfts/src/impl_nonfungibles.rs#L44-L62) an attribute from `CollectionOwner` namespace or metadata, but `set_attribute` [sets](https://github.com/paritytech/polkadot-sdk/blob/8d81f1e648a21d7d14f94bc86503d3c77ead5807/substrate/frame/nfts/src/impl_nonfungibles.rs#L266-L280) an attribute in `Pallet` namespace (i.e., it sets a system attribute!). ### Future-proofing Similar to how the pallet-nfts introduced new kinds of attributes, other NFT engines could also introduce different kinds of NFT operations. Or have sophisticated permission checks. Instead of bloating the general interface with the concrete use cases, I believe it would be great to make it granular and flexible, which this PR aspires to achieve. This way, we can preserve the consistency of the interface, make its implementation for an NFT engine more straightforward (since the NFT engine will implement only what it needs), and the pallets like pallet-nft-fractionalization that use NFT engines would work with more NFT engines, increasing the interoperability between NFT engines and other on-chain mechanisms. ## New frame-support traits The new `asset_ops` module is added to `frame_support::traits::tokens`. It defines several "asset operations". We avoid duplicating the interfaces with the same idea by providing the possibility to implement them on different structures representing different asset kinds. For example, similar operations can be performed on Collections and NFTs, such as creating Collections/NFTs, transferring their ownership, managing their metadata, etc. The following "operations" are defined: * Create * Inspect * Update * Destroy * Stash * Restore <details> <summary>Q&A: What do Inspect and Update operations mean?</summary> >Inspect is an interface meant to inspect any information about an asset. This information could be 1) asset owner, 2) attribute bytes, 3) a flag representing the asset's ability to be transferred, or 4) any other "feature" of the asset. >The Update is the corresponding interface for updating this information. </details> <details> <summary>Q&A: What do Stash/Restore operations mean?</summary> >This can be considered a variant of "Locking," but I decided to call it "Stash" because the actual "lock" operation is represented by the `CanUpdate<Owner<AccountId>>` update strategy. "Stash" implies losing ownership of the token to the chain itself. The symmetrical "Restore" operation may restore the token to any location, not just the before-stash owner. It depends on the particular chain business logic. </details> Each operation can be implemented multiple times using different strategies associated with this operation. This PR provides the implementation of the new traits for pallet-uniques. ### A generic example: operations and strategies Let's illustrate how we can implement the new traits for an NFT engine. Imagine we have an NftEngine pallet (or a Smart Contract accessible from Rust; it doesn't matter), and we need to expose the following to other on-chain mechanisms: * Collection "from-to" transfer and a transfer without a check. * The similar transfers for NFTs * NFT force-transfers * A flag representing the ability of a collection to be transferred * The same flag for NFTs * NFT byte data * NFT attributes like in the pallet-uniques (byte data under a byte key) Here is how this will look: ```rust pub struct Collection<PalletInstance>(PhantomData<PalletInstance>); pub struct Token<PalletInstance>(PhantomData<PalletInstance>); impl AssetDefinition for Collection<NftEngine> { type Id = /* the collection ID type */; } impl AssetDefinition for Token<NftEngine> { type Id = /* the *full* NFT ID type */; } // --- Collection operations --- // The collection transfer without checks impl Update<Owner<AccountId>> for Collection<NftEngine> { fn update( class_id: &Self::Id, _strategy: Owner<AccountId>, new_owner: &AccountId, ) -> DispatchResult { todo!("use NftEngine internals to perform the collection transfer to the `new_owner`") } } // The collection "from-to" transfer impl Update<ChangeOwnerFrom<AccountId>> for Collection<NftEngine> { fn update( class_id: &Self::Id, strategy: ChangeOwnerFrom<AccountId>, new_owner: &AccountId, ) -> DispatchResult { let CheckState(from, ..) = strategy; todo!("check if `from` is the current owner"); // Reuse the previous impl Self::update(class_id, Owner::default(), new_owner) } } // A flag representing the ability of a collection to be transferred impl Inspect<CanUpdate<Owner<AccountId>>> for Collection<NftEngine> { fn inspect( class_id: &Self::Id, _can_transfer: CanUpdate<Owner<AccountId>>, ) -> Result<bool, DispatchError> { todo!("use NftEngine internals to learn if the collection can be transferred") } } // --- NFT operations --- // The NFT transfer implementation is similar in structure. // The NFT transfer without checks impl Update<Owner<AccountId>> for Token<NftEngine> { fn update( instance_id: &Self::Id, _strategy: Owner<AccountId>, new_owner: &AccountId, ) -> DispatchResult { todo!("use NftEngine internals to perform the NFT transfer") } } // The NFT "from-to" transfer impl Update<ChangeOwnerFrom<AccountId>> for Token<NftEngine> { fn update( instance_id: &Self::Id, strategy: ChangeOwnerFrom<AccountId><AccountId>, new_owner: &AccountId, ) -> DispatchResult { let CheckState(from, ..) = strategy; todo!("check if `from` is the current owner"); // Reuse the previous impl Self::transfer(instance_id, Owner::default(), new_owner) } } // There are meta-strategies like CheckOrigin, which carries an Origin and any internal strategy. // It abstracts origin checks for any possible operation. // For example, we can do this to implement NFT force-transfers impl Update<CheckOrigin<RuntimeOrigin, Owner<AccountId>>> for Token<NftEngine> { fn update( instance_id: &Self::Id, strategy: CheckOrigin<RuntimeOrigin, Owner<AccountId>>, new_owner: &AccountId, ) -> DispatchResult { let CheckOrigin(origin, owner_strategy) = strategy; ensure_root(origin)?; Self::transfer(instance_id, owner_strategy, new_owner) } } // A flag representing the ability of an NFT to be transferred impl Inspect<CanUpdate<Owner<AccountId>>> for Token<NftEngine> { fn inspect( instance_id: &Self::Id, _can_transfer: CanUpdate<Owner<AccountId>>, ) -> Result<bool, DispatchError> { todo!("use NftEngine internals to learn if the NFT can be transferred") } } // The NFT bytes (notice that we have a different return type because of the "Bytes" strategy). impl Inspect<Bytes> for Token<NftEngine> { fn inspect( instance_id: &Self::Id, _bytes: Bytes, ) -> Result<Vec<u8>, DispatchError> { todo!("use NftEngine internals to get the NFT bytes") } } // Some strategies like Bytes and CanUpdate are generic so that they can have different "parameters". // We can add a custom byte request called "Attribute" to make the attribute logic for NFTs. Its parameter carries the key. // Note: in this PR, pallet-uniques provides the Attribute request: https://github.com/UniqueNetwork/polkadot-sdk/blob/fb55a66a657b9e357a0b0a9490773221d3ef03bf/substrate/frame/uniques/src/types.rs#L151. // For self-containment, let's declare the pallet-uniques' `Attribute` here. pub struct Attribute<'a>(pub &'a [u8]); // The NFT attributes implementation impl<'a> Inspect<Bytes<Attribute<'a>>> for Token<NftEngine> { fn inspect( instance_id: &Self::Id, strategy: Bytes<Attribute>, ) -> Result<Vec<u8>, DispatchError> { let Bytes(Attribute(attribute_key)) = strategy; todo!("use NftEngine internals to get the attribute bytes") } } ``` For further examples, see how pallet-uniques implements these operations for [collections](https://github.com/UniqueNetwork/polkadot-sdk/blob/feature/asset-ops-traits-only/substrate/frame/uniques/src/asset_ops/collection.rs) and [items](https://github.com/UniqueNetwork/polkadot-sdk/blob/feature/asset-ops-traits-only/substrate/frame/uniques/src/asset_ops/item.rs). The usage examples can be found in the `asset_ops` module docs (which is based on [this comment](paritytech#5620 (comment))) and in the pallet-uniques tests. [^1]: Don't confuse `NonFungibleAdapter` (collection-less) and `NonFungiblesAdapter` (in-collection; see "s" in the name). --------- Co-authored-by: Francisco Aguirre <franciscoaguirreperez@gmail.com>
1 parent dc0d727 commit fd076a1

10 files changed

Lines changed: 2545 additions & 1 deletion

File tree

prdoc/pr_5620.prdoc

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
title: "New NFT traits: granular and abstract interface"
2+
3+
doc:
4+
- audience: Runtime Dev
5+
description: |-
6+
This PR introduces a new set of traits that represent different asset operations in a granular and abstract way.
7+
The new abstractions provide an interface for collections and tokens for use in general and XCM contexts.
8+
9+
crates:
10+
- name: frame-support
11+
bump: minor
12+
- name: pallet-uniques
13+
bump: minor

substrate/frame/support/src/traits/tokens.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
//! Traits for working with tokens and their associated datastructures.
1919
20+
pub mod asset_ops;
2021
pub mod currency;
2122
pub mod fungible;
2223
pub mod fungibles;
Lines changed: 321 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,321 @@
1+
// This file is part of Substrate.
2+
3+
// Copyright (C) Parity Technologies (UK) Ltd.
4+
// SPDX-License-Identifier: Apache-2.0
5+
6+
// Licensed under the Apache License, Version 2.0 (the "License");
7+
// you may not use this file except in compliance with the License.
8+
// You may obtain a copy of the License at
9+
//
10+
// http://www.apache.org/licenses/LICENSE-2.0
11+
//
12+
// Unless required by applicable law or agreed to in writing, software
13+
// distributed under the License is distributed on an "AS IS" BASIS,
14+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
// See the License for the specific language governing permissions and
16+
// limitations under the License.
17+
18+
//! Abstract asset operations traits.
19+
//!
20+
//! The following operations are defined:
21+
//! * [`Inspect`]
22+
//! * [`Update`]
23+
//! * [`Create`]
24+
//! * [`Destroy`]
25+
//! * [`Stash`]
26+
//! * [`Restore`]
27+
//!
28+
//! Also, all the operations above (except the `Create` operation) use
29+
//! the [`AssetDefinition`] to retrieve the `Id` type of the asset.
30+
//!
31+
//! An asset operation can be implemented multiple times
32+
//! using different strategies associated with this operation.
33+
//!
34+
//! A strategy defines the operation behavior,
35+
//! may supply additional parameters,
36+
//! and may define a return value type of the operation.
37+
//!
38+
//! ### Usage Example
39+
//!
40+
//! This example shows how to interact with pallet-uniques (assuming the pallet called Uniques in
41+
//! the chain’s Runtime) via the asset ops.
42+
//!
43+
//! If you are interested in the implementation example, you can look at the pallet-uniques
44+
//! implementation. You can check out the pallet-uniques tests if you want more examples of usage.
45+
//!
46+
//! ```rust,ignore
47+
//! type Collection = pallet_uniques::asset_ops::Collection<Uniques>;
48+
//! type Item = pallet_uniques::asset_ops::Item<Uniques>;
49+
//!
50+
//! // Collection creation
51+
//! //
52+
//! // Note the `Owner` and `Admin` are inspect strategies.
53+
//! //
54+
//! // **Any** inspect strategy can be used to produce a config value
55+
//! // using the `WithConfig` creation strategy.
56+
//! Collection::create(WithConfig::new(
57+
//! (
58+
//! Owner::with_config_value(collection_owner),
59+
//! Admin::with_config_value(collection_admin)
60+
//! ),
61+
//! PredefinedId::from(collection_id),
62+
//! )).unwrap();
63+
//!
64+
//! // Get the collection owner
65+
//! let owner = Collection::inspect(&collection_id, Owner::default()).unwrap();
66+
//!
67+
//! // Get the collection admin
68+
//! let admin = Collection::inspect(&collection_id, Admin::default()).unwrap();
69+
//!
70+
//! // Get collection metadata
71+
//! let metadata = Collection::inspect(&collection_id, Bytes::default()).unwrap();
72+
//!
73+
//! // Get collection attribute
74+
//! use pallet_uniques::asset_strategies::Attribute;
75+
//! let attr_key = "example-key";
76+
//! let attr_value = Collection::inspect(
77+
//! &collection_id,
78+
//! Bytes(Attribute(attr_key.as_slice())),
79+
//! ).unwrap();
80+
//!
81+
//! // Item creation (note the usage of the same strategy -- WithConfig)
82+
//! Item::create(WithConfig::new(
83+
//! Owner::with_config_value(item_owner),
84+
//! PredefinedId::from(item_id),
85+
//! )).unwrap();
86+
//!
87+
//! // Get the item owner
88+
//! let item_owner = Item::inspect(&(collection_id, item_id), Owner::default()).unwrap();
89+
//!
90+
//! // Get item attribute
91+
//! let attr_key = "example-key";
92+
//! let attr_value = Item::inspect(
93+
//! &(collection_id, item_id),
94+
//! Bytes(Attribute(attr_key.as_slice())),
95+
//! ).unwrap();
96+
//!
97+
//! // Unconditionally update the item's owner (unchecked transfer)
98+
//! Item::update(&(collection_id, item_id), Owner::default(), &bob).unwrap();
99+
//!
100+
//! // CheckOrigin then transfer
101+
//! Item::update(
102+
//! &(collection_id, item_id),
103+
//! CheckOrigin(RuntimeOrigin::root(), Owner::default()),
104+
//! &bob,
105+
//! ).unwrap();
106+
//!
107+
//! // From-To transfer
108+
//! Item::update(
109+
//! &(collection_id, item_id),
110+
//! ChangeOwnerFrom::check(alice),
111+
//! &bob,
112+
//! ).unwrap();
113+
//!
114+
//! // Lock item (forbid changing its Owner)
115+
//! //
116+
//! // Note that Owner strategy is turned into the `CanUpdate<Owner>` strategy
117+
//! // via the `as_can_update` function.
118+
//! //
119+
//! // **Any** update strategy can be turned into the `CanUpdate` this way.
120+
//! Item::update(
121+
//! &(collection_id, item_id),
122+
//! Owner::default().as_can_update(),
123+
//! false,
124+
//! );
125+
//! ```
126+
127+
use core::marker::PhantomData;
128+
use sp_runtime::DispatchError;
129+
use sp_std::vec::Vec;
130+
131+
pub mod common_strategies;
132+
133+
/// Trait for defining an asset.
134+
/// The definition must provide the `Id` type to identify the asset.
135+
pub trait AssetDefinition {
136+
/// Type for identifying the asset.
137+
type Id;
138+
}
139+
140+
/// Get the `Id` type of the asset definition.
141+
pub type AssetIdOf<T> = <T as AssetDefinition>::Id;
142+
143+
/// A strategy for use in the [`Inspect`] implementations.
144+
///
145+
/// The common inspect strategies are:
146+
/// * [`Bytes`](common_strategies::Bytes)
147+
/// * [`Owner`](common_strategies::Owner)
148+
/// * [`CanCreate`](common_strategies::CanCreate)
149+
/// * [`CanDestroy`](common_strategies::CanDestroy)
150+
/// * [`CanUpdate`](common_strategies::CanUpdate)
151+
pub trait InspectStrategy {
152+
/// The value representing the asset's state related to this `InspectStrategy`.
153+
type Value;
154+
}
155+
156+
/// A trait representing the ability of a certain asset to **provide** its state
157+
/// information.
158+
///
159+
/// This trait can be implemented multiple times using different
160+
/// [`inspect strategies`](InspectStrategy).
161+
///
162+
/// An inspect strategy defines how the asset state is identified/retrieved
163+
/// and what [`Value`](InspectStrategy::Value) type is returned.
164+
pub trait Inspect<Strategy: InspectStrategy>: AssetDefinition {
165+
/// Inspect state information of the asset
166+
/// using the given `id` and the inspect `strategy`.
167+
///
168+
/// The ID type is retrieved from the [`AssetDefinition`].
169+
fn inspect(id: &Self::Id, strategy: Strategy) -> Result<Strategy::Value, DispatchError>;
170+
}
171+
172+
/// A strategy for use in the [`Update`] implementations.
173+
///
174+
/// The common update strategies are:
175+
/// * [`Bytes`](common_strategies::Bytes)
176+
/// * [`CanCreate`](common_strategies::CanCreate)
177+
/// * [`CanDestroy`](common_strategies::CanDestroy)
178+
/// * [`CanUpdate`](common_strategies::CanUpdate)
179+
pub trait UpdateStrategy {
180+
/// The value to update the asset's state.
181+
/// Usually, it should be related to the corresponding `InspectStrategy::Value`.
182+
///
183+
/// For instance:
184+
/// * If the `Value` is `Vec<u8>`, the `UpdateValue` can be `Option<&'a [u8]>` (e.g., asset
185+
/// attributes that can be modified or deleted).
186+
/// * If the `Value` is `bool`, the `UpdateValue` can also be `bool`.
187+
type UpdateValue<'a>;
188+
189+
/// This type represents a successful asset state update.
190+
/// It will be in the [`Result`] type of the [`Update::update`] function.
191+
type Success;
192+
}
193+
194+
/// A trait representing the ability of a certain asset to **update** its state information.
195+
///
196+
/// This trait can be implemented multiple times using different
197+
/// [`update strategies`](UpdateStrategy).
198+
///
199+
/// An update strategy defines how the asset state is identified
200+
/// and what [`UpdateValue`](UpdateStrategy::UpdateValue) type is used.
201+
pub trait Update<Strategy: UpdateStrategy>: AssetDefinition {
202+
/// Update the state information of the asset
203+
/// using the given `id`, the update `strategy`, and the strategy's `update_value`.
204+
///
205+
/// The ID type is retrieved from the [`AssetDefinition`].
206+
fn update(
207+
id: &Self::Id,
208+
strategy: Strategy,
209+
update_value: Strategy::UpdateValue<'_>,
210+
) -> Result<Strategy::Success, DispatchError>;
211+
}
212+
213+
/// A strategy for use in the [`Create`] implementations.
214+
///
215+
/// The common "create" strategy is [`WithConfig`](common_strategies::WithConfig).
216+
pub trait CreateStrategy {
217+
/// This type represents a successful asset creation.
218+
/// It will be in the [`Result`] type of the [`Create::create`] function.
219+
type Success;
220+
}
221+
222+
/// An ID assignment approach to use in the "create" strategies.
223+
///
224+
/// The common ID assignments are:
225+
/// * [`AutoId`](common_strategies::AutoId)
226+
/// * [`PredefinedId`](common_strategies::PredefinedId)
227+
/// * [`DeriveAndReportId`](common_strategies::DeriveAndReportId)
228+
pub trait IdAssignment {
229+
/// The reported ID type.
230+
///
231+
/// Examples:
232+
/// * [`AutoId`](common_strategies::AutoId) returns the ID of the newly created asset
233+
/// * [`PredefinedId`](common_strategies::PredefinedId) accepts the ID to be assigned to the
234+
/// newly created asset
235+
/// * [`DeriveAndReportId`](common_strategies::DeriveAndReportId) returns the ID derived from
236+
/// the input parameters
237+
type ReportedId;
238+
}
239+
240+
/// A trait representing the ability of a certain asset to be created.
241+
///
242+
/// This trait can be implemented multiple times using different
243+
/// [`"create" strategies`](CreateStrategy).
244+
///
245+
/// A create strategy defines all aspects of asset creation including how an asset ID is assigned.
246+
pub trait Create<Strategy: CreateStrategy> {
247+
/// Create a new asset using the provided `strategy`.
248+
fn create(strategy: Strategy) -> Result<Strategy::Success, DispatchError>;
249+
}
250+
251+
/// A strategy for use in the [`Destroy`] implementations.
252+
///
253+
/// The common destroy strategies are:
254+
/// * [`NoParams`](common_strategies::NoParams)
255+
/// * [`IfOwnedBy`](common_strategies::IfOwnedBy)
256+
/// * [`WithWitness`](common_strategies::WithWitness)
257+
pub trait DestroyStrategy {
258+
/// This type represents a successful asset destruction.
259+
/// It will be in the [`Result`] type of the [`Destroy::destroy`] function.
260+
type Success;
261+
}
262+
263+
/// A trait representing the ability of a certain asset to be destroyed.
264+
///
265+
/// This trait can be implemented multiple times using different
266+
/// [`destroy strategies`](DestroyStrategy).
267+
///
268+
/// A destroy strategy defines destroy parameters and the result value type.
269+
pub trait Destroy<Strategy: DestroyStrategy>: AssetDefinition {
270+
/// Destroy the asset identified by the given `id` using the provided `strategy`.
271+
///
272+
/// The ID type is retrieved from the [`AssetDefinition`].
273+
fn destroy(id: &Self::Id, strategy: Strategy) -> Result<Strategy::Success, DispatchError>;
274+
}
275+
276+
/// A strategy for use in the [`Stash`] implementations.
277+
///
278+
/// The common stash strategies are:
279+
/// * [`NoParams`](common_strategies::NoParams)
280+
/// * [`IfOwnedBy`](common_strategies::IfOwnedBy)
281+
pub trait StashStrategy {
282+
/// This type represents a successful asset stashing.
283+
/// It will be in the [`Result`] type of the [`Stash::stash`] function.
284+
type Success;
285+
}
286+
287+
/// A trait representing the ability of a certain asset to be stashed.
288+
///
289+
/// This trait can be implemented multiple times using different
290+
/// [`stash strategies`](StashStrategy).
291+
///
292+
/// A stash strategy defines stash parameters.
293+
pub trait Stash<Strategy: StashStrategy>: AssetDefinition {
294+
/// Stash the asset identified by the given `id` using the provided `strategy`.
295+
///
296+
/// The ID type is retrieved from the [`AssetDefinition`].
297+
fn stash(id: &Self::Id, strategy: Strategy) -> Result<Strategy::Success, DispatchError>;
298+
}
299+
300+
/// A strategy for use in the [`Restore`] implementations.
301+
/// The common restore strategies are:
302+
/// * [`NoParams`](common_strategies::NoParams)
303+
/// * [`WithConfig`](common_strategies::WithConfig)
304+
pub trait RestoreStrategy {
305+
/// This type represents a successful asset restoration.
306+
/// It will be in the [`Result`] type of the [`Restore::restore`] function.
307+
type Success;
308+
}
309+
310+
/// A trait representing the ability of a certain asset to be restored.
311+
///
312+
/// This trait can be implemented multiple times using different
313+
/// [`restore strategies`](RestoreStrategy).
314+
///
315+
/// A restore strategy defines restore parameters.
316+
pub trait Restore<Strategy: RestoreStrategy>: AssetDefinition {
317+
/// Restore the asset identified by the given `id` using the provided `strategy`.
318+
///
319+
/// The ID type is retrieved from the [`AssetDefinition`].
320+
fn restore(id: &Self::Id, strategy: Strategy) -> Result<Strategy::Success, DispatchError>;
321+
}

0 commit comments

Comments
 (0)