Skip to content

Commit a575ba1

Browse files
committed
Merge branch 'grarco/better-gas-interface' (#3428)
* origin/grarco/better-gas-interface: Logs tx used gas Increases masp gas limit in genesis files and removes custom setup in integration tests update Hermes Returns `WholeGas` from `dry_run_tx` Adds conversion from `WholeGas` to `GasLimit` Updates gas in ibc e2e test Fixes gas payment in masp integration tests Updates gas limit in unit tests Changelog #3428 Changelog #3428 Removes misleading gas message Fixes ibc e2e test Fixes unit tests Clippy + fmt Compacts `BatchResults` into `TxResult` Remove gas from `TxResult`. Adjusts dry run result Reduces gas scale param in genesis Introduces `WholeGas` type
2 parents f77a23e + 209da0c commit a575ba1

File tree

27 files changed

+339
-338
lines changed

27 files changed

+339
-338
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
- Improved the interface of the gas type. Removed the duplicated gas used from
2+
events. ([\#3428](https://github.com/anoma/namada/pull/3428))
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1.9.0-namada-beta13-rc2
1+
1.9.0-namada-beta14-rc

crates/gas/src/event.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
33
use namada_events::extend::EventAttributeEntry;
44

5-
use super::Gas;
5+
use crate::WholeGas;
66

77
/// Extend an [`namada_events::Event`] with gas used data.
8-
pub struct GasUsed(pub Gas);
8+
pub struct GasUsed(pub WholeGas);
99

1010
impl EventAttributeEntry<'static> for GasUsed {
11-
type Value = Gas;
11+
type Value = WholeGas;
1212
type ValueOwned = Self::Value;
1313

1414
const KEY: &'static str = "gas_used";

crates/gas/src/lib.rs

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,10 @@ pub const MASP_PARALLEL_GAS_DIVIDER: u64 = PARALLEL_GAS_DIVIDER / 2;
116116
/// Gas module result for functions that may fail
117117
pub type Result<T> = std::result::Result<T, Error>;
118118

119-
/// Representation of gas in sub-units. This effectively decouples gas metering
120-
/// from fee payment, allowing higher resolution when accounting for gas while,
121-
/// at the same time, providing a contained gas value when paying fees.
119+
/// Representation of tracking gas in sub-units. This effectively decouples gas
120+
/// metering from fee payment, allowing higher resolution when accounting for
121+
/// gas while, at the same time, providing a contained gas value when paying
122+
/// fees.
122123
#[derive(
123124
Clone,
124125
Copy,
@@ -154,8 +155,8 @@ impl Gas {
154155
}
155156

156157
/// Converts the sub gas units to whole ones. If the sub units are not a
157-
/// multiple of the `SCALE` than ceil the quotient
158-
pub fn get_whole_gas_units(&self, scale: u64) -> u64 {
158+
/// multiple of the scale than ceil the quotient
159+
pub fn get_whole_gas_units(&self, scale: u64) -> WholeGas {
159160
let quotient = self
160161
.sub
161162
.checked_div(scale)
@@ -166,18 +167,18 @@ impl Gas {
166167
.expect("Gas quotient remainder should not overflow")
167168
== 0
168169
{
169-
quotient
170+
quotient.into()
170171
} else {
171172
quotient
172173
.checked_add(1)
173174
.expect("Cannot overflow as the quotient is scaled down u64")
175+
.into()
174176
}
175177
}
176178

177-
/// Generates a `Gas` instance from a whole amount
178-
pub fn from_whole_units(whole: u64, scale: u64) -> Option<Self> {
179-
let sub = whole.checked_mul(scale)?;
180-
Some(Self { sub })
179+
/// Generates a `Gas` instance from a `WholeGas` amount
180+
pub fn from_whole_units(whole: WholeGas, scale: u64) -> Option<Self> {
181+
scale.checked_mul(whole.into()).map(|sub| Self { sub })
181182
}
182183
}
183184

@@ -193,20 +194,46 @@ impl From<Gas> for u64 {
193194
}
194195
}
195196

196-
impl Display for Gas {
197-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198-
// Need to do this now that the gas scale is a parameter. Should
199-
// manually scale gas first before calling this
200-
write!(f, "{}", self.sub)
197+
/// Gas represented in whole units. Used for fee payment and to display
198+
/// information to the user.
199+
#[derive(
200+
Debug,
201+
Clone,
202+
Copy,
203+
PartialEq,
204+
BorshSerialize,
205+
BorshDeserialize,
206+
BorshDeserializer,
207+
BorshSchema,
208+
Serialize,
209+
Deserialize,
210+
Eq,
211+
)]
212+
pub struct WholeGas(u64);
213+
214+
impl From<u64> for WholeGas {
215+
fn from(amount: u64) -> WholeGas {
216+
Self(amount)
201217
}
202218
}
203219

204-
impl FromStr for Gas {
220+
impl From<WholeGas> for u64 {
221+
fn from(whole: WholeGas) -> u64 {
222+
whole.0
223+
}
224+
}
225+
226+
impl FromStr for WholeGas {
205227
type Err = GasParseError;
206228

207229
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
208-
let raw: u64 = s.parse().map_err(GasParseError::Parse)?;
209-
Ok(Self { sub: raw })
230+
Ok(Self(s.parse().map_err(GasParseError::Parse)?))
231+
}
232+
}
233+
234+
impl Display for WholeGas {
235+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236+
write!(f, "{}", self.0)
210237
}
211238
}
212239

crates/light_sdk/src/reading/asynchronous/tx.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use namada_sdk::events::Event;
22
use namada_sdk::rpc::{TxEventQuery, TxResponse};
3-
use namada_sdk::tx::data::TxResult;
3+
use namada_sdk::tx::data::DryRunResult;
44

55
use super::*;
66

@@ -25,7 +25,7 @@ pub async fn query_tx_events(
2525
pub async fn dry_run_tx(
2626
tendermint_addr: &str,
2727
tx_bytes: Vec<u8>,
28-
) -> Result<TxResult<String>, Error> {
28+
) -> Result<DryRunResult, Error> {
2929
let client = HttpClient::new(
3030
TendermintAddress::from_str(tendermint_addr)
3131
.map_err(|e| Error::Other(e.to_string()))?,

crates/light_sdk/src/reading/blocking/tx.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ pub fn query_tx_events(
2626
pub fn dry_run_tx(
2727
tendermint_addr: &str,
2828
tx_bytes: Vec<u8>,
29-
) -> Result<TxResult, Error> {
29+
) -> Result<DryRunResult, Error> {
3030
let client = HttpClient::new(
3131
TendermintAddress::from_str(tendermint_addr)
3232
.map_err(|e| Error::Other(e.to_string()))?,

crates/namada/src/ledger/mod.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ mod dry_run_tx {
2525

2626
use namada_sdk::queries::{EncodedResponseQuery, RequestCtx, RequestQuery};
2727
use namada_state::{DBIter, ResultExt, StorageHasher, DB};
28-
use namada_tx::data::{ExtendedTxResult, GasLimit, TxResult};
28+
use namada_tx::data::{DryRunResult, ExtendedTxResult, GasLimit, TxResult};
2929

3030
use super::protocol;
3131
use crate::vm::wasm::{TxCache, VpCache};
@@ -132,18 +132,22 @@ mod dry_run_tx {
132132
} else {
133133
temp_state.write_log_mut().drop_tx();
134134
}
135-
tx_result.batch_results.insert_inner_tx_result(
135+
tx_result.insert_inner_tx_result(
136136
wrapper_hash.as_ref(),
137137
either::Right(cmt),
138138
batched_tx_result,
139139
);
140140
}
141141
// Account gas for both batch and wrapper
142-
tx_result.gas_used = tx_gas_meter.borrow().get_tx_consumed_gas();
142+
let gas_used = tx_gas_meter
143+
.borrow()
144+
.get_tx_consumed_gas()
145+
.get_whole_gas_units(gas_scale);
143146
let tx_result_string = tx_result.to_result_string();
144-
let data = tx_result_string.serialize_to_vec();
147+
let dry_run_result = DryRunResult(tx_result_string, gas_used);
148+
145149
Ok(EncodedResponseQuery {
146-
data,
150+
data: dry_run_result.serialize_to_vec(),
147151
proof: None,
148152
info: Default::default(),
149153
height: ctx.state.in_mem().get_last_block_height(),
@@ -331,7 +335,7 @@ mod test {
331335
assert!(
332336
result
333337
.data
334-
.batch_results
338+
.0
335339
.get_inner_tx_result(None, either::Right(cmt))
336340
.unwrap()
337341
.as_ref()

crates/namada/src/ledger/protocol/mod.rs

Lines changed: 32 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ use namada_token::utils::is_masp_transfer;
1919
use namada_tx::action::Read;
2020
use namada_tx::data::protocol::{ProtocolTx, ProtocolTxType};
2121
use namada_tx::data::{
22-
BatchResults, BatchedTxResult, ExtendedTxResult, TxResult, VpStatusFlags,
23-
VpsResult, WrapperTx,
22+
BatchedTxResult, ExtendedTxResult, TxResult, VpStatusFlags, VpsResult,
23+
WrapperTx,
2424
};
2525
use namada_tx::{BatchedTxRef, Tx, TxCommitments};
2626
use namada_vote_ext::EthereumTxData;
@@ -275,17 +275,14 @@ where
275275
},
276276
)?;
277277

278-
Ok(TxResult {
279-
gas_used: tx_gas_meter.borrow().get_tx_consumed_gas(),
280-
batch_results: {
281-
let mut batch_results = BatchResults::new();
282-
batch_results.insert_inner_tx_result(
283-
wrapper_hash,
284-
either::Right(cmt),
285-
Ok(batched_tx_result),
286-
);
287-
batch_results
288-
},
278+
Ok({
279+
let mut batch_results = TxResult::new();
280+
batch_results.insert_inner_tx_result(
281+
wrapper_hash,
282+
either::Right(cmt),
283+
Ok(batched_tx_result),
284+
);
285+
batch_results
289286
}
290287
.to_extended_result(None))
291288
}
@@ -296,17 +293,14 @@ where
296293
let batched_tx_result =
297294
apply_protocol_tx(protocol_tx.tx, tx.data(cmt), state)?;
298295

299-
Ok(TxResult {
300-
batch_results: {
301-
let mut batch_results = BatchResults::new();
302-
batch_results.insert_inner_tx_result(
303-
None,
304-
either::Right(cmt),
305-
Ok(batched_tx_result),
306-
);
307-
batch_results
308-
},
309-
..Default::default()
296+
Ok({
297+
let mut batch_results = TxResult::new();
298+
batch_results.insert_inner_tx_result(
299+
None,
300+
either::Right(cmt),
301+
Ok(batched_tx_result),
302+
);
303+
batch_results
310304
}
311305
.to_extended_result(None))
312306
}
@@ -382,16 +376,11 @@ where
382376
) {
383377
Err(Error::GasError(ref msg)) => {
384378
// Gas error aborts the execution of the entire batch
385-
extended_tx_result.tx_result.gas_used =
386-
tx_gas_meter.borrow().get_tx_consumed_gas();
387-
extended_tx_result
388-
.tx_result
389-
.batch_results
390-
.insert_inner_tx_result(
391-
wrapper_hash,
392-
either::Right(cmt),
393-
Err(Error::GasError(msg.to_owned())),
394-
);
379+
extended_tx_result.tx_result.insert_inner_tx_result(
380+
wrapper_hash,
381+
either::Right(cmt),
382+
Err(Error::GasError(msg.to_owned())),
383+
);
395384
state.write_log_mut().drop_tx();
396385
return Err(DispatchError {
397386
error: Error::GasError(msg.to_owned()),
@@ -402,16 +391,11 @@ where
402391
let is_accepted =
403392
matches!(&res, Ok(result) if result.is_accepted());
404393

405-
extended_tx_result
406-
.tx_result
407-
.batch_results
408-
.insert_inner_tx_result(
409-
wrapper_hash,
410-
either::Right(cmt),
411-
res,
412-
);
413-
extended_tx_result.tx_result.gas_used =
414-
tx_gas_meter.borrow().get_tx_consumed_gas();
394+
extended_tx_result.tx_result.insert_inner_tx_result(
395+
wrapper_hash,
396+
either::Right(cmt),
397+
res,
398+
);
415399
if is_accepted {
416400
// If the transaction was a masp one append the
417401
// transaction refs for the events
@@ -488,9 +472,9 @@ where
488472
shell_params.state.write_log_mut().commit_batch();
489473

490474
let (batch_results, masp_tx_refs) = payment_result.map_or_else(
491-
|| (BatchResults::default(), None),
475+
|| (TxResult::default(), None),
492476
|(batched_result, masp_section_ref)| {
493-
let mut batch = BatchResults::default();
477+
let mut batch = TxResult::default();
494478
batch.insert_inner_tx_result(
495479
// Ok to unwrap cause if we have a batched result it means
496480
// we've executed the first tx in the batch
@@ -508,11 +492,7 @@ where
508492
.add_wrapper_gas(tx_bytes)
509493
.map_err(|err| Error::GasError(err.to_string()))?;
510494

511-
Ok(TxResult {
512-
gas_used: tx_gas_meter.borrow().get_tx_consumed_gas(),
513-
batch_results,
514-
}
515-
.to_extended_result(masp_tx_refs))
495+
Ok(batch_results.to_extended_result(masp_tx_refs))
516496
}
517497

518498
/// Perform the actual transfer of fees from the fee payer to the block
@@ -702,7 +682,7 @@ where
702682
let gas_scale = get_gas_scale(&**state).map_err(Error::StorageError)?;
703683

704684
let mut gas_meter = TxGasMeter::new(
705-
namada_gas::Gas::from_whole_units(max_gas_limit, gas_scale)
685+
namada_gas::Gas::from_whole_units(max_gas_limit.into(), gas_scale)
706686
.ok_or_else(|| {
707687
Error::GasError("Overflow in gas expansion".to_string())
708688
})?,

crates/node/src/bench_utils.rs

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,7 @@ use namada::masp::MaspTxRefs;
7777
use namada::state::StorageRead;
7878
use namada::token::{Amount, DenominatedAmount, Transfer};
7979
use namada::tx::data::pos::Bond;
80-
use namada::tx::data::{
81-
BatchResults, BatchedTxResult, Fee, TxResult, VpsResult,
82-
};
80+
use namada::tx::data::{BatchedTxResult, Fee, TxResult, VpsResult};
8381
use namada::tx::event::{new_tx_event, Batch};
8482
use namada::tx::{
8583
Authorization, BatchedTx, BatchedTxRef, Code, Data, Section, Tx,
@@ -919,24 +917,19 @@ impl Client for BenchShell {
919917
.iter()
920918
.enumerate()
921919
.map(|(idx, (tx, changed_keys))| {
922-
let tx_result = TxResult::<String> {
923-
gas_used: 0.into(),
924-
batch_results: {
925-
let mut batch_results = BatchResults::new();
926-
batch_results.insert_inner_tx_result(
927-
tx.wrapper_hash().as_ref(),
928-
either::Right(
929-
tx.first_commitments().unwrap(),
930-
),
931-
Ok(BatchedTxResult {
932-
changed_keys: changed_keys.to_owned(),
933-
vps_result: VpsResult::default(),
934-
initialized_accounts: vec![],
935-
events: BTreeSet::default(),
936-
}),
937-
);
938-
batch_results
939-
},
920+
let tx_result = {
921+
let mut batch_results = TxResult::new();
922+
batch_results.insert_inner_tx_result(
923+
tx.wrapper_hash().as_ref(),
924+
either::Right(tx.first_commitments().unwrap()),
925+
Ok(BatchedTxResult {
926+
changed_keys: changed_keys.to_owned(),
927+
vps_result: VpsResult::default(),
928+
initialized_accounts: vec![],
929+
events: BTreeSet::default(),
930+
}),
931+
);
932+
batch_results
940933
};
941934
let event: Event = new_tx_event(tx, height.value())
942935
.with(Batch(&tx_result))

0 commit comments

Comments
 (0)