1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
//! # Unique Assets Implementation: Commodities
//!
//! This pallet exposes capabilities for managing unique assets, also known as
//! non-fungible tokens (NFTs).
//!
//! - [`commodities::Trait`](./trait.Trait.html)
//! - [`Calls`](./enum.Call.html)
//! - [`Errors`](./enum.Error.html)
//! - [`Events`](./enum.RawEvent.html)
//!
//! ## Overview
//!
//! Assets that share a common metadata structure may be created and distributed
//! by an asset admin. Asset owners may burn assets or transfer their
//! ownership. Configuration parameters are used to limit the total number of a
//! type of asset that may exist as well as the number that any one account may
//! own. Assets are uniquely identified by the hash of the info that defines
//! them, as calculated by the runtime system's hashing algorithm.
//!
//! This pallet implements the [`UniqueAssets`](./nft/trait.UniqueAssets.html)
//! trait and is optimized for assets that are expected to be traded frequently.
//!
//! ### Dispatchable Functions
//!
//! * [`mint`](./enum.Call.html#variant.mint) - Use the provided asset info to
//!   create a new unique asset for the specified user. May only be called by
//!   the asset admin.
//!
//! * [`burn`](./enum.Call.html#variant.burn) - Destroy an asset. May only be
//!   called by asset owner.
//!
//! * [`transfer`](./enum.Call.html#variant.transfer) - Transfer ownership of
//!   an asset to another account. May only be called by current asset owner.

#![cfg_attr(not(feature = "std"), no_std)]

use codec::{Decode, Encode, FullCodec};
use frame_support::{
    decl_error, decl_event, decl_module, decl_storage, dispatch, ensure,
    traits::{EnsureOrigin, Get},
    Hashable,
};
use frame_system::{self as system, ensure_signed};
use sp_runtime::{
    traits::{Hash, Member},
    RuntimeDebug,
};
use sp_std::{
    cmp::{Eq, Ordering},
    fmt::Debug,
    vec::Vec,
};

pub mod nft;
pub use crate::nft::{UniqueAssets, NFT};

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

pub trait Trait<I = DefaultInstance>: system::Trait {
    /// The dispatch origin that is able to mint new instances of this type of asset.
    type AssetAdmin: EnsureOrigin<Self::Origin>;
    /// The data type that is used to describe this type of asset.
    type AssetInfo: Hashable + Member + Debug + Default + FullCodec;
    /// The maximum number of this type of asset that may exist (minted - burned).
    type AssetLimit: Get<u128>;
    /// The maximum number of this type of asset that any single account may own.
    type UserAssetLimit: Get<u64>;
    type Event: From<Event<Self, I>> + Into<<Self as system::Trait>::Event>;
}

/// The runtime system's hashing algorithm is used to uniquely identify assets.
pub type AssetId<T> = <T as frame_system::Trait>::Hash;

/// An alias for this pallet's NFT implementation.
pub type IdentifiedAssetFor<T, I> = IdentifiedAsset<AssetId<T>, <T as Trait<I>>::AssetInfo>;

/// A generic definition of an NFT that will be used by this pallet.
#[derive(Encode, Decode, Clone, Eq, RuntimeDebug)]
pub struct IdentifiedAsset<Hash, AssetInfo> {
    pub id: Hash,
    pub asset: AssetInfo,
}

impl<AssetId: Ord, AssetInfo: Eq> Ord for IdentifiedAsset<AssetId, AssetInfo> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.id.cmp(&other.id)
    }
}

impl<AssetId: Ord, AssetInfo> PartialOrd for IdentifiedAsset<AssetId, AssetInfo> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.id.cmp(&other.id))
    }
}

impl<AssetId: Eq, AssetInfo> PartialEq for IdentifiedAsset<AssetId, AssetInfo> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl<AssetId, AssetInfo> NFT for IdentifiedAsset<AssetId, AssetInfo> {
    type Id = AssetId;
    type Info = AssetInfo;
}

decl_storage! {
    trait Store for Module<T: Trait<I>, I: Instance = DefaultInstance> as Commodity {
        /// The total number of this type of asset that exists (minted - burned).
        Total get(fn total): u128 = 0;
        /// The total number of this type of asset that has been burned (may overflow).
        Burned get(fn burned): u128 = 0;
        /// The total number of this type of asset owned by an account.
        TotalForAccount get(fn total_for_account): map hasher(blake2_128_concat) T::AccountId => u64 = 0;
        /// A mapping from an account to a list of all of the assets of this type that are owned by it.
        AssetsForAccount get(fn assets_for_account): map hasher(blake2_128_concat) T::AccountId => Vec<IdentifiedAssetFor<T, I>>;
        /// A mapping from an asset ID to the account that owns it.
        AccountForAsset get(fn account_for_asset): map hasher(identity) AssetId<T> => T::AccountId;
    }
}

