Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add state override for gas estimates #1358

Merged
merged 49 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
cff1757
feat: add state override for gas estimates
aon Mar 5, 2024
9b68b44
Merge branch 'main' into aon-add-override-estimate-gas-tracer
aon Mar 5, 2024
77f8d21
chore: run zk format
aon Mar 5, 2024
e2ad0f4
fix: change state overrides to use storage_view
aon Mar 6, 2024
aa58304
feat: improve `StateOverride` with custom serializer
aon Mar 7, 2024
0327102
fix: remove pub from hashmap
aon Mar 7, 2024
9f9e328
feat: add storage overrides struct
aon Mar 11, 2024
df87370
fix: read value on overrided state
aon Mar 11, 2024
c0b37c4
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 12, 2024
d1bee52
minor changes
Mar 12, 2024
dbab472
Merge branch 'aon-add-override-estimate-gas-tracer' of github.com:mat…
Mar 12, 2024
671689c
create new state_override file and add tests
Mar 13, 2024
0335fb2
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 14, 2024
a640cee
linter and spellcheck
Mar 14, 2024
f6db295
Merge branch 'aon-add-override-estimate-gas-tracer' of github.com:mat…
Mar 14, 2024
1a39ddd
Cargo lock
Mar 14, 2024
2deec8c
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 14, 2024
f62e51e
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 15, 2024
31384e4
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 15, 2024
dbc177e
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 18, 2024
c32cf4f
fix merge conflicts
Jun 6, 2024
5c56d18
zk fmt
Jun 6, 2024
93aa395
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jun 6, 2024
945946f
Revert submodule update to match main
Jun 6, 2024
da57e99
contracts
Jun 6, 2024
fd8af63
fix CI
Jun 10, 2024
f6ee13d
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 10, 2024
7182490
change test function signature
Jun 10, 2024
422e69f
merge with main
Jun 13, 2024
b8b663f
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 17, 2024
4ac87e0
Move StorageOverrides inside StorageView
Jun 19, 2024
f4c0189
Apply earlier the storageOverrides
Jun 19, 2024
f023a17
fix spelling
Jun 19, 2024
8ec5256
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 24, 2024
20932d4
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 27, 2024
4fee27a
storageview implement overrideStorage trait
Jun 28, 2024
299f3f0
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 28, 2024
bc4b245
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Deniallugo Jul 1, 2024
9479f03
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jul 1, 2024
157577b
add logic for stateDiff and State with tests, and added state_overrid…
Jul 1, 2024
9649f59
remove toml
Jul 1, 2024
5cb963e
outdated comment
Jul 2, 2024
241991e
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jul 2, 2024
a0627cb
add logic for testing stateDiff and State differences and fix nits
Jul 11, 2024
33a83c8
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jul 11, 2024
cf7b8cb
fix error on merge
Jul 12, 2024
b074154
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jul 16, 2024
3685e54
fix tests
Jul 17, 2024
3d3c469
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jul 22, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions core/lib/types/src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use strum::Display;
Expand Down Expand Up @@ -733,3 +735,17 @@ pub struct Proof {
pub address: Address,
pub storage_proof: Vec<StorageProof>,
}

/// Collection of overridden accounts, useful for `eth_estimateGas`.
pub type StateOverride = HashMap<Address, OverrideAccount>;

