Skip to main content

sui_types/
gas.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// SPDX-License-Identifier: Apache-2.0
4
5#![deny(clippy::arithmetic_side_effects)]
6#![deny(clippy::cast_possible_truncation)]
7#![deny(clippy::indexing_slicing)]
8#![deny(clippy::cast_possible_wrap)]
9#![deny(clippy::cast_sign_loss)]
10
11pub use checked::*;
12use serde::{Deserialize, Serialize};
13
14use crate::{base_types::ObjectID, gas_model::gas_v2::PerObjectStorage};
15
16pub mod checked {
17
18    use crate::gas::GasUsageReport;
19    use crate::gas_model::gas_common::{check_gas_data, check_gas_objects};
20    use crate::gas_model::gas_predicates::{
21        check_for_gas_price_too_high, txn_base_cost_as_multiplier,
22    };
23    use crate::gas_model::gas_v2::PerObjectStorage;
24    use crate::{
25        ObjectID,
26        effects::{TransactionEffects, TransactionEffectsAPI},
27        error::{ExecutionError, UserInputError, UserInputResult},
28        gas_model::{
29            gas_v2::SuiGasStatus as SuiGasStatusV2, gas_v3::SuiGasStatus as SuiGasStatusV3,
30            tables::GasStatus,
31        },
32        object::Object,
33        sui_serde::{BigInt, Readable},
34        transaction::{GasData, ObjectReadResult, TransactionKind, is_gasless_transaction},
35    };
36    use enum_dispatch::enum_dispatch;
37    use itertools::MultiUnzip;
38    use schemars::JsonSchema;
39    use serde::{Deserialize, Serialize};
40    use serde_with::serde_as;
41    use sui_protocol_config::ProtocolConfig;
42
43    #[enum_dispatch]
44    pub trait SuiGasStatusAPI {
45        fn is_unmetered(&self) -> bool;
46        fn move_gas_status(&self) -> &GasStatus;
47        fn move_gas_status_mut(&mut self) -> &mut GasStatus;
48        fn bucketize_computation(&mut self, aborted: Option<bool>) -> Result<(), ExecutionError>;
49        fn summary(&self) -> GasCostSummary;
50        fn gas_budget(&self) -> u64;
51        fn gas_price(&self) -> u64;
52        fn reference_gas_price(&self) -> u64;
53        fn storage_gas_units(&self) -> u64;
54        fn storage_rebate(&self) -> u64;
55        fn unmetered_storage_rebate(&self) -> u64;
56        fn gas_used(&self) -> u64;
57        fn reset_storage_cost_and_rebate(&mut self);
58        fn charge_storage_read(&mut self, size: usize) -> Result<(), ExecutionError>;
59        fn charge_publish_package(&mut self, size: usize) -> Result<(), ExecutionError>;
60        fn track_storage_mutation(
61            &mut self,
62            object_id: ObjectID,
63            new_size: usize,
64            storage_rebate: u64,
65        ) -> Option<u64>;
66        fn charge_storage_and_rebate(&mut self) -> Result<(), ExecutionError>;
67        fn adjust_computation_on_out_of_gas(&mut self);
68        fn gas_usage_report(&self) -> GasUsageReport;
69        fn per_object_storage(&self) -> &Vec<(ObjectID, PerObjectStorage)>;
70    }
71
72    /// Version-aware gas status: `V2` is the legacy model (`gas_model_version < 15`, incl. replay),
73    /// `V3` is the v15+ pipeline. Dispatched by `gas_model_version() >= 15`.
74    #[enum_dispatch(SuiGasStatusAPI)]
75    #[derive(Debug)]
76    pub enum SuiGasStatus {
77        // V1 does not exists any longer as it was a pre mainnet version.
78        // So we start the enum from V2
79        V2(SuiGasStatusV2),
80        V3(SuiGasStatusV3),
81    }
82
83    impl SuiGasStatus {
84        /// Charge reading a package input. Earlier gas models charge packages as other inputs.
85        pub fn charge_package_object_read(&mut self, size: usize) -> Result<(), ExecutionError> {
86            match self {
87                Self::V2(status) => status.charge_storage_read(size),
88                Self::V3(status) => status.charge_package_object_read(size),
89            }
90        }
91
92        /// Build the status for execution. Validation lives in `check_gas_price` and
93        /// `check_gas_budget_and_balance`.
94        fn new(
95            gas_budget: u64,
96            gas_price: u64,
97            reference_gas_price: u64,
98            config: &ProtocolConfig,
99        ) -> Self {
100            // Dispatch by gas model version: v15+ uses the clean gas_v3 pipeline;
101            // everything older keeps the legacy gas_v2 path so replay determinism holds.
102            if config.gas_model_version() >= 15 {
103                Self::V3(SuiGasStatusV3::new_with_budget(
104                    gas_budget,
105                    gas_price,
106                    reference_gas_price,
107                    config,
108                ))
109            } else {
110                Self::V2(SuiGasStatusV2::new_with_budget(
111                    gas_budget,
112                    gas_price,
113                    reference_gas_price,
114                    config,
115                ))
116            }
117        }
118
119        /// The status a transaction is executed with, derived from what signing validated.
120        pub fn for_execution(
121            gas_data: &GasData,
122            kind: &TransactionKind,
123            reference_gas_price: u64,
124            config: &ProtocolConfig,
125        ) -> Self {
126            match execution_gas_params(gas_data, kind, reference_gas_price, config) {
127                None => Self::new_unmetered(config),
128                Some((budget, price)) => Self::new(budget, price, reference_gas_price, config),
129            }
130        }
131
132        pub fn new_unmetered(config: &ProtocolConfig) -> Self {
133            // Same dispatch as `new`: v15+ uses gas_v3, everything older keeps gas_v2 so
134            // replay determinism holds.
135            if config.gas_model_version() >= 15 {
136                Self::V3(SuiGasStatusV3::new_unmetered())
137            } else {
138                Self::V2(SuiGasStatusV2::new_unmetered())
139            }
140        }
141    }
142
143    /// Budget and price a transaction is metered with, or `None` when it runs unmetered. Gasless
144    /// transactions are metered at the reference price up to the computation cap.
145    pub fn execution_gas_params(
146        gas_data: &GasData,
147        kind: &TransactionKind,
148        reference_gas_price: u64,
149        config: &ProtocolConfig,
150    ) -> Option<(u64, u64)> {
151        if gas_data.is_unmetered() || kind.is_system_tx() {
152            return None;
153        }
154        if config.enable_gasless() && is_gasless_transaction(gas_data, kind) {
155            let price = reference_gas_price.max(1);
156            let budget = config.gasless_max_computation_units().saturating_mul(price);
157            return Some((budget, price));
158        }
159        Some((gas_data.budget, gas_data.price))
160    }
161
162    /// Signing-time check of the gas price against the reference price and the maximum.
163    pub fn check_gas_price(
164        gas_price: u64,
165        reference_gas_price: u64,
166        config: &ProtocolConfig,
167    ) -> UserInputResult {
168        if gas_price < reference_gas_price {
169            return Err(UserInputError::GasPriceUnderRGP {
170                gas_price,
171                reference_gas_price,
172            });
173        }
174        if check_for_gas_price_too_high(config.gas_model_version())
175            && gas_price >= config.max_gas_price()
176        {
177            return Err(UserInputError::GasPriceTooHigh {
178                max_gas_price: config.max_gas_price(),
179            });
180        }
181        Ok(())
182    }
183
184    /// The smallest budget a transaction may sign for: the base transaction cost at the signed
185    /// price, or the flat base cost when `txn_base_cost_as_multiplier` is off.
186    pub fn minimum_gas_budget(config: &ProtocolConfig, gas_price: u64) -> u64 {
187        let base_tx_cost = config.base_tx_cost_fixed();
188        if txn_base_cost_as_multiplier(config) {
189            base_tx_cost
190                .checked_mul(gas_price)
191                .expect("base tx cost cannot overflow: gas_price is bounded by max_gas_price")
192        } else {
193            base_tx_cost
194        }
195    }
196
197    /// Signing-time check that the gas objects are address owned and that the budget is within
198    /// bounds and covered by them plus the address balance.
199    pub fn check_gas_budget_and_balance(
200        gas_objs: &[&ObjectReadResult],
201        gas_budget: u64,
202        gas_price: u64,
203        available_address_balance_gas: u64,
204        config: &ProtocolConfig,
205    ) -> UserInputResult {
206        check_gas_objects(gas_objs)?;
207        check_gas_data(
208            gas_objs,
209            gas_budget,
210            available_address_balance_gas,
211            minimum_gas_budget(config, gas_price),
212            config.max_tx_gas(),
213        )
214    }
215
216    /// Summary of the charges in a transaction.
217    /// Storage is charged independently of computation.
218    /// There are 3 parts to the storage charges:
219    /// `storage_cost`: it is the charge of storage at the time the transaction is executed.
220    ///                 The cost of storage is the number of bytes of the objects being mutated
221    ///                 multiplied by a variable storage cost per byte
222    /// `storage_rebate`: this is the amount a user gets back when manipulating an object.
223    ///                   The `storage_rebate` is the `storage_cost` for an object minus fees.
224    /// `non_refundable_storage_fee`: not all the value of the object storage cost is
225    ///                               given back to user and there is a small fraction that
226    ///                               is kept by the system. This value tracks that charge.
227    ///
228    /// When looking at a gas cost summary the amount charged to the user is
229    /// `computation_cost + storage_cost - storage_rebate`
230    /// and that is the amount that is deducted from the gas coins.
231    /// `non_refundable_storage_fee` is collected from the objects being mutated/deleted
232    /// and it is tracked by the system in storage funds.
233    ///
234    /// Objects deleted, including the older versions of objects mutated, have the storage field
235    /// on the objects added up to a pool of "potential rebate". This rebate then is reduced
236    /// by the "nonrefundable rate" such that:
237    /// `potential_rebate(storage cost of deleted/mutated objects) =
238    /// storage_rebate + non_refundable_storage_fee`
239
240    #[serde_as]
241    #[derive(Eq, PartialEq, Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
242    #[serde(rename_all = "camelCase")]
243    pub struct GasCostSummary {
244        /// Cost of computation/execution
245        #[schemars(with = "BigInt<u64>")]
246        #[serde_as(as = "Readable<BigInt<u64>, _>")]
247        pub computation_cost: u64,
248        /// Storage cost, it's the sum of all storage cost for all objects created or mutated.
249        #[schemars(with = "BigInt<u64>")]
250        #[serde_as(as = "Readable<BigInt<u64>, _>")]
251        pub storage_cost: u64,
252        /// The amount of storage cost refunded to the user for all objects deleted or mutated in the
253        /// transaction.
254        #[schemars(with = "BigInt<u64>")]
255        #[serde_as(as = "Readable<BigInt<u64>, _>")]
256        pub storage_rebate: u64,
257        /// The fee for the rebate. The portion of the storage rebate kept by the system.
258        #[schemars(with = "BigInt<u64>")]
259        #[serde_as(as = "Readable<BigInt<u64>, _>")]
260        pub non_refundable_storage_fee: u64,
261    }
262
263    impl GasCostSummary {
264        pub fn new(
265            computation_cost: u64,
266            storage_cost: u64,
267            storage_rebate: u64,
268            non_refundable_storage_fee: u64,
269        ) -> GasCostSummary {
270            GasCostSummary {
271                computation_cost,
272                storage_cost,
273                storage_rebate,
274                non_refundable_storage_fee,
275            }
276        }
277
278        pub fn gas_used(&self) -> u64 {
279            self.computation_cost.saturating_add(self.storage_cost)
280        }
281
282        /// Portion of the storage rebate that gets passed on to the transaction sender. The remainder
283        /// will be burned, then re-minted + added to the storage fund at the next epoch change
284        pub fn sender_rebate(&self, storage_rebate_rate: u64) -> u64 {
285            // we round storage rebate such that `>= x.5` goes to x+1 (rounds up) and
286            // `< x.5` goes to x (truncates). We replicate `f32/64::round()`
287            const BASIS_POINTS: u128 = 10000;
288            let rebate = (self.storage_rebate as u128)
289                .saturating_mul(storage_rebate_rate as u128)
290                .saturating_add(BASIS_POINTS / 2) // integer rounding adds half of the denominator
291                / BASIS_POINTS;
292            u64::try_from(rebate).unwrap_or(u64::MAX)
293        }
294
295        /// Get net gas usage, positive number means used gas; negative number means refund.
296        pub fn net_gas_usage(&self) -> i64 {
297            // Never i64::MIN: callers negate this value.
298            const MAX: i128 = i64::MAX as i128;
299            const MIN: i128 = -MAX;
300            let net = (self.computation_cost as i128)
301                .saturating_add(self.storage_cost as i128)
302                .saturating_sub(self.storage_rebate as i128);
303            i64::try_from(net.clamp(MIN, MAX)).unwrap_or(i64::MAX)
304        }
305
306        pub fn new_from_txn_effects<'a>(
307            transactions: impl Iterator<Item = &'a TransactionEffects>,
308        ) -> GasCostSummary {
309            let (storage_costs, computation_costs, storage_rebates, non_refundable_storage_fee): (
310                Vec<u64>,
311                Vec<u64>,
312                Vec<u64>,
313                Vec<u64>,
314            ) = transactions
315                .map(|e| {
316                    (
317                        e.gas_cost_summary().storage_cost,
318                        e.gas_cost_summary().computation_cost,
319                        e.gas_cost_summary().storage_rebate,
320                        e.gas_cost_summary().non_refundable_storage_fee,
321                    )
322                })
323                .multiunzip();
324
325            GasCostSummary {
326                storage_cost: storage_costs.iter().sum(),
327                computation_cost: computation_costs.iter().sum(),
328                storage_rebate: storage_rebates.iter().sum(),
329                non_refundable_storage_fee: non_refundable_storage_fee.iter().sum(),
330            }
331        }
332    }
333
334    impl std::fmt::Display for GasCostSummary {
335        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
336            write!(
337                f,
338                "computation_cost: {}, storage_cost: {},  storage_rebate: {}, non_refundable_storage_fee: {}",
339                self.computation_cost,
340                self.storage_cost,
341                self.storage_rebate,
342                self.non_refundable_storage_fee,
343            )
344        }
345    }
346
347    impl std::ops::AddAssign<&Self> for GasCostSummary {
348        fn add_assign(&mut self, other: &Self) {
349            self.computation_cost = self.computation_cost.saturating_add(other.computation_cost);
350            self.storage_cost = self.storage_cost.saturating_add(other.storage_cost);
351            self.storage_rebate = self.storage_rebate.saturating_add(other.storage_rebate);
352            self.non_refundable_storage_fee = self
353                .non_refundable_storage_fee
354                .saturating_add(other.non_refundable_storage_fee);
355        }
356    }
357
358    impl std::ops::AddAssign<Self> for GasCostSummary {
359        fn add_assign(&mut self, other: Self) {
360            self.add_assign(&other)
361        }
362    }
363
364    //
365    // Helper functions to deal with gas coins operations.
366    //
367
368    pub fn deduct_gas(gas_object: &mut Object, charge_or_rebate: i64) {
369        // The object must be a gas coin as we have checked in transaction handle phase.
370        let gas_coin = gas_object.data.try_as_move_mut().unwrap();
371        let balance = gas_coin.get_coin_value_unsafe();
372        let new_balance = if charge_or_rebate < 0 {
373            balance.saturating_add(charge_or_rebate.unsigned_abs())
374        } else {
375            let charge = charge_or_rebate.unsigned_abs();
376            assert!(balance >= charge);
377            balance.saturating_sub(charge)
378        };
379        gas_coin.set_coin_value_unsafe(new_balance)
380    }
381
382    pub fn get_gas_balance(gas_object: &Object) -> UserInputResult<u64> {
383        if let Some(move_obj) = gas_object.data.try_as_move() {
384            if !move_obj.type_().is_gas_coin() {
385                return Err(UserInputError::InvalidGasObject {
386                    object_id: gas_object.id(),
387                });
388            }
389            Ok(move_obj.get_coin_value_unsafe())
390        } else {
391            Err(UserInputError::InvalidGasObject {
392                object_id: gas_object.id(),
393            })
394        }
395    }
396}
397
398#[derive(Debug, Clone, Serialize, Deserialize)]
399pub struct GasUsageReport {
400    pub cost_summary: GasCostSummary,
401    pub gas_used: u64,
402    pub gas_budget: u64,
403    pub gas_price: u64,
404    pub reference_gas_price: u64,
405    pub storage_gas_price: u64,
406    pub rebate_rate: u64,
407    pub per_object_storage: Vec<(ObjectID, PerObjectStorage)>,
408}