Skip to content

Precompile advanced order#2685

Draft
open-junius wants to merge 92 commits into
devnet-readyfrom
precompile-advanced-order
Draft

Precompile advanced order#2685
open-junius wants to merge 92 commits into
devnet-readyfrom
precompile-advanced-order

Conversation

@open-junius
Copy link
Copy Markdown
Contributor

Description

Related Issue(s)

  • Closes #[issue number]

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Other (please describe):

Breaking Change

If this PR introduces a breaking change, please provide a detailed description of the impact and the migration path for existing applications.

Checklist

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have run ./scripts/fix_rust.sh to ensure my code is formatted and linted correctly
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Screenshots (if applicable)

Please include any relevant screenshots or GIFs that demonstrate the changes made.

Additional Notes

Please provide any additional information or context that may be helpful for reviewers.

Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review — see the sticky summary comment for the verdict and the inline comments below for specific findings.

/// subnet are skipped.
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::execute_batched_orders(orders.len() as u32))]
pub fn execute_batched_orders(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] Batched execution is not atomic after collecting user assets

execute_batched_orders pulls TAO/staked alpha from every order signer into the pallet account via collect_assets, then makes later fallible calls (net_pool_swap, distribution transfers, zero-output checks). Without a transaction boundary, an error after collect_assets can return Err while leaving balances/stake already moved into or through the pallet account and orders not marked fulfilled. A public relayer can trigger this with valid signed orders plus a later slippage/zero-output/distribution failure, locking or misrouting user funds. Wrap the whole batched dispatch in a FRAME transaction so any later error rolls back the asset collection and intermediate transfers.

Suggested change
pub fn execute_batched_orders(
#[frame_support::transactional]
pub fn execute_batched_orders(

Comment on lines +153 to +176
let available =
Self::get_stake_for_hotkey_and_coldkey_on_subnet(from_hotkey, from_coldkey, netuid);
ensure!(available >= amount, Error::<T>::NotEnoughStakeToWithdraw);
Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(
from_hotkey,
from_coldkey,
netuid,
amount,
);
Self::increase_stake_for_hotkey_and_coldkey_on_subnet(
to_hotkey, to_coldkey, netuid, amount,
);
LastColdkeyHotkeyStakeBlock::<T>::insert(
to_coldkey,
to_hotkey,
Self::get_current_block_as_u64(),
);
if validate_receiver {
ensure!(
Self::hotkey_account_exists(to_hotkey),
Error::<T>::HotKeyAccountNotExists
);
Self::set_stake_operation_limit(to_hotkey, to_coldkey, netuid);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] Stake transfer mutates balances before receiver validation

transfer_staked_alpha decreases the sender stake, increases receiver stake, and writes the rate-limit block before checking hotkey_account_exists(to_hotkey) when validate_receiver is true. In the new batched limit-order distribution path, a buy order with an unregistered destination hotkey can therefore make this helper return Err after stake has already been moved. Validate the receiver before any stake mutation, then set the receiver rate limit after the successful move.

Suggested change
let available =
Self::get_stake_for_hotkey_and_coldkey_on_subnet(from_hotkey, from_coldkey, netuid);
ensure!(available >= amount, Error::<T>::NotEnoughStakeToWithdraw);
Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(
from_hotkey,
from_coldkey,
netuid,
amount,
);
Self::increase_stake_for_hotkey_and_coldkey_on_subnet(
to_hotkey, to_coldkey, netuid, amount,
);
LastColdkeyHotkeyStakeBlock::<T>::insert(
to_coldkey,
to_hotkey,
Self::get_current_block_as_u64(),
);
if validate_receiver {
ensure!(
Self::hotkey_account_exists(to_hotkey),
Error::<T>::HotKeyAccountNotExists
);
Self::set_stake_operation_limit(to_hotkey, to_coldkey, netuid);
}
if validate_receiver {
ensure!(
Self::hotkey_account_exists(to_hotkey),
Error::<T>::HotKeyAccountNotExists
);
}
let available =
Self::get_stake_for_hotkey_and_coldkey_on_subnet(from_hotkey, from_coldkey, netuid);
ensure!(available >= amount, Error::<T>::NotEnoughStakeToWithdraw);
Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(
from_hotkey,
from_coldkey,
netuid,
amount,
);
Self::increase_stake_for_hotkey_and_coldkey_on_subnet(
to_hotkey, to_coldkey, netuid, amount,
);
LastColdkeyHotkeyStakeBlock::<T>::insert(
to_coldkey,
to_hotkey,
Self::get_current_block_as_u64(),
);
if validate_receiver {
Self::set_stake_operation_limit(to_hotkey, to_coldkey, netuid);
}

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 25, 2026

🛡️ AI Review — Skeptic (security review)

VERDICT: VULNERABLE

MEDIUM scrutiny: open-junius has repo write permission and substantial prior activity; no Gittensor allowlist hit; branch is precompile-advanced-order -> devnet-ready.

No trusted review prompt or copilot-instruction files are modified in this PR. Static review found the prior fund-safety issues still present, plus a fee-evasion path in direct buy-order execution.

Findings

Sev File Finding
HIGH pallets/limit-orders/src/lib.rs:797 Batched execution is not atomic after collecting user assets inline
HIGH pallets/subtensor/src/staking/order_swap.rs:152 Stake transfer mutates balances before receiver validation inline
MEDIUM pallets/limit-orders/src/lib.rs:720 Direct buy execution can fill an order without collecting its fee inline

Prior-comment reconciliation

  • 9d96ce03: not addressedexecute_batched_orders still delegates into a multi-step asset collection, pool swap, and distribution flow without a transaction boundary.
  • 3aeaa1bb: not addressedtransfer_staked_alpha still performs stake mutations before the validate_receiver hotkey-existence check.

Conclusion

The PR appears legitimate, but the new limit-order execution paths can still leave assets moved after later failures, and direct buy execution can mark orders filled without collecting the signed fee. These are security/economic vulnerabilities and should block merge.


📜 Previous run (superseded)
Sev File Finding Status
HIGH pallets/limit-orders/src/lib.rs:441 Batched execution is not atomic after collecting user assets ➡️ Carried forward to current findings
execute_batched_orders still delegates into a multi-step asset collection, pool swap, and distribution flow without a transaction boundary.
HIGH pallets/subtensor/src/staking/order_swap.rs:176 Stake transfer mutates balances before receiver validation ➡️ Carried forward to current findings
transfer_staked_alpha still performs stake mutations before the validate_receiver hotkey-existence check.

# 🔍 AI Review — Auditor (domain review) has not yet run on this PR.

@github-actions
Copy link
Copy Markdown
Contributor

🔄 AI review updated — Skeptic: VULNERABLE

Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review — see the sticky summary comment for the verdict and the inline comments below for specific findings.

Comment on lines +439 to +441
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::execute_batched_orders(orders.len() as u32))]
pub fn execute_batched_orders(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] Batched execution is not atomic after collecting user assets