/// Account override for `eth_estimateGas`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OverrideAccount {
aon marked this conversation as resolved.
Show resolved Hide resolved
pub balance: Option<U256>,
pub nonce: Option<U256>,
pub code: Option<Bytes>,
pub state: Option<HashMap<H256, H256>>,
pub state_diff: Option<HashMap<H256, H256>>,
}
9 changes: 7 additions & 2 deletions core/lib/web3_decl/src/namespaces/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use jsonrpsee::{
proc_macros::rpc,
};
use zksync_types::{
api::{BlockId, BlockIdVariant, BlockNumber, Transaction, TransactionVariant},
api::{BlockId, BlockIdVariant, BlockNumber, StateOverride, Transaction, TransactionVariant},
transaction_request::CallRequest,
Address, H256,
};
Expand Down Expand Up @@ -36,7 +36,12 @@ pub trait EthNamespace {
async fn call(&self, req: CallRequest, block: Option<BlockIdVariant>) -> RpcResult<Bytes>;

#[method(name = "estimateGas")]
async fn estimate_gas(&self, req: CallRequest, _block: Option<BlockNumber>) -> RpcResult<U256>;
async fn estimate_gas(
&self,
req: CallRequest,
_block: Option<BlockNumber>,
state_override: Option<StateOverride>,
) -> RpcResult<U256>;

#[method(name = "gasPrice")]
async fn gas_price(&self) -> RpcResult<U256>;
Expand Down
149 changes: 143 additions & 6 deletions core/lib/zksync_core/src/api_server/tx_sender/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
//! Helper module to submit transactions into the zkSync Network.

use std::{cmp, sync::Arc, time::Instant};
use std::{cmp, collections::HashMap, sync::Arc, time::Instant};

use anyhow::Context as _;
use itertools::Itertools;
use multivm::{
interface::VmExecutionResultAndLogs,
utils::{adjust_pubdata_price_for_tx, derive_base_fee_and_gas_per_pubdata, derive_overhead},
Expand All @@ -13,17 +14,18 @@ use zksync_contracts::BaseSystemContracts;
use zksync_dal::{transactions_dal::L2TxSubmissionResult, ConnectionPool, StorageProcessor};
use zksync_state::PostgresStorageCaches;
use zksync_types::{
api::StateOverride,
fee::{Fee, TransactionExecutionMetrics},
fee_model::BatchFeeInput,
get_code_key, get_intrinsic_constants,
get_code_key, get_intrinsic_constants, get_nonce_key,
l1::is_l1_tx_type,
l2::{error::TxCheckError::TxDuplication, L2Tx},
utils::storage_key_for_eth_balance,
utils::{decompose_full_nonce, nonces_to_full_nonce, storage_key_for_eth_balance},
AccountTreeId, Address, ExecuteTransactionCommon, L2ChainId, MiniblockNumber, Nonce,
PackedEthSignature, ProtocolVersionId, Transaction, VmVersion, H160, H256, MAX_L2_TX_GAS_LIMIT,
MAX_NEW_FACTORY_DEPS, U256,
PackedEthSignature, ProtocolVersionId, StorageKey, StorageLog, Transaction, VmVersion, H160,
H256, MAX_L2_TX_GAS_LIMIT, MAX_NEW_FACTORY_DEPS, U256,
};
use zksync_utils::h256_to_u256;
use zksync_utils::{bytecode::hash_bytecode, h256_to_u256, u256_to_h256};

pub(super) use self::result::SubmitTxError;
use self::tx_sink::TxSink;
Expand Down Expand Up @@ -629,6 +631,7 @@ impl TxSender {
mut tx: Transaction,
estimated_fee_scale_factor: f64,
acceptable_overestimation: u32,
state_override: Option<StateOverride>,
aon marked this conversation as resolved.
Show resolved Hide resolved
) -> Result<Fee, SubmitTxError> {
let estimation_started_at = Instant::now();

Expand Down Expand Up @@ -690,6 +693,140 @@ impl TxSender {
)
})?;

if let Some(overrides) = &state_override {
for (account, overrides) in overrides {
if overrides.state.is_some() && overrides.state_diff.is_some() {
return Err(SubmitTxError::Unexecutable(
"state and stateDiff are mutually exclusive".to_string(),
aon marked this conversation as resolved.
Show resolved Hide resolved
));
}

if let Some(balance) = overrides.balance {
let balance_key = storage_key_for_eth_balance(account);
let log = StorageLog::new_write_log(balance_key, u256_to_h256(balance));
self.acquire_replica_connection()
.await?
.storage_logs_dal()
.append_storage_logs(
block_args.resolved_block_number(),
&[(H256::zero(), vec![log])],
)
.await
.map_err(|err| SubmitTxError::Internal(err.into()))?;
}

if let Some(nonce) = overrides.nonce {
let nonce_key = get_nonce_key(account);
let mut connection = self.acquire_replica_connection().await?;

let full_nonce = connection
.storage_web3_dal()
.get_value(&nonce_key)
.await
.map_err(|err| SubmitTxError::Internal(err.into()))?;
let (_, deployment_nonce) = decompose_full_nonce(h256_to_u256(full_nonce));
let new_full_nonce = nonces_to_full_nonce(nonce, deployment_nonce);

let log = StorageLog::new_write_log(nonce_key, u256_to_h256(new_full_nonce));
connection
.storage_logs_dal()
.append_storage_logs(
block_args.resolved_block_number(),
&[(H256::zero(), vec![log])],
)
.await
.map_err(|err| SubmitTxError::Internal(err.into()))?;
}

if let Some(code) = &overrides.code {
let code_key = get_code_key(account);
let code_hash = hash_bytecode(&code.0);

let mut connection = self.acquire_replica_connection().await?;

let log = StorageLog::new_write_log(code_key, code_hash);
connection
.storage_logs_dal()
.append_storage_logs(
block_args.resolved_block_number(),
&[(H256::zero(), vec![log])],
)
.await
.map_err(|err| SubmitTxError::Internal(err.into()))?;
connection
.factory_deps_dal()
.insert_factory_deps(
block_args.resolved_block_number(),
&HashMap::from_iter(vec![(code_hash, code.0.clone())]),
)
.await
.map_err(|err| SubmitTxError::Internal(err.into()))?;
}

if let Some(state) = &overrides.state {
let mut connection = self.acquire_replica_connection().await?;

// First find storage keys to clear
let keys_to_clear = connection
.storage_logs_dal()
.dump_all_storage_logs_for_tests()
.await
.iter()
.filter(|log| &log.address == account)
.map(|log| log.key)
.unique()
.collect::<Vec<_>>();

// Now clear keys and add new values
let mut logs: Vec<StorageLog> = keys_to_clear
.iter()
.map(|key| {
StorageLog::new_write_log(
StorageKey::new(AccountTreeId::new(*account), *key),
H256::zero(),
)
})
.collect();
logs.extend(state.iter().map(|(key, value)| {
StorageLog::new_write_log(
StorageKey::new(AccountTreeId::new(*account), *key),
*value,
)
}));

connection
.storage_logs_dal()
.append_storage_logs(
block_args.resolved_block_number(),
&[(H256::zero(), logs)],
)
.await
.map_err(|err| SubmitTxError::Internal(err.into()))?;
}

if let Some(state_diff) = &overrides.state_diff {
let logs = state_diff
.iter()
.map(|(key, value)| {
StorageLog::new_write_log(
StorageKey::new(AccountTreeId::new(*account), *key),
*value,
)
})
.collect();
self.acquire_replica_connection()
.await?
.storage_logs_dal()
.append_storage_logs(
aon marked this conversation as resolved.
Show resolved Hide resolved
block_args.resolved_block_number(),
&[(H256::zero(), logs)],
)
.await
.map_err(|err| SubmitTxError::Internal(err.into()))?;
}
}
}

if !tx.is_l1()
&& account_code_hash == H256::zero()
&& tx.execute.value > self.get_balance(&tx.initiator_account()).await?
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use zksync_types::{
api::{
Block, BlockId, BlockIdVariant, BlockNumber, Log, Transaction, TransactionId,
TransactionReceipt, TransactionVariant,
Block, BlockId, BlockIdVariant, BlockNumber, Log, StateOverride, Transaction,
TransactionId, TransactionReceipt, TransactionVariant,
},
transaction_request::CallRequest,
web3::types::{FeeHistory, Index, SyncState},
Expand Down Expand Up @@ -33,8 +33,13 @@ impl EthNamespaceServer for EthNamespace {
.map_err(|err| self.current_method().map_err(err))
}

async fn estimate_gas(&self, req: CallRequest, block: Option<BlockNumber>) -> RpcResult<U256> {
self.estimate_gas_impl(req, block)
async fn estimate_gas(
&self,
req: CallRequest,
block: Option<BlockNumber>,
state_override: Option<StateOverride>,
) -> RpcResult<U256> {
self.estimate_gas_impl(req, block, state_override)
.await
.map_err(|err| self.current_method().map_err(err))
}
Expand Down
12 changes: 9 additions & 3 deletions core/lib/zksync_core/src/api_server/web3/namespaces/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use anyhow::Context as _;
use zksync_system_constants::DEFAULT_L2_TX_GAS_PER_PUBDATA_BYTE;
use zksync_types::{
api::{
BlockId, BlockNumber, GetLogsFilter, Transaction, TransactionId, TransactionReceipt,
TransactionVariant,
BlockId, BlockNumber, GetLogsFilter, StateOverride, Transaction, TransactionId,
TransactionReceipt, TransactionVariant,
},
l2::{L2Tx, TransactionType},
transaction_request::CallRequest,
Expand Down Expand Up @@ -92,6 +92,7 @@ impl EthNamespace {
&self,
request: CallRequest,
_block: Option<BlockNumber>,
state_override: Option<StateOverride>,
) -> Result<U256, Web3Error> {
let mut request_with_gas_per_pubdata_overridden = request;
self.state
Expand Down Expand Up @@ -133,7 +134,12 @@ impl EthNamespace {
let fee = self
.state
.tx_sender
.get_txs_fee_in_wei(tx.into(), scale_factor, acceptable_overestimation)
.get_txs_fee_in_wei(
tx.into(),
scale_factor,
acceptable_overestimation,
state_override,
)
.await?;
Ok(fee.gas_limit)
}
Expand Down
2 changes: 1 addition & 1 deletion core/lib/zksync_core/src/api_server/web3/namespaces/zks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl ZksNamespace {
Ok(self
.state
.tx_sender
.get_txs_fee_in_wei(tx, scale_factor, acceptable_overestimation)
.get_txs_fee_in_wei(tx, scale_factor, acceptable_overestimation, None)
.await?)
}

Expand Down
Loading
Loading