penumbra_sdk_dex/component/action_handler/position/withdraw.rs
1use anyhow::Result;
2use ark_ff::Zero;
3use async_trait::async_trait;
4use cnidarium::StateWrite;
5use cnidarium_component::ActionHandler;
6use decaf377::Fr;
7
8use crate::{component::PositionManager, lp::action::PositionWithdraw};
9
10#[async_trait]
11/// Debits a closed position NFT and credits a withdrawn position NFT and the final reserves.
12impl ActionHandler for PositionWithdraw {
13 type CheckStatelessContext = ();
14 async fn check_stateless(&self, _context: ()) -> Result<()> {
15 // Nothing to do: the only validation is of the state change,
16 // and that's done by the value balance mechanism.
17 Ok(())
18 }
19
20 async fn check_and_execute<S: StateWrite>(&self, mut state: S) -> Result<()> {
21 // See comment in check_stateful for why we check the position state here:
22 // we need to ensure that we're checking the reserves at the moment we execute
23 // the withdrawal, to prevent any possibility of TOCTOU attacks.
24
25 // Execute the withdrawal, extracting the reserves from the position.
26 let actual_reserves = state
27 .withdraw_position(self.position_id, self.sequence)
28 .await?;
29
30 // Next, and CRITICALLY, check that the commitment to the amount the user is
31 // withdrawing is correct.
32 //
33 // Unlike other actions, where a balance commitment is used for
34 // shielding a value, this commitment is used for compression, giving a
35 // single commitment rather than a list of token amounts.
36 //
37 // Note: since this is forming a commitment only to the reserves,
38 // we are implicitly setting the reward amount to 0. However, we can
39 // add support for rewards in the future without client changes.
40 let expected_reserves_commitment = actual_reserves.commit(Fr::zero());
41
42 if self.reserves_commitment != expected_reserves_commitment {
43 anyhow::bail!(
44 "reserves commitment {:?} is incorrect, expected {:?}",
45 self.reserves_commitment,
46 expected_reserves_commitment
47 );
48 }
49
50 Ok(())
51 }
52}