moonproof_contracts/fee_balancing.rs
1//! Contract-tx dust-fee balancing.
2//!
3//! Unblocks live-harness submission of contract deploys and calls. The
4//! moonproof submit pipeline splits `prove → balance → submit`, where
5//! `balance` is a pure seal — fee coverage isn't added in `balance_tx`.
6//! Instead, this module attaches the dust-balancing intent to the
7//! **unproven** contract tx so that `ProofProvider::prove_tx` proves
8//! the contract intent + the dust spend in one pass, `balance_tx`
9//! seals the combined result, and `submit_tx` submits.
10//!
11//! Mirrors what the wallet facade's `build_transfer_recipe` already
12//! does for transfer/swap recipes — the underlying helper
13//! [`moonproof_wallet::balance_dust_fee`] is shared verbatim.
14//!
15//! # Who owns the dust state?
16//!
17//! The caller. `FeeBalancingConfig` holds the `DustState` +
18//! `DustSecretKey` by value / reference; the facade-driven sync code
19//! advances them via `fold_dust_events` before the caller hands them
20//! to this module. After submission, the caller re-syncs via the
21//! indexer — we don't try to thread the post-spend `DustState` back
22//! out through the submit pipeline, because the canonical state is
23//! whatever the indexer reports once the tx lands in a block.
24
25use moonproof_ledger::base_crypto::time::Timestamp;
26use moonproof_ledger::ledger::dust::DustSecretKey;
27use moonproof_ledger::ledger::structure::LedgerParameters;
28use moonproof_wallet::{DustState, FacadeState};
29
30use crate::error::{ContractRuntimeError, Result};
31
32/// Parameters for injecting a dust-fee balancing intent into a
33/// contract transaction before [`ProofProvider::prove_tx`].
34///
35/// Construct via [`FeeBalancingConfig::new`]. The struct holds the
36/// `DustState` by value (cloned once at the balance site —
37/// `DustState::clone` is cheap because storage is `Arc`-backed
38/// internally) so callers can freely re-use their facade state.
39///
40/// # Fields
41///
42/// - `dust_state` — the current sub-wallet-owned dust state. Must be
43/// populated with the latest dust events the indexer has reported
44/// (typically via [`moonproof_wallet::fold_dust_events`]).
45/// - `dust_secret_key` — the caller's dust secret key, used to sign
46/// dust spends.
47/// - `current_time` — chain-tip timestamp used as the dust spend's
48/// `ctime`. Must be chain-derived — see
49/// [`moonproof_wallet::fetch_chain_parameters`].
50/// - `ttl` — TTL stamped on the dust-balancing intent. Typically
51/// `current_time + Duration::from_secs(3_600)` to align with
52/// `ttl_one_hour`.
53/// - `ledger_parameters` — the parameters of the block `current_time`
54/// comes from. The fee is priced against their fee prices, which move
55/// per block.
56#[derive(Debug, Clone)]
57pub struct FeeBalancingConfig {
58 pub dust_state: DustState,
59 pub dust_secret_key: DustSecretKey,
60 pub current_time: Timestamp,
61 pub ttl: Timestamp,
62 pub ledger_parameters: LedgerParameters,
63}
64
65impl FeeBalancingConfig {
66 /// Construct a new config. Clones the inputs — callers that want
67 /// to avoid the `DustState` clone can use struct-literal
68 /// construction directly.
69 #[must_use]
70 pub fn new(
71 dust_state: DustState,
72 dust_secret_key: DustSecretKey,
73 current_time: Timestamp,
74 ttl: Timestamp,
75 ledger_parameters: LedgerParameters,
76 ) -> Self {
77 Self {
78 dust_state,
79 dust_secret_key,
80 current_time,
81 ttl,
82 ledger_parameters,
83 }
84 }
85
86 /// The config for a wallet state the sync driver produced, which
87 /// carries the tip time and ledger parameters of one block.
88 #[must_use]
89 pub fn from_synced(
90 synced: &FacadeState,
91 dust_secret_key: DustSecretKey,
92 ttl: Timestamp,
93 ) -> Self {
94 Self::new(
95 synced.dust.clone(),
96 dust_secret_key,
97 synced.chain_tip_ts(),
98 ttl,
99 synced.ledger_parameters().clone(),
100 )
101 }
102}
103
104/// Merge a dust-fee balancing intent into `tx`. Delegates to
105/// [`moonproof_wallet::balance_dust_fee`]; the only translation layer
106/// is the error mapping (`WalletError` → [`ContractRuntimeError::Wallet`]).
107///
108/// Returns the merged unproven transaction. The caller is responsible
109/// for re-syncing their `DustState` from the indexer after submission
110/// — this helper discards the post-spend state because the contract-
111/// runtime layer doesn't carry facade state through its submit
112/// pipeline.
113pub fn apply_fee_balancing<R>(
114 rng: &mut R,
115 #[expect(
116 clippy::needless_pass_by_value,
117 reason = "exported signature; callers hand over the transaction they are replacing with the balanced one"
118 )]
119 tx: moonproof_wallet::UnprovenTransaction,
120 config: &FeeBalancingConfig,
121 network_id: &str,
122) -> Result<moonproof_wallet::UnprovenTransaction>
123where
124 R: rand::Rng + rand::CryptoRng,
125{
126 let (_dust_state_after, merged) = moonproof_wallet::balance_dust_fee(
127 rng,
128 config.dust_state.clone(),
129 &config.dust_secret_key,
130 &tx,
131 &moonproof_wallet::FeeContext {
132 current_time: config.current_time,
133 ttl: config.ttl,
134 network_id,
135 ledger_parameters: &config.ledger_parameters,
136 },
137 )
138 .map_err(ContractRuntimeError::Wallet)?;
139 Ok(merged)
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145
146 fn assert_send_sync<T: Send + Sync>() {}
147
148 #[test]
149 fn fee_balancing_config_is_send_sync() {
150 assert_send_sync::<FeeBalancingConfig>();
151 }
152}