From 0abd4991215878c7aea8f83307ea3fbefc79ea73 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Tue, 23 Jul 2024 19:21:18 +0200 Subject: [PATCH] refactor: read state --- pallets/api/src/fungibles/mod.rs | 36 +++++++++++++++++++---- pop-api/src/v0/assets/fungibles.rs | 18 ++++-------- runtime/devnet/src/extensions/mod.rs | 43 +++++----------------------- 3 files changed, 43 insertions(+), 54 deletions(-) diff --git a/pallets/api/src/fungibles/mod.rs b/pallets/api/src/fungibles/mod.rs index 3b096490..03f03abf 100644 --- a/pallets/api/src/fungibles/mod.rs +++ b/pallets/api/src/fungibles/mod.rs @@ -159,6 +159,30 @@ pub mod pallet { } impl Pallet { + /// 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`, 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) -> Vec { + 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 @@ -166,7 +190,7 @@ pub mod pallet { /// /// # Returns /// The total supply of the token, or an error if the operation fails. - pub fn total_supply(id: AssetIdOf) -> BalanceOf { + fn total_supply(id: AssetIdOf) -> BalanceOf { Assets::::total_supply(id) } @@ -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, owner: &AccountIdOf) -> BalanceOf { + fn balance_of(id: AssetIdOf, owner: &AccountIdOf) -> BalanceOf { Assets::::balance(id, owner) } @@ -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, owner: &AccountIdOf, spender: &AccountIdOf, @@ -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) -> Vec { + fn token_name(id: AssetIdOf) -> Vec { as MetadataInspect>>::name(id) } @@ -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) -> Vec { + fn token_symbol(id: AssetIdOf) -> Vec { as MetadataInspect>>::symbol(id) } @@ -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) -> u8 { + fn token_decimals(id: AssetIdOf) -> u8 { as MetadataInspect>>::decimals(id) } } diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index 0805393f..90229de2 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -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, @@ -62,10 +62,9 @@ mod constants { pub fn total_supply(id: AssetId) -> Result { ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, FUNGIBLES, TOTAL_SUPPLY])) .input::() - .output::>, true>() + .output::, true>() .handle_error_code::() .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 @@ -81,10 +80,9 @@ pub fn total_supply(id: AssetId) -> Result { pub fn balance_of(id: AssetId, owner: AccountId) -> Result { ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, FUNGIBLES, BALANCE_OF])) .input::<(AssetId, AccountId)>() - .output::>, true>() + .output::, true>() .handle_error_code::() .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 @@ -101,10 +99,9 @@ pub fn balance_of(id: AssetId, owner: AccountId) -> Result { pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, FUNGIBLES, ALLOWANCE])) .input::<(AssetId, AccountId, AccountId)>() - .output::>, true>() + .output::, true>() .handle_error_code::() .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 @@ -217,7 +214,6 @@ pub mod metadata { .output::>, true>() .handle_error_code::() .call(&(id)) - .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } /// Returns the token symbol for a given asset ID. @@ -234,7 +230,6 @@ pub mod metadata { .output::>, true>() .handle_error_code::() .call(&(id)) - .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } /// Returns the token decimals for a given asset ID. @@ -248,10 +243,9 @@ pub mod metadata { pub fn token_decimals(id: AssetId) -> Result { ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, FUNGIBLES, TOKEN_DECIMALS])) .input::() - .output::>, true>() + .output::, true>() .handle_error_code::() .call(&(id)) - .and_then(|v| ::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } } diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index 4496c458..fc12cb0d 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -2,10 +2,7 @@ mod v0; use crate::{ config::assets::TrustBackedAssetsInstance, - fungibles::{ - self, - FungiblesKey::{self, *}, - }, + fungibles::{self, FungiblesKey}, state_keys::RuntimeStateKeys, AccountId, AllowedApiCalls, RuntimeCall, RuntimeOrigin, }; @@ -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 = >::decode(&mut ¶ms[..]) .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::(key, env), + RuntimeStateKeys::Fungibles(key) => fungibles::Pallet::::read_state(key), }, - }? - .encode(); + }; log::trace!( target:LOG_TARGET, "{} result: {:?}.", LOG_PREFIX, result @@ -281,34 +280,6 @@ impl TryFrom for FuncId { } } -fn read_fungibles_state( - key: FungiblesKey, - env: &mut Environment, -) -> Result, DispatchError> -where - T: pallet_contracts::Config - + pallet_assets::Config - + fungibles::Config, - E: Ext, - T: frame_system::Config, -{ - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - match key { - TotalSupply(id) => Ok(fungibles::Pallet::::total_supply(id).encode()), - BalanceOf(id, owner) => Ok(fungibles::Pallet::::balance_of(id, &owner).encode()), - Allowance(id, owner, spender) => { - Ok(fungibles::Pallet::::allowance(id, &owner, &spender).encode()) - }, - TokenName(id) => Ok(fungibles::Pallet::::token_name(id).encode()), - TokenSymbol(id) => Ok(fungibles::Pallet::::token_symbol(id).encode()), - TokenDecimals(id) => Ok(fungibles::Pallet::::token_decimals(id).encode()), - // AssetsKeys::AssetExists(id) => { - // env.charge_weight(T::DbWeight::get().reads(1_u64))?; - // Ok(pallet_assets::Pallet::::asset_exists(id).encode()) - // }, - } -} - #[cfg(test)] mod tests { use super::*;