decl_event!(
    pub enum Event<T, I = DefaultInstance>
    where
        AssetId = <T as system::Trait>::Hash,
        AccountId = <T as system::Trait>::AccountId,
    {
        /// The asset has been burned.
        Burned(AssetId),
        /// The asset has been minted and distributed to the account.
        Minted(AssetId, AccountId),
        /// Ownership of the asset has been transferred to the account.
        Transferred(AssetId, AccountId),
    }
);

decl_error! {
    pub enum Error for Module<T: Trait<I>, I: Instance> {
        // Thrown when there is an attempt to mint a duplicate asset.
        AssetExists,
        // Thrown when there is an attempt to burn or transfer a nonexistent asset.
        NonexistentAsset,
        // Thrown when someone who is not the owner of an asset attempts to transfer or burn it.
        NotAssetOwner,
        // Thrown when the asset admin attempts to mint an asset and the maximum number of this
        // type of asset already exists.
        TooManyAssets,
        // Thrown when an attempt is made to mint or transfer an asset to an account that already
        // owns the maximum number of this type of asset.
        TooManyAssetsForAccount,
    }
}

decl_module! {
    pub struct Module<T: Trait<I>, I: Instance = DefaultInstance> for enum Call where origin: T::Origin {
        type Error = Error<T, I>;
        fn deposit_event() = default;

        /// Create a new unique asset from the provided asset info and identify the specified
        /// account as its owner. The ID of the new asset will be equal to the hash of the info
        /// that defines it, as calculated by the runtime system's hashing algorithm.
        ///
        /// The dispatch origin for this call must be the asset admin.
        ///
        /// This function will throw an error if it is called with asset info that describes
        /// an existing (duplicate) asset, if the maximum number of this type of asset already
        /// exists or if the specified owner already owns the maximum number of this type of
        /// asset.
        ///
        /// - `owner_account`: Receiver of the asset.
        /// - `asset_info`: The information that defines the asset.
        #[weight = 10_000]
        pub fn mint(origin, owner_account: T::AccountId, asset_info: T::AssetInfo) -> dispatch::DispatchResult {
            T::AssetAdmin::ensure_origin(origin)?;

            let asset_id = <Self as UniqueAssets<_>>::mint(&owner_account, asset_info)?;
            Self::deposit_event(RawEvent::Minted(asset_id, owner_account.clone()));
            Ok(())
        }

        /// Destroy the specified asset.
        ///
        /// The dispatch origin for this call must be the asset owner.
        ///
        /// - `asset_id`: The hash (calculated by the runtime system's hashing algorithm)
        ///   of the info that defines the asset to destroy.
        #[weight = 10_000]
        pub fn burn(origin, asset_id: AssetId<T>) -> dispatch::DispatchResult {
            let who = ensure_signed(origin)?;
            ensure!(who == Self::account_for_asset(&asset_id), Error::<T, I>::NotAssetOwner);

            <Self as UniqueAssets<_>>::burn(&asset_id)?;
            Self::deposit_event(RawEvent::Burned(asset_id.clone()));
            Ok(())
        }

        /// Transfer an asset to a new owner.
        ///
        /// The dispatch origin for this call must be the asset owner.
        ///
        /// This function will throw an error if the new owner already owns the maximum
        /// number of this type of asset.
        ///
        /// - `dest_account`: Receiver of the asset.
        /// - `asset_id`: The hash (calculated by the runtime system's hashing algorithm)
        ///   of the info that defines the asset to destroy.
        #[weight = 10_000]
        pub fn transfer(origin, dest_account: T::AccountId, asset_id: AssetId<T>) -> dispatch::DispatchResult {
            let who = ensure_signed(origin)?;
            ensure!(who == Self::account_for_asset(&asset_id), Error::<T, I>::NotAssetOwner);

            <Self as UniqueAssets<_>>::transfer(&dest_account, &asset_id)?;
            Self::deposit_event(RawEvent::Transferred(asset_id.clone(), dest_account.clone()));
            Ok(())
        }
    }
}

