Skip to content

Commit a5d62f6

Browse files
committed
Add gas cost
1 parent 4b2f923 commit a5d62f6

File tree

4 files changed

+196
-73
lines changed

4 files changed

+196
-73
lines changed

packages/vm/src/environment.rs

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ pub struct GasConfig {
5555
pub bls12_381_hash_to_g2_cost: u64,
5656
/// bls12-381 pairing equality check cost
5757
pub bls12_381_pairing_equality_cost: LinearGasCost,
58+
/// cost for reading memory regions <= 8MB
59+
pub read_region_small_cost: LinearGasCost,
60+
/// cost for reading memory regions > 8MB
61+
pub read_region_large_cost: LinearGasCost,
62+
/// cost for validating bytes into a String
63+
pub string_from_bytes_cost: LinearGasCost,
64+
/// cost for calling a host function
65+
pub host_call_cost: u64,
5866
}
5967

6068
impl Default for GasConfig {
@@ -97,6 +105,30 @@ impl Default for GasConfig {
97105
base: 2112 * GAS_PER_US,
98106
per_item: 163 * GAS_PER_US,
99107
},
108+
read_region_small_cost: LinearGasCost {
109+
base: 200000,
110+
per_item: 115,
111+
},
112+
read_region_large_cost: LinearGasCost {
113+
base: 0,
114+
per_item: 520,
115+
},
116+
string_from_bytes_cost: LinearGasCost {
117+
base: 28700,
118+
per_item: 1400,
119+
},
120+
host_call_cost: 18000,
121+
}
122+
}
123+
}
124+
125+
impl GasConfig {
126+
pub fn read_region_cost(&self, bytes: usize) -> VmResult<u64> {
127+
const THRESHOLD: usize = 8 * 1000 * 1000;
128+
if bytes <= THRESHOLD {
129+
self.read_region_small_cost.total_cost(bytes as u64)
130+
} else {
131+
self.read_region_large_cost.total_cost(bytes as u64)
100132
}
101133
}
102134
}
@@ -115,8 +147,13 @@ pub struct LinearGasCost {
115147
}
116148

117149
impl LinearGasCost {
118-
pub fn total_cost(&self, items: u64) -> u64 {
119-
self.base + self.per_item * items
150+
pub fn total_cost(&self, items: u64) -> VmResult<u64> {
151+
self.total_cost_opt(items)
152+
.ok_or_else(VmError::gas_depletion)
153+
}
154+
155+
fn total_cost_opt(&self, items: u64) -> Option<u64> {
156+
self.base.checked_add(self.per_item.checked_mul(items)?)
120157
}
121158
}
122159

0 commit comments

Comments
 (0)