Skip to content

Commit

Permalink
refactor: read state
Browse files Browse the repository at this point in the history
  • Loading branch information
Daanvdplas committed Jul 23, 2024
1 parent d20726b commit 0abd499
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 54 deletions.
36 changes: 30 additions & 6 deletions pallets/api/src/fungibles/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,38 @@ pub mod pallet {
}

impl<T: Config> Pallet<T> {
/// Reads the state of the fungible asset based on the provided key.
///
/// This function matches the key to determine the type of state query and returns the
/// encoded result.
///
/// # Arguments
/// * `key` - An instance of `FungiblesKey<T>`, which specifies the type of state query and
/// the associated parameters.
///
/// # Returns
/// A vector of bytes representing the encoded result of the state query.
pub fn read_state(key: FungiblesKey<T>) -> Vec<u8> {
use FungiblesKey::*;

match key {
TotalSupply(id) => Self::total_supply(id).encode(),
BalanceOf(id, owner) => Self::balance_of(id, &owner).encode(),
Allowance(id, owner, spender) => Self::allowance(id, &owner, &spender).encode(),
TokenName(id) => Self::token_name(id).encode(),
TokenSymbol(id) => Self::token_symbol(id).encode(),
TokenDecimals(id) => Self::token_decimals(id).encode(),
}
}

/// Returns the total token supply for a given asset ID.
///
/// # Arguments
/// * `id` - The ID of the asset.
///
/// # Returns
/// The total supply of the token, or an error if the operation fails.
pub fn total_supply(id: AssetIdOf<T>) -> BalanceOf<T> {
fn total_supply(id: AssetIdOf<T>) -> BalanceOf<T> {
Assets::<T>::total_supply(id)
}

Expand All @@ -179,7 +203,7 @@ pub mod pallet {
///
/// # Returns
/// The balance of the specified account, or an error if the operation fails.
pub fn balance_of(id: AssetIdOf<T>, owner: &AccountIdOf<T>) -> BalanceOf<T> {
fn balance_of(id: AssetIdOf<T>, owner: &AccountIdOf<T>) -> BalanceOf<T> {
Assets::<T>::balance(id, owner)
}

Expand All @@ -193,7 +217,7 @@ pub mod pallet {
///
/// # Returns
/// The remaining allowance, or an error if the operation fails.
pub fn allowance(
fn allowance(
id: AssetIdOf<T>,
owner: &AccountIdOf<T>,
spender: &AccountIdOf<T>,
Expand All @@ -208,7 +232,7 @@ pub mod pallet {
///
/// # Returns
/// The name of the token as a byte vector, or an error if the operation fails.
pub fn token_name(id: AssetIdOf<T>) -> Vec<u8> {
fn token_name(id: AssetIdOf<T>) -> Vec<u8> {
<Assets<T> as MetadataInspect<AccountIdOf<T>>>::name(id)
}

Expand All @@ -219,7 +243,7 @@ pub mod pallet {
///
/// # Returns
/// The symbol of the token as a byte vector, or an error if the operation fails.
pub fn token_symbol(id: AssetIdOf<T>) -> Vec<u8> {
fn token_symbol(id: AssetIdOf<T>) -> Vec<u8> {
<Assets<T> as MetadataInspect<AccountIdOf<T>>>::symbol(id)
}

Expand All @@ -230,7 +254,7 @@ pub mod pallet {
///
/// # Returns
/// The number of decimals of the token as a byte vector, or an error if the operation fails.
pub fn token_decimals(id: AssetIdOf<T>) -> u8 {
fn token_decimals(id: AssetIdOf<T>) -> u8 {
<Assets<T> as MetadataInspect<AccountIdOf<T>>>::decimals(id)
}
}
Expand Down
18 changes: 6 additions & 12 deletions pop-api/src/v0/assets/fungibles.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use ink::{env::chain_extension::ChainExtensionMethod, prelude::vec::Vec, scale::Decode};
use ink::{env::chain_extension::ChainExtensionMethod, prelude::vec::Vec};

use crate::{
constants::{ASSETS, BALANCES, DECODING_FAILED, DISPATCH, FUNGIBLES, READ_STATE},
constants::{ASSETS, BALANCES, DISPATCH, FUNGIBLES, READ_STATE},
primitives::{AccountId, AssetId, Balance},
v0::V0,
Result, StatusCode,
Expand Down Expand Up @@ -62,10 +62,9 @@ mod constants {
pub fn total_supply(id: AssetId) -> Result<Balance> {
ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, FUNGIBLES, TOTAL_SUPPLY]))
.input::<AssetId>()
.output::<Result<Vec<u8>>, true>()
.output::<Result<Balance>, true>()
.handle_error_code::<StatusCode>()
.call(&(id))
.and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
}

/// Returns the account balance for the specified `owner` for a given asset ID. Returns `0` if
Expand All @@ -81,10 +80,9 @@ pub fn total_supply(id: AssetId) -> Result<Balance> {
pub fn balance_of(id: AssetId, owner: AccountId) -> Result<Balance> {
ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, FUNGIBLES, BALANCE_OF]))
.input::<(AssetId, AccountId)>()
.output::<Result<Vec<u8>>, true>()
.output::<Result<Balance>, true>()
.handle_error_code::<StatusCode>()
.call(&(id, owner))
.and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
}

/// Returns the amount which `spender` is still allowed to withdraw from `owner` for a given
Expand All @@ -101,10 +99,9 @@ pub fn balance_of(id: AssetId, owner: AccountId) -> Result<Balance> {
pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result<Balance> {
ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, FUNGIBLES, ALLOWANCE]))
.input::<(AssetId, AccountId, AccountId)>()
.output::<Result<Vec<u8>>, true>()
.output::<Result<Balance>, true>()
.handle_error_code::<StatusCode>()
.call(&(id, owner, spender))
.and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
}

/// Transfers `value` amount of tokens from the caller's account to account `to`, with additional
Expand Down Expand Up @@ -217,7 +214,6 @@ pub mod metadata {
.output::<Result<Vec<u8>>, true>()
.handle_error_code::<StatusCode>()
.call(&(id))
.and_then(|v| <Vec<u8>>::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
}

/// Returns the token symbol for a given asset ID.
Expand All @@ -234,7 +230,6 @@ pub mod metadata {
.output::<Result<Vec<u8>>, true>()
.handle_error_code::<StatusCode>()
.call(&(id))
.and_then(|v| <Vec<u8>>::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
}

/// Returns the token decimals for a given asset ID.
Expand All @@ -248,10 +243,9 @@ pub mod metadata {
pub fn token_decimals(id: AssetId) -> Result<u8> {
ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, FUNGIBLES, TOKEN_DECIMALS]))
.input::<AssetId>()
.output::<Result<Vec<u8>>, true>()
.output::<Result<u8>, true>()
.handle_error_code::<StatusCode>()
.call(&(id))
.and_then(|v| <u8>::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
}
}

Expand Down
43 changes: 7 additions & 36 deletions runtime/devnet/src/extensions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ mod v0;

use crate::{
config::assets::TrustBackedAssetsInstance,
fungibles::{
self,
FungiblesKey::{self, *},
},
fungibles::{self, FungiblesKey},

Check warning on line 5 in runtime/devnet/src/extensions/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

unused import: `FungiblesKey`

warning: unused import: `FungiblesKey` --> runtime/devnet/src/extensions/mod.rs:5:20 | 5 | fungibles::{self, FungiblesKey}, | ^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default
state_keys::RuntimeStateKeys,
AccountId, AllowedApiCalls, RuntimeCall, RuntimeOrigin,
};
Expand Down Expand Up @@ -167,19 +164,21 @@ where
{
const LOG_PREFIX: &str = " read_state |";

// Prefix params with version, pallet, index to simplify decoding.
// Prefix params with version, pallet, index to simplify decoding, and decode parameters for
// reading state.
params.insert(0, version);
params.insert(1, pallet_index);
params.insert(2, call_index);
let key = <VersionedStateRead<T>>::decode(&mut &params[..])
.map_err(|_| DispatchError::Other("DecodingFailed"))?;

// Charge weight for doing one storage read.
env.charge_weight(T::DbWeight::get().reads(1_u64))?;
let result = match key {
VersionedStateRead::V0(key) => match key {
RuntimeStateKeys::Fungibles(key) => read_fungibles_state::<T, E>(key, env),
RuntimeStateKeys::Fungibles(key) => fungibles::Pallet::<T>::read_state(key),
},
}?
.encode();
};
log::trace!(
target:LOG_TARGET,
"{} result: {:?}.", LOG_PREFIX, result
Expand Down Expand Up @@ -281,34 +280,6 @@ impl TryFrom<u8> for FuncId {
}
}

fn read_fungibles_state<T, E>(
key: FungiblesKey<T>,
env: &mut Environment<E, BufInBufOutState>,
) -> Result<Vec<u8>, DispatchError>
where
T: pallet_contracts::Config
+ pallet_assets::Config<TrustBackedAssetsInstance, AssetId = AssetId>
+ fungibles::Config,
E: Ext<T = T>,
T: frame_system::Config<AccountId = sp_runtime::AccountId32>,
{
env.charge_weight(T::DbWeight::get().reads(1_u64))?;
match key {
TotalSupply(id) => Ok(fungibles::Pallet::<T>::total_supply(id).encode()),
BalanceOf(id, owner) => Ok(fungibles::Pallet::<T>::balance_of(id, &owner).encode()),
Allowance(id, owner, spender) => {
Ok(fungibles::Pallet::<T>::allowance(id, &owner, &spender).encode())
},
TokenName(id) => Ok(fungibles::Pallet::<T>::token_name(id).encode()),
TokenSymbol(id) => Ok(fungibles::Pallet::<T>::token_symbol(id).encode()),
TokenDecimals(id) => Ok(fungibles::Pallet::<T>::token_decimals(id).encode()),
// AssetsKeys::AssetExists(id) => {
// env.charge_weight(T::DbWeight::get().reads(1_u64))?;
// Ok(pallet_assets::Pallet::<T, TrustBackedAssetsInstance>::asset_exists(id).encode())
// },
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit 0abd499

Please sign in to comment.