1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This file is part of Frontier.
//
// Copyright (c) 2022 Parity Technologies (UK) Ltd.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::{cell::RefCell, collections::BTreeMap, sync::Arc};
use ethereum_types::{H160, H256, U256};
use evm::{ExitError, ExitReason};
use jsonrpsee::core::RpcResult;
use scale_codec::{Decode, Encode};
// Substrate
use sc_client_api::backend::{Backend, StorageProvider};
use sc_transaction_pool::ChainApi;
use sp_api::{
ApiExt, CallApiAt, CallApiAtParams, CallContext, Extensions, ProvideRuntimeApi,
StorageTransactionCache,
};
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_blockchain::HeaderBackend;
use sp_inherents::CreateInherentDataProviders;
use sp_io::hashing::{blake2_128, twox_128};
use sp_runtime::{traits::Block as BlockT, DispatchError, SaturatedConversion};
use sp_state_machine::OverlayedChanges;
// Frontier
use fc_rpc_core::types::*;
use fp_evm::{ExecutionInfo, ExecutionInfoV2};
use fp_rpc::{EthereumRuntimeRPCApi, RuntimeStorageOverride};
use fp_storage::{EVM_ACCOUNT_CODES, PALLET_EVM};
use crate::{
eth::{Eth, EthConfig},
frontier_backend_client, internal_err,
};
/// Default JSONRPC error code return by geth
pub const JSON_RPC_ERROR_DEFAULT: i32 = -32000;
/// Allow to adapt a request for `estimate_gas`.
/// Can be used to estimate gas of some contracts using a different function
/// in the case the normal gas estimation doesn't work.
///
/// Exemple: a precompile that tries to do a subcall but succeeds regardless of the
/// success of the subcall. The gas estimation will thus optimize the gas limit down
/// to the minimum, while we want to estimate a gas limit that will allow the subcall to
/// have enough gas to succeed.
pub trait EstimateGasAdapter {
fn adapt_request(request: CallRequest) -> CallRequest;
}
impl EstimateGasAdapter for () {
fn adapt_request(request: CallRequest) -> CallRequest {
request
}
}
impl<B, C, P, CT, BE, A, CIDP, EC> Eth<B, C, P, CT, BE, A, CIDP, EC>
where
B: BlockT,
C: CallApiAt<B> + ProvideRuntimeApi<B>,
C::Api: BlockBuilderApi<B> + EthereumRuntimeRPCApi<B>,
C: HeaderBackend<B> + StorageProvider<B, BE> + 'static,
BE: Backend<B> + 'static,
A: ChainApi<Block = B>,
CIDP: CreateInherentDataProviders<B, ()> + Send + 'static,
EC: EthConfig<B, C>,
{
pub async fn call(
&self,
request: CallRequest,
number: Option<BlockNumber>,
state_overrides: Option<BTreeMap<H160, CallStateOverride>>,
) -> RpcResult<Bytes> {
let CallRequest {
from,
to,
gas_price,
max_fee_per_gas,
max_priority_fee_per_gas,
gas,
value,
data,
nonce,
access_list,
..
} = request;
let (gas_price, max_fee_per_gas, max_priority_fee_per_gas) = {
let details = fee_details(gas_price, max_fee_per_gas, max_priority_fee_per_gas)?;
(
details.gas_price,
details.max_fee_per_gas,
details.max_priority_fee_per_gas,
)
};
let (substrate_hash, api) = match frontier_backend_client::native_block_id::<B, C>(
self.client.as_ref(),
self.backend.as_ref(),
number,
)
.await?
{
Some(id) => {
let hash = self
.client
.expect_block_hash_from_id(&id)
.map_err(|_| crate::err(JSON_RPC_ERROR_DEFAULT, "header not found", None))?;
(hash, self.client.runtime_api())
},
None => {
// Not mapped in the db, assume pending.
let (hash, api) = self.pending_runtime_api().await.map_err(|err| {
internal_err(format!("Create pending runtime api error: {err}"))
})?;
(hash, api)
},
};
let api_version = if let Ok(Some(api_version)) =
api.api_version::<dyn EthereumRuntimeRPCApi<B>>(substrate_hash)
{
api_version
} else {
return Err(internal_err("failed to retrieve Runtime Api version"))
};
let block = if api_version > 1 {
api.current_block(substrate_hash)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
} else {
#[allow(deprecated)]
let legacy_block = api
.current_block_before_version_2(substrate_hash)
.map_err(|err| internal_err(format!("runtime error: {err}")))?;
legacy_block.map(|block| block.into())
};
let block_gas_limit = block
.ok_or_else(|| internal_err("block unavailable, cannot query gas limit"))?
.header
.gas_limit;
let max_gas_limit = block_gas_limit * self.execute_gas_limit_multiplier;
// use given gas limit or query current block's limit
let gas_limit = match gas {
Some(amount) => {
if amount > max_gas_limit {
return Err(internal_err(format!(
"provided gas limit is too high (can be up to {}x the block gas limit)",
self.execute_gas_limit_multiplier
)))
}
amount
},
// If gas limit is not specified in the request we either use the multiplier if supported
// or fallback to the block gas limit.
None => match api.gas_limit_multiplier_support(substrate_hash) {
Ok(_) => max_gas_limit,
_ => block_gas_limit,
},
};
let data = data.map(|d| d.0).unwrap_or_default();
match to {
Some(to) => {
if api_version == 1 {
// Legacy pre-london
#[allow(deprecated)]
let info = api
.call_before_version_2(
substrate_hash,
from.unwrap_or_default(),
to,
data,
value.unwrap_or_default(),
gas_limit,
gas_price,
nonce,
false,
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
error_on_execution_failure(&info.exit_reason, &info.value)?;
Ok(Bytes(info.value))
} else if api_version >= 2 && api_version < 4 {
// Post-london
#[allow(deprecated)]
let info = api
.call_before_version_4(
substrate_hash,
from.unwrap_or_default(),
to,
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
false,
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
error_on_execution_failure(&info.exit_reason, &info.value)?;
Ok(Bytes(info.value))
} else if api_version == 4 || api_version == 5 {
// Post-london + access list support
let encoded_params = Encode::encode(&(
&from.unwrap_or_default(),
&to,
&data,
&value.unwrap_or_default(),
&gas_limit,
&max_fee_per_gas,
&max_priority_fee_per_gas,
&nonce,
&false,
&Some(
access_list
.unwrap_or_default()
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect::<Vec<(sp_core::H160, Vec<H256>)>>(),
),
));
let overlayed_changes = self.create_overrides_overlay(
substrate_hash,
api_version,
state_overrides,
)?;
let storage_transaction_cache =
RefCell::<StorageTransactionCache<B, C::StateBackend>>::default();
let params = CallApiAtParams {
at: substrate_hash,
function: "EthereumRuntimeRPCApi_call",
arguments: encoded_params,
overlayed_changes: &RefCell::new(overlayed_changes),
storage_transaction_cache: &storage_transaction_cache,
call_context: CallContext::Offchain,
recorder: &None,
extensions: &RefCell::new(Extensions::new()),
};
let value = if api_version == 4 {
let info = self
.client
.call_api_at(params)
.and_then(|r| {
Result::map_err(
<Result<ExecutionInfo::<Vec<u8>>, DispatchError> as Decode>::decode(&mut &r[..]),
|error| sp_api::ApiError::FailedToDecodeReturnValue {
function: "EthereumRuntimeRPCApi_call",
error,
},
)
})
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
error_on_execution_failure(&info.exit_reason, &info.value)?;
info.value
} else if api_version == 5 {
let info = self
.client
.call_api_at(params)
.and_then(|r| {
Result::map_err(
<Result<ExecutionInfoV2::<Vec<u8>>, DispatchError> as Decode>::decode(&mut &r[..]),
|error| sp_api::ApiError::FailedToDecodeReturnValue {
function: "EthereumRuntimeRPCApi_call",
error,
},
)
})
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
error_on_execution_failure(&info.exit_reason, &info.value)?;
info.value
} else {
unreachable!("invalid version");
};
Ok(Bytes(value))
} else {
Err(internal_err("failed to retrieve Runtime Api version"))
}
},
None => {
if api_version == 1 {
// Legacy pre-london
#[allow(deprecated)]
let info = api
.create_before_version_2(
substrate_hash,
from.unwrap_or_default(),
data,
value.unwrap_or_default(),
gas_limit,
gas_price,
nonce,
false,
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
error_on_execution_failure(&info.exit_reason, &[])?;
let code = api
.account_code_at(substrate_hash, info.value)
.map_err(|err| internal_err(format!("runtime error: {err}")))?;
Ok(Bytes(code))
} else if api_version >= 2 && api_version < 4 {
// Post-london
#[allow(deprecated)]
let info = api
.create_before_version_4(
substrate_hash,
from.unwrap_or_default(),
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
false,
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
error_on_execution_failure(&info.exit_reason, &[])?;
let code = api
.account_code_at(substrate_hash, info.value)
.map_err(|err| internal_err(format!("runtime error: {err}")))?;
Ok(Bytes(code))
} else if api_version == 4 {
// Post-london + access list support
let access_list = access_list.unwrap_or_default();
#[allow(deprecated)]
let info = api
.create_before_version_5(
substrate_hash,
from.unwrap_or_default(),
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
false,
Some(
access_list
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect(),
),
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
error_on_execution_failure(&info.exit_reason, &[])?;
let code = api
.account_code_at(substrate_hash, info.value)
.map_err(|err| internal_err(format!("runtime error: {err}")))?;
Ok(Bytes(code))
} else if api_version == 5 {
// Post-london + access list support
let access_list = access_list.unwrap_or_default();
let info = api
.create(
substrate_hash,
from.unwrap_or_default(),
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
false,
Some(
access_list
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect(),
),
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
error_on_execution_failure(&info.exit_reason, &[])?;
let code = api
.account_code_at(substrate_hash, info.value)
.map_err(|err| internal_err(format!("runtime error: {err}")))?;
Ok(Bytes(code))
} else {
Err(internal_err("failed to retrieve Runtime Api version"))
}
},
}
}
pub async fn estimate_gas(
&self,
request: CallRequest,
number: Option<BlockNumber>,
) -> RpcResult<U256> {
let client = Arc::clone(&self.client);
let block_data_cache = Arc::clone(&self.block_data_cache);
// Define the lower bound of estimate
const MIN_GAS_PER_TX: U256 = U256([21_000, 0, 0, 0]);
// Get substrate hash and runtime api
let (substrate_hash, api) = match frontier_backend_client::native_block_id::<B, C>(
self.client.as_ref(),
self.backend.as_ref(),
number,
)
.await?
{
Some(id) => {
let hash = client
.expect_block_hash_from_id(&id)
.map_err(|_| crate::err(JSON_RPC_ERROR_DEFAULT, "header not found", None))?;
(hash, client.runtime_api())
},
None => {
// Not mapped in the db, assume pending.
let (hash, api) = self.pending_runtime_api().await.map_err(|err| {
internal_err(format!("Create pending runtime api error: {err}"))
})?;
(hash, api)
},
};
// Adapt request for gas estimation.
let request = EC::EstimateGasAdapter::adapt_request(request);
// For simple transfer to simple account, return MIN_GAS_PER_TX directly
let is_simple_transfer = match &request.data {
None => true,
Some(vec) => vec.0.is_empty(),
};
if is_simple_transfer {
if let Some(to) = request.to {
let to_code = api
.account_code_at(substrate_hash, to)
.map_err(|err| internal_err(format!("runtime error: {err}")))?;
if to_code.is_empty() {
return Ok(MIN_GAS_PER_TX)
}
}
}
let (gas_price, max_fee_per_gas, max_priority_fee_per_gas) = {
let details = fee_details(
request.gas_price,
request.max_fee_per_gas,
request.max_priority_fee_per_gas,
)?;
(
details.gas_price,
details.max_fee_per_gas,
details.max_priority_fee_per_gas,
)
};
let block_gas_limit = {
let schema = fc_storage::onchain_storage_schema(client.as_ref(), substrate_hash);
let block = block_data_cache.current_block(schema, substrate_hash).await;
block
.ok_or_else(|| internal_err("block unavailable, cannot query gas limit"))?
.header
.gas_limit
};
let max_gas_limit = block_gas_limit * self.execute_gas_limit_multiplier;
// Determine the highest possible gas limits
let mut highest = match request.gas {
Some(amount) => {
if amount > max_gas_limit {
return Err(internal_err(format!(
"provided gas limit is too high (can be up to {}x the block gas limit)",
self.execute_gas_limit_multiplier
)))
}
amount
},
// If gas limit is not specified in the request we either use the multiplier if supported
// or fallback to the block gas limit.
None => match api.gas_limit_multiplier_support(substrate_hash) {
Ok(_) => max_gas_limit,
_ => block_gas_limit,
},
};
// Recap the highest gas allowance with account's balance.
if let Some(from) = request.from {
let gas_price = gas_price.unwrap_or_default();
if gas_price > U256::zero() {
let balance = api
.account_basic(substrate_hash, from)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.balance;
let mut available = balance;
if let Some(value) = request.value {
if value > available {
return Err(internal_err("insufficient funds for transfer"))
}
available -= value;
}
let allowance = available / gas_price;
if highest > allowance {
log::warn!(
"Gas estimation capped by limited funds original {} balance {} sent {} feecap {} fundable {}",
highest,
balance,
request.value.unwrap_or_default(),
gas_price,
allowance
);
highest = allowance;
}
}
}
struct ExecutableResult {
data: Vec<u8>,
exit_reason: ExitReason,
used_gas: U256,
}
// Create a helper to check if a gas allowance results in an executable transaction.
//
// A new ApiRef instance needs to be used per execution to avoid the overlayed state to affect
// the estimation result of subsequent calls.
//
// Note that this would have a performance penalty if we introduce gas estimation for past
// blocks - and thus, past runtime versions. Substrate has a default `runtime_cache_size` of
// 2 slots LRU-style, meaning if users were to access multiple runtime versions in a short period
// of time, the RPC response time would degrade a lot, as the VersionedRuntime needs to be compiled.
//
// To solve that, and if we introduce historical gas estimation, we'd need to increase that default.
#[rustfmt::skip]
let executable = move |
request, gas_limit, api_version, api: sp_api::ApiRef<'_, C::Api>, estimate_mode
| -> RpcResult<ExecutableResult> {
let CallRequest {
from,
to,
gas,
value,
data,
nonce,
access_list,
..
} = request;
// Use request gas limit only if it less than gas_limit parameter
let gas_limit = core::cmp::min(gas.unwrap_or(gas_limit), gas_limit);
let data = data.map(|d| d.0).unwrap_or_default();
let (exit_reason, data, used_gas) = match to {
Some(to) => {
if api_version == 1 {
// Legacy pre-london
#[allow(deprecated)]
let info = api.call_before_version_2(
substrate_hash,
from.unwrap_or_default(),
to,
data,
value.unwrap_or_default(),
gas_limit,
gas_price,
nonce,
estimate_mode,
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
(info.exit_reason, info.value, info.used_gas)
} else if api_version < 4 {
// Post-london
#[allow(deprecated)]
let info = api.call_before_version_4(
substrate_hash,
from.unwrap_or_default(),
to,
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
estimate_mode,
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
(info.exit_reason, info.value, info.used_gas)
} else if api_version == 4 {
// Post-london + access list support
let access_list = access_list.unwrap_or_default();
#[allow(deprecated)]
let info = api.call_before_version_5(
substrate_hash,
from.unwrap_or_default(),
to,
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
estimate_mode,
Some(
access_list
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect(),
),
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
(info.exit_reason, info.value, info.used_gas)
} else {
// Post-london + access list support
let access_list = access_list.unwrap_or_default();
let info = api.call(
substrate_hash,
from.unwrap_or_default(),
to,
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
estimate_mode,
Some(
access_list
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect(),
),
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
(info.exit_reason, info.value, info.used_gas.effective)
}
}
None => {
if api_version == 1 {
// Legacy pre-london
#[allow(deprecated)]
let info = api.create_before_version_2(
substrate_hash,
from.unwrap_or_default(),
data,
value.unwrap_or_default(),
gas_limit,
gas_price,
nonce,
estimate_mode,
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
(info.exit_reason, Vec::new(), info.used_gas)
} else if api_version < 4 {
// Post-london
#[allow(deprecated)]
let info = api.create_before_version_4(
substrate_hash,
from.unwrap_or_default(),
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
estimate_mode,
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
(info.exit_reason, Vec::new(), info.used_gas)
} else if api_version == 4 {
// Post-london + access list support
let access_list = access_list.unwrap_or_default();
#[allow(deprecated)]
let info = api.create_before_version_5(
substrate_hash,
from.unwrap_or_default(),
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
estimate_mode,
Some(
access_list
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect(),
),
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
(info.exit_reason, Vec::new(), info.used_gas)
} else {
// Post-london + access list support
let access_list = access_list.unwrap_or_default();
let info = api.create(
substrate_hash,
from.unwrap_or_default(),
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
estimate_mode,
Some(
access_list
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect(),
),
)
.map_err(|err| internal_err(format!("runtime error: {err}")))?
.map_err(|err| internal_err(format!("execution fatal: {err:?}")))?;
(info.exit_reason, Vec::new(), info.used_gas.effective)
}
}
};
Ok(ExecutableResult {
exit_reason,
data,
used_gas,
})
};
let api_version = if let Ok(Some(api_version)) =
client
.runtime_api()
.api_version::<dyn EthereumRuntimeRPCApi<B>>(substrate_hash)
{
api_version
} else {
return Err(internal_err("failed to retrieve Runtime Api version"))
};
// Verify that the transaction succeed with highest capacity
let cap = highest;
let estimate_mode = !cfg!(feature = "rpc-binary-search-estimate");
let ExecutableResult {
data,
exit_reason,
used_gas,
} = executable(
request.clone(),
highest,
api_version,
client.runtime_api(),
estimate_mode,
)?;
match exit_reason {
ExitReason::Succeed(_) => (),
ExitReason::Error(ExitError::OutOfGas) =>
return Err(internal_err(format!(
"gas required exceeds allowance {}",
cap
))),
// If the transaction reverts, there are two possible cases,
// it can revert because the called contract feels that it does not have enough
// gas left to continue, or it can revert for another reason unrelated to gas.
ExitReason::Revert(revert) => {
if request.gas.is_some() || request.gas_price.is_some() {
// If the user has provided a gas limit or a gas price, then we have executed
// with less block gas limit, so we must reexecute with block gas limit to
// know if the revert is due to a lack of gas or not.
let ExecutableResult {
data,
exit_reason,
used_gas: _,
} = executable(
request.clone(),
max_gas_limit,
api_version,
client.runtime_api(),
estimate_mode,
)?;
match exit_reason {
ExitReason::Succeed(_) =>
return Err(internal_err(format!(
"gas required exceeds allowance {cap}",
))),
// The execution has been done with block gas limit, so it is not a lack of gas from the user.
other => error_on_execution_failure(&other, &data)?,
}
} else {
// The execution has already been done with block gas limit, so it is not a lack of gas from the user.
error_on_execution_failure(&ExitReason::Revert(revert), &data)?
}
},
other => error_on_execution_failure(&other, &data)?,
};
#[cfg(not(feature = "rpc-binary-search-estimate"))]
{
Ok(used_gas)
}
#[cfg(feature = "rpc-binary-search-estimate")]
{
// On binary search, evm estimate mode is disabled
let estimate_mode = false;
// Define the lower bound of the binary search
let mut lowest = MIN_GAS_PER_TX;
// Start close to the used gas for faster binary search
let mut mid = std::cmp::min(used_gas * 3, (highest + lowest) / 2);
// Execute the binary search and hone in on an executable gas limit.
let mut previous_highest = highest;
while (highest - lowest) > U256::one() {
let ExecutableResult {
data,
exit_reason,
used_gas: _,
} = executable(
request.clone(),
mid,
api_version,
client.runtime_api(),
estimate_mode,
)?;
match exit_reason {
ExitReason::Succeed(_) => {
highest = mid;
// If the variation in the estimate is less than 10%,
// then the estimate is considered sufficiently accurate.
if (previous_highest - highest) * 10 / previous_highest < U256::one() {
return Ok(highest)
}
previous_highest = highest;
},
ExitReason::Revert(_)
| ExitReason::Error(ExitError::OutOfGas)
| ExitReason::Error(ExitError::InvalidCode(_)) => {
lowest = mid;
},
other => error_on_execution_failure(&other, &data)?,
}
mid = (highest + lowest) / 2;
}
Ok(highest)
}
}
/// Given an address mapped `CallStateOverride`, creates `OverlayedChanges` to be used for
/// `CallApiAt` eth_call.
fn create_overrides_overlay(
&self,
block_hash: B::Hash,
api_version: u32,
state_overrides: Option<BTreeMap<H160, CallStateOverride>>,
) -> RpcResult<OverlayedChanges> {
let mut overlayed_changes = OverlayedChanges::default();
if let Some(state_overrides) = state_overrides {
for (address, state_override) in state_overrides {
if EC::RuntimeStorageOverride::is_enabled() {
EC::RuntimeStorageOverride::set_overlayed_changes(
self.client.as_ref(),
&mut overlayed_changes,
block_hash,
api_version,
address,
state_override.balance,
state_override.nonce,
);
} else if state_override.balance.is_some() || state_override.nonce.is_some() {
return Err(internal_err(
"state override unsupported for balance and nonce",
))
}
if let Some(code) = &state_override.code {
let mut key = [twox_128(PALLET_EVM), twox_128(EVM_ACCOUNT_CODES)]
.concat()
.to_vec();
key.extend(blake2_128(address.as_bytes()));
key.extend(address.as_bytes());
let encoded_code = code.clone().into_vec().encode();
overlayed_changes.set_storage(key.clone(), Some(encoded_code));
}
let mut account_storage_key = [
twox_128(PALLET_EVM),
twox_128(fp_storage::EVM_ACCOUNT_STORAGES),
]
.concat()
.to_vec();
account_storage_key.extend(blake2_128(address.as_bytes()));
account_storage_key.extend(address.as_bytes());
// Use `state` first. If `stateDiff` is also present, it resolves consistently
if let Some(state) = &state_override.state {
// clear all storage
if let Ok(all_keys) = self.client.storage_keys(
block_hash,
Some(&sp_storage::StorageKey(account_storage_key.clone())),
None,
) {
for key in all_keys {
overlayed_changes.set_storage(key.0, None);
}
}
// set provided storage
for (k, v) in state {
let mut slot_key = account_storage_key.clone();
slot_key.extend(blake2_128(k.as_bytes()));
slot_key.extend(k.as_bytes());
overlayed_changes.set_storage(slot_key, Some(v.as_bytes().to_owned()));
}
}
if let Some(state_diff) = &state_override.state_diff {
for (k, v) in state_diff {
let mut slot_key = account_storage_key.clone();
slot_key.extend(blake2_128(k.as_bytes()));
slot_key.extend(k.as_bytes());
overlayed_changes.set_storage(slot_key, Some(v.as_bytes().to_owned()));
}
}
}
}
Ok(overlayed_changes)
}
}
pub fn error_on_execution_failure(reason: &ExitReason, data: &[u8]) -> RpcResult<()> {
match reason {
ExitReason::Succeed(_) => Ok(()),
ExitReason::Error(err) => {
if *err == ExitError::OutOfGas {
// `ServerError(0)` will be useful in estimate gas
return Err(internal_err("out of gas"))
}
Err(crate::internal_err_with_data(
format!("evm error: {err:?}"),
&[],
))
},
ExitReason::Revert(_) => {
const LEN_START: usize = 36;
const MESSAGE_START: usize = 68;
let mut message = "VM Exception while processing transaction: revert".to_string();
// A minimum size of error function selector (4) + offset (32) + string length (32)
// should contain a utf-8 encoded revert reason.
if data.len() > MESSAGE_START {
let message_len =
U256::from(&data[LEN_START..MESSAGE_START]).saturated_into::<usize>();
let message_end = MESSAGE_START.saturating_add(message_len);
if data.len() >= message_end {
let body: &[u8] = &data[MESSAGE_START..message_end];
if let Ok(reason) = std::str::from_utf8(body) {
message = format!("{message} {reason}");
}
}
}
Err(crate::internal_err_with_data(message, data))
},
ExitReason::Fatal(err) => Err(crate::internal_err_with_data(
format!("evm fatal: {err:?}"),
&[],
)),
}
}
struct FeeDetails {
gas_price: Option<U256>,
max_fee_per_gas: Option<U256>,
max_priority_fee_per_gas: Option<U256>,
}
fn fee_details(
request_gas_price: Option<U256>,
request_max_fee: Option<U256>,
request_priority: Option<U256>,
) -> RpcResult<FeeDetails> {
match (request_gas_price, request_max_fee, request_priority) {
(gas_price, None, None) => {
// Legacy request, all default to gas price.
// A zero-set gas price is None.
let gas_price = if gas_price.unwrap_or_default().is_zero() {
None
} else {
gas_price
};
Ok(FeeDetails {
gas_price,
max_fee_per_gas: gas_price,
max_priority_fee_per_gas: gas_price,
})
},
(_, max_fee, max_priority) => {
// eip-1559
// A zero-set max fee is None.
let max_fee = if max_fee.unwrap_or_default().is_zero() {
None
} else {
max_fee
};
// Ensure `max_priority_fee_per_gas` is less or equal to `max_fee_per_gas`.
if let Some(max_priority) = max_priority {
let max_fee = max_fee.unwrap_or_default();
if max_priority > max_fee {
return Err(internal_err(
"Invalid input: `max_priority_fee_per_gas` greater than `max_fee_per_gas`",
))
}
}
Ok(FeeDetails {
gas_price: max_fee,
max_fee_per_gas: max_fee,
max_priority_fee_per_gas: max_priority,
})
},
}
}