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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! # Assets Module //! //! A simple, secure module for dealing with fungible assets. //! //! ## Overview //! //! The Assets module provides functionality for asset management of fungible asset classes //! with a fixed supply, including: //! //! * Asset Issuance //! * Asset Transfer //! * Asset Destruction //! //! To use it in your runtime, you need to implement the assets [`Trait`](./trait.Trait.html). //! //! The supported dispatchable functions are documented in the [`Call`](./enum.Call.html) enum. //! //! ### Terminology //! //! * **Asset issuance:** The creation of a new asset, whose total supply will belong to the //! account that issues the asset. //! * **Asset transfer:** The action of transferring assets from one account to another. //! * **Asset destruction:** The process of an account removing its entire holding of an asset. //! * **Fungible asset:** An asset whose units are interchangeable. //! * **Non-fungible asset:** An asset for which each unit has unique characteristics. //! //! ### Goals //! //! The assets system in Substrate is designed to make the following possible: //! //! * Issue a unique asset to its creator's account. //! * Move assets between accounts. //! * Remove an account's balance of an asset when requested by that account's owner and update //! the asset's total supply. //! //! ## Interface //! //! ### Dispatchable Functions //! //! * `issue` - Issues the total supply of a new fungible asset to the account of the caller of the function. //! * `transfer` - Transfers an `amount` of units of fungible asset `id` from the balance of //! the function caller's account (`origin`) to a `target` account. //! * `destroy` - Destroys the entire holding of a fungible asset `id` associated with the account //! that called the function. //! //! Please refer to the [`Call`](./enum.Call.html) enum and its associated variants for documentation on each function. //! //! ### Public Functions //! <!-- Original author of descriptions: @gavofyork --> //! //! * `balance` - Get the asset `id` balance of `who`. //! * `total_supply` - Get the total supply of an asset `id`. //! //! Please refer to the [`Module`](./struct.Module.html) struct for details on publicly available functions. //! //! ## Usage //! //! The following example shows how to use the Assets module in your runtime by exposing public functions to: //! //! * Issue a new fungible asset for a token distribution event (airdrop). //! * Query the fungible asset holding balance of an account. //! * Query the total supply of a fungible asset that has been issued. //! //! ### Prerequisites //! //! Import the Assets module and types and derive your runtime's configuration traits from the Assets module trait. //! //! ### Simple Code Snippet //! //! ```rust,ignore //! use pallet_assets as assets; //! use frame_support::{decl_module, dispatch, ensure}; //! use frame_system::{self as system, ensure_signed}; //! //! pub trait Trait: assets::Trait { } //! //! decl_module! { //! pub struct Module<T: Trait> for enum Call where origin: T::Origin { //! pub fn issue_token_airdrop(origin) -> dispatch::DispatchResult { //! let sender = ensure_signed(origin).map_err(|e| e.as_str())?; //! //! const ACCOUNT_ALICE: u64 = 1; //! const ACCOUNT_BOB: u64 = 2; //! const COUNT_AIRDROP_RECIPIENTS: u64 = 2; //! const TOKENS_FIXED_SUPPLY: u64 = 100; //! //! ensure!(!COUNT_AIRDROP_RECIPIENTS.is_zero(), "Divide by zero error."); //! //! let asset_id = Self::next_asset_id(); //! //! <NextAssetId<T>>::mutate(|asset_id| *asset_id += 1); //! <Balances<T>>::insert((asset_id, &ACCOUNT_ALICE), TOKENS_FIXED_SUPPLY / COUNT_AIRDROP_RECIPIENTS); //! <Balances<T>>::insert((asset_id, &ACCOUNT_BOB), TOKENS_FIXED_SUPPLY / COUNT_AIRDROP_RECIPIENTS); //! <TotalSupply<T>>::insert(asset_id, TOKENS_FIXED_SUPPLY); //! //! Self::deposit_event(RawEvent::Issued(asset_id, sender, TOKENS_FIXED_SUPPLY)); //! Ok(()) //! } //! } //! } //! ``` //! //! ## Assumptions //! //! Below are assumptions that must be held when using this module. If any of //! them are violated, the behavior of this module is undefined. //! //! * The total count of assets should be less than //! `Trait::AssetId::max_value()`. //! //! ## Related Modules //! //! * [`System`](../frame_system/index.html) //! * [`Support`](../frame_support/index.html) // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{Parameter, decl_module, decl_event, decl_storage, decl_error, ensure}; use sp_runtime::traits::{Member, AtLeast32Bit, Zero, StaticLookup}; use frame_system::{self as system, ensure_signed}; use sp_runtime::traits::One; /// The module configuration trait. pub trait Trait: frame_system::Trait { /// The overarching event type. type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>; /// The units in which we record balances. type Balance: Member + Parameter + AtLeast32Bit + Default + Copy; /// The arithmetic type of asset identifier. type AssetId: Parameter + AtLeast32Bit + Default + Copy; } decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; /// Issue a new class of fungible assets. There are, and will only ever be, `total` /// such assets and they'll all belong to the `origin` initially. It will have an /// identifier `AssetId` instance: this will be specified in the `Issued` event. /// /// # <weight> /// - `O(1)` /// - 1 storage mutation (codec `O(1)`). /// - 2 storage writes (condec `O(1)`). /// - 1 event. /// # </weight> #[weight = 0] fn issue(origin, #[compact] total: T::Balance) { let origin = ensure_signed(origin)?; let id = Self::next_asset_id(); <NextAssetId<T>>::mutate(|id| *id += One::one()); <Balances<T>>::insert((id, &origin), total); <TotalSupply<T>>::insert(id, total); Self::deposit_event(RawEvent::Issued(id, origin, total)); } /// Move some assets from one holder to another. /// /// # <weight> /// - `O(1)` /// - 1 static lookup /// - 2 storage mutations (codec `O(1)`). /// - 1 event. /// # </weight> #[weight = 0] fn transfer(origin, #[compact] id: T::AssetId, target: <T::Lookup as StaticLookup>::Source, #[compact] amount: T::Balance ) { let origin = ensure_signed(origin)?; let origin_account = (id, origin.clone()); let origin_balance = <Balances<T>>::get(&origin_account); let target = T::Lookup::lookup(target)?; ensure!(!amount.is_zero(), Error::<T>::AmountZero); ensure!(origin_balance >= amount, Error::<T>::BalanceLow); Self::deposit_event(RawEvent::Transferred(id, origin, target.clone(), amount)); <Balances<T>>::insert(origin_account, origin_balance - amount); <Balances<T>>::mutate((id, target), |balance| *balance += amount); } /// Destroy any assets of `id` owned by `origin`. /// /// # <weight> /// - `O(1)` /// - 1 storage mutation (codec `O(1)`). /// - 1 storage deletion (codec `O(1)`). /// - 1 event. /// # </weight> #[weight = 0] fn destroy(origin, #[compact] id: T::AssetId) { let origin = ensure_signed(origin)?; let balance = <Balances<T>>::take((id, &origin)); ensure!(!balance.is_zero(), Error::<T>::BalanceZero); <TotalSupply<T>>::mutate(id, |total_supply| *total_supply -= balance); Self::deposit_event(RawEvent::Destroyed(id, origin, balance)); } } } decl_event! { pub enum Event<T> where <T as frame_system::Trait>::AccountId, <T as Trait>::Balance, <T as Trait>::AssetId, { /// Some assets were issued. Issued(AssetId, AccountId, Balance), /// Some assets were transferred. Transferred(AssetId, AccountId, AccountId, Balance), /// Some assets were destroyed. Destroyed(AssetId, AccountId, Balance), } } decl_error! { pub enum Error for Module<T: Trait> { /// Transfer amount should be non-zero AmountZero, /// Account balance must be greater than or equal to the transfer amount BalanceLow, /// Balance should be non-zero BalanceZero, } } decl_storage! { trait Store for Module<T: Trait> as Assets { /// The number of units of assets held by any given account. Balances: map hasher(blake2_128_concat) (T::AssetId, T::AccountId) => T::Balance; /// The next asset identifier up for grabs. NextAssetId get(fn next_asset_id): T::AssetId; /// The total unit supply of an asset. /// /// TWOX-NOTE: `AssetId` is trusted, so this is safe. TotalSupply: map hasher(twox_64_concat) T::AssetId => T::Balance; } } // The main implementation block for the module. impl<T: Trait> Module<T> { // Public immutables /// Get the asset `id` balance of `who`. pub fn balance(id: T::AssetId, who: T::AccountId) -> T::Balance { <Balances<T>>::get((id, who)) } /// Get the total supply of an asset `id`. pub fn total_supply(id: T::AssetId) -> T::Balance { <TotalSupply<T>>::get(id) } } #[cfg(test)] mod tests { use super::*; use frame_support::{impl_outer_origin, assert_ok, assert_noop, parameter_types, weights::Weight}; use sp_core::H256; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; impl_outer_origin! { pub enum Origin for Test where system = frame_system {} } // For testing the pallet, we construct most of a mock runtime. This means // first constructing a configuration type (`Test`) which `impl`s each of the // configuration traits of pallets we want to use. #[derive(Clone, Eq, PartialEq)] pub struct Test; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type Call = (); type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; type DbWeight = (); type BlockExecutionWeight = (); type ExtrinsicBaseWeight = (); type MaximumExtrinsicWeight = MaximumBlockWeight; type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); type ModuleToIndex = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); } impl Trait for Test { type Event = (); type Balance = u64; type AssetId = u32; } type Assets = Module<Test>; // This function basically just builds a genesis storage key/value store according to // our desired mockup. fn new_test_ext() -> sp_io::TestExternalities { frame_system::GenesisConfig::default().build_storage::<Test>().unwrap().into() } #[test] fn issuing_asset_units_to_issuer_should_work() { new_test_ext().execute_with(|| { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); }); } #[test] fn querying_total_supply_should_work() { new_test_ext().execute_with(|| { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); assert_eq!(Assets::balance(0, 1), 50); assert_eq!(Assets::balance(0, 2), 50); assert_ok!(Assets::transfer(Origin::signed(2), 0, 3, 31)); assert_eq!(Assets::balance(0, 1), 50); assert_eq!(Assets::balance(0, 2), 19); assert_eq!(Assets::balance(0, 3), 31); assert_ok!(Assets::destroy(Origin::signed(3), 0)); assert_eq!(Assets::total_supply(0), 69); }); } #[test] fn transferring_amount_above_available_balance_should_work() { new_test_ext().execute_with(|| { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); assert_eq!(Assets::balance(0, 1), 50); assert_eq!(Assets::balance(0, 2), 50); }); } #[test] fn transferring_amount_more_than_available_balance_should_not_work() { new_test_ext().execute_with(|| { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); assert_eq!(Assets::balance(0, 1), 50); assert_eq!(Assets::balance(0, 2), 50); assert_ok!(Assets::destroy(Origin::signed(1), 0)); assert_eq!(Assets::balance(0, 1), 0); assert_noop!(Assets::transfer(Origin::signed(1), 0, 1, 50), Error::<Test>::BalanceLow); }); } #[test] fn transferring_less_than_one_unit_should_not_work() { new_test_ext().execute_with(|| { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 0), Error::<Test>::AmountZero); }); } #[test] fn transferring_more_units_than_total_supply_should_not_work() { new_test_ext().execute_with(|| { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 101), Error::<Test>::BalanceLow); }); } #[test] fn destroying_asset_balance_with_positive_balance_should_work() { new_test_ext().execute_with(|| { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::destroy(Origin::signed(1), 0)); }); } #[test] fn destroying_asset_balance_with_zero_balance_should_not_work() { new_test_ext().execute_with(|| { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 2), 0); assert_noop!(Assets::destroy(Origin::signed(2), 0), Error::<Test>::BalanceZero); }); } }