Skip to content

Commit

Permalink
Merge v0.5.3 (#90)
Browse files Browse the repository at this point in the history
* Rename test_ to step_ for clarity (ava-labs#636)

* Codeowners fix (specific dir overrides global) (ava-labs#639)

* rename state upgrade test (ava-labs#641)

* plugin/evm: fix godoc typo (ava-labs#647)

Signed-off-by: Gyuho Lee <gyuho.lee@avalabs.org>

* plugin/evm: remove unncessary tx.Hash op in map iter (ava-labs#648)

Signed-off-by: Gyuho Lee <gyuho.lee@avalabs.org>

* deployExampleRewardManager.ts hardhat script fixed (ava-labs#650)

* Migrate HardHat tests to DS-tests (Solidity tests) (ava-labs#601)

* Increase trie dirty default cache size to 512MB (ava-labs#656)

* export gingkgo suites (ava-labs#659)

* export gingkgo suites

* remove precompiles description from ping tests

* update package.json

* fix url in package json

* change package name

* Publish npm module for contract-examples (ava-labs#663)

* export gingkgo suites

* remove precompiles description from ping tests

* update package.json

* fix url in package json

* change package name

* prepare for module publishing

* use npm ci

* preload ethers

* nits

* Fix broken path to docs in README. (ava-labs#665)

* Fix contract examples package json (ava-labs#672)

* rename contract-examples to contracts & fix pack issue

* allow custom CMD to be run on blockchains for e2e tests

* move default hardhat test to utils

* fix comment

* add more comments

* change folder reference

* Bump got and ethereum-waffle in /contracts (ava-labs#680)

Removes [got](https://github.com/sindresorhus/got). It's no longer used after updating ancestor dependency [ethereum-waffle](https://github.com/EthWorks/Waffle). These dependencies need to be updated together.


Removes `got`

Updates `ethereum-waffle` from 3.4.4 to 4.0.10
- [Release notes](https://github.com/EthWorks/Waffle/releases)
- [Commits](https://github.com/EthWorks/Waffle/compare/ethereum-waffle@3.4.4...ethereum-waffle@4.0.10)

---
updated-dependencies:
- dependency-name: got
  dependency-type: indirect
- dependency-name: ethereum-waffle
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Bump flat and hardhat in /contracts (ava-labs#679)

Bumps [flat](https://github.com/hughsk/flat) to 5.0.2 and updates ancestor dependency [hardhat](https://github.com/nomiclabs/hardhat). These dependencies need to be updated together.


Updates `flat` from 4.1.1 to 5.0.2
- [Commits](hughsk/flat@4.1.1...5.0.2)

Updates `hardhat` from 2.6.1 to 2.15.0
- [Release notes](https://github.com/nomiclabs/hardhat/releases)
- [Commits](https://github.com/nomiclabs/hardhat/compare/hardhat-core-v2.6.1...hardhat@2.15.0)

---
updated-dependencies:
- dependency-name: flat
  dependency-type: indirect
- dependency-name: hardhat
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Fix core benchmarks (ava-labs#697)

* remove unused line in test (ava-labs#695)

* bump version to v0.5.2 (ava-labs#681)

* bump version to v0.5.2

* downgrade avalanchego to 1.10.2

* update compatibility

* Remove unused ethereum-waffle and ethereumjs-tx pkgs (ava-labs#685)

* move state upgrade related functions to own file (ava-labs#684)

* Update load test to use ANR for network setup (ava-labs#579)

* Update load test to use ANR for network setup

* Remove ToWebsocketURI that relies on strings feature added in go1.20

* Update load test to use ENV var from CI if populated

* Move env var logic into NewDefaultANRConfig

* Add init functions and clean up comments

* Remove unnecessary helper

* Remove unneeded cmd

* Cleanup

* Address PR comments

* Move 2 min timeout for SetupNetwork to the start of the function

* Turn list of txs into tx sequence (ava-labs#683)

* Turn list of txs into tx sequence

* Add agent comments

* Remove unused code and address comments

* add some more comments

* address more comments'

* lint

* Remove :::warning

---------

Co-authored-by: Anusha <anushachillara@gmail.com>

* Minor simulator fixes (ava-labs#703)

* add benchmark to template (ava-labs#705)

* add benchmark to template

* fix comment

* Add metrics for gas price / usage (ava-labs#700)

Co-authored-by: aaronbuchwald <aaron.buchwald56@gmail.com>

* added config setting to prune warpdb (ava-labs#702)

* added config setting to prune warpdb

* refactored warp prune uint test

* message

* fixed up nits

* fixed nits

* fixed nits

* Update plugin/evm/config.go

* Add wrapped validator state for primary to subnet warp messages (ava-labs#708)

* Add wrapped validator state for primary to subnet warp message verification

* Address PR comment

* upload network runner artifact after e2e test run (ava-labs#709)

* Differentiate mandatory/optional Subnet-EVM Network Upgrades (ava-labs#640)

* remove network upgrades from upgrade configs and enforce them in vm init

* fix tests

* remove unused var

* remove extra shutdown

* copy test chain config when modify

* use SimulatedTestChainConfig for simulated tests

* copy modified test chain config

* add optional upgrades

* Add tests

* fix comments

* use unmarshal in test

* unexport functions

* add commented out test

* add TODO comment

* add blockchain.Stop as defer to test (ava-labs#714)

Co-authered-by: najeal <haim.nathan@icloud.com>
Co-authored-by: Ceyhun Onur <ceyhun.onur@avalabs.org>

* Add support for predicate gas into IntrinsicGas (ava-labs#713)

* Add support for predicate gas

* Address review

* Fix test and add test for PredicateGas

* Address comments

* Add signature aggregation helpers (ava-labs#711)

* Add signature aggregation helpers

* Fix

* Move WarpQuorumDenominator into new file

* Address comments

* fix var rename

* Improve comments

* Address comments

* Add predicate packing helper (ava-labs#710)

* Add predicate packing helper

* move predicate code and add readme

* fix moved import

* fix merge

* Run ginkgo precompile tests in parallel (ava-labs#712)

Use SynchronizedBeforeSuite to create the node and all the subnet that are
needed to run tests. Pass the blockchainID to each work processor and run the
tests in parallel to reduce runtime

* Fix BlockContext comment (ava-labs#731)

* precompile accepter should take logIdx (ava-labs#728)

* precompile accepter should take logIdx

* minimize mock

* copyright yr

* add comments

* Improve tests (ava-labs#733)

Improve tests based on feedback from ava-labs#712

* Fix precompile test gen template (ava-labs#737)

* fix Benchmark

* fix spelling/references in Benchmark

* Clean up gossip (ava-labs#744)

* Remove call from precompile (ava-labs#748)

* Fix nil types tmpl (ava-labs#751)

* add more nil types and fix int types

* readd hash type

* remove convertToNil

* Sync coreth v0.12.4 rc0 (ava-labs#694)

* apply diff to rc0

* replace coreth with subnet-evm

* go mod tidy

* remove must commit

* remove apricots

* replace coreth with subnet-evm

* rename banff and cortina

* test memory db

* add dUpgrade

* fix errors

* sync with v0.12.4-rc0

* more diffs

* change templates

* readd preparePredicateSlots

* run goimports

* readd tx allow list check to txpool

* Fix tests

* readd subnet evm check for tests

* fix tests

* add gas limit & coinbase fakers

* Fix timestamp types

* check error from newblockchain

* fix gas limit in simulated genesis

* downgrade ci to go 1.19

* gofmt files

* rebump go to 1.20

* bump anr to latest

* bump anr to latest

* prepare predicate storage slots in Subnet-EVM

* uncomment tests

* change order of airdrop memory cleanup

* add utils import

* Coreth 0.12.4 x apply (ava-labs#720)

Co-authored-by: Darioush Jalali <darioush.jalali@avalabs.org>

* move instruction sets

* revert unpack changes

* reduce diffs

* move genesis verify to vm (ava-labs#753)

* move genesis verify to vm

* fix comment

* set a correct default from genesis

* fix log

* revert change to vm.go

---------

Co-authored-by: Darioush Jalali <darioush.jalali@avalabs.org>

* avoid adding/removing GasLimits in tests (ava-labs#755)

* move genesis verify to vm

* fix comment

* set a correct default from genesis

* fix log

* revert change to vm.go

* avoid adding/removing GasLimits in tests

* nit

---------

Co-authored-by: Ceyhun Onur <ceyhun.onur@avalabs.org>

---------

Co-authored-by: Darioush Jalali <darioush.jalali@avalabs.org>

* Bump avalanchego to v1.10.5 and bump Subnet-EVM for v0.5.3 release (ava-labs#757)

* Bump avalanchego to v1.10.5 and bump Subnet-EVM for v0.5.3 release

* bump anr version to v1.7.1

* Migrate ABI unpack fix (ava-labs#750)

* change sprintf verb and use values (ava-labs#760)

* Generalize precompile test suite (ava-labs#759)

* restore old functions, generalize paths in sync subnet creation

* add subnet suit struct and methods

* move constants

* fix reviews

* add comment

* Update subnet.go

Signed-off-by: Ceyhun Onur <ceyhun.onur@avalabs.org>

---------

Signed-off-by: Ceyhun Onur <ceyhun.onur@avalabs.org>

* Add warp contract implementation (ava-labs#718)

* Add warp contract implementation

* Cleanup predicate test

* Fix new function signature

* Replace invalid fuzz test with unit test

* Add chain config to enable warp API for warp e2e test

* remove unused var

* Add experimental warning and move warp precompile to x/ package

* fix warning label

* Fix warning

* vm test nits

* Improve sendWarpMessenger sol comment

* more vm warp test nits

* Move warp params into params package

* More vm warp test nits

* Address more PR comments

* Remove triggerTx2

* Add check for expected topics from sendWarpMessage log

* Fix config test

* Fix incorrect replace

* remove unnecessary echo

* Address comments

* Address comments

* Address PR comments

* Improve comments

* Convert [32]byte type to common.Hash

* Add base cost for getVerifiedWarpMessage

* fix require equal type check

* Fix updated awm message format

* Update warp message format

* Move IWarpMessenger.sol to interfaces/

* Add newline to warp genesis

* uncomment assertion

* Fix broken links in README

* Add metrics to simulator (ava-labs#706)

* add tps

* get block build metrics

* Add issuance time, confirmed time, issued-> acceptance time, verify time

* Log times at end of batch

* cleaner

* address comments

* remove unused code block

* avoids taking len of channel

* nits

* pass in stringID

* move to loader

* remove unused field

* revert file back

* cleaner

* lint

* make it work for ws or for rpc

* protect

* endpoint

* no return on defer

* sep to a funciton

* have blockchainidstr passed in

* typo

* pass in metrics through config

* address comments

* address more comments and edit err policy of metrics functions

* add more logging to load_test

* typo

* better check

* fix endpoints

* typo:

* individual

* histogram

* address feedback:

* remove metrics from default

* address comments

* simplify time metrics

* better explanation

* address comments

* address comments

* cleanup

* more cleanup

* rename vars for clarity

* ws

* cleanup

* address comments

* ws

* expose metrics add flag

* fix blocking issue of http server and gracefully stop it

* cleanup

* use constant

* add issuance to confirmation metrics

* ws

* simplify metrics server

* Bump avalanchego to v1.10.5 and bump Subnet-EVM for v0.5.3 release (ava-labs#757)

* Bump avalanchego to v1.10.5 and bump Subnet-EVM for v0.5.3 release

* bump anr version to v1.7.1

* handle control c

* print out output

* clean up

* clean up

* remove go routines to close client

* address comments

* memory leak

* fix

* print

* e2e test: connect to appropriate chain (ava-labs#771)

* Bump avalanchego dep and update version for next release (ava-labs#770)

* Bump avalanchego dep and update version for next release

* Update cache sizes

* Update flag in run script to replace staking-enabled=false

* Update block builder to enforce predicate one tx at a time (ava-labs#773)

* Update block builder to enforce predicate one tx at a time

* remove dead code

* Update miner/worker.go

Co-authored-by: Darioush Jalali <darioush.jalali@avalabs.org>
Signed-off-by: aaronbuchwald <aaron.buchwald56@gmail.com>

---------

Signed-off-by: aaronbuchwald <aaron.buchwald56@gmail.com>
Co-authored-by: Darioush Jalali <darioush.jalali@avalabs.org>

* update iocorders address

* remove state-sync-enabled from chain config

* 1s block ticker

* flush hubbleFeed when len > 512

* fix compilation err

---------

Signed-off-by: Gyuho Lee <gyuho.lee@avalabs.org>
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Ceyhun Onur <ceyhun.onur@avalabs.org>
Signed-off-by: aaronbuchwald <aaron.buchwald56@gmail.com>
Co-authored-by: Richard Pringle <rpring9@gmail.com>
Co-authored-by: Darioush Jalali <darioush.jalali@avalabs.org>
Co-authored-by: Ceyhun Onur <ceyhun.onur@avalabs.org>
Co-authored-by: Gyuho Lee <gyuho.lee@avalabs.org>
Co-authored-by: İzzet Emre Demir <izzetemredemir@gmail.com>
Co-authored-by: aaronbuchwald <aaron.buchwald56@gmail.com>
Co-authored-by: Gabriel Cardona <gabriel@avalabs.org>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Anusha <anushachillara@gmail.com>
Co-authored-by: Cesar <137245636+nytzuga@users.noreply.github.com>
Co-authored-by: morrisettjohn <60852062+morrisettjohn@users.noreply.github.com>
Co-authored-by: nathan haim <nathan.haim@free.fr>
Co-authored-by: Martin Eckardt <m.eckardt@outlook.com>
Co-authored-by: rodrigo <77309055+RodrigoVillar@users.noreply.github.com>
Co-authored-by: Anusha <63559942+anusha-ctrl@users.noreply.github.com>
  • Loading branch information
16 people authored Aug 4, 2023
1 parent f5399b0 commit 5f214bb
Show file tree
Hide file tree
Showing 536 changed files with 49,677 additions and 42,622 deletions.
7 changes: 4 additions & 3 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

# Specific directories:

peer/ @anusha-ctrl
contract-examples/ @anusha-ctrl
scripts/ @anusha-ctrl
peer/ @anusha-ctrl @ceyonur @darioush @aaronbuchwald
contracts/ @anusha-ctrl @ceyonur @darioush @aaronbuchwald
scripts/ @anusha-ctrl @ceyonur @darioush @aaronbuchwald

15 changes: 11 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ jobs:
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: "14.x"
- name: Yarn install
run: yarn
working-directory: ./contract-examples
node-version: "18.15"
- name: NPM Clean Install
run: npm ci
working-directory: ./contracts
- name: Install AvalancheGo Release
shell: bash
run: BASEDIR=/tmp/e2e-test AVALANCHEGO_BUILD_PATH=/tmp/e2e-test/avalanchego ./scripts/install_avalanchego_release.sh
Expand All @@ -81,3 +81,10 @@ jobs:
- name: Run E2E Tests
shell: bash
run: AVALANCHEGO_BUILD_PATH=/tmp/e2e-test/avalanchego DATA_DIR=/tmp/e2e-test/data ./scripts/run_ginkgo.sh
- name: Upload Artifact
if: always()
uses: actions/upload-artifact@v3
with:
name: subnet-evm-e2e-logs
path: /tmp/network-runner-root-data*/
retention-days: 5
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ var privateKey2 = "31b571bf6894a248831ff937bb49f7754509fe93bbd2517c9c73c4144c0e9
Each blockchain is an instance of a Virtual Machine (VM), much like an object in an object-oriented language is an instance of a class.
That is, the VM defines the behavior of the blockchain.

Subnet EVM is the [Virtual Machine (VM)](https://docs.avax.network/overview/getting-started/avalanche-platform/#virtual-machines) that defines the Subnet Contract Chains. Subnet EVM is a simplified version of [Coreth VM (C-Chain)](https://github.com/ava-labs/coreth).
Subnet EVM is the [Virtual Machine (VM)](https://docs.avax.network/learn/avalanche/virtual-machines) that defines the Subnet Contract Chains. Subnet EVM is a simplified version of [Coreth VM (C-Chain)](https://github.com/ava-labs/coreth).

This chain implements the Ethereum Virtual Machine and supports Solidity smart contracts as well as most other Ethereum client functionality.

Expand Down Expand Up @@ -59,7 +59,10 @@ The Subnet EVM runs in a separate process from the main AvalancheGo process and
[v0.4.11] AvalancheGo@v1.9.10-v1.9.16 (Protocol Version: 24)
[v0.4.12] AvalancheGo@v1.9.10-v1.9.16 (Protocol Version: 24)
[v0.5.0] AvalancheGo@v1.10.0 (Protocol Version: 25)
[v0.5.1] AvalancheGo@v1.10.1 (Protocol Version: 26)
[v0.5.1] AvalancheGo@v1.10.1-v1.10.4 (Protocol Version: 26)
[v0.5.2] AvalancheGo@v1.10.1-v1.10.4 (Protocol Version: 26)
[v0.5.3] AvalancheGo@v1.10.5-v1.10.6 (Protocol Version: 27)
[v0.5.4] AvalancheGo@v1.10.5-v1.10.6 (Protocol Version: 27)
```

## API
Expand Down
2 changes: 1 addition & 1 deletion accounts/abi/abi.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ func (abi ABI) getArguments(name string, data []byte) (Arguments, error) {
var args Arguments
if method, ok := abi.Methods[name]; ok {
if len(data)%32 != 0 {
return nil, fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
return nil, fmt.Errorf("abi: improperly formatted output: %q - Bytes: %+v", data, data)
}
args = method.Outputs
}
Expand Down
12 changes: 6 additions & 6 deletions accounts/abi/abi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -738,12 +738,12 @@ func TestBareEvents(t *testing.T) {
// TestUnpackEvent is based on this contract:
//
// contract T {
// event received(address sender, uint amount, bytes memo);
// event receivedAddr(address sender);
// function receive(bytes memo) external payable {
// received(msg.sender, msg.value, memo);
// receivedAddr(msg.sender);
// }
// event received(address sender, uint amount, bytes memo);
// event receivedAddr(address sender);
// function receive(bytes memo) external payable {
// received(msg.sender, msg.value, memo);
// receivedAddr(msg.sender);
// }
// }
//
// When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
Expand Down
118 changes: 75 additions & 43 deletions accounts/abi/bind/backends/simulated.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,18 @@ type SimulatedBackend struct {
// and uses a simulated blockchain for testing purposes.
// A simulated backend always uses chainID 1337.
func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
cpcfg := params.TestChainConfig
cpcfg.ChainID = big.NewInt(1337)
genesis := core.Genesis{Config: cpcfg, GasLimit: gasLimit, Alloc: alloc}
genesis.MustCommit(database)
copyConfig := *params.TestChainConfig
copyConfig.ChainID = big.NewInt(1337)
genesis := core.Genesis{
Config: &copyConfig,
GasLimit: gasLimit,
Alloc: alloc,
}
cacheConfig := &core.CacheConfig{}
blockchain, _ := core.NewBlockChain(database, cacheConfig, genesis.Config, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{})

blockchain, err := core.NewBlockChain(database, cacheConfig, &genesis, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{}, false)
if err != nil {
panic(fmt.Sprintf("failed to create simulated blockchain: %v", err))
}
backend := &SimulatedBackend{
database: database,
blockchain: blockchain,
Expand All @@ -122,9 +127,12 @@ func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.Genesis

filterBackend := &filterBackend{database, blockchain, backend}
backend.filterSystem = filters.NewFilterSystem(filterBackend, filters.Config{})
backend.events = filters.NewEventSystem(backend.filterSystem, false)
backend.events = filters.NewEventSystem(backend.filterSystem)

backend.rollback(blockchain.CurrentBlock())
header := backend.blockchain.CurrentBlock()
block := backend.blockchain.GetBlock(header.Hash(), header.Number.Uint64())

backend.rollback(block)
return backend
}

Expand Down Expand Up @@ -170,7 +178,10 @@ func (b *SimulatedBackend) Rollback() {
b.mu.Lock()
defer b.mu.Unlock()

b.rollback(b.blockchain.CurrentBlock())
header := b.blockchain.CurrentBlock()
block := b.blockchain.GetBlock(header.Hash(), header.Number.Uint64())

b.rollback(block)
}

func (b *SimulatedBackend) rollback(parent *types.Block) {
Expand Down Expand Up @@ -209,7 +220,7 @@ func (b *SimulatedBackend) Fork(ctx context.Context, parent common.Hash) error {

// stateByBlockNumber retrieves a state by a given blocknumber.
func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *big.Int) (*state.StateDB, error) {
if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 {
if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number) == 0 {
return b.blockchain.State()
}
block, err := b.blockByNumber(ctx, blockNumber)
Expand Down Expand Up @@ -338,7 +349,7 @@ func (b *SimulatedBackend) BlockByNumber(ctx context.Context, number *big.Int) (
// (associated with its hash) if found without Lock.
func (b *SimulatedBackend) blockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
if number == nil || number.Cmp(b.acceptedBlock.Number()) == 0 {
return b.blockchain.CurrentBlock(), nil
return b.blockByHash(ctx, b.blockchain.CurrentBlock().Hash())
}

block := b.blockchain.GetBlockByNumber(uint64(number.Int64()))
Expand Down Expand Up @@ -466,7 +477,7 @@ func (b *SimulatedBackend) CallContract(ctx context.Context, call interfaces.Cal
b.mu.Lock()
defer b.mu.Unlock()

if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number) != 0 {
return nil, errBlockNumberUnsupported
}
stateDB, err := b.blockchain.State()
Expand All @@ -490,7 +501,7 @@ func (b *SimulatedBackend) AcceptedCallContract(ctx context.Context, call interf
defer b.mu.Unlock()
defer b.acceptedState.RevertToSnapshot(b.acceptedState.Snapshot())

res, err := b.callContract(ctx, call, b.acceptedBlock, b.acceptedState)
res, err := b.callContract(ctx, call, b.acceptedBlock.Header(), b.acceptedState)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -562,7 +573,7 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call interfaces.Call
available := new(big.Int).Set(balance)
if call.Value != nil {
if call.Value.Cmp(available) >= 0 {
return 0, errors.New("insufficient funds for transfer")
return 0, core.ErrInsufficientFundsForTransfer
}
available.Sub(available, call.Value)
}
Expand All @@ -584,7 +595,7 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call interfaces.Call
call.Gas = gas

snapshot := b.acceptedState.Snapshot()
res, err := b.callContract(ctx, call, b.acceptedBlock, b.acceptedState)
res, err := b.callContract(ctx, call, b.acceptedBlock.Header(), b.acceptedState)
b.acceptedState.RevertToSnapshot(snapshot)

if err != nil {
Expand All @@ -599,7 +610,6 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call interfaces.Call
for lo+1 < hi {
mid := (hi + lo) / 2
failed, _, err := executable(mid)

// If the error is not nil(consensus error), it means the provided message
// call or transaction will never be accepted no matter how much gas it is
// assigned. Return the error directly, don't struggle any more
Expand Down Expand Up @@ -634,13 +644,13 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call interfaces.Call

// callContract implements common code between normal and pending contract calls.
// state is modified during execution, make sure to copy it if necessary.
func (b *SimulatedBackend) callContract(ctx context.Context, call interfaces.CallMsg, block *types.Block, stateDB *state.StateDB) (*core.ExecutionResult, error) {
func (b *SimulatedBackend) callContract(ctx context.Context, call interfaces.CallMsg, header *types.Header, stateDB *state.StateDB) (*core.ExecutionResult, error) {
// Gas prices post 1559 need to be initialized
if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) {
return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
}
head := b.blockchain.CurrentHeader()
if !b.blockchain.Config().IsSubnetEVM(new(big.Int).SetUint64(head.Time)) {
if !b.blockchain.Config().IsSubnetEVM(head.Time) {
// If there's no basefee, then it must be a non-1559 execution
if call.GasPrice == nil {
call.GasPrice = new(big.Int)
Expand Down Expand Up @@ -673,20 +683,33 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call interfaces.Cal
if call.Value == nil {
call.Value = new(big.Int)
}

// Set infinite balance to the fake caller account.
from := stateDB.GetOrNewStateObject(call.From)
from.SetBalance(math.MaxBig256)

// Execute the call.
msg := callMsg{call}
msg := &core.Message{
From: call.From,
To: call.To,
Value: call.Value,
GasLimit: call.Gas,
GasPrice: call.GasPrice,
GasFeeCap: call.GasFeeCap,
GasTipCap: call.GasTipCap,
Data: call.Data,
AccessList: call.AccessList,
SkipAccountChecks: true,
}

txContext := core.NewEVMTxContext(msg)
evmContext := core.NewEVMBlockContext(block.Header(), b.blockchain, nil)
// Create a new environment which holds all relevant information
// about the transaction and calling mechanisms.
txContext := core.NewEVMTxContext(msg)
evmContext := core.NewEVMBlockContext(header, b.blockchain, nil)
vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{NoBaseFee: true})
gasPool := new(core.GasPool).AddGas(math.MaxUint64)

return core.NewStateTransition(vmEnv, msg, gasPool).TransitionDb()
return core.ApplyMessage(vmEnv, msg, gasPool)
}

// SendTransaction updates the pending block to include the given transaction.
Expand Down Expand Up @@ -830,8 +853,12 @@ func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
if len(b.acceptedBlock.Transactions()) != 0 {
return errors.New("Could not adjust time on non-empty block")
}
block := b.blockchain.GetBlockByHash(b.acceptedBlock.ParentHash())
if block == nil {
return fmt.Errorf("could not find parent")
}

blocks, _, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), dummy.NewFaker(), b.database, 1, 10, func(number int, block *core.BlockGen) {
blocks, _, _ := core.GenerateChain(b.config, block, dummy.NewFaker(), b.database, 1, 10, func(number int, block *core.BlockGen) {
block.OffsetTime(int64(adjustment.Seconds()))
})
stateDB, _ := b.blockchain.State()
Expand All @@ -847,23 +874,6 @@ func (b *SimulatedBackend) Blockchain() *core.BlockChain {
return b.blockchain
}

// callMsg implements core.Message to allow passing it as a transaction simulator.
type callMsg struct {
interfaces.CallMsg
}

func (m callMsg) From() common.Address { return m.CallMsg.From }
func (m callMsg) Nonce() uint64 { return 0 }
func (m callMsg) IsFake() bool { return true }
func (m callMsg) To() *common.Address { return m.CallMsg.To }
func (m callMsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
func (m callMsg) GasFeeCap() *big.Int { return m.CallMsg.GasFeeCap }
func (m callMsg) GasTipCap() *big.Int { return m.CallMsg.GasTipCap }
func (m callMsg) Gas() uint64 { return m.CallMsg.Gas }
func (m callMsg) Value() *big.Int { return m.CallMsg.Value }
func (m callMsg) Data() []byte { return m.CallMsg.Data }
func (m callMsg) AccessList() types.AccessList { return m.CallMsg.AccessList }

// filterBackend implements filters.Backend to support filtering for logs without
// taking bloom-bits acceleration structures into account.
type filterBackend struct {
Expand Down Expand Up @@ -900,17 +910,31 @@ func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db }

func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }

func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
if block == rpc.LatestBlockNumber {
func (fb *filterBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) {
switch number {
case rpc.PendingBlockNumber, rpc.AcceptedBlockNumber:
if block := fb.backend.acceptedBlock; block != nil {
return block.Header(), nil
}
return nil, nil
case rpc.LatestBlockNumber:
return fb.bc.CurrentHeader(), nil
default:
return fb.bc.GetHeaderByNumber(uint64(number.Int64())), nil
}
return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
}

func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
return fb.bc.GetHeaderByHash(hash), nil
}

func (fb *filterBackend) GetBody(ctx context.Context, hash common.Hash, number rpc.BlockNumber) (*types.Body, error) {
if body := fb.bc.GetBody(hash); body != nil {
return body, nil
}
return nil, errors.New("block body not found")
}

func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
number := rawdb.ReadHeaderNumber(fb.db, hash)
if number == nil {
Expand Down Expand Up @@ -950,6 +974,14 @@ func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.Matche
panic("not supported")
}

func (fb *filterBackend) ChainConfig() *params.ChainConfig {
panic("not supported")
}

func (fb *filterBackend) CurrentHeader() *types.Header {
panic("not supported")
}

func nullSubscription() event.Subscription {
return event.NewSubscription(func(quit <-chan struct{}) error {
<-quit
Expand Down
Loading

0 comments on commit 5f214bb

Please sign in to comment.