difftreelog
doc(pallet-fungible): document public api
in: master
3 files changed
pallets/fungible/src/common.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/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};20use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};21use pallet_common::{CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight};22use pallet_structure::Error as StructureError;23use sp_runtime::ArithmeticError;24use sp_std::{vec::Vec, vec};25use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};2627use crate::{28 Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,29};3031pub struct CommonWeights<T: Config>(PhantomData<T>);32impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {33 fn create_item() -> Weight {34 <SelfWeightOf<T>>::create_item()35 }3637 fn create_multiple_items(_data: &[CreateItemData]) -> Weight {38 // All items minted for the same user, so it works same as create_item39 Self::create_item()40 }4142 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {43 match data {44 CreateItemExData::Fungible(f) => {45 <SelfWeightOf<T>>::create_multiple_items_ex(f.len() as u32)46 }47 _ => 0,48 }49 }5051 fn burn_item() -> Weight {52 <SelfWeightOf<T>>::burn_item()53 }5455 fn set_collection_properties(_amount: u32) -> Weight {56 // Error57 058 }5960 fn delete_collection_properties(_amount: u32) -> Weight {61 // Error62 063 }6465 fn set_token_properties(_amount: u32) -> Weight {66 // Error67 068 }6970 fn delete_token_properties(_amount: u32) -> Weight {71 // Error72 073 }7475 fn set_token_property_permissions(_amount: u32) -> Weight {76 // Error77 078 }7980 fn transfer() -> Weight {81 <SelfWeightOf<T>>::transfer()82 }8384 fn approve() -> Weight {85 <SelfWeightOf<T>>::approve()86 }8788 fn transfer_from() -> Weight {89 <SelfWeightOf<T>>::transfer_from()90 }9192 fn burn_from() -> Weight {93 <SelfWeightOf<T>>::burn_from()94 }9596 fn burn_recursively_self_raw() -> Weight {97 // Read to get total balance98 Self::burn_item() + T::DbWeight::get().reads(1)99 }100101 fn burn_recursively_breadth_raw(_amount: u32) -> Weight {102 // Fungible tokens can't have children103 0104 }105}106107/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete108/// methods and adds weight info.109impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {110 fn create_item(111 &self,112 sender: T::CrossAccountId,113 to: T::CrossAccountId,114 data: up_data_structs::CreateItemData,115 nesting_budget: &dyn Budget,116 ) -> DispatchResultWithPostInfo {117 match data {118 up_data_structs::CreateItemData::Fungible(data) => with_weight(119 <Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),120 <CommonWeights<T>>::create_item(),121 ),122 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),123 }124 }125126 fn create_multiple_items(127 &self,128 sender: T::CrossAccountId,129 to: T::CrossAccountId,130 data: Vec<up_data_structs::CreateItemData>,131 nesting_budget: &dyn Budget,132 ) -> DispatchResultWithPostInfo {133 let mut sum: u128 = 0;134 for data in data {135 match data {136 up_data_structs::CreateItemData::Fungible(data) => {137 sum = sum138 .checked_add(data.value)139 .ok_or(ArithmeticError::Overflow)?;140 }141 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),142 }143 }144145 with_weight(146 <Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),147 <CommonWeights<T>>::create_item(),148 )149 }150151 fn create_multiple_items_ex(152 &self,153 sender: <T>::CrossAccountId,154 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,155 nesting_budget: &dyn Budget,156 ) -> DispatchResultWithPostInfo {157 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);158 let data = match data {159 up_data_structs::CreateItemExData::Fungible(f) => f,160 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),161 };162163 with_weight(164 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),165 weight,166 )167 }168169 fn burn_item(170 &self,171 sender: T::CrossAccountId,172 token: TokenId,173 amount: u128,174 ) -> DispatchResultWithPostInfo {175 ensure!(176 token == TokenId::default(),177 <Error<T>>::FungibleItemsHaveNoId178 );179180 with_weight(181 <Pallet<T>>::burn(self, &sender, amount),182 <CommonWeights<T>>::burn_item(),183 )184 }185186 fn burn_item_recursively(187 &self,188 sender: T::CrossAccountId,189 token: TokenId,190 self_budget: &dyn Budget,191 _breadth_budget: &dyn Budget,192 ) -> DispatchResultWithPostInfo {193 // Should not happen?194 ensure!(195 token == TokenId::default(),196 <Error<T>>::FungibleItemsHaveNoId197 );198 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);199200 with_weight(201 <Pallet<T>>::burn(self, &sender, <Balance<T>>::get((self.id, &sender))),202 <CommonWeights<T>>::burn_recursively_self_raw(),203 )204 }205206 fn transfer(207 &self,208 from: T::CrossAccountId,209 to: T::CrossAccountId,210 token: TokenId,211 amount: u128,212 nesting_budget: &dyn Budget,213 ) -> DispatchResultWithPostInfo {214 ensure!(215 token == TokenId::default(),216 <Error<T>>::FungibleItemsHaveNoId217 );218219 with_weight(220 <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),221 <CommonWeights<T>>::transfer(),222 )223 }224225 fn approve(226 &self,227 sender: T::CrossAccountId,228 spender: T::CrossAccountId,229 token: TokenId,230 amount: u128,231 ) -> DispatchResultWithPostInfo {232 ensure!(233 token == TokenId::default(),234 <Error<T>>::FungibleItemsHaveNoId235 );236237 with_weight(238 <Pallet<T>>::set_allowance(self, &sender, &spender, amount),239 <CommonWeights<T>>::approve(),240 )241 }242243 fn transfer_from(244 &self,245 sender: T::CrossAccountId,246 from: T::CrossAccountId,247 to: T::CrossAccountId,248 token: TokenId,249 amount: u128,250 nesting_budget: &dyn Budget,251 ) -> DispatchResultWithPostInfo {252 ensure!(253 token == TokenId::default(),254 <Error<T>>::FungibleItemsHaveNoId255 );256257 with_weight(258 <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),259 <CommonWeights<T>>::transfer_from(),260 )261 }262263 fn burn_from(264 &self,265 sender: T::CrossAccountId,266 from: T::CrossAccountId,267 token: TokenId,268 amount: u128,269 nesting_budget: &dyn Budget,270 ) -> DispatchResultWithPostInfo {271 ensure!(272 token == TokenId::default(),273 <Error<T>>::FungibleItemsHaveNoId274 );275276 with_weight(277 <Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),278 <CommonWeights<T>>::burn_from(),279 )280 }281282 fn set_collection_properties(283 &self,284 _sender: T::CrossAccountId,285 _property: Vec<Property>,286 ) -> DispatchResultWithPostInfo {287 fail!(<Error<T>>::SettingPropertiesNotAllowed)288 }289290 fn delete_collection_properties(291 &self,292 _sender: &T::CrossAccountId,293 _property_keys: Vec<PropertyKey>,294 ) -> DispatchResultWithPostInfo {295 fail!(<Error<T>>::SettingPropertiesNotAllowed)296 }297298 fn set_token_properties(299 &self,300 _sender: T::CrossAccountId,301 _token_id: TokenId,302 _property: Vec<Property>,303 ) -> DispatchResultWithPostInfo {304 fail!(<Error<T>>::SettingPropertiesNotAllowed)305 }306307 fn set_token_property_permissions(308 &self,309 _sender: &T::CrossAccountId,310 _property_permissions: Vec<PropertyKeyPermission>,311 ) -> DispatchResultWithPostInfo {312 fail!(<Error<T>>::SettingPropertiesNotAllowed)313 }314315 fn delete_token_properties(316 &self,317 _sender: T::CrossAccountId,318 _token_id: TokenId,319 _property_keys: Vec<PropertyKey>,320 ) -> DispatchResultWithPostInfo {321 fail!(<Error<T>>::SettingPropertiesNotAllowed)322 }323324 fn check_nesting(325 &self,326 _sender: <T>::CrossAccountId,327 _from: (CollectionId, TokenId),328 _under: TokenId,329 _budget: &dyn Budget,330 ) -> sp_runtime::DispatchResult {331 fail!(<Error<T>>::FungibleDisallowsNesting)332 }333334 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}335336 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}337338 fn collection_tokens(&self) -> Vec<TokenId> {339 vec![TokenId::default()]340 }341342 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {343 if <Balance<T>>::get((self.id, account)) != 0 {344 vec![TokenId::default()]345 } else {346 vec![]347 }348 }349350 fn token_exists(&self, token: TokenId) -> bool {351 token == TokenId::default()352 }353354 fn last_token_id(&self) -> TokenId {355 TokenId::default()356 }357358 fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {359 None360 }361362 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {363 None364 }365366 fn token_properties(367 &self,368 _token_id: TokenId,369 _keys: Option<Vec<PropertyKey>>,370 ) -> Vec<Property> {371 Vec::new()372 }373374 fn total_supply(&self) -> u32 {375 1376 }377378 fn account_balance(&self, account: T::CrossAccountId) -> u32 {379 if <Balance<T>>::get((self.id, account)) != 0 {380 1381 } else {382 0383 }384 }385386 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {387 if token != TokenId::default() {388 return 0;389 }390 <Balance<T>>::get((self.id, account))391 }392393 fn allowance(394 &self,395 sender: T::CrossAccountId,396 spender: T::CrossAccountId,397 token: TokenId,398 ) -> u128 {399 if token != TokenId::default() {400 return 0;401 }402 <Allowance<T>>::get((self.id, sender, spender))403 }404405 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {406 None407 }408}pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+//! ERC-20 standart support implementation.
+
use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
use core::convert::TryInto;
use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -14,6 +14,68 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+//! # Fungible Pallet
+//!
+//! The Fungible pallet provides functionality for dealing with fungible assets.
+//!
+//! - [`CreateItemData`]
+//! - [`Config`]
+//! - [`FungibleHandle`]
+//! - [`Pallet`]
+//! - [`TotalSupply`]
+//! - [`Balance`]
+//! - [`Allowance`]
+//! - [`Error`]
+//!
+//! ## Fungible tokens
+//!
+//! Fungible tokens or assets are divisible and non-unique. For instance,
+//! fiat currencies like the dollar are fungible: A $1 bill
+//! in New York City has the same value as a $1 bill in Miami.
+//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,
+//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s
+//! ability to maintain one standard value. As well, it needs to have uniform acceptance.
+//! This means that a currency’s history should not be able to affect its value,
+//! and this is due to the fact that each piece that is a part of the currency is equal
+//! in value when compared to every other piece of that exact same currency.
+//! In the world of cryptocurrencies, this is essentially a coin or a token
+//! that can be replaced by another identical coin or token, and they are
+//! both mutually interchangeable. A popular implementation of fungible tokens is
+//! the ERC-20 token standard.
+//!
+//! ### ERC-20
+//!
+//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,
+//! is a Token Standard that implements an API for tokens within Smart Contracts.
+//!
+//! Example functionalities ERC-20 provides:
+//!
+//! * transfer tokens from one account to another
+//! * get the current token balance of an account
+//! * get the total supply of the token available on the network
+//! * approve whether an amount of token from an account can be spent by a third-party account
+//!
+//! ## Overview
+//!
+//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:
+//!
+//! * Asset Issuance
+//! * Asset Transferal
+//! * Asset Destruction
+//! * Delegated Asset Transfers
+//!
+//! **NOTE:** The created fungible asset always has `token_id` = 0.
+//! So `tokenA` and `tokenB` will have different `collection_id`.
+//!
+//! ### Implementations
+//!
+//! The Fungible pallet provides implementations for the following traits.
+//!
+//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder):
+//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections
+//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight
+//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls
+
#![cfg_attr(not(feature = "std"), no_std)]
use core::ops::Deref;
@@ -57,13 +119,13 @@
pub enum Error<T> {
/// Not Fungible item data used to mint in Fungible collection.
NotFungibleDataUsedToMintFungibleCollectionToken,
- /// Not default id passed as TokenId argument
+ /// Not default id passed as TokenId argument.
FungibleItemsHaveNoId,
- /// Tried to set data for fungible item
+ /// Tried to set data for fungible item.
FungibleItemsDontHaveData,
- /// Fungible token does not support nested
+ /// Fungible token does not support nesting.
FungibleDisallowsNesting,
- /// Setting item properties is not allowed
+ /// Setting item properties is not allowed.
SettingPropertiesNotAllowed,
}
@@ -78,10 +140,12 @@
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
+ /// Total amount of fungible tokens inside a collection.
#[pallet::storage]
pub type TotalSupply<T: Config> =
StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;
+ /// Amount of tokens owned by an account inside a collection.
#[pallet::storage]
pub type Balance<T: Config> = StorageNMap<
Key = (
@@ -92,6 +156,7 @@
QueryKind = ValueQuery,
>;
+ /// Storage for delegated assets.
#[pallet::storage]
pub type Allowance<T: Config> = StorageNMap<
Key = (
@@ -103,15 +168,19 @@
QueryKind = ValueQuery,
>;
}
-
+/// Handler for fungible assets.
pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
impl<T: Config> FungibleHandle<T> {
+ /// Casts [pallet_common::CollectionHandle] into [FungibleHandle].
pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {
Self(inner)
}
+
+ /// Casts [FungibleHandle] into [pallet_common::CollectionHandle].
pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
self.0
}
+ /// Returns a mutable reference to the internal [pallet_common::CollectionHandle].
pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {
&mut self.0
}
@@ -132,13 +201,17 @@
}
}
+/// 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,
data: CreateCollectionData<T::AccountId>,
) -> Result<CollectionId, DispatchError> {
<PalletCommon<T>>::init_collection(owner, data, false)
}
+
+ /// Destroys a collection.
pub fn destroy_collection(
collection: FungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -159,10 +232,14 @@
Ok(())
}
+ ///Checks if collection has tokens. Return `true` if it has.
fn collection_has_tokens(collection_id: CollectionId) -> bool {
<TotalSupply<T>>::get(collection_id) != 0
}
+ /// Burns the specified amount of the token. If the token balance
+ /// or total supply is less than the given value,
+ /// it will return [DispatchError].
pub fn burn(
collection: &FungibleHandle<T>,
owner: &T::CrossAccountId,
@@ -207,6 +284,8 @@
Ok(())
}
+ /// Transfers the specified amount of tokens. Will check that
+ /// the transfer is allowed for the token.
pub fn transfer(
collection: &FungibleHandle<T>,
from: &T::CrossAccountId,
@@ -277,6 +356,7 @@
Ok(())
}
+ /// Minting tokens for multiple IDs.
pub fn create_multiple_items(
collection: &FungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -378,6 +458,7 @@
));
}
+ /// Sets the amount of owner tokens that the spender can manage.
pub fn set_allowance(
collection: &FungibleHandle<T>,
owner: &T::CrossAccountId,
@@ -441,6 +522,7 @@
Ok(allowance)
}
+ /// Transfers of tokens that `from` gave to `spender` to manage, to `to` ID.
pub fn transfer_from(
collection: &FungibleHandle<T>,
spender: &T::CrossAccountId,
@@ -460,6 +542,7 @@
Ok(())
}
+ /// Burns managed tokens.
pub fn burn_from(
collection: &FungibleHandle<T>,
spender: &T::CrossAccountId,