difftreelog
refactor return CrossAccountId in backing storages
in: master
14 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -75,9 +75,17 @@
) -> Result<String>;
#[rpc(name = "nft_adminlist")]
- fn adminlist(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<Vec<AccountId>>;
+ fn adminlist(
+ &self,
+ collection: CollectionId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<CrossAccountId>>;
#[rpc(name = "nft_allowlist")]
- fn allowlist(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<Vec<AccountId>>;
+ fn allowlist(
+ &self,
+ collection: CollectionId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<CrossAccountId>>;
#[rpc(name = "nft_lastTokenId")]
fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;
}
@@ -150,7 +158,7 @@
pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string());
pass_method!(allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string());
- pass_method!(adminlist(collection: CollectionId) -> Vec<AccountId>);
- pass_method!(allowlist(collection: CollectionId) -> Vec<AccountId>);
+ pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);
+ pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);
pass_method!(last_token_id(collection: CollectionId) -> TokenId);
}
pallets/common/src/account.rsdiffbeforeafterboth--- a/pallets/common/src/account.rs
+++ b/pallets/common/src/account.rs
@@ -19,6 +19,8 @@
fn from_sub(account: AccountId) -> Self;
fn from_eth(account: H160) -> Self;
+
+ fn conv_eq(&self, other: &Self) -> bool;
}
#[derive(Encode, Decode, Serialize, Deserialize, TypeInfo)]
@@ -28,7 +30,7 @@
Ethereum(H160),
}
-#[derive(Eq)]
+#[derive(PartialEq, Eq)]
pub struct BasicCrossAccountId<T: Config> {
/// If true - then ethereum is canonical encoding
from_ethereum: bool,
@@ -77,18 +79,6 @@
}
}
-impl<T: Config> PartialEq for BasicCrossAccountId<T> {
- fn eq(&self, other: &Self) -> bool {
- if self.from_ethereum == other.from_ethereum {
- self.substrate == other.substrate && self.ethereum == other.ethereum
- } else if self.from_ethereum {
- // ethereum is canonical encoding, but we need to compare derived address
- self.substrate == other.substrate
- } else {
- self.ethereum == other.ethereum
- }
- }
-}
impl<T: Config> Clone for BasicCrossAccountId<T> {
fn clone(&self) -> Self {
Self {
@@ -158,6 +148,16 @@
from_ethereum: true,
}
}
+ fn conv_eq(&self, other: &Self) -> bool {
+ if self.from_ethereum == other.from_ethereum {
+ self.substrate == other.substrate && self.ethereum == other.ethereum
+ } else if self.from_ethereum {
+ // ethereum is canonical encoding, but we need to compare derived address
+ self.substrate == other.substrate
+ } else {
+ self.ethereum == other.ethereum
+ }
+ }
}
impl<T: Config> From<BasicCrossAccountIdRepr<T::AccountId>> for BasicCrossAccountId<T> {
fn from(repr: BasicCrossAccountIdRepr<T::AccountId>) -> Self {
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -98,7 +98,7 @@
pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> Result<bool, DispatchError> {
self.consume_sload()?;
- Ok(*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject.as_sub())))
+ Ok(*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject)))
}
pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {
ensure!(self.is_owner_or_admin(subject)?, <Error<T>>::NoPermission);
@@ -114,7 +114,7 @@
self.consume_sload()?;
ensure!(
- <Allowlist<T>>::get((self.id, user.as_sub())),
+ <Allowlist<T>>::get((self.id, user)),
<Error<T>>::AddressNotInAllowlist
);
Ok(())
@@ -139,8 +139,7 @@
#[frame_support::pallet]
pub mod pallet {
use super::*;
- use frame_support::{pallet_prelude::*};
- use frame_support::{Blake2_128Concat, storage::Key};
+ use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};
use account::{EvmBackwardsAddressMapping, CrossAccountId};
use frame_support::traits::Currency;
use nft_data_structs::TokenId;
@@ -311,7 +310,7 @@
pub type IsAdmin<T: Config> = StorageNMap<
Key = (
Key<Blake2_128Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = bool,
QueryKind = ValueQuery,
@@ -322,7 +321,7 @@
pub type Allowlist<T: Config> = StorageNMap<
Key = (
Key<Blake2_128Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = bool,
QueryKind = ValueQuery,
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -2,9 +2,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use nft_data_structs::TokenId;
-use pallet_common::{
- CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
-};
+use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
@@ -188,7 +186,7 @@
}
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
- if <Balance<T>>::get((self.id, account.as_sub())) != 0 {
+ if <Balance<T>>::get((self.id, account)) != 0 {
vec![TokenId::default()]
} else {
vec![]
@@ -218,7 +216,7 @@
}
fn account_balance(&self, account: T::CrossAccountId) -> u32 {
- if <Balance<T>>::get((self.id, account.as_sub())) != 0 {
+ if <Balance<T>>::get((self.id, account)) != 0 {
1
} else {
0
@@ -229,7 +227,7 @@
if token != TokenId::default() {
return 0;
}
- <Balance<T>>::get((self.id, account.as_sub()))
+ <Balance<T>>::get((self.id, account))
}
fn allowance(
@@ -241,6 +239,6 @@
if token != TokenId::default() {
return 0;
}
- <Allowance<T>>::get((self.id, sender.as_sub(), spender.as_sub()))
+ <Allowance<T>>::get((self.id, sender, spender))
}
}
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -52,7 +52,7 @@
}
fn balance_of(&self, owner: address) -> Result<uint256> {
let owner = T::CrossAccountId::from_eth(owner);
- let balance = <Balance<T>>::get((self.id, owner.as_sub()));
+ let balance = <Balance<T>>::get((self.id, owner));
Ok(balance.into())
}
fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {
@@ -92,7 +92,7 @@
let owner = T::CrossAccountId::from_eth(owner);
let spender = T::CrossAccountId::from_eth(spender);
- Ok(<Allowance<T>>::get((self.id, owner.as_sub(), spender.as_sub())).into())
+ Ok(<Allowance<T>>::get((self.id, owner, spender)).into())
}
}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -55,7 +55,7 @@
pub(super) type Balance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = u128,
QueryKind = ValueQuery,
@@ -65,8 +65,8 @@
pub(super) type Allowance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128, T::AccountId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128, T::CrossAccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = u128,
QueryKind = ValueQuery,
@@ -119,7 +119,7 @@
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
- let balance = <Balance<T>>::get((collection.id, owner.as_sub()))
+ let balance = <Balance<T>>::get((collection.id, owner))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -130,9 +130,9 @@
// =========
if balance == 0 {
- <Balance<T>>::remove((collection.id, owner.as_sub()));
+ <Balance<T>>::remove((collection.id, owner));
} else {
- <Balance<T>>::insert((collection.id, owner.as_sub()), balance);
+ <Balance<T>>::insert((collection.id, owner), balance);
}
<TotalSupply<T>>::insert(collection.id, total_supply);
@@ -167,12 +167,12 @@
}
<PalletCommon<T>>::ensure_correct_receiver(to)?;
- let balance_from = <Balance<T>>::get((collection.id, from.as_sub()))
+ let balance_from = <Balance<T>>::get((collection.id, from))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let balance_to = if from != to {
Some(
- <Balance<T>>::get((collection.id, to.as_sub()))
+ <Balance<T>>::get((collection.id, to))
.checked_add(amount)
.ok_or(ArithmeticError::Overflow)?,
)
@@ -190,11 +190,11 @@
if let Some(balance_to) = balance_to {
// from != to
if balance_from == 0 {
- <Balance<T>>::remove((collection.id, from.as_sub()));
+ <Balance<T>>::remove((collection.id, from));
} else {
- <Balance<T>>::insert((collection.id, from.as_sub()), balance_from);
+ <Balance<T>>::insert((collection.id, from), balance_from);
}
- <Balance<T>>::insert((collection.id, to.as_sub()), balance_to);
+ <Balance<T>>::insert((collection.id, to), balance_to);
}
collection.log_infallible(ERC20Events::Transfer {
@@ -242,7 +242,7 @@
collection.consume_sload()?;
let balance = balances
.entry(user.clone())
- .or_insert_with(|| <Balance<T>>::get((collection.id, user.as_sub())));
+ .or_insert_with(|| <Balance<T>>::get((collection.id, user)));
*balance = (*balance)
.checked_add(amount)
.ok_or(ArithmeticError::Overflow)?;
@@ -259,7 +259,7 @@
<TotalSupply<T>>::insert(collection.id, total_supply);
for (user, amount) in balances {
- <Balance<T>>::insert((collection.id, user.as_sub()), amount);
+ <Balance<T>>::insert((collection.id, &user), amount);
collection.log_infallible(ERC20Events::Transfer {
from: H160::default(),
@@ -283,7 +283,7 @@
spender: &T::CrossAccountId,
amount: u128,
) {
- <Allowance<T>>::insert((collection.id, owner.as_sub(), spender.as_sub()), amount);
+ <Allowance<T>>::insert((collection.id, owner, spender), amount);
collection.log_infallible(ERC20Events::Approval {
owner: *owner.as_eth(),
@@ -310,7 +310,7 @@
collection.check_allowlist(&spender)?;
}
- if <Balance<T>>::get((collection.id, owner.as_sub())) < amount {
+ if <Balance<T>>::get((collection.id, owner)) < amount {
ensure!(
collection.ignores_owned_amount(owner)?,
<CommonError<T>>::CantApproveMoreThanOwned
@@ -330,7 +330,7 @@
to: &T::CrossAccountId,
amount: u128,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::transfer(collection, from, to, amount);
}
if collection.access == AccessMode::WhiteList {
@@ -338,8 +338,7 @@
collection.check_allowlist(spender)?;
}
- let allowance = <Allowance<T>>::get((collection.id, from.as_sub(), spender.as_sub()))
- .checked_sub(amount);
+ let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
collection.ignores_allowance(spender)?,
@@ -362,7 +361,7 @@
from: &T::CrossAccountId,
amount: u128,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::burn(collection, from, amount);
}
if collection.access == AccessMode::WhiteList {
@@ -370,8 +369,7 @@
collection.check_allowlist(spender)?;
}
- let allowance = <Allowance<T>>::get((collection.id, from.as_sub(), spender.as_sub()))
- .checked_sub(amount);
+ let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
collection.ignores_allowance(spender)?,
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -948,12 +948,12 @@
// TODO: limit returned entries?
impl<T: Config> Pallet<T> {
- pub fn adminlist(collection: CollectionId) -> Vec<T::AccountId> {
+ pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
<IsAdmin<T>>::iter_prefix((collection,))
.map(|(a, _)| a)
.collect()
}
- pub fn allowlist(collection: CollectionId) -> Vec<T::AccountId> {
+ pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
<Allowlist<T>>::iter_prefix((collection,))
.map(|(a, _)| a)
.collect()
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -2,9 +2,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use nft_data_structs::TokenId;
-use pallet_common::{
- CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
-};
+use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
@@ -200,7 +198,7 @@
}
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
- <Owned<T>>::iter_prefix((self.id, account.as_sub()))
+ <Owned<T>>::iter_prefix((self.id, account))
.map(|(id, _)| id)
.collect()
}
@@ -234,7 +232,7 @@
}
fn account_balance(&self, account: T::CrossAccountId) -> u32 {
- <AccountBalance<T>>::get((self.id, account.as_sub()))
+ <AccountBalance<T>>::get((self.id, account))
}
fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -93,7 +93,7 @@
impl<T: Config> NonfungibleHandle<T> {
fn balance_of(&self, owner: address) -> Result<uint256> {
let owner = T::CrossAccountId::from_eth(owner);
- let balance = <AccountBalance<T>>::get((self.id, owner.as_sub()));
+ let balance = <AccountBalance<T>>::get((self.id, owner));
Ok(balance.into())
}
fn owner_of(&self, token_id: uint256) -> Result<address> {
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -80,7 +80,7 @@
pub(super) type Owned<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
Key<Twox64Concat, TokenId>,
),
Value = bool,
@@ -91,7 +91,7 @@
pub(super) type AccountBalance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = u32,
QueryKind = ValueQuery,
@@ -179,7 +179,7 @@
// =========
- <Owned<T>>::remove((collection.id, token_data.owner.as_sub(), token));
+ <Owned<T>>::remove((collection.id, &token_data.owner, token));
<TokensBurnt<T>>::insert(collection.id, burnt);
<TokenData<T>>::remove((collection.id, token));
let old_spender = <Allowance<T>>::take((collection.id, token));
@@ -234,11 +234,11 @@
}
<PalletCommon<T>>::ensure_correct_receiver(to)?;
- let balance_from = <AccountBalance<T>>::get((collection.id, from.as_sub()))
+ let balance_from = <AccountBalance<T>>::get((collection.id, from))
.checked_sub(1)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let balance_to = if from != to {
- let balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))
+ let balance_to = <AccountBalance<T>>::get((collection.id, to))
.checked_add(1)
.ok_or(ArithmeticError::Overflow)?;
@@ -268,13 +268,13 @@
if let Some(balance_to) = balance_to {
// from != to
if balance_from == 0 {
- <AccountBalance<T>>::remove((collection.id, from.as_sub()));
+ <AccountBalance<T>>::remove((collection.id, from));
} else {
- <AccountBalance<T>>::insert((collection.id, from.as_sub()), balance_from);
+ <AccountBalance<T>>::insert((collection.id, from), balance_from);
}
- <AccountBalance<T>>::insert((collection.id, to.as_sub()), balance_to);
- <Owned<T>>::remove((collection.id, from.as_sub(), token));
- <Owned<T>>::insert((collection.id, to.as_sub(), token), true);
+ <AccountBalance<T>>::insert((collection.id, to), balance_to);
+ <Owned<T>>::remove((collection.id, from, token));
+ <Owned<T>>::insert((collection.id, to, token), true);
}
Self::set_allowance_unchecked(collection, from, token, None, true);
@@ -336,8 +336,8 @@
let mut balances = BTreeMap::new();
for data in &data {
let balance = balances
- .entry(data.owner.as_sub())
- .or_insert_with(|| <AccountBalance<T>>::get((collection.id, data.owner.as_sub())));
+ .entry(&data.owner)
+ .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));
*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;
ensure!(
@@ -364,7 +364,7 @@
owner: data.owner.clone(),
},
);
- <Owned<T>>::insert((collection.id, data.owner.as_sub(), token), true);
+ <Owned<T>>::insert((collection.id, &data.owner, token), true);
collection.log_infallible(ERC721Events::Transfer {
from: H160::default(),
@@ -481,7 +481,7 @@
to: &T::CrossAccountId,
token: TokenId,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::transfer(collection, from, to, token);
}
if collection.access == AccessMode::WhiteList {
@@ -509,7 +509,7 @@
from: &T::CrossAccountId,
token: TokenId,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::burn(collection, from, token);
}
if collection.access == AccessMode::WhiteList {
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -3,9 +3,7 @@
use sp_std::collections::btree_map::BTreeMap;
use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};
use nft_data_structs::TokenId;
-use pallet_common::{
- CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
-};
+use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
@@ -196,7 +194,7 @@
}
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
- <Owned<T>>::iter_prefix((self.id, account.as_sub()))
+ <Owned<T>>::iter_prefix((self.id, account))
.map(|(id, _)| id)
.collect()
}
@@ -224,11 +222,11 @@
}
fn account_balance(&self, account: T::CrossAccountId) -> u32 {
- <AccountBalance<T>>::get((self.id, account.as_sub()))
+ <AccountBalance<T>>::get((self.id, account))
}
fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {
- <Balance<T>>::get((self.id, token, account.as_sub()))
+ <Balance<T>>::get((self.id, token, account))
}
fn allowance(
@@ -237,6 +235,6 @@
spender: T::CrossAccountId,
token: TokenId,
) -> u128 {
- <Allowance<T>>::get((self.id, token, sender.as_sub(), spender))
+ <Allowance<T>>::get((self.id, token, sender, spender))
}
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -83,7 +83,7 @@
pub(super) type Owned<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
Key<Twox64Concat, TokenId>,
),
Value = bool,
@@ -95,7 +95,7 @@
Key = (
Key<Twox64Concat, CollectionId>,
// Owner
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = u32,
QueryKind = ValueQuery,
@@ -107,7 +107,7 @@
Key<Twox64Concat, CollectionId>,
Key<Twox64Concat, TokenId>,
// Owner
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = u128,
QueryKind = ValueQuery,
@@ -119,7 +119,7 @@
Key<Twox64Concat, CollectionId>,
Key<Twox64Concat, TokenId>,
// Owner
- Key<Blake2_128, T::AccountId>,
+ Key<Blake2_128, T::CrossAccountId>,
// Spender
Key<Blake2_128Concat, T::CrossAccountId>,
),
@@ -206,18 +206,18 @@
if total_supply == 0 {
// Ensure user actually owns this amount
ensure!(
- <Balance<T>>::get((collection.id, token, owner.as_sub())) == amount,
+ <Balance<T>>::get((collection.id, token, owner)) == amount,
<CommonError<T>>::TokenValueTooLow
);
- let account_balance = <AccountBalance<T>>::get((collection.id, owner.as_sub()))
+ let account_balance = <AccountBalance<T>>::get((collection.id, owner))
.checked_sub(1)
// Should not occur
.ok_or(ArithmeticError::Underflow)?;
// =========
- <Owned<T>>::remove((collection.id, owner.as_sub(), token));
- <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);
+ <Owned<T>>::remove((collection.id, owner, token));
+ <AccountBalance<T>>::insert((collection.id, owner), account_balance);
Self::burn_token(collection, token)?;
<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
collection.id,
@@ -228,11 +228,11 @@
return Ok(());
}
- let balance = <Balance<T>>::get((collection.id, token, owner.as_sub()))
+ let balance = <Balance<T>>::get((collection.id, token, owner))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let account_balance = if balance == 0 {
- <AccountBalance<T>>::get((collection.id, owner.as_sub()))
+ <AccountBalance<T>>::get((collection.id, owner))
.checked_sub(1)
// Should not occur
.ok_or(ArithmeticError::Underflow)?
@@ -243,11 +243,11 @@
// =========
if balance == 0 {
- <Owned<T>>::remove((collection.id, owner.as_sub(), token));
- <Balance<T>>::remove((collection.id, token, owner.as_sub()));
- <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);
+ <Owned<T>>::remove((collection.id, owner, token));
+ <Balance<T>>::remove((collection.id, token, owner));
+ <AccountBalance<T>>::insert((collection.id, owner), account_balance);
} else {
- <Balance<T>>::insert((collection.id, token, owner.as_sub()), balance);
+ <Balance<T>>::insert((collection.id, token, owner), balance);
}
<TotalSupply<T>>::insert((collection.id, token), total_supply);
// TODO: ERC20 transfer event
@@ -278,13 +278,13 @@
}
<PalletCommon<T>>::ensure_correct_receiver(to)?;
- let balance_from = <Balance<T>>::get((collection.id, token, from.as_sub()))
+ let balance_from = <Balance<T>>::get((collection.id, token, from))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let mut create_target = false;
let from_to_differ = from != to;
let balance_to = if from != to {
- let old_balance = <Balance<T>>::get((collection.id, token, to.as_sub()));
+ let old_balance = <Balance<T>>::get((collection.id, token, to));
if old_balance == 0 {
create_target = true;
}
@@ -299,7 +299,7 @@
let account_balance_from = if balance_from == 0 {
Some(
- <AccountBalance<T>>::get((collection.id, from.as_sub()))
+ <AccountBalance<T>>::get((collection.id, from))
.checked_sub(1)
// Should not occur
.ok_or(ArithmeticError::Underflow)?,
@@ -310,7 +310,7 @@
// Account data is created in token, AccountBalance should be increased
// But only if from != to as we shouldn't check overflow in this case
let account_balance_to = if create_target && from_to_differ {
- let account_balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))
+ let account_balance_to = <AccountBalance<T>>::get((collection.id, to))
.checked_add(1)
.ok_or(ArithmeticError::Overflow)?;
ensure!(
@@ -328,18 +328,18 @@
if let Some(balance_to) = balance_to {
// from != to
if balance_from == 0 {
- <Balance<T>>::remove((collection.id, token, from.as_sub()));
+ <Balance<T>>::remove((collection.id, token, from));
} else {
- <Balance<T>>::insert((collection.id, token, from.as_sub()), balance_from);
+ <Balance<T>>::insert((collection.id, token, from), balance_from);
}
- <Balance<T>>::insert((collection.id, token, to.as_sub()), balance_to);
+ <Balance<T>>::insert((collection.id, token, to), balance_to);
if let Some(account_balance_from) = account_balance_from {
- <AccountBalance<T>>::insert((collection.id, from.as_sub()), account_balance_from);
- <Owned<T>>::remove((collection.id, from.as_sub(), token));
+ <AccountBalance<T>>::insert((collection.id, from), account_balance_from);
+ <Owned<T>>::remove((collection.id, from, token));
}
if let Some(account_balance_to) = account_balance_to {
- <AccountBalance<T>>::insert((collection.id, to.as_sub()), account_balance_to);
- <Owned<T>>::insert((collection.id, to.as_sub(), token), true);
+ <AccountBalance<T>>::insert((collection.id, to), account_balance_to);
+ <Owned<T>>::insert((collection.id, to, token), true);
}
}
@@ -412,8 +412,8 @@
for data in &data {
for (owner, _) in &data.users {
let balance = balances
- .entry(owner.as_sub())
- .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner.as_sub())));
+ .entry(owner)
+ .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));
*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;
ensure!(
@@ -444,8 +444,8 @@
if amount == 0 {
continue;
}
- <Balance<T>>::insert((collection.id, token_id, user.as_sub()), amount);
- <Owned<T>>::insert((collection.id, user.as_sub(), TokenId(token_id)), true);
+ <Balance<T>>::insert((collection.id, token_id, &user), amount);
+ <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);
// TODO: ERC20 transfer event
<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
collection.id,
@@ -465,7 +465,7 @@
token: TokenId,
amount: u128,
) {
- <Allowance<T>>::insert((collection.id, token, sender.as_sub(), spender), amount);
+ <Allowance<T>>::insert((collection.id, token, sender, spender), amount);
// TODO: ERC20 approval event
<PalletCommon<T>>::deposit_event(CommonEvent::Approved(
collection.id,
@@ -490,7 +490,7 @@
<PalletCommon<T>>::ensure_correct_receiver(spender)?;
- if <Balance<T>>::get((collection.id, token, sender.as_sub())) < amount {
+ if <Balance<T>>::get((collection.id, token, sender)) < amount {
ensure!(
collection.ignores_owned_amount(sender)? && Self::token_exists(collection, token),
<CommonError<T>>::CantApproveMoreThanOwned
@@ -511,7 +511,7 @@
token: TokenId,
amount: u128,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::transfer(collection, from, to, token, amount);
}
if collection.access == AccessMode::WhiteList {
@@ -519,8 +519,8 @@
collection.check_allowlist(spender)?;
}
- let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))
- .checked_sub(amount);
+ let allowance =
+ <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
collection.ignores_allowance(spender)?,
@@ -544,7 +544,7 @@
token: TokenId,
amount: u128,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::burn(collection, from, token, amount);
}
if collection.access == AccessMode::WhiteList {
@@ -552,8 +552,8 @@
collection.check_allowlist(spender)?;
}
- let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))
- .checked_sub(amount);
+ let allowance =
+ <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
collection.ignores_allowance(spender)?,
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -30,8 +30,8 @@
/// Used for ethereum integration
fn eth_contract_code(account: H160) -> Option<Vec<u8>>;
- fn adminlist(collection: CollectionId) -> Vec<AccountId>;
- fn allowlist(collection: CollectionId) -> Vec<AccountId>;
+ fn adminlist(collection: CollectionId) -> Vec<CrossAccountId>;
+ fn allowlist(collection: CollectionId) -> Vec<CrossAccountId>;
fn last_token_id(collection: CollectionId) -> TokenId;
}
}
runtime/src/lib.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,26 AccountIdConversion,27 },28 transaction_validity::{TransactionSource, TransactionValidity},29 ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};40// A few exports that help ease life for downstream crates.41pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44 construct_runtime, match_type,45 dispatch::DispatchResult,46 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 traits::{48 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50 },51 weights::{52 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55 },56};57use nft_data_structs::*;58// use pallet_contracts::weights::WeightInfo;59// #[cfg(any(feature = "std", test))]60use frame_system::{61 self as system, EnsureRoot, EnsureSigned,62 limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{65 traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73 traits::{Dispatchable, PostDispatchInfoOf},74 transaction_validity::TransactionValidityError,75};7677// pub use pallet_timestamp::Call as TimestampCall;78pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7980// Polkadot imports81use pallet_xcm::XcmPassthrough;82use polkadot_parachain::primitives::Sibling;83use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};84use xcm_builder::{85 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,86 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,87 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,88 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,89 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,90};91use xcm_executor::{Config, XcmExecutor};9293// mod chain_extension;94// use crate::chain_extension::{NFTExtension, Imbalance};9596/// An index to a block.97pub type BlockNumber = u32;9899/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.100pub type Signature = MultiSignature;101102/// Some way of identifying an account on the chain. We intentionally make it equivalent103/// to the public key of our transaction signing scheme.104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;105106pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;107108/// The type for looking up accounts. We don't expect more than 4 billion of them, but you109/// never know...110pub type AccountIndex = u32;111112/// Balance of an account.113pub type Balance = u128;114115/// Index of a transaction in the chain.116pub type Index = u32;117118/// A hash of some data used by the chain.119pub type Hash = sp_core::H256;120121/// Digest item type.122pub type DigestItem = generic::DigestItem<Hash>;123124/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know125/// the specifics of the runtime. They can then be made to be agnostic over specific formats126/// of data like extrinsics, allowing for them to continue syncing the network through upgrades127/// to even the core data structures.128pub mod opaque {129 use super::*;130131 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;132133 /// Opaque block type.134 pub type Block = generic::Block<Header, UncheckedExtrinsic>;135136 pub type SessionHandlers = ();137138 impl_opaque_keys! {139 pub struct SessionKeys {140 pub aura: Aura,141 }142 }143}144145/// This runtime version.146pub const VERSION: RuntimeVersion = RuntimeVersion {147 spec_name: create_runtime_str!("opal"),148 impl_name: create_runtime_str!("opal"),149 authoring_version: 1,150 spec_version: 912200,151 impl_version: 1,152 apis: RUNTIME_API_VERSIONS,153 transaction_version: 1,154};155156pub const MILLISECS_PER_BLOCK: u64 = 12000;157158pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;159160// These time units are defined in number of blocks.161pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);162pub const HOURS: BlockNumber = MINUTES * 60;163pub const DAYS: BlockNumber = HOURS * 24;164165parameter_types! {166 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;167}168169#[derive(codec::Encode, codec::Decode)]170pub enum XCMPMessage<XAccountId, XBalance> {171 /// Transfer tokens to the given account from the Parachain account.172 TransferToken(XAccountId, XBalance),173}174175/// The version information used to identify this runtime when compiled natively.176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178 NativeVersion {179 runtime_version: VERSION,180 can_author_with: Default::default(),181 }182}183184type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;185186pub struct DealWithFees;187impl OnUnbalanced<NegativeImbalance> for DealWithFees {188 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {189 if let Some(fees) = fees_then_tips.next() {190 // for fees, 100% to treasury191 let mut split = fees.ration(100, 0);192 if let Some(tips) = fees_then_tips.next() {193 // for tips, if any, 100% to treasury194 tips.ration_merge_into(100, 0, &mut split);195 }196 Treasury::on_unbalanced(split.0);197 // Author::on_unbalanced(split.1);198 }199 }200}201202/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.203/// This is used to limit the maximal weight of a single extrinsic.204const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);205/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used206/// by Operational extrinsics.207const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);208/// We allow for 2 seconds of compute with a 6 second average block time.209const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;210211parameter_types! {212 pub const BlockHashCount: BlockNumber = 2400;213 pub RuntimeBlockLength: BlockLength =214 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);215 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);216 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;217 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()218 .base_block(BlockExecutionWeight::get())219 .for_class(DispatchClass::all(), |weights| {220 weights.base_extrinsic = ExtrinsicBaseWeight::get();221 })222 .for_class(DispatchClass::Normal, |weights| {223 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);224 })225 .for_class(DispatchClass::Operational, |weights| {226 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);227 // Operational transactions have some extra reserved space, so that they228 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.229 weights.reserved = Some(230 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT231 );232 })233 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)234 .build_or_panic();235 pub const Version: RuntimeVersion = VERSION;236 pub const SS58Prefix: u8 = 42;237}238239parameter_types! {240 pub const ChainId: u64 = 8888;241}242243pub struct FixedFee;244impl FeeCalculator for FixedFee {245 fn min_gas_price() -> U256 {246 1.into()247 }248}249250impl pallet_evm::Config for Runtime {251 type BlockGasLimit = BlockGasLimit;252 type FeeCalculator = FixedFee;253 type GasWeightMapping = ();254 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;255 type CallOrigin = EnsureAddressTruncated;256 type WithdrawOrigin = EnsureAddressTruncated;257 type AddressMapping = HashedAddressMapping<Self::Hashing>;258 type Precompiles = ();259 type Currency = Balances;260 type Event = Event;261 type OnMethodCall = (262 pallet_evm_migration::OnMethodCall<Self>,263 pallet_nft::NftErcSupport<Self>,264 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,265 );266 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;267 type ChainId = ChainId;268 type Runner = pallet_evm::runner::stack::Runner<Self>;269 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;270 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;271 type FindAuthor = EthereumFindAuthor<Aura>;272}273274impl pallet_evm_migration::Config for Runtime {275 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;276}277278pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);279impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {280 fn find_author<'a, I>(digests: I) -> Option<H160>281 where282 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,283 {284 if let Some(author_index) = F::find_author(digests) {285 let authority_id = Aura::authorities()[author_index as usize].clone();286 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));287 }288 None289 }290}291292parameter_types! {293 pub BlockGasLimit: U256 = U256::from(u32::max_value());294}295296impl pallet_ethereum::Config for Runtime {297 type Event = Event;298 type StateRoot = pallet_ethereum::IntermediateStateRoot;299 type EvmSubmitLog = pallet_evm::Pallet<Self>;300}301302impl pallet_randomness_collective_flip::Config for Runtime {}303304impl system::Config for Runtime {305 /// The data to be stored in an account.306 type AccountData = pallet_balances::AccountData<Balance>;307 /// The identifier used to distinguish between accounts.308 type AccountId = AccountId;309 /// The basic call filter to use in dispatchable.310 type BaseCallFilter = Everything;311 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).312 type BlockHashCount = BlockHashCount;313 /// The maximum length of a block (in bytes).314 type BlockLength = RuntimeBlockLength;315 /// The index type for blocks.316 type BlockNumber = BlockNumber;317 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.318 type BlockWeights = RuntimeBlockWeights;319 /// The aggregated dispatch type that is available for extrinsics.320 type Call = Call;321 /// The weight of database operations that the runtime can invoke.322 type DbWeight = RocksDbWeight;323 /// The ubiquitous event type.324 type Event = Event;325 /// The type for hashing blocks and tries.326 type Hash = Hash;327 /// The hashing algorithm used.328 type Hashing = BlakeTwo256;329 /// The header type.330 type Header = generic::Header<BlockNumber, BlakeTwo256>;331 /// The index type for storing how many extrinsics an account has signed.332 type Index = Index;333 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.334 type Lookup = AccountIdLookup<AccountId, ()>;335 /// What to do if an account is fully reaped from the system.336 type OnKilledAccount = ();337 /// What to do if a new account is created.338 type OnNewAccount = ();339 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;340 /// The ubiquitous origin type.341 type Origin = Origin;342 /// This type is being generated by `construct_runtime!`.343 type PalletInfo = PalletInfo;344 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.345 type SS58Prefix = SS58Prefix;346 /// Weight information for the extrinsics of this pallet.347 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;348 /// Version of the runtime.349 type Version = Version;350}351352parameter_types! {353 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;354}355356impl pallet_timestamp::Config for Runtime {357 /// A timestamp: milliseconds since the unix epoch.358 type Moment = u64;359 type OnTimestampSet = ();360 type MinimumPeriod = MinimumPeriod;361 type WeightInfo = ();362}363364parameter_types! {365 // pub const ExistentialDeposit: u128 = 500;366 pub const ExistentialDeposit: u128 = 0;367 pub const MaxLocks: u32 = 50;368}369370impl pallet_balances::Config for Runtime {371 type MaxLocks = MaxLocks;372 type MaxReserves = ();373 type ReserveIdentifier = [u8; 8];374 /// The type for recording an account's balance.375 type Balance = Balance;376 /// The ubiquitous event type.377 type Event = Event;378 type DustRemoval = Treasury;379 type ExistentialDeposit = ExistentialDeposit;380 type AccountStore = System;381 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;382}383384pub const MICROUNIQUE: Balance = 1_000_000_000;385pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;386pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;387pub const UNIQUE: Balance = 100 * CENTIUNIQUE;388389pub const fn deposit(items: u32, bytes: u32) -> Balance {390 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE391}392393/*394parameter_types! {395 pub TombstoneDeposit: Balance = deposit(396 1,397 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,398 );399 pub DepositPerContract: Balance = TombstoneDeposit::get();400 pub const DepositPerStorageByte: Balance = deposit(0, 1);401 pub const DepositPerStorageItem: Balance = deposit(1, 0);402 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);403 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;404 pub const SignedClaimHandicap: u32 = 2;405 pub const MaxDepth: u32 = 32;406 pub const MaxValueSize: u32 = 16 * 1024;407 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb408 // The lazy deletion runs inside on_initialize.409 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *410 RuntimeBlockWeights::get().max_block;411 // The weight needed for decoding the queue should be less or equal than a fifth412 // of the overall weight dedicated to the lazy deletion.413 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (414 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -415 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)416 )) / 5) as u32;417 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();418}419420impl pallet_contracts::Config for Runtime {421 type Time = Timestamp;422 type Randomness = RandomnessCollectiveFlip;423 type Currency = Balances;424 type Event = Event;425 type RentPayment = ();426 type SignedClaimHandicap = SignedClaimHandicap;427 type TombstoneDeposit = TombstoneDeposit;428 type DepositPerContract = DepositPerContract;429 type DepositPerStorageByte = DepositPerStorageByte;430 type DepositPerStorageItem = DepositPerStorageItem;431 type RentFraction = RentFraction;432 type SurchargeReward = SurchargeReward;433 type WeightPrice = pallet_transaction_payment::Pallet<Self>;434 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;435 type ChainExtension = NFTExtension;436 type DeletionQueueDepth = DeletionQueueDepth;437 type DeletionWeightLimit = DeletionWeightLimit;438 type Schedule = Schedule;439 type CallStack = [pallet_contracts::Frame<Self>; 31];440}441*/442443parameter_types! {444 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer445 /// This value increases the priority of `Operational` transactions by adding446 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.447 pub const OperationalFeeMultiplier: u8 = 5;448}449450/// Linear implementor of `WeightToFeePolynomial`451pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);452453impl<T> WeightToFeePolynomial for LinearFee<T>454where455 T: BaseArithmetic + From<u32> + Copy + Unsigned,456{457 type Balance = T;458459 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {460 smallvec!(WeightToFeeCoefficient {461 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer462 coeff_frac: Perbill::zero(),463 negative: false,464 degree: 1,465 })466 }467}468469impl pallet_transaction_payment::Config for Runtime {470 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;471 type TransactionByteFee = TransactionByteFee;472 type OperationalFeeMultiplier = OperationalFeeMultiplier;473 type WeightToFee = LinearFee<Balance>;474 type FeeMultiplierUpdate = ();475}476477parameter_types! {478 pub const ProposalBond: Permill = Permill::from_percent(5);479 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;480 pub const SpendPeriod: BlockNumber = 5 * MINUTES;481 pub const Burn: Permill = Permill::from_percent(0);482 pub const TipCountdown: BlockNumber = 1 * DAYS;483 pub const TipFindersFee: Percent = Percent::from_percent(20);484 pub const TipReportDepositBase: Balance = 1 * UNIQUE;485 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;486 pub const BountyDepositBase: Balance = 1 * UNIQUE;487 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;488 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");489 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;490 pub const MaximumReasonLength: u32 = 16384;491 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);492 pub const BountyValueMinimum: Balance = 5 * UNIQUE;493 pub const MaxApprovals: u32 = 100;494}495496impl pallet_treasury::Config for Runtime {497 type PalletId = TreasuryModuleId;498 type Currency = Balances;499 type ApproveOrigin = EnsureRoot<AccountId>;500 type RejectOrigin = EnsureRoot<AccountId>;501 type Event = Event;502 type OnSlash = ();503 type ProposalBond = ProposalBond;504 type ProposalBondMinimum = ProposalBondMinimum;505 type SpendPeriod = SpendPeriod;506 type Burn = Burn;507 type BurnDestination = ();508 type SpendFunds = ();509 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;510 type MaxApprovals = MaxApprovals;511}512513impl pallet_sudo::Config for Runtime {514 type Event = Event;515 type Call = Call;516}517518parameter_types! {519 pub const MinVestedTransfer: Balance = 10 * UNIQUE;520}521522impl pallet_vesting::Config for Runtime {523 type Event = Event;524 type Currency = Balances;525 type BlockNumberToBalance = ConvertInto;526 type MinVestedTransfer = MinVestedTransfer;527 type WeightInfo = ();528 const MAX_VESTING_SCHEDULES: u32 = 28;529}530531parameter_types! {532 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;533 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;534}535536impl cumulus_pallet_parachain_system::Config for Runtime {537 type Event = Event;538 type OnValidationData = ();539 type SelfParaId = parachain_info::Pallet<Self>;540 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<541 // MaxDownwardMessageWeight,542 // XcmExecutor<XcmConfig>,543 // Call,544 // >;545 type OutboundXcmpMessageSource = XcmpQueue;546 type DmpMessageHandler = DmpQueue;547 type ReservedDmpWeight = ReservedDmpWeight;548 type ReservedXcmpWeight = ReservedXcmpWeight;549 type XcmpMessageHandler = XcmpQueue;550}551552impl parachain_info::Config for Runtime {}553554impl cumulus_pallet_aura_ext::Config for Runtime {}555556parameter_types! {557 pub const RelayLocation: MultiLocation = MultiLocation::parent();558 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;559 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();560 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();561}562563/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used564/// when determining ownership of accounts for asset transacting and when attempting to use XCM565/// `Transact` in order to determine the dispatch Origin.566pub type LocationToAccountId = (567 // The parent (Relay-chain) origin converts to the default `AccountId`.568 ParentIsDefault<AccountId>,569 // Sibling parachain origins convert to AccountId via the `ParaId::into`.570 SiblingParachainConvertsVia<Sibling, AccountId>,571 // Straight up local `AccountId32` origins just alias directly to `AccountId`.572 AccountId32Aliases<RelayNetwork, AccountId>,573);574575/// Means for transacting assets on this chain.576pub type LocalAssetTransactor = CurrencyAdapter<577 // Use this currency:578 Balances,579 // Use this currency when it is a fungible asset matching the given location or name:580 IsConcrete<RelayLocation>,581 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:582 LocationToAccountId,583 // Our chain's account ID type (we can't get away without mentioning it explicitly):584 AccountId,585 // We don't track any teleports.586 (),587>;588589/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,590/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can591/// biases the kind of local `Origin` it will become.592pub type XcmOriginToTransactDispatchOrigin = (593 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location594 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for595 // foreign chains who want to have a local sovereign account on this chain which they control.596 SovereignSignedViaLocation<LocationToAccountId, Origin>,597 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when598 // recognised.599 RelayChainAsNative<RelayOrigin, Origin>,600 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when601 // recognised.602 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,603 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a604 // transaction from the Root origin.605 ParentAsSuperuser<Origin>,606 // Native signed account converter; this just converts an `AccountId32` origin into a normal607 // `Origin::Signed` origin of the same 32-byte value.608 SignedAccountId32AsNative<RelayNetwork, Origin>,609 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.610 XcmPassthrough<Origin>,611);612613parameter_types! {614 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.615 pub UnitWeightCost: Weight = 1_000_000;616 // 1200 UNIQUEs buy 1 second of weight.617 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);618 pub const MaxInstructions: u32 = 100;619 pub const MaxAuthorities: u32 = 100_000;620}621622match_type! {623 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {624 MultiLocation { parents: 1, interior: Here } |625 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }626 };627}628629pub type Barrier = (630 TakeWeightCredit,631 AllowTopLevelPaidExecutionFrom<Everything>,632 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,633 // ^^^ Parent & its unit plurality gets free execution634);635636pub struct XcmConfig;637impl Config for XcmConfig {638 type Call = Call;639 type XcmSender = XcmRouter;640 // How to withdraw and deposit an asset.641 type AssetTransactor = LocalAssetTransactor;642 type OriginConverter = XcmOriginToTransactDispatchOrigin;643 type IsReserve = NativeAsset;644 type IsTeleporter = (); // Teleportation is disabled645 type LocationInverter = LocationInverter<Ancestry>;646 type Barrier = Barrier;647 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;648 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;649 type ResponseHandler = (); // Don't handle responses for now.650 type SubscriptionService = PolkadotXcm;651652 type AssetTrap = PolkadotXcm;653 type AssetClaims = PolkadotXcm;654}655656// parameter_types! {657// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;658// }659660/// No local origins on this chain are allowed to dispatch XCM sends/executions.661pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);662663/// The means for routing XCM messages which are not for local execution into the right message664/// queues.665pub type XcmRouter = (666 // Two routers - use UMP to communicate with the relay chain:667 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,668 // ..and XCMP to communicate with the sibling chains.669 XcmpQueue,670);671672impl pallet_evm_coder_substrate::Config for Runtime {673 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;674}675676impl pallet_xcm::Config for Runtime {677 type Event = Event;678 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;679 type XcmRouter = XcmRouter;680 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;681 type XcmExecuteFilter = Everything;682 type XcmExecutor = XcmExecutor<XcmConfig>;683 type XcmTeleportFilter = Everything;684 type XcmReserveTransferFilter = Everything;685 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;686 type LocationInverter = LocationInverter<Ancestry>;687 type Origin = Origin;688 type Call = Call;689 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;690 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;691}692693impl cumulus_pallet_xcm::Config for Runtime {694 type Event = Event;695 type XcmExecutor = XcmExecutor<XcmConfig>;696}697698impl cumulus_pallet_xcmp_queue::Config for Runtime {699 type Event = Event;700 type XcmExecutor = XcmExecutor<XcmConfig>;701 type ChannelInfo = ParachainSystem;702 type VersionWrapper = ();703}704705impl cumulus_pallet_dmp_queue::Config for Runtime {706 type Event = Event;707 type XcmExecutor = XcmExecutor<XcmConfig>;708 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;709}710711impl pallet_aura::Config for Runtime {712 type AuthorityId = AuraId;713 type DisabledValidators = ();714 type MaxAuthorities = MaxAuthorities;715}716717parameter_types! {718 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();719 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;720}721722impl pallet_common::Config for Runtime {723 type Event = Event;724 type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;725 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;726 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;727728 type Currency = Balances;729 type CollectionCreationPrice = CollectionCreationPrice;730 type TreasuryAccountId = TreasuryAccountId;731}732733impl pallet_fungible::Config for Runtime {734 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;735}736impl pallet_refungible::Config for Runtime {737 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;738}739impl pallet_nonfungible::Config for Runtime {740 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;741}742743/// Used for the pallet nft in `./nft.rs`744impl pallet_nft::Config for Runtime {745 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;746}747748parameter_types! {749 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied750}751752/// Used for the pallet inflation753impl pallet_inflation::Config for Runtime {754 type Currency = Balances;755 type TreasuryAccountId = TreasuryAccountId;756 type InflationBlockInterval = InflationBlockInterval;757}758759parameter_types! {760 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *761 RuntimeBlockWeights::get().max_block;762 pub const MaxScheduledPerBlock: u32 = 50;763}764765pub struct Sponsoring;766impl SponsoringResolve<AccountId, Call> for Sponsoring {767 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>768 where769 Call: Dispatchable<Info = DispatchInfo>,770 AccountId: AsRef<[u8]>,771 {772 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)773 }774}775776type SponsorshipHandler = (777 pallet_nft::NftSponsorshipHandler<Runtime>,778 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,779);780781impl pallet_unq_scheduler::Config for Runtime {782 type Event = Event;783 type Origin = Origin;784 type PalletsOrigin = OriginCaller;785 type Call = Call;786 type MaximumWeight = MaximumSchedulerWeight;787 type ScheduleOrigin = EnsureSigned<AccountId>;788 type MaxScheduledPerBlock = MaxScheduledPerBlock;789 type SponsorshipHandler = SponsorshipHandler;790 type WeightInfo = ();791}792793impl pallet_nft_transaction_payment::Config for Runtime {794 type SponsorshipHandler = SponsorshipHandler;795}796797impl pallet_evm_transaction_payment::Config for Runtime {798 type SponsorshipHandler = (799 pallet_nft::NftEthSponsorshipHandler<Self>,800 pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,801 );802 type Currency = Balances;803}804805impl pallet_nft_charge_transaction::Config for Runtime {}806807// impl pallet_contract_helpers::Config for Runtime {808// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;809// }810811parameter_types! {812 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049813 pub const HelpersContractAddress: H160 = H160([814 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,815 ]);816}817818impl pallet_evm_contract_helpers::Config for Runtime {819 type ContractAddress = HelpersContractAddress;820 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;821}822823construct_runtime!(824 pub enum Runtime where825 Block = Block,826 NodeBlock = opaque::Block,827 UncheckedExtrinsic = UncheckedExtrinsic828 {829 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,830 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,831832 Aura: pallet_aura::{Pallet, Config<T>} = 22,833 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,834835 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,836 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,837 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,838 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,839 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,840 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,841 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,842 Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,843 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,844845 // XCM helpers.846 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,847 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,848 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,849 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,850851 // Unique Pallets852 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,853 Nft: pallet_nft::{Pallet, Call, Storage} = 61,854 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,855 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,856 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,857 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,858 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,859 Fungible: pallet_fungible::{Pallet, Storage} = 67,860 Refungible: pallet_refungible::{Pallet, Storage} = 68,861 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,862863 // Frontier864 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,865 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,866867 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,868 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,869 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,870 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,871 }872);873874pub struct TransactionConverter;875876impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {877 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {878 UncheckedExtrinsic::new_unsigned(879 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),880 )881 }882}883884impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {885 fn convert_transaction(886 &self,887 transaction: pallet_ethereum::Transaction,888 ) -> opaque::UncheckedExtrinsic {889 let extrinsic = UncheckedExtrinsic::new_unsigned(890 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),891 );892 let encoded = extrinsic.encode();893 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])894 .expect("Encoded extrinsic is always valid")895 }896}897898/// The address format for describing accounts.899pub type Address = sp_runtime::MultiAddress<AccountId, ()>;900/// Block header type as expected by this runtime.901pub type Header = generic::Header<BlockNumber, BlakeTwo256>;902/// Block type as expected by this runtime.903pub type Block = generic::Block<Header, UncheckedExtrinsic>;904/// A Block signed with a Justification905pub type SignedBlock = generic::SignedBlock<Block>;906/// BlockId type as expected by this runtime.907pub type BlockId = generic::BlockId<Block>;908/// The SignedExtension to the basic transaction logic.909pub type SignedExtra = (910 system::CheckSpecVersion<Runtime>,911 // system::CheckTxVersion<Runtime>,912 system::CheckGenesis<Runtime>,913 system::CheckEra<Runtime>,914 system::CheckNonce<Runtime>,915 system::CheckWeight<Runtime>,916 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,917 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,918);919/// Unchecked extrinsic type as expected by this runtime.920pub type UncheckedExtrinsic =921 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;922/// Extrinsic type that has already been checked.923pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;924/// Executive: handles dispatch to the various modules.925pub type Executive = frame_executive::Executive<926 Runtime,927 Block,928 frame_system::ChainContext<Runtime>,929 Runtime,930 AllPallets,931>;932933impl_opaque_keys! {934 pub struct SessionKeys {935 pub aura: Aura,936 }937}938939impl fp_self_contained::SelfContainedCall for Call {940 type SignedInfo = H160;941942 fn is_self_contained(&self) -> bool {943 match self {944 Call::Ethereum(call) => call.is_self_contained(),945 _ => false,946 }947 }948949 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {950 match self {951 Call::Ethereum(call) => call.check_self_contained(),952 _ => None,953 }954 }955956 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {957 match self {958 Call::Ethereum(call) => call.validate_self_contained(info),959 _ => None,960 }961 }962963 fn pre_dispatch_self_contained(964 &self,965 info: &Self::SignedInfo,966 ) -> Option<Result<(), TransactionValidityError>> {967 match self {968 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),969 _ => None,970 }971 }972973 fn apply_self_contained(974 self,975 info: Self::SignedInfo,976 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {977 match self {978 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(979 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),980 )),981 _ => None,982 }983 }984}985986macro_rules! dispatch_nft_runtime {987 ($collection:ident.$method:ident($($name:ident),*)) => {{988 use pallet_nft::dispatch::Dispatched;989990 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());991 let dispatch = collection.as_dyn();992993 dispatch.$method($($name),*)994 }};995}996impl_runtime_apis! {997 impl up_rpc::NftApi<Block, CrossAccountId, AccountId>998 for Runtime999 {1000 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1001 dispatch_nft_runtime!(collection.account_tokens(account))1002 }1003 fn token_exists(collection: CollectionId, token: TokenId) -> bool {1004 dispatch_nft_runtime!(collection.token_exists(token))1005 }10061007 fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1008 dispatch_nft_runtime!(collection.token_owner(token))1009 }1010 fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1011 dispatch_nft_runtime!(collection.const_metadata(token))1012 }1013 fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1014 dispatch_nft_runtime!(collection.variable_metadata(token))1015 }10161017 fn collection_tokens(collection: CollectionId) -> u32 {1018 dispatch_nft_runtime!(collection.collection_tokens())1019 }1020 fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1021 dispatch_nft_runtime!(collection.account_balance(account))1022 }1023 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1024 dispatch_nft_runtime!(collection.balance(account, token))1025 }1026 fn allowance(1027 collection: CollectionId,1028 sender: CrossAccountId,1029 spender: CrossAccountId,1030 token: TokenId,1031 ) -> u128 {1032 dispatch_nft_runtime!(collection.allowance(sender, spender, token))1033 }10341035 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1036 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account).or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account)).or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1037 }1038 fn adminlist(collection: CollectionId) -> Vec<AccountId> {1039 <pallet_nft::Pallet<Runtime>>::adminlist(collection)1040 }1041 fn allowlist(collection: CollectionId) -> Vec<AccountId> {1042 <pallet_nft::Pallet<Runtime>>::allowlist(collection)1043 }1044 fn last_token_id(collection: CollectionId) -> TokenId {1045 dispatch_nft_runtime!(collection.last_token_id())1046 }1047 }10481049 impl sp_api::Core<Block> for Runtime {1050 fn version() -> RuntimeVersion {1051 VERSION1052 }10531054 fn execute_block(block: Block) {1055 Executive::execute_block(block)1056 }10571058 fn initialize_block(header: &<Block as BlockT>::Header) {1059 Executive::initialize_block(header)1060 }1061 }10621063 impl sp_api::Metadata<Block> for Runtime {1064 fn metadata() -> OpaqueMetadata {1065 OpaqueMetadata::new(Runtime::metadata().into())1066 }1067 }10681069 impl sp_block_builder::BlockBuilder<Block> for Runtime {1070 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1071 Executive::apply_extrinsic(extrinsic)1072 }10731074 fn finalize_block() -> <Block as BlockT>::Header {1075 Executive::finalize_block()1076 }10771078 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1079 data.create_extrinsics()1080 }10811082 fn check_inherents(1083 block: Block,1084 data: sp_inherents::InherentData,1085 ) -> sp_inherents::CheckInherentsResult {1086 data.check_extrinsics(&block)1087 }10881089 // fn random_seed() -> <Block as BlockT>::Hash {1090 // RandomnessCollectiveFlip::random_seed().01091 // }1092 }10931094 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1095 fn validate_transaction(1096 source: TransactionSource,1097 tx: <Block as BlockT>::Extrinsic,1098 hash: <Block as BlockT>::Hash,1099 ) -> TransactionValidity {1100 Executive::validate_transaction(source, tx, hash)1101 }1102 }11031104 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1105 fn offchain_worker(header: &<Block as BlockT>::Header) {1106 Executive::offchain_worker(header)1107 }1108 }11091110 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1111 fn chain_id() -> u64 {1112 <Runtime as pallet_evm::Config>::ChainId::get()1113 }11141115 fn account_basic(address: H160) -> EVMAccount {1116 EVM::account_basic(&address)1117 }11181119 fn gas_price() -> U256 {1120 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1121 }11221123 fn account_code_at(address: H160) -> Vec<u8> {1124 EVM::account_codes(address)1125 }11261127 fn author() -> H160 {1128 <pallet_evm::Pallet<Runtime>>::find_author()1129 }11301131 fn storage_at(address: H160, index: U256) -> H256 {1132 let mut tmp = [0u8; 32];1133 index.to_big_endian(&mut tmp);1134 EVM::account_storages(address, H256::from_slice(&tmp[..]))1135 }11361137 fn call(1138 from: H160,1139 to: H160,1140 data: Vec<u8>,1141 value: U256,1142 gas_limit: U256,1143 gas_price: Option<U256>,1144 nonce: Option<U256>,1145 estimate: bool,1146 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1147 let config = if estimate {1148 let mut config = <Runtime as pallet_evm::Config>::config().clone();1149 config.estimate = true;1150 Some(config)1151 } else {1152 None1153 };11541155 <Runtime as pallet_evm::Config>::Runner::call(1156 from,1157 to,1158 data,1159 value,1160 gas_limit.low_u64(),1161 gas_price,1162 nonce,1163 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1164 ).map_err(|err| err.into())1165 }11661167 fn create(1168 from: H160,1169 data: Vec<u8>,1170 value: U256,1171 gas_limit: U256,1172 gas_price: Option<U256>,1173 nonce: Option<U256>,1174 estimate: bool,1175 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1176 let config = if estimate {1177 let mut config = <Runtime as pallet_evm::Config>::config().clone();1178 config.estimate = true;1179 Some(config)1180 } else {1181 None1182 };11831184 <Runtime as pallet_evm::Config>::Runner::create(1185 from,1186 data,1187 value,1188 gas_limit.low_u64(),1189 gas_price,1190 nonce,1191 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1192 ).map_err(|err| err.into())1193 }11941195 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1196 Ethereum::current_transaction_statuses()1197 }11981199 fn current_block() -> Option<pallet_ethereum::Block> {1200 Ethereum::current_block()1201 }12021203 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1204 Ethereum::current_receipts()1205 }12061207 fn current_all() -> (1208 Option<pallet_ethereum::Block>,1209 Option<Vec<pallet_ethereum::Receipt>>,1210 Option<Vec<TransactionStatus>>1211 ) {1212 (1213 Ethereum::current_block(),1214 Ethereum::current_receipts(),1215 Ethereum::current_transaction_statuses()1216 )1217 }12181219 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1220 xts.into_iter().filter_map(|xt| match xt.0.function {1221 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1222 _ => None1223 }).collect()1224 }1225 }12261227 impl sp_session::SessionKeys<Block> for Runtime {1228 fn decode_session_keys(1229 encoded: Vec<u8>,1230 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1231 SessionKeys::decode_into_raw_public_keys(&encoded)1232 }12331234 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1235 SessionKeys::generate(seed)1236 }1237 }12381239 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1240 fn slot_duration() -> sp_consensus_aura::SlotDuration {1241 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1242 }12431244 fn authorities() -> Vec<AuraId> {1245 Aura::authorities().to_vec()1246 }1247 }12481249 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1250 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1251 ParachainSystem::collect_collation_info()1252 }1253 }12541255 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1256 fn account_nonce(account: AccountId) -> Index {1257 System::account_nonce(account)1258 }1259 }12601261 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1262 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1263 TransactionPayment::query_info(uxt, len)1264 }1265 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1266 TransactionPayment::query_fee_details(uxt, len)1267 }1268 }12691270 /*1271 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1272 for Runtime1273 {1274 fn call(1275 origin: AccountId,1276 dest: AccountId,1277 value: Balance,1278 gas_limit: u64,1279 input_data: Vec<u8>,1280 ) -> pallet_contracts_primitives::ContractExecResult {1281 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1282 }12831284 fn instantiate(1285 origin: AccountId,1286 endowment: Balance,1287 gas_limit: u64,1288 code: pallet_contracts_primitives::Code<Hash>,1289 data: Vec<u8>,1290 salt: Vec<u8>,1291 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1292 {1293 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1294 }12951296 fn get_storage(1297 address: AccountId,1298 key: [u8; 32],1299 ) -> pallet_contracts_primitives::GetStorageResult {1300 Contracts::get_storage(address, key)1301 }13021303 fn rent_projection(1304 address: AccountId,1305 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1306 Contracts::rent_projection(address)1307 }1308 }1309 */13101311 #[cfg(feature = "runtime-benchmarks")]1312 impl frame_benchmarking::Benchmark<Block> for Runtime {1313 fn benchmark_metadata(extra: bool) -> (1314 Vec<frame_benchmarking::BenchmarkList>,1315 Vec<frame_support::traits::StorageInfo>,1316 ) {1317 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1318 use frame_support::traits::StorageInfoTrait;13191320 let mut list = Vec::<BenchmarkList>::new();13211322 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1323 list_benchmark!(list, extra, pallet_nft, Nft);1324 list_benchmark!(list, extra, pallet_inflation, Inflation);1325 list_benchmark!(list, extra, pallet_fungible, Fungible);1326 list_benchmark!(list, extra, pallet_refungible, Refungible);1327 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);13281329 let storage_info = AllPalletsWithSystem::storage_info();13301331 return (list, storage_info)1332 }13331334 fn dispatch_benchmark(1335 config: frame_benchmarking::BenchmarkConfig1336 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1337 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13381339 let whitelist: Vec<TrackedStorageKey> = vec![1340 // Block Number1341 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1342 // Total Issuance1343 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1344 // Execution Phase1345 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1346 // Event Count1347 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1348 // System Events1349 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1350 ];13511352 let mut batches = Vec::<BenchmarkBatch>::new();1353 let params = (&config, &whitelist);13541355 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1356 add_benchmark!(params, batches, pallet_nft, Nft);1357 add_benchmark!(params, batches, pallet_inflation, Inflation);1358 add_benchmark!(params, batches, pallet_fungible, Fungible);1359 add_benchmark!(params, batches, pallet_refungible, Refungible);1360 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);13611362 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1363 Ok(batches)1364 }1365 }1366}13671368struct CheckInherents;13691370impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1371 fn check_inherents(1372 block: &Block,1373 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1374 ) -> sp_inherents::CheckInherentsResult {1375 let relay_chain_slot = relay_state_proof1376 .read_slot()1377 .expect("Could not read the relay chain slot from the proof");13781379 let inherent_data =1380 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1381 relay_chain_slot,1382 sp_std::time::Duration::from_secs(6),1383 )1384 .create_inherent_data()1385 .expect("Could not create the timestamp inherent data");13861387 inherent_data.check_extrinsics(block)1388 }1389}13901391cumulus_pallet_parachain_system::register_validate_block!(1392 Runtime = Runtime,1393 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1394 CheckInherents = CheckInherents,1395);1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,26 AccountIdConversion,27 },28 transaction_validity::{TransactionSource, TransactionValidity},29 ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};40// A few exports that help ease life for downstream crates.41pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44 construct_runtime, match_type,45 dispatch::DispatchResult,46 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 traits::{48 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50 },51 weights::{52 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55 },56};57use nft_data_structs::*;58// use pallet_contracts::weights::WeightInfo;59// #[cfg(any(feature = "std", test))]60use frame_system::{61 self as system, EnsureRoot, EnsureSigned,62 limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{65 traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73 traits::{Dispatchable, PostDispatchInfoOf},74 transaction_validity::TransactionValidityError,75};7677// pub use pallet_timestamp::Call as TimestampCall;78pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7980// Polkadot imports81use pallet_xcm::XcmPassthrough;82use polkadot_parachain::primitives::Sibling;83use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};84use xcm_builder::{85 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,86 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,87 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,88 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,89 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,90};91use xcm_executor::{Config, XcmExecutor};9293// mod chain_extension;94// use crate::chain_extension::{NFTExtension, Imbalance};9596/// An index to a block.97pub type BlockNumber = u32;9899/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.100pub type Signature = MultiSignature;101102/// Some way of identifying an account on the chain. We intentionally make it equivalent103/// to the public key of our transaction signing scheme.104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;105106pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;107108/// The type for looking up accounts. We don't expect more than 4 billion of them, but you109/// never know...110pub type AccountIndex = u32;111112/// Balance of an account.113pub type Balance = u128;114115/// Index of a transaction in the chain.116pub type Index = u32;117118/// A hash of some data used by the chain.119pub type Hash = sp_core::H256;120121/// Digest item type.122pub type DigestItem = generic::DigestItem<Hash>;123124/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know125/// the specifics of the runtime. They can then be made to be agnostic over specific formats126/// of data like extrinsics, allowing for them to continue syncing the network through upgrades127/// to even the core data structures.128pub mod opaque {129 use super::*;130131 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;132133 /// Opaque block type.134 pub type Block = generic::Block<Header, UncheckedExtrinsic>;135136 pub type SessionHandlers = ();137138 impl_opaque_keys! {139 pub struct SessionKeys {140 pub aura: Aura,141 }142 }143}144145/// This runtime version.146pub const VERSION: RuntimeVersion = RuntimeVersion {147 spec_name: create_runtime_str!("opal"),148 impl_name: create_runtime_str!("opal"),149 authoring_version: 1,150 spec_version: 912200,151 impl_version: 1,152 apis: RUNTIME_API_VERSIONS,153 transaction_version: 1,154};155156pub const MILLISECS_PER_BLOCK: u64 = 12000;157158pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;159160// These time units are defined in number of blocks.161pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);162pub const HOURS: BlockNumber = MINUTES * 60;163pub const DAYS: BlockNumber = HOURS * 24;164165parameter_types! {166 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;167}168169#[derive(codec::Encode, codec::Decode)]170pub enum XCMPMessage<XAccountId, XBalance> {171 /// Transfer tokens to the given account from the Parachain account.172 TransferToken(XAccountId, XBalance),173}174175/// The version information used to identify this runtime when compiled natively.176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178 NativeVersion {179 runtime_version: VERSION,180 can_author_with: Default::default(),181 }182}183184type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;185186pub struct DealWithFees;187impl OnUnbalanced<NegativeImbalance> for DealWithFees {188 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {189 if let Some(fees) = fees_then_tips.next() {190 // for fees, 100% to treasury191 let mut split = fees.ration(100, 0);192 if let Some(tips) = fees_then_tips.next() {193 // for tips, if any, 100% to treasury194 tips.ration_merge_into(100, 0, &mut split);195 }196 Treasury::on_unbalanced(split.0);197 // Author::on_unbalanced(split.1);198 }199 }200}201202/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.203/// This is used to limit the maximal weight of a single extrinsic.204const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);205/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used206/// by Operational extrinsics.207const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);208/// We allow for 2 seconds of compute with a 6 second average block time.209const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;210211parameter_types! {212 pub const BlockHashCount: BlockNumber = 2400;213 pub RuntimeBlockLength: BlockLength =214 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);215 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);216 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;217 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()218 .base_block(BlockExecutionWeight::get())219 .for_class(DispatchClass::all(), |weights| {220 weights.base_extrinsic = ExtrinsicBaseWeight::get();221 })222 .for_class(DispatchClass::Normal, |weights| {223 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);224 })225 .for_class(DispatchClass::Operational, |weights| {226 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);227 // Operational transactions have some extra reserved space, so that they228 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.229 weights.reserved = Some(230 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT231 );232 })233 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)234 .build_or_panic();235 pub const Version: RuntimeVersion = VERSION;236 pub const SS58Prefix: u8 = 42;237}238239parameter_types! {240 pub const ChainId: u64 = 8888;241}242243pub struct FixedFee;244impl FeeCalculator for FixedFee {245 fn min_gas_price() -> U256 {246 1.into()247 }248}249250impl pallet_evm::Config for Runtime {251 type BlockGasLimit = BlockGasLimit;252 type FeeCalculator = FixedFee;253 type GasWeightMapping = ();254 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;255 type CallOrigin = EnsureAddressTruncated;256 type WithdrawOrigin = EnsureAddressTruncated;257 type AddressMapping = HashedAddressMapping<Self::Hashing>;258 type Precompiles = ();259 type Currency = Balances;260 type Event = Event;261 type OnMethodCall = (262 pallet_evm_migration::OnMethodCall<Self>,263 pallet_nft::NftErcSupport<Self>,264 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,265 );266 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;267 type ChainId = ChainId;268 type Runner = pallet_evm::runner::stack::Runner<Self>;269 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;270 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;271 type FindAuthor = EthereumFindAuthor<Aura>;272}273274impl pallet_evm_migration::Config for Runtime {275 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;276}277278pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);279impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {280 fn find_author<'a, I>(digests: I) -> Option<H160>281 where282 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,283 {284 if let Some(author_index) = F::find_author(digests) {285 let authority_id = Aura::authorities()[author_index as usize].clone();286 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));287 }288 None289 }290}291292parameter_types! {293 pub BlockGasLimit: U256 = U256::from(u32::max_value());294}295296impl pallet_ethereum::Config for Runtime {297 type Event = Event;298 type StateRoot = pallet_ethereum::IntermediateStateRoot;299 type EvmSubmitLog = pallet_evm::Pallet<Self>;300}301302impl pallet_randomness_collective_flip::Config for Runtime {}303304impl system::Config for Runtime {305 /// The data to be stored in an account.306 type AccountData = pallet_balances::AccountData<Balance>;307 /// The identifier used to distinguish between accounts.308 type AccountId = AccountId;309 /// The basic call filter to use in dispatchable.310 type BaseCallFilter = Everything;311 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).312 type BlockHashCount = BlockHashCount;313 /// The maximum length of a block (in bytes).314 type BlockLength = RuntimeBlockLength;315 /// The index type for blocks.316 type BlockNumber = BlockNumber;317 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.318 type BlockWeights = RuntimeBlockWeights;319 /// The aggregated dispatch type that is available for extrinsics.320 type Call = Call;321 /// The weight of database operations that the runtime can invoke.322 type DbWeight = RocksDbWeight;323 /// The ubiquitous event type.324 type Event = Event;325 /// The type for hashing blocks and tries.326 type Hash = Hash;327 /// The hashing algorithm used.328 type Hashing = BlakeTwo256;329 /// The header type.330 type Header = generic::Header<BlockNumber, BlakeTwo256>;331 /// The index type for storing how many extrinsics an account has signed.332 type Index = Index;333 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.334 type Lookup = AccountIdLookup<AccountId, ()>;335 /// What to do if an account is fully reaped from the system.336 type OnKilledAccount = ();337 /// What to do if a new account is created.338 type OnNewAccount = ();339 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;340 /// The ubiquitous origin type.341 type Origin = Origin;342 /// This type is being generated by `construct_runtime!`.343 type PalletInfo = PalletInfo;344 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.345 type SS58Prefix = SS58Prefix;346 /// Weight information for the extrinsics of this pallet.347 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;348 /// Version of the runtime.349 type Version = Version;350}351352parameter_types! {353 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;354}355356impl pallet_timestamp::Config for Runtime {357 /// A timestamp: milliseconds since the unix epoch.358 type Moment = u64;359 type OnTimestampSet = ();360 type MinimumPeriod = MinimumPeriod;361 type WeightInfo = ();362}363364parameter_types! {365 // pub const ExistentialDeposit: u128 = 500;366 pub const ExistentialDeposit: u128 = 0;367 pub const MaxLocks: u32 = 50;368}369370impl pallet_balances::Config for Runtime {371 type MaxLocks = MaxLocks;372 type MaxReserves = ();373 type ReserveIdentifier = [u8; 8];374 /// The type for recording an account's balance.375 type Balance = Balance;376 /// The ubiquitous event type.377 type Event = Event;378 type DustRemoval = Treasury;379 type ExistentialDeposit = ExistentialDeposit;380 type AccountStore = System;381 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;382}383384pub const MICROUNIQUE: Balance = 1_000_000_000;385pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;386pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;387pub const UNIQUE: Balance = 100 * CENTIUNIQUE;388389pub const fn deposit(items: u32, bytes: u32) -> Balance {390 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE391}392393/*394parameter_types! {395 pub TombstoneDeposit: Balance = deposit(396 1,397 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,398 );399 pub DepositPerContract: Balance = TombstoneDeposit::get();400 pub const DepositPerStorageByte: Balance = deposit(0, 1);401 pub const DepositPerStorageItem: Balance = deposit(1, 0);402 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);403 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;404 pub const SignedClaimHandicap: u32 = 2;405 pub const MaxDepth: u32 = 32;406 pub const MaxValueSize: u32 = 16 * 1024;407 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb408 // The lazy deletion runs inside on_initialize.409 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *410 RuntimeBlockWeights::get().max_block;411 // The weight needed for decoding the queue should be less or equal than a fifth412 // of the overall weight dedicated to the lazy deletion.413 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (414 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -415 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)416 )) / 5) as u32;417 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();418}419420impl pallet_contracts::Config for Runtime {421 type Time = Timestamp;422 type Randomness = RandomnessCollectiveFlip;423 type Currency = Balances;424 type Event = Event;425 type RentPayment = ();426 type SignedClaimHandicap = SignedClaimHandicap;427 type TombstoneDeposit = TombstoneDeposit;428 type DepositPerContract = DepositPerContract;429 type DepositPerStorageByte = DepositPerStorageByte;430 type DepositPerStorageItem = DepositPerStorageItem;431 type RentFraction = RentFraction;432 type SurchargeReward = SurchargeReward;433 type WeightPrice = pallet_transaction_payment::Pallet<Self>;434 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;435 type ChainExtension = NFTExtension;436 type DeletionQueueDepth = DeletionQueueDepth;437 type DeletionWeightLimit = DeletionWeightLimit;438 type Schedule = Schedule;439 type CallStack = [pallet_contracts::Frame<Self>; 31];440}441*/442443parameter_types! {444 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer445 /// This value increases the priority of `Operational` transactions by adding446 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.447 pub const OperationalFeeMultiplier: u8 = 5;448}449450/// Linear implementor of `WeightToFeePolynomial`451pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);452453impl<T> WeightToFeePolynomial for LinearFee<T>454where455 T: BaseArithmetic + From<u32> + Copy + Unsigned,456{457 type Balance = T;458459 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {460 smallvec!(WeightToFeeCoefficient {461 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer462 coeff_frac: Perbill::zero(),463 negative: false,464 degree: 1,465 })466 }467}468469impl pallet_transaction_payment::Config for Runtime {470 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;471 type TransactionByteFee = TransactionByteFee;472 type OperationalFeeMultiplier = OperationalFeeMultiplier;473 type WeightToFee = LinearFee<Balance>;474 type FeeMultiplierUpdate = ();475}476477parameter_types! {478 pub const ProposalBond: Permill = Permill::from_percent(5);479 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;480 pub const SpendPeriod: BlockNumber = 5 * MINUTES;481 pub const Burn: Permill = Permill::from_percent(0);482 pub const TipCountdown: BlockNumber = 1 * DAYS;483 pub const TipFindersFee: Percent = Percent::from_percent(20);484 pub const TipReportDepositBase: Balance = 1 * UNIQUE;485 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;486 pub const BountyDepositBase: Balance = 1 * UNIQUE;487 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;488 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");489 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;490 pub const MaximumReasonLength: u32 = 16384;491 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);492 pub const BountyValueMinimum: Balance = 5 * UNIQUE;493 pub const MaxApprovals: u32 = 100;494}495496impl pallet_treasury::Config for Runtime {497 type PalletId = TreasuryModuleId;498 type Currency = Balances;499 type ApproveOrigin = EnsureRoot<AccountId>;500 type RejectOrigin = EnsureRoot<AccountId>;501 type Event = Event;502 type OnSlash = ();503 type ProposalBond = ProposalBond;504 type ProposalBondMinimum = ProposalBondMinimum;505 type SpendPeriod = SpendPeriod;506 type Burn = Burn;507 type BurnDestination = ();508 type SpendFunds = ();509 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;510 type MaxApprovals = MaxApprovals;511}512513impl pallet_sudo::Config for Runtime {514 type Event = Event;515 type Call = Call;516}517518parameter_types! {519 pub const MinVestedTransfer: Balance = 10 * UNIQUE;520}521522impl pallet_vesting::Config for Runtime {523 type Event = Event;524 type Currency = Balances;525 type BlockNumberToBalance = ConvertInto;526 type MinVestedTransfer = MinVestedTransfer;527 type WeightInfo = ();528 const MAX_VESTING_SCHEDULES: u32 = 28;529}530531parameter_types! {532 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;533 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;534}535536impl cumulus_pallet_parachain_system::Config for Runtime {537 type Event = Event;538 type OnValidationData = ();539 type SelfParaId = parachain_info::Pallet<Self>;540 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<541 // MaxDownwardMessageWeight,542 // XcmExecutor<XcmConfig>,543 // Call,544 // >;545 type OutboundXcmpMessageSource = XcmpQueue;546 type DmpMessageHandler = DmpQueue;547 type ReservedDmpWeight = ReservedDmpWeight;548 type ReservedXcmpWeight = ReservedXcmpWeight;549 type XcmpMessageHandler = XcmpQueue;550}551552impl parachain_info::Config for Runtime {}553554impl cumulus_pallet_aura_ext::Config for Runtime {}555556parameter_types! {557 pub const RelayLocation: MultiLocation = MultiLocation::parent();558 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;559 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();560 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();561}562563/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used564/// when determining ownership of accounts for asset transacting and when attempting to use XCM565/// `Transact` in order to determine the dispatch Origin.566pub type LocationToAccountId = (567 // The parent (Relay-chain) origin converts to the default `AccountId`.568 ParentIsDefault<AccountId>,569 // Sibling parachain origins convert to AccountId via the `ParaId::into`.570 SiblingParachainConvertsVia<Sibling, AccountId>,571 // Straight up local `AccountId32` origins just alias directly to `AccountId`.572 AccountId32Aliases<RelayNetwork, AccountId>,573);574575/// Means for transacting assets on this chain.576pub type LocalAssetTransactor = CurrencyAdapter<577 // Use this currency:578 Balances,579 // Use this currency when it is a fungible asset matching the given location or name:580 IsConcrete<RelayLocation>,581 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:582 LocationToAccountId,583 // Our chain's account ID type (we can't get away without mentioning it explicitly):584 AccountId,585 // We don't track any teleports.586 (),587>;588589/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,590/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can591/// biases the kind of local `Origin` it will become.592pub type XcmOriginToTransactDispatchOrigin = (593 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location594 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for595 // foreign chains who want to have a local sovereign account on this chain which they control.596 SovereignSignedViaLocation<LocationToAccountId, Origin>,597 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when598 // recognised.599 RelayChainAsNative<RelayOrigin, Origin>,600 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when601 // recognised.602 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,603 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a604 // transaction from the Root origin.605 ParentAsSuperuser<Origin>,606 // Native signed account converter; this just converts an `AccountId32` origin into a normal607 // `Origin::Signed` origin of the same 32-byte value.608 SignedAccountId32AsNative<RelayNetwork, Origin>,609 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.610 XcmPassthrough<Origin>,611);612613parameter_types! {614 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.615 pub UnitWeightCost: Weight = 1_000_000;616 // 1200 UNIQUEs buy 1 second of weight.617 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);618 pub const MaxInstructions: u32 = 100;619 pub const MaxAuthorities: u32 = 100_000;620}621622match_type! {623 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {624 MultiLocation { parents: 1, interior: Here } |625 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }626 };627}628629pub type Barrier = (630 TakeWeightCredit,631 AllowTopLevelPaidExecutionFrom<Everything>,632 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,633 // ^^^ Parent & its unit plurality gets free execution634);635636pub struct XcmConfig;637impl Config for XcmConfig {638 type Call = Call;639 type XcmSender = XcmRouter;640 // How to withdraw and deposit an asset.641 type AssetTransactor = LocalAssetTransactor;642 type OriginConverter = XcmOriginToTransactDispatchOrigin;643 type IsReserve = NativeAsset;644 type IsTeleporter = (); // Teleportation is disabled645 type LocationInverter = LocationInverter<Ancestry>;646 type Barrier = Barrier;647 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;648 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;649 type ResponseHandler = (); // Don't handle responses for now.650 type SubscriptionService = PolkadotXcm;651652 type AssetTrap = PolkadotXcm;653 type AssetClaims = PolkadotXcm;654}655656// parameter_types! {657// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;658// }659660/// No local origins on this chain are allowed to dispatch XCM sends/executions.661pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);662663/// The means for routing XCM messages which are not for local execution into the right message664/// queues.665pub type XcmRouter = (666 // Two routers - use UMP to communicate with the relay chain:667 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,668 // ..and XCMP to communicate with the sibling chains.669 XcmpQueue,670);671672impl pallet_evm_coder_substrate::Config for Runtime {673 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;674}675676impl pallet_xcm::Config for Runtime {677 type Event = Event;678 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;679 type XcmRouter = XcmRouter;680 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;681 type XcmExecuteFilter = Everything;682 type XcmExecutor = XcmExecutor<XcmConfig>;683 type XcmTeleportFilter = Everything;684 type XcmReserveTransferFilter = Everything;685 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;686 type LocationInverter = LocationInverter<Ancestry>;687 type Origin = Origin;688 type Call = Call;689 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;690 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;691}692693impl cumulus_pallet_xcm::Config for Runtime {694 type Event = Event;695 type XcmExecutor = XcmExecutor<XcmConfig>;696}697698impl cumulus_pallet_xcmp_queue::Config for Runtime {699 type Event = Event;700 type XcmExecutor = XcmExecutor<XcmConfig>;701 type ChannelInfo = ParachainSystem;702 type VersionWrapper = ();703}704705impl cumulus_pallet_dmp_queue::Config for Runtime {706 type Event = Event;707 type XcmExecutor = XcmExecutor<XcmConfig>;708 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;709}710711impl pallet_aura::Config for Runtime {712 type AuthorityId = AuraId;713 type DisabledValidators = ();714 type MaxAuthorities = MaxAuthorities;715}716717parameter_types! {718 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();719 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;720}721722impl pallet_common::Config for Runtime {723 type Event = Event;724 type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;725 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;726 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;727728 type Currency = Balances;729 type CollectionCreationPrice = CollectionCreationPrice;730 type TreasuryAccountId = TreasuryAccountId;731}732733impl pallet_fungible::Config for Runtime {734 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;735}736impl pallet_refungible::Config for Runtime {737 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;738}739impl pallet_nonfungible::Config for Runtime {740 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;741}742743/// Used for the pallet nft in `./nft.rs`744impl pallet_nft::Config for Runtime {745 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;746}747748parameter_types! {749 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied750}751752/// Used for the pallet inflation753impl pallet_inflation::Config for Runtime {754 type Currency = Balances;755 type TreasuryAccountId = TreasuryAccountId;756 type InflationBlockInterval = InflationBlockInterval;757}758759parameter_types! {760 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *761 RuntimeBlockWeights::get().max_block;762 pub const MaxScheduledPerBlock: u32 = 50;763}764765pub struct Sponsoring;766impl SponsoringResolve<AccountId, Call> for Sponsoring {767 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>768 where769 Call: Dispatchable<Info = DispatchInfo>,770 AccountId: AsRef<[u8]>,771 {772 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)773 }774}775776type SponsorshipHandler = (777 pallet_nft::NftSponsorshipHandler<Runtime>,778 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,779);780781impl pallet_unq_scheduler::Config for Runtime {782 type Event = Event;783 type Origin = Origin;784 type PalletsOrigin = OriginCaller;785 type Call = Call;786 type MaximumWeight = MaximumSchedulerWeight;787 type ScheduleOrigin = EnsureSigned<AccountId>;788 type MaxScheduledPerBlock = MaxScheduledPerBlock;789 type SponsorshipHandler = SponsorshipHandler;790 type WeightInfo = ();791}792793impl pallet_nft_transaction_payment::Config for Runtime {794 type SponsorshipHandler = SponsorshipHandler;795}796797impl pallet_evm_transaction_payment::Config for Runtime {798 type SponsorshipHandler = (799 pallet_nft::NftEthSponsorshipHandler<Self>,800 pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,801 );802 type Currency = Balances;803}804805impl pallet_nft_charge_transaction::Config for Runtime {}806807// impl pallet_contract_helpers::Config for Runtime {808// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;809// }810811parameter_types! {812 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049813 pub const HelpersContractAddress: H160 = H160([814 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,815 ]);816}817818impl pallet_evm_contract_helpers::Config for Runtime {819 type ContractAddress = HelpersContractAddress;820 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;821}822823construct_runtime!(824 pub enum Runtime where825 Block = Block,826 NodeBlock = opaque::Block,827 UncheckedExtrinsic = UncheckedExtrinsic828 {829 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,830 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,831832 Aura: pallet_aura::{Pallet, Config<T>} = 22,833 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,834835 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,836 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,837 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,838 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,839 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,840 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,841 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,842 Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,843 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,844845 // XCM helpers.846 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,847 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,848 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,849 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,850851 // Unique Pallets852 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,853 Nft: pallet_nft::{Pallet, Call, Storage} = 61,854 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,855 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,856 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,857 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,858 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,859 Fungible: pallet_fungible::{Pallet, Storage} = 67,860 Refungible: pallet_refungible::{Pallet, Storage} = 68,861 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,862863 // Frontier864 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,865 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,866867 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,868 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,869 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,870 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,871 }872);873874pub struct TransactionConverter;875876impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {877 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {878 UncheckedExtrinsic::new_unsigned(879 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),880 )881 }882}883884impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {885 fn convert_transaction(886 &self,887 transaction: pallet_ethereum::Transaction,888 ) -> opaque::UncheckedExtrinsic {889 let extrinsic = UncheckedExtrinsic::new_unsigned(890 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),891 );892 let encoded = extrinsic.encode();893 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])894 .expect("Encoded extrinsic is always valid")895 }896}897898/// The address format for describing accounts.899pub type Address = sp_runtime::MultiAddress<AccountId, ()>;900/// Block header type as expected by this runtime.901pub type Header = generic::Header<BlockNumber, BlakeTwo256>;902/// Block type as expected by this runtime.903pub type Block = generic::Block<Header, UncheckedExtrinsic>;904/// A Block signed with a Justification905pub type SignedBlock = generic::SignedBlock<Block>;906/// BlockId type as expected by this runtime.907pub type BlockId = generic::BlockId<Block>;908/// The SignedExtension to the basic transaction logic.909pub type SignedExtra = (910 system::CheckSpecVersion<Runtime>,911 // system::CheckTxVersion<Runtime>,912 system::CheckGenesis<Runtime>,913 system::CheckEra<Runtime>,914 system::CheckNonce<Runtime>,915 system::CheckWeight<Runtime>,916 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,917 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,918);919/// Unchecked extrinsic type as expected by this runtime.920pub type UncheckedExtrinsic =921 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;922/// Extrinsic type that has already been checked.923pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;924/// Executive: handles dispatch to the various modules.925pub type Executive = frame_executive::Executive<926 Runtime,927 Block,928 frame_system::ChainContext<Runtime>,929 Runtime,930 AllPallets,931>;932933impl_opaque_keys! {934 pub struct SessionKeys {935 pub aura: Aura,936 }937}938939impl fp_self_contained::SelfContainedCall for Call {940 type SignedInfo = H160;941942 fn is_self_contained(&self) -> bool {943 match self {944 Call::Ethereum(call) => call.is_self_contained(),945 _ => false,946 }947 }948949 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {950 match self {951 Call::Ethereum(call) => call.check_self_contained(),952 _ => None,953 }954 }955956 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {957 match self {958 Call::Ethereum(call) => call.validate_self_contained(info),959 _ => None,960 }961 }962963 fn pre_dispatch_self_contained(964 &self,965 info: &Self::SignedInfo,966 ) -> Option<Result<(), TransactionValidityError>> {967 match self {968 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),969 _ => None,970 }971 }972973 fn apply_self_contained(974 self,975 info: Self::SignedInfo,976 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {977 match self {978 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(979 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),980 )),981 _ => None,982 }983 }984}985986macro_rules! dispatch_nft_runtime {987 ($collection:ident.$method:ident($($name:ident),*)) => {{988 use pallet_nft::dispatch::Dispatched;989990 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());991 let dispatch = collection.as_dyn();992993 dispatch.$method($($name),*)994 }};995}996impl_runtime_apis! {997 impl up_rpc::NftApi<Block, CrossAccountId, AccountId>998 for Runtime999 {1000 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1001 dispatch_nft_runtime!(collection.account_tokens(account))1002 }1003 fn token_exists(collection: CollectionId, token: TokenId) -> bool {1004 dispatch_nft_runtime!(collection.token_exists(token))1005 }10061007 fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1008 dispatch_nft_runtime!(collection.token_owner(token))1009 }1010 fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1011 dispatch_nft_runtime!(collection.const_metadata(token))1012 }1013 fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1014 dispatch_nft_runtime!(collection.variable_metadata(token))1015 }10161017 fn collection_tokens(collection: CollectionId) -> u32 {1018 dispatch_nft_runtime!(collection.collection_tokens())1019 }1020 fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1021 dispatch_nft_runtime!(collection.account_balance(account))1022 }1023 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1024 dispatch_nft_runtime!(collection.balance(account, token))1025 }1026 fn allowance(1027 collection: CollectionId,1028 sender: CrossAccountId,1029 spender: CrossAccountId,1030 token: TokenId,1031 ) -> u128 {1032 dispatch_nft_runtime!(collection.allowance(sender, spender, token))1033 }10341035 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1036 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account)1037 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1038 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1039 }1040 fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1041 <pallet_nft::Pallet<Runtime>>::adminlist(collection)1042 }1043 fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1044 <pallet_nft::Pallet<Runtime>>::allowlist(collection)1045 }1046 fn last_token_id(collection: CollectionId) -> TokenId {1047 dispatch_nft_runtime!(collection.last_token_id())1048 }1049 }10501051 impl sp_api::Core<Block> for Runtime {1052 fn version() -> RuntimeVersion {1053 VERSION1054 }10551056 fn execute_block(block: Block) {1057 Executive::execute_block(block)1058 }10591060 fn initialize_block(header: &<Block as BlockT>::Header) {1061 Executive::initialize_block(header)1062 }1063 }10641065 impl sp_api::Metadata<Block> for Runtime {1066 fn metadata() -> OpaqueMetadata {1067 OpaqueMetadata::new(Runtime::metadata().into())1068 }1069 }10701071 impl sp_block_builder::BlockBuilder<Block> for Runtime {1072 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1073 Executive::apply_extrinsic(extrinsic)1074 }10751076 fn finalize_block() -> <Block as BlockT>::Header {1077 Executive::finalize_block()1078 }10791080 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1081 data.create_extrinsics()1082 }10831084 fn check_inherents(1085 block: Block,1086 data: sp_inherents::InherentData,1087 ) -> sp_inherents::CheckInherentsResult {1088 data.check_extrinsics(&block)1089 }10901091 // fn random_seed() -> <Block as BlockT>::Hash {1092 // RandomnessCollectiveFlip::random_seed().01093 // }1094 }10951096 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1097 fn validate_transaction(1098 source: TransactionSource,1099 tx: <Block as BlockT>::Extrinsic,1100 hash: <Block as BlockT>::Hash,1101 ) -> TransactionValidity {1102 Executive::validate_transaction(source, tx, hash)1103 }1104 }11051106 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1107 fn offchain_worker(header: &<Block as BlockT>::Header) {1108 Executive::offchain_worker(header)1109 }1110 }11111112 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1113 fn chain_id() -> u64 {1114 <Runtime as pallet_evm::Config>::ChainId::get()1115 }11161117 fn account_basic(address: H160) -> EVMAccount {1118 EVM::account_basic(&address)1119 }11201121 fn gas_price() -> U256 {1122 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1123 }11241125 fn account_code_at(address: H160) -> Vec<u8> {1126 EVM::account_codes(address)1127 }11281129 fn author() -> H160 {1130 <pallet_evm::Pallet<Runtime>>::find_author()1131 }11321133 fn storage_at(address: H160, index: U256) -> H256 {1134 let mut tmp = [0u8; 32];1135 index.to_big_endian(&mut tmp);1136 EVM::account_storages(address, H256::from_slice(&tmp[..]))1137 }11381139 fn call(1140 from: H160,1141 to: H160,1142 data: Vec<u8>,1143 value: U256,1144 gas_limit: U256,1145 gas_price: Option<U256>,1146 nonce: Option<U256>,1147 estimate: bool,1148 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1149 let config = if estimate {1150 let mut config = <Runtime as pallet_evm::Config>::config().clone();1151 config.estimate = true;1152 Some(config)1153 } else {1154 None1155 };11561157 <Runtime as pallet_evm::Config>::Runner::call(1158 from,1159 to,1160 data,1161 value,1162 gas_limit.low_u64(),1163 gas_price,1164 nonce,1165 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1166 ).map_err(|err| err.into())1167 }11681169 fn create(1170 from: H160,1171 data: Vec<u8>,1172 value: U256,1173 gas_limit: U256,1174 gas_price: Option<U256>,1175 nonce: Option<U256>,1176 estimate: bool,1177 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1178 let config = if estimate {1179 let mut config = <Runtime as pallet_evm::Config>::config().clone();1180 config.estimate = true;1181 Some(config)1182 } else {1183 None1184 };11851186 <Runtime as pallet_evm::Config>::Runner::create(1187 from,1188 data,1189 value,1190 gas_limit.low_u64(),1191 gas_price,1192 nonce,1193 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1194 ).map_err(|err| err.into())1195 }11961197 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1198 Ethereum::current_transaction_statuses()1199 }12001201 fn current_block() -> Option<pallet_ethereum::Block> {1202 Ethereum::current_block()1203 }12041205 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1206 Ethereum::current_receipts()1207 }12081209 fn current_all() -> (1210 Option<pallet_ethereum::Block>,1211 Option<Vec<pallet_ethereum::Receipt>>,1212 Option<Vec<TransactionStatus>>1213 ) {1214 (1215 Ethereum::current_block(),1216 Ethereum::current_receipts(),1217 Ethereum::current_transaction_statuses()1218 )1219 }12201221 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1222 xts.into_iter().filter_map(|xt| match xt.0.function {1223 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1224 _ => None1225 }).collect()1226 }1227 }12281229 impl sp_session::SessionKeys<Block> for Runtime {1230 fn decode_session_keys(1231 encoded: Vec<u8>,1232 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1233 SessionKeys::decode_into_raw_public_keys(&encoded)1234 }12351236 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1237 SessionKeys::generate(seed)1238 }1239 }12401241 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1242 fn slot_duration() -> sp_consensus_aura::SlotDuration {1243 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1244 }12451246 fn authorities() -> Vec<AuraId> {1247 Aura::authorities().to_vec()1248 }1249 }12501251 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1252 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1253 ParachainSystem::collect_collation_info()1254 }1255 }12561257 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1258 fn account_nonce(account: AccountId) -> Index {1259 System::account_nonce(account)1260 }1261 }12621263 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1264 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1265 TransactionPayment::query_info(uxt, len)1266 }1267 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1268 TransactionPayment::query_fee_details(uxt, len)1269 }1270 }12711272 /*1273 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1274 for Runtime1275 {1276 fn call(1277 origin: AccountId,1278 dest: AccountId,1279 value: Balance,1280 gas_limit: u64,1281 input_data: Vec<u8>,1282 ) -> pallet_contracts_primitives::ContractExecResult {1283 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1284 }12851286 fn instantiate(1287 origin: AccountId,1288 endowment: Balance,1289 gas_limit: u64,1290 code: pallet_contracts_primitives::Code<Hash>,1291 data: Vec<u8>,1292 salt: Vec<u8>,1293 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1294 {1295 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1296 }12971298 fn get_storage(1299 address: AccountId,1300 key: [u8; 32],1301 ) -> pallet_contracts_primitives::GetStorageResult {1302 Contracts::get_storage(address, key)1303 }13041305 fn rent_projection(1306 address: AccountId,1307 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1308 Contracts::rent_projection(address)1309 }1310 }1311 */13121313 #[cfg(feature = "runtime-benchmarks")]1314 impl frame_benchmarking::Benchmark<Block> for Runtime {1315 fn benchmark_metadata(extra: bool) -> (1316 Vec<frame_benchmarking::BenchmarkList>,1317 Vec<frame_support::traits::StorageInfo>,1318 ) {1319 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1320 use frame_support::traits::StorageInfoTrait;13211322 let mut list = Vec::<BenchmarkList>::new();13231324 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1325 list_benchmark!(list, extra, pallet_nft, Nft);1326 list_benchmark!(list, extra, pallet_inflation, Inflation);1327 list_benchmark!(list, extra, pallet_fungible, Fungible);1328 list_benchmark!(list, extra, pallet_refungible, Refungible);1329 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);13301331 let storage_info = AllPalletsWithSystem::storage_info();13321333 return (list, storage_info)1334 }13351336 fn dispatch_benchmark(1337 config: frame_benchmarking::BenchmarkConfig1338 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1339 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13401341 let whitelist: Vec<TrackedStorageKey> = vec![1342 // Block Number1343 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1344 // Total Issuance1345 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1346 // Execution Phase1347 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1348 // Event Count1349 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1350 // System Events1351 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1352 ];13531354 let mut batches = Vec::<BenchmarkBatch>::new();1355 let params = (&config, &whitelist);13561357 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1358 add_benchmark!(params, batches, pallet_nft, Nft);1359 add_benchmark!(params, batches, pallet_inflation, Inflation);1360 add_benchmark!(params, batches, pallet_fungible, Fungible);1361 add_benchmark!(params, batches, pallet_refungible, Refungible);1362 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);13631364 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1365 Ok(batches)1366 }1367 }1368}13691370struct CheckInherents;13711372impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1373 fn check_inherents(1374 block: &Block,1375 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1376 ) -> sp_inherents::CheckInherentsResult {1377 let relay_chain_slot = relay_state_proof1378 .read_slot()1379 .expect("Could not read the relay chain slot from the proof");13801381 let inherent_data =1382 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1383 relay_chain_slot,1384 sp_std::time::Duration::from_secs(6),1385 )1386 .create_inherent_data()1387 .expect("Could not create the timestamp inherent data");13881389 inherent_data.check_extrinsics(block)1390 }1391}13921393cumulus_pallet_parachain_system::register_validate_block!(1394 Runtime = Runtime,1395 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1396 CheckInherents = CheckInherents,1397);