Skip to content

Commit

Permalink
feat: Add consolidated updates to pallet-solana (#113)
Browse files Browse the repository at this point in the history
* feat: Add GenesisConfig to pallet-solana

* feat: Change pallet-solana's Currency trait bound to Mutate

* refactor: Make AccountData return an empty vec by default

* fix: Update slot number when initializing ProgramCacheForTxBatch

* test: Add spl-token program test

* test: Remove irrelevant spl-token tests
  • Loading branch information
conr2d authored Jan 2, 2025
1 parent e9860ee commit 3847333
Show file tree
Hide file tree
Showing 24 changed files with 10,463 additions and 113 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ members = [
"vendor/solana/programs/compute-budget",
"vendor/solana/programs/loader-v4",
"vendor/solana/programs/system",
"vendor/solana/programs/token",
]
default-members = [
"core-primitives",
Expand Down Expand Up @@ -182,6 +183,7 @@ solana-metrics = { path = "vendor/solana/metrics" }
solana-poseidon = { path = "vendor/solana/poseidon", default-features = false }
solana-program-runtime = { path = "vendor/solana/program-runtime", default-features = false }
solana-system-program = { path = "vendor/solana/programs/system", default-features = false }
spl-token = { path = "vendor/solana/programs/token" }

[profile.release]
panic = "unwind"
Expand Down
1 change: 1 addition & 0 deletions frame/solana/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ rand = { workspace = true, default-features = true }
solana-sdk = { workspace = true, features = ["dev-context-only-utils"] }
sp-core = { workspace = true, default-features = true }
sp-io = { workspace = true, default-features = true }
spl-token = { workspace = true }

[features]
default = ["std"]
Expand Down
63 changes: 44 additions & 19 deletions frame/solana/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ extern crate derive_where;
extern crate solana_metrics;

pub use pallet::*;
pub use types::*;

pub use solana_rbpf;
pub use solana_sdk::{pubkey::Pubkey, transaction::VersionedTransaction as Transaction};
Expand All @@ -40,6 +41,7 @@ mod runtime;
mod svm;
#[cfg(test)]
mod tests;
mod types;

use frame_support::{
dispatch::{DispatchErrorWithPostInfo, PostDispatchInfo},
Expand Down Expand Up @@ -85,10 +87,12 @@ impl<O: Into<Result<RawOrigin, O>> + From<RawOrigin>> EnsureOrigin<O> for Ensure
pub mod pallet {
use super::*;
use crate::runtime::bank::Bank;
use core::marker::PhantomData;
use frame_support::{dispatch::DispatchInfo, pallet_prelude::*, traits::fungible};
use frame_system::{pallet_prelude::*, CheckWeight};
use np_runtime::traits::LossyInto;
use solana_sdk::{
account::Account,
clock,
fee_calculator::FeeCalculator,
hash::Hash,
Expand Down Expand Up @@ -128,7 +132,7 @@ pub mod pallet {
+ LossyInto<u64>;

#[pallet::no_default]
type Currency: fungible::Unbalanced<Self::AccountId, Balance = Self::Balance>;
type Currency: fungible::Mutate<Self::AccountId, Balance = Self::Balance>;

#[pallet::constant]
#[pallet::no_default_bounds]
Expand Down Expand Up @@ -183,20 +187,6 @@ pub mod pallet {
#[pallet::origin]
pub type Origin = RawOrigin;

#[derive(Decode, Encode, MaxEncodedLen, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct HashInfo<T: Config> {
pub fee_calculator: FeeCalculator,
pub hash_index: BlockNumberFor<T>,
pub timestamp: T::Moment,
}

impl<T: Config> HashInfo<T> {
pub fn lamports_per_signature(&self) -> u64 {
self.fee_calculator.lamports_per_signature
}
}

#[pallet::storage]
#[pallet::getter(fn slot)]
pub type Slot<T: Config> = StorageValue<_, clock::Slot, ValueQuery>;
Expand All @@ -210,13 +200,48 @@ pub mod pallet {

#[pallet::storage]
#[pallet::getter(fn account_meta)]
pub type AccountMeta<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, crate::runtime::meta::AccountMeta>;
pub type AccountMeta<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, AccountMetadata>;

#[pallet::storage]
#[pallet::getter(fn account_data)]
pub type AccountData<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, BoundedVec<u8, T::MaxPermittedDataLength>>;
pub type AccountData<T: Config> = StorageMap<
_,
Twox64Concat,
T::AccountId,
BoundedVec<u8, T::MaxPermittedDataLength>,
ValueQuery,
>;

#[pallet::genesis_config]
#[derive_where(Default)]
pub struct GenesisConfig<T: Config> {
accounts: Vec<(Pubkey, Account)>,
_marker: PhantomData<T>,
}

#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
self.accounts.iter().for_each(|(pubkey, account)| {
let who = T::AccountIdConversion::convert(*pubkey);
assert!(<frame_system::Pallet<T>>::account_exists(&who));
<AccountMeta<T>>::insert(
&who,
AccountMetadata {
rent_epoch: account.rent_epoch,
owner: account.owner,
executable: account.executable,
},
);
(!account.data.is_empty()).then(|| {
<AccountData<T>>::insert(
who,
BoundedVec::try_from(account.data.clone()).expect("valid data"),
);
});
});
}
}

#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
Expand Down
15 changes: 10 additions & 5 deletions frame/solana/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,23 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![
(Keypair::alice().account_id(), 10_000_000_000_000_000_000u128),
(Keypair::bob().account_id(), 10_000_000_000_000_000_000u128),
(Keypair::alice().account_id(), sol_into_balances(10)),
(Keypair::bob().account_id(), sol_into_balances(10)),
],
}
.assimilate_storage(&mut t)
.unwrap();
t.into()
}

pub const fn sol_into_lamports(sol: u64) -> u64 {
sol * 10u64.pow(9)
}

pub const fn sol_into_balances(sol: u64) -> Balance {
(sol_into_lamports(sol) as Balance) * 10u128.pow(9)
}

pub trait KeypairExt: Sized {
fn create() -> Self;

Expand All @@ -138,9 +146,6 @@ pub trait KeypairExt: Sized {
fn bob() -> Self {
Self::get("Bob")
}
fn charlie() -> Self {
Self::get("Charlie")
}
}

fn pair_to_bytes(pair: Pair) -> [u8; 64] {
Expand Down
12 changes: 4 additions & 8 deletions frame/solana/src/runtime/bank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.

use crate::{
runtime::lamports::Lamports,
svm::{
account_loader::{
CheckedTransactionDetails, TransactionCheckResult, TransactionLoadResult,
Expand All @@ -31,7 +30,7 @@ use crate::{
},
transaction_results::TransactionExecutionResult,
},
AccountData, AccountMeta, Config, Pallet,
AccountData, AccountMeta, AccountMetadata, Config, Lamports, Pallet,
};
use frame_support::{
sp_runtime::traits::{Convert, ConvertBack, SaturatedConversion},
Expand Down Expand Up @@ -507,7 +506,7 @@ impl<T: Config> Bank<T> {

fn store_account(&self, pubkey: &T::AccountId, account: &AccountSharedData) {
<AccountMeta<T>>::mutate(pubkey, |meta| {
*meta = Some(crate::runtime::meta::AccountMeta {
*meta = Some(AccountMetadata {
rent_epoch: account.rent_epoch(),
owner: *account.owner(),
executable: account.executable(),
Expand Down Expand Up @@ -561,13 +560,10 @@ impl<T: Config> TransactionProcessingCallback for Bank<T> {
let account = <AccountMeta<T>>::get(&pubkey)?;
let lamports =
<Lamports<T>>::new(T::Currency::reducible_balance(&pubkey, Preserve, Polite));
let data = <AccountData<T>>::get(&pubkey);
let data = <AccountData<T>>::get(&pubkey).into();
Some(AccountSharedData::from(Account {
lamports: lamports.get(),
data: match data {
Some(data) => data.into(),
None => vec![],
},
data,
owner: account.owner,
executable: account.executable,
rent_epoch: account.rent_epoch,
Expand Down
49 changes: 0 additions & 49 deletions frame/solana/src/runtime/meta.rs

This file was deleted.

2 changes: 0 additions & 2 deletions frame/solana/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,3 @@
#![allow(unexpected_cfgs)]

pub mod bank;
pub mod lamports;
pub mod meta;
6 changes: 3 additions & 3 deletions frame/solana/src/svm/transaction_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,8 @@ impl TransactionProcessor {
_check_program_modification_slot: bool,
_limit_to_load_programs: bool,
) -> ProgramCacheForTxBatch {
let mut loaded_programs_for_tx_batch = ProgramCacheForTxBatch::default();

// FIXME: program_runtime_environments.
loaded_programs_for_tx_batch.environments = ProgramRuntimeEnvironments {
let environments = ProgramRuntimeEnvironments {
program_runtime_v1: Arc::new(
create_program_runtime_environment_v1(
&Default::default(),
Expand All @@ -420,6 +418,8 @@ impl TransactionProcessor {
false, /* debugging_features */
)),
};
let mut loaded_programs_for_tx_batch =
ProgramCacheForTxBatch::new(self.slot, environments, None, self.epoch);

// FIXME: load builtins.
for cached_program in self.program_cache.iter() {
Expand Down
Loading

0 comments on commit 3847333

Please sign in to comment.