Skip to content

Commit 9820e7f

Browse files
DaanvdplasFrank Bell
andauthored
refactor: remove read state encoding (#122)
Co-authored-by: Frank Bell <[email protected]>
1 parent 30ff91a commit 9820e7f

File tree

8 files changed

+106
-141
lines changed

8 files changed

+106
-141
lines changed

pallets/api/src/fungibles/mod.rs

Lines changed: 25 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -180,61 +180,33 @@ pub mod pallet {
180180
}
181181

182182
impl<T: Config> Pallet<T> {
183-
/// Returns the total token supply for a given asset ID.
183+
/// Reads fungible asset state based on the provided value.
184184
///
185-
/// # Parameters
186-
/// * `id` - The ID of the asset.
187-
pub fn total_supply(id: AssetIdOf<T>) -> BalanceOf<T> {
188-
AssetsOf::<T>::total_supply(id)
189-
}
190-
191-
/// Returns the account balance for the specified `owner` for a given asset ID. Returns `0` if
192-
/// the account is non-existent.
185+
/// This function matches the value to determine the type of state query and returns the
186+
/// encoded result.
193187
///
194-
/// # Parameters
195-
/// * `id` - The ID of the asset.
196-
/// * `owner` - The account whose balance is being queried.
197-
pub fn balance_of(id: AssetIdOf<T>, owner: &AccountIdOf<T>) -> BalanceOf<T> {
198-
AssetsOf::<T>::balance(id, owner)
199-
}
200-
201-
/// Returns the amount which `spender` is still allowed to withdraw from `owner` for a given
202-
/// asset ID. Returns `0` if no allowance has been set.
203-
///
204-
/// # Parameters
205-
/// * `id` - The ID of the asset.
206-
/// * `owner` - The account that owns the tokens.
207-
/// * `spender` - The account that is allowed to spend the tokens.
208-
pub fn allowance(
209-
id: AssetIdOf<T>,
210-
owner: &AccountIdOf<T>,
211-
spender: &AccountIdOf<T>,
212-
) -> BalanceOf<T> {
213-
AssetsOf::<T>::allowance(id, owner, spender)
214-
}
215-
216-
/// Returns the token name for a given asset ID.
217-
///
218-
/// # Parameters
219-
/// * `id` - The ID of the asset.
220-
pub fn token_name(id: AssetIdOf<T>) -> Vec<u8> {
221-
<AssetsOf<T> as MetadataInspect<AccountIdOf<T>>>::name(id)
222-
}
223-
224-
/// Returns the token symbol for a given asset ID.
225-
///
226-
/// # Parameters
227-
/// * `id` - The ID of the asset.
228-
pub fn token_symbol(id: AssetIdOf<T>) -> Vec<u8> {
229-
<AssetsOf<T> as MetadataInspect<AccountIdOf<T>>>::symbol(id)
230-
}
231-
232-
/// Returns the token decimals for a given asset ID.
233-
///
234-
/// # Parameters
235-
/// * `id` - The ID of the asset.
236-
pub fn token_decimals(id: AssetIdOf<T>) -> u8 {
237-
<AssetsOf<T> as MetadataInspect<AccountIdOf<T>>>::decimals(id)
188+
/// # Parameter
189+
/// * `value` - An instance of `Read<T>`, which specifies the type of state query and
190+
/// the associated parameters.
191+
pub fn read_state(value: Read<T>) -> Vec<u8> {
192+
use Read::*;
193+
194+
match value {
195+
TotalSupply(id) => AssetsOf::<T>::total_supply(id).encode(),
196+
BalanceOf { id, owner } => AssetsOf::<T>::balance(id, owner).encode(),
197+
Allowance { id, owner, spender } => {
198+
AssetsOf::<T>::allowance(id, &owner, &spender).encode()
199+
},
200+
TokenName(id) => {
201+
<AssetsOf<T> as MetadataInspect<AccountIdOf<T>>>::name(id).encode()
202+
},
203+
TokenSymbol(id) => {
204+
<AssetsOf<T> as MetadataInspect<AccountIdOf<T>>>::symbol(id).encode()
205+
},
206+
TokenDecimals(id) => {
207+
<AssetsOf<T> as MetadataInspect<AccountIdOf<T>>>::decimals(id).encode()
208+
},
209+
}
238210
}
239211
}
240212
}

pallets/api/src/fungibles/tests.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
use crate::mock::*;
1+
use crate::{fungibles::Read::*, mock::*};
2+
use codec::Encode;
23
use frame_support::{
34
assert_ok,
45
traits::fungibles::{approvals::Inspect, metadata::Inspect as MetadataInspect},
@@ -60,15 +61,18 @@ fn increase_allowance_works() {
6061
fn total_supply_works() {
6162
new_test_ext().execute_with(|| {
6263
create_asset_and_mint_to(ALICE, ASSET, ALICE, 100);
63-
assert_eq!(Assets::total_supply(ASSET), Fungibles::total_supply(ASSET));
64+
assert_eq!(Assets::total_supply(ASSET).encode(), Fungibles::read_state(TotalSupply(ASSET)));
6465
});
6566
}
6667

6768
#[test]
6869
fn balance_of_works() {
6970
new_test_ext().execute_with(|| {
7071
create_asset_and_mint_to(ALICE, ASSET, ALICE, 100);
71-
assert_eq!(Assets::balance(ASSET, ALICE), Fungibles::balance_of(ASSET, &ALICE));
72+
assert_eq!(
73+
Assets::balance(ASSET, ALICE).encode(),
74+
Fungibles::read_state(BalanceOf { id: ASSET, owner: ALICE })
75+
);
7276
});
7377
}
7478

@@ -77,8 +81,8 @@ fn allowance_works() {
7781
new_test_ext().execute_with(|| {
7882
create_asset_mint_and_approve(ALICE, ASSET, BOB, 100, ALICE, 50);
7983
assert_eq!(
80-
Assets::allowance(ASSET, &ALICE, &BOB),
81-
Fungibles::allowance(ASSET, &ALICE, &BOB)
84+
Assets::allowance(ASSET, &ALICE, &BOB).encode(),
85+
Fungibles::read_state(Allowance { id: ASSET, owner: ALICE, spender: BOB })
8286
);
8387
});
8488
}
@@ -90,9 +94,9 @@ fn token_metadata_works() {
9094
let symbol: Vec<u8> = vec![21, 22, 23];
9195
let decimals: u8 = 69;
9296
create_asset_and_set_metadata(ALICE, ASSET, name.clone(), symbol.clone(), decimals);
93-
assert_eq!(Assets::name(ASSET), Fungibles::token_name(ASSET));
94-
assert_eq!(Assets::symbol(ASSET), Fungibles::token_symbol(ASSET));
95-
assert_eq!(Assets::decimals(ASSET), Fungibles::token_decimals(ASSET));
97+
assert_eq!(Assets::name(ASSET).encode(), Fungibles::read_state(TokenName(ASSET)));
98+
assert_eq!(Assets::symbol(ASSET).encode(), Fungibles::read_state(TokenSymbol(ASSET)));
99+
assert_eq!(Assets::decimals(ASSET).encode(), Fungibles::read_state(TokenDecimals(ASSET)));
96100
});
97101
}
98102

pop-api/src/lib.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
#![cfg_attr(not(feature = "std"), no_std, no_main)]
22

3-
use ink::env::chain_extension::ChainExtensionMethod;
4-
53
use constants::DECODING_FAILED;
6-
use ink::env::chain_extension::FromStatusCode;
4+
use ink::env::chain_extension::{ChainExtensionMethod, FromStatusCode};
75
#[cfg(feature = "assets")]
86
pub use v0::assets;
97

pop-api/src/v0/assets/fungibles.rs

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
use ink::{env::chain_extension::ChainExtensionMethod, prelude::vec::Vec, scale::Decode};
2-
31
use crate::{
4-
constants::{ASSETS, BALANCES, DECODING_FAILED, FUNGIBLES},
2+
constants::{ASSETS, BALANCES, FUNGIBLES},
53
primitives::{AccountId, AssetId, Balance},
6-
v0::V0,
74
Result, StatusCode,
85
};
96
use constants::*;
7+
use ink::{env::chain_extension::ChainExtensionMethod, prelude::vec::Vec};
108
pub use metadata::*;
119

1210
/// Helper method to build a dispatch call `ChainExtensionMethod` for fungibles `v0`
@@ -78,10 +76,9 @@ mod constants {
7876
pub fn total_supply(id: AssetId) -> Result<Balance> {
7977
build_read_state(TOTAL_SUPPLY)
8078
.input::<AssetId>()
81-
.output::<Result<Vec<u8>>, true>()
79+
.output::<Result<Balance>, true>()
8280
.handle_error_code::<StatusCode>()
8381
.call(&(id))
84-
.and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
8582
}
8683

8784
/// Returns the account balance for the specified `owner` for a given asset ID. Returns `0` if
@@ -97,10 +94,9 @@ pub fn total_supply(id: AssetId) -> Result<Balance> {
9794
pub fn balance_of(id: AssetId, owner: AccountId) -> Result<Balance> {
9895
build_read_state(BALANCE_OF)
9996
.input::<(AssetId, AccountId)>()
100-
.output::<Result<Vec<u8>>, true>()
97+
.output::<Result<Balance>, true>()
10198
.handle_error_code::<StatusCode>()
10299
.call(&(id, owner))
103-
.and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
104100
}
105101

106102
/// Returns the amount which `spender` is still allowed to withdraw from `owner` for a given
@@ -117,10 +113,9 @@ pub fn balance_of(id: AssetId, owner: AccountId) -> Result<Balance> {
117113
pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result<Balance> {
118114
build_read_state(ALLOWANCE)
119115
.input::<(AssetId, AccountId, AccountId)>()
120-
.output::<Result<Vec<u8>>, true>()
116+
.output::<Result<Balance>, true>()
121117
.handle_error_code::<StatusCode>()
122118
.call(&(id, owner, spender))
123-
.and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
124119
}
125120

126121
/// Transfers `value` amount of tokens from the caller's account to account `to`, with additional
@@ -233,7 +228,6 @@ pub mod metadata {
233228
.output::<Result<Vec<u8>>, true>()
234229
.handle_error_code::<StatusCode>()
235230
.call(&(id))
236-
.and_then(|v| <Vec<u8>>::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
237231
}
238232

239233
/// Returns the token symbol for a given asset ID.
@@ -250,7 +244,6 @@ pub mod metadata {
250244
.output::<Result<Vec<u8>>, true>()
251245
.handle_error_code::<StatusCode>()
252246
.call(&(id))
253-
.and_then(|v| <Vec<u8>>::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
254247
}
255248

256249
/// Returns the token decimals for a given asset ID.
@@ -264,10 +257,9 @@ pub mod metadata {
264257
pub fn token_decimals(id: AssetId) -> Result<u8> {
265258
build_read_state(TOKEN_DECIMALS)
266259
.input::<AssetId>()
267-
.output::<Result<Vec<u8>>, true>()
260+
.output::<Result<u8>, true>()
268261
.handle_error_code::<StatusCode>()
269262
.call(&(id))
270-
.and_then(|v| <u8>::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED)))
271263
}
272264
}
273265

pop-api/src/v0/assets/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
#[cfg(feature = "fungibles")]
22
pub mod fungibles;
3-

runtime/devnet/src/config/api.rs

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,37 @@ pub enum RuntimeRead<T: fungibles::Config> {
1111
Fungibles(fungibles::Read<T>),
1212
}
1313

14-
impl fungibles::Config for Runtime {
15-
type AssetsInstance = TrustBackedAssetsInstance;
16-
type WeightInfo = fungibles::weights::SubstrateWeight<Runtime>;
17-
}
18-
19-
/// A type to identify allowed calls to the Runtime from contracts. Used by Pop API
14+
/// A type to identify allowed calls to the Runtime from the API.
2015
pub struct AllowedApiCalls;
2116

2217
impl Contains<RuntimeCall> for AllowedApiCalls {
18+
/// Allowed runtime calls from the API.
2319
fn contains(c: &RuntimeCall) -> bool {
24-
use fungibles::Call as FungiblesCall;
20+
use fungibles::Call::*;
21+
matches!(
22+
c,
23+
RuntimeCall::Fungibles(transfer { .. } | approve { .. } | increase_allowance { .. })
24+
)
25+
}
26+
}
27+
28+
impl<T: fungibles::Config> Contains<RuntimeRead<T>> for AllowedApiCalls {
29+
/// Allowed state queries from the API.
30+
fn contains(c: &RuntimeRead<T>) -> bool {
31+
use fungibles::Read::*;
2532
matches!(
2633
c,
27-
RuntimeCall::Fungibles(
28-
FungiblesCall::transfer { .. }
29-
| FungiblesCall::approve { .. }
30-
| FungiblesCall::increase_allowance { .. }
34+
RuntimeRead::Fungibles(
35+
TotalSupply(..)
36+
| BalanceOf { .. } | Allowance { .. }
37+
| TokenName(..) | TokenSymbol(..)
38+
| TokenDecimals(..)
3139
)
3240
)
3341
}
3442
}
43+
44+
impl fungibles::Config for Runtime {
45+
type AssetsInstance = TrustBackedAssetsInstance;
46+
type WeightInfo = fungibles::weights::SubstrateWeight<Runtime>;
47+
}

0 commit comments

Comments
 (0)