difftreelog
doc(pallet-fungible): document public api
in: master
3 files changed
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -104,6 +104,8 @@
}
}
+/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete
+/// methods and adds weight info.
impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {
fn create_item(
&self,
pallets/fungible/src/erc.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::char::{REPLACEMENT_CHARACTER, decode_utf16};18use core::convert::TryInto;19use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};20use up_data_structs::CollectionMode;21use pallet_common::erc::{CommonEvmHandler, PrecompileResult};22use sp_std::vec::Vec;23use pallet_evm::{account::CrossAccountId, PrecompileHandle};24use pallet_evm_coder_substrate::{call, dispatch_to_evm};25use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};26use pallet_common::{CollectionHandle, erc::CollectionCall};2728use crate::{29 Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,30 weights::WeightInfo,31};3233#[derive(ToLog)]34pub enum ERC20Events {35 Transfer {36 #[indexed]37 from: address,38 #[indexed]39 to: address,40 value: uint256,41 },42 Approval {43 #[indexed]44 owner: address,45 #[indexed]46 spender: address,47 value: uint256,48 },49}5051#[solidity_interface(name = "ERC20", events(ERC20Events))]52impl<T: Config> FungibleHandle<T> {53 fn name(&self) -> Result<string> {54 Ok(decode_utf16(self.name.iter().copied())55 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))56 .collect::<string>())57 }58 fn symbol(&self) -> Result<string> {59 Ok(string::from_utf8_lossy(&self.token_prefix).into())60 }61 fn total_supply(&self) -> Result<uint256> {62 self.consume_store_reads(1)?;63 Ok(<TotalSupply<T>>::get(self.id).into())64 }6566 fn decimals(&self) -> Result<uint8> {67 Ok(if let CollectionMode::Fungible(decimals) = &self.mode {68 *decimals69 } else {70 unreachable!()71 })72 }73 fn balance_of(&self, owner: address) -> Result<uint256> {74 self.consume_store_reads(1)?;75 let owner = T::CrossAccountId::from_eth(owner);76 let balance = <Balance<T>>::get((self.id, owner));77 Ok(balance.into())78 }79 #[weight(<SelfWeightOf<T>>::transfer())]80 fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {81 let caller = T::CrossAccountId::from_eth(caller);82 let to = T::CrossAccountId::from_eth(to);83 let amount = amount.try_into().map_err(|_| "amount overflow")?;84 let budget = self85 .recorder86 .weight_calls_budget(<StructureWeight<T>>::find_parent());8788 <Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;89 Ok(true)90 }91 #[weight(<SelfWeightOf<T>>::transfer_from())]92 fn transfer_from(93 &mut self,94 caller: caller,95 from: address,96 to: address,97 amount: uint256,98 ) -> Result<bool> {99 let caller = T::CrossAccountId::from_eth(caller);100 let from = T::CrossAccountId::from_eth(from);101 let to = T::CrossAccountId::from_eth(to);102 let amount = amount.try_into().map_err(|_| "amount overflow")?;103 let budget = self104 .recorder105 .weight_calls_budget(<StructureWeight<T>>::find_parent());106107 <Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)108 .map_err(dispatch_to_evm::<T>)?;109 Ok(true)110 }111 #[weight(<SelfWeightOf<T>>::approve())]112 fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {113 let caller = T::CrossAccountId::from_eth(caller);114 let spender = T::CrossAccountId::from_eth(spender);115 let amount = amount.try_into().map_err(|_| "amount overflow")?;116117 <Pallet<T>>::set_allowance(self, &caller, &spender, amount)118 .map_err(dispatch_to_evm::<T>)?;119 Ok(true)120 }121 fn allowance(&self, owner: address, spender: address) -> Result<uint256> {122 self.consume_store_reads(1)?;123 let owner = T::CrossAccountId::from_eth(owner);124 let spender = T::CrossAccountId::from_eth(spender);125126 Ok(<Allowance<T>>::get((self.id, owner, spender)).into())127 }128}129130#[solidity_interface(name = "ERC20UniqueExtensions")]131impl<T: Config> FungibleHandle<T> {132 #[weight(<SelfWeightOf<T>>::burn_from())]133 fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {134 let caller = T::CrossAccountId::from_eth(caller);135 let from = T::CrossAccountId::from_eth(from);136 let amount = amount.try_into().map_err(|_| "amount overflow")?;137 let budget = self138 .recorder139 .weight_calls_budget(<StructureWeight<T>>::find_parent());140141 <Pallet<T>>::burn_from(self, &caller, &from, amount, &budget)142 .map_err(dispatch_to_evm::<T>)?;143 Ok(true)144 }145}146147#[solidity_interface(148 name = "UniqueFungible",149 is(150 ERC20,151 ERC20UniqueExtensions,152 via("CollectionHandle<T>", common_mut, Collection)153 )154)]155impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> {}156157generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);158generate_stubgen!(gen_iface, UniqueFungibleCall<()>, false);159160impl<T: Config> CommonEvmHandler for FungibleHandle<T>161where162 T::AccountId: From<[u8; 32]>,163{164 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");165166 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {167 call::<T, UniqueFungibleCall<T>, _, _>(handle, self)168 }169}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//! ERC-20 standart support implementation.1819use core::char::{REPLACEMENT_CHARACTER, decode_utf16};20use core::convert::TryInto;21use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};22use up_data_structs::CollectionMode;23use pallet_common::erc::{CommonEvmHandler, PrecompileResult};24use sp_std::vec::Vec;25use pallet_evm::{account::CrossAccountId, PrecompileHandle};26use pallet_evm_coder_substrate::{call, dispatch_to_evm};27use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};28use pallet_common::{CollectionHandle, erc::CollectionCall};2930use crate::{31 Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,32 weights::WeightInfo,33};3435#[derive(ToLog)]36pub enum ERC20Events {37 Transfer {38 #[indexed]39 from: address,40 #[indexed]41 to: address,42 value: uint256,43 },44 Approval {45 #[indexed]46 owner: address,47 #[indexed]48 spender: address,49 value: uint256,50 },51}5253#[solidity_interface(name = "ERC20", events(ERC20Events))]54impl<T: Config> FungibleHandle<T> {55 fn name(&self) -> Result<string> {56 Ok(decode_utf16(self.name.iter().copied())57 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))58 .collect::<string>())59 }60 fn symbol(&self) -> Result<string> {61 Ok(string::from_utf8_lossy(&self.token_prefix).into())62 }63 fn total_supply(&self) -> Result<uint256> {64 self.consume_store_reads(1)?;65 Ok(<TotalSupply<T>>::get(self.id).into())66 }6768 fn decimals(&self) -> Result<uint8> {69 Ok(if let CollectionMode::Fungible(decimals) = &self.mode {70 *decimals71 } else {72 unreachable!()73 })74 }75 fn balance_of(&self, owner: address) -> Result<uint256> {76 self.consume_store_reads(1)?;77 let owner = T::CrossAccountId::from_eth(owner);78 let balance = <Balance<T>>::get((self.id, owner));79 Ok(balance.into())80 }81 #[weight(<SelfWeightOf<T>>::transfer())]82 fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {83 let caller = T::CrossAccountId::from_eth(caller);84 let to = T::CrossAccountId::from_eth(to);85 let amount = amount.try_into().map_err(|_| "amount overflow")?;86 let budget = self87 .recorder88 .weight_calls_budget(<StructureWeight<T>>::find_parent());8990 <Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;91 Ok(true)92 }93 #[weight(<SelfWeightOf<T>>::transfer_from())]94 fn transfer_from(95 &mut self,96 caller: caller,97 from: address,98 to: address,99 amount: uint256,100 ) -> Result<bool> {101 let caller = T::CrossAccountId::from_eth(caller);102 let from = T::CrossAccountId::from_eth(from);103 let to = T::CrossAccountId::from_eth(to);104 let amount = amount.try_into().map_err(|_| "amount overflow")?;105 let budget = self106 .recorder107 .weight_calls_budget(<StructureWeight<T>>::find_parent());108109 <Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)110 .map_err(dispatch_to_evm::<T>)?;111 Ok(true)112 }113 #[weight(<SelfWeightOf<T>>::approve())]114 fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {115 let caller = T::CrossAccountId::from_eth(caller);116 let spender = T::CrossAccountId::from_eth(spender);117 let amount = amount.try_into().map_err(|_| "amount overflow")?;118119 <Pallet<T>>::set_allowance(self, &caller, &spender, amount)120 .map_err(dispatch_to_evm::<T>)?;121 Ok(true)122 }123 fn allowance(&self, owner: address, spender: address) -> Result<uint256> {124 self.consume_store_reads(1)?;125 let owner = T::CrossAccountId::from_eth(owner);126 let spender = T::CrossAccountId::from_eth(spender);127128 Ok(<Allowance<T>>::get((self.id, owner, spender)).into())129 }130}131132#[solidity_interface(name = "ERC20UniqueExtensions")]133impl<T: Config> FungibleHandle<T> {134 #[weight(<SelfWeightOf<T>>::burn_from())]135 fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {136 let caller = T::CrossAccountId::from_eth(caller);137 let from = T::CrossAccountId::from_eth(from);138 let amount = amount.try_into().map_err(|_| "amount overflow")?;139 let budget = self140 .recorder141 .weight_calls_budget(<StructureWeight<T>>::find_parent());142143 <Pallet<T>>::burn_from(self, &caller, &from, amount, &budget)144 .map_err(dispatch_to_evm::<T>)?;145 Ok(true)146 }147}148149#[solidity_interface(150 name = "UniqueFungible",151 is(152 ERC20,153 ERC20UniqueExtensions,154 via("CollectionHandle<T>", common_mut, Collection)155 )156)]157impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> {}158159generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);160generate_stubgen!(gen_iface, UniqueFungibleCall<()>, false);161162impl<T: Config> CommonEvmHandler for FungibleHandle<T>163where164 T::AccountId: From<[u8; 32]>,165{166 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");167168 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {169 call::<T, UniqueFungibleCall<T>, _, _>(handle, self)170 }171}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,