Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

precompile #2049

Merged
merged 11 commits into from
May 6, 2022
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

82 changes: 77 additions & 5 deletions runtime/acala/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ pub use sp_runtime::BuildStorage;
pub use authority::AuthorityConfigImpl;
pub use constants::{fee::*, time::*};
use module_support::mocks::MockStableAsset;
use module_support::ExchangeRateProvider;
pub use primitives::{
define_combined_task,
evm::{AccessListItem, EstimateResourcesRequest},
Expand Down Expand Up @@ -161,6 +162,7 @@ parameter_types! {
// This Pallet is only used to payment fee pool, it's not added to whitelist by design.
// because transaction payment pallet will ensure the accounts always have enough ED.
pub const TransactionPaymentPalletId: PalletId = PalletId(*b"aca/fees");
pub const StableAssetPalletId: PalletId = PalletId(*b"nuts/sta");
}

pub fn get_all_module_accounts() -> Vec<AccountId> {
Expand All @@ -176,6 +178,7 @@ pub fn get_all_module_accounts() -> Vec<AccountId> {
TreasuryPalletId::get().into_account(),
TreasuryReservePalletId::get().into_account(),
UnreleasedNativeVaultAccountId::get(),
StableAssetPalletId::get().into_account(),
]
}

Expand Down Expand Up @@ -796,8 +799,12 @@ parameter_type_with_key! {
}

parameter_type_with_key! {
pub PricingPegged: |_currency_id: CurrencyId| -> Option<CurrencyId> {
None
pub PricingPegged: |currency_id: CurrencyId| -> Option<CurrencyId> {
match currency_id {
// taiKSM
CurrencyId::StableAssetPoolToken(0) => Some(DOT),
_ => None,
}
};
}

Expand Down Expand Up @@ -1015,7 +1022,7 @@ where
}

parameter_types! {
pub CollateralCurrencyIds: Vec<CurrencyId> = vec![ACA, DOT, LCDOT, LDOT];
pub CollateralCurrencyIds: Vec<CurrencyId> = vec![ACA, DOT, LCDOT, LDOT, CurrencyId::StableAssetPoolToken(0)];
pub DefaultLiquidationRatio: Ratio = Ratio::saturating_from_rational(150, 100);
pub DefaultDebitExchangeRate: ExchangeRate = ExchangeRate::saturating_from_rational(1, 10);
pub DefaultLiquidationPenalty: Rate = Rate::saturating_from_rational(8, 100);
Expand Down Expand Up @@ -1499,6 +1506,68 @@ impl module_idle_scheduler::Config for Runtime {
type DisableBlockThreshold = ConstU32<6>;
}

pub struct EnsurePoolAssetId;
impl nutsfinance_stable_asset::traits::ValidateAssetId<CurrencyId> for EnsurePoolAssetId {
fn validate(currency_id: CurrencyId) -> bool {
matches!(currency_id, CurrencyId::StableAssetPoolToken(_))
}
}

pub struct ConvertBalanceHoma;
impl orml_tokens::ConvertBalance<Balance, Balance> for ConvertBalanceHoma {
type AssetId = CurrencyId;

fn convert_balance(balance: Balance, asset_id: CurrencyId) -> Balance {
match asset_id {
CurrencyId::Token(TokenSymbol::LDOT) => {
Homa::get_exchange_rate().checked_mul_int(balance).unwrap_or_default()
}
_ => balance,
}
}

fn convert_balance_back(balance: Balance, asset_id: CurrencyId) -> Balance {
match asset_id {
CurrencyId::Token(TokenSymbol::LDOT) => Homa::get_exchange_rate()
.reciprocal()
.and_then(|x| x.checked_mul_int(balance))
.unwrap_or_default(),
_ => balance,
}
}
}

pub struct IsLiquidToken;
impl Contains<CurrencyId> for IsLiquidToken {
fn contains(currency_id: &CurrencyId) -> bool {
matches!(currency_id, CurrencyId::Token(TokenSymbol::LDOT))
}
}

type RebaseTokens = orml_tokens::Combiner<
AccountId,
IsLiquidToken,
orml_tokens::Mapper<AccountId, Tokens, ConvertBalanceHoma, Balance, GetLiquidCurrencyId>,
Tokens,
>;

impl nutsfinance_stable_asset::Config for Runtime {
type Event = Event;
type AssetId = CurrencyId;
type Balance = Balance;
type Assets = RebaseTokens;
type PalletId = StableAssetPalletId;

type AtLeast64BitUnsigned = u128;
type FeePrecision = ConstU128<10_000_000_000>; // 10 decimals
type APrecision = ConstU128<100>; // 2 decimals
type PoolAssetLimit = ConstU32<5>;
type SwapExactOverAmount = ConstU128<100>;
type WeightInfo = weights::nutsfinance_stable_asset::WeightInfo<Runtime>;
type ListingOrigin = EnsureRootOrHalfGeneralCouncil;
type EnsurePoolAssetId = EnsurePoolAssetId;
}

construct_runtime!(
pub enum Runtime where
Block = Block,
Expand Down Expand Up @@ -1599,6 +1668,9 @@ construct_runtime!(
EVMBridge: module_evm_bridge exclude_parts { Call } = 131,
EvmAccounts: module_evm_accounts = 132,

// Stable asset
StableAsset: nutsfinance_stable_asset = 200,

// Parachain System, always put it at the end
ParachainSystem: cumulus_pallet_parachain_system = 30,

Expand Down Expand Up @@ -2084,8 +2156,8 @@ mod tests {
fn check_call_size() {
println!("{:?}", core::mem::size_of::<Call>());
assert!(
core::mem::size_of::<Call>() <= 240,
"size of Call is more than 240 bytes: some calls have too big arguments, use Box to \
core::mem::size_of::<Call>() <= 280,
"size of Call is more than 280 bytes: some calls have too big arguments, use Box to \
reduce the size of Call.
If the limit is too strong, maybe consider increasing the limit",
);
Expand Down
2 changes: 2 additions & 0 deletions runtime/acala/src/weights/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,5 @@ pub mod orml_authority;
pub mod orml_oracle;
pub mod orml_tokens;
pub mod orml_vesting;

pub mod nutsfinance_stable_asset;
131 changes: 131 additions & 0 deletions runtime/acala/src/weights/nutsfinance_stable_asset.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// This file is part of Acala.

// Copyright (C) 2020-2022 Acala Foundation.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Autogenerated weights for nutsfinance_stable_asset
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2022-03-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("karura-dev"), DB CACHE: 1024

// Executed Command:
// target/production/acala
// benchmark
// --chain=karura-dev
// --steps=50
// --repeat=20
// --pallet=*
// --extrinsic=*
// --execution=wasm
// --wasm-execution=compiled
// --heap-pages=4096
// --template=./templates/runtime-weight-template.hbs
// --output=./runtime/karura/src/weights/

#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]

use frame_support::{traits::Get, weights::Weight};
use sp_std::marker::PhantomData;

/// Weight functions for nutsfinance_stable_asset.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> nutsfinance_stable_asset::WeightInfo for WeightInfo<T> {
// Storage: StableAsset PoolCount (r:1 w:1)
// Storage: StableAsset Pools (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn create_pool() -> Weight {
(23_041_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
// Storage: StableAsset Pools (r:1 w:1)
fn modify_a() -> Weight {
(16_092_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: StableAsset Pools (r:1 w:1)
// Storage: Tokens Accounts (r:6 w:6)
// Storage: System Account (r:2 w:2)
// Storage: Tokens TotalIssuance (r:1 w:1)
// Storage: AssetRegistry AssetMetadatas (r:1 w:0)
fn mint(u: u32, ) -> Weight {
(73_727_000 as Weight)
// Standard Error: 117_000
.saturating_add((17_942_000 as Weight).saturating_mul(u as Weight))
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(u as Weight)))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(u as Weight)))
}
// Storage: StableAsset Pools (r:1 w:1)
// Storage: Tokens Accounts (r:5 w:5)
// Storage: System Account (r:1 w:0)
// Storage: Tokens TotalIssuance (r:1 w:1)
// Storage: AssetRegistry AssetMetadatas (r:1 w:0)
fn swap(u: u32, ) -> Weight {
(71_743_000 as Weight)
// Standard Error: 140_000
.saturating_add((5_807_000 as Weight).saturating_mul(u as Weight))
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(u as Weight)))
.saturating_add(T::DbWeight::get().writes(7 as Weight))
}
// Storage: StableAsset Pools (r:1 w:1)
// Storage: Tokens Accounts (r:6 w:6)
// Storage: System Account (r:1 w:0)
// Storage: AssetRegistry AssetMetadatas (r:1 w:0)
// Storage: Tokens TotalIssuance (r:1 w:1)
fn redeem_proportion(u: u32, ) -> Weight {
(81_025_000 as Weight)
// Standard Error: 699_000
.saturating_add((13_663_000 as Weight).saturating_mul(u as Weight))
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(u as Weight)))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(u as Weight)))
}
// Storage: StableAsset Pools (r:1 w:1)
// Storage: Tokens Accounts (r:5 w:4)
// Storage: AssetRegistry AssetMetadatas (r:1 w:0)
// Storage: System Account (r:1 w:0)
// Storage: Tokens TotalIssuance (r:1 w:1)
fn redeem_single(u: u32, ) -> Weight {
(89_436_000 as Weight)
// Standard Error: 819_000
.saturating_add((2_425_000 as Weight).saturating_mul(u as Weight))
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(u as Weight)))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
// Storage: StableAsset Pools (r:1 w:1)
// Storage: Tokens Accounts (r:6 w:6)
// Storage: AssetRegistry AssetMetadatas (r:1 w:0)
// Storage: System Account (r:1 w:0)
// Storage: Tokens TotalIssuance (r:1 w:1)
fn redeem_multi(u: u32, ) -> Weight {
(63_297_000 as Weight)
// Standard Error: 154_000
.saturating_add((14_971_000 as Weight).saturating_mul(u as Weight))
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(u as Weight)))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(u as Weight)))
}
}
1 change: 1 addition & 0 deletions runtime/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ module-evm-accounts = { path = "../../modules/evm-accounts", default-features =
module-asset-registry = { path = "../../modules/asset-registry", default-features = false, optional = true }
module-evm-bridge = { path = "../../modules/evm-bridge", default-features = false, optional = true }
primitives = { package = "acala-primitives", path = "../../primitives", default-features = false }
nutsfinance-stable-asset = { version = "0.1.0", default-features = false, path = "../../ecosystem-modules/stable-asset/lib/stable-asset", package = "nutsfinance-stable-asset" }

# orml
orml-oracle = { path = "../../orml/oracle", default-features = false }
Expand Down
2 changes: 1 addition & 1 deletion runtime/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ use module_evm::GenesisAccount;
use orml_traits::GetByKey;
pub use precompile::{
AllPrecompiles, DEXPrecompile, EVMPrecompile, MultiCurrencyPrecompile, NFTPrecompile, OraclePrecompile,
SchedulePrecompile,
SchedulePrecompile, StableAssetPrecompile,
};
pub use primitives::{
currency::{TokenInfo, ACA, AUSD, BNC, DOT, KAR, KBTC, KINT, KSM, KUSD, LCDOT, LDOT, LKSM, PHA, RENBTC, VSKSM},
Expand Down
15 changes: 15 additions & 0 deletions runtime/common/src/precompile/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,21 @@ impl Output {
ethabi::encode(&[out])
}

pub fn encode_u128_array(&self, b: Vec<u128>) -> Vec<u8> {
let result: Vec<Token> = b.iter().map(|x| Token::Uint(U256::from(*x))).collect();
let out = Token::FixedArray(result);
ethabi::encode(&[out])
}

pub fn encode_address_array(&self, b: Vec<H160>) -> Vec<u8> {
let result: Vec<Token> = b
.iter()
.map(|x| Token::Address(H160::from_slice(x.as_bytes())))
.collect();
let out = Token::FixedArray(result);
ethabi::encode(&[out])
}

pub fn encode_bytes(&self, b: &[u8]) -> Vec<u8> {
let out = Token::Bytes(b.to_vec());
ethabi::encode(&[out])
Expand Down
38 changes: 37 additions & 1 deletion runtime/common/src/precompile/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,34 @@ impl module_dex::Config for Test {
type OnLiquidityPoolUpdated = ();
}

parameter_types! {
pub const StableAssetPalletId: PalletId = PalletId(*b"nuts/sta");
}

pub struct EnsurePoolAssetId;
impl nutsfinance_stable_asset::traits::ValidateAssetId<CurrencyId> for EnsurePoolAssetId {
fn validate(_currency_id: CurrencyId) -> bool {
true
}
}

impl nutsfinance_stable_asset::Config for Test {
type Event = Event;
type AssetId = CurrencyId;
type Balance = Balance;
type Assets = Tokens;
type PalletId = StableAssetPalletId;

type AtLeast64BitUnsigned = u128;
type FeePrecision = ConstU128<10_000_000_000>; // 10 decimals
type APrecision = ConstU128<100>; // 2 decimals
type PoolAssetLimit = ConstU32<5>;
type SwapExactOverAmount = ConstU128<100>;
type WeightInfo = ();
type ListingOrigin = EnsureSignedBy<ListingOrigin, AccountId>;
type EnsurePoolAssetId = EnsurePoolAssetId;
}

pub type AdaptedBasicCurrency = module_currencies::BasicCurrencyAdapter<Test, Balances, Amount, BlockNumber>;

pub type EvmErc20InfoMapping = module_asset_registry::EvmErc20InfoMapping<Test>;
Expand Down Expand Up @@ -557,6 +585,7 @@ frame_support::construct_runtime!(
EVMModule: module_evm,
EvmAccounts: module_evm_accounts,
IdleScheduler: module_idle_scheduler,
StableAsset: nutsfinance_stable_asset,
}
);

Expand Down Expand Up @@ -614,7 +643,14 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
Origin::root(),
EvmAddressMapping::<Test>::get_account_id(&alice_evm_addr()),
RENBTC,
1_000
1_000_000_000
));

assert_ok!(Currencies::update_balance(
Origin::root(),
EvmAddressMapping::<Test>::get_account_id(&alice_evm_addr()),
AUSD,
1_000_000_000
));
});
ext
Expand Down
Loading