execute_batched_orders can transfer TAO/staked alpha into the pallet account in collect_assets, then return Err from net_pool_swap, distribute_alpha_pro_rata, or distribute_tao_pro_rata. Without a transaction boundary on the extrinsic, those earlier balance/stake mutations are not rolled back, so a failing batch can strand or move user assets while the order remains unfulfilled. Wrap the whole batched extrinsic in #[frame_support::transactional] or otherwise make every post-collection failure non-fatal and fully accounted.

Suggested change
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::execute_batched_orders(orders.len() as u32))]
pub fn execute_batched_orders(
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::execute_batched_orders(orders.len() as u32))]
#[frame_support::transactional]
pub fn execute_batched_orders(

Comment on lines +153 to +176
let available =
Self::get_stake_for_hotkey_and_coldkey_on_subnet(from_hotkey, from_coldkey, netuid);
ensure!(available >= amount, Error::<T>::NotEnoughStakeToWithdraw);
Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(
from_hotkey,
from_coldkey,
netuid,
amount,
);
Self::increase_stake_for_hotkey_and_coldkey_on_subnet(
to_hotkey, to_coldkey, netuid, amount,
);
LastColdkeyHotkeyStakeBlock::<T>::insert(
to_coldkey,
to_hotkey,
Self::get_current_block_as_u64(),
);
if validate_receiver {
ensure!(
Self::hotkey_account_exists(to_hotkey),
Error::<T>::HotKeyAccountNotExists
);
Self::set_stake_operation_limit(to_hotkey, to_coldkey, netuid);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] Stake transfer mutates balances before receiver validation

When validate_receiver is true, this function decreases the sender stake, increases the receiver stake, and writes LastColdkeyHotkeyStakeBlock before checking hotkey_account_exists(to_hotkey). If that receiver check fails, the function returns an error after mutating stake accounting. In the current batched-order path this compounds the missing atomicity issue; the receiver-side validation needs to happen before any stake movement.

Suggested change
let available =
Self::get_stake_for_hotkey_and_coldkey_on_subnet(from_hotkey, from_coldkey, netuid);
ensure!(available >= amount, Error::<T>::NotEnoughStakeToWithdraw);
Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(
from_hotkey,
from_coldkey,
netuid,
amount,
);
Self::increase_stake_for_hotkey_and_coldkey_on_subnet(
to_hotkey, to_coldkey, netuid, amount,
);
LastColdkeyHotkeyStakeBlock::<T>::insert(
to_coldkey,
to_hotkey,
Self::get_current_block_as_u64(),
);
if validate_receiver {
ensure!(
Self::hotkey_account_exists(to_hotkey),
Error::<T>::HotKeyAccountNotExists
);
Self::set_stake_operation_limit(to_hotkey, to_coldkey, netuid);
}
if validate_receiver {
ensure!(
Self::hotkey_account_exists(to_hotkey),
Error::<T>::HotKeyAccountNotExists
);
}
let available =
Self::get_stake_for_hotkey_and_coldkey_on_subnet(from_hotkey, from_coldkey, netuid);
ensure!(available >= amount, Error::<T>::NotEnoughStakeToWithdraw);
Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(
from_hotkey,
from_coldkey,
netuid,
amount,
);
Self::increase_stake_for_hotkey_and_coldkey_on_subnet(
to_hotkey, to_coldkey, netuid, amount,
);
LastColdkeyHotkeyStakeBlock::<T>::insert(
to_coldkey,
to_hotkey,
Self::get_current_block_as_u64(),
);
if validate_receiver {
Self::set_stake_operation_limit(to_hotkey, to_coldkey, netuid);
}

@github-actions
Copy link
Copy Markdown
Contributor

🔄 AI review updated — Skeptic: VULNERABLE

Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review — see the sticky summary comment for the verdict and the inline comments below for specific findings.

let pallet_hotkey = T::PalletHotkey::get();

// Pull all input assets into the pallet intermediary before touching the pool.
Self::collect_assets(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] Batched execution is not atomic after collecting user assets

execute_batched_orders still starts by moving every buyer's TAO and seller's staked alpha into the pallet intermediary, then performs the net pool swap, pro-rata distributions, fee forwarding, order-status writes, and event emission as separate fallible steps. There is no outer #[transactional] / with_transaction boundary around the whole batch. If any later transfer or swap fails after this line, earlier collect_assets transfers are not rolled back, so users can lose assets while the extrinsic returns an error and some orders remain unfilled. Wrap the full do_execute_batched_orders asset-collection/swap/distribution/status-write flow in a transaction, or prevalidate every fallible post-collection transfer so no failure is possible after user assets are pulled.

Comment on lines +138 to +152
Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(
from_hotkey,
from_coldkey,
netuid,
amount,
);
Self::increase_stake_for_hotkey_and_coldkey_on_subnet(
to_hotkey, to_coldkey, netuid, amount,
);
LastColdkeyHotkeyStakeBlock::<T>::insert(
to_coldkey,
to_hotkey,
Self::get_current_block_as_u64(),
);
if validate_receiver {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] Stake transfer mutates balances before receiver validation

transfer_staked_alpha decreases the sender's stake, increases the receiver's stake, and writes LastColdkeyHotkeyStakeBlock before checking validate_receiver. The batch distributor calls this with validate_receiver = true for buyers, so a bad buyer hotkey can make the function return HotKeyAccountNotExists after stake has already been moved out of the pallet intermediary. Because this helper is not transactional and the outer batch is not transactional, that failure leaves mutated stake/accounting behind. Validate to_hotkey before lines 138-151, or make this helper transactional so receiver-validation failures roll back the mutations.

Comment on lines +713 to +720
let (amount_in, amount_out) = if order.order_type.is_buy() {
// partial fill validations have passed, it is safe here to do this
let tao_in = TaoBalance::from(signed_order.partial_fill.unwrap_or(order.amount));
// Deduct fee from TAO input before swapping.
let fee_tao = TaoBalance::from(order.fee_rate.mul_floor(tao_in.to_u64()));
let tao_after_fee = tao_in.saturating_sub(fee_tao);

let alpha_out = T::SwapInterface::buy_alpha(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Direct buy execution can fill an order without collecting its fee

For buy orders, the pallet only passes tao_after_fee into buy_alpha, so the subtensor-side balance validation only proves the signer can pay the net swap amount. The fee is then forwarded best-effort from the signer after the swap. A signer with exactly amount - fee free TAO can have the order execute and be marked fulfilled, while forward_fee fails and leaves the fee unpaid. This makes the signed fee field unenforceable in the direct execute_orders path. Require/fund the gross buy amount atomically, or make buy fee transfer a hard precondition before marking the order executed.

@github-actions
Copy link
Copy Markdown
Contributor

🔄 AI review updated — Skeptic: VULNERABLE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants