1pub use checked::*;
7
8#[iota_macros::with_checked_arithmetic]
9pub mod checked {
10
11 use std::collections::HashMap;
12
13 use enum_dispatch::enum_dispatch;
14 use iota_protocol_config::ProtocolConfig;
15 use iota_sdk_types::{GasCostSummary, GasPayment, ObjectReference, Transaction};
16
17 use crate::{
18 ObjectId,
19 error::{ExecutionError, IotaResult, UserInputError, UserInputResult},
20 gas_model::{
21 gas_v1::{IotaGasStatus as IotaGasStatusV1, min_transaction_cost},
22 tables::GasStatus,
23 },
24 object::{MoveStructExt, Object},
25 transaction::{InputObjects, ObjectReadResult, TransactionAPI},
26 };
27
28 #[enum_dispatch]
29 pub trait IotaGasStatusAPI {
30 fn is_unmetered(&self) -> bool;
31 fn move_gas_status(&self) -> &GasStatus;
32 fn move_gas_status_mut(&mut self) -> &mut GasStatus;
33 fn bucketize_computation(&mut self) -> Result<(), ExecutionError>;
34 fn summary(&self) -> GasCostSummary;
35 fn gas_budget(&self) -> u64;
36 fn gas_price(&self) -> u64;
37 fn reference_gas_price(&self) -> u64;
38 fn storage_gas_units(&self) -> u64;
39 fn storage_rebate(&self) -> u64;
40 fn unmetered_storage_rebate(&self) -> u64;
41 fn gas_used(&self) -> u64;
42 fn reset_storage_cost_and_rebate(&mut self);
43 fn charge_storage_read(&mut self, size: usize) -> Result<(), ExecutionError>;
44 fn charge_publish_package(&mut self, size: usize) -> Result<(), ExecutionError>;
45 fn track_storage_mutation(
46 &mut self,
47 object_id: ObjectId,
48 new_size: usize,
49 storage_rebate: u64,
50 ) -> u64;
51 fn charge_storage_and_rebate(&mut self) -> Result<(), ExecutionError>;
52 fn adjust_computation_on_out_of_gas(&mut self);
53 }
54
55 #[enum_dispatch(IotaGasStatusAPI)]
57 #[derive(Debug)]
58 pub enum IotaGasStatus {
59 V1(IotaGasStatusV1),
60 }
61
62 impl IotaGasStatus {
63 pub fn new(
64 gas_budget: u64,
65 gas_price: u64,
66 reference_gas_price: u64,
67 config: &ProtocolConfig,
68 ) -> IotaResult<Self> {
69 check_gas_price_bounds(gas_price, reference_gas_price, config)?;
70
71 Ok(Self::V1(IotaGasStatusV1::new_with_budget(
72 gas_budget,
73 gas_price,
74 reference_gas_price,
75 config,
76 )))
77 }
78
79 pub fn new_unmetered() -> Self {
80 Self::V1(IotaGasStatusV1::new_unmetered())
83 }
84
85 pub fn check_gas_balance(
92 &self,
93 gas_objs: &[&ObjectReadResult],
94 gas_budget: u64,
95 bounded_budget: bool,
96 ) -> UserInputResult {
97 match self {
98 Self::V1(status) => status.check_gas_balance(gas_objs, gas_budget, bounded_budget),
99 }
100 }
101 }
102
103 pub fn check_gas_bounds(
111 config: &ProtocolConfig,
112 reference_gas_price: u64,
113 gas_price: u64,
114 gas_budget: u64,
115 ) -> UserInputResult<()> {
116 check_gas_price_bounds(gas_price, reference_gas_price, config)?;
117 check_gas_budget_bounds(
118 gas_budget,
119 min_transaction_cost(config, gas_price),
120 config.max_tx_gas(),
121 )
122 }
123
124 pub(crate) fn check_gas_price_bounds(
127 gas_price: u64,
128 reference_gas_price: u64,
129 config: &ProtocolConfig,
130 ) -> UserInputResult<()> {
131 if gas_price < reference_gas_price {
132 return Err(UserInputError::GasPriceUnderRGP {
133 gas_price,
134 reference_gas_price,
135 });
136 }
137 if gas_price > config.max_gas_price() {
138 return Err(UserInputError::GasPriceTooHigh {
139 max_gas_price: config.max_gas_price(),
140 });
141 }
142 Ok(())
143 }
144
145 pub(crate) fn check_gas_budget_bounds(
147 gas_budget: u64,
148 min_budget: u64,
149 max_budget: u64,
150 ) -> UserInputResult<()> {
151 if gas_budget > max_budget {
152 return Err(UserInputError::GasBudgetTooHigh {
153 gas_budget,
154 max_budget,
155 });
156 }
157 if gas_budget < min_budget {
158 return Err(UserInputError::GasBudgetTooLow {
159 gas_budget,
160 min_budget,
161 });
162 }
163 Ok(())
164 }
165
166 pub fn deduct_gas(gas_object: &mut Object, charge_or_rebate: i64) {
169 let gas_coin = gas_object.data.as_opt_mut_struct().unwrap();
171 let balance = gas_coin.get_coin_value_unchecked();
172 let new_balance = if charge_or_rebate < 0 {
173 balance + (-charge_or_rebate as u64)
174 } else {
175 assert!(balance >= charge_or_rebate as u64);
176 balance - charge_or_rebate as u64
177 };
178 gas_coin.set_coin_value_unchecked(new_balance)
179 }
180
181 pub fn get_gas_balance(gas_object: &Object) -> UserInputResult<u64> {
182 if let Some(move_obj) = gas_object.data.as_opt_struct() {
183 if !move_obj.struct_tag().is_gas_coin() {
184 return Err(UserInputError::InvalidGasObject {
185 object_id: gas_object.id(),
186 });
187 }
188 Ok(move_obj.get_coin_value_unchecked())
189 } else {
190 Err(UserInputError::InvalidGasObject {
191 object_id: gas_object.id(),
192 })
193 }
194 }
195
196 pub fn fill_in_unset_simulation_gas(
200 transaction: &mut Transaction,
201 input_objects: &InputObjects,
202 reference_gas_price: u64,
203 protocol_config: &ProtocolConfig,
204 ) {
205 if transaction.gas_price() == 0 {
206 transaction.gas_data_mut().price = reference_gas_price;
207 }
208 if transaction.gas_budget() == 0 {
209 let min_gas_budget = protocol_config
210 .base_tx_cost_fixed()
211 .saturating_mul(transaction.gas_price());
212
213 let gas_balance = gas_coins_balance(input_objects, transaction.gas());
218
219 let budget = std::cmp::min(protocol_config.max_tx_gas() as u128, gas_balance)
224 .max(min_gas_budget as u128);
225
226 transaction.gas_data_mut().budget = budget as u64;
227 }
228 }
229
230 fn gas_coins_balance(input_objects: &InputObjects, gas: &[ObjectReference]) -> u128 {
233 let objects: HashMap<_, _> = input_objects
234 .iter()
235 .map(|object| (object.id(), object))
236 .collect();
237
238 gas.iter()
239 .filter_map(|gas_ref| objects.get(&gas_ref.object_id)?.as_object())
240 .filter_map(|object| get_gas_balance(object).ok())
241 .map(u128::from)
242 .sum()
243 }
244
245 pub fn report_simulation_gas(reported: &mut GasPayment, simulated: &GasPayment, gas_used: u64) {
257 let estimating = reported.budget == 0;
258 *reported = simulated.clone();
259 if estimating {
260 reported.budget = gas_used;
261 }
262 }
263}
264
265#[cfg(test)]
266#[path = "unit_tests/gas_tests.rs"]
267mod gas_tests;