From b9571311ba4d820abdf2c366feec64b77885a65b Mon Sep 17 00:00:00 2001
From: Joonatan Saarhelo <joon.saar@gmail.com>
Date: Wed, 8 May 2024 13:13:41 +0100
Subject: [PATCH] chore: clarify pubdata logic

---
 .../src/versions/vm_latest/oracles/storage.rs      | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/core/lib/multivm/src/versions/vm_latest/oracles/storage.rs b/core/lib/multivm/src/versions/vm_latest/oracles/storage.rs
index b2d8b3ccd728..389b4ac521b1 100644
--- a/core/lib/multivm/src/versions/vm_latest/oracles/storage.rs
+++ b/core/lib/multivm/src/versions/vm_latest/oracles/storage.rs
@@ -377,12 +377,14 @@ impl<S: WriteStorage, H: HistoryMode> VmStorageOracle for StorageOracle<S, H> {
         query.read_value = read_value;
 
         let pubdata_cost = if query.aux_byte == STORAGE_AUX_BYTE && query.rw_flag {
-            // It is considered that the user has paid for the whole base price for the writes
-            let to_pay_by_user = self.base_price_for_write_query(&query);
-            let prepaid = self.prepaid_for_write(&storage_key);
-
-            // Note, that the diff may be negative, e.g. in case the new write returns to the previous value.
-            let diff = (to_pay_by_user as i32) - (prepaid as i32);
+            let current_price = self.base_price_for_write_query(&query);
+            let previous_price = self.prepaid_for_write(&storage_key);
+
+            // Note, that the diff may be negative, e.g. in case the new write returns to the original value.
+            // The end result is that users pay as much pubdata in total as would have been required to set
+            // the slots to their final values.
+            // The only case where users overpay is when some transaction ends up with a negative pubdata total.
+            let diff = (current_price as i32) - (previous_price as i32);
 
             self.paid_changes.apply_historic_record(
                 HashMapHistoryEvent {