Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/actions/run-redsuite/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ runs:
uses: actions/checkout@v5
with:
repository: magicblock-labs/redsuite
ref: 3.5.8
ref: 1488223536910cbddbb8550aa644ce196c709574 # https://github.com/magicblock-labs/redsuite/pull/337
path: redsuite
persist-credentials: false

Expand Down
21 changes: 16 additions & 5 deletions core/src/intent/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -518,18 +518,29 @@ impl UndelegateType {
}

pub fn calculate_commit_fee(accounts: &[CommittedAccount]) -> Result<u64, InstructionError> {
accounts.iter().try_fold(0u64, |fee, account| {
if account.commit_id == 0 {
calculate_commit_fee_for_ids(accounts.iter().map(|account| account.commit_id))
}

/// Calculate the fee before copying the accounts into settlement snapshots.
pub fn calculate_commit_fee_for_ids(
commit_ids: impl IntoIterator<Item = u64>,
) -> Result<u64, InstructionError> {
commit_ids.into_iter().try_fold(0u64, |fee, commit_id| {
if commit_id == 0 {
return Err(InstructionError::Custom(MISSING_COMMIT_NONCE_ERR));
}
Ok(fee + if account.commit_id > ACTUAL_COMMIT_LIMIT { COMMIT_FEE_LAMPORTS } else { 0 })
Ok(fee + if commit_id > ACTUAL_COMMIT_LIMIT { COMMIT_FEE_LAMPORTS } else { 0 })
})
}

fn calculate_actions_fee(actions: &[BaseAction]) -> u64 {
calculate_actions_fee_for_units(actions.iter().map(|action| action.compute_units))
}

pub fn calculate_actions_fee_for_units(compute_units: impl IntoIterator<Item = u32>) -> u64 {
const MICRO_LAMPORTS_PER_LAMPORT: u64 = 1_000_000;
let micro_lamports = actions.iter().fold(0u64, |acc, action| {
acc.saturating_add(action.compute_units as u64 * COMPUTE_UNIT_PRICE_MICRO_LAMPORTS)
let micro_lamports = compute_units.into_iter().fold(0u64, |acc, units| {
acc.saturating_add(units as u64 * COMPUTE_UNIT_PRICE_MICRO_LAMPORTS)
});
micro_lamports.div_ceil(MICRO_LAMPORTS_PER_LAMPORT)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use magic_program_api::args::{
pub use mbv_core::intent::{
ACTUAL_COMMIT_LIMIT, BaseAction, COMMIT_FEE_LAMPORTS, COMPUTE_UNIT_PRICE_MICRO_LAMPORTS,
CommitAndUndelegate, CommitType, MagicBaseIntent, MagicIntentBundle, ProgramArgs,
UndelegateType, calculate_commit_fee,
UndelegateType, calculate_actions_fee_for_units, calculate_commit_fee,
calculate_commit_fee_for_ids,
};
use mbv_core::{
Slot,
Expand Down Expand Up @@ -79,6 +80,51 @@ impl<'a, 'ic, 'ix_data> ConstructionContext<'a, 'ic, 'ix_data> {

type CommitAccountRef<'a, 'ix_data> = (Pubkey, InstructionAccount<'a, 'ix_data>);

/// Calculate the fee using the IDs that construction will reserve, without
/// changing account state. The caller charges it before capturing snapshots.
pub(crate) fn calculate_intent_bundle_fee(
args: &MagicIntentBundleArgs,
transaction_context: &TransactionContext<'_>,
) -> Result<u64, InstructionError> {
let mut commit_ids = Vec::new();
let mut fee = 0;
let actions_fee = |actions: &[BaseActionArgs]| {
calculate_actions_fee_for_units(actions.iter().map(|action| action.compute_units))
};

for commit in [
args.commit.as_ref(),
args.commit_and_undelegate.as_ref().map(|intent| &intent.commit_type),
args.commit_finalize.as_ref(),
args.commit_finalize_and_undelegate.as_ref().map(|intent| &intent.commit_type),
]
.into_iter()
.flatten()
{
for index in commit.committed_accounts_indices() {
let account = get_instruction_account_with_idx(transaction_context, *index as u16)?;
commit_ids.push(u64::from(account.borrow()?.commit_seq()) + 1);
}
if let CommitTypeArgs::WithBaseActions { base_actions, .. } = commit {
fee += actions_fee(base_actions);
}
}
for intent in [
args.commit_and_undelegate.as_ref(),
args.commit_finalize_and_undelegate.as_ref(),
]
.into_iter()
.flatten()
{
if let UndelegateTypeArgs::WithBaseActions { base_actions } = &intent.undelegate_type {
fee += actions_fee(base_actions);
}
}
fee += actions_fee(&args.standalone_actions);

Ok(fee + calculate_commit_fee_for_ids(commit_ids)?)
}

/// Scheduled action to be executed on base layer
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, SchemaRead, SchemaWrite)]
pub struct ScheduledIntentBundle {
Expand All @@ -93,6 +139,8 @@ pub struct ScheduledIntentBundle {
}

impl ScheduledIntentBundle {
/// Validate, reserve IDs, and capture settlement state after the scheduling
/// handler charges the fee, before changing ownership.
pub fn try_new(
args: MagicIntentBundleArgs,
intent_id: u64,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::collections::HashSet;

use mbv_core::intent::{
CommitAndUndelegate, CommitType, MagicBaseIntent, UndelegateType, calculate_commit_fee,
CommitAndUndelegate, CommitType, MagicBaseIntent, UndelegateType, calculate_commit_fee_for_ids,
outbox::outbox_intent_pda, types::CommittedAccount,
};
use mbv_core::token_programs::try_remap_ata_to_eata;
use solana_account::{AccountMode, ReadableAccount, WritableAccount};
use solana_account_info::MAX_PERMITTED_DATA_INCREASE;
use solana_instruction::error::InstructionError;
Expand Down Expand Up @@ -89,7 +90,7 @@ pub(crate) fn process_schedule_commit(
// NOTE: we don't require PDAs to be signers as in our case verifying that the
// program owning the PDAs invoked us directly via CPI is sufficient
// Thus we can be `invoke`d unsigned and no seeds need to be provided
let mut committed_accounts: Vec<CommittedAccount> = Vec::new();
let mut accounts_to_commit = Vec::new();
let mut seen_committed_pubkeys: HashSet<Pubkey> = HashSet::new();
for idx in committees_start..ix_accs_len {
let acc_pubkey = get_instruction_pubkey_with_idx(transaction_context, idx as u16)?;
Expand Down Expand Up @@ -149,55 +150,50 @@ pub(crate) fn process_schedule_commit(
)?;

let account = acc.borrow()?;
let mut committed = CommittedAccount::from_account_shared(*acc_pubkey, &account);
let committed_pubkey = try_remap_ata_to_eata(acc_pubkey, &account)
.map_or(*acc_pubkey, |(pubkey, _)| pubkey);
drop(account);

if &committed.pubkey != acc_pubkey {
if &committed_pubkey != acc_pubkey {
ic_msg!(
invoke_context,
"ScheduleCommit: remapping ATA {} -> eATA {}",
acc_pubkey,
committed.pubkey
committed_pubkey
);
}

// Backwards-compat: merge duplicate accounts (by final restored pubkey).
// Keep the first occurrence and ignore subsequent duplicates.
if !(seen_committed_pubkeys.insert(committed.pubkey)) {
if !seen_committed_pubkeys.insert(committed_pubkey) {
continue;
}

committed.commit_id = reserve_commit_id(&acc)?;
committed_accounts.push(committed);
accounts_to_commit.push((*acc_pubkey, acc));
}
}

if opts.request_undelegation {
// If the account is scheduled to be undelegated then we need to lock it
// immediately in order to prevent the following actions:
// - writes to the account
// - scheduling further commits for this account
//
// Setting the owner will prevent both, since in both cases the _actual_
// owner program needs to sign for the account which is not possible at
// that point
// NOTE: this owner change only takes effect if the transaction which
// includes this instruction succeeds.
//
// We also set the undelegating flag on the account in order to detect
// undelegations for which we miss updates
mark_account_as_undelegated(invoke_context, &acc)?;
ic_msg!(
invoke_context,
"ScheduleCommit: Marking account {} as undelegating",
acc_pubkey
);
}
// reserve_commit_id also increments account's commit_seq
let commit_ids = accounts_to_commit
.iter()
.map(|(_, account)| reserve_commit_id(account))
.collect::<Result<Vec<_>, _>>()?;

if let Some(ref fee_vault) = magic_fee_vault {
let fee = calculate_commit_fee_for_ids(commit_ids)?;
charge_delegated_payer(&payer_account, fee_vault, fee)?;
}

if let Some(fee_vault) = magic_fee_vault {
let fee = calculate_commit_fee(&committed_accounts)?;
charge_delegated_payer(&payer_account, &fee_vault, fee)?;
} else if !opts.request_undelegation {
// The payer or fee vault may also be committed. Copy their post-fee state,
// before undelegation changes their owner and account mode.
let committed_accounts = accounts_to_commit
.iter()
.map(|(pubkey, account)| {
let account = account.borrow()?;
Ok(CommittedAccount::from_account_shared(*pubkey, &account))
})
.collect::<Result<Vec<_>, InstructionError>>()?;
if magic_fee_vault.is_none() && !opts.request_undelegation {
// We validate commit nonces only for plain commits.
// If accounts are undelegated we don't want to fail.
check_commit_limits(&committed_accounts, invoke_context)?;
Expand Down Expand Up @@ -240,6 +236,19 @@ pub(crate) fn process_schedule_commit(
);
})?;

if opts.request_undelegation {
for (pubkey, account) in &accounts_to_commit {
// Lock the local account only after capturing its original owner.
// The transaction rolls this back if a later instruction fails.
mark_account_as_undelegated(invoke_context, account)?;
ic_msg!(
invoke_context,
"ScheduleCommit: Marking account {} as undelegating",
pubkey
);
}
}

let scheduled_base_intent = ScheduledIntentBundle {
intent_id,
slot: clock.slot,
Expand Down
Loading
Loading