sui_adapter_v1/
gas_charger.rs1pub use checked::*;
6
7#[sui_macros::with_checked_arithmetic]
8pub mod checked {
9
10 use crate::sui_types::gas::SuiGasStatusAPI;
11 use crate::temporary_store::TemporaryStore;
12 use sui_protocol_config::ProtocolConfig;
13 use sui_types::gas::{deduct_gas, GasCostSummary, SuiGasStatus};
14 use sui_types::gas_model::gas_predicates::{
15 charge_upgrades, dont_charge_budget_on_storage_oog,
16 };
17 use sui_types::{
18 base_types::{ObjectID, ObjectRef},
19 digests::TransactionDigest,
20 error::ExecutionError,
21 gas_model::tables::GasStatus,
22 is_system_package,
23 object::Data,
24 };
25 use tracing::trace;
26
27 #[derive(Debug)]
36 pub struct GasCharger {
37 tx_digest: TransactionDigest,
38 gas_model_version: u64,
39 gas_coins: Vec<ObjectRef>,
40 smashed_gas_coin: Option<ObjectID>,
43 gas_status: SuiGasStatus,
44 }
45
46 impl GasCharger {
47 pub fn new(
48 tx_digest: TransactionDigest,
49 gas_coins: Vec<ObjectRef>,
50 gas_status: SuiGasStatus,
51 protocol_config: &ProtocolConfig,
52 ) -> Self {
53 let gas_model_version = protocol_config.gas_model_version();
54 Self {
55 tx_digest,
56 gas_model_version,
57 gas_coins,
58 smashed_gas_coin: None,
59 gas_status,
60 }
61 }
62
63 pub fn new_unmetered(tx_digest: TransactionDigest) -> Self {
64 Self {
65 tx_digest,
66 gas_model_version: 6, gas_coins: vec![],
68 smashed_gas_coin: None,
69 gas_status: SuiGasStatus::new_unmetered(),
70 }
71 }
72
73 pub(crate) fn gas_coins(&self) -> &[ObjectRef] {
76 &self.gas_coins
77 }
78
79 pub fn gas_coin(&self) -> Option<ObjectID> {
82 self.smashed_gas_coin
83 }
84
85 pub fn gas_budget(&self) -> u64 {
86 self.gas_status.gas_budget()
87 }
88
89 pub fn unmetered_storage_rebate(&self) -> u64 {
90 self.gas_status.unmetered_storage_rebate()
91 }
92
93 pub fn no_charges(&self) -> bool {
94 self.gas_status.gas_used() == 0
95 && self.gas_status.storage_rebate() == 0
96 && self.gas_status.storage_gas_units() == 0
97 }
98
99 pub fn is_unmetered(&self) -> bool {
100 self.gas_status.is_unmetered()
101 }
102
103 pub fn move_gas_status(&self) -> &GasStatus {
104 self.gas_status.move_gas_status()
105 }
106
107 pub fn move_gas_status_mut(&mut self) -> &mut GasStatus {
108 self.gas_status.move_gas_status_mut()
109 }
110
111 pub fn into_gas_status(self) -> SuiGasStatus {
112 self.gas_status
113 }
114
115 pub fn summary(&self) -> GasCostSummary {
116 self.gas_status.summary()
117 }
118
119 pub fn smash_gas(&mut self, temporary_store: &mut TemporaryStore<'_>) {
127 let gas_coin_count = self.gas_coins.len();
128 if gas_coin_count == 0 || (gas_coin_count == 1 && self.gas_coins[0].0 == ObjectID::ZERO)
129 {
130 return; }
132 let gas_coin_id = self.gas_coins[0].0;
135 self.smashed_gas_coin = Some(gas_coin_id);
136 if gas_coin_count == 1 {
137 return;
138 }
139 let new_balance = self
141 .gas_coins
142 .iter()
143 .map(|obj_ref| {
144 let obj = temporary_store.objects().get(&obj_ref.0).unwrap();
145 let Data::Move(move_obj) = &obj.data else {
146 return Err(ExecutionError::invariant_violation(
147 "Provided non-gas coin object as input for gas!",
148 ));
149 };
150 if !move_obj.type_().is_gas_coin() {
151 return Err(ExecutionError::invariant_violation(
152 "Provided non-gas coin object as input for gas!",
153 ));
154 }
155 Ok(move_obj.get_coin_value_unsafe())
156 })
157 .collect::<Result<Vec<u64>, ExecutionError>>()
158 .unwrap_or_else(|_| {
161 panic!(
162 "Invariant violation: non-gas coin object as input for gas in txn {}",
163 self.tx_digest
164 )
165 })
166 .iter()
167 .sum();
168 let mut primary_gas_object = temporary_store
169 .objects()
170 .get(&gas_coin_id)
171 .unwrap_or_else(|| {
173 panic!(
174 "Invariant violation: gas coin not found in store in txn {}",
175 self.tx_digest
176 )
177 })
178 .clone();
179 for (id, _version, _digest) in &self.gas_coins[1..] {
181 debug_assert_ne!(*id, primary_gas_object.id());
182 temporary_store.delete_input_object(id);
183 }
184 primary_gas_object
185 .data
186 .try_as_move_mut()
187 .unwrap_or_else(|| {
189 panic!(
190 "Invariant violation: invalid coin object in txn {}",
191 self.tx_digest
192 )
193 })
194 .set_coin_value_unsafe(new_balance);
195 temporary_store.mutate_input_object(primary_gas_object);
196 }
197
198 pub fn track_storage_mutation(
203 &mut self,
204 object_id: ObjectID,
205 new_size: usize,
206 storage_rebate: u64,
207 ) -> u64 {
208 self.gas_status
209 .track_storage_mutation(object_id, new_size, storage_rebate)
210 }
211
212 pub fn reset_storage_cost_and_rebate(&mut self) {
213 self.gas_status.reset_storage_cost_and_rebate();
214 }
215
216 pub fn charge_publish_package(&mut self, size: usize) -> Result<(), ExecutionError> {
217 self.gas_status.charge_publish_package(size)
218 }
219
220 pub fn charge_upgrade_package(&mut self, size: usize) -> Result<(), ExecutionError> {
221 if charge_upgrades(self.gas_model_version) {
222 self.gas_status.charge_publish_package(size)
223 } else {
224 Ok(())
225 }
226 }
227
228 pub fn charge_input_objects(
229 &mut self,
230 temporary_store: &TemporaryStore<'_>,
231 ) -> Result<(), ExecutionError> {
232 let objects = temporary_store.objects();
233 let _object_count = objects.len();
235 let total_size = temporary_store
237 .objects()
238 .iter()
239 .filter(|(id, _)| !is_system_package(**id))
241 .map(|(_, obj)| obj.object_size_for_gas_metering())
242 .sum();
243 self.gas_status.charge_storage_read(total_size)
244 }
245
246 pub fn reset(&mut self, temporary_store: &mut TemporaryStore<'_>) {
249 temporary_store.drop_writes();
250 self.gas_status.reset_storage_cost_and_rebate();
251 self.smash_gas(temporary_store);
252 }
253
254 pub fn charge_gas<T>(
265 &mut self,
266 temporary_store: &mut TemporaryStore<'_>,
267 execution_result: &mut Result<T, ExecutionError>,
268 ) -> GasCostSummary {
269 debug_assert!(self.gas_status.storage_rebate() == 0);
272 debug_assert!(self.gas_status.storage_gas_units() == 0);
273
274 if self.smashed_gas_coin.is_some() {
275 if let Err(err) = self.gas_status.bucketize_computation(None) {
277 if execution_result.is_ok() {
278 *execution_result = Err(err);
279 }
280 }
281
282 if execution_result.is_err() {
284 self.reset(temporary_store);
285 }
286 }
287
288 temporary_store.ensure_active_inputs_mutated();
290 temporary_store.collect_storage_and_rebate(self);
291
292 if self.smashed_gas_coin.is_some() {
293 #[skip_checked_arithmetic]
294 trace!(target: "replay_gas_info", "Gas smashing has occurred for this transaction");
295 }
296
297 if let Some(gas_object_id) = self.smashed_gas_coin {
300 if dont_charge_budget_on_storage_oog(self.gas_model_version) {
301 self.handle_storage_and_rebate_v2(temporary_store, execution_result)
302 } else {
303 self.handle_storage_and_rebate_v1(temporary_store, execution_result)
304 }
305
306 let cost_summary = self.gas_status.summary();
307 let gas_used = cost_summary.net_gas_usage();
308
309 let mut gas_object = temporary_store.read_object(&gas_object_id).unwrap().clone();
310 deduct_gas(&mut gas_object, gas_used);
311 #[skip_checked_arithmetic]
312 trace!(gas_used, gas_obj_id =? gas_object.id(), gas_obj_ver =? gas_object.version(), "Updated gas object");
313
314 temporary_store.mutate_input_object(gas_object);
315 cost_summary
316 } else {
317 GasCostSummary::default()
318 }
319 }
320
321 fn handle_storage_and_rebate_v1<T>(
322 &mut self,
323 temporary_store: &mut TemporaryStore<'_>,
324 execution_result: &mut Result<T, ExecutionError>,
325 ) {
326 if let Err(err) = self.gas_status.charge_storage_and_rebate() {
327 self.reset(temporary_store);
328 self.gas_status.adjust_computation_on_out_of_gas();
329 temporary_store.ensure_active_inputs_mutated();
330 temporary_store.collect_rebate(self);
331 if execution_result.is_ok() {
332 *execution_result = Err(err);
333 }
334 }
335 }
336
337 fn handle_storage_and_rebate_v2<T>(
338 &mut self,
339 temporary_store: &mut TemporaryStore<'_>,
340 execution_result: &mut Result<T, ExecutionError>,
341 ) {
342 if let Err(err) = self.gas_status.charge_storage_and_rebate() {
343 self.reset(temporary_store);
346 temporary_store.ensure_active_inputs_mutated();
347 temporary_store.collect_storage_and_rebate(self);
348 if let Err(err) = self.gas_status.charge_storage_and_rebate() {
349 self.reset(temporary_store);
352 self.gas_status.adjust_computation_on_out_of_gas();
353 temporary_store.ensure_active_inputs_mutated();
354 temporary_store.collect_rebate(self);
355 if execution_result.is_ok() {
356 *execution_result = Err(err);
357 }
358 } else if execution_result.is_ok() {
359 *execution_result = Err(err);
360 }
361 }
362 }
363 }
364}