Skip to content

Commit

Permalink
Shibuya compiles
Browse files Browse the repository at this point in the history
  • Loading branch information
Dinonard committed Aug 2, 2024
1 parent df1ccc1 commit 6f994c2
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 77 deletions.
8 changes: 7 additions & 1 deletion pallets/inflation/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use super::*;

use frame_benchmarking::v2::*;
use frame_support::traits::tokens::Precision;
use frame_system::{Pallet as System, RawOrigin};
use sp_std::prelude::*;

Expand Down Expand Up @@ -65,7 +66,12 @@ fn initial_config<T: Config>() {

// Create some issuance so it's not zero
let dummy_account = whitelisted_caller();
T::Currency::make_free_balance_be(&dummy_account, 1_000_000_000_000_000_000_000);
let _debt = T::Currency::deposit(
&dummy_account,
1_000_000_000_000_000_000_000,
Precision::Exact,
)
.expect("Must succeed for benchmarking");
}

#[benchmarks]
Expand Down
25 changes: 15 additions & 10 deletions pallets/inflation/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,14 @@ use astar_primitives::{
},
Balance,
};
use frame_support::{pallet_prelude::*, traits::Currency, DefaultNoBound};
use frame_support::{
pallet_prelude::*,
traits::{
fungible::{Balanced, Credit, Inspect},
tokens::Precision,
},
DefaultNoBound,
};
use frame_system::{ensure_root, pallet_prelude::*};
use serde::{Deserialize, Serialize};
use sp_runtime::{
Expand Down Expand Up @@ -136,19 +143,15 @@ pub mod pallet {
pub struct Pallet<T>(PhantomData<T>);

// Negative imbalance type of this pallet.
pub(crate) type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
pub(crate) type CreditOf<T> =
Credit<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;

#[pallet::config]
pub trait Config: frame_system::Config {
/// The currency trait.
/// This has been soft-deprecated but it still needs to be used here in order to access `NegativeImbalance`
/// which is defined in the currency trait.
type Currency: Currency<Self::AccountId, Balance = Balance>;
type Currency: Balanced<Self::AccountId, Balance = Balance>;

/// Handler for 'per-block' payouts.
type PayoutPerBlock: PayoutPerBlock<NegativeImbalanceOf<Self>>;
type PayoutPerBlock: PayoutPerBlock<CreditOf<Self>>;

/// Cycle ('year') configuration - covers periods, subperiods, eras & blocks.
type CycleConfiguration: CycleConfiguration;
Expand Down Expand Up @@ -451,9 +454,11 @@ pub mod pallet {

// This can fail only if the amount is below existential deposit & the account doesn't exist,
// or if the account has no provider references.
// Another possibility is overflow, but if that happens, we already have a huge problem.
//
// In both cases, the reward is lost but this can be ignored since it's extremely unlikely
// to appear and doesn't bring any real harm.
let _ = T::Currency::deposit_creating(account, reward);
let _ = T::Currency::deposit(account, reward, Precision::Exact);
Ok(())
}
}
Expand Down
19 changes: 10 additions & 9 deletions pallets/inflation/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,13 @@
// along with Astar. If not, see <http://www.gnu.org/licenses/>.

use crate::{
self as pallet_inflation, ActiveInflationConfig, CycleConfiguration, InflationParameters,
InflationParams, NegativeImbalanceOf, PayoutPerBlock,
self as pallet_inflation, ActiveInflationConfig, CreditOf, CycleConfiguration,
InflationParameters, InflationParams, PayoutPerBlock,
};

use frame_support::{
construct_runtime, parameter_types,
traits::Currency,
traits::{ConstU128, ConstU32, Hooks},
traits::{fungible::Balanced, ConstU128, ConstU32, Hooks},
weights::Weight,
PalletId,
};
Expand Down Expand Up @@ -110,13 +109,15 @@ pub(crate) const TREASURY_POT: PalletId = PalletId(*b"moktrsry");
pub(crate) const COLLATOR_POT: PalletId = PalletId(*b"mokcolat");

pub struct DummyPayoutPerBlock;
impl PayoutPerBlock<NegativeImbalanceOf<Test>> for DummyPayoutPerBlock {
fn treasury(reward: NegativeImbalanceOf<Test>) {
Balances::resolve_creating(&TREASURY_POT.into_account_truncating(), reward);
impl PayoutPerBlock<CreditOf<Test>> for DummyPayoutPerBlock {
fn treasury(reward: CreditOf<Test>) {
Balances::resolve(&TREASURY_POT.into_account_truncating(), reward)
.expect("Must succeed for test.");
}

fn collators(reward: NegativeImbalanceOf<Test>) {
Balances::resolve_creating(&COLLATOR_POT.into_account_truncating(), reward);
fn collators(reward: CreditOf<Test>) {
Balances::resolve(&COLLATOR_POT.into_account_truncating(), reward)
.expect("Must succeed for test.");
}
}

Expand Down
11 changes: 6 additions & 5 deletions runtime/astar/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use frame_support::{
genesis_builder_helper::{build_state, get_preset},
parameter_types,
traits::{
fungible::{Balanced, Credit, HoldConsideration},
AsEnsureOriginWithArg, ConstBool, ConstU32, Contains, Currency, FindAuthor, Get, Imbalance,
InstanceFilter, Nothing, OnFinalize, OnUnbalanced, Randomness, WithdrawReasons,
},
Expand Down Expand Up @@ -402,12 +403,12 @@ impl pallet_dapp_staking_v3::Config for Runtime {
}

pub struct InflationPayoutPerBlock;
impl pallet_inflation::PayoutPerBlock<NegativeImbalance> for InflationPayoutPerBlock {
fn treasury(reward: NegativeImbalance) {
Balances::resolve_creating(&TreasuryPalletId::get().into_account_truncating(), reward);
impl pallet_inflation::PayoutPerBlock<Credit<AccountId, Balances>> for InflationPayoutPerBlock {
fn treasury(reward: Credit<AccountId, Balances>) {
let _ = Balances::resolve(&TreasuryPalletId::get().into_account_truncating(), reward);
}

fn collators(reward: NegativeImbalance) {
fn collators(reward: Credit<AccountId, Balances>) {
ToStakingPot::on_unbalanced(reward);
}
}
Expand Down Expand Up @@ -548,7 +549,7 @@ pub struct ToStakingPot;
impl OnUnbalanced<NegativeImbalance> for ToStakingPot {
fn on_nonzero_unbalanced(amount: NegativeImbalance) {
let staking_pot = PotId::get().into_account_truncating();
Balances::resolve_creating(&staking_pot, amount);
Balances::resolve(&staking_pot, amount);
}
}

Expand Down
10 changes: 5 additions & 5 deletions runtime/local/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use frame_support::{
genesis_builder_helper::{build_state, get_preset},
parameter_types,
traits::{
fungible::HoldConsideration,
fungible::{Balanced, Credit, HoldConsideration},
tokens::{PayFromAccount, UnityAssetBalanceConversion},
AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, Currency, EqualPrivilegeOnly,
FindAuthor, Get, InstanceFilter, LinearStoragePrice, Nothing, OnFinalize, WithdrawReasons,
Expand Down Expand Up @@ -500,12 +500,12 @@ impl pallet_dapp_staking_v3::Config for Runtime {
}

pub struct InflationPayoutPerBlock;
impl pallet_inflation::PayoutPerBlock<NegativeImbalance> for InflationPayoutPerBlock {
fn treasury(reward: NegativeImbalance) {
Balances::resolve_creating(&TreasuryPalletId::get().into_account_truncating(), reward);
impl pallet_inflation::PayoutPerBlock<Credit<AccountId, Balances>> for InflationPayoutPerBlock {
fn treasury(reward: Credit<AccountId, Balances>) {
let _ = Balances::resolve(&TreasuryPalletId::get().into_account_truncating(), reward);
}

fn collators(_reward: NegativeImbalance) {
fn collators(_reward: Credit<AccountId, Balances>) {
// no collators for local dev node
}
}
Expand Down
88 changes: 46 additions & 42 deletions runtime/shibuya/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,18 @@ use frame_support::{
genesis_builder_helper::{build_state, get_preset},
parameter_types,
traits::{
fungible::HoldConsideration,
fungible::{Balanced, Credit, HoldConsideration},
tokens::{PayFromAccount, UnityAssetBalanceConversion},
AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, Contains, Currency,
EqualPrivilegeOnly, FindAuthor, Get, Imbalance, InstanceFilter, LinearStoragePrice,
Nothing, OnFinalize, OnUnbalanced, WithdrawReasons,
AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, Contains, EqualPrivilegeOnly,
FindAuthor, Get, Imbalance, InstanceFilter, LinearStoragePrice, Nothing, OnFinalize,
OnUnbalanced, WithdrawReasons,
},
weights::{
constants::{
BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND,
},
ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
WeightToFeePolynomial,
ConstantMultiplier, Weight, WeightToFee as WeightToFeeT, WeightToFeeCoefficient,
WeightToFeeCoefficients, WeightToFeePolynomial,
},
ConsensusEngineId, PalletId,
};
Expand Down Expand Up @@ -72,8 +72,8 @@ use sp_runtime::{
};
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
use xcm::{
latest::prelude::*, IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation,
VersionedXcm,
v4::{AssetId as XcmAssetId, Location as XcmLocation},
IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
};
use xcm_fee_payment_runtime_api::Error as XcmPaymentApiError;

Expand Down Expand Up @@ -483,12 +483,12 @@ impl pallet_dapp_staking_v3::Config for Runtime {
}

pub struct InflationPayoutPerBlock;
impl pallet_inflation::PayoutPerBlock<NegativeImbalance> for InflationPayoutPerBlock {
fn treasury(reward: NegativeImbalance) {
Balances::resolve_creating(&TreasuryPalletId::get().into_account_truncating(), reward);
impl pallet_inflation::PayoutPerBlock<Credit<AccountId, Balances>> for InflationPayoutPerBlock {
fn treasury(reward: Credit<AccountId, Balances>) {
let _ = Balances::resolve(&TreasuryPalletId::get().into_account_truncating(), reward);
}

fn collators(reward: NegativeImbalance) {
fn collators(reward: Credit<AccountId, Balances>) {
ToStakingPot::on_unbalanced(reward);
}
}
Expand Down Expand Up @@ -623,13 +623,11 @@ parameter_types! {
pub TreasuryAccountId: AccountId = TreasuryPalletId::get().into_account_truncating();
}

type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;

pub struct ToStakingPot;
impl OnUnbalanced<NegativeImbalance> for ToStakingPot {
fn on_nonzero_unbalanced(amount: NegativeImbalance) {
impl OnUnbalanced<Credit<AccountId, Balances>> for ToStakingPot {
fn on_nonzero_unbalanced(amount: Credit<AccountId, Balances>) {
let staking_pot = PotId::get().into_account_truncating();
Balances::resolve_creating(&staking_pot, amount);
let _ = Balances::resolve(&staking_pot, amount);
}
}

Expand Down Expand Up @@ -795,7 +793,7 @@ impl WeightToFeePolynomial for WeightToFee {
///
/// Similar to standard `WeightToFee` handler, but force uses the minimum multiplier.
pub struct XcmWeightToFee;
impl frame_support::weights::WeightToFee for XcmWeightToFee {
impl WeightToFeeT for XcmWeightToFee {
type Balance = Balance;

fn weight_to_fee(n: &Weight) -> Self::Balance {
Expand All @@ -804,8 +802,8 @@ impl frame_support::weights::WeightToFee for XcmWeightToFee {
}

pub struct DealWithFees;
impl OnUnbalanced<NegativeImbalance> for DealWithFees {
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {
impl OnUnbalanced<Credit<AccountId, Balances>> for DealWithFees {
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = Credit<AccountId, Balances>>) {
if let Some(fees) = fees_then_tips.next() {
// Burn 80% of fees, rest goes to collator, including 100% of the tips.
let (to_burn, mut collator) = fees.ration(80, 20);
Expand All @@ -824,7 +822,7 @@ impl OnUnbalanced<NegativeImbalance> for DealWithFees {

impl pallet_transaction_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;
type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, DealWithFees>;
type WeightToFee = WeightToFee;
type OperationalFeeMultiplier = OperationalFeeMultiplier;
type FeeMultiplierUpdate = TargetedFeeAdjustment<
Expand Down Expand Up @@ -930,7 +928,7 @@ impl pallet_evm::Config for Runtime {
// Ethereum-compatible chain_id:
// * Shibuya: 81
type ChainId = EVMChainId;
type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, ToStakingPot>;
type OnChargeTransaction = pallet_evm::EVMFungibleAdapter<Balances, ToStakingPot>;
type BlockGasLimit = BlockGasLimit;
type Timestamp = Timestamp;
type OnCreate = ();
Expand Down Expand Up @@ -2182,42 +2180,48 @@ impl_runtime_apis! {
}

// Native asset is always supported
let native_asset_location: Location = Location::try_from(xcm_config::ShibuyaLocation::get())
let native_asset_location: XcmLocation = XcmLocation::try_from(xcm_config::ShibuyaLocation::get())
.map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;

Ok([VersionedAssetId::V4(native_asset_location).into()]
.into_iter()
// Acquire foreign assets which have 'units per second' configured
.chain(
pallet_xc_asset_config::AssetLocationUnitsPerSecond::<Runtime>::iter_keys().map(|asset_location| {
VersionedAssetId::V3(asset_location.into())
})
Ok([VersionedAssetId::V4(native_asset_location.into())]
.into_iter()
// Acquire foreign assets which have 'units per second' configured
.chain(
pallet_xc_asset_config::AssetLocationUnitsPerSecond::<Runtime>::iter_keys().filter_map(|asset_location| {

).filter_map(|asset| asset.into_version(xcm_version).ok()))
match XcmLocation::try_from(asset_location) {
Ok(asset) => Some(VersionedAssetId::V4(asset.into())),
Err(_) => None,
}
})
).filter_map(|asset| asset.into_version(xcm_version).ok()).collect())
}

// TODO: improve this function, reduce code duplication, especially on a such functional level
// TODO: improve this function, reduce code duplication, especially on a such a functional level
fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
let native_asset_location: Location = Location::try_from(xcm_config::ShibuyaLocation::get())
let native_asset_location: XcmLocation = XcmLocation::try_from(xcm_config::ShibuyaLocation::get())
.map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
let native_asset = VersionedAssetId::V4(native_asset_location.into());

let asset = asset
.into_version(4)
.map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;

if native_asset == asset {
Ok(XcmWeightToFee::weight_to_fee(weight))
}else {

match pallet_xc_asset_config::AssetLocationUnitsPerSecond::<Runtime>::get(asset.into()) {
Some(units_per_sec) => {
Ok(units_per_sec.saturating_mul(weight.ref_time() as u128)
/ (WEIGHT_REF_TIME_PER_SECOND as u128))
}
None => Err(XcmPaymentApiError::AssetNotFound),
if native_asset == asset {
Ok(XcmWeightToFee::weight_to_fee(&weight))
} else {
let asset_id: XcmAssetId = asset.try_into().map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
let versioned_location = VersionedLocation::V4(asset_id.0);

match pallet_xc_asset_config::AssetLocationUnitsPerSecond::<Runtime>::get(versioned_location) {
Some(units_per_sec) => {
Ok(units_per_sec.saturating_mul(weight.ref_time() as u128)
/ (WEIGHT_REF_TIME_PER_SECOND as u128))
}
None => Err(XcmPaymentApiError::WeightNotComputable),
}
}
}

fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
Expand Down
11 changes: 6 additions & 5 deletions runtime/shiden/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use frame_support::{
genesis_builder_helper::{build_state, get_preset},
parameter_types,
traits::{
fungible::{Balanced, Credit, HoldConsideration},
AsEnsureOriginWithArg, ConstU32, Contains, Currency, FindAuthor, Get, Imbalance,
InstanceFilter, Nothing, OnFinalize, OnUnbalanced, WithdrawReasons,
},
Expand Down Expand Up @@ -442,12 +443,12 @@ impl pallet_dapp_staking_v3::Config for Runtime {
}

pub struct InflationPayoutPerBlock;
impl pallet_inflation::PayoutPerBlock<NegativeImbalance> for InflationPayoutPerBlock {
fn treasury(reward: NegativeImbalance) {
Balances::resolve_creating(&TreasuryPalletId::get().into_account_truncating(), reward);
impl pallet_inflation::PayoutPerBlock<Credit<AccountId, Balances>> for InflationPayoutPerBlock {
fn treasury(reward: Credit<AccountId, Balances>) {
let _ = Balances::resolve(&TreasuryPalletId::get().into_account_truncating(), reward);
}

fn collators(reward: NegativeImbalance) {
fn collators(reward: Credit<AccountId, Balances>) {
ToStakingPot::on_unbalanced(reward);
}
}
Expand Down Expand Up @@ -592,7 +593,7 @@ pub struct ToStakingPot;
impl OnUnbalanced<NegativeImbalance> for ToStakingPot {
fn on_nonzero_unbalanced(amount: NegativeImbalance) {
let staking_pot = PotId::get().into_account_truncating();
Balances::resolve_creating(&staking_pot, amount);
Balances::resolve(&staking_pot, amount);
}
}

Expand Down

0 comments on commit 6f994c2

Please sign in to comment.