impl<T: Trait<I>, I: Instance> UniqueAssets<IdentifiedAsset<AssetId<T>, <T as Trait<I>>::AssetInfo>>
    for Module<T, I>
{
    type AccountId = <T as system::Trait>::AccountId;
    type AssetLimit = T::AssetLimit;
    type UserAssetLimit = T::UserAssetLimit;

    fn total() -> u128 {
        Self::total()
    }

    fn burned() -> u128 {
        Self::burned()
    }

    fn total_for_account(account: &T::AccountId) -> u64 {
        Self::total_for_account(account)
    }

    fn assets_for_account(
        account: &T::AccountId,
    ) -> Vec<IdentifiedAsset<AssetId<T>, <T as Trait<I>>::AssetInfo>> {
        Self::assets_for_account(account)
    }

    fn owner_of(asset_id: &AssetId<T>) -> T::AccountId {
        Self::account_for_asset(asset_id)
    }

    fn mint(
        owner_account: &T::AccountId,
        asset_info: <T as Trait<I>>::AssetInfo,
    ) -> dispatch::result::Result<AssetId<T>, dispatch::DispatchError> {
        let asset_id = T::Hashing::hash_of(&asset_info);

        ensure!(
            !AccountForAsset::<T, I>::contains_key(&asset_id),
            Error::<T, I>::AssetExists
        );

        ensure!(
            Self::total_for_account(owner_account) < T::UserAssetLimit::get(),
            Error::<T, I>::TooManyAssetsForAccount
        );

        ensure!(
            Self::total() < T::AssetLimit::get(),
            Error::<T, I>::TooManyAssets
        );

        let new_asset = IdentifiedAsset {
            id: asset_id,
            asset: asset_info,
        };

        Total::<I>::mutate(|total| *total += 1);
        TotalForAccount::<T, I>::mutate(owner_account, |total| *total += 1);
        AssetsForAccount::<T, I>::mutate(owner_account, |assets| {
            match assets.binary_search(&new_asset) {
                Ok(_pos) => {} // should never happen
                Err(pos) => assets.insert(pos, new_asset),
            }
        });
        AccountForAsset::<T, I>::insert(asset_id, &owner_account);

        Ok(asset_id)
    }

    fn burn(asset_id: &AssetId<T>) -> dispatch::DispatchResult {
        let owner = Self::owner_of(asset_id);
        ensure!(
            owner != T::AccountId::default(),
            Error::<T, I>::NonexistentAsset
        );

        let burn_asset = IdentifiedAsset::<AssetId<T>, <T as Trait<I>>::AssetInfo> {
            id: *asset_id,
            asset: <T as Trait<I>>::AssetInfo::default(),
        };

        Total::<I>::mutate(|total| *total -= 1);
        Burned::<I>::mutate(|total| *total += 1);
        TotalForAccount::<T, I>::mutate(&owner, |total| *total -= 1);
        AssetsForAccount::<T, I>::mutate(owner, |assets| {
            let pos = assets
                .binary_search(&burn_asset)
                .expect("We already checked that we have the correct owner; qed");
            assets.remove(pos);
        });
        AccountForAsset::<T, I>::remove(&asset_id);

        Ok(())
    }

    fn transfer(dest_account: &T::AccountId, asset_id: &AssetId<T>) -> dispatch::DispatchResult {
        let owner = Self::owner_of(&asset_id);
        ensure!(
            owner != T::AccountId::default(),
            Error::<T, I>::NonexistentAsset
        );

        ensure!(
            Self::total_for_account(dest_account) < T::UserAssetLimit::get(),
            Error::<T, I>::TooManyAssetsForAccount
        );

        let xfer_asset = IdentifiedAsset::<AssetId<T>, <T as Trait<I>>::AssetInfo> {
            id: *asset_id,
            asset: <T as Trait<I>>::AssetInfo::default(),
        };

        TotalForAccount::<T, I>::mutate(&owner, |total| *total -= 1);
        TotalForAccount::<T, I>::mutate(dest_account, |total| *total += 1);
        let asset = AssetsForAccount::<T, I>::mutate(owner, |assets| {
            let pos = assets
                .binary_search(&xfer_asset)
                .expect("We already checked that we have the correct owner; qed");
            assets.remove(pos)
        });
        AssetsForAccount::<T, I>::mutate(dest_account, |assets| {
            match assets.binary_search(&asset) {
                Ok(_pos) => {} // should never happen
                Err(pos) => assets.insert(pos, asset),
            }
        });
        AccountForAsset::<T, I>::insert(&asset_id, &dest_account);

        Ok(())
    }
}