diff --git a/core/chains/evm/client/simulated_backend_client.go b/core/chains/evm/client/simulated_backend_client.go index e12c1855292..df3b709e6f7 100644 --- a/core/chains/evm/client/simulated_backend_client.go +++ b/core/chains/evm/client/simulated_backend_client.go @@ -12,10 +12,10 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/ethereum/go-ethereum/rpc" "github.com/smartcontractkit/chainlink-common/pkg/utils/hex" @@ -66,20 +66,35 @@ var ( // SimulatedBackendClient is an Client implementation using a simulated // blockchain backend. Note that not all RPC methods are implemented here. type SimulatedBackendClient struct { - b *backends.SimulatedBackend - t testing.TB - chainId *big.Int + b evmtypes.Backend // *simulated.Backend, or something satisfying same interface + client simulated.Client + t testing.TB + chainId *big.Int + chainFamily evmtypes.ChainFamily + headByNumberCallback func(ctx context.Context, c *SimulatedBackendClient, n *big.Int) error } // NewSimulatedBackendClient creates an eth client backed by a simulated backend. -func NewSimulatedBackendClient(t testing.TB, b *backends.SimulatedBackend, chainId *big.Int) *SimulatedBackendClient { +func NewSimulatedBackendClient(t testing.TB, b *simulated.Backend, chainId *big.Int) *SimulatedBackendClient { return &SimulatedBackendClient{ b: b, + client: b.Client(), t: t, chainId: chainId, } } +// Switch to a new backend client (simulating an rpc failover event) +// If chainFamily = Optimism, the new backend will exhibit the non-geth behavior of optimism (and some other rpc clients), +// where success rather than an error code is returned when a call to FilterLogs() fails to find the block hash +// requested. This combined with a failover event can lead to the "eventual consistency" behavior that Backup LogPoller +// and other solutions were designed to recover from. +func (c *SimulatedBackendClient) SetBackend(backend evmtypes.Backend, chainFamily evmtypes.ChainFamily) { + c.chainFamily = chainFamily + c.b = backend + c.client = backend.Client() +} + // Dial noop for the sim. func (c *SimulatedBackendClient) Dial(context.Context) error { return nil @@ -113,13 +128,20 @@ func (c *SimulatedBackendClient) CallContext(ctx context.Context, result interfa // FilterLogs returns all logs that respect the passed filter query. func (c *SimulatedBackendClient) FilterLogs(ctx context.Context, q ethereum.FilterQuery) (logs []types.Log, err error) { - return c.b.FilterLogs(ctx, q) + logs, err = c.client.FilterLogs(ctx, q) + if c.chainFamily == evmtypes.Optimism { + if err != nil && err.Error() == "unknown block" { + return []types.Log{}, nil // emulate optimism behavior of returning success instead of "unknown block" + } + } + + return logs, err } // SubscribeFilterLogs registers a subscription for push notifications of logs // from a given address. func (c *SimulatedBackendClient) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, channel chan<- types.Log) (ethereum.Subscription, error) { - return c.b.SubscribeFilterLogs(ctx, q, channel) + return c.client.SubscribeFilterLogs(ctx, q, channel) } func (c *SimulatedBackendClient) TokenBalance(ctx context.Context, address common.Address, contractAddress common.Address) (balance *big.Int, err error) { @@ -128,7 +150,7 @@ func (c *SimulatedBackendClient) TokenBalance(ctx context.Context, address commo return nil, fmt.Errorf("%w: while seeking the ERC20 balance of %s on %s", err, address, contractAddress) } - b, err := c.b.CallContract(ctx, ethereum.CallMsg{ + b, err := c.client.CallContract(ctx, ethereum.CallMsg{ To: &contractAddress, Data: callData}, big.NewInt(int64(rpc.LatestBlockNumber))) if err != nil { @@ -149,11 +171,11 @@ func (c *SimulatedBackendClient) LINKBalance(ctx context.Context, address common // TransactionReceipt returns the transaction receipt for the given transaction hash. func (c *SimulatedBackendClient) TransactionReceipt(ctx context.Context, receipt common.Hash) (*types.Receipt, error) { - return c.b.TransactionReceipt(ctx, receipt) + return c.client.TransactionReceipt(ctx, receipt) } func (c *SimulatedBackendClient) TransactionByHash(ctx context.Context, txHash common.Hash) (tx *types.Transaction, err error) { - tx, _, err = c.b.TransactionByHash(ctx, txHash) + tx, _, err = c.client.TransactionByHash(ctx, txHash) return } @@ -163,7 +185,7 @@ func (c *SimulatedBackendClient) blockNumber(ctx context.Context, number interfa switch n { case "latest": var n uint64 - n, err = c.b.BlockNumber(ctx) + n, err = c.client.BlockNumber(ctx) if err != nil { return } @@ -174,7 +196,7 @@ func (c *SimulatedBackendClient) blockNumber(ctx context.Context, number interfa return big.NewInt(0), nil case "pending": var h *types.Header - h, err = c.b.HeaderByNumber(ctx, new(big.Int).SetInt64(rpc.PendingBlockNumber.Int64())) + h, err = c.client.HeaderByNumber(ctx, new(big.Int).SetInt64(rpc.PendingBlockNumber.Int64())) if err != nil { return } @@ -182,7 +204,7 @@ func (c *SimulatedBackendClient) blockNumber(ctx context.Context, number interfa return case "finalized": var h *types.Header - h, err = c.b.HeaderByNumber(ctx, new(big.Int).SetInt64(rpc.FinalizedBlockNumber.Int64())) + h, err = c.client.HeaderByNumber(ctx, new(big.Int).SetInt64(rpc.FinalizedBlockNumber.Int64())) if err != nil { return } @@ -208,17 +230,29 @@ func (c *SimulatedBackendClient) blockNumber(ctx context.Context, number interfa } } +func (c *SimulatedBackendClient) RegisterHeadByNumberCallback(cb func(ctx context.Context, c *SimulatedBackendClient, n *big.Int) error) { + c.headByNumberCallback = cb +} + // HeadByNumber returns our own header type. func (c *SimulatedBackendClient) HeadByNumber(ctx context.Context, n *big.Int) (*evmtypes.Head, error) { if n == nil { n = big.NewInt(int64(rpc.LatestBlockNumber)) } - header, err := c.b.HeaderByNumber(ctx, n) + header, err := c.client.HeaderByNumber(ctx, n) if err != nil { return nil, err } else if header == nil { return nil, ethereum.NotFound } + + if c.headByNumberCallback != nil { + err = c.headByNumberCallback(ctx, c, n) + if err != nil { + return nil, err + } + } + return &evmtypes.Head{ EVMChainID: ubig.NewI(c.chainId.Int64()), Hash: header.Hash(), @@ -230,7 +264,7 @@ func (c *SimulatedBackendClient) HeadByNumber(ctx context.Context, n *big.Int) ( // HeadByHash returns our own header type. func (c *SimulatedBackendClient) HeadByHash(ctx context.Context, h common.Hash) (*evmtypes.Head, error) { - header, err := c.b.HeaderByHash(ctx, h) + header, err := c.client.HeaderByHash(ctx, h) if err != nil { return nil, err } else if header == nil { @@ -247,16 +281,16 @@ func (c *SimulatedBackendClient) HeadByHash(ctx context.Context, h common.Hash) // BlockByNumber returns a geth block type. func (c *SimulatedBackendClient) BlockByNumber(ctx context.Context, n *big.Int) (*types.Block, error) { - return c.b.BlockByNumber(ctx, n) + return c.client.BlockByNumber(ctx, n) } // BlockByNumber returns a geth block type. func (c *SimulatedBackendClient) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { - return c.b.BlockByHash(ctx, hash) + return c.client.BlockByHash(ctx, hash) } func (c *SimulatedBackendClient) LatestBlockHeight(ctx context.Context) (*big.Int, error) { - header, err := c.b.HeaderByNumber(ctx, nil) + header, err := c.client.HeaderByNumber(ctx, nil) return header.Number, err } @@ -272,18 +306,18 @@ func (c *SimulatedBackendClient) ChainID() (*big.Int, error) { // PendingNonceAt gets pending nonce i.e. mempool nonce. func (c *SimulatedBackendClient) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { - return c.b.PendingNonceAt(ctx, account) + return c.client.PendingNonceAt(ctx, account) } // NonceAt gets nonce as of a specified block. func (c *SimulatedBackendClient) SequenceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (evmtypes.Nonce, error) { - nonce, err := c.b.NonceAt(ctx, account, blockNumber) + nonce, err := c.client.NonceAt(ctx, account, blockNumber) return evmtypes.Nonce(nonce), err } // BalanceAt gets balance as of a specified block. func (c *SimulatedBackendClient) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) { - return c.b.BalanceAt(ctx, account, blockNumber) + return c.client.BalanceAt(ctx, account, blockNumber) } type headSubscription struct { @@ -313,7 +347,7 @@ func (c *SimulatedBackendClient) SubscribeNewHead( ch := make(chan *types.Header) var err error - subscription.subscription, err = c.b.SubscribeNewHead(ctx, ch) + subscription.subscription, err = c.client.SubscribeNewHead(ctx, ch) if err != nil { return nil, fmt.Errorf("%w: could not subscribe to new heads on "+ "simulated backend", err) @@ -348,11 +382,11 @@ func (c *SimulatedBackendClient) SubscribeNewHead( // HeaderByNumber returns the geth header type. func (c *SimulatedBackendClient) HeaderByNumber(ctx context.Context, n *big.Int) (*types.Header, error) { - return c.b.HeaderByNumber(ctx, n) + return c.client.HeaderByNumber(ctx, n) } func (c *SimulatedBackendClient) HeaderByHash(ctx context.Context, h common.Hash) (*types.Header, error) { - return c.b.HeaderByHash(ctx, h) + return c.client.HeaderByHash(ctx, h) } func (c *SimulatedBackendClient) SendTransactionReturnCode(ctx context.Context, tx *types.Transaction, fromAddress common.Address) (commonclient.SendTxReturnCode, error) { @@ -373,7 +407,7 @@ func (c *SimulatedBackendClient) SendTransaction(ctx context.Context, tx *types. if err != nil { logger.Test(c.t).Panic(fmt.Errorf("invalid transaction: %v (tx: %#v)", err, tx)) } - pendingNonce, err := c.b.PendingNonceAt(ctx, sender) + pendingNonce, err := c.client.PendingNonceAt(ctx, sender) if err != nil { panic(fmt.Errorf("unable to determine nonce for account %s: %v", sender.Hex(), err)) } @@ -384,7 +418,7 @@ func (c *SimulatedBackendClient) SendTransaction(ctx context.Context, tx *types. return nil } - err = c.b.SendTransaction(ctx, tx) + err = c.client.SendTransaction(ctx, tx) return err } @@ -412,7 +446,7 @@ func (c *SimulatedBackendClient) CallContract(ctx context.Context, msg ethereum. // Message string `json:"message"` // Data interface{} `json:"data,omitempty"` //} - res, err := c.b.CallContract(ctx, msg, blockNumber) + res, err := c.client.CallContract(ctx, msg, blockNumber) if err != nil { dataErr := revertError{} if errors.Is(err, &dataErr) { @@ -431,7 +465,7 @@ func (c *SimulatedBackendClient) PendingCallContract(ctx context.Context, msg et // Message string `json:"message"` // Data interface{} `json:"data,omitempty"` //} - res, err := c.b.PendingCallContract(ctx, msg) + res, err := c.client.PendingCallContract(ctx, msg) if err != nil { dataErr := revertError{} if errors.Is(err, &dataErr) { @@ -445,22 +479,22 @@ func (c *SimulatedBackendClient) PendingCallContract(ctx context.Context, msg et // CodeAt gets the code associated with an account as of a specified block. func (c *SimulatedBackendClient) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) { - return c.b.CodeAt(ctx, account, blockNumber) + return c.client.CodeAt(ctx, account, blockNumber) } // PendingCodeAt gets the latest code. func (c *SimulatedBackendClient) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { - return c.b.PendingCodeAt(ctx, account) + return c.client.PendingCodeAt(ctx, account) } // EstimateGas estimates gas for a msg. func (c *SimulatedBackendClient) EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error) { - return c.b.EstimateGas(ctx, call) + return c.client.EstimateGas(ctx, call) } // SuggestGasPrice recommends a gas price. func (c *SimulatedBackendClient) SuggestGasPrice(ctx context.Context) (*big.Int, error) { - panic("unimplemented") + return c.client.SuggestGasPrice(ctx) } // BatchCallContext makes a batch rpc call. @@ -506,10 +540,10 @@ func (c *SimulatedBackendClient) BatchCallContextAll(ctx context.Context, b []rp // SuggestGasTipCap suggests a gas tip cap. func (c *SimulatedBackendClient) SuggestGasTipCap(ctx context.Context) (tipCap *big.Int, err error) { - return c.b.SuggestGasTipCap(ctx) + return c.client.SuggestGasTipCap(ctx) } -func (c *SimulatedBackendClient) Backend() *backends.SimulatedBackend { +func (c *SimulatedBackendClient) Backend() evmtypes.Backend { return c.b } @@ -529,17 +563,17 @@ func (c *SimulatedBackendClient) IsL2() bool { func (c *SimulatedBackendClient) fetchHeader(ctx context.Context, blockNumOrTag string) (*types.Header, error) { switch blockNumOrTag { case rpc.SafeBlockNumber.String(): - return c.b.HeaderByNumber(ctx, big.NewInt(int64(rpc.SafeBlockNumber))) + return c.client.HeaderByNumber(ctx, big.NewInt(int64(rpc.SafeBlockNumber))) case rpc.LatestBlockNumber.String(): - return c.b.HeaderByNumber(ctx, big.NewInt(int64(rpc.LatestBlockNumber))) + return c.client.HeaderByNumber(ctx, big.NewInt(int64(rpc.LatestBlockNumber))) case rpc.FinalizedBlockNumber.String(): - return c.b.HeaderByNumber(ctx, big.NewInt(int64(rpc.FinalizedBlockNumber))) + return c.client.HeaderByNumber(ctx, big.NewInt(int64(rpc.FinalizedBlockNumber))) default: blockNum, ok := new(big.Int).SetString(blockNumOrTag, 0) if !ok { return nil, fmt.Errorf("error while converting block number string: %s to big.Int ", blockNumOrTag) } - return c.b.HeaderByNumber(ctx, blockNum) + return c.client.HeaderByNumber(ctx, blockNum) } } @@ -553,7 +587,7 @@ func (c *SimulatedBackendClient) ethGetTransactionReceipt(ctx context.Context, r return fmt.Errorf("SimulatedBackendClient expected arg to be a hash, got: %T", args[0]) } - receipt, err := c.b.TransactionReceipt(ctx, hash) + receipt, err := c.client.TransactionReceipt(ctx, hash) if err != nil { return err } @@ -625,7 +659,7 @@ func (c *SimulatedBackendClient) ethEstimateGas(ctx context.Context, result inte return fmt.Errorf("SimulatedBackendClient expected second arg to be the string 'latest' or a *big.Int for eth_call, got: %T", args[1]) } - resp, err := c.b.EstimateGas(ctx, toCallMsg(params)) + resp, err := c.client.EstimateGas(ctx, toCallMsg(params)) if err != nil { return err } @@ -656,7 +690,7 @@ func (c *SimulatedBackendClient) ethCall(ctx context.Context, result interface{} return fmt.Errorf("SimulatedBackendClient expected second arg to be the string 'latest' or a *big.Int for eth_call, got: %T", args[1]) } - resp, err := c.b.CallContract(ctx, toCallMsg(params), nil /* always latest block on simulated backend */) + resp, err := c.client.CallContract(ctx, toCallMsg(params), nil /* always latest block on simulated backend */) if err != nil { return err } @@ -687,7 +721,7 @@ func (c *SimulatedBackendClient) ethGetHeaderByNumber(ctx context.Context, resul return fmt.Errorf("SimulatedBackendClient expected first arg to be a string for eth_getHeaderByNumber: %w", err) } - header, err := c.b.HeaderByNumber(ctx, blockNumber) + header, err := c.client.HeaderByNumber(ctx, blockNumber) if err != nil { return err } @@ -703,7 +737,7 @@ func (c *SimulatedBackendClient) ethGetHeaderByNumber(ctx context.Context, resul } func (c *SimulatedBackendClient) LatestFinalizedBlock(ctx context.Context) (*evmtypes.Head, error) { - h, err := c.b.HeaderByNumber(ctx, big.NewInt(rpc.FinalizedBlockNumber.Int64())) + h, err := c.client.HeaderByNumber(ctx, big.NewInt(rpc.FinalizedBlockNumber.Int64())) if err != nil { return nil, err } @@ -773,7 +807,7 @@ func (c *SimulatedBackendClient) ethGetLogs(ctx context.Context, result interfac Addresses: addresses, Topics: topics, } - logs, err := c.b.FilterLogs(ctx, query) + logs, err := c.FilterLogs(ctx, query) if err != nil { return err } diff --git a/core/chains/evm/forwarders/forwarder_manager_test.go b/core/chains/evm/forwarders/forwarder_manager_test.go index 3a515e7ab39..9c4ab02fb40 100644 --- a/core/chains/evm/forwarders/forwarder_manager_test.go +++ b/core/chains/evm/forwarders/forwarder_manager_test.go @@ -5,15 +5,15 @@ import ( "testing" "time" - "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" - - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" @@ -42,26 +42,26 @@ func TestFwdMgr_MaybeForwardTransaction(t *testing.T) { owner := testutils.MustNewSimTransactor(t) ctx := testutils.Context(t) - ec := backends.NewSimulatedBackend(map[common.Address]core.GenesisAccount{ + b := simulated.NewBackend(types.GenesisAlloc{ owner.From: { Balance: big.NewInt(0).Mul(big.NewInt(10), big.NewInt(1e18)), }, - }, 10e6) - t.Cleanup(func() { ec.Close() }) + }, simulated.WithBlockGasLimit(10e6)) + t.Cleanup(func() { b.Close() }) linkAddr := common.HexToAddress("0x01BE23585060835E02B77ef475b0Cc51aA1e0709") - operatorAddr, _, _, err := operator_wrapper.DeployOperator(owner, ec, linkAddr, owner.From) + operatorAddr, _, _, err := operator_wrapper.DeployOperator(owner, b.Client(), linkAddr, owner.From) require.NoError(t, err) - forwarderAddr, _, forwarder, err := authorized_forwarder.DeployAuthorizedForwarder(owner, ec, linkAddr, owner.From, operatorAddr, []byte{}) + forwarderAddr, _, forwarder, err := authorized_forwarder.DeployAuthorizedForwarder(owner, b.Client(), linkAddr, owner.From, operatorAddr, []byte{}) require.NoError(t, err) - ec.Commit() + b.Commit() _, err = forwarder.SetAuthorizedSenders(owner, []common.Address{owner.From}) require.NoError(t, err) - ec.Commit() + b.Commit() authorized, err := forwarder.GetAuthorizedSenders(nil) require.NoError(t, err) t.Log(authorized) - evmClient := client.NewSimulatedBackendClient(t, ec, testutils.FixtureChainID) + evmClient := client.NewSimulatedBackendClient(t, b, testutils.FixtureChainID) lpOpts := logpoller.Opts{ PollPeriod: 100 * time.Millisecond, @@ -109,21 +109,21 @@ func TestFwdMgr_AccountUnauthorizedToForward_SkipsForwarding(t *testing.T) { cfg := configtest.NewTestGeneralConfig(t) evmcfg := evmtest.NewChainScopedConfig(t, cfg) owner := testutils.MustNewSimTransactor(t) - ec := backends.NewSimulatedBackend(map[common.Address]core.GenesisAccount{ + b := simulated.NewBackend(types.GenesisAlloc{ owner.From: { Balance: big.NewInt(0).Mul(big.NewInt(10), big.NewInt(1e18)), }, - }, 10e6) - t.Cleanup(func() { ec.Close() }) + }, simulated.WithBlockGasLimit(10e6)) + t.Cleanup(func() { b.Close() }) linkAddr := common.HexToAddress("0x01BE23585060835E02B77ef475b0Cc51aA1e0709") - operatorAddr, _, _, err := operator_wrapper.DeployOperator(owner, ec, linkAddr, owner.From) + operatorAddr, _, _, err := operator_wrapper.DeployOperator(owner, b.Client(), linkAddr, owner.From) require.NoError(t, err) - forwarderAddr, _, _, err := authorized_forwarder.DeployAuthorizedForwarder(owner, ec, linkAddr, owner.From, operatorAddr, []byte{}) + forwarderAddr, _, _, err := authorized_forwarder.DeployAuthorizedForwarder(owner, b.Client(), linkAddr, owner.From, operatorAddr, []byte{}) require.NoError(t, err) - ec.Commit() + b.Commit() - evmClient := client.NewSimulatedBackendClient(t, ec, testutils.FixtureChainID) + evmClient := client.NewSimulatedBackendClient(t, b, testutils.FixtureChainID) lpOpts := logpoller.Opts{ PollPeriod: 100 * time.Millisecond, FinalityDepth: 2, diff --git a/core/chains/evm/logpoller/helper_test.go b/core/chains/evm/logpoller/helper_test.go index a20c9dd493e..4282dc56d24 100644 --- a/core/chains/evm/logpoller/helper_test.go +++ b/core/chains/evm/logpoller/helper_test.go @@ -9,19 +9,20 @@ import ( "time" pkgerrors "github.com/pkg/errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller" + evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/log_emitter" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" @@ -37,7 +38,8 @@ type TestHarness struct { ChainID, ChainID2 *big.Int ORM, ORM2 logpoller.ORM LogPoller logpoller.LogPollerTest - Client *backends.SimulatedBackend + Client *client.SimulatedBackendClient + Backend evmtypes.Backend Owner *bind.TransactOpts Emitter1, Emitter2 *log_emitter.LogEmitter EmitterAddress1, EmitterAddress2 common.Address @@ -52,28 +54,28 @@ func SetupTH(t testing.TB, opts logpoller.Opts) TestHarness { o := logpoller.NewORM(chainID, db, lggr) o2 := logpoller.NewORM(chainID2, db, lggr) owner := testutils.MustNewSimTransactor(t) - ec := backends.NewSimulatedBackend(map[common.Address]core.GenesisAccount{ + + backend := simulated.NewBackend(types.GenesisAlloc{ owner.From: { Balance: big.NewInt(0).Mul(big.NewInt(10), big.NewInt(1e18)), }, - }, 10e6) + }, simulated.WithBlockGasLimit(10e6)) + // Poll period doesn't matter, we intend to call poll and save logs directly in the test. // Set it to some insanely high value to not interfere with any tests. - esc := client.NewSimulatedBackendClient(t, ec, chainID) - // Mark genesis block as finalized to avoid any nulls in the tests - //TODO OK to drop? - //head := esc.Backend().Blockchain().CurrentHeader() - //esc.Backend().Blockchain().SetFinalized(head) + + esc := client.NewSimulatedBackendClient(t, backend, chainID) if opts.PollPeriod == 0 { opts.PollPeriod = 1 * time.Hour } lp := logpoller.NewLogPoller(o, esc, lggr, opts) - emitterAddress1, _, emitter1, err := log_emitter.DeployLogEmitter(owner, ec) + emitterAddress1, _, emitter1, err := log_emitter.DeployLogEmitter(owner, backend.Client()) require.NoError(t, err) - emitterAddress2, _, emitter2, err := log_emitter.DeployLogEmitter(owner, ec) + emitterAddress2, _, emitter2, err := log_emitter.DeployLogEmitter(owner, backend.Client()) require.NoError(t, err) - ec.Commit() + backend.Commit() + return TestHarness{ Lggr: lggr, ChainID: chainID, @@ -81,7 +83,8 @@ func SetupTH(t testing.TB, opts logpoller.Opts) TestHarness { ORM: o, ORM2: o2, LogPoller: lp, - Client: ec, + Client: esc, + Backend: backend, Owner: owner, Emitter1: emitter1, Emitter2: emitter2, @@ -112,3 +115,10 @@ func (th *TestHarness) assertHaveCanonical(t *testing.T, start, end int) { assert.Equal(t, chainBlk.Hash().Bytes(), blk.BlockHash.Bytes(), "block %v", i) } } + +// Simulates an RPC failover event to an alternate rpc server. This can also be used to +// simulate switching back to the primary rpc after it recovers. +func (th *TestHarness) SetActiveClient(backend evmtypes.Backend, chainFamily evmtypes.ChainFamily) { + th.Backend = backend + th.Client.SetBackend(backend, chainFamily) +} diff --git a/core/chains/evm/logpoller/log_poller.go b/core/chains/evm/logpoller/log_poller.go index b1d7d1da623..19115cd75f0 100644 --- a/core/chains/evm/logpoller/log_poller.go +++ b/core/chains/evm/logpoller/log_poller.go @@ -27,6 +27,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/types/query" "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink-common/pkg/utils/mathutil" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" ubig "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big" diff --git a/core/chains/evm/logpoller/log_poller_test.go b/core/chains/evm/logpoller/log_poller_test.go index cb7ae53ba70..6b9cb9d1e6e 100644 --- a/core/chains/evm/logpoller/log_poller_test.go +++ b/core/chains/evm/logpoller/log_poller_test.go @@ -10,13 +10,10 @@ import ( "github.com/cometbft/cometbft/libs/rand" "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core" - "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/params" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/leanovate/gopter" "github.com/leanovate/gopter/gen" "github.com/leanovate/gopter/prop" @@ -156,7 +153,7 @@ func TestLogPoller_Integration(t *testing.T) { BackupPollerBlockDelay: 100, } th := SetupTH(t, lpOpts) - th.Client.Commit() // Block 2. Ensure we have finality number of blocks + th.Backend.Commit() // Block 2. Ensure we have finality number of blocks ctx := testutils.Context(t) require.NoError(t, th.LogPoller.RegisterFilter(ctx, logpoller.Filter{Name: "Integration test", EventSigs: []common.Hash{EmitterABI.Events["Log1"].ID}, Addresses: []common.Address{th.EmitterAddress1}})) @@ -172,7 +169,7 @@ func TestLogPoller_Integration(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter1.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() } // Calling Start() after RegisterFilter() simulates a node restart after job creation, should reload Filter from db. require.NoError(t, th.LogPoller.Start(testutils.Context(t))) @@ -226,8 +223,9 @@ func TestLogPoller_Integration(t *testing.T) { assert.ErrorIs(t, th.LogPoller.Replay(ctx, 4), logpoller.ErrReplayRequestAborted) } -// Simulate a badly behaving rpc server, where unfinalized blocks can return different logs -// for the same block hash. We should be able to handle this without missing any logs, as +// Simulate an rpc failover event on optimism, where logs are requested from a block hash which doesn't +// exist on the new rpc server, but a successful error code is returned. This is bad/buggy behavior on the +// part of the rpc server, but we should be able to handle this without missing any logs, as // long as the logs returned for finalized blocks are consistent. func Test_BackupLogPoller(t *testing.T) { tests := []struct { @@ -259,15 +257,6 @@ func Test_BackupLogPoller(t *testing.T) { BackupPollerBlockDelay: 100, }, ) - // later, we will need at least 32 blocks filled with logs for cache invalidation - for i := int64(0); i < 32; i++ { - // to invalidate geth's internal read-cache, a matching log must be found in the bloom Filter - // for each of the 32 blocks - tx, err := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(i + 7)}) - require.NoError(t, err) - require.NotNil(t, tx) - th.Client.Commit() - } ctx := testutils.Context(t) @@ -301,6 +290,11 @@ func Test_BackupLogPoller(t *testing.T) { assert.NoError(t, th.LogPoller.UnregisterFilter(ctx, "filter2")) }() + for n := 1; n < 31; n++ { + h := th.Backend.Commit() + require.Len(t, h, 32) + } + // generate some tx's with logs tx1, err := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(1)}) require.NoError(t, err) @@ -314,83 +308,82 @@ func Test_BackupLogPoller(t *testing.T) { require.NoError(t, err) require.NotNil(t, tx3) - th.Client.Commit() // commit block 34 with 3 tx's included + th.Backend.Commit() // commit block 32 with 3 tx's included - h, err := th.Client.HeaderByNumber(ctx, nil) // get latest header + block32, err := th.Client.BlockByNumber(ctx, nil) require.NoError(t, err) - require.Equal(t, uint64(34), h.Number.Uint64()) + require.Equal(t, uint64(32), block32.Number().Uint64()) - // save these 3 receipts for later - receipts := rawdb.ReadReceipts(th.EthDB, h.Hash(), h.Number.Uint64(), uint64(time.Now().Unix()), params.AllEthashProtocolChanges) - require.NotZero(t, receipts.Len()) + // Ensure that the logs have been included in this rpc server's view of the blockchain + txs := block32.Body().Transactions + require.Len(t, txs, 3) + receipt, err := th.Client.TransactionReceipt(ctx, txs[0].Hash()) + require.NoError(t, err) + require.NotZero(t, receipt) + require.Len(t, receipt.Logs, 1) - // Simulate a situation where the rpc server has a block, but no logs available for it yet - // this can't happen with geth itself, but can with other clients. - rawdb.WriteReceipts(th.EthDB, h.Hash(), h.Number.Uint64(), types.Receipts{}) // wipes out all logs for block 34 + // Simulate an optimism rpc server, which is behind and still syncing + backupRpc := simulated.NewBackend(types.GenesisAlloc{ + th.Owner.From: { + Balance: big.NewInt(0).Mul(big.NewInt(10), big.NewInt(1e18)), + }, + }, simulated.WithBlockGasLimit(10e6)) + + primaryRpc := th.Backend // save primaryRpc for later - body := rawdb.ReadBody(th.EthDB, h.Hash(), h.Number.Uint64()) - require.Equal(t, 3, len(body.Transactions)) - txs := body.Transactions // save transactions for later - body.Transactions = types.Transactions{} // number of tx's must match # of logs for GetLogs() to succeed - rawdb.WriteBody(th.EthDB, h.Hash(), h.Number.Uint64(), body) + // Failover to simulated optimism rpc on block 30 + th.Client.RegisterHeadByNumberCallback(func(ctx context.Context, c *client.SimulatedBackendClient, n *big.Int) error { + if n.Int64() != 32 { + return nil + } + th.SetActiveClient(backupRpc, evmtypes.Optimism) + return nil + }) currentBlockNumber := th.PollAndSaveLogs(ctx, 1) - assert.Equal(t, int64(35), currentBlockNumber) - - // simulate logs becoming available - rawdb.WriteReceipts(th.EthDB, h.Hash(), h.Number.Uint64(), receipts) - require.True(t, rawdb.HasReceipts(th.EthDB, h.Hash(), h.Number.Uint64())) - body.Transactions = txs - rawdb.WriteBody(th.EthDB, h.Hash(), h.Number.Uint64(), body) - - // flush out cached block 34 by reading logs from first 32 blocks - query := ethereum.FilterQuery{ - FromBlock: big.NewInt(int64(2)), - ToBlock: big.NewInt(int64(33)), - Addresses: []common.Address{th.EmitterAddress1}, - Topics: [][]common.Hash{{EmitterABI.Events["Log1"].ID}}, - } - fLogs, err := th.Client.FilterLogs(ctx, query) - require.NoError(t, err) - require.Equal(t, 32, len(fLogs)) + require.Equal(t, int64(33), currentBlockNumber) // logs shouldn't show up yet - logs, err := th.LogPoller.Logs(ctx, 34, 34, EmitterABI.Events["Log1"].ID, th.EmitterAddress1) + logs, err := th.LogPoller.Logs(ctx, 32, 32, EmitterABI.Events["Log1"].ID, th.EmitterAddress1) require.NoError(t, err) - assert.Equal(t, 0, len(logs)) + require.Equal(t, 0, len(logs)) - th.Client.Commit() - th.Client.Commit() - markBlockAsFinalized(t, th, 34) + finalizeThroughBlock(t, th, 32) + + b, ok := primaryRpc.(*simulated.Backend) + require.True(t, ok) + th.SetActiveClient(b, evmtypes.Optimism) // restore primary rpc // Run ordinary poller + backup poller at least once - currentBlock, _ := th.LogPoller.LatestBlock(ctx) - th.LogPoller.PollAndSaveLogs(ctx, currentBlock.BlockNumber+1) + require.NoError(t, err) + currentBlockNumber = th.PollAndSaveLogs(ctx, currentBlockNumber) + require.Equal(t, int64(33), currentBlockNumber) th.LogPoller.BackupPollAndSaveLogs(ctx) - currentBlock, _ = th.LogPoller.LatestBlock(ctx) - - require.Equal(t, int64(37), currentBlock.BlockNumber+1) + latestBlock, err := th.LogPoller.LatestBlock(ctx) + require.NoError(t, err) + require.Equal(t, currentBlockNumber-1, latestBlock.BlockNumber) // shouldn't change // logs still shouldn't show up, because we don't want to backfill the last finalized log // to help with reorg detection - logs, err = th.LogPoller.Logs(ctx, 34, 34, EmitterABI.Events["Log1"].ID, th.EmitterAddress1) + logs, err = th.LogPoller.Logs(ctx, 32, 32, EmitterABI.Events["Log1"].ID, th.EmitterAddress1) require.NoError(t, err) - assert.Equal(t, 0, len(logs)) - th.Client.Commit() - markBlockAsFinalized(t, th, 35) + require.Equal(t, 0, len(logs)) + th.Backend.Commit() + finalizeThroughBlock(t, th, 64) // Run ordinary poller + backup poller at least once more - th.LogPoller.PollAndSaveLogs(ctx, currentBlockNumber+1) + th.LogPoller.PollAndSaveLogs(ctx, currentBlockNumber) th.LogPoller.BackupPollAndSaveLogs(ctx) - currentBlock, _ = th.LogPoller.LatestBlock(ctx) + currentBlock, err := th.LogPoller.LatestBlock(ctx) + require.NoError(t, err) - require.Equal(t, int64(38), currentBlock.BlockNumber+1) + require.Equal(t, int64(64), currentBlock.BlockNumber) // all 3 logs in block 34 should show up now, thanks to backup logger logs, err = th.LogPoller.Logs(ctx, 30, 37, EmitterABI.Events["Log1"].ID, th.EmitterAddress1) require.NoError(t, err) - assert.Equal(t, 5, len(logs)) - logs, err = th.LogPoller.Logs(ctx, 34, 34, EmitterABI.Events["Log2"].ID, th.EmitterAddress1) + assert.Equal(t, 1, len(logs)) + logs, err = th.LogPoller.Logs(ctx, 32, 32, EmitterABI.Events["Log2"].ID, th.EmitterAddress1) require.NoError(t, err) assert.Equal(t, 1, len(logs)) logs, err = th.LogPoller.Logs(ctx, 32, 36, EmitterABI.Events["Log1"].ID, th.EmitterAddress2) @@ -401,7 +394,7 @@ func Test_BackupLogPoller(t *testing.T) { } func TestLogPoller_BackupPollAndSaveLogsWithPollerNotWorking(t *testing.T) { - emittedLogs := 30 + emittedLogs := 40 // Intentionally use very low backupLogPollerDelay to verify if finality is used properly ctx := testutils.Context(t) lpOpts := logpoller.Opts{ @@ -413,27 +406,25 @@ func TestLogPoller_BackupPollAndSaveLogsWithPollerNotWorking(t *testing.T) { } th := SetupTH(t, lpOpts) - header, err := th.Client.HeaderByNumber(ctx, nil) - require.NoError(t, err) - // Emit some logs in blocks for i := 0; i < emittedLogs; i++ { + if i == 30 { + // Call PollAndSave with no filters are registered. We call it on block 31, so that + // it misses the logs for blocks 2 - 31 but marks block 0 as finalized (rather than 32) + currentBlock := th.PollAndSaveLogs(ctx, 1) + // currentBlock should be blockChain start + number of emitted logs + 1 + assert.Equal(t, int64(32), currentBlock) + } + _, err2 := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() } - // First PollAndSave, no filters are registered - // 0 (finalized) -> 1 -> 2 -> ... - currentBlock := th.PollAndSaveLogs(ctx, 1) - // currentBlock should be blockChain start + number of emitted logs + 1 - assert.Equal(t, int64(emittedLogs)+header.Number.Int64()+1, currentBlock) - // LogPoller not working, but chain in the meantime has progressed - // 0 -> 1 -> 2 -> ... -> currentBlock - 10 (finalized) -> .. -> currentBlock - markBlockAsFinalized(t, th, currentBlock-10) + // 0 -> 1 -> 2 -> ... -> 32 (finalized) -> .. -> 42 (currentBlock) - err = th.LogPoller.RegisterFilter(ctx, logpoller.Filter{ + err := th.LogPoller.RegisterFilter(ctx, logpoller.Filter{ Name: "Test Emitter", EventSigs: []common.Hash{EmitterABI.Events["Log1"].ID}, Addresses: []common.Address{th.EmitterAddress1}, @@ -448,23 +439,22 @@ func TestLogPoller_BackupPollAndSaveLogsWithPollerNotWorking(t *testing.T) { logs, err := th.LogPoller.Logs( ctx, 0, - currentBlock, + 42, EmitterABI.Events["Log1"].ID, th.EmitterAddress1, ) require.NoError(t, err) require.Len(t, logs, emittedLogs-10) - // Progressing even more, move blockchain forward by 1 block and mark it as finalized - th.Client.Commit() - markBlockAsFinalized(t, th, currentBlock) + // Finalize the rest of the logs emitted, after which Backup Poller should pick them up + finalizeThroughBlock(t, th, 42) th.LogPoller.BackupPollAndSaveLogs(ctx) // All emitted logs should be backfilled logs, err = th.LogPoller.Logs( ctx, 0, - currentBlock+1, + 43, EmitterABI.Events["Log1"].ID, th.EmitterAddress1, ) @@ -488,15 +478,15 @@ func TestLogPoller_BackupPollAndSaveLogsWithDeepBlockDelay(t *testing.T) { for i := 0; i < emittedLogs; i++ { _, err := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err) - th.Client.Commit() + th.Backend.Commit() } // Emit one more empty block - th.Client.Commit() + th.Backend.Commit() header, err := th.Client.HeaderByNumber(ctx, nil) require.NoError(t, err) // Mark everything as finalized - markBlockAsFinalized(t, th, header.Number.Int64()) + //markBlockAsFinalized(t, th, header.Number.Int64()) // First PollAndSave, no filters are registered, but finalization is the same as the latest block // 1 -> 2 -> ... @@ -548,28 +538,30 @@ func TestLogPoller_BackupPollAndSaveLogsSkippingLogsThatAreTooOld(t *testing.T) // Emit some logs in blocks for i := 1; i <= logsBatch; i++ { - _, err := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) + _, err := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(0x100 + i))}) require.NoError(t, err) - th.Client.Commit() + th.Backend.Commit() } // First PollAndSave, no filters are registered, but finalization is the same as the latest block // 1 -> 2 -> ... -> firstBatchBlock - firstBatchBlock := th.PollAndSaveLogs(ctx, 1) - // Mark current tip of the chain as finalized (after emitting 10 logs) - markBlockAsFinalized(t, th, firstBatchBlock-1) + firstBatchBlock := th.PollAndSaveLogs(ctx, 1) - 1 + + // Mark all blocks from first batch of emitted logs as finalized + finalizeThroughBlock(t, th, firstBatchBlock) // Emit 2nd batch of block for i := 1; i <= logsBatch; i++ { - _, err := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(100 + i))}) + _, err := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(0x200 + i))}) require.NoError(t, err) - th.Client.Commit() + th.Backend.Commit() } - // 1 -> 2 -> ... -> firstBatchBlock (finalized) -> .. -> firstBatchBlock + emitted logs - secondBatchBlock := th.PollAndSaveLogs(ctx, firstBatchBlock) - // Mark current tip of the block as finalized (after emitting 20 logs) - markBlockAsFinalized(t, th, secondBatchBlock-1) + // 1 -> 2 -> ... -> firstBatchBlock (finalized) -> .. -> firstBatchBlock + logsBatch + secondBatchBlock := th.PollAndSaveLogs(ctx, firstBatchBlock) - 1 + + // Mark all blocks from second batch of emitted logs as finalized + finalizeThroughBlock(t, th, secondBatchBlock) // Register filter err := th.LogPoller.RegisterFilter(ctx, logpoller.Filter{ @@ -583,8 +575,8 @@ func TestLogPoller_BackupPollAndSaveLogsSkippingLogsThatAreTooOld(t *testing.T) th.LogPoller.BackupPollAndSaveLogs(ctx) require.NoError(t, err) - // Only the 2nd batch + 1 log from a previous batch should be backfilled, because we perform backfill starting - // from one block behind the latest finalized block + // Only the 2nd batch should be backfilled, because we perform backfill starting from one + // behind the latest finalized block logs, err := th.LogPoller.Logs( ctx, 0, @@ -594,7 +586,7 @@ func TestLogPoller_BackupPollAndSaveLogsSkippingLogsThatAreTooOld(t *testing.T) ) require.NoError(t, err) require.Len(t, logs, logsBatch) - require.Equal(t, hexutil.MustDecode(`0x000000000000000000000000000000000000000000000000000000000000000a`), logs[0].Data) + require.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000201`), logs[0].Data) // 0x201 = 1st log from 2nd batch } func TestLogPoller_BlockTimestamps(t *testing.T) { @@ -619,39 +611,37 @@ func TestLogPoller_BlockTimestamps(t *testing.T) { require.Equal(t, big.NewInt(1), blk.Number()) start := blk.Time() - // There is automatically a 10s delay between each block. To make sure it's including the correct block timestamps, + // There is automatically a 1ns delay between each block. To make sure it's including the correct block timestamps, // we introduce irregularities by inserting two additional block delays. We can't control the block times for // blocks produced by the log emitter, but we can adjust the time on empty blocks in between. Simulated time - // sequence: [ #1 ] ..(10s + delay1).. [ #2 ] ..10s.. [ #3 (LOG1) ] ..(10s + delay2).. [ #4 ] ..10s.. [ #5 (LOG2) ] - const delay1 = 589 - const delay2 = 643 - time1 := start + 20 + delay1 - time2 := time1 + 20 + delay2 + // sequence: [ #1 ] ..(1ns + delay1).. [ #2 ] ..1ns.. [ #3 (LOG1) ] ..(1ns + delay2).. [ #4 ] ..1ns.. [ #5 (LOG2) ] + const delay1 = 589 * time.Second + const delay2 = 643 * time.Second + time1 := start + 1 + uint64(delay1) + time2 := time1 + 1 + uint64(delay2) - require.NoError(t, th.Client.AdjustTime(delay1*time.Second)) - hash := th.Client.Commit() + require.NoError(t, th.Backend.AdjustTime(delay1)) - blk, err = th.Client.BlockByHash(ctx, hash) + blk, err = th.Client.BlockByNumber(ctx, nil) require.NoError(t, err) require.Equal(t, big.NewInt(2), blk.Number()) - assert.Equal(t, time1-10, blk.Time()) + assert.Equal(t, time1-1, blk.Time()) _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(1)}) require.NoError(t, err) - hash = th.Client.Commit() + hash := th.Backend.Commit() blk, err = th.Client.BlockByHash(ctx, hash) require.NoError(t, err) require.Equal(t, big.NewInt(3), blk.Number()) assert.Equal(t, time1, blk.Time()) - require.NoError(t, th.Client.AdjustTime(delay2*time.Second)) - th.Client.Commit() + require.NoError(t, th.Backend.AdjustTime(delay2)) _, err = th.Emitter2.EmitLog2(th.Owner, []*big.Int{big.NewInt(2)}) require.NoError(t, err) - hash = th.Client.Commit() + th.Client.Commit() - blk, err = th.Client.BlockByHash(ctx, hash) + blk, err = th.Client.BlockByNumber(ctx, nil) require.NoError(t, err) require.Equal(t, big.NewInt(5), blk.Number()) assert.Equal(t, time2, blk.Time()) @@ -703,11 +693,12 @@ func TestLogPoller_SynchronizedWithGeth(t *testing.T) { // Set up a test chain with a log emitting contract deployed. orm := logpoller.NewORM(chainID, db, lggr) // Note this property test is run concurrently and the sim is not threadsafe. - ec := backends.NewSimulatedBackend(map[common.Address]core.GenesisAccount{ + backend := simulated.NewBackend(types.GenesisAlloc{ owner.From: { Balance: big.NewInt(0).Mul(big.NewInt(10), big.NewInt(1e18)), }, - }, 10e6) + }, simulated.WithBlockGasLimit(10e6)) + ec := backend.Client() _, _, emitter1, err := log_emitter.DeployLogEmitter(owner, ec) require.NoError(t, err) @@ -718,9 +709,9 @@ func TestLogPoller_SynchronizedWithGeth(t *testing.T) { RpcBatchSize: 2, KeepFinalizedBlocksDepth: 1000, } - lp := logpoller.NewLogPoller(orm, client.NewSimulatedBackendClient(t, ec, chainID), lggr, lpOpts) + lp := logpoller.NewLogPoller(orm, client.NewSimulatedBackendClient(t, backend, chainID), lggr, lpOpts) for i := 0; i < finalityDepth; i++ { // Have enough blocks that we could reorg the full finalityDepth-1. - ec.Commit() + backend.Commit() } currentBlockNumber := int64(1) lp.PollAndSaveLogs(testutils.Context(t), currentBlockNumber) @@ -750,7 +741,7 @@ func TestLogPoller_SynchronizedWithGeth(t *testing.T) { if rand.Bool() { // Mine blocks for j := 0; j < int(mineOrReorg[i]); j++ { - ec.Commit() + backend.Commit() latest, err1 := ec.BlockByNumber(testutils.Context(t), nil) require.NoError(t, err1) t.Log("mined block", latest.Hash()) @@ -762,13 +753,13 @@ func TestLogPoller_SynchronizedWithGeth(t *testing.T) { reorgedBlock := big.NewInt(0).Sub(latest.Number(), big.NewInt(int64(mineOrReorg[i]))) reorg, err1 := ec.BlockByNumber(testutils.Context(t), reorgedBlock) require.NoError(t, err1) - require.NoError(t, ec.Fork(testutils.Context(t), reorg.Hash())) + require.NoError(t, backend.Fork(reorg.Hash())) t.Logf("Reorging from (%v, %x) back to (%v, %x)\n", latest.NumberU64(), latest.Hash(), reorgedBlock.Uint64(), reorg.Hash()) // Actually need to change the block here to trigger the reorg. _, err1 = emitter1.EmitLog1(owner, []*big.Int{big.NewInt(1)}) require.NoError(t, err1) for j := 0; j < int(mineOrReorg[i]+1); j++ { // Need +1 to make it actually longer height so we detect it. - ec.Commit() + backend.Commit() } latest, err1 = ec.BlockByNumber(testutils.Context(t), nil) require.NoError(t, err1) @@ -825,7 +816,6 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { b, err := th.Client.BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) require.Equal(t, uint64(1), b.NumberU64()) - require.Equal(t, uint64(10), b.Time()) // Test scenario: single block in chain, no logs. // Chain genesis <- 1 @@ -839,7 +829,6 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { assert.Equal(t, lpb.BlockHash, b.Hash()) assert.Equal(t, lpb.BlockNumber, int64(b.NumberU64())) assert.Equal(t, int64(1), int64(b.NumberU64())) - assert.Equal(t, uint64(10), b.Time()) // No logs. lgs, err := th.ORM.SelectLogsByBlockRange(testutils.Context(t), 1, 1) @@ -860,7 +849,7 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { // DB: 1 _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(1)}) require.NoError(t, err) - th.Client.Commit() + th.Backend.Commit() // Polling should get us the L1 log. newStart = th.PollAndSaveLogs(testutils.Context(t), newStart) @@ -884,19 +873,17 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { // DB: 1, 2 // - Detect a reorg, // - Update the block 2's hash - // - Save L1' + // - Save L1_2 // - L1_1 deleted - reorgedOutBlock, err := th.Client.BlockByNumber(testutils.Context(t), big.NewInt(2)) - require.NoError(t, err) lca, err := th.Client.BlockByNumber(testutils.Context(t), big.NewInt(1)) require.NoError(t, err) - require.NoError(t, th.Client.Fork(testutils.Context(t), lca.Hash())) + require.NoError(t, th.Backend.Fork(lca.Hash())) _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(2)}) require.NoError(t, err) // Create 2' - th.Client.Commit() + th.Backend.Commit() // Create 3 (we need a new block for us to do any polling and detect the reorg). - th.Client.Commit() + th.Backend.Commit() newStart = th.PollAndSaveLogs(testutils.Context(t), newStart) assert.Equal(t, int64(4), newStart) @@ -909,18 +896,26 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000002`), lgs[0].Data) th.assertHaveCanonical(t, 1, 3) - // Test scenario: reorg back to previous tip. - // Chain gen <- 1 <- 2 (L1_1) <- 3' (L1_3) <- 4 - // \ 2'(L1_2) <- 3 - require.NoError(t, th.Client.Fork(testutils.Context(t), reorgedOutBlock.Hash())) + parent, err := th.Client.BlockByNumber(testutils.Context(t), big.NewInt(1)) + require.NoError(t, err) + + // Test scenario: reorg back to a chain that looks similar to the original chain. (simulated geth used to allow + // re-org'ing back to exactly the same chain--now the best we can do is re-emit the same logs on a new one to simulate that) + // Chain gen <- 1 <- 2 (L1_1) + // \ 2' (L1_2) <- 3 + // \ 2''(L1_1) <- 3' <- 4 + require.NoError(t, th.Backend.Fork(parent.Hash())) + // Re-emit L1 to make 2'' tip look like original 2 tip + _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(1)}) + require.NoError(t, err) + th.Backend.Commit() _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(3)}) require.NoError(t, err) // Create 3' - th.Client.Commit() + th.Backend.Commit() // Create 4 - th.Client.Commit() - // Mark block 1 as finalized - markBlockAsFinalized(t, th, 1) + th.Backend.Commit() + newStart = th.PollAndSaveLogs(testutils.Context(t), newStart) assert.Equal(t, int64(5), newStart) latest, err = th.ORM.SelectLatestBlock(testutils.Context(t)) @@ -928,8 +923,8 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { assert.Equal(t, int64(4), latest.BlockNumber) lgs, err = th.ORM.SelectLogsByBlockRange(testutils.Context(t), 1, 3) require.NoError(t, err) - // We expect ONLY L1_1 and L1_3 since L1_2 is reorg'd out. - assert.Equal(t, 2, len(lgs)) + + require.Equal(t, 2, len(lgs)) assert.Equal(t, int64(2), lgs[0].BlockNumber) assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000001`), lgs[0].Data) assert.Equal(t, int64(3), lgs[1].BlockNumber) @@ -949,13 +944,15 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { _, err = th.Emitter2.EmitLog1(th.Owner, []*big.Int{big.NewInt(5)}) require.NoError(t, err) // Create 4 - th.Client.Commit() + th.Backend.Commit() _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(6)}) require.NoError(t, err) // Create 5 - th.Client.Commit() + th.Backend.Commit() // Mark block 2 as finalized - markBlockAsFinalized(t, th, 3) + //if tt.finalityTag { + // finalizeThroughBlock(t, th, 3) + //} newStart = th.PollAndSaveLogs(testutils.Context(t), newStart) assert.Equal(t, int64(7), newStart) @@ -982,10 +979,8 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { for i := 7; i < 11; i++ { _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err) - th.Client.Commit() + th.Backend.Commit() } - // Mark block 7 as finalized - markBlockAsFinalized(t, th, 7) newStart = th.PollAndSaveLogs(testutils.Context(t), newStart) assert.Equal(t, int64(11), newStart) @@ -998,43 +993,42 @@ func TestLogPoller_PollAndSaveLogs(t *testing.T) { assert.Equal(t, int64(8), lgs[1].BlockNumber) assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000009`), lgs[2].Data) assert.Equal(t, int64(9), lgs[2].BlockNumber) - th.assertDontHave(t, 7, 7) // Do not expect to save backfilled blocks. th.assertHaveCanonical(t, 8, 10) // Test scenario large backfill (multiple batches) - // Chain gen <- 1 <- 2 (L1_1) <- 3' L1_3 <- 4 <- 5 (L1_4, L2_5) <- 6 (L1_6) <- 7 (L1_7) <- 8 (L1_8) <- 9 (L1_9) <- 10..16 + // Chain gen <- 1 <- 2 (L1_1) <- 3' L1_3 <- 4 <- 5 (L1_4, L2_5) <- 6 (L1_6) <- 7 (L1_7) <- 8 (L1_8) <- 9 (L1_9) <- 10..32 // \ 2'(L1_2) <- 3 - // DB: 1, 2, 3, 4, 5, 6, (backfilled 7), 8, 9, 10 - // - 11, 12, 13 backfilled in batch 1 - // - 14 backfilled in batch 2 - // - 15, 16, 17 to be treated as unfinalized - for i := 11; i < 18; i++ { + // DB: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 + // - 11 - 13 backfilled in batch 1 + // - 14 - 16 backfilled in batch 2 + // ... + // - 33, 34, 35 to be treated as unfinalized + for i := 11; i < 36; i++ { _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err) - th.Client.Commit() + th.Backend.Commit() } - // Mark block 14 as finalized - markBlockAsFinalized(t, th, 14) newStart = th.PollAndSaveLogs(testutils.Context(t), newStart) - assert.Equal(t, int64(18), newStart) - lgs, err = th.ORM.SelectLogsByBlockRange(testutils.Context(t), 11, 17) + assert.Equal(t, int64(36), newStart) + lgs, err = th.ORM.SelectLogsByBlockRange(testutils.Context(t), 11, 36) require.NoError(t, err) - assert.Equal(t, 7, len(lgs)) - th.assertHaveCanonical(t, 14, 16) // Should have last finalized block plus unfinalized blocks + assert.Equal(t, 25, len(lgs)) + th.assertHaveCanonical(t, 32, 36) // Should have last finalized block plus unfinalized blocks th.assertDontHave(t, 11, 13) // Should not have older finalized blocks + th.assertDontHave(t, 14, 16) // Should not have older finalized blocks // Verify that a custom block timestamp will get written to db correctly also b, err = th.Client.BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) - require.Equal(t, uint64(17), b.NumberU64()) - require.Equal(t, uint64(170), b.Time()) - require.NoError(t, th.Client.AdjustTime(1*time.Hour)) - th.Client.Commit() + require.Equal(t, uint64(35), b.NumberU64()) + blockTimestamp := b.Time() + require.NoError(t, th.Backend.AdjustTime(time.Hour)) + th.Backend.Commit() b, err = th.Client.BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) - require.Equal(t, uint64(180+time.Hour.Seconds()), b.Time()) + require.Equal(t, blockTimestamp+uint64(time.Hour)+1, b.Time()) }) } } @@ -1076,51 +1070,50 @@ func TestLogPoller_ReorgDeeperThanFinality(t *testing.T) { require.NoError(t, err) // Test scenario - // Chain gen <- 1 <- 2 <- 3 (finalized) <- 4 (L1_1) + // Chain gen <- 1 <- 2 <- ... <- 32 (finalized) <- 33 (L1_1) + finalizeThroughBlock(t, th, 32) _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(1)}) require.NoError(t, err) - th.Client.Commit() - th.Client.Commit() - th.Client.Commit() - markBlockAsFinalized(t, th, 3) + th.Backend.Commit() // Polling should get us the L1 log. firstPoll := th.PollAndSaveLogs(testutils.Context(t), 1) - assert.Equal(t, int64(5), firstPoll) + assert.Equal(t, int64(34), firstPoll) assert.NoError(t, th.LogPoller.Healthy()) // Fork deeper than finality depth - // Chain gen <- 1 <- 2 <- 3 (finalized) <- 4 (L1_1) - // \ 2' <- 3' <- 4' <- 5' <- 6' (finalized) <- 7' <- 8' <- 9' <- 10' (L1_2) - lca, err := th.Client.BlockByNumber(testutils.Context(t), big.NewInt(1)) + // Chain gen <- 1 <- 2 <- 3 <- ... <- 32 (finalized) <- 33 (L1_1) + // \ <- 3' <- ... <- 31' <- 32' (finalized) <- 33' <- 34' (L1_2) + lca, err := th.Client.BlockByNumber(testutils.Context(t), big.NewInt(2)) require.NoError(t, err) - require.NoError(t, th.Client.Fork(testutils.Context(t), lca.Hash())) + require.NoError(t, th.Backend.Fork(lca.Hash())) - // Create 2' - _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(2)}) + // Create 3' + _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(3)}) require.NoError(t, err) - th.Client.Commit() + th.Backend.Commit() - // Create 3-10 - for i := 3; i < 10; i++ { + finalizeThroughBlock(t, th, 32) + + // Create 33' - 34' + for i := 33; i < 35; i++ { _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err) - th.Client.Commit() + th.Backend.Commit() } - markBlockAsFinalized(t, th, 6) secondPoll := th.PollAndSaveLogs(testutils.Context(t), firstPoll) assert.Equal(t, firstPoll, secondPoll) assert.Equal(t, logpoller.ErrFinalityViolated, th.LogPoller.Healthy()) - // Manually remove latest block from the log poller to bring it back to life + // Manually remove re-org'd chain from the log poller to bring it back to life // LogPoller should be healthy again after first poll - // Chain gen <- 1 - // \ 2' <- 3' <- 4' <- 5' <- 6' (finalized) <- 7' <- 8' <- 9' <- 10' (L1_2) - require.NoError(t, th.ORM.DeleteLogsAndBlocksAfter(testutils.Context(t), 2)) + // Chain gen <- 1 <- 2 + // \ <- 3' <- 4' <- 5' <- 32' (finalized) <- 33' <- 34' (L1_2) + require.NoError(t, th.ORM.DeleteLogsAndBlocksAfter(testutils.Context(t), 3)) // Poll from latest recoveryPoll := th.PollAndSaveLogs(testutils.Context(t), 1) - assert.Equal(t, int64(10), recoveryPoll) + assert.Equal(t, int64(35), recoveryPoll) assert.NoError(t, th.LogPoller.Healthy()) }) } @@ -1151,8 +1144,8 @@ func TestLogPoller_PollAndSaveLogsDeepReorg(t *testing.T) { lpOpts := logpoller.Opts{ UseFinalityTag: tt.finalityTag, FinalityDepth: tt.finalityDepth, - BackfillBatchSize: 3, - RpcBatchSize: 2, + BackfillBatchSize: 50, + RpcBatchSize: 50, KeepFinalizedBlocksDepth: 1000, } th := SetupTH(t, lpOpts) @@ -1170,8 +1163,8 @@ func TestLogPoller_PollAndSaveLogsDeepReorg(t *testing.T) { // DB: 1 _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(1)}) require.NoError(t, err) - th.Client.Commit() - markBlockAsFinalized(t, th, 1) + th.Backend.Commit() + //markBlockAsFinalized(t, th, 1) // Polling should get us the L1 log. newStart := th.PollAndSaveLogs(testutils.Context(t), 1) @@ -1185,34 +1178,34 @@ func TestLogPoller_PollAndSaveLogsDeepReorg(t *testing.T) { // Single block reorg and log poller not working for a while, mine blocks and progress with finalization // Chain gen <- 1 <- 2 (L1_1) - // \ 2'(L1_2) <- 3 <- 4 <- 5 <- 6 (finalized on chain) <- 7 <- 8 <- 9 <- 10 + // \ 2'(L1_2) <- 3' <- 4' <- ... <- 32' (finalized on chain) <- 33' <- 34' <- 35' lca, err := th.Client.BlockByNumber(testutils.Context(t), big.NewInt(1)) require.NoError(t, err) - require.NoError(t, th.Client.Fork(testutils.Context(t), lca.Hash())) + require.NoError(t, th.Backend.Fork(lca.Hash())) // Create 2' _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(2)}) require.NoError(t, err) - th.Client.Commit() - // Create 3-10 - for i := 3; i < 10; i++ { + th.Backend.Commit() + // Create 3-35 + for i := 3; i <= 35; i++ { _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err) - th.Client.Commit() + th.Backend.Commit() } - markBlockAsFinalized(t, th, 6) + finalizeThroughBlock(t, th, 32) newStart = th.PollAndSaveLogs(testutils.Context(t), newStart) - assert.Equal(t, int64(10), newStart) + assert.Equal(t, int64(36), newStart) assert.NoError(t, th.LogPoller.Healthy()) // Expect L1_2 to be properly updated - lgs, err = th.ORM.SelectLogsByBlockRange(testutils.Context(t), 2, 2) + lgs, err = th.ORM.SelectLogsByBlockRange(testutils.Context(t), 2, 31) require.NoError(t, err) - require.NotZero(t, len(lgs)) + require.Len(t, lgs, 30) assert.Equal(t, hexutil.MustDecode(`0x0000000000000000000000000000000000000000000000000000000000000002`), lgs[0].Data) - th.assertHaveCanonical(t, 1, 1) - th.assertDontHave(t, 2, 3) // These blocks are backfilled - th.assertHaveCanonical(t, 5, 10) + th.assertHaveCanonical(t, 1, 2) + th.assertDontHave(t, 2, 31) // These blocks are backfilled + th.assertHaveCanonical(t, 32, 36) }) } } @@ -1314,11 +1307,11 @@ func TestLogPoller_GetBlocks_Range(t *testing.T) { _, err := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(1)}) require.NoError(t, err) - th.Client.Commit() // Commit block #2 with log in it + th.Backend.Commit() // Commit block #2 with log in it _, err = th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(2)}) require.NoError(t, err) - th.Client.Commit() // Commit block #3 with a different log + th.Backend.Commit() // Commit block #3 with a different log err = th.LogPoller.RegisterFilter(testutils.Context(t), logpoller.Filter{ Name: "GetBlocks Test", @@ -1346,7 +1339,7 @@ func TestLogPoller_GetBlocks_Range(t *testing.T) { require.Error(t, err) assert.Equal(t, "Received unfinalized block 2 while expecting finalized block (latestFinalizedBlockNumber = 1)", err.Error()) - th.Client.Commit() // Commit block #4, so that block #2 is finalized + th.Backend.Commit() // Commit block #4, so that block #2 is finalized // Assert block 2 is not yet in DB _, err = th.ORM.SelectBlockByNumber(testutils.Context(t), 2) @@ -1358,7 +1351,7 @@ func TestLogPoller_GetBlocks_Range(t *testing.T) { assert.Equal(t, 1, len(rpcBlocks)) assert.Equal(t, 2, int(rpcBlocks[0].BlockNumber)) - th.Client.Commit() // commit block #5 so that #3 becomes finalized + th.Backend.Commit() // commit block #5 so that #3 becomes finalized // Assert block 3 is not yet in DB _, err = th.ORM.SelectBlockByNumber(testutils.Context(t), 3) @@ -1429,7 +1422,7 @@ func TestGetReplayFromBlock(t *testing.T) { th := SetupTH(t, lpOpts) // Commit a few blocks for i := 0; i < 10; i++ { - th.Client.Commit() + th.Backend.Commit() } // Nothing in the DB yet, should use whatever we specify. @@ -1444,7 +1437,7 @@ func TestGetReplayFromBlock(t *testing.T) { // Commit a few more so chain is ahead. for i := 0; i < 3; i++ { - th.Client.Commit() + th.Backend.Commit() } // Should take min(latest, requested), in this case latest. requested = int64(15) @@ -1471,20 +1464,21 @@ func TestLogPoller_DBErrorHandling(t *testing.T) { o := logpoller.NewORM(chainID1, db, lggr) owner := testutils.MustNewSimTransactor(t) - ec := backends.NewSimulatedBackend(map[common.Address]core.GenesisAccount{ + backend := simulated.NewBackend(types.GenesisAlloc{ owner.From: { Balance: big.NewInt(0).Mul(big.NewInt(10), big.NewInt(1e18)), }, - }, 10e6) + }, simulated.WithBlockGasLimit(10e6)) + ec := backend.Client() _, _, emitter, err := log_emitter.DeployLogEmitter(owner, ec) require.NoError(t, err) _, err = emitter.EmitLog1(owner, []*big.Int{big.NewInt(9)}) require.NoError(t, err) _, err = emitter.EmitLog1(owner, []*big.Int{big.NewInt(7)}) require.NoError(t, err) - ec.Commit() - ec.Commit() - ec.Commit() + backend.Commit() + backend.Commit() + backend.Commit() lpOpts := logpoller.Opts{ PollPeriod: time.Hour, @@ -1493,7 +1487,7 @@ func TestLogPoller_DBErrorHandling(t *testing.T) { RpcBatchSize: 2, KeepFinalizedBlocksDepth: 1000, } - lp := logpoller.NewLogPoller(o, client.NewSimulatedBackendClient(t, ec, chainID2), lggr, lpOpts) + lp := logpoller.NewLogPoller(o, client.NewSimulatedBackendClient(t, backend, chainID2), lggr, lpOpts) err = lp.Replay(ctx, 5) // block number too high require.ErrorContains(t, err, "Invalid replay block number") @@ -1655,23 +1649,25 @@ func Test_PollAndQueryFinalizedBlocks(t *testing.T) { for i := 0; i < firstBatchLen; i++ { _, err1 := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() } // Mark current head as finalized - //TODO can we skip? - //h := th.Client.Blockchain().CurrentHeader() - //th.Client.Blockchain().SetFinalized(h) + + h, err := th.Client.HeaderByNumber(ctx, nil) + require.NoError(t, err) + assert.NotNil(t, h) + finalizeThroughBlock(t, th, h.Number.Int64()) // Generate next blocks, not marked as finalized for i := 0; i < secondBatchLen; i++ { _, err1 := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() } currentBlock := th.PollAndSaveLogs(ctx, 1) - require.Equal(t, int(currentBlock), firstBatchLen+secondBatchLen+2) + require.Equal(t, 32+secondBatchLen+1, int(currentBlock)) finalizedLogs, err := th.LogPoller.LogsDataWordGreaterThan( ctx, @@ -1699,7 +1695,7 @@ func Test_PollAndQueryFinalizedBlocks(t *testing.T) { func Test_PollAndSavePersistsFinalityInBlocks(t *testing.T) { ctx := testutils.Context(t) - numberOfBlocks := 10 + numberOfBlocks := 37 // must be greater than 1 epoch tests := []struct { name string @@ -1716,14 +1712,14 @@ func Test_PollAndSavePersistsFinalityInBlocks(t *testing.T) { { name: "setting last finalized block number to 0 if finality is too deep", useFinalityTag: false, - finalityDepth: 20, + finalityDepth: 40, expectedFinalizedBlock: 0, }, { name: "using finality from chain", useFinalityTag: true, finalityDepth: 0, - expectedFinalizedBlock: 1, + expectedFinalizedBlock: 32, }, } for _, tt := range tests { @@ -1740,14 +1736,13 @@ func Test_PollAndSavePersistsFinalityInBlocks(t *testing.T) { _, err := th.LogPoller.LatestBlock(ctx) require.Error(t, err) - // Mark first block as finalized - //TODO OK to skip? - //h := th.Client.Blockchain().CurrentHeader() - //th.Client.Blockchain().SetFinalized(h) - // Create a couple of blocks for i := 0; i < numberOfBlocks-1; i++ { - th.Client.Commit() + th.Backend.Commit() + } + + if tt.useFinalityTag { + finalizeThroughBlock(t, th, tt.expectedFinalizedBlock) } th.PollAndSaveLogs(ctx, 1) @@ -1802,7 +1797,7 @@ func Test_CreatedAfterQueriesWithBackfill(t *testing.T) { for i := 0; i < emittedLogs; i++ { _, err2 := th.Emitter1.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() } // First PollAndSave, no filters are registered @@ -1815,10 +1810,13 @@ func Test_CreatedAfterQueriesWithBackfill(t *testing.T) { }) require.NoError(t, err) - // Emit blocks to cover finality depth, because backup always backfill up to the one block before last finalized - for i := 0; i < int(tt.finalityDepth)+1; i++ { - bh := th.Client.Commit() - markBlockAsFinalizedByHash(t, th, bh) + // Finalize current block, because backup always backfill up to one block before last finalized + if tt.finalityTag { + finalizeThroughBlock(t, th, currentBlock) + } else { + for i := 0; i < int(tt.finalityDepth)+1; i++ { + th.Backend.Commit() + } } // LogPoller should backfill entire history @@ -1911,18 +1909,25 @@ func Test_PruneOldBlocks(t *testing.T) { } } -func markBlockAsFinalized(t *testing.T, th TestHarness, blockNumber int64) { - _, err := th.Client.BlockByNumber(testutils.Context(t), big.NewInt(blockNumber)) +// Commits new blocks until blockNumber is finalized. This requires committing all of +// the rest of the blocks in the epoch blockNumber belongs to, where each new epoch +// ends on a 32-block boundary (blockNumber % 32 == 0) +func finalizeThroughBlock(t *testing.T, th TestHarness, blockNumber int64) { + var currentBlock common.Hash + ctx := testutils.Context(t) + targetBlockNumber := blockNumber + if targetBlockNumber%32 != 0 { + targetBlockNumber = 32 * (blockNumber/32 + 1) + } + h, err := th.Client.HeaderByNumber(ctx, nil) require.NoError(t, err) - //TODO ok to skip? - //th.Client.Blockchain().SetFinalized(b.Header()) -} - -func markBlockAsFinalizedByHash(t *testing.T, th TestHarness, blockHash common.Hash) { - _, err := th.Client.BlockByHash(testutils.Context(t), blockHash) + for n := h.Number.Int64(); n < targetBlockNumber; n++ { + currentBlock = th.Backend.Commit() + require.Len(t, currentBlock, 32) + } + h, err = th.Client.HeaderByNumber(ctx, nil) require.NoError(t, err) - //TODO ok to skip? - //th.Client.Blockchain().SetFinalized(b.Header()) + require.GreaterOrEqual(t, h.Number.Int64(), targetBlockNumber) } func TestFindLCA(t *testing.T) { diff --git a/core/chains/evm/types/types.go b/core/chains/evm/types/types.go index 57a53bce67a..5c405b1cdc5 100644 --- a/core/chains/evm/types/types.go +++ b/core/chains/evm/types/types.go @@ -6,10 +6,12 @@ import ( "log/slog" "math/big" "os" + "time" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" gethTypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/jackc/pgtype" pkgerrors "github.com/pkg/errors" "gopkg.in/guregu/null.v4" @@ -400,3 +402,22 @@ func (h *HashArray) Scan(src interface{}) error { } return err } + +// Interface which is satisfied by simulated.Backend. Defined here so that default geth behavior can be +// overridden in tests, and injected into our SimulatedBackend wrapper. This can be used to simulate rpc +// servers with quirky behavior that differs from geth +type Backend interface { + Close() error + Commit() common.Hash + Rollback() + Fork(parentHash common.Hash) error + AdjustTime(adjustment time.Duration) error + Client() simulated.Client +} + +type ChainFamily uint + +const ( + Geth = ChainFamily(iota) + Optimism +) diff --git a/core/gethwrappers/abigen_test.go b/core/gethwrappers/abigen_test.go index 6d6023ed7f4..5874bf0b57c 100644 --- a/core/gethwrappers/abigen_test.go +++ b/core/gethwrappers/abigen_test.go @@ -4,9 +4,8 @@ import ( "math/big" "testing" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/log_emitter" @@ -17,11 +16,12 @@ import ( // We perform this test using the generated LogEmitter wrapper. func TestGeneratedDeployMethodAddressField(t *testing.T) { owner := testutils.MustNewSimTransactor(t) - ec := backends.NewSimulatedBackend(map[common.Address]core.GenesisAccount{ + ec := simulated.NewBackend(types.GenesisAlloc{ owner.From: { Balance: big.NewInt(0).Mul(big.NewInt(10), big.NewInt(1e18)), }, - }, 10e6) + }, simulated.WithBlockGasLimit(10e6)).Client() + emitterAddr, _, emitter, err := log_emitter.DeployLogEmitter(owner, ec) require.NoError(t, err) require.Equal(t, emitterAddr, emitter.Address()) diff --git a/core/gethwrappers/keystone/generation/generated-wrapper-dependency-versions-do-not-edit.txt b/core/gethwrappers/keystone/generation/generated-wrapper-dependency-versions-do-not-edit.txt index 54d1355c62f..7b21aec577a 100644 --- a/core/gethwrappers/keystone/generation/generated-wrapper-dependency-versions-do-not-edit.txt +++ b/core/gethwrappers/keystone/generation/generated-wrapper-dependency-versions-do-not-edit.txt @@ -1,4 +1,4 @@ -GETH_VERSION: 1.13.8 +GETH_VERSION: 1.13.14 forwarder: ../../../contracts/solc/v0.8.19/KeystoneForwarder/KeystoneForwarder.abi ../../../contracts/solc/v0.8.19/KeystoneForwarder/KeystoneForwarder.bin ed9164cfe4619dff824b11df46b66f4c6834b2ca072923f10d9ebc57ce508ed8 keystone_capability_registry: ../../../contracts/solc/v0.8.19/CapabilityRegistry/CapabilityRegistry.abi ../../../contracts/solc/v0.8.19/CapabilityRegistry/CapabilityRegistry.bin d4e0661491c2adc7f0d7553287c938fb32664b9f07770f6d57ae6511ce9884cd ocr3_capability: ../../../contracts/solc/v0.8.19/OCR3Capability/OCR3Capability.abi ../../../contracts/solc/v0.8.19/OCR3Capability/OCR3Capability.bin 9dcbdf55bd5729ba266148da3f17733eb592c871c2108ccca546618628fd9ad2 diff --git a/core/gethwrappers/llo-feeds/generation/generated-wrapper-dependency-versions-do-not-edit.txt b/core/gethwrappers/llo-feeds/generation/generated-wrapper-dependency-versions-do-not-edit.txt index 8a3ad8cb2fd..103c137fdb9 100644 --- a/core/gethwrappers/llo-feeds/generation/generated-wrapper-dependency-versions-do-not-edit.txt +++ b/core/gethwrappers/llo-feeds/generation/generated-wrapper-dependency-versions-do-not-edit.txt @@ -1,5 +1,5 @@ GETH_VERSION: 1.13.14 -channel_config_store: ../../../contracts/solc/v0.8.19/ChannelConfigStore/ChannelConfigStore.abi ../../../contracts/solc/v0.8.19/ChannelConfigStore/ChannelConfigStore.bin 4ae3e6ca866fdf48850d67c0c7a4bdaf4905c81a4e3ce5efb9ef9613a55d8454 +channel_config_store: ../../../contracts/solc/v0.8.19/ChannelConfigStore/ChannelConfigStore.abi ../../../contracts/solc/v0.8.19/ChannelConfigStore/ChannelConfigStore.bin c90e29d9f1a885098982b6175e0447416431b28c605273c807694ac7141e9167 channel_config_verifier_proxy: ../../../contracts/solc/v0.8.19/ChannelVerifierProxy/ChannelVerifierProxy.abi ../../../contracts/solc/v0.8.19/ChannelVerifierProxy/ChannelVerifierProxy.bin 655658e5f61dfadfe3268de04f948b7e690ad03ca45676e645d6cd6018154661 channel_verifier: ../../../contracts/solc/v0.8.19/ChannelVerifier/ChannelVerifier.abi ../../../contracts/solc/v0.8.19/ChannelVerifier/ChannelVerifier.bin e6020553bd8e3e6b250fcaffe7efd22aea955c8c1a0eb05d282fdeb0ab6550b7 errored_verifier: ../../../contracts/solc/v0.8.19/ErroredVerifier/ErroredVerifier.abi ../../../contracts/solc/v0.8.19/ErroredVerifier/ErroredVerifier.bin a3e5a77262e13ee30fe8d35551b32a3452d71929e43fd780bbfefeaf4aa62e43 diff --git a/core/gethwrappers/operatorforwarder/generation/generated-wrapper-dependency-versions-do-not-edit.txt b/core/gethwrappers/operatorforwarder/generation/generated-wrapper-dependency-versions-do-not-edit.txt index 1569801b3fb..a30823b737f 100644 --- a/core/gethwrappers/operatorforwarder/generation/generated-wrapper-dependency-versions-do-not-edit.txt +++ b/core/gethwrappers/operatorforwarder/generation/generated-wrapper-dependency-versions-do-not-edit.txt @@ -1,4 +1,4 @@ -GETH_VERSION: 1.13.8 +GETH_VERSION: 1.13.14 authorized_forwarder: ../../../contracts/solc/v0.8.19/AuthorizedForwarder/AuthorizedForwarder.abi ../../../contracts/solc/v0.8.19/AuthorizedForwarder/AuthorizedForwarder.bin 8ea76c883d460f8353a45a493f2aebeb5a2d9a7b4619d1bc4fff5fb590bb3e10 authorized_receiver: ../../../contracts/solc/v0.8.19/AuthorizedReceiver/AuthorizedReceiver.abi ../../../contracts/solc/v0.8.19/AuthorizedReceiver/AuthorizedReceiver.bin 18e8969ba3234b027e1b16c11a783aca58d0ea5c2361010ec597f134b7bf1c4f link_token_receiver: ../../../contracts/solc/v0.8.19/LinkTokenReceiver/LinkTokenReceiver.abi ../../../contracts/solc/v0.8.19/LinkTokenReceiver/LinkTokenReceiver.bin 839552e2bea179bdf2591805422fb33769c1646d5a014a00fc2c0cd9c03ef229 diff --git a/core/gethwrappers/transmission/generation/generated-wrapper-dependency-versions-do-not-edit.txt b/core/gethwrappers/transmission/generation/generated-wrapper-dependency-versions-do-not-edit.txt index f8709faff58..bc32be85110 100644 --- a/core/gethwrappers/transmission/generation/generated-wrapper-dependency-versions-do-not-edit.txt +++ b/core/gethwrappers/transmission/generation/generated-wrapper-dependency-versions-do-not-edit.txt @@ -1,9 +1,9 @@ GETH_VERSION: 1.13.14 -entry_point: ../../../contracts/solc/v0.8.15/EntryPoint/EntryPoint.abi ../../../contracts/solc/v0.8.15/EntryPoint/EntryPoint.bin 2cb4bb2ba3efa8df3dfb0a57eb3727d17b68fe202682024fa7cfb4faf026833e +entry_point: ../../../contracts/solc/v0.8.19/EntryPoint/EntryPoint.abi ../../../contracts/solc/v0.8.19/EntryPoint/EntryPoint.bin e43da0e61256471b317cab1c87f2425cecba9b81ac21633334f889bab2f0777d greeter: ../../../contracts/solc/v0.8.15/Greeter.abi ../../../contracts/solc/v0.8.15/Greeter.bin 653dcba5c33a46292073939ce1e639372cf521c0ec2814d4c9f20c72f796f18c -greeter_wrapper: ../../../contracts/solc/v0.8.15/Greeter/Greeter.abi ../../../contracts/solc/v0.8.15/Greeter/Greeter.bin 653dcba5c33a46292073939ce1e639372cf521c0ec2814d4c9f20c72f796f18c -paymaster_wrapper: ../../../contracts/solc/v0.8.15/Paymaster/Paymaster.abi ../../../contracts/solc/v0.8.15/Paymaster/Paymaster.bin 189ef817a5b7a6ff53ddf35b1988465b8aec479c47b77236fe20bf7e67d48100 +greeter_wrapper: ../../../contracts/solc/v0.8.19/Greeter/Greeter.abi ../../../contracts/solc/v0.8.19/Greeter/Greeter.bin 7f6def58e337a53553a46cb7992cf2d75ec951014d79376fcb869a2b16b53f6d +paymaster_wrapper: ../../../contracts/solc/v0.8.19/Paymaster/Paymaster.abi ../../../contracts/solc/v0.8.19/Paymaster/Paymaster.bin dbdd1341cfa2d5c09730e0decc32339f62d1a4ea89835a51ff774226ddfbd04b sca: ../../../contracts/solc/v0.8.15/SCA.abi ../../../contracts/solc/v0.8.15/SCA.bin ae0f860cdac87d4ac505edbd228bd3ea1108550453aba67aebcb61f09cf70d0b -sca_wrapper: ../../../contracts/solc/v0.8.15/SCA/SCA.abi ../../../contracts/solc/v0.8.15/SCA/SCA.bin 2a8100fbdb41e6ce917ed333a624eaa4a8984b07e2d8d8ca6bba9bc9f74b05d7 -smart_contract_account_factory: ../../../contracts/solc/v0.8.15/SmartContractAccountFactory/SmartContractAccountFactory.abi ../../../contracts/solc/v0.8.15/SmartContractAccountFactory/SmartContractAccountFactory.bin a44d6fa2dbf9cb3441d6d637d89e1cd656f28b6bf4146f58d508067474bf845b -smart_contract_account_helper: ../../../contracts/solc/v0.8.15/SmartContractAccountHelper/SmartContractAccountHelper.abi ../../../contracts/solc/v0.8.15/SmartContractAccountHelper/SmartContractAccountHelper.bin 22f960a74bd1581a12aa4f8f438a3f265f32f43682f5c1897ca50707b9982d56 +sca_wrapper: ../../../contracts/solc/v0.8.19/SCA/SCA.abi ../../../contracts/solc/v0.8.19/SCA/SCA.bin 6ef817bdefad1b5e84f06e0bdc40848000ab00e1a38371435b793946f425a8e6 +smart_contract_account_factory: ../../../contracts/solc/v0.8.19/SmartContractAccountFactory/SmartContractAccountFactory.abi ../../../contracts/solc/v0.8.19/SmartContractAccountFactory/SmartContractAccountFactory.bin a357132e2782c462fa31ed80c270fe002e666a48ecfe407b71c278fc3a0d3679 +smart_contract_account_helper: ../../../contracts/solc/v0.8.19/SmartContractAccountHelper/SmartContractAccountHelper.abi ../../../contracts/solc/v0.8.19/SmartContractAccountHelper/SmartContractAccountHelper.bin a06aff23aded74d53bd342fdc32d80c3b474ff38223df27f3395e9fd90abd12a diff --git a/core/internal/cltest/cltest.go b/core/internal/cltest/cltest.go index f6a127a309d..ce336adf98f 100644 --- a/core/internal/cltest/cltest.go +++ b/core/internal/cltest/cltest.go @@ -18,9 +18,9 @@ import ( "testing" "time" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/ethereum/go-ethereum/rpc" "github.com/gin-gonic/gin" "github.com/google/uuid" @@ -201,7 +201,7 @@ type TestApplication struct { Logger logger.Logger Server *httptest.Server Started bool - Backend *backends.SimulatedBackend + Backend *simulated.Backend Keys []ethkey.KeyV2 } diff --git a/core/internal/cltest/simulated_backend.go b/core/internal/cltest/simulated_backend.go index 8be7ba78275..1496c54798a 100644 --- a/core/internal/cltest/simulated_backend.go +++ b/core/internal/cltest/simulated_backend.go @@ -5,11 +5,12 @@ import ( "testing" "time" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" + evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/evmtest" @@ -17,8 +18,8 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" ) -func NewSimulatedBackend(t *testing.T, alloc core.GenesisAlloc, gasLimit uint32) *backends.SimulatedBackend { - backend := backends.NewSimulatedBackend(alloc, uint64(gasLimit)) +func NewSimulatedBackend(t *testing.T, alloc types.GenesisAlloc, gasLimit uint32) *simulated.Backend { + backend := simulated.NewBackend(alloc, simulated.WithBlockGasLimit(uint64(gasLimit))) // NOTE: Make sure to finish closing any application/client before // backend.Close or they can hang t.Cleanup(func() { @@ -29,10 +30,10 @@ func NewSimulatedBackend(t *testing.T, alloc core.GenesisAlloc, gasLimit uint32) func NewApplicationWithConfigV2OnSimulatedBlockchain( t testing.TB, cfg chainlink.GeneralConfig, - backend *backends.SimulatedBackend, + backend *simulated.Backend, flagsAndDeps ...interface{}, ) *TestApplication { - bid, err := backend.ChainID(testutils.Context(t)) + bid, err := backend.Client().ChainID(testutils.Context(t)) require.NoError(t, err) if bid.Cmp(testutils.SimulatedChainID) != 0 { t.Fatalf("expected backend chain ID to be %s but it was %s", testutils.SimulatedChainID.String(), bid.String()) @@ -55,10 +56,10 @@ func NewApplicationWithConfigV2OnSimulatedBlockchain( func NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain( t testing.TB, cfg chainlink.GeneralConfig, - backend *backends.SimulatedBackend, + backend *simulated.Backend, flagsAndDeps ...interface{}, ) *TestApplication { - bid, err := backend.ChainID(testutils.Context(t)) + bid, err := backend.Client().ChainID(testutils.Context(t)) require.NoError(t, err) if bid.Cmp(testutils.SimulatedChainID) != 0 { t.Fatalf("expected backend chain ID to be %s but it was %s", testutils.SimulatedChainID.String(), bid.String()) @@ -75,7 +76,7 @@ func NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain( } // Mine forces the simulated backend to produce a new block every X seconds -func Mine(backend *backends.SimulatedBackend, blockTime time.Duration) (stopMining func()) { +func Mine(backend evmtypes.Backend, blockTime time.Duration) (stopMining func()) { timer := time.NewTicker(blockTime) chStop := make(chan struct{}) wg := sync.WaitGroup{} diff --git a/core/internal/features/features_test.go b/core/internal/features/features_test.go index 54a4a72c819..3067f9a2300 100644 --- a/core/internal/features/features_test.go +++ b/core/internal/features/features_test.go @@ -18,10 +18,10 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/ethereum/go-ethereum/rpc" "github.com/google/uuid" "github.com/hashicorp/consul/sdk/freeport" @@ -41,6 +41,7 @@ import ( commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" @@ -293,30 +294,30 @@ type OperatorContracts struct { multiWord *multiwordconsumer_wrapper.MultiWordConsumer singleWord *consumer_wrapper.Consumer operator *operator_wrapper.Operator - sim *backends.SimulatedBackend + sim *simulated.Backend } func setupOperatorContracts(t *testing.T) OperatorContracts { user := testutils.MustNewSimTransactor(t) - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ user.From: {Balance: assets.Ether(1000).ToInt()}, } gasLimit := uint32(ethconfig.Defaults.Miner.GasCeil * 2) b := cltest.NewSimulatedBackend(t, genesisData, gasLimit) - linkTokenAddress, _, linkContract, err := link_token_interface.DeployLinkToken(user, b) + linkTokenAddress, _, linkContract, err := link_token_interface.DeployLinkToken(user, b.Client()) require.NoError(t, err) b.Commit() - operatorAddress, _, operatorContract, err := operator_wrapper.DeployOperator(user, b, linkTokenAddress, user.From) + operatorAddress, _, operatorContract, err := operator_wrapper.DeployOperator(user, b.Client(), linkTokenAddress, user.From) require.NoError(t, err) b.Commit() var empty [32]byte - multiWordConsumerAddress, _, multiWordConsumerContract, err := multiwordconsumer_wrapper.DeployMultiWordConsumer(user, b, linkTokenAddress, operatorAddress, empty) + multiWordConsumerAddress, _, multiWordConsumerContract, err := multiwordconsumer_wrapper.DeployMultiWordConsumer(user, b.Client(), linkTokenAddress, operatorAddress, empty) require.NoError(t, err) b.Commit() - singleConsumerAddress, _, singleConsumerContract, err := consumer_wrapper.DeployConsumer(user, b, linkTokenAddress, operatorAddress, empty) + singleConsumerAddress, _, singleConsumerContract, err := consumer_wrapper.DeployConsumer(user, b.Client(), linkTokenAddress, operatorAddress, empty) require.NoError(t, err) b.Commit() @@ -379,15 +380,15 @@ func TestIntegration_DirectRequest(t *testing.T) { tx, err := operatorContracts.operator.SetAuthorizedSenders(operatorContracts.user, authorizedSenders) require.NoError(t, err) b.Commit() - cltest.RequireTxSuccessful(t, b, tx.Hash()) + cltest.RequireTxSuccessful(t, b.Client(), tx.Hash()) // Fund node account with ETH. - n, err := b.NonceAt(testutils.Context(t), operatorContracts.user.From, nil) + n, err := b.Client().NonceAt(testutils.Context(t), operatorContracts.user.From, nil) require.NoError(t, err) tx = cltest.NewLegacyTransaction(n, sendingKeys[0].Address, assets.Ether(100).ToInt(), 21000, big.NewInt(1000000000), nil) signedTx, err := operatorContracts.user.Signer(operatorContracts.user.From, tx) require.NoError(t, err) - err = b.SendTransaction(testutils.Context(t), signedTx) + err = b.Client().SendTransaction(testutils.Context(t), signedTx) require.NoError(t, err) b.Commit() @@ -409,7 +410,7 @@ func TestIntegration_DirectRequest(t *testing.T) { tx, err = operatorContracts.multiWord.SetSpecID(operatorContracts.user, jobID) require.NoError(t, err) b.Commit() - cltest.RequireTxSuccessful(t, b, tx.Hash()) + cltest.RequireTxSuccessful(t, b.Client(), tx.Hash()) operatorContracts.user.GasLimit = 1000000 tx, err = operatorContracts.multiWord.RequestMultipleParametersWithCustomURLs(operatorContracts.user, @@ -420,7 +421,7 @@ func TestIntegration_DirectRequest(t *testing.T) { ) require.NoError(t, err) b.Commit() - cltest.RequireTxSuccessful(t, b, tx.Hash()) + cltest.RequireTxSuccessful(t, b.Client(), tx.Hash()) empty := big.NewInt(0) assertPricesUint256(t, empty, empty, empty, operatorContracts.multiWord) @@ -446,7 +447,7 @@ func TestIntegration_DirectRequest(t *testing.T) { tx, err = operatorContracts.singleWord.SetSpecID(operatorContracts.user, jobIDSingleWord) require.NoError(t, err) b.Commit() - cltest.RequireTxSuccessful(t, b, tx.Hash()) + cltest.RequireTxSuccessful(t, b.Client(), tx.Hash()) mockServerUSD2 := cltest.NewHTTPMockServer(t, 200, "GET", `{"USD": 614.64}`) tx, err = operatorContracts.singleWord.RequestMultipleParametersWithCustomURLs(operatorContracts.user, mockServerUSD2.URL, "USD", @@ -454,7 +455,7 @@ func TestIntegration_DirectRequest(t *testing.T) { ) require.NoError(t, err) b.Commit() - cltest.RequireTxSuccessful(t, b, tx.Hash()) + cltest.RequireTxSuccessful(t, b.Client(), tx.Hash()) pipelineRuns = cltest.WaitForPipelineComplete(t, 0, jobSingleWord.ID, 1, 8, app.JobORM(), testutils.WaitTimeout(t), time.Second) pipelineRun = pipelineRuns[0] @@ -481,12 +482,12 @@ func setupAppForEthTx(t *testing.T, operatorContracts OperatorContracts) (app *c require.Len(t, sendingKeys, 1) // Fund node account with ETH. - n, err := b.NonceAt(testutils.Context(t), operatorContracts.user.From, nil) + n, err := b.Client().NonceAt(testutils.Context(t), operatorContracts.user.From, nil) require.NoError(t, err) tx := cltest.NewLegacyTransaction(n, sendingKeys[0].Address, assets.Ether(100).ToInt(), 21000, big.NewInt(1000000000), nil) signedTx, err := operatorContracts.user.Signer(operatorContracts.user.From, tx) require.NoError(t, err) - err = b.SendTransaction(testutils.Context(t), signedTx) + err = b.Client().SendTransaction(testutils.Context(t), signedTx) require.NoError(t, err) b.Commit() @@ -635,19 +636,19 @@ observationSource = """ }) } -func setupOCRContracts(t *testing.T) (*bind.TransactOpts, *backends.SimulatedBackend, common.Address, *offchainaggregator.OffchainAggregator, *flags_wrapper.Flags, common.Address) { +func setupOCRContracts(t *testing.T) (*bind.TransactOpts, *simulated.Backend, common.Address, *offchainaggregator.OffchainAggregator, *flags_wrapper.Flags, common.Address) { owner := testutils.MustNewSimTransactor(t) sb := new(big.Int) sb, _ = sb.SetString("100000000000000000000000", 10) // 1000 eth - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ owner.From: {Balance: sb}, } gasLimit := uint32(ethconfig.Defaults.Miner.GasCeil * 2) b := cltest.NewSimulatedBackend(t, genesisData, gasLimit) - linkTokenAddress, _, linkContract, err := link_token_interface.DeployLinkToken(owner, b) + linkTokenAddress, _, linkContract, err := link_token_interface.DeployLinkToken(owner, b.Client()) require.NoError(t, err) accessAddress, _, _, err := - testoffchainaggregator.DeploySimpleWriteAccessController(owner, b) + testoffchainaggregator.DeploySimpleWriteAccessController(owner, b.Client()) require.NoError(t, err, "failed to deploy test access controller contract") b.Commit() @@ -655,7 +656,7 @@ func setupOCRContracts(t *testing.T) (*bind.TransactOpts, *backends.SimulatedBac min.Exp(big.NewInt(-2), big.NewInt(191), nil) max.Exp(big.NewInt(2), big.NewInt(191), nil) max.Sub(max, big.NewInt(1)) - ocrContractAddress, _, ocrContract, err := offchainaggregator.DeployOffchainAggregator(owner, b, + ocrContractAddress, _, ocrContract, err := offchainaggregator.DeployOffchainAggregator(owner, b.Client(), 1000, // _maximumGasPrice uint32, 200, //_reasonableGasPrice uint32, 3.6e7, // 3.6e7 microLINK, or 36 LINK @@ -672,7 +673,7 @@ func setupOCRContracts(t *testing.T) (*bind.TransactOpts, *backends.SimulatedBac _, err = linkContract.Transfer(owner, ocrContractAddress, big.NewInt(1000)) require.NoError(t, err) - flagsContractAddress, _, flagsContract, err := flags_wrapper.DeployFlags(owner, b, owner.From) + flagsContractAddress, _, flagsContract, err := flags_wrapper.DeployFlags(owner, b.Client(), owner.From) require.NoError(t, err, "failed to deploy flags contract to simulated ethereum blockchain") b.Commit() @@ -680,7 +681,7 @@ func setupOCRContracts(t *testing.T) (*bind.TransactOpts, *backends.SimulatedBac } func setupNode(t *testing.T, owner *bind.TransactOpts, portV2 int, - b *backends.SimulatedBackend, overrides func(c *chainlink.Config, s *chainlink.Secrets), + b *simulated.Backend, overrides func(c *chainlink.Config, s *chainlink.Secrets), ) (*cltest.TestApplication, string, common.Address, ocrkey.KeyV2) { ctx := testutils.Context(t) p2pKey := keystest.NewP2PKeyV2(t) @@ -711,13 +712,13 @@ func setupNode(t *testing.T, owner *bind.TransactOpts, portV2 int, transmitter := sendingKeys[0].Address // Fund the transmitter address with some ETH - n, err := b.NonceAt(testutils.Context(t), owner.From, nil) + n, err := b.Client().NonceAt(testutils.Context(t), owner.From, nil) require.NoError(t, err) tx := cltest.NewLegacyTransaction(n, transmitter, assets.Ether(100).ToInt(), 21000, big.NewInt(1000000000), nil) signedTx, err := owner.Signer(owner.From, tx) require.NoError(t, err) - err = b.SendTransaction(testutils.Context(t), signedTx) + err = b.Client().SendTransaction(testutils.Context(t), signedTx) require.NoError(t, err) b.Commit() @@ -726,7 +727,7 @@ func setupNode(t *testing.T, owner *bind.TransactOpts, portV2 int, return app, p2pKey.PeerID().Raw(), transmitter, key } -func setupForwarderEnabledNode(t *testing.T, owner *bind.TransactOpts, portV2 int, b *backends.SimulatedBackend, overrides func(c *chainlink.Config, s *chainlink.Secrets)) (*cltest.TestApplication, string, common.Address, common.Address, ocrkey.KeyV2) { +func setupForwarderEnabledNode(t *testing.T, owner *bind.TransactOpts, portV2 int, b *simulated.Backend, overrides func(c *chainlink.Config, s *chainlink.Secrets)) (*cltest.TestApplication, string, common.Address, common.Address, ocrkey.KeyV2) { ctx := testutils.Context(t) p2pKey := keystest.NewP2PKeyV2(t) config, _ := heavyweight.FullTestDBV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -754,13 +755,13 @@ func setupForwarderEnabledNode(t *testing.T, owner *bind.TransactOpts, portV2 in transmitter := sendingKeys[0].Address // Fund the transmitter address with some ETH - n, err := b.NonceAt(testutils.Context(t), owner.From, nil) + n, err := b.Client().NonceAt(testutils.Context(t), owner.From, nil) require.NoError(t, err) tx := cltest.NewLegacyTransaction(n, transmitter, assets.Ether(100).ToInt(), 21000, big.NewInt(1000000000), nil) signedTx, err := owner.Signer(owner.From, tx) require.NoError(t, err) - err = b.SendTransaction(testutils.Context(t), signedTx) + err = b.Client().SendTransaction(testutils.Context(t), signedTx) require.NoError(t, err) b.Commit() @@ -768,7 +769,7 @@ func setupForwarderEnabledNode(t *testing.T, owner *bind.TransactOpts, portV2 in require.NoError(t, err) // deploy a forwarder - forwarder, _, authorizedForwarder, err := authorized_forwarder.DeployAuthorizedForwarder(owner, b, common.HexToAddress("0x326C977E6efc84E512bB9C30f76E30c160eD06FB"), owner.From, common.Address{}, []byte{}) + forwarder, _, authorizedForwarder, err := authorized_forwarder.DeployAuthorizedForwarder(owner, b.Client(), common.HexToAddress("0x326C977E6efc84E512bB9C30f76E30c160eD06FB"), owner.From, common.Address{}, []byte{}) require.NoError(t, err) // set EOA as an authorized sender for the forwarder @@ -778,7 +779,7 @@ func setupForwarderEnabledNode(t *testing.T, owner *bind.TransactOpts, portV2 in // add forwarder address to be tracked in db forwarderORM := forwarders.NewORM(app.GetDB()) - chainID, err := b.ChainID(testutils.Context(t)) + chainID, err := b.Client().ChainID(testutils.Context(t)) require.NoError(t, err) _, err = forwarderORM.CreateForwarder(testutils.Context(t), forwarder, ubig.Big(*chainID)) require.NoError(t, err) diff --git a/core/internal/features/ocr2/features_ocr2_test.go b/core/internal/features/ocr2/features_ocr2_test.go index 5e628a4d8d9..914abcd50d9 100644 --- a/core/internal/features/ocr2/features_ocr2_test.go +++ b/core/internal/features/ocr2/features_ocr2_test.go @@ -17,11 +17,10 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/hashicorp/consul/sdk/freeport" "github.com/onsi/gomega" "github.com/stretchr/testify/assert" @@ -64,16 +63,16 @@ type ocr2Node struct { keybundle ocr2key.KeyBundle } -func setupOCR2Contracts(t *testing.T) (*bind.TransactOpts, *backends.SimulatedBackend, common.Address, *ocr2aggregator.OCR2Aggregator) { +func setupOCR2Contracts(t *testing.T) (*bind.TransactOpts, *simulated.Backend, common.Address, *ocr2aggregator.OCR2Aggregator) { owner := testutils.MustNewSimTransactor(t) sb := new(big.Int) sb, _ = sb.SetString("100000000000000000000", 10) // 1 eth - genesisData := core.GenesisAlloc{owner.From: {Balance: sb}} + genesisData := types.GenesisAlloc{owner.From: {Balance: sb}} gasLimit := ethconfig.Defaults.Miner.GasCeil * 2 - b := backends.NewSimulatedBackend(genesisData, gasLimit) - linkTokenAddress, _, linkContract, err := link_token_interface.DeployLinkToken(owner, b) + b := simulated.NewBackend(genesisData, simulated.WithBlockGasLimit(gasLimit)) + linkTokenAddress, _, linkContract, err := link_token_interface.DeployLinkToken(owner, b.Client()) require.NoError(t, err) - accessAddress, _, _, err := testoffchainaggregator2.DeploySimpleWriteAccessController(owner, b) + accessAddress, _, _, err := testoffchainaggregator2.DeploySimpleWriteAccessController(owner, b.Client()) require.NoError(t, err, "failed to deploy test access controller contract") b.Commit() @@ -83,7 +82,7 @@ func setupOCR2Contracts(t *testing.T) (*bind.TransactOpts, *backends.SimulatedBa maxAnswer.Sub(maxAnswer, big.NewInt(1)) ocrContractAddress, _, ocrContract, err := ocr2aggregator.DeployOCR2Aggregator( owner, - b, + b.Client(), linkTokenAddress, //_link common.Address, minAnswer, // -2**191 maxAnswer, // 2**191 - 1 @@ -108,7 +107,7 @@ func setupNodeOCR2( owner *bind.TransactOpts, port int, useForwarder bool, - b *backends.SimulatedBackend, + b *simulated.Backend, p2pV2Bootstrappers []commontypes.BootstrapperLocator, ) *ocr2Node { ctx := testutils.Context(t) @@ -143,7 +142,7 @@ func setupNodeOCR2( effectiveTransmitter := sendingKeys[0].Address // Fund the transmitter address with some ETH - n, err := b.NonceAt(testutils.Context(t), owner.From, nil) + n, err := b.Client().NonceAt(testutils.Context(t), owner.From, nil) require.NoError(t, err) tx := cltest.NewLegacyTransaction( @@ -154,7 +153,7 @@ func setupNodeOCR2( nil) signedTx, err := owner.Signer(owner.From, tx) require.NoError(t, err) - err = b.SendTransaction(testutils.Context(t), signedTx) + err = b.Client().SendTransaction(testutils.Context(t), signedTx) require.NoError(t, err) b.Commit() @@ -163,7 +162,7 @@ func setupNodeOCR2( if useForwarder { // deploy a forwarder - faddr, _, authorizedForwarder, err2 := authorized_forwarder.DeployAuthorizedForwarder(owner, b, common.HexToAddress("0x326C977E6efc84E512bB9C30f76E30c160eD06FB"), owner.From, common.Address{}, []byte{}) + faddr, _, authorizedForwarder, err2 := authorized_forwarder.DeployAuthorizedForwarder(owner, b.Client(), common.HexToAddress("0x326C977E6efc84E512bB9C30f76E30c160eD06FB"), owner.From, common.Address{}, []byte{}) require.NoError(t, err2) // set EOA as an authorized sender for the forwarder @@ -173,7 +172,7 @@ func setupNodeOCR2( // add forwarder address to be tracked in db forwarderORM := forwarders.NewORM(app.GetDB()) - chainID, err := b.ChainID(testutils.Context(t)) + chainID, err := b.Client().ChainID(testutils.Context(t)) require.NoError(t, err) _, err2 = forwarderORM.CreateForwarder(testutils.Context(t), faddr, ubig.Big(*chainID)) require.NoError(t, err2) @@ -619,7 +618,7 @@ updateInterval = "1m" } } -func initOCR2(t *testing.T, lggr logger.Logger, b *backends.SimulatedBackend, +func initOCR2(t *testing.T, lggr logger.Logger, b *simulated.Backend, ocrContract *ocr2aggregator.OCR2Aggregator, owner *bind.TransactOpts, bootstrapNode *ocr2Node, @@ -637,7 +636,7 @@ func initOCR2(t *testing.T, lggr logger.Logger, b *backends.SimulatedBackend, payees, ) require.NoError(t, err) - blockBeforeConfig, err = b.BlockByNumber(testutils.Context(t), nil) + blockBeforeConfig, err = b.Client().BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) signers, effectiveTransmitters, threshold, _, encodedConfigVersion, encodedConfig, err := confighelper2.ContractSetConfigArgsForEthereumIntegrationTest( oracles, diff --git a/core/services/fluxmonitorv2/integrations_test.go b/core/services/fluxmonitorv2/integrations_test.go index 8dc355e4741..ef134136a4c 100644 --- a/core/services/fluxmonitorv2/integrations_test.go +++ b/core/services/fluxmonitorv2/integrations_test.go @@ -16,16 +16,17 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/onsi/gomega" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" + "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log" @@ -69,7 +70,7 @@ type fluxAggregatorUniverse struct { flagsContractAddress common.Address evmChainID big.Int // Abstraction representation of the ethereum blockchain - backend *backends.SimulatedBackend + backend *simulated.Backend aggregatorABI abi.ABI // Cast of participants sergey *bind.TransactOpts // Owns all the LINK initially @@ -116,7 +117,7 @@ func setupFluxAggregatorUniverse(t *testing.T, configOptions ...func(cfg *fluxAg f.neil = testutils.MustNewSimTransactor(t) f.ned = testutils.MustNewSimTransactor(t) f.nallory = oracleTransactor - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ f.sergey.From: {Balance: assets.Ether(1000).ToInt()}, f.neil.From: {Balance: assets.Ether(1000).ToInt()}, f.ned.From: {Balance: assets.Ether(1000).ToInt()}, @@ -129,10 +130,10 @@ func setupFluxAggregatorUniverse(t *testing.T, configOptions ...func(cfg *fluxAg require.NoError(t, err, "could not parse FluxAggregator ABI") var linkAddress common.Address - linkAddress, _, f.linkContract, err = link_token_interface.DeployLinkToken(f.sergey, f.backend) + linkAddress, _, f.linkContract, err = link_token_interface.DeployLinkToken(f.sergey, f.backend.Client()) require.NoError(t, err, "failed to deploy link contract to simulated ethereum blockchain") - f.flagsContractAddress, _, f.flagsContract, err = flags_wrapper.DeployFlags(f.sergey, f.backend, f.sergey.From) + f.flagsContractAddress, _, f.flagsContract, err = flags_wrapper.DeployFlags(f.sergey, f.backend.Client(), f.sergey.From) require.NoError(t, err, "failed to deploy flags contract to simulated ethereum blockchain") f.backend.Commit() @@ -147,7 +148,7 @@ func setupFluxAggregatorUniverse(t *testing.T, configOptions ...func(cfg *fluxAg f.sergey.GasLimit = uint64(gasLimit) f.aggregatorContractAddress, _, f.aggregatorContract, err = faw.DeployFluxAggregator( f.sergey, - f.backend, + f.backend.Client(), linkAddress, big.NewInt(fee), faTimeout, @@ -251,7 +252,7 @@ type answerParams struct { func checkSubmission(t *testing.T, p answerParams, currentBalance int64, receiptBlock uint64) { t.Helper() if receiptBlock == 0 { - h, err := p.fa.backend.HeaderByNumber(testutils.Context(t), nil) + h, err := p.fa.backend.Client().HeaderByNumber(testutils.Context(t), nil) require.NoError(t, err) receiptBlock = h.Number.Uint64() } @@ -355,7 +356,7 @@ func submitAnswer(t *testing.T, p answerParams) { checkSubmission(t, p, cb.Int64(), 0) } -func awaitSubmission(t *testing.T, backend *backends.SimulatedBackend, submissionReceived chan *faw.FluxAggregatorSubmissionReceived) ( +func awaitSubmission(t *testing.T, backend *simulated.Backend, submissionReceived chan *faw.FluxAggregatorSubmissionReceived) ( receiptBlock uint64, answer int64, ) { t.Helper() @@ -416,7 +417,7 @@ func checkLogWasConsumed(t *testing.T, fa fluxAggregatorUniverse, ds sqlutil.Dat g := gomega.NewWithT(t) g.Eventually(func() bool { ctx := testutils.Context(t) - block, err := fa.backend.BlockByNumber(ctx, big.NewInt(int64(blockNumber))) + block, err := fa.backend.Client().BlockByNumber(ctx, big.NewInt(int64(blockNumber))) require.NoError(t, err) require.NotNil(t, block) orm := log.NewORM(ds, fa.evmChainID) diff --git a/core/services/keeper/integration_test.go b/core/services/keeper/integration_test.go index 9e4cf5f9041..9a7e47144c8 100644 --- a/core/services/keeper/integration_test.go +++ b/core/services/keeper/integration_test.go @@ -8,7 +8,6 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" "github.com/onsi/gomega" @@ -17,6 +16,7 @@ import ( "github.com/stretchr/testify/require" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/forwarders" @@ -189,7 +189,7 @@ func TestKeeperEthIntegration(t *testing.T) { carrol := testutils.MustNewSimTransactor(t) // client nelly := testutils.MustNewSimTransactor(t) // other keeper operator 1 nick := testutils.MustNewSimTransactor(t) // other keeper operator 2 - genesisData := core.GenesisAlloc{ + genesisData := types.GenesisAlloc{ sergey.From: {Balance: assets.Ether(1000).ToInt()}, steve.From: {Balance: assets.Ether(1000).ToInt()}, carrol.From: {Balance: assets.Ether(1000).ToInt()}, @@ -249,7 +249,7 @@ func TestKeeperEthIntegration(t *testing.T) { }) korm := keeper.NewORM(db, logger.TestLogger(t)) - app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, config, backend.Backend(), nodeKey) + app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, config, b, nodeKey) require.NoError(t, app.Start(ctx)) // create job @@ -341,7 +341,7 @@ func TestKeeperForwarderEthIntegration(t *testing.T) { carrol := testutils.MustNewSimTransactor(t) // client nelly := testutils.MustNewSimTransactor(t) // other keeper operator 1 nick := testutils.MustNewSimTransactor(t) // other keeper operator 2 - genesisData := core.GenesisAlloc{ + genesisData := types.GenesisAlloc{ sergey.From: {Balance: assets.Ether(1000).ToInt()}, steve.From: {Balance: assets.Ether(1000).ToInt()}, carrol.From: {Balance: assets.Ether(1000).ToInt()}, @@ -409,7 +409,7 @@ func TestKeeperForwarderEthIntegration(t *testing.T) { }) korm := keeper.NewORM(db, logger.TestLogger(t)) - app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, config, backend.Backend(), nodeKey) + app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, config, b, nodeKey) require.NoError(t, app.Start(ctx)) forwarderORM := forwarders.NewORM(db) @@ -497,7 +497,7 @@ func TestMaxPerformDataSize(t *testing.T) { carrol := testutils.MustNewSimTransactor(t) // client nelly := testutils.MustNewSimTransactor(t) // other keeper operator 1 nick := testutils.MustNewSimTransactor(t) // other keeper operator 2 - genesisData := core.GenesisAlloc{ + genesisData := types.GenesisAlloc{ sergey.From: {Balance: assets.Ether(1000).ToInt()}, steve.From: {Balance: assets.Ether(1000).ToInt()}, carrol.From: {Balance: assets.Ether(1000).ToInt()}, @@ -553,7 +553,7 @@ func TestMaxPerformDataSize(t *testing.T) { }) korm := keeper.NewORM(db, logger.TestLogger(t)) - app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, config, backend.Backend(), nodeKey) + app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, config, b, nodeKey) require.NoError(t, app.Start(ctx)) // create job diff --git a/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go b/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go index 3f96b49cfe0..ddb3ca712ba 100644 --- a/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go +++ b/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go @@ -15,11 +15,11 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/hashicorp/consul/sdk/freeport" "github.com/onsi/gomega" "github.com/stretchr/testify/require" @@ -29,6 +29,7 @@ import ( ocrtypes2 "github.com/smartcontractkit/libocr/offchainreporting2plus/types" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" @@ -58,7 +59,7 @@ func ptr[T any](v T) *T { return &v } var allowListPrivateKey = "0xae78c8b502571dba876742437f8bc78b689cf8518356c0921393d89caaf284ce" -func SetOracleConfig(t *testing.T, b *backends.SimulatedBackend, owner *bind.TransactOpts, coordinatorContract *functions_coordinator.FunctionsCoordinator, oracles []confighelper2.OracleIdentityExtra, batchSize int, functionsPluginConfig *functionsConfig.ReportingPluginConfig) { +func SetOracleConfig(t *testing.T, b *simulated.Backend, owner *bind.TransactOpts, coordinatorContract *functions_coordinator.FunctionsCoordinator, oracles []confighelper2.OracleIdentityExtra, batchSize int, functionsPluginConfig *functionsConfig.ReportingPluginConfig) { S := make([]int, len(oracles)) for i := 0; i < len(S); i++ { S[i] = 1 @@ -109,7 +110,7 @@ func SetOracleConfig(t *testing.T, b *backends.SimulatedBackend, owner *bind.Tra CommitWithFinality(b) } -func CreateAndFundSubscriptions(t *testing.T, b *backends.SimulatedBackend, owner *bind.TransactOpts, linkToken *link_token_interface.LinkToken, routerContractAddress common.Address, routerContract *functions_router.FunctionsRouter, clientContracts []deployedClientContract, allowListContract *functions_allow_list.TermsOfServiceAllowList) (subscriptionId uint64) { +func CreateAndFundSubscriptions(t *testing.T, b *simulated.Backend, owner *bind.TransactOpts, linkToken *link_token_interface.LinkToken, routerContractAddress common.Address, routerContract *functions_router.FunctionsRouter, clientContracts []deployedClientContract, allowListContract *functions_allow_list.TermsOfServiceAllowList) (subscriptionId uint64) { allowed, err := allowListContract.HasAccess(nilOpts, owner.From, []byte{}) require.NoError(t, err) if !allowed { @@ -152,7 +153,7 @@ func CreateAndFundSubscriptions(t *testing.T, b *backends.SimulatedBackend, owne const finalityDepth int = 4 -func CommitWithFinality(b *backends.SimulatedBackend) { +func CommitWithFinality(b *simulated.Backend) { for i := 0; i < finalityDepth; i++ { b.Commit() } @@ -168,26 +169,26 @@ type Coordinator struct { Contract *functions_coordinator.FunctionsCoordinator } -func StartNewChainWithContracts(t *testing.T, nClients int) (*bind.TransactOpts, *backends.SimulatedBackend, *time.Ticker, Coordinator, Coordinator, []deployedClientContract, common.Address, *functions_router.FunctionsRouter, *link_token_interface.LinkToken, common.Address, *functions_allow_list.TermsOfServiceAllowList) { +func StartNewChainWithContracts(t *testing.T, nClients int) (*bind.TransactOpts, *simulated.Backend, *time.Ticker, Coordinator, Coordinator, []deployedClientContract, common.Address, *functions_router.FunctionsRouter, *link_token_interface.LinkToken, common.Address, *functions_allow_list.TermsOfServiceAllowList) { owner := testutils.MustNewSimTransactor(t) owner.GasPrice = big.NewInt(int64(DefaultGasPrice)) sb := new(big.Int) sb, _ = sb.SetString("100000000000000000000", 10) // 1 eth - genesisData := core.GenesisAlloc{owner.From: {Balance: sb}} + genesisData := types.GenesisAlloc{owner.From: {Balance: sb}} gasLimit := ethconfig.Defaults.Miner.GasCeil * 2 // 60 M blocks - b := backends.NewSimulatedBackend(genesisData, gasLimit) + b := simulated.NewBackend(genesisData, simulated.WithBlockGasLimit(gasLimit)) b.Commit() // Deploy LINK token - linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(owner, b) + linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(owner, b.Client()) require.NoError(t, err) // Deploy mock LINK/ETH price feed - linkEthFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(owner, b, 18, big.NewInt(5_000_000_000_000_000)) + linkEthFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(owner, b.Client(), 18, big.NewInt(5_000_000_000_000_000)) require.NoError(t, err) // Deploy mock LINK/USD price feed - linkUsdFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(owner, b, 18, big.NewInt(1_500_00_000)) + linkUsdFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(owner, b.Client(), 18, big.NewInt(1_500_00_000)) require.NoError(t, err) // Deploy Router contract @@ -204,7 +205,7 @@ func StartNewChainWithContracts(t *testing.T, nClients int) (*bind.TransactOpts, SubscriptionDepositMinimumRequests: 10, SubscriptionDepositJuels: big.NewInt(9 * 1e18), // 9 LINK } - routerAddress, _, routerContract, err := functions_router.DeployFunctionsRouter(owner, b, linkAddr, functionsRouterConfig) + routerAddress, _, routerContract, err := functions_router.DeployFunctionsRouter(owner, b.Client(), linkAddr, functionsRouterConfig) require.NoError(t, err) // Deploy Allow List contract @@ -217,7 +218,7 @@ func StartNewChainWithContracts(t *testing.T, nClients int) (*bind.TransactOpts, } var initialAllowedSenders []common.Address var initialBlockedSenders []common.Address - allowListAddress, _, allowListContract, err := functions_allow_list.DeployTermsOfServiceAllowList(owner, b, allowListConfig, initialAllowedSenders, initialBlockedSenders) + allowListAddress, _, allowListContract, err := functions_allow_list.DeployTermsOfServiceAllowList(owner, b.Client(), allowListConfig, initialAllowedSenders, initialBlockedSenders) require.NoError(t, err) // Deploy Coordinator contract (matches updateConfig() in FunctionsBilling.sol) @@ -236,15 +237,15 @@ func StartNewChainWithContracts(t *testing.T, nClients int) (*bind.TransactOpts, FallbackUsdPerUnitLinkDecimals: uint8(8), } require.NoError(t, err) - coordinatorAddress, _, coordinatorContract, err := functions_coordinator.DeployFunctionsCoordinator(owner, b, routerAddress, coordinatorConfig, linkEthFeedAddr, linkUsdFeedAddr) + coordinatorAddress, _, coordinatorContract, err := functions_coordinator.DeployFunctionsCoordinator(owner, b.Client(), routerAddress, coordinatorConfig, linkEthFeedAddr, linkUsdFeedAddr) require.NoError(t, err) - proposalAddress, _, proposalContract, err := functions_coordinator.DeployFunctionsCoordinator(owner, b, routerAddress, coordinatorConfig, linkEthFeedAddr, linkUsdFeedAddr) + proposalAddress, _, proposalContract, err := functions_coordinator.DeployFunctionsCoordinator(owner, b.Client(), routerAddress, coordinatorConfig, linkEthFeedAddr, linkUsdFeedAddr) require.NoError(t, err) // Deploy Client contracts clientContracts := []deployedClientContract{} for i := 0; i < nClients; i++ { - clientContractAddress, _, clientContract, err := functions_client_example.DeployFunctionsClientExample(owner, b, routerAddress) + clientContractAddress, _, clientContract, err := functions_client_example.DeployFunctionsClientExample(owner, b.Client(), routerAddress) require.NoError(t, err) clientContracts = append(clientContracts, deployedClientContract{ Address: clientContractAddress, @@ -275,7 +276,7 @@ func StartNewChainWithContracts(t *testing.T, nClients int) (*bind.TransactOpts, return owner, b, ticker, active, proposed, clientContracts, routerAddress, routerContract, linkToken, allowListAddress, allowListContract } -func SetupRouterRoutes(t *testing.T, b *backends.SimulatedBackend, owner *bind.TransactOpts, routerContract *functions_router.FunctionsRouter, coordinatorAddress common.Address, proposedCoordinatorAddress common.Address, allowListAddress common.Address) { +func SetupRouterRoutes(t *testing.T, b *simulated.Backend, owner *bind.TransactOpts, routerContract *functions_router.FunctionsRouter, coordinatorAddress common.Address, proposedCoordinatorAddress common.Address, allowListAddress common.Address) { allowListId, err := routerContract.GetAllowListId(nilOpts) require.NoError(t, err) var donId [32]byte @@ -311,7 +312,7 @@ func StartNewNode( t *testing.T, owner *bind.TransactOpts, port int, - b *backends.SimulatedBackend, + b *simulated.Backend, maxGas uint32, p2pV2Bootstrappers []commontypes.BootstrapperLocator, ocr2Keystore []byte, @@ -355,7 +356,7 @@ func StartNewNode( transmitter := sendingKeys[0].Address // fund the transmitter address - n, err := b.NonceAt(testutils.Context(t), owner.From, nil) + n, err := b.Client().NonceAt(testutils.Context(t), owner.From, nil) require.NoError(t, err) tx := cltest.NewLegacyTransaction( @@ -366,7 +367,7 @@ func StartNewNode( nil) signedTx, err := owner.Signer(owner.From, tx) require.NoError(t, err) - err = b.SendTransaction(testutils.Context(t), signedTx) + err = b.Client().SendTransaction(testutils.Context(t), signedTx) require.NoError(t, err) b.Commit() @@ -539,7 +540,7 @@ func GetExpectedResponse(source []byte) [32]byte { func CreateFunctionsNodes( t *testing.T, owner *bind.TransactOpts, - b *backends.SimulatedBackend, + b *simulated.Backend, routerAddress common.Address, nOracleNodes int, maxGas int, @@ -595,7 +596,7 @@ func CreateFunctionsNodes( func ClientTestRequests( t *testing.T, owner *bind.TransactOpts, - b *backends.SimulatedBackend, + b *simulated.Backend, linkToken *link_token_interface.LinkToken, routerAddress common.Address, routerContract *functions_router.FunctionsRouter, diff --git a/core/services/ocr2/plugins/llo/helpers_test.go b/core/services/ocr2/plugins/llo/helpers_test.go index 73f7fedc926..c37a85b2dc9 100644 --- a/core/services/ocr2/plugins/llo/helpers_test.go +++ b/core/services/ocr2/plugins/llo/helpers_test.go @@ -14,8 +14,8 @@ import ( "testing" "time" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/shopspring/decimal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -158,7 +158,7 @@ func setupNode( t *testing.T, port int, dbName string, - backend *backends.SimulatedBackend, + backend *simulated.Backend, csaKey csakey.KeyV2, ) (app chainlink.Application, peerID string, clientPubKey credentials.StaticSizedPublicKey, ocr2kb ocr2key.KeyBundle, observedLogs *observer.ObservedLogs) { k := big.NewInt(int64(port)) // keys unique to port diff --git a/core/services/ocr2/plugins/llo/integration_test.go b/core/services/ocr2/plugins/llo/integration_test.go index b6f752541f4..7be9c94ded5 100644 --- a/core/services/ocr2/plugins/llo/integration_test.go +++ b/core/services/ocr2/plugins/llo/integration_test.go @@ -11,10 +11,10 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/hashicorp/consul/sdk/freeport" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -46,20 +46,20 @@ var ( multiplier int64 = 100000000 ) -func setupBlockchain(t *testing.T) (*bind.TransactOpts, *backends.SimulatedBackend, *channel_verifier.ChannelVerifier, common.Address, *channel_config_store.ChannelConfigStore, common.Address) { +func setupBlockchain(t *testing.T) (*bind.TransactOpts, *simulated.Backend, *channel_verifier.ChannelVerifier, common.Address, *channel_config_store.ChannelConfigStore, common.Address) { steve := testutils.MustNewSimTransactor(t) // config contract deployer and owner - genesisData := core.GenesisAlloc{steve.From: {Balance: assets.Ether(1000).ToInt()}} + genesisData := types.GenesisAlloc{steve.From: {Balance: assets.Ether(1000).ToInt()}} backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) backend.Commit() backend.Commit() // ensure starting block number at least 1 // Deploy contracts - verifierProxyAddr, _, _, err := verifier_proxy.DeployVerifierProxy(steve, backend, common.Address{}) // zero address for access controller disables access control + verifierProxyAddr, _, _, err := verifier_proxy.DeployVerifierProxy(steve, backend.Client(), common.Address{}) // zero address for access controller disables access control require.NoError(t, err) - verifierAddress, _, verifierContract, err := channel_verifier.DeployChannelVerifier(steve, backend, verifierProxyAddr) + verifierAddress, _, verifierContract, err := channel_verifier.DeployChannelVerifier(steve, backend.Client(), verifierProxyAddr) require.NoError(t, err) - configStoreAddress, _, configStoreContract, err := channel_config_store.DeployChannelConfigStore(steve, backend) + configStoreAddress, _, configStoreContract, err := channel_config_store.DeployChannelConfigStore(steve, backend.Client()) require.NoError(t, err) backend.Commit() @@ -255,7 +255,7 @@ func TestIntegration_LLO(t *testing.T) { // TODO: test verification } -func setConfig(t *testing.T, steve *bind.TransactOpts, backend *backends.SimulatedBackend, verifierContract *channel_verifier.ChannelVerifier, verifierAddress common.Address, nodes []Node, oracles []confighelper.OracleIdentityExtra) ocr2types.ConfigDigest { +func setConfig(t *testing.T, steve *bind.TransactOpts, backend *simulated.Backend, verifierContract *channel_verifier.ChannelVerifier, verifierAddress common.Address, nodes []Node, oracles []confighelper.OracleIdentityExtra) ocr2types.ConfigDigest { // Setup config on contract rawOnchainConfig := datastreamsllo.OnchainConfig{} onchainConfig, err := (&datastreamsllo.JSONOnchainConfigCodec{}).Encode(rawOnchainConfig) @@ -310,7 +310,7 @@ func setConfig(t *testing.T, steve *bind.TransactOpts, backend *backends.Simulat return l.ConfigDigest } -func setChannelDefinitions(t *testing.T, steve *bind.TransactOpts, backend *backends.SimulatedBackend, configStoreContract *channel_config_store.ChannelConfigStore, streams []Stream) map[llotypes.ChannelID]channel_config_store.IChannelConfigStoreChannelDefinition { +func setChannelDefinitions(t *testing.T, steve *bind.TransactOpts, backend *simulated.Backend, configStoreContract *channel_config_store.ChannelConfigStore, streams []Stream) map[llotypes.ChannelID]channel_config_store.IChannelConfigStoreChannelDefinition { channels := []llotypes.ChannelID{ rand.Uint32(), rand.Uint32(), diff --git a/core/services/ocr2/plugins/llo/onchain_channel_definition_cache_integration_test.go b/core/services/ocr2/plugins/llo/onchain_channel_definition_cache_integration_test.go index ea8f64c02fa..a21a9dfc7d8 100644 --- a/core/services/ocr2/plugins/llo/onchain_channel_definition_cache_integration_test.go +++ b/core/services/ocr2/plugins/llo/onchain_channel_definition_cache_integration_test.go @@ -7,7 +7,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" chainselectors "github.com/smartcontractkit/chain-selectors" "github.com/stretchr/testify/assert" @@ -36,13 +36,13 @@ func Test_ChannelDefinitionCache_Integration(t *testing.T) { orm := llo.NewORM(db, testutils.SimulatedChainID) steve := testutils.MustNewSimTransactor(t) // config contract deployer and owner - genesisData := core.GenesisAlloc{steve.From: {Balance: assets.Ether(1000).ToInt()}} + genesisData := types.GenesisAlloc{steve.From: {Balance: assets.Ether(1000).ToInt()}} backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) backend.Commit() // ensure starting block number at least 1 ethClient := client.NewSimulatedBackendClient(t, backend, testutils.SimulatedChainID) - configStoreAddress, _, configStoreContract, err := channel_config_store.DeployChannelConfigStore(steve, backend) + configStoreAddress, _, configStoreContract, err := channel_config_store.DeployChannelConfigStore(steve, backend.Client()) require.NoError(t, err) channel1 := rand.Uint32() @@ -73,7 +73,7 @@ func Test_ChannelDefinitionCache_Integration(t *testing.T) { require.NoError(t, utils.JustError(configStoreContract.AddChannel(steve, channel2, channel2Def))) h := backend.Commit() - channel2Block, err := backend.BlockByHash(ctx, h) + channel2Block, err := backend.Client().BlockByHash(ctx, h) require.NoError(t, err) t.Run("with zero fromblock", func(t *testing.T) { diff --git a/core/services/ocr2/plugins/mercury/helpers_test.go b/core/services/ocr2/plugins/mercury/helpers_test.go index fbb51557eb1..58bde79587e 100644 --- a/core/services/ocr2/plugins/mercury/helpers_test.go +++ b/core/services/ocr2/plugins/mercury/helpers_test.go @@ -12,8 +12,8 @@ import ( "testing" "time" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/zap/zapcore" @@ -27,6 +27,7 @@ import ( ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest/heavyweight" @@ -154,7 +155,7 @@ func setupNode( t *testing.T, port int, dbName string, - backend *backends.SimulatedBackend, + backend *simulated.Backend, csaKey csakey.KeyV2, ) (app chainlink.Application, peerID string, clientPubKey credentials.StaticSizedPublicKey, ocr2kb ocr2key.KeyBundle, observedLogs *observer.ObservedLogs) { k := big.NewInt(int64(port)) // keys unique to port diff --git a/core/services/ocr2/plugins/mercury/integration_test.go b/core/services/ocr2/plugins/mercury/integration_test.go index 2339117d4e3..b35dd9e2f1e 100644 --- a/core/services/ocr2/plugins/mercury/integration_test.go +++ b/core/services/ocr2/plugins/mercury/integration_test.go @@ -18,10 +18,10 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/hashicorp/consul/sdk/freeport" "github.com/shopspring/decimal" "github.com/stretchr/testify/assert" @@ -89,32 +89,32 @@ func detectPanicLogs(t *testing.T, logObservers []*observer.ObservedLogs) { } } -func setupBlockchain(t *testing.T) (*bind.TransactOpts, *backends.SimulatedBackend, *verifier.Verifier, common.Address) { +func setupBlockchain(t *testing.T) (*bind.TransactOpts, *simulated.Backend, *verifier.Verifier, common.Address) { steve := testutils.MustNewSimTransactor(t) // config contract deployer and owner - genesisData := core.GenesisAlloc{steve.From: {Balance: assets.Ether(1000).ToInt()}} + genesisData := gethtypes.GenesisAlloc{steve.From: {Balance: assets.Ether(1000).ToInt()}} backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) backend.Commit() // ensure starting block number at least 1 stopMining := cltest.Mine(backend, 1*time.Second) // Should be greater than deltaRound since we cannot access old blocks on simulated blockchain t.Cleanup(stopMining) // Deploy contracts - linkTokenAddress, _, linkToken, err := token.DeployLinkToken(steve, backend) + linkTokenAddress, _, linkToken, err := token.DeployLinkToken(steve, backend.Client()) require.NoError(t, err) _, err = linkToken.Transfer(steve, steve.From, big.NewInt(1000)) require.NoError(t, err) - nativeTokenAddress, _, nativeToken, err := token.DeployLinkToken(steve, backend) + nativeTokenAddress, _, nativeToken, err := token.DeployLinkToken(steve, backend.Client()) require.NoError(t, err) _, err = nativeToken.Transfer(steve, steve.From, big.NewInt(1000)) require.NoError(t, err) - verifierProxyAddr, _, verifierProxy, err := verifier_proxy.DeployVerifierProxy(steve, backend, common.Address{}) // zero address for access controller disables access control + verifierProxyAddr, _, verifierProxy, err := verifier_proxy.DeployVerifierProxy(steve, backend.Client(), common.Address{}) // zero address for access controller disables access control require.NoError(t, err) - verifierAddress, _, verifier, err := verifier.DeployVerifier(steve, backend, verifierProxyAddr) + verifierAddress, _, verifier, err := verifier.DeployVerifier(steve, backend.Client(), verifierProxyAddr) require.NoError(t, err) _, err = verifierProxy.InitializeVerifier(steve, verifierAddress) require.NoError(t, err) - rewardManagerAddr, _, rewardManager, err := reward_manager.DeployRewardManager(steve, backend, linkTokenAddress) + rewardManagerAddr, _, rewardManager, err := reward_manager.DeployRewardManager(steve, backend.Client(), linkTokenAddress) require.NoError(t, err) - feeManagerAddr, _, _, err := fee_manager.DeployFeeManager(steve, backend, linkTokenAddress, nativeTokenAddress, verifierProxyAddr, rewardManagerAddr) + feeManagerAddr, _, _, err := fee_manager.DeployFeeManager(steve, backend.Client(), linkTokenAddress, nativeTokenAddress, verifierProxyAddr, rewardManagerAddr) require.NoError(t, err) _, err = verifierProxy.SetFeeManager(steve, feeManagerAddr) require.NoError(t, err) @@ -372,7 +372,7 @@ func integration_MercuryV1(t *testing.T) { num, err := (&reportcodecv1.ReportCodec{}).CurrentBlockNumFromReport(ocr2types.Report(report.([]byte))) require.NoError(t, err) - currentBlock, err := backend.BlockByNumber(testutils.Context(t), nil) + currentBlock, err := backend.Client().BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) assert.GreaterOrEqual(t, currentBlock.Number().Int64(), num) @@ -436,7 +436,7 @@ func integration_MercuryV1(t *testing.T) { num, err := (&reportcodecv1.ReportCodec{}).CurrentBlockNumFromReport(ocr2types.Report(report.([]byte))) require.NoError(t, err) - currentBlock, err := backend.BlockByNumber(testutils.Context(t), nil) + currentBlock, err := backend.Client().BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) assert.GreaterOrEqual(t, currentBlock.Number().Int64(), num) diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/integration_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/integration_test.go index 46314dde418..d71b62f9530 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/integration_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider/integration_test.go @@ -6,12 +6,13 @@ import ( "testing" "time" + gethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/smartcontractkit/chainlink-automation/pkg/v3/types" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/eth/ethconfig" "github.com/jmoiron/sqlx" "github.com/stretchr/testify/require" @@ -393,7 +394,7 @@ func waitLogProvider(ctx context.Context, t *testing.T, logProvider logprovider. } // waitLogPoller waits until the log poller is familiar with the given block -func waitLogPoller(ctx context.Context, t *testing.T, backend *backends.SimulatedBackend, lp logpoller.LogPollerTest, ethClient *evmclient.SimulatedBackendClient) { +func waitLogPoller(ctx context.Context, t *testing.T, backend *simulated.Backend, lp logpoller.LogPollerTest, ethClient *evmclient.SimulatedBackendClient) { t.Log("waiting for log poller to get updated") // let the log poller work b, err := ethClient.BlockByHash(ctx, backend.Commit()) @@ -421,7 +422,7 @@ func pollFn(ctx context.Context, t *testing.T, lp logpoller.LogPollerTest, ethCl func triggerEvents( ctx context.Context, t *testing.T, - backend *backends.SimulatedBackend, + backend *simulated.Backend, account *bind.TransactOpts, rounds int, poll func(blockHash common.Hash), @@ -450,7 +451,7 @@ func deployUpkeepCounter( t *testing.T, n int, ethClient *evmclient.SimulatedBackendClient, - backend *backends.SimulatedBackend, + backend *simulated.Backend, account *bind.TransactOpts, logProvider logprovider.LogEventProvider, ) ( @@ -460,7 +461,7 @@ func deployUpkeepCounter( ) { for i := 0; i < n; i++ { upkeepAddr, _, upkeepContract, err := log_upkeep_counter_wrapper.DeployLogUpkeepCounter( - account, backend, + account, backend.Client(), big.NewInt(100000), ) require.NoError(t, err) @@ -494,7 +495,7 @@ func newPlainLogTriggerConfig(upkeepAddr common.Address) logprovider.LogTriggerC } } -func setupDependencies(t *testing.T, db *sqlx.DB, backend *backends.SimulatedBackend) (logpoller.LogPollerTest, *evmclient.SimulatedBackendClient) { +func setupDependencies(t *testing.T, db *sqlx.DB, backend *simulated.Backend) (logpoller.LogPollerTest, *evmclient.SimulatedBackendClient) { ethClient := evmclient.NewSimulatedBackendClient(t, backend, big.NewInt(1337)) pollerLggr := logger.TestLogger(t) pollerLggr.SetLogLevel(zapcore.WarnLevel) @@ -522,11 +523,11 @@ func setup(lggr logger.Logger, poller logpoller.LogPoller, c evmclient.Client, s return provider, recoverer } -func setupBackend(t *testing.T) (*backends.SimulatedBackend, func(), []*bind.TransactOpts) { +func setupBackend(t *testing.T) (*simulated.Backend, func(), []*bind.TransactOpts) { sergey := testutils.MustNewSimTransactor(t) // owns all the link steve := testutils.MustNewSimTransactor(t) // registry owner carrol := testutils.MustNewSimTransactor(t) // upkeep owner - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ sergey.From: {Balance: assets.Ether(1000000000000000000).ToInt()}, steve.From: {Balance: assets.Ether(1000000000000000000).ToInt()}, carrol.From: {Balance: assets.Ether(1000000000000000000).ToInt()}, diff --git a/core/services/ocr2/plugins/ocr2keeper/integration_21_test.go b/core/services/ocr2/plugins/ocr2keeper/integration_21_test.go index 027c799494b..5ee6731299f 100644 --- a/core/services/ocr2/plugins/ocr2keeper/integration_21_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/integration_21_test.go @@ -15,12 +15,11 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core" gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/hashicorp/consul/sdk/freeport" "github.com/onsi/gomega" "github.com/stretchr/testify/assert" @@ -94,7 +93,7 @@ func TestIntegration_KeeperPluginConditionalUpkeep(t *testing.T) { sergey := testutils.MustNewSimTransactor(t) // owns all the link steve := testutils.MustNewSimTransactor(t) // registry owner carrol := testutils.MustNewSimTransactor(t) // upkeep owner - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ sergey.From: {Balance: assets.Ether(10000).ToInt()}, steve.From: {Balance: assets.Ether(10000).ToInt()}, carrol.From: {Balance: assets.Ether(10000).ToInt()}, @@ -103,7 +102,7 @@ func TestIntegration_KeeperPluginConditionalUpkeep(t *testing.T) { var nodeKeys [5]ethkey.KeyV2 for i := int64(0); i < 5; i++ { nodeKeys[i] = cltest.MustGenerateRandomKey(t) - genesisData[nodeKeys[i].Address] = core.GenesisAccount{Balance: assets.Ether(1000).ToInt()} + genesisData[nodeKeys[i].Address] = gethtypes.Account{Balance: assets.Ether(1000).ToInt()} } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) @@ -111,11 +110,11 @@ func TestIntegration_KeeperPluginConditionalUpkeep(t *testing.T) { defer stopMining() // Deploy registry - linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(sergey, backend) + linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(sergey, backend.Client()) require.NoError(t, err) - gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend, 18, big.NewInt(60000000000)) + gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend.Client(), 18, big.NewInt(60000000000)) require.NoError(t, err) - linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend, 18, big.NewInt(2000000000000000000)) + linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend.Client(), 18, big.NewInt(2000000000000000000)) require.NoError(t, err) registry := deployKeeper21Registry(t, steve, backend, linkAddr, linkFeedAddr, gasFeedAddr) @@ -129,7 +128,7 @@ func TestIntegration_KeeperPluginConditionalUpkeep(t *testing.T) { require.NoError(t, err) // Register new upkeep - upkeepAddr, _, upkeepContract, err := basic_upkeep_contract.DeployBasicUpkeepContract(carrol, backend) + upkeepAddr, _, upkeepContract, err := basic_upkeep_contract.DeployBasicUpkeepContract(carrol, backend.Client()) require.NoError(t, err) registrationTx, err := registry.RegisterUpkeep(steve, upkeepAddr, 2_500_000, carrol.From, 0, []byte{}, []byte{}, []byte{}) require.NoError(t, err) @@ -195,7 +194,7 @@ func TestIntegration_KeeperPluginLogUpkeep(t *testing.T) { sergey := testutils.MustNewSimTransactor(t) // owns all the link steve := testutils.MustNewSimTransactor(t) // registry owner carrol := testutils.MustNewSimTransactor(t) // upkeep owner - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ sergey.From: {Balance: assets.Ether(10000).ToInt()}, steve.From: {Balance: assets.Ether(10000).ToInt()}, carrol.From: {Balance: assets.Ether(10000).ToInt()}, @@ -204,7 +203,7 @@ func TestIntegration_KeeperPluginLogUpkeep(t *testing.T) { var nodeKeys [5]ethkey.KeyV2 for i := int64(0); i < 5; i++ { nodeKeys[i] = cltest.MustGenerateRandomKey(t) - genesisData[nodeKeys[i].Address] = core.GenesisAccount{Balance: assets.Ether(1000).ToInt()} + genesisData[nodeKeys[i].Address] = gethtypes.Account{Balance: assets.Ether(1000).ToInt()} } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) @@ -212,11 +211,11 @@ func TestIntegration_KeeperPluginLogUpkeep(t *testing.T) { defer stopMining() // Deploy registry - linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(sergey, backend) + linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(sergey, backend.Client()) require.NoError(t, err) - gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend, 18, big.NewInt(60000000000)) + gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend.Client(), 18, big.NewInt(60000000000)) require.NoError(t, err) - linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend, 18, big.NewInt(2000000000000000000)) + linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend.Client(), 18, big.NewInt(2000000000000000000)) require.NoError(t, err) registry := deployKeeper21Registry(t, steve, backend, linkAddr, linkFeedAddr, gasFeedAddr) @@ -225,7 +224,6 @@ func TestIntegration_KeeperPluginLogUpkeep(t *testing.T) { _, err = linkToken.Transfer(sergey, carrol.From, big.NewInt(0).Mul(oneHunEth, big.NewInt(int64(upkeeps+1)))) require.NoError(t, err) - backend.Commit() ids, addrs, contracts := deployUpkeeps(t, backend, carrol, steve, linkToken, registry, upkeeps) @@ -260,7 +258,7 @@ func TestIntegration_KeeperPluginLogUpkeep(t *testing.T) { } }) - h, err := backend.HeaderByNumber(testutils.Context(t), nil) + h, err := backend.Client().HeaderByNumber(testutils.Context(t), nil) require.NoError(t, err) beforeDummyBlocks := h.Number.Uint64() @@ -304,7 +302,7 @@ func TestIntegration_KeeperPluginLogUpkeep_Retry(t *testing.T) { linkOwner := testutils.MustNewSimTransactor(t) // owns all the link registryOwner := testutils.MustNewSimTransactor(t) // registry owner upkeepOwner := testutils.MustNewSimTransactor(t) // upkeep owner - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ linkOwner.From: {Balance: assets.Ether(10000).ToInt()}, registryOwner.From: {Balance: assets.Ether(10000).ToInt()}, upkeepOwner.From: {Balance: assets.Ether(10000).ToInt()}, @@ -314,7 +312,7 @@ func TestIntegration_KeeperPluginLogUpkeep_Retry(t *testing.T) { var nodeKeys [5]ethkey.KeyV2 for i := int64(0); i < 5; i++ { nodeKeys[i] = cltest.MustGenerateRandomKey(t) - genesisData[nodeKeys[i].Address] = core.GenesisAccount{Balance: assets.Ether(1000).ToInt()} + genesisData[nodeKeys[i].Address] = gethtypes.Account{Balance: assets.Ether(1000).ToInt()} } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) @@ -322,13 +320,13 @@ func TestIntegration_KeeperPluginLogUpkeep_Retry(t *testing.T) { defer stopMining() // Deploy registry - linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(linkOwner, backend) + linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(linkOwner, backend.Client()) require.NoError(t, err) - gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(registryOwner, backend, 18, big.NewInt(60000000000)) + gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(registryOwner, backend.Client(), 18, big.NewInt(60000000000)) require.NoError(t, err) - linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(registryOwner, backend, 18, big.NewInt(2000000000000000000)) + linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(registryOwner, backend.Client(), 18, big.NewInt(2000000000000000000)) require.NoError(t, err) registry := deployKeeper21Registry(t, registryOwner, backend, linkAddr, linkFeedAddr, gasFeedAddr) @@ -439,7 +437,7 @@ func TestIntegration_KeeperPluginLogUpkeep_ErrHandler(t *testing.T) { linkOwner := testutils.MustNewSimTransactor(t) // owns all the link registryOwner := testutils.MustNewSimTransactor(t) // registry owner upkeepOwner := testutils.MustNewSimTransactor(t) // upkeep owner - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ linkOwner.From: {Balance: assets.Ether(10000).ToInt()}, registryOwner.From: {Balance: assets.Ether(10000).ToInt()}, upkeepOwner.From: {Balance: assets.Ether(10000).ToInt()}, @@ -449,7 +447,7 @@ func TestIntegration_KeeperPluginLogUpkeep_ErrHandler(t *testing.T) { var nodeKeys [5]ethkey.KeyV2 for i := int64(0); i < 5; i++ { nodeKeys[i] = cltest.MustGenerateRandomKey(t) - genesisData[nodeKeys[i].Address] = core.GenesisAccount{Balance: assets.Ether(1000).ToInt()} + genesisData[nodeKeys[i].Address] = gethtypes.Account{Balance: assets.Ether(1000).ToInt()} } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) @@ -457,13 +455,13 @@ func TestIntegration_KeeperPluginLogUpkeep_ErrHandler(t *testing.T) { defer stopMining() // Deploy registry - linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(linkOwner, backend) + linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(linkOwner, backend.Client()) require.NoError(t, err) - gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(registryOwner, backend, 18, big.NewInt(60000000000)) + gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(registryOwner, backend.Client(), 18, big.NewInt(60000000000)) require.NoError(t, err) - linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(registryOwner, backend, 18, big.NewInt(2000000000000000000)) + linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(registryOwner, backend.Client(), 18, big.NewInt(2000000000000000000)) require.NoError(t, err) registry := deployKeeper21Registry(t, registryOwner, backend, linkAddr, linkFeedAddr, gasFeedAddr) @@ -511,19 +509,19 @@ func TestIntegration_KeeperPluginLogUpkeep_ErrHandler(t *testing.T) { require.NoError(t, feeds.EnableMercury(t, backend, registry, registryOwner)) require.NoError(t, feeds.VerifyEnv(t, backend, registry, registryOwner)) - h, err := backend.HeaderByNumber(testutils.Context(t), nil) - require.NoError(t, err) - startBlock := h.Number.Int64() - // start emitting events in a separate go-routine - // feed lookup relies on a single contract event log to perform multiple - // listener contracts - go func() { - // only 1 event is necessary to make all 10 upkeeps eligible - _ = feeds.EmitEvents(t, backend, 1, func() { - // pause per emit for expected block production time - time.Sleep(3 * time.Second) - }) - }() + h, err := backend.Client().HeaderByNumber(testutils.Context(t), nil) + require.NoError(t, err) + startBlock := h.Number.Int64() + // start emitting events in a separate go-routine + // feed lookup relies on a single contract event log to perform multiple + // listener contracts + go func() { + // only 1 event is necessary to make all 10 upkeeps eligible + _ = feeds.EmitEvents(t, backend, 1, func() { + // pause per emit for expected block production time + time.Sleep(3 * time.Second) + }) + }() go makeDummyBlocks(t, backend, 3*time.Second, 1000) @@ -560,7 +558,7 @@ func startMercuryServer(t *testing.T, mercuryServer *mercury.SimulatedMercurySer }) } -func makeDummyBlocks(t *testing.T, backend *backends.SimulatedBackend, interval time.Duration, count int) { +func makeDummyBlocks(t *testing.T, backend *simulated.Backend, interval time.Duration, count int) { go func() { ctx, cancel := context.WithCancel(testutils.Context(t)) defer cancel() @@ -594,14 +592,14 @@ func mapListener(m *sync.Map, n int) func() bool { } } -func listenPerformedN(t *testing.T, backend *backends.SimulatedBackend, registry *iregistry21.IKeeperRegistryMaster, ids []*big.Int, startBlock int64, count int) (func() bool, func()) { +func listenPerformedN(t *testing.T, backend *simulated.Backend, registry *iregistry21.IKeeperRegistryMaster, ids []*big.Int, startBlock int64, count int) (func() bool, func()) { cache := &sync.Map{} ctx, cancel := context.WithCancel(testutils.Context(t)) start := startBlock go func() { for ctx.Err() == nil { - h, err := backend.HeaderByNumber(testutils.Context(t), nil) + h, err := backend.Client().HeaderByNumber(testutils.Context(t), nil) require.NoError(t, err) currentBlock := h.Number.Uint64() @@ -646,11 +644,11 @@ func listenPerformedN(t *testing.T, backend *backends.SimulatedBackend, registry return mapListener(cache, count), cancel } -func listenPerformed(t *testing.T, backend *backends.SimulatedBackend, registry *iregistry21.IKeeperRegistryMaster, ids []*big.Int, startBlock int64) (func() bool, func()) { +func listenPerformed(t *testing.T, backend *simulated.Backend, registry *iregistry21.IKeeperRegistryMaster, ids []*big.Int, startBlock int64) (func() bool, func()) { return listenPerformedN(t, backend, registry, ids, startBlock, 0) } -func setupNodes(t *testing.T, nodeKeys [5]ethkey.KeyV2, registry *iregistry21.IKeeperRegistryMaster, backend *backends.SimulatedBackend, usr *bind.TransactOpts, useBufferV1 bool) ([]Node, *mercury.SimulatedMercuryServer) { +func setupNodes(t *testing.T, nodeKeys [5]ethkey.KeyV2, registry *iregistry21.IKeeperRegistryMaster, backend *simulated.Backend, usr *bind.TransactOpts, useBufferV1 bool) ([]Node, *mercury.SimulatedMercuryServer) { lggr := logger.TestLogger(t) mServer := mercury.NewSimulatedMercuryServer() mServer.Start() @@ -806,7 +804,7 @@ func setupNodes(t *testing.T, nodeKeys [5]ethkey.KeyV2, registry *iregistry21.IK return nodes, mServer } -func deployUpkeeps(t *testing.T, backend *backends.SimulatedBackend, carrol, steve *bind.TransactOpts, linkToken *link_token_interface.LinkToken, registry *iregistry21.IKeeperRegistryMaster, n int) ([]*big.Int, []common.Address, []*log_upkeep_counter_wrapper.LogUpkeepCounter) { +func deployUpkeeps(t *testing.T, backend *simulated.Backend, carrol, steve *bind.TransactOpts, linkToken *link_token_interface.LinkToken, registry *iregistry21.IKeeperRegistryMaster, n int) ([]*big.Int, []common.Address, []*log_upkeep_counter_wrapper.LogUpkeepCounter) { ids := make([]*big.Int, n) addrs := make([]common.Address, n) contracts := make([]*log_upkeep_counter_wrapper.LogUpkeepCounter, n) @@ -814,7 +812,7 @@ func deployUpkeeps(t *testing.T, backend *backends.SimulatedBackend, carrol, ste backend.Commit() time.Sleep(1 * time.Second) upkeepAddr, _, upkeepContract, err := log_upkeep_counter_wrapper.DeployLogUpkeepCounter( - carrol, backend, + carrol, backend.Client(), big.NewInt(100000), ) require.NoError(t, err) @@ -835,7 +833,7 @@ func deployUpkeeps(t *testing.T, backend *backends.SimulatedBackend, carrol, ste return ids, addrs, contracts } -func registerUpkeep(t *testing.T, registry *iregistry21.IKeeperRegistryMaster, upkeepAddr common.Address, carrol, steve *bind.TransactOpts, backend *backends.SimulatedBackend) *big.Int { +func registerUpkeep(t *testing.T, registry *iregistry21.IKeeperRegistryMaster, upkeepAddr common.Address, carrol, steve *bind.TransactOpts, backend *simulated.Backend) *big.Int { logTriggerConfigType := abi.MustNewType("tuple(address contractAddress, uint8 filterSelector, bytes32 topic0, bytes32 topic1, bytes32 topic2, bytes32 topic3)") logTriggerConfig, err := abi.Encode(map[string]interface{}{ "contractAddress": upkeepAddr, @@ -858,16 +856,16 @@ func registerUpkeep(t *testing.T, registry *iregistry21.IKeeperRegistryMaster, u func deployKeeper21Registry( t *testing.T, auth *bind.TransactOpts, - backend *backends.SimulatedBackend, + backend *simulated.Backend, linkAddr, linkFeedAddr, gasFeedAddr common.Address, ) *iregistry21.IKeeperRegistryMaster { - automationForwarderLogicAddr, _, _, err := automationForwarderLogic.DeployAutomationForwarderLogic(auth, backend) + automationForwarderLogicAddr, _, _, err := automationForwarderLogic.DeployAutomationForwarderLogic(auth, backend.Client()) require.NoError(t, err) backend.Commit() registryLogicBAddr, _, _, err := registrylogicb21.DeployKeeperRegistryLogicB( auth, - backend, + backend.Client(), 0, // Payment model linkAddr, linkFeedAddr, @@ -879,7 +877,7 @@ func deployKeeper21Registry( registryLogicAAddr, _, _, err := registrylogica21.DeployKeeperRegistryLogicA( auth, - backend, + backend.Client(), registryLogicBAddr, ) require.NoError(t, err) @@ -887,20 +885,20 @@ func deployKeeper21Registry( registryAddr, _, _, err := registry21.DeployKeeperRegistry( auth, - backend, + backend.Client(), registryLogicAAddr, ) require.NoError(t, err) backend.Commit() - registryMaster, err := iregistry21.NewIKeeperRegistryMaster(registryAddr, backend) + registryMaster, err := iregistry21.NewIKeeperRegistryMaster(registryAddr, backend.Client()) require.NoError(t, err) return registryMaster } -func getUpkeepIdFromTx21(t *testing.T, registry *iregistry21.IKeeperRegistryMaster, registrationTx *gethtypes.Transaction, backend *backends.SimulatedBackend) *big.Int { - receipt, err := backend.TransactionReceipt(testutils.Context(t), registrationTx.Hash()) +func getUpkeepIdFromTx21(t *testing.T, registry *iregistry21.IKeeperRegistryMaster, registrationTx *gethtypes.Transaction, backend *simulated.Backend) *big.Int { + receipt, err := backend.Client().TransactionReceipt(testutils.Context(t), registrationTx.Hash()) require.NoError(t, err) parsedLog, err := registry.ParseUpkeepRegistered(*receipt.Logs[0]) require.NoError(t, err) @@ -913,7 +911,7 @@ type registerAndFundFunc func(*testing.T, common.Address, *bind.TransactOpts, ui func registerAndFund( registry *iregistry21.IKeeperRegistryMaster, registryOwner *bind.TransactOpts, - backend *backends.SimulatedBackend, + backend *simulated.Backend, linkToken *link_token_interface.LinkToken, ) registerAndFundFunc { return func(t *testing.T, upkeepAddr common.Address, upkeepOwner *bind.TransactOpts, trigger uint8, config []byte) *big.Int { @@ -932,7 +930,7 @@ func registerAndFund( backend.Commit() - receipt, err := backend.TransactionReceipt(testutils.Context(t), registrationTx.Hash()) + receipt, err := backend.Client().TransactionReceipt(testutils.Context(t), registrationTx.Hash()) require.NoError(t, err) parsedLog, err := registry.ParseUpkeepRegistered(*receipt.Logs[0]) @@ -968,10 +966,10 @@ type feedLookupUpkeepController struct { } func newFeedLookupUpkeepController( - backend *backends.SimulatedBackend, + backend *simulated.Backend, protocolOwner *bind.TransactOpts, ) (*feedLookupUpkeepController, error) { - addr, _, contract, err := dummy_protocol_wrapper.DeployDummyProtocol(protocolOwner, backend) + addr, _, contract, err := dummy_protocol_wrapper.DeployDummyProtocol(protocolOwner, backend.Client()) if err != nil { return nil, err } @@ -987,7 +985,7 @@ func newFeedLookupUpkeepController( func (c *feedLookupUpkeepController) DeployUpkeeps( t *testing.T, - backend *backends.SimulatedBackend, + backend *simulated.Backend, owner *bind.TransactOpts, count int, checkErrResultsProvider func(i int) bool, @@ -1003,7 +1001,7 @@ func (c *feedLookupUpkeepController) DeployUpkeeps( } addr, _, contract, err := log_triggered_streams_lookup_wrapper.DeployLogTriggeredStreamsLookup( owner, - backend, + backend.Client(), false, false, checkErrResult, @@ -1033,7 +1031,7 @@ func (c *feedLookupUpkeepController) RegisterAndFund( t *testing.T, registry *iregistry21.IKeeperRegistryMaster, registryOwner *bind.TransactOpts, - backend *backends.SimulatedBackend, + backend *simulated.Backend, linkToken *link_token_interface.LinkToken, ) error { ids := make([]*big.Int, len(c.contracts)) @@ -1065,7 +1063,7 @@ func (c *feedLookupUpkeepController) RegisterAndFund( func (c *feedLookupUpkeepController) EnableMercury( t *testing.T, - backend *backends.SimulatedBackend, + backend *simulated.Backend, registry *iregistry21.IKeeperRegistryMaster, registryOwner *bind.TransactOpts, ) error { @@ -1104,7 +1102,7 @@ func (c *feedLookupUpkeepController) EnableMercury( require.True(t, checkBytes.MercuryEnabled) } - bl, _ := backend.BlockByHash(testutils.Context(t), backend.Commit()) + bl, _ := backend.Client().BlockByHash(testutils.Context(t), backend.Commit()) t.Logf("block number after mercury enabled: %d", bl.NumberU64()) return nil @@ -1112,7 +1110,7 @@ func (c *feedLookupUpkeepController) EnableMercury( func (c *feedLookupUpkeepController) VerifyEnv( t *testing.T, - backend *backends.SimulatedBackend, + backend *simulated.Backend, registry *iregistry21.IKeeperRegistryMaster, registryOwner *bind.TransactOpts, ) error { @@ -1156,7 +1154,7 @@ func (c *feedLookupUpkeepController) VerifyEnv( func (c *feedLookupUpkeepController) EmitEvents( t *testing.T, - backend *backends.SimulatedBackend, + backend *simulated.Backend, count int, afterEmit func(), ) error { @@ -1173,7 +1171,7 @@ func (c *feedLookupUpkeepController) EmitEvents( backend.Commit() // verify event was emitted - block, _ := backend.BlockByHash(ctx, backend.Commit()) + block, _ := backend.Client().BlockByHash(ctx, backend.Commit()) t.Logf("block number after emit event: %d", block.NumberU64()) iter, _ := c.protocol.FilterLimitOrderExecuted( diff --git a/core/services/ocr2/plugins/ocr2keeper/integration_test.go b/core/services/ocr2/plugins/ocr2keeper/integration_test.go index bb32d3a8530..70070653fca 100644 --- a/core/services/ocr2/plugins/ocr2keeper/integration_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/integration_test.go @@ -11,12 +11,11 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core" gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/hashicorp/consul/sdk/freeport" "github.com/onsi/gomega" "github.com/pkg/errors" @@ -76,13 +75,13 @@ var ( func deployKeeper20Registry( t *testing.T, auth *bind.TransactOpts, - backend *backends.SimulatedBackend, + backend *simulated.Backend, linkAddr, linkFeedAddr, gasFeedAddr common.Address, ) *keeper_registry_wrapper2_0.KeeperRegistry { logicAddr, _, _, err := keeper_registry_logic2_0.DeployKeeperRegistryLogic( auth, - backend, + backend.Client(), 0, // Payment model linkAddr, linkFeedAddr, @@ -92,13 +91,13 @@ func deployKeeper20Registry( regAddr, _, _, err := keeper_registry_wrapper2_0.DeployKeeperRegistry( auth, - backend, + backend.Client(), logicAddr, ) require.NoError(t, err) backend.Commit() - registry, err := keeper_registry_wrapper2_0.NewKeeperRegistry(regAddr, backend) + registry, err := keeper_registry_wrapper2_0.NewKeeperRegistry(regAddr, backend.Client()) require.NoError(t, err) return registry @@ -108,7 +107,7 @@ func setupNode( t *testing.T, port int, nodeKey ethkey.KeyV2, - backend *backends.SimulatedBackend, + backend *simulated.Backend, p2pV2Bootstrappers []commontypes.BootstrapperLocator, mercury mercury.MercuryEndpointMock, ) (chainlink.Application, string, common.Address, ocr2key.KeyBundle) { @@ -192,8 +191,8 @@ func accountsToAddress(accounts []ocrTypes.Account) (addresses []common.Address, return addresses, nil } -func getUpkeepIdFromTx(t *testing.T, registry *keeper_registry_wrapper2_0.KeeperRegistry, registrationTx *gethtypes.Transaction, backend *backends.SimulatedBackend) *big.Int { - receipt, err := backend.TransactionReceipt(testutils.Context(t), registrationTx.Hash()) +func getUpkeepIdFromTx(t *testing.T, registry *keeper_registry_wrapper2_0.KeeperRegistry, registrationTx *gethtypes.Transaction, backend *simulated.Backend) *big.Int { + receipt, err := backend.Client().TransactionReceipt(testutils.Context(t), registrationTx.Hash()) require.NoError(t, err) parsedLog, err := registry.ParseUpkeepRegistered(*receipt.Logs[0]) require.NoError(t, err) @@ -208,7 +207,7 @@ func TestIntegration_KeeperPluginBasic(t *testing.T) { sergey := testutils.MustNewSimTransactor(t) // owns all the link steve := testutils.MustNewSimTransactor(t) // registry owner carrol := testutils.MustNewSimTransactor(t) // upkeep owner - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ sergey.From: {Balance: assets.Ether(1000).ToInt()}, steve.From: {Balance: assets.Ether(1000).ToInt()}, carrol.From: {Balance: assets.Ether(1000).ToInt()}, @@ -217,7 +216,7 @@ func TestIntegration_KeeperPluginBasic(t *testing.T) { var nodeKeys [5]ethkey.KeyV2 for i := int64(0); i < 5; i++ { nodeKeys[i] = cltest.MustGenerateRandomKey(t) - genesisData[nodeKeys[i].Address] = core.GenesisAccount{Balance: assets.Ether(1000).ToInt()} + genesisData[nodeKeys[i].Address] = gethtypes.Account{Balance: assets.Ether(1000).ToInt()} } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) @@ -225,11 +224,11 @@ func TestIntegration_KeeperPluginBasic(t *testing.T) { defer stopMining() // Deploy contracts - linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(sergey, backend) + linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(sergey, backend.Client()) require.NoError(t, err) - gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend, 18, big.NewInt(60000000000)) + gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend.Client(), 18, big.NewInt(60000000000)) require.NoError(t, err) - linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend, 18, big.NewInt(2000000000000000000)) + linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend.Client(), 18, big.NewInt(2000000000000000000)) require.NoError(t, err) registry := deployKeeper20Registry(t, steve, backend, linkAddr, linkFeedAddr, gasFeedAddr) @@ -377,7 +376,7 @@ func TestIntegration_KeeperPluginBasic(t *testing.T) { backend.Commit() // Register new upkeep - upkeepAddr, _, upkeepContract, err := basic_upkeep_contract.DeployBasicUpkeepContract(carrol, backend) + upkeepAddr, _, upkeepContract, err := basic_upkeep_contract.DeployBasicUpkeepContract(carrol, backend.Client()) require.NoError(t, err) registrationTx, err := registry.RegisterUpkeep(steve, upkeepAddr, 2_500_000, carrol.From, []byte{}, []byte{}) require.NoError(t, err) @@ -424,10 +423,10 @@ func setupForwarderForNode( t *testing.T, app chainlink.Application, caller *bind.TransactOpts, - backend *backends.SimulatedBackend, + backend *simulated.Backend, recipient common.Address, linkAddr common.Address) common.Address { - faddr, _, authorizedForwarder, err := authorized_forwarder.DeployAuthorizedForwarder(caller, backend, linkAddr, caller.From, recipient, []byte{}) + faddr, _, authorizedForwarder, err := authorized_forwarder.DeployAuthorizedForwarder(caller, backend.Client(), linkAddr, caller.From, recipient, []byte{}) require.NoError(t, err) // set EOA as an authorized sender for the forwarder @@ -437,7 +436,7 @@ func setupForwarderForNode( // add forwarder address to be tracked in db forwarderORM := forwarders.NewORM(app.GetDB()) - chainID, err := backend.ChainID(testutils.Context(t)) + chainID, err := backend.Client().ChainID(testutils.Context(t)) require.NoError(t, err) _, err = forwarderORM.CreateForwarder(testutils.Context(t), faddr, ubig.Big(*chainID)) require.NoError(t, err) @@ -459,7 +458,7 @@ func TestIntegration_KeeperPluginForwarderEnabled(t *testing.T) { sergey := testutils.MustNewSimTransactor(t) // owns all the link steve := testutils.MustNewSimTransactor(t) // registry owner carrol := testutils.MustNewSimTransactor(t) // upkeep owner - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ sergey.From: {Balance: assets.Ether(1000).ToInt()}, steve.From: {Balance: assets.Ether(1000).ToInt()}, carrol.From: {Balance: assets.Ether(1000).ToInt()}, @@ -468,7 +467,7 @@ func TestIntegration_KeeperPluginForwarderEnabled(t *testing.T) { var nodeKeys [5]ethkey.KeyV2 for i := int64(0); i < 5; i++ { nodeKeys[i] = cltest.MustGenerateRandomKey(t) - genesisData[nodeKeys[i].Address] = core.GenesisAccount{Balance: assets.Ether(1000).ToInt()} + genesisData[nodeKeys[i].Address] = gethtypes.Account{Balance: assets.Ether(1000).ToInt()} } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) @@ -476,11 +475,11 @@ func TestIntegration_KeeperPluginForwarderEnabled(t *testing.T) { defer stopMining() // Deploy contracts - linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(sergey, backend) + linkAddr, _, linkToken, err := link_token_interface.DeployLinkToken(sergey, backend.Client()) require.NoError(t, err) - gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend, 18, big.NewInt(60000000000)) + gasFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend.Client(), 18, big.NewInt(60000000000)) require.NoError(t, err) - linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend, 18, big.NewInt(2000000000000000000)) + linkFeedAddr, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract(steve, backend.Client(), 18, big.NewInt(2000000000000000000)) require.NoError(t, err) registry := deployKeeper20Registry(t, steve, backend, linkAddr, linkFeedAddr, gasFeedAddr) @@ -640,7 +639,7 @@ func TestIntegration_KeeperPluginForwarderEnabled(t *testing.T) { backend.Commit() // Register new upkeep - upkeepAddr, _, upkeepContract, err := basic_upkeep_contract.DeployBasicUpkeepContract(carrol, backend) + upkeepAddr, _, upkeepContract, err := basic_upkeep_contract.DeployBasicUpkeepContract(carrol, backend.Client()) require.NoError(t, err) registrationTx, err := registry.RegisterUpkeep(steve, upkeepAddr, 2_500_000, carrol.From, []byte{}, []byte{}) require.NoError(t, err) diff --git a/core/services/ocr2/plugins/ocr2vrf/internal/ocr2vrf_integration_test.go b/core/services/ocr2/plugins/ocr2vrf/internal/ocr2vrf_integration_test.go index fe14eb4451e..ee722587de6 100644 --- a/core/services/ocr2/plugins/ocr2vrf/internal/ocr2vrf_integration_test.go +++ b/core/services/ocr2/plugins/ocr2vrf/internal/ocr2vrf_integration_test.go @@ -10,12 +10,12 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/hashicorp/consul/sdk/freeport" "github.com/onsi/gomega" "github.com/stretchr/testify/require" @@ -32,6 +32,7 @@ import ( commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" commonutils "github.com/smartcontractkit/chainlink-common/pkg/utils" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/forwarders" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" @@ -59,7 +60,7 @@ import ( type ocr2vrfUniverse struct { owner *bind.TransactOpts - backend *backends.SimulatedBackend + backend *simulated.Backend dkgAddress common.Address dkg *dkg_wrapper.DKG @@ -101,12 +102,12 @@ func setupOCR2VRFContracts( t *testing.T, beaconPeriod int64, keyID [32]byte, consumerShouldFail bool) ocr2vrfUniverse { owner := testutils.MustNewSimTransactor(t) owner.GasPrice = assets.GWei(1).ToInt() - genesisData := core.GenesisAlloc{ + genesisData := types.GenesisAlloc{ owner.From: { Balance: assets.Ether(100).ToInt(), }, } - b := backends.NewSimulatedBackend(genesisData, ethconfig.Defaults.Miner.GasCeil*2) + b := simulated.NewBackend(genesisData, simulated.WithBlockGasLimit(ethconfig.Defaults.Miner.GasCeil*2)) // deploy OCR2VRF contracts, which have the following deploy order: // * link token @@ -115,21 +116,21 @@ func setupOCR2VRFContracts( // * VRF (coordinator, and beacon) // * VRF consumer linkAddress, _, link, err := link_token_interface.DeployLinkToken( - owner, b) + owner, b.Client()) require.NoError(t, err) b.Commit() feedAddress, _, feed, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract( - owner, b, 18, assets.GWei(int(1e7)).ToInt()) // 0.01 eth per link + owner, b.Client(), 18, assets.GWei(int(1e7)).ToInt()) // 0.01 eth per link require.NoError(t, err) b.Commit() - dkgAddress, _, dkg, err := dkg_wrapper.DeployDKG(owner, b) + dkgAddress, _, dkg, err := dkg_wrapper.DeployDKG(owner, b.Client()) require.NoError(t, err) b.Commit() coordinatorAddress, _, coordinator, err := vrf_wrapper.DeployVRFCoordinator( - owner, b, big.NewInt(beaconPeriod), linkAddress) + owner, b.Client(), big.NewInt(beaconPeriod), linkAddress) require.NoError(t, err) b.Commit() @@ -148,17 +149,17 @@ func setupOCR2VRFContracts( b.Commit() beaconAddress, _, beacon, err := vrf_beacon.DeployVRFBeacon( - owner, b, linkAddress, coordinatorAddress, dkgAddress, keyID) + owner, b.Client(), linkAddress, coordinatorAddress, dkgAddress, keyID) require.NoError(t, err) b.Commit() consumerAddress, _, consumer, err := vrf_beacon_consumer.DeployBeaconVRFConsumer( - owner, b, coordinatorAddress, consumerShouldFail, big.NewInt(beaconPeriod)) + owner, b.Client(), coordinatorAddress, consumerShouldFail, big.NewInt(beaconPeriod)) require.NoError(t, err) b.Commit() loadTestConsumerAddress, _, loadTestConsumer, err := load_test_beacon_consumer.DeployLoadTestBeaconVRFConsumer( - owner, b, coordinatorAddress, consumerShouldFail, big.NewInt(beaconPeriod)) + owner, b.Client(), coordinatorAddress, consumerShouldFail, big.NewInt(beaconPeriod)) require.NoError(t, err) b.Commit() @@ -221,7 +222,7 @@ func setupNodeOCR2( owner *bind.TransactOpts, port int, dbName string, - b *backends.SimulatedBackend, + b *simulated.Backend, useForwarders bool, p2pV2Bootstrappers []commontypes.BootstrapperLocator, ) *ocr2Node { @@ -276,7 +277,7 @@ func setupNodeOCR2( require.Len(t, sendingKeys, 2) // Deploy a forwarder. - faddr, _, authorizedForwarder, err := authorized_forwarder.DeployAuthorizedForwarder(owner, b, common.HexToAddress("0x326C977E6efc84E512bB9C30f76E30c160eD06FB"), owner.From, common.Address{}, []byte{}) + faddr, _, authorizedForwarder, err := authorized_forwarder.DeployAuthorizedForwarder(owner, b.Client(), common.HexToAddress("0x326C977E6efc84E512bB9C30f76E30c160eD06FB"), owner.From, common.Address{}, []byte{}) require.NoError(t, err) // Set the node's sending keys as authorized senders. @@ -296,7 +297,7 @@ func setupNodeOCR2( var sendingKeyStrings []string for _, k := range sendingKeys { sendingKeyStrings = append(sendingKeyStrings, k.Address.String()) - n, err := b.NonceAt(ctx, owner.From, nil) + n, err := b.Client().NonceAt(ctx, owner.From, nil) require.NoError(t, err) tx := cltest.NewLegacyTransaction( @@ -307,7 +308,7 @@ func setupNodeOCR2( nil) signedTx, err := owner.Signer(owner.From, tx) require.NoError(t, err) - err = b.SendTransaction(ctx, signedTx) + err = b.Client().SendTransaction(ctx, signedTx) require.NoError(t, err) b.Commit() } @@ -410,7 +411,7 @@ func runOCR2VRFTest(t *testing.T, useForwarders bool) { } }() - blockBeforeConfig, err := uni.backend.BlockByNumber(ctx, nil) + blockBeforeConfig, err := uni.backend.Client().BlockByNumber(ctx, nil) require.NoError(t, err) t.Log("Setting DKG config before block:", blockBeforeConfig.Number().String()) @@ -661,7 +662,7 @@ linkEthFeedAddress = "%s" totalNopPayout := new(big.Int) for idx, payeeTransactor := range payeeTransactors { // Fund the payee with some ETH. - n, err2 := uni.backend.NonceAt(ctx, uni.owner.From, nil) + n, err2 := uni.backend.Client().NonceAt(ctx, uni.owner.From, nil) require.NoError(t, err2) tx := cltest.NewLegacyTransaction( n, payeeTransactor.From, @@ -671,7 +672,7 @@ linkEthFeedAddress = "%s" nil) signedTx, err2 := uni.owner.Signer(uni.owner.From, tx) require.NoError(t, err2) - err2 = uni.backend.SendTransaction(ctx, signedTx) + err2 = uni.backend.Client().SendTransaction(ctx, signedTx) require.NoError(t, err2) _, err2 = uni.beacon.WithdrawPayment(payeeTransactor, transmitters[idx]) diff --git a/core/services/relay/evm/chain_reader_test.go b/core/services/relay/evm/chain_reader_test.go index c3cb36b93e3..c81cafebf3c 100644 --- a/core/services/relay/evm/chain_reader_test.go +++ b/core/services/relay/evm/chain_reader_test.go @@ -13,12 +13,11 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core" evmtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/smartcontractkit/libocr/commontypes" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -63,7 +62,7 @@ func TestChainReaderGetLatestValue(t *testing.T) { anyString := "foo" tx, err := it.evmTest.TriggerEventWithDynamicTopic(it.auth, anyString) require.NoError(t, err) - it.sim.Commit() + it.backend.Commit() it.incNonce() it.awaitTx(t, tx) @@ -113,7 +112,7 @@ func triggerFourTopics(t *testing.T, it *chainReaderInterfaceTester, i1, i2, i3 tx, err := it.evmTest.ChainReaderTesterTransactor.TriggerWithFourTopics(it.auth, i1, i2, i3) require.NoError(t, err) require.NoError(t, err) - it.sim.Commit() + it.backend.Commit() it.incNonce() it.awaitTx(t, tx) } @@ -124,7 +123,7 @@ type chainReaderInterfaceTester struct { address2 string chainConfig types.ChainReaderConfig auth *bind.TransactOpts - sim *backends.SimulatedBackend + backend *simulated.Backend pk *ecdsa.PrivateKey evmTest *chain_reader_tester.ChainReaderTester cr evm.ChainReaderService @@ -238,7 +237,7 @@ func (it *chainReaderInterfaceTester) Setup(t *testing.T) { }, }, } - it.client = client.NewSimulatedBackendClient(t, it.sim, big.NewInt(1337)) + it.client = client.NewSimulatedBackendClient(t, it.backend, big.NewInt(1337)) it.deployNewContracts(t) } @@ -308,7 +307,7 @@ func (it *chainReaderInterfaceTester) sendTxWithTestStruct(t *testing.T, testStr midToInternalType(testStruct.NestedStruct), ) require.NoError(t, err) - it.sim.Commit() + it.backend.Commit() it.incNonce() it.awaitTx(t, tx) } @@ -337,8 +336,8 @@ func (it *chainReaderInterfaceTester) setupChainNoClient(t require.TestingT) { it.auth, err = bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(1337)) require.NoError(t, err) - it.sim = backends.NewSimulatedBackend(core.GenesisAlloc{it.auth.From: {Balance: big.NewInt(math.MaxInt64)}}, commonGasLimitOnEvms*5000) - it.sim.Commit() + it.backend = simulated.NewBackend(evmtypes.GenesisAlloc{it.auth.From: {Balance: big.NewInt(math.MaxInt64)}}, simulated.WithBlockGasLimit(commonGasLimitOnEvms*5000)) + it.backend.Commit() } func (it *chainReaderInterfaceTester) deployNewContracts(t *testing.T) { @@ -348,7 +347,7 @@ func (it *chainReaderInterfaceTester) deployNewContracts(t *testing.T) { func (it *chainReaderInterfaceTester) deployNewContract(t *testing.T) string { ctx := testutils.Context(t) - gasPrice, err := it.sim.SuggestGasPrice(ctx) + gasPrice, err := it.client.SuggestGasPrice(ctx) require.NoError(t, err) it.auth.GasPrice = gasPrice @@ -356,10 +355,10 @@ func (it *chainReaderInterfaceTester) deployNewContract(t *testing.T) string { // Not sure if there's a better way to get it. it.auth.GasLimit = 10552800 - address, tx, ts, err := chain_reader_tester.DeployChainReaderTester(it.auth, it.sim) + address, tx, ts, err := chain_reader_tester.DeployChainReaderTester(it.auth, it.client) require.NoError(t, err) - it.sim.Commit() + it.backend.Commit() if it.evmTest == nil { it.evmTest = ts } @@ -370,7 +369,7 @@ func (it *chainReaderInterfaceTester) deployNewContract(t *testing.T) string { func (it *chainReaderInterfaceTester) awaitTx(t *testing.T, tx *evmtypes.Transaction) { ctx := testutils.Context(t) - receipt, err := it.sim.TransactionReceipt(ctx, tx.Hash()) + receipt, err := it.client.TransactionReceipt(ctx, tx.Hash()) require.NoError(t, err) require.Equal(t, evmtypes.ReceiptStatusSuccessful, receipt.Status) } diff --git a/core/services/relay/evm/config_poller_test.go b/core/services/relay/evm/config_poller_test.go index 8c02c4e2e7e..7931bfaa5d9 100644 --- a/core/services/relay/evm/config_poller_test.go +++ b/core/services/relay/evm/config_poller_test.go @@ -8,11 +8,11 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/onsi/gomega" "github.com/pkg/errors" "github.com/stretchr/testify/assert" @@ -52,7 +52,8 @@ func TestConfigPoller(t *testing.T) { var configStoreContractAddr common.Address var configStoreContract *ocrconfigurationstoreevmsimple.OCRConfigurationStoreEVMSimple var user *bind.TransactOpts - var b *backends.SimulatedBackend + var b *simulated.Backend + var ec simulated.Client var linkTokenAddress common.Address var accessAddress common.Address ctx := testutils.Context(t) @@ -64,16 +65,18 @@ func TestConfigPoller(t *testing.T) { require.NoError(t, err) user, err = bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337)) require.NoError(t, err) - b = backends.NewSimulatedBackend(core.GenesisAlloc{ + b = simulated.NewBackend(types.GenesisAlloc{ user.From: {Balance: big.NewInt(1000000000000000000)}}, - 5*ethconfig.Defaults.Miner.GasCeil) - linkTokenAddress, _, _, err = link_token_interface.DeployLinkToken(user, b) + simulated.WithBlockGasLimit(5*ethconfig.Defaults.Miner.GasCeil)) + require.NotNil(t, b) + ec = b.Client() + linkTokenAddress, _, _, err = link_token_interface.DeployLinkToken(user, ec) require.NoError(t, err) - accessAddress, _, _, err = testoffchainaggregator2.DeploySimpleWriteAccessController(user, b) + accessAddress, _, _, err = testoffchainaggregator2.DeploySimpleWriteAccessController(user, ec) require.NoError(t, err, "failed to deploy test access controller contract") ocrAddress, _, ocrContract, err = ocr2aggregator.DeployOCR2Aggregator( user, - b, + ec, linkTokenAddress, big.NewInt(0), big.NewInt(10), @@ -83,7 +86,7 @@ func TestConfigPoller(t *testing.T) { "TEST", ) require.NoError(t, err) - configStoreContractAddr, _, configStoreContract, err = ocrconfigurationstoreevmsimple.DeployOCRConfigurationStoreEVMSimple(user, b) + configStoreContractAddr, _, configStoreContract, err = ocrconfigurationstoreevmsimple.DeployOCRConfigurationStoreEVMSimple(user, ec) require.NoError(t, err) b.Commit() @@ -133,7 +136,7 @@ func TestConfigPoller(t *testing.T) { DeltaC: 10, }, ocrContract, user) b.Commit() - latest, err := b.BlockByNumber(testutils.Context(t), nil) + latest, err := ec.BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) // Ensure we capture this config set log. require.NoError(t, lp.Replay(testutils.Context(t), latest.Number().Int64()-1)) @@ -164,7 +167,7 @@ func TestConfigPoller(t *testing.T) { var err error ocrAddress, _, ocrContract, err = ocr2aggregator.DeployOCR2Aggregator( user, - b, + ec, linkTokenAddress, big.NewInt(0), big.NewInt(10), @@ -207,7 +210,7 @@ func TestConfigPoller(t *testing.T) { changedInBlock, configDigest, err := cp.LatestConfigDetails(testutils.Context(t)) require.NoError(t, err) - latest, err := b.BlockByNumber(testutils.Context(t), nil) + latest, err := ec.BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) onchainDetails, err := ocrContract.LatestConfigDetails(nil) @@ -239,7 +242,7 @@ func TestConfigPoller(t *testing.T) { // deploy it again to reset to empty config ocrAddress, _, ocrContract, err = ocr2aggregator.DeployOCR2Aggregator( user, - b, + ec, linkTokenAddress, big.NewInt(0), big.NewInt(10), diff --git a/core/services/relay/evm/functions/config_poller_test.go b/core/services/relay/evm/functions/config_poller_test.go index 2d96b2fd15d..dd16245464e 100644 --- a/core/services/relay/evm/functions/config_poller_test.go +++ b/core/services/relay/evm/functions/config_poller_test.go @@ -7,10 +7,10 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/onsi/gomega" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -53,17 +53,17 @@ func runTest(t *testing.T, pluginType functions.FunctionsPluginType, expectedDig require.NoError(t, err) user, err := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337)) require.NoError(t, err) - b := backends.NewSimulatedBackend(core.GenesisAlloc{ + b := simulated.NewBackend(types.GenesisAlloc{ user.From: {Balance: big.NewInt(1000000000000000000)}}, - 5*ethconfig.Defaults.Miner.GasCeil) + simulated.WithBlockGasLimit(5*ethconfig.Defaults.Miner.GasCeil)) defer b.Close() - linkTokenAddress, _, _, err := link_token_interface.DeployLinkToken(user, b) + linkTokenAddress, _, _, err := link_token_interface.DeployLinkToken(user, b.Client()) require.NoError(t, err) - accessAddress, _, _, err := testoffchainaggregator2.DeploySimpleWriteAccessController(user, b) + accessAddress, _, _, err := testoffchainaggregator2.DeploySimpleWriteAccessController(user, b.Client()) require.NoError(t, err, "failed to deploy test access controller contract") ocrAddress, _, ocrContract, err := ocr2aggregator.DeployOCR2Aggregator( user, - b, + b.Client(), linkTokenAddress, big.NewInt(0), big.NewInt(10), @@ -122,7 +122,7 @@ func runTest(t *testing.T, pluginType functions.FunctionsPluginType, expectedDig // Set the config contractConfig := setFunctionsConfig(t, pluginConfig, ocrContract, user) b.Commit() - latest, err := b.BlockByNumber(testutils.Context(t), nil) + latest, err := b.Client().BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) // Ensure we capture this config set log. require.NoError(t, lp.Replay(testutils.Context(t), latest.Number().Int64()-1)) diff --git a/core/services/relay/evm/mercury/config_digest_test.go b/core/services/relay/evm/mercury/config_digest_test.go index fe718e92fe5..56004dcfdb4 100644 --- a/core/services/relay/evm/mercury/config_digest_test.go +++ b/core/services/relay/evm/mercury/config_digest_test.go @@ -7,11 +7,11 @@ import ( "unsafe" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/leanovate/gopter" "github.com/leanovate/gopter/gen" "github.com/leanovate/gopter/prop" @@ -28,12 +28,12 @@ func TestConfigCalculationMatches(t *testing.T) { require.NoError(t, err, "could not make private key for EOA owner") owner, err := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337)) require.NoError(t, err) - backend := backends.NewSimulatedBackend( - core.GenesisAlloc{owner.From: {Balance: new(big.Int).Lsh(big.NewInt(1), 60)}}, - ethconfig.Defaults.Miner.GasCeil, + backend := simulated.NewBackend( + types.GenesisAlloc{owner.From: {Balance: new(big.Int).Lsh(big.NewInt(1), 60)}}, + simulated.WithBlockGasLimit(ethconfig.Defaults.Miner.GasCeil), ) _, _, eoa, err := exposed_verifier.DeployExposedVerifier( - owner, backend, + owner, backend.Client(), ) backend.Commit() require.NoError(t, err, "could not deploy test EOA") diff --git a/core/services/relay/evm/mercury/config_poller_test.go b/core/services/relay/evm/mercury/config_poller_test.go index f828938f954..4f4a930280b 100644 --- a/core/services/relay/evm/mercury/config_poller_test.go +++ b/core/services/relay/evm/mercury/config_poller_test.go @@ -85,7 +85,7 @@ func TestMercuryConfigPoller(t *testing.T) { require.NoError(t, err, "failed to setConfig with feed ID") th.backend.Commit() - latest, err := th.backend.BlockByNumber(testutils.Context(t), nil) + latest, err := th.backend.Client().BlockByNumber(testutils.Context(t), nil) require.NoError(t, err) // Ensure we capture this config set log. require.NoError(t, th.logPoller.Replay(testutils.Context(t), latest.Number().Int64()-1)) diff --git a/core/services/relay/evm/mercury/helpers_test.go b/core/services/relay/evm/mercury/helpers_test.go index f2923696bfc..9a0cfec7154 100644 --- a/core/services/relay/evm/mercury/helpers_test.go +++ b/core/services/relay/evm/mercury/helpers_test.go @@ -6,12 +6,12 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/stretchr/testify/require" "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" @@ -139,7 +139,7 @@ func buildSamplePayload(report []byte) []byte { type TestHarness struct { configPoller *ConfigPoller user *bind.TransactOpts - backend *backends.SimulatedBackend + backend *simulated.Backend verifierAddress common.Address verifierContract *verifier.Verifier logPoller logpoller.LogPoller @@ -150,13 +150,13 @@ func SetupTH(t *testing.T, feedID common.Hash) TestHarness { require.NoError(t, err) user, err := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337)) require.NoError(t, err) - b := backends.NewSimulatedBackend(core.GenesisAlloc{ + b := simulated.NewBackend(types.GenesisAlloc{ user.From: {Balance: big.NewInt(1000000000000000000)}}, - 5*ethconfig.Defaults.Miner.GasCeil) + simulated.WithBlockGasLimit(5*ethconfig.Defaults.Miner.GasCeil)) - proxyAddress, _, verifierProxy, err := verifier_proxy.DeployVerifierProxy(user, b, common.Address{}) + proxyAddress, _, verifierProxy, err := verifier_proxy.DeployVerifierProxy(user, b.Client(), common.Address{}) require.NoError(t, err, "failed to deploy test mercury verifier proxy contract") - verifierAddress, _, verifierContract, err := verifier.DeployVerifier(user, b, proxyAddress) + verifierAddress, _, verifierContract, err := verifier.DeployVerifier(user, b.Client(), proxyAddress) require.NoError(t, err, "failed to deploy test mercury verifier contract") _, err = verifierProxy.InitializeVerifier(user, verifierAddress) require.NoError(t, err) diff --git a/core/services/transmission/integration_test.go b/core/services/transmission/integration_test.go index c8c6137cad7..418d8e26b67 100644 --- a/core/services/transmission/integration_test.go +++ b/core/services/transmission/integration_test.go @@ -6,9 +6,8 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" @@ -42,7 +41,7 @@ type EntryPointUniverse struct { holder1 *bind.TransactOpts holder1Key ethkey.KeyV2 holder2 *bind.TransactOpts - backend *backends.SimulatedBackend + backend *simulated.Backend entryPointAddress common.Address entryPoint *entry_point.EntryPoint factoryAddress common.Address @@ -69,7 +68,7 @@ func deployTransmissionUniverse(t *testing.T) *EntryPointUniverse { holder1 = holder1Transactor holder2 = testutils.MustNewSimTransactor(t) ) - genesisData := core.GenesisAlloc{ + genesisData := types.GenesisAlloc{ holder1.From: {Balance: assets.Ether(1000).ToInt()}, holder2.From: {Balance: assets.Ether(1000).ToInt()}, } @@ -78,26 +77,26 @@ func deployTransmissionUniverse(t *testing.T) *EntryPointUniverse { backend.Commit() // Setup all contracts and addresses used by tests. - entryPointAddress, _, entryPoint, err := entry_point.DeployEntryPoint(holder1, backend) + entryPointAddress, _, entryPoint, err := entry_point.DeployEntryPoint(holder1, backend.Client()) require.NoError(t, err) - factoryAddress, _, _, _ := smart_contract_account_factory.DeploySmartContractAccountFactory(holder1, backend) + factoryAddress, _, _, _ := smart_contract_account_factory.DeploySmartContractAccountFactory(holder1, backend.Client()) require.NoError(t, err) - _, _, helper, err := smart_contract_account_helper.DeploySmartContractAccountHelper(holder1, backend) + _, _, helper, err := smart_contract_account_helper.DeploySmartContractAccountHelper(holder1, backend.Client()) require.NoError(t, err) - greeterAddress, _, greeter, err := greeter_wrapper.DeployGreeter(holder1, backend) + greeterAddress, _, greeter, err := greeter_wrapper.DeployGreeter(holder1, backend.Client()) require.NoError(t, err) - linkTokenAddress, _, linkToken, err := link_token_interface.DeployLinkToken(holder1, backend) + linkTokenAddress, _, linkToken, err := link_token_interface.DeployLinkToken(holder1, backend.Client()) require.NoError(t, err) linkEthFeedAddress, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract( holder1, - backend, + backend.Client(), 18, (*big.Int)(assets.GWei(5000000)), // .005 ETH ) require.NoError(t, err) - vrfCoordinatorAddress, _, vrfCoordinator, err := vrf_coordinator_mock.DeployVRFCoordinatorMock(holder1, backend, linkTokenAddress) + vrfCoordinatorAddress, _, vrfCoordinator, err := vrf_coordinator_mock.DeployVRFCoordinatorMock(holder1, backend.Client(), linkTokenAddress) require.NoError(t, err) - vrfConsumerAddress, _, _, err := solidity_vrf_consumer_interface_v08.DeployVRFConsumer(holder1, backend, vrfCoordinatorAddress, linkTokenAddress) + vrfConsumerAddress, _, _, err := solidity_vrf_consumer_interface_v08.DeployVRFConsumer(holder1, backend.Client(), vrfCoordinatorAddress, linkTokenAddress) require.NoError(t, err) backend.Commit() @@ -194,7 +193,7 @@ func Test4337Basic(t *testing.T) { tx, err := universe.entryPoint.DepositTo(holder1, toDeployAddress) require.NoError(t, err) backend.Commit() - _, err = bind.WaitMined(testutils.Context(t), backend, tx) + _, err = bind.WaitMined(testutils.Context(t), backend.Client(), tx) require.NoError(t, err) holder1.Value = assets.Ether(0).ToInt() balance, err := universe.entryPoint.BalanceOf(nil, toDeployAddress) @@ -205,7 +204,7 @@ func Test4337Basic(t *testing.T) { tx, err = universe.entryPoint.HandleOps(holder2, []entry_point.UserOperation{userOp}, holder1.From) require.NoError(t, err) backend.Commit() - _, err = bind.WaitMined(testutils.Context(t), backend, tx) + _, err = bind.WaitMined(testutils.Context(t), backend.Client(), tx) require.NoError(t, err) // Ensure "bye" was successfully set as the greeting. @@ -214,7 +213,7 @@ func Test4337Basic(t *testing.T) { require.Equal(t, "bye", greetingResult) // Assert smart contract account is created and nonce incremented. - sca, err := sca_wrapper.NewSCA(toDeployAddress, backend) + sca, err := sca_wrapper.NewSCA(toDeployAddress, backend.Client()) require.NoError(t, err) onChainNonce, err := sca.SNonce(nil) require.NoError(t, err) @@ -264,16 +263,16 @@ func Test4337WithLinkTokenPaymaster(t *testing.T) { t.Log("Full user operation calldata:", common.Bytes2Hex(fullEncoding)) // Deposit to LINK paymaster. - linkTokenAddress, _, linkToken, err := link_token_interface.DeployLinkToken(holder1, backend) + linkTokenAddress, _, linkToken, err := link_token_interface.DeployLinkToken(holder1, backend.Client()) require.NoError(t, err) linkEthFeedAddress, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract( holder1, - backend, + backend.Client(), 18, (*big.Int)(assets.GWei(5000000)), // .005 ETH ) require.NoError(t, err) - paymasterAddress, _, _, err := paymaster_wrapper.DeployPaymaster(holder1, backend, linkTokenAddress, linkEthFeedAddress, universe.entryPointAddress) + paymasterAddress, _, _, err := paymaster_wrapper.DeployPaymaster(holder1, backend.Client(), linkTokenAddress, linkEthFeedAddress, universe.entryPointAddress) require.NoError(t, err) backend.Commit() tx, err := linkToken.TransferAndCall( @@ -284,7 +283,7 @@ func Test4337WithLinkTokenPaymaster(t *testing.T) { ) require.NoError(t, err) backend.Commit() - _, err = bind.WaitMined(testutils.Context(t), backend, tx) + _, err = bind.WaitMined(testutils.Context(t), backend.Client(), tx) require.NoError(t, err) // Construct and execute user operation. @@ -318,7 +317,7 @@ func Test4337WithLinkTokenPaymaster(t *testing.T) { tx, err = universe.entryPoint.DepositTo(holder1, paymasterAddress) require.NoError(t, err) backend.Commit() - _, err = bind.WaitMined(testutils.Context(t), backend, tx) + _, err = bind.WaitMined(testutils.Context(t), backend.Client(), tx) require.NoError(t, err) holder1.Value = assets.Ether(0).ToInt() balance, err := universe.entryPoint.BalanceOf(nil, paymasterAddress) @@ -329,7 +328,7 @@ func Test4337WithLinkTokenPaymaster(t *testing.T) { tx, err = universe.entryPoint.HandleOps(holder2, []entry_point.UserOperation{userOp}, holder1.From) require.NoError(t, err) backend.Commit() - _, err = bind.WaitMined(testutils.Context(t), backend, tx) + _, err = bind.WaitMined(testutils.Context(t), backend.Client(), tx) require.NoError(t, err) // Ensure "bye" was successfully set as the greeting. @@ -338,7 +337,7 @@ func Test4337WithLinkTokenPaymaster(t *testing.T) { require.Equal(t, "bye", greetingResult) // Assert smart contract account is created and nonce incremented. - sca, err := sca_wrapper.NewSCA(toDeployAddress, backend) + sca, err := sca_wrapper.NewSCA(toDeployAddress, backend.Client()) require.NoError(t, err) onChainNonce, err := sca.SNonce(nil) require.NoError(t, err) @@ -386,7 +385,7 @@ func Test4337WithLinkTokenVRFRequestAndPaymaster(t *testing.T) { t.Log("Full user operation calldata:", common.Bytes2Hex(fullEncoding)) // Deposit to LINK paymaster. - paymasterAddress, _, _, err := paymaster_wrapper.DeployPaymaster(holder1, backend, universe.linkTokenAddress, universe.linkEthFeedAddress, universe.entryPointAddress) + paymasterAddress, _, _, err := paymaster_wrapper.DeployPaymaster(holder1, backend.Client(), universe.linkTokenAddress, universe.linkEthFeedAddress, universe.entryPointAddress) require.NoError(t, err) backend.Commit() tx, err := universe.linkToken.TransferAndCall( @@ -397,7 +396,7 @@ func Test4337WithLinkTokenVRFRequestAndPaymaster(t *testing.T) { ) require.NoError(t, err) backend.Commit() - _, err = bind.WaitMined(testutils.Context(t), backend, tx) + _, err = bind.WaitMined(testutils.Context(t), backend.Client(), tx) require.NoError(t, err) // Generate encoded paymaster data to fund the VRF consumer. @@ -435,7 +434,7 @@ func Test4337WithLinkTokenVRFRequestAndPaymaster(t *testing.T) { tx, err = universe.entryPoint.DepositTo(holder1, paymasterAddress) require.NoError(t, err) backend.Commit() - _, err = bind.WaitMined(testutils.Context(t), backend, tx) + _, err = bind.WaitMined(testutils.Context(t), backend.Client(), tx) require.NoError(t, err) holder1.Value = assets.Ether(0).ToInt() balance, err := universe.entryPoint.BalanceOf(nil, paymasterAddress) @@ -444,13 +443,13 @@ func Test4337WithLinkTokenVRFRequestAndPaymaster(t *testing.T) { // Run handleOps from holder2's account, to demonstrate that any account can execute this signed user operation. // Manually execute transaction to test ABI packing. - gasPrice, err := backend.SuggestGasPrice(testutils.Context(t)) + gasPrice, err := backend.Client().SuggestGasPrice(testutils.Context(t)) require.NoError(t, err) - accountNonce, err := backend.PendingNonceAt(testutils.Context(t), holder2.From) + accountNonce, err := backend.Client().PendingNonceAt(testutils.Context(t), holder2.From) require.NoError(t, err) payload, err := entrypointABI.Pack("handleOps", []entry_point.UserOperation{userOp}, holder1.From) require.NoError(t, err) - gas, err := backend.EstimateGas(testutils.Context(t), ethereum.CallMsg{ + gas, err := backend.Client().EstimateGas(testutils.Context(t), ethereum.CallMsg{ From: holder2.From, To: &universe.entryPointAddress, Gas: 0, @@ -468,15 +467,15 @@ func Test4337WithLinkTokenVRFRequestAndPaymaster(t *testing.T) { require.NoError(t, err) signedtx, err := holder2.Signer(holder2.From, unsigned) require.NoError(t, err) - err = backend.SendTransaction(testutils.Context(t), signedtx) + err = backend.Client().SendTransaction(testutils.Context(t), signedtx) require.NoError(t, err) - backend.Commit() - receipt, err := bind.WaitMined(testutils.Context(t), backend, signedtx) + backend.Client() + receipt, err := bind.WaitMined(testutils.Context(t), backend.Client(), signedtx) require.NoError(t, err) t.Log("Receipt:", receipt.Status) // Assert the VRF request was correctly made. - logs, err := backend.FilterLogs(testutils.Context(t), ethereum.FilterQuery{ + logs, err := backend.Client().FilterLogs(testutils.Context(t), ethereum.FilterQuery{ Addresses: []common.Address{universe.vrfCoordinatorAddress}, }) require.NoError(t, err) @@ -488,7 +487,7 @@ func Test4337WithLinkTokenVRFRequestAndPaymaster(t *testing.T) { require.Equal(t, universe.vrfConsumerAddress, randomnessRequestLog.Sender) // Assert smart contract account is created and nonce incremented. - sca, err := sca_wrapper.NewSCA(toDeployAddress, backend) + sca, err := sca_wrapper.NewSCA(toDeployAddress, backend.Client()) require.NoError(t, err) onChainNonce, err := sca.SNonce(nil) require.NoError(t, err) diff --git a/core/services/vrf/proof/proof_response_test.go b/core/services/vrf/proof/proof_response_test.go index 994ac80b5e2..32d4ad7e300 100644 --- a/core/services/vrf/proof/proof_response_test.go +++ b/core/services/vrf/proof/proof_response_test.go @@ -4,13 +4,14 @@ import ( "math/big" "testing" + gethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/solidity_vrf_verifier_wrapper" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" proof2 "github.com/smartcontractkit/chainlink/v2/core/services/vrf/proof" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/ethconfig" "github.com/pkg/errors" @@ -44,10 +45,10 @@ func TestMarshaledProof(t *testing.T) { ethereumKey, _ := crypto.GenerateKey() auth, err := bind.NewKeyedTransactorWithChainID(ethereumKey, big.NewInt(1337)) require.NoError(t, err) - genesisData := core.GenesisAlloc{auth.From: {Balance: assets.Ether(100).ToInt()}} + genesisData := gethtypes.GenesisAlloc{auth.From: {Balance: assets.Ether(100).ToInt()}} gasLimit := uint32(ethconfig.Defaults.Miner.GasCeil) backend := cltest.NewSimulatedBackend(t, genesisData, gasLimit) - _, _, verifier, err := solidity_vrf_verifier_wrapper.DeployVRFTestHelper(auth, backend) + _, _, verifier, err := solidity_vrf_verifier_wrapper.DeployVRFTestHelper(auth, backend.Client()) if err != nil { panic(errors.Wrapf(err, "while initializing EVM contract wrapper")) } diff --git a/core/services/vrf/solidity_cross_tests/vrf_hash_to_curve_cost_test.go b/core/services/vrf/solidity_cross_tests/vrf_hash_to_curve_cost_test.go index 29d1db437d1..c2e703204c0 100644 --- a/core/services/vrf/solidity_cross_tests/vrf_hash_to_curve_cost_test.go +++ b/core/services/vrf/solidity_cross_tests/vrf_hash_to_curve_cost_test.go @@ -6,6 +6,9 @@ import ( "strings" "testing" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/solidity_vrf_verifier_wrapper" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" @@ -19,9 +22,7 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -31,7 +32,7 @@ type contract struct { contract *bind.BoundContract address common.Address abi *abi.ABI - backend *backends.SimulatedBackend + backend *simulated.Backend } // deployVRFContract returns a deployed VRF contract, with some extra attributes @@ -43,14 +44,14 @@ func deployVRFContract(t *testing.T) (contract, common.Address) { D: big.NewInt(1), } auth, _ := bind.NewKeyedTransactorWithChainID(&key, testutils.SimulatedChainID) - genesisData := core.GenesisAlloc{auth.From: {Balance: assets.Ether(100).ToInt()}} + genesisData := types.GenesisAlloc{auth.From: {Balance: assets.Ether(100).ToInt()}} gasLimit := uint32(ethconfig.Defaults.Miner.GasCeil) backend := cltest.NewSimulatedBackend(t, genesisData, gasLimit) parsed, err := abi.JSON(strings.NewReader( solidity_vrf_verifier_wrapper.VRFTestHelperABI)) require.NoError(t, err, "could not parse VRF ABI") address, _, vRFContract, err := bind.DeployContract(auth, parsed, - common.FromHex(solidity_vrf_verifier_wrapper.VRFTestHelperBin), backend) + common.FromHex(solidity_vrf_verifier_wrapper.VRFTestHelperBin), backend.Client()) require.NoError(t, err, "failed to deploy VRF contract to simulated blockchain") backend.Commit() return contract{vRFContract, address, &parsed, backend}, crypto.PubkeyToAddress( @@ -60,14 +61,14 @@ func deployVRFContract(t *testing.T) (contract, common.Address) { // estimateGas returns the estimated gas cost of running the given method on the // contract at address to, on the given backend, with the given args, and given // that the transaction is sent from the from address. -func estimateGas(t *testing.T, backend *backends.SimulatedBackend, +func estimateGas(t *testing.T, backend *simulated.Backend, from, to common.Address, abi *abi.ABI, method string, args ...interface{}, ) uint64 { rawData, err := abi.Pack(method, args...) require.NoError(t, err, "failed to construct raw %s transaction with args %s", method, args) callMsg := ethereum.CallMsg{From: from, To: &to, Data: rawData} - estimate, err := backend.EstimateGas(testutils.Context(t), callMsg) + estimate, err := backend.Client().EstimateGas(testutils.Context(t), callMsg) require.NoError(t, err, "failed to estimate gas from %s call with args %s", method, args) return estimate diff --git a/core/services/vrf/solidity_cross_tests/vrf_solidity_crosscheck_test.go b/core/services/vrf/solidity_cross_tests/vrf_solidity_crosscheck_test.go index 2476ee04ce2..c7c61cc3f39 100644 --- a/core/services/vrf/solidity_cross_tests/vrf_solidity_crosscheck_test.go +++ b/core/services/vrf/solidity_cross_tests/vrf_solidity_crosscheck_test.go @@ -7,19 +7,21 @@ import ( "strings" "testing" + gethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/solidity_vrf_verifier_wrapper" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" proof2 "github.com/smartcontractkit/chainlink/v2/core/services/vrf/proof" "github.com/ethereum/go-ethereum/eth/ethconfig" - "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.dedis.ch/kyber/v3" "github.com/smartcontractkit/chainlink-common/pkg/utils" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/vrfkey" @@ -43,10 +45,10 @@ import ( // pure.) Revert to that, and see if it helps. func deployVRFTestHelper(t *testing.T) *solidity_vrf_verifier_wrapper.VRFTestHelper { auth := testutils.MustNewSimTransactor(t) - genesisData := core.GenesisAlloc{auth.From: {Balance: assets.Ether(100).ToInt()}} + genesisData := gethtypes.GenesisAlloc{auth.From: {Balance: assets.Ether(100).ToInt()}} gasLimit := uint32(ethconfig.Defaults.Miner.GasCeil) backend := cltest.NewSimulatedBackend(t, genesisData, gasLimit) - _, _, verifier, err := solidity_vrf_verifier_wrapper.DeployVRFTestHelper(auth, backend) + _, _, verifier, err := solidity_vrf_verifier_wrapper.DeployVRFTestHelper(auth, backend.Client()) require.NoError(t, err, "failed to deploy VRF contract to simulated blockchain") backend.Commit() return verifier diff --git a/core/services/vrf/solidity_cross_tests/vrf_v08_solidity_crosscheck_test.go b/core/services/vrf/solidity_cross_tests/vrf_v08_solidity_crosscheck_test.go index 0552f93fea1..9842686b454 100644 --- a/core/services/vrf/solidity_cross_tests/vrf_v08_solidity_crosscheck_test.go +++ b/core/services/vrf/solidity_cross_tests/vrf_v08_solidity_crosscheck_test.go @@ -5,17 +5,19 @@ import ( mrand "math/rand" "testing" + gethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/solidity_vrf_v08_verifier_wrapper" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" proof2 "github.com/smartcontractkit/chainlink/v2/core/services/vrf/proof" "github.com/ethereum/go-ethereum/eth/ethconfig" - "github.com/ethereum/go-ethereum/core" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/utils" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/vrfkey" @@ -27,10 +29,10 @@ import ( // except we are testing against the v0.8 implementation of VRF.sol. func deployVRFV08TestHelper(t *testing.T) *solidity_vrf_v08_verifier_wrapper.VRFV08TestHelper { auth := testutils.MustNewSimTransactor(t) - genesisData := core.GenesisAlloc{auth.From: {Balance: assets.Ether(100).ToInt()}} + genesisData := gethtypes.GenesisAlloc{auth.From: {Balance: assets.Ether(100).ToInt()}} gasLimit := uint32(ethconfig.Defaults.Miner.GasCeil) backend := cltest.NewSimulatedBackend(t, genesisData, gasLimit) - _, _, verifier, err := solidity_vrf_v08_verifier_wrapper.DeployVRFV08TestHelper(auth, backend) + _, _, verifier, err := solidity_vrf_v08_verifier_wrapper.DeployVRFV08TestHelper(auth, backend.Client()) require.NoError(t, err, "failed to deploy VRF contract to simulated blockchain") backend.Commit() return verifier diff --git a/core/services/vrf/v1/integration_test.go b/core/services/vrf/v1/integration_test.go index f4352cb38c3..7e771df5523 100644 --- a/core/services/vrf/v1/integration_test.go +++ b/core/services/vrf/v1/integration_test.go @@ -16,6 +16,7 @@ import ( "gopkg.in/guregu/null.v4" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/txmgr" ubig "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big" "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/solidity_vrf_coordinator_interface" @@ -116,11 +117,11 @@ func TestIntegration_VRF_JPV2(t *testing.T) { }, testutils.WaitTimeout(t), 500*time.Millisecond).Should(gomega.BeTrue()) // Check that each sending address sent one transaction - n1, err := cu.Backend.PendingNonceAt(ctx, key1.Address) + n1, err := cu.Backend.Client().PendingNonceAt(ctx, key1.Address) require.NoError(t, err) require.EqualValues(t, 1, n1) - n2, err := cu.Backend.PendingNonceAt(ctx, key2.Address) + n2, err := cu.Backend.Client().PendingNonceAt(ctx, key2.Address) require.NoError(t, err) require.EqualValues(t, 1, n2) }) @@ -163,7 +164,7 @@ func TestIntegration_VRF_WithBHS(t *testing.T) { require.NoError(t, err) cu.Backend.Commit() - h, err := cu.Backend.HeaderByNumber(testutils.Context(t), nil) + h, err := cu.Backend.Client().HeaderByNumber(testutils.Context(t), nil) require.NoError(t, err) requestBlock := h.Number diff --git a/core/services/vrf/v2/bhs_feeder_test.go b/core/services/vrf/v2/bhs_feeder_test.go index b39fd0dec7f..f9eb4266080 100644 --- a/core/services/vrf/v2/bhs_feeder_test.go +++ b/core/services/vrf/v2/bhs_feeder_test.go @@ -84,7 +84,7 @@ func TestStartHeartbeats(t *testing.T) { t.Logf("Sleeping %.2f seconds before checking blockhash in BHS added by BHS_Heartbeats_Service\n", diff.Seconds()) time.Sleep(diff) // storeEarliest in BHS contract stores blocktip - 256 in the Blockhash Store (BHS) - tipHeader, err := uni.backend.HeaderByNumber(testutils.Context(t), nil) + tipHeader, err := uni.backend.Client().HeaderByNumber(testutils.Context(t), nil) require.NoError(t, err) // the storeEarliest transaction will end up in a new block, hence the + 1 below. blockNumberStored := tipHeader.Number.Uint64() - 256 + 1 diff --git a/core/services/vrf/v2/integration_helpers_test.go b/core/services/vrf/v2/integration_helpers_test.go index d61779c5714..9cbd1eb61f4 100644 --- a/core/services/vrf/v2/integration_helpers_test.go +++ b/core/services/vrf/v2/integration_helpers_test.go @@ -7,9 +7,9 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/google/uuid" "github.com/onsi/gomega" "github.com/shopspring/decimal" @@ -154,11 +154,11 @@ func testSingleConsumerHappyPath( assertNumRandomWords(t, consumerContract, numWords) // Assert that both send addresses were used to fulfill the requests - n, err := uni.backend.PendingNonceAt(ctx, key1.Address) + n, err := uni.backend.Client().PendingNonceAt(ctx, key1.Address) require.NoError(t, err) require.EqualValues(t, 1, n) - n, err = uni.backend.PendingNonceAt(ctx, key2.Address) + n, err = uni.backend.Client().PendingNonceAt(ctx, key2.Address) require.NoError(t, err) require.EqualValues(t, 1, n) @@ -849,7 +849,7 @@ func createSubscriptionAndGetSubscriptionCreatedEvent( t *testing.T, subOwner *bind.TransactOpts, coordinator v22.CoordinatorV2_X, - backend *backends.SimulatedBackend, + backend *simulated.Backend, ) v22.SubscriptionCreated { _, err := coordinator.CreateSubscription(subOwner) require.NoError(t, err) @@ -928,7 +928,7 @@ func testSingleConsumerForcedFulfillment( eoaConsumerAddr, _, eoaConsumer, err := vrf_external_sub_owner_example.DeployVRFExternalSubOwnerExample( uni.neil, - uni.backend, + uni.backend.Client(), uni.oldRootContractAddress, uni.linkContractAddress, ) @@ -1431,7 +1431,7 @@ func testSingleConsumerMultipleGasLanes( assertNumRandomWords(t, consumerContract, numWords) } -func topUpSubscription(t *testing.T, consumer *bind.TransactOpts, consumerContract vrftesthelpers.VRFConsumerContract, backend *backends.SimulatedBackend, fundingAmount *big.Int, nativePayment bool) { +func topUpSubscription(t *testing.T, consumer *bind.TransactOpts, consumerContract vrftesthelpers.VRFConsumerContract, backend *simulated.Backend, fundingAmount *big.Int, nativePayment bool) { if nativePayment { _, err := consumerContract.TopUpSubscriptionNative(consumer, fundingAmount) require.NoError(t, err) @@ -1614,11 +1614,11 @@ func testConsumerProxyHappyPath( assertNumRandomWords(t, consumerContract, numWords) // Assert that both send addresses were used to fulfill the requests - n, err := uni.backend.PendingNonceAt(ctx, key1.Address) + n, err := uni.backend.Client().PendingNonceAt(ctx, key1.Address) require.NoError(t, err) require.EqualValues(t, 1, n) - n, err = uni.backend.PendingNonceAt(ctx, key2.Address) + n, err = uni.backend.Client().PendingNonceAt(ctx, key2.Address) require.NoError(t, err) require.EqualValues(t, 1, n) @@ -1631,7 +1631,7 @@ func testConsumerProxyCoordinatorZeroAddress( ) { // Deploy another upgradeable consumer, proxy, and proxy admin // to test vrfCoordinator != 0x0 condition. - upgradeableConsumerAddress, _, _, err := vrf_consumer_v2_upgradeable_example.DeployVRFConsumerV2UpgradeableExample(uni.neil, uni.backend) + upgradeableConsumerAddress, _, _, err := vrf_consumer_v2_upgradeable_example.DeployVRFConsumerV2UpgradeableExample(uni.neil, uni.backend.Client()) require.NoError(t, err, "failed to deploy upgradeable consumer to simulated ethereum blockchain") uni.backend.Commit() @@ -1643,7 +1643,7 @@ func testConsumerProxyCoordinatorZeroAddress( uni.linkContractAddress) require.NoError(t, err) _, _, _, err = vrfv2_transparent_upgradeable_proxy.DeployVRFV2TransparentUpgradeableProxy( - uni.neil, uni.backend, upgradeableConsumerAddress, uni.proxyAdminAddress, initializeCalldata) + uni.neil, uni.backend.Client(), upgradeableConsumerAddress, uni.proxyAdminAddress, initializeCalldata) require.Error(t, err) } diff --git a/core/services/vrf/v2/integration_v2_plus_test.go b/core/services/vrf/v2/integration_v2_plus_test.go index 1c05444948f..7d9486c52a3 100644 --- a/core/services/vrf/v2/integration_v2_plus_test.go +++ b/core/services/vrf/v2/integration_v2_plus_test.go @@ -10,13 +10,14 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core" + gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" "github.com/onsi/gomega" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/config/toml" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" @@ -84,7 +85,7 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer vrfConsumers = append(vrfConsumers, testutils.MustNewSimTransactor(t)) } - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ sergey.From: {Balance: assets.Ether(1000).ToInt()}, neil.From: {Balance: assets.Ether(1000).ToInt()}, ned.From: {Balance: assets.Ether(1000).ToInt()}, @@ -94,7 +95,7 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer submanager.From: {Balance: assets.Ether(1000).ToInt()}, } for _, consumer := range vrfConsumers { - genesisData[consumer.From] = core.GenesisAccount{ + genesisData[consumer.From] = gethtypes.Account{ Balance: assets.Ether(1000).ToInt(), } } @@ -107,33 +108,33 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer vrf_coordinator_v2plus_interface.IVRFCoordinatorV2PlusInternalABI)) require.NoError(t, err) backend := cltest.NewSimulatedBackend(t, genesisData, gasLimit) - h, err := backend.HeaderByNumber(testutils.Context(t), nil) + h, err := backend.Client().HeaderByNumber(testutils.Context(t), nil) require.NoError(t, err) blockTime := time.UnixMilli(int64(h.Time)) err = backend.AdjustTime(time.Since(blockTime) - 24*time.Hour) require.NoError(t, err) - backend.Commit() + // Deploy link linkAddress, _, linkContract, err := link_token_interface.DeployLinkToken( - sergey, backend) + sergey, backend.Client()) require.NoError(t, err, "failed to deploy link contract to simulated ethereum blockchain") // Deploy feed linkEthFeed, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract( - evil, backend, 18, vrftesthelpers.WeiPerUnitLink.BigInt()) // 0.01 eth per link + evil, backend.Client(), 18, vrftesthelpers.WeiPerUnitLink.BigInt()) // 0.01 eth per link require.NoError(t, err) // Deploy blockhash store - bhsAddress, _, bhsContract, err := blockhash_store.DeployBlockhashStore(neil, backend) + bhsAddress, _, bhsContract, err := blockhash_store.DeployBlockhashStore(neil, backend.Client()) require.NoError(t, err, "failed to deploy BlockhashStore contract to simulated ethereum blockchain") // Deploy trusted BHS - trustedBHSAddress, _, trustedBhsContract, err := trusted_blockhash_store.DeployTrustedBlockhashStore(neil, backend, []common.Address{}) + trustedBHSAddress, _, trustedBhsContract, err := trusted_blockhash_store.DeployTrustedBlockhashStore(neil, backend.Client(), []common.Address{}) require.NoError(t, err, "failed to deploy trusted BlockhashStore contract to simulated ethereum blockchain") // Deploy batch blockhash store - batchBHSAddress, _, batchBHSContract, err := batch_blockhash_store.DeployBatchBlockhashStore(neil, backend, bhsAddress) + batchBHSAddress, _, batchBHSContract, err := batch_blockhash_store.DeployBatchBlockhashStore(neil, backend.Client(), bhsAddress) require.NoError(t, err, "failed to deploy BatchBlockhashStore contract to simulated ethereum blockchain") // Deploy VRF V2plus coordinator @@ -143,7 +144,7 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer } coordinatorAddress, _, coordinatorContract, err := vrf_coordinator_v2_5.DeployVRFCoordinatorV25( - neil, backend, bhsAddr) + neil, backend.Client(), bhsAddr) require.NoError(t, err, "failed to deploy VRFCoordinatorV2 contract to simulated ethereum blockchain") backend.Commit() @@ -152,7 +153,7 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer backend.Commit() migrationTestCoordinatorAddress, _, migrationTestCoordinator, err := vrf_coordinator_v2_plus_v2_example.DeployVRFCoordinatorV2PlusV2Example( - neil, backend, linkAddress, coordinatorAddress) + neil, backend.Client(), linkAddress, coordinatorAddress) require.NoError(t, err) backend.Commit() @@ -163,7 +164,7 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer // Deploy batch VRF V2 coordinator batchCoordinatorAddress, _, batchCoordinatorContract, err := batch_vrf_coordinator_v2plus.DeployBatchVRFCoordinatorV2Plus( - neil, backend, coordinatorAddress, + neil, backend.Client(), coordinatorAddress, ) require.NoError(t, err, "failed to deploy BatchVRFCoordinatorV2 contract to simulated ethereum blockchain") backend.Commit() @@ -177,7 +178,7 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer // Deploy a VRF consumer. It has a starting balance of 500 LINK. consumerContractAddress, _, consumerContract, err2 := vrfv2plus_consumer_example.DeployVRFV2PlusConsumerExample( - author, backend, coordinatorAddress, linkAddress) + author, backend.Client(), coordinatorAddress, linkAddress) require.NoError(t, err2, "failed to deploy VRFConsumer contract to simulated ethereum blockchain") _, err2 = linkContract.Transfer(sergey, consumerContractAddress, assets.Ether(500).ToInt()) // Actually, LINK require.NoError(t, err2, "failed to send LINK to VRFConsumer contract on simulated ethereum blockchain") @@ -191,18 +192,18 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer // Deploy malicious consumer with 1 link maliciousConsumerContractAddress, _, maliciousConsumerContract, err := vrf_malicious_consumer_v2_plus.DeployVRFMaliciousConsumerV2Plus( - evil, backend, coordinatorAddress, linkAddress) + evil, backend.Client(), coordinatorAddress, linkAddress) require.NoError(t, err, "failed to deploy VRFMaliciousConsumer contract to simulated ethereum blockchain") _, err = linkContract.Transfer(sergey, maliciousConsumerContractAddress, assets.Ether(1).ToInt()) // Actually, LINK require.NoError(t, err, "failed to send LINK to VRFMaliciousConsumer contract on simulated ethereum blockchain") backend.Commit() // Deploy upgradeable consumer, proxy, and proxy admin - upgradeableConsumerAddress, _, _, err := vrf_consumer_v2_plus_upgradeable_example.DeployVRFConsumerV2PlusUpgradeableExample(neil, backend) + upgradeableConsumerAddress, _, _, err := vrf_consumer_v2_plus_upgradeable_example.DeployVRFConsumerV2PlusUpgradeableExample(neil, backend.Client()) require.NoError(t, err, "failed to deploy upgradeable consumer to simulated ethereum blockchain") backend.Commit() - proxyAdminAddress, _, proxyAdmin, err := vrfv2_proxy_admin.DeployVRFV2ProxyAdmin(neil, backend) + proxyAdminAddress, _, proxyAdmin, err := vrfv2_proxy_admin.DeployVRFV2ProxyAdmin(neil, backend.Client()) require.NoError(t, err) backend.Commit() @@ -215,7 +216,7 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer t.Log("initialize calldata:", hexified, "coordinator:", coordinatorAddress.String(), "link:", linkAddress) require.NoError(t, err) proxyAddress, _, _, err := vrfv2_transparent_upgradeable_proxy.DeployVRFV2TransparentUpgradeableProxy( - neil, backend, upgradeableConsumerAddress, proxyAdminAddress, initializeCalldata) + neil, backend.Client(), upgradeableConsumerAddress, proxyAdminAddress, initializeCalldata) require.NoError(t, err) _, err = linkContract.Transfer(sergey, proxyAddress, assets.Ether(500).ToInt()) // Actually, LINK @@ -228,7 +229,7 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer require.Equal(t, upgradeableConsumerAddress, implAddress) proxiedConsumer, err := vrf_consumer_v2_plus_upgradeable_example.NewVRFConsumerV2PlusUpgradeableExample( - proxyAddress, backend) + proxyAddress, backend.Client()) require.NoError(t, err) cAddress, err := proxiedConsumer.COORDINATOR(nil) @@ -243,7 +244,7 @@ func newVRFCoordinatorV2PlusUniverse(t *testing.T, key ethkey.KeyV2, numConsumer // Deploy always reverting consumer revertingConsumerContractAddress, _, revertingConsumerContract, err := vrfv2plus_reverting_example.DeployVRFV2PlusRevertingExample( - reverter, backend, coordinatorAddress, linkAddress, + reverter, backend.Client(), coordinatorAddress, linkAddress, ) require.NoError(t, err, "failed to deploy VRFRevertingExample contract to simulated eth blockchain") _, err = linkContract.Transfer(sergey, revertingConsumerContractAddress, assets.Ether(500).ToInt()) // Actually, LINK @@ -694,24 +695,24 @@ func TestVRFV2PlusIntegration_ConsumerProxy_CoordinatorZeroAddress(t *testing.T) func TestVRFV2PlusIntegration_ExternalOwnerConsumerExample(t *testing.T) { owner := testutils.MustNewSimTransactor(t) random := testutils.MustNewSimTransactor(t) - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ owner.From: {Balance: assets.Ether(10).ToInt()}, random.From: {Balance: assets.Ether(10).ToInt()}, } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) linkAddress, _, linkContract, err := link_token_interface.DeployLinkToken( - owner, backend) + owner, backend.Client()) require.NoError(t, err) backend.Commit() // Deploy feed linkEthFeed, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract( - owner, backend, 18, vrftesthelpers.WeiPerUnitLink.BigInt()) // 0.01 eth per link + owner, backend.Client(), 18, vrftesthelpers.WeiPerUnitLink.BigInt()) // 0.01 eth per link require.NoError(t, err) backend.Commit() coordinatorAddress, _, coordinator, err := vrf_coordinator_v2_5.DeployVRFCoordinatorV25( - owner, backend, common.Address{}) //bhs not needed for this test + owner, backend.Client(), common.Address{}) //bhs not needed for this test require.NoError(t, err) _, err = coordinator.SetConfig(owner, uint16(1), // minimumRequestConfirmations @@ -729,7 +730,7 @@ func TestVRFV2PlusIntegration_ExternalOwnerConsumerExample(t *testing.T) { _, err = coordinator.SetLINKAndLINKNativeFeed(owner, linkAddress, linkEthFeed) require.NoError(t, err) backend.Commit() - consumerAddress, _, consumer, err := vrf_v2plus_sub_owner.DeployVRFV2PlusExternalSubOwnerExample(owner, backend, coordinatorAddress, linkAddress) + consumerAddress, _, consumer, err := vrf_v2plus_sub_owner.DeployVRFV2PlusExternalSubOwnerExample(owner, backend.Client(), coordinatorAddress, linkAddress) require.NoError(t, err) backend.Commit() _, err = linkContract.Transfer(owner, consumerAddress, assets.Ether(2).ToInt()) @@ -772,29 +773,29 @@ func TestVRFV2PlusIntegration_ExternalOwnerConsumerExample(t *testing.T) { func TestVRFV2PlusIntegration_SimpleConsumerExample(t *testing.T) { owner := testutils.MustNewSimTransactor(t) random := testutils.MustNewSimTransactor(t) - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ owner.From: {Balance: assets.Ether(10).ToInt()}, } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) linkAddress, _, linkContract, err := link_token_interface.DeployLinkToken( - owner, backend) + owner, backend.Client()) require.NoError(t, err) backend.Commit() // Deploy feed linkEthFeed, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract( - owner, backend, 18, vrftesthelpers.WeiPerUnitLink.BigInt()) // 0.01 eth per link + owner, backend.Client(), 18, vrftesthelpers.WeiPerUnitLink.BigInt()) // 0.01 eth per link require.NoError(t, err) backend.Commit() coordinatorAddress, _, coordinator, err := vrf_coordinator_v2_5.DeployVRFCoordinatorV25( - owner, backend, common.Address{}) // bhs not needed for this test + owner, backend.Client(), common.Address{}) // bhs not needed for this test require.NoError(t, err) backend.Commit() _, err = coordinator.SetLINKAndLINKNativeFeed(owner, linkAddress, linkEthFeed) require.NoError(t, err) backend.Commit() - consumerAddress, _, consumer, err := vrf_v2plus_single_consumer.DeployVRFV2PlusSingleConsumerExample(owner, backend, coordinatorAddress, linkAddress, 1, 1, 1, [32]byte{}, false) + consumerAddress, _, consumer, err := vrf_v2plus_single_consumer.DeployVRFV2PlusSingleConsumerExample(owner, backend.Client(), coordinatorAddress, linkAddress, 1, 1, 1, [32]byte{}, false) require.NoError(t, err) backend.Commit() _, err = linkContract.Transfer(owner, consumerAddress, assets.Ether(2).ToInt()) @@ -886,7 +887,7 @@ func TestVRFV2PlusIntegration_RequestCost(t *testing.T) { tx, err := consumerContract.CreateSubscriptionAndFund(consumerOwner, assets.Ether(5).ToInt()) require.NoError(tt, err) uni.backend.Commit() - r, err := uni.backend.TransactionReceipt(testutils.Context(t), tx.Hash()) + r, err := uni.backend.Client().TransactionReceipt(testutils.Context(t), tx.Hash()) require.NoError(tt, err) t.Log("gas used by proxied CreateSubscriptionAndFund:", r.GasUsed) @@ -1220,7 +1221,7 @@ func TestVRFV2PlusIntegration_Migration(t *testing.T) { require.NoError(t, err) linkContractBalance, err := uni.linkContract.BalanceOf(nil, uni.migrationTestCoordinatorAddress) require.NoError(t, err) - balance, err := uni.backend.BalanceAt(ctx, uni.migrationTestCoordinatorAddress, nil) + balance, err := uni.backend.Client().BalanceAt(ctx, uni.migrationTestCoordinatorAddress, nil) require.NoError(t, err) require.Equal(t, subV1.Balance(), totalLinkBalance) @@ -1321,7 +1322,7 @@ func TestVRFV2PlusIntegration_CancelSubscription(t *testing.T) { linkBalanceBeforeCancel, err := uni.linkContract.BalanceOf(nil, uni.neil.From) require.NoError(t, err) - nativeBalanceBeforeCancel, err := uni.backend.BalanceAt(testutils.Context(t), uni.neil.From, nil) + nativeBalanceBeforeCancel, err := uni.backend.Client().BalanceAt(testutils.Context(t), uni.neil.From, nil) require.NoError(t, err) // non-owner cannot cancel subscription diff --git a/core/services/vrf/v2/integration_v2_reverted_txns_test.go b/core/services/vrf/v2/integration_v2_reverted_txns_test.go index 4dfaf619b62..8357d802075 100644 --- a/core/services/vrf/v2/integration_v2_reverted_txns_test.go +++ b/core/services/vrf/v2/integration_v2_reverted_txns_test.go @@ -279,7 +279,7 @@ func fulfillVRFReq(t *testing.T, require.NoError(t, err) ec := th.uni.backend - chainID, err := th.uni.backend.ChainID(testutils.Context(t)) + chainID, err := th.uni.backend.Client().ChainID(testutils.Context(t)) require.NoError(t, err) chain, err := th.app.GetRelayers().LegacyEVMChains().Get(chainID.String()) require.NoError(t, err) @@ -346,7 +346,7 @@ func fulfilBatchVRFReq(t *testing.T, require.NoError(t, err) ec := th.uni.backend - chainID, err := th.uni.backend.ChainID(testutils.Context(t)) + chainID, err := th.uni.backend.Client().ChainID(testutils.Context(t)) require.NoError(t, err) chain, err := th.app.GetRelayers().LegacyEVMChains().Get(chainID.String()) require.NoError(t, err) @@ -597,7 +597,7 @@ func newRevertTxnTH(t *testing.T, th.eoaConsumerAddr, _, th.eoaConsumer, err = vrf_external_sub_owner_example.DeployVRFExternalSubOwnerExample( uni.neil, - uni.backend, + uni.backend.Client(), coordinatorAddress, uni.linkContractAddress, ) diff --git a/core/services/vrf/v2/integration_v2_test.go b/core/services/vrf/v2/integration_v2_test.go index 102d79a76c7..d1fc8555b94 100644 --- a/core/services/vrf/v2/integration_v2_test.go +++ b/core/services/vrf/v2/integration_v2_test.go @@ -13,12 +13,11 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core" gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/google/uuid" "github.com/onsi/gomega" "github.com/shopspring/decimal" @@ -110,7 +109,7 @@ type coordinatorV2UniverseCommon struct { proxyAdminAddress common.Address // Abstract representation of the ethereum blockchain - backend *backends.SimulatedBackend + backend *simulated.Backend coordinatorABI *abi.ABI consumerABI *abi.ABI @@ -166,7 +165,7 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in vrfConsumers = append(vrfConsumers, testutils.MustNewSimTransactor(t)) } - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ sergey.From: {Balance: assets.Ether(1000).ToInt()}, neil.From: {Balance: assets.Ether(1000).ToInt()}, ned.From: {Balance: assets.Ether(1000).ToInt()}, @@ -175,8 +174,10 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in reverter.From: {Balance: assets.Ether(1000).ToInt()}, } for _, consumer := range vrfConsumers { - genesisData[consumer.From] = core.GenesisAccount{ - Balance: assets.Ether(1000).ToInt(), + genesisData = gethtypes.GenesisAlloc{ + consumer.From: { + Balance: assets.Ether(1000).ToInt(), + }, } } @@ -188,42 +189,42 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in vrf_coordinator_v2.VRFCoordinatorV2ABI)) require.NoError(t, err) backend := cltest.NewSimulatedBackend(t, genesisData, gasLimit) - h, err := backend.HeaderByNumber(testutils.Context(t), nil) + h, err := backend.Client().HeaderByNumber(testutils.Context(t), nil) require.NoError(t, err) blockTime := time.UnixMilli(int64(h.Time)) err = backend.AdjustTime(time.Since(blockTime) - 24*time.Hour) require.NoError(t, err) - backend.Commit() + // Deploy link linkAddress, _, linkContract, err := link_token_interface.DeployLinkToken( - sergey, backend) + sergey, backend.Client()) require.NoError(t, err, "failed to deploy link contract to simulated ethereum blockchain") // Deploy feed linkEthFeed, _, _, err := mock_v3_aggregator_contract.DeployMockV3AggregatorContract( - evil, backend, 18, vrftesthelpers.WeiPerUnitLink.BigInt()) // 0.01 eth per link + evil, backend.Client(), 18, vrftesthelpers.WeiPerUnitLink.BigInt()) // 0.01 eth per link require.NoError(t, err) // Deploy blockhash store - bhsAddress, _, bhsContract, err := blockhash_store.DeployBlockhashStore(neil, backend) + bhsAddress, _, bhsContract, err := blockhash_store.DeployBlockhashStore(neil, backend.Client()) require.NoError(t, err, "failed to deploy BlockhashStore contract to simulated ethereum blockchain") // Deploy batch blockhash store - batchBHSAddress, _, batchBHSContract, err := batch_blockhash_store.DeployBatchBlockhashStore(neil, backend, bhsAddress) + batchBHSAddress, _, batchBHSContract, err := batch_blockhash_store.DeployBatchBlockhashStore(neil, backend.Client(), bhsAddress) require.NoError(t, err, "failed to deploy BatchBlockhashStore contract to simulated ethereum blockchain") // Deploy VRF V2 coordinator coordinatorAddress, _, coordinatorContract, err := vrf_coordinator_v2.DeployVRFCoordinatorV2( - neil, backend, linkAddress, bhsAddress, linkEthFeed /* linkEth*/) + neil, backend.Client(), linkAddress, bhsAddress, linkEthFeed /* linkEth*/) require.NoError(t, err, "failed to deploy VRFCoordinatorV2 contract to simulated ethereum blockchain") backend.Commit() // Deploy batch VRF V2 coordinator batchCoordinatorAddress, _, batchCoordinatorContract, err := batch_vrf_coordinator_v2.DeployBatchVRFCoordinatorV2( - neil, backend, coordinatorAddress, + neil, backend.Client(), coordinatorAddress, ) require.NoError(t, err, "failed to deploy BatchVRFCoordinatorV2 contract to simulated ethereum blockchain") backend.Commit() @@ -238,13 +239,13 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in // tests that don't really use this code path (which will be 99.9% of all // real-world use cases). vrfOwnerAddress, _, vrfOwner, err := vrf_owner.DeployVRFOwner( - neil, backend, oldRootContractAddress, + neil, backend.Client(), oldRootContractAddress, ) require.NoError(t, err, "failed to deploy VRFOwner contract to simulated ethereum blockchain") backend.Commit() vrfOwnerAddressNew, _, vrfOwnerNew, err := vrf_owner.DeployVRFOwner( - neil, backend, coordinatorAddress, + neil, backend.Client(), coordinatorAddress, ) require.NoError(t, err, "failed to deploy VRFOwner contract for vrfOwnerNew to simulated ethereum blockchain") backend.Commit() @@ -252,7 +253,7 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in // Deploy batch VRF V2 coordinator oldBatchCoordinatorAddress, _, oldBatchCoordinatorContract, err := batch_vrf_coordinator_v2.DeployBatchVRFCoordinatorV2( - neil, backend, coordinatorAddress, + neil, backend.Client(), coordinatorAddress, ) require.NoError(t, err, "failed to deploy BatchVRFCoordinatorV2 contract wrapping old vrf coordinator v2 to simulated ethereum blockchain") backend.Commit() @@ -266,7 +267,7 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in // Deploy a VRF consumer. It has a starting balance of 500 LINK. consumerContractAddress, _, consumerContract, err2 := vrf_consumer_v2.DeployVRFConsumerV2( - author, backend, coordinatorAddress, linkAddress) + author, backend.Client(), coordinatorAddress, linkAddress) require.NoError(t, err2, "failed to deploy VRFConsumer contract to simulated ethereum blockchain") _, err2 = linkContract.Transfer(sergey, consumerContractAddress, assets.Ether(500).ToInt()) // Actually, LINK require.NoError(t, err2, "failed to send LINK to VRFConsumer contract on simulated ethereum blockchain") @@ -280,18 +281,18 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in // Deploy malicious consumer with 1 link maliciousConsumerContractAddress, _, maliciousConsumerContract, err := vrf_malicious_consumer_v2.DeployVRFMaliciousConsumerV2( - evil, backend, coordinatorAddress, linkAddress) + evil, backend.Client(), coordinatorAddress, linkAddress) require.NoError(t, err, "failed to deploy VRFMaliciousConsumer contract to simulated ethereum blockchain") _, err = linkContract.Transfer(sergey, maliciousConsumerContractAddress, assets.Ether(1).ToInt()) // Actually, LINK require.NoError(t, err, "failed to send LINK to VRFMaliciousConsumer contract on simulated ethereum blockchain") backend.Commit() // Deploy upgradeable consumer, proxy, and proxy admin - upgradeableConsumerAddress, _, _, err := vrf_consumer_v2_upgradeable_example.DeployVRFConsumerV2UpgradeableExample(neil, backend) + upgradeableConsumerAddress, _, _, err := vrf_consumer_v2_upgradeable_example.DeployVRFConsumerV2UpgradeableExample(neil, backend.Client()) require.NoError(t, err, "failed to deploy upgradeable consumer to simulated ethereum blockchain") backend.Commit() - proxyAdminAddress, _, proxyAdmin, err := vrfv2_proxy_admin.DeployVRFV2ProxyAdmin(neil, backend) + proxyAdminAddress, _, proxyAdmin, err := vrfv2_proxy_admin.DeployVRFV2ProxyAdmin(neil, backend.Client()) require.NoError(t, err) backend.Commit() @@ -304,7 +305,7 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in t.Log("initialize calldata:", hexified, "coordinator:", coordinatorAddress.String(), "link:", linkAddress) require.NoError(t, err) proxyAddress, _, _, err := vrfv2_transparent_upgradeable_proxy.DeployVRFV2TransparentUpgradeableProxy( - neil, backend, upgradeableConsumerAddress, proxyAdminAddress, initializeCalldata) + neil, backend.Client(), upgradeableConsumerAddress, proxyAdminAddress, initializeCalldata) require.NoError(t, err) _, err = linkContract.Transfer(sergey, proxyAddress, assets.Ether(500).ToInt()) // Actually, LINK @@ -317,7 +318,7 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in require.Equal(t, upgradeableConsumerAddress, implAddress) proxiedConsumer, err := vrf_consumer_v2_upgradeable_example.NewVRFConsumerV2UpgradeableExample( - proxyAddress, backend) + proxyAddress, backend.Client()) require.NoError(t, err) cAddress, err := proxiedConsumer.COORDINATOR(nil) @@ -332,7 +333,7 @@ func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers in // Deploy always reverting consumer revertingConsumerContractAddress, _, revertingConsumerContract, err := vrfv2_reverting_example.DeployVRFV2RevertingExample( - reverter, backend, coordinatorAddress, linkAddress, + reverter, backend.Client(), coordinatorAddress, linkAddress, ) require.NoError(t, err, "failed to deploy VRFRevertingExample contract to simulated eth blockchain") _, err = linkContract.Transfer(sergey, revertingConsumerContractAddress, assets.Ether(500).ToInt()) // Actually, LINK @@ -434,7 +435,7 @@ func deployOldCoordinator( linkAddress common.Address, bhsAddress common.Address, linkEthFeed common.Address, - backend *backends.SimulatedBackend, + backend *simulated.Backend, neil *bind.TransactOpts, ) ( common.Address, @@ -445,30 +446,30 @@ func deployOldCoordinator( ctorArgs, err := evmutils.ABIEncode(`[{"type":"address"}, {"type":"address"}, {"type":"address"}]`, linkAddress, bhsAddress, linkEthFeed) require.NoError(t, err) bytecode = append(bytecode, ctorArgs...) - nonce, err := backend.PendingNonceAt(ctx, neil.From) + nonce, err := backend.Client().PendingNonceAt(ctx, neil.From) require.NoError(t, err) - gasPrice, err := backend.SuggestGasPrice(ctx) + gasPrice, err := backend.Client().SuggestGasPrice(ctx) require.NoError(t, err) unsignedTx := gethtypes.NewContractCreation(nonce, big.NewInt(0), 15e6, gasPrice, bytecode) signedTx, err := neil.Signer(neil.From, unsignedTx) require.NoError(t, err) - err = backend.SendTransaction(ctx, signedTx) + err = backend.Client().SendTransaction(ctx, signedTx) require.NoError(t, err, "could not deploy old vrf coordinator to simulated blockchain") backend.Commit() - receipt, err := backend.TransactionReceipt(ctx, signedTx.Hash()) + receipt, err := backend.Client().TransactionReceipt(ctx, signedTx.Hash()) require.NoError(t, err) oldRootContractAddress := receipt.ContractAddress require.NotEqual(t, common.HexToAddress("0x0"), oldRootContractAddress, "old vrf coordinator address equal to zero address, deployment failed") - oldRootContract, err := vrf_coordinator_v2.NewVRFCoordinatorV2(oldRootContractAddress, backend) + oldRootContract, err := vrf_coordinator_v2.NewVRFCoordinatorV2(oldRootContractAddress, backend.Client()) require.NoError(t, err, "could not create wrapper object for old vrf coordinator v2") return oldRootContractAddress, oldRootContract } // Send eth from prefunded account. // Amount is number of ETH not wei. -func sendEth(t *testing.T, key ethkey.KeyV2, ec *backends.SimulatedBackend, to common.Address, eth int) { +func sendEth(t *testing.T, key ethkey.KeyV2, b *simulated.Backend, to common.Address, eth int) { ctx := testutils.Context(t) - nonce, err := ec.PendingNonceAt(ctx, key.Address) + nonce, err := b.Client().PendingNonceAt(ctx, key.Address) require.NoError(t, err) tx := gethtypes.NewTx(&gethtypes.DynamicFeeTx{ ChainID: testutils.SimulatedChainID, @@ -482,9 +483,9 @@ func sendEth(t *testing.T, key ethkey.KeyV2, ec *backends.SimulatedBackend, to c }) signedTx, err := gethtypes.SignTx(tx, gethtypes.NewLondonSigner(testutils.SimulatedChainID), key.ToEcdsaPrivKey()) require.NoError(t, err) - err = ec.SendTransaction(ctx, signedTx) + err = b.Client().SendTransaction(ctx, signedTx) require.NoError(t, err) - ec.Commit() + b.Commit() } func subscribeVRF( @@ -492,7 +493,7 @@ func subscribeVRF( author *bind.TransactOpts, consumerContract vrftesthelpers.VRFConsumerContract, coordinator v22.CoordinatorV2_X, - backend *backends.SimulatedBackend, + backend *simulated.Backend, fundingAmount *big.Int, nativePayment bool, ) (v22.Subscription, *big.Int) { @@ -665,7 +666,7 @@ func requestRandomnessAndAssertRandomWordsRequestedEvent( numWords uint32, cbGasLimit uint32, coordinator v22.CoordinatorV2_X, - backend *backends.SimulatedBackend, + backend *simulated.Backend, nativePayment bool, ) (requestID *big.Int, requestBlockNumber uint64) { minRequestConfirmations := uint16(2) @@ -714,7 +715,7 @@ func subscribeAndAssertSubscriptionCreatedEvent( consumerContractAddress common.Address, fundingAmount *big.Int, coordinator v22.CoordinatorV2_X, - backend *backends.SimulatedBackend, + backend *simulated.Backend, nativePayment bool, ) *big.Int { // Create a subscription and fund with LINK. @@ -781,7 +782,7 @@ func assertNumRandomWords( } } -func mine(t *testing.T, requestID, subID *big.Int, backend *backends.SimulatedBackend, db *sqlx.DB, vrfVersion vrfcommon.Version, chainId *big.Int) bool { +func mine(t *testing.T, requestID, subID *big.Int, backend *simulated.Backend, db *sqlx.DB, vrfVersion vrfcommon.Version, chainId *big.Int) bool { txstore := txmgr.NewTxStore(db, logger.TestLogger(t)) var metaField string if vrfVersion == vrfcommon.V2Plus { @@ -807,7 +808,7 @@ func mine(t *testing.T, requestID, subID *big.Int, backend *backends.SimulatedBa }, testutils.WaitTimeout(t), time.Second).Should(gomega.BeTrue()) } -func mineBatch(t *testing.T, requestIDs []*big.Int, subID *big.Int, backend *backends.SimulatedBackend, db *sqlx.DB, vrfVersion vrfcommon.Version, chainId *big.Int) bool { +func mineBatch(t *testing.T, requestIDs []*big.Int, subID *big.Int, backend *simulated.Backend, db *sqlx.DB, vrfVersion vrfcommon.Version, chainId *big.Int) bool { requestIDMap := map[string]bool{} txstore := txmgr.NewTxStore(db, logger.TestLogger(t)) var metaField string @@ -1145,7 +1146,7 @@ func deployWrapper(t *testing.T, uni coordinatorV2UniverseCommon, wrapperOverhea wrapperConsumer *vrfv2_wrapper_consumer_example.VRFV2WrapperConsumerExample, wrapperConsumerAddress common.Address, ) { - wrapperAddress, _, wrapper, err := vrfv2_wrapper.DeployVRFV2Wrapper(uni.neil, uni.backend, uni.linkContractAddress, uni.linkEthFeedAddress, uni.rootContractAddress) + wrapperAddress, _, wrapper, err := vrfv2_wrapper.DeployVRFV2Wrapper(uni.neil, uni.backend.Client(), uni.linkContractAddress, uni.linkEthFeedAddress, uni.rootContractAddress) require.NoError(t, err) uni.backend.Commit() @@ -1153,7 +1154,7 @@ func deployWrapper(t *testing.T, uni coordinatorV2UniverseCommon, wrapperOverhea require.NoError(t, err) uni.backend.Commit() - wrapperConsumerAddress, _, wrapperConsumer, err = vrfv2_wrapper_consumer_example.DeployVRFV2WrapperConsumerExample(uni.neil, uni.backend, uni.linkContractAddress, wrapperAddress) + wrapperConsumerAddress, _, wrapperConsumer, err = vrfv2_wrapper_consumer_example.DeployVRFV2WrapperConsumerExample(uni.neil, uni.backend.Client(), uni.linkContractAddress, wrapperAddress) require.NoError(t, err) uni.backend.Commit() @@ -1521,18 +1522,18 @@ func registerProvingKeyHelper(t *testing.T, uni coordinatorV2UniverseCommon, coo func TestExternalOwnerConsumerExample(t *testing.T) { owner := testutils.MustNewSimTransactor(t) random := testutils.MustNewSimTransactor(t) - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ owner.From: {Balance: assets.Ether(10).ToInt()}, random.From: {Balance: assets.Ether(10).ToInt()}, } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) linkAddress, _, linkContract, err := link_token_interface.DeployLinkToken( - owner, backend) + owner, backend.Client()) require.NoError(t, err) backend.Commit() coordinatorAddress, _, coordinator, err := vrf_coordinator_v2.DeployVRFCoordinatorV2( - owner, backend, linkAddress, common.Address{}, common.Address{}) + owner, backend.Client(), linkAddress, common.Address{}, common.Address{}) require.NoError(t, err) _, err = coordinator.SetConfig(owner, uint16(1), uint32(10000), 1, 1, big.NewInt(10), vrf_coordinator_v2.VRFCoordinatorV2FeeConfig{ FulfillmentFlatFeeLinkPPMTier1: 0, @@ -1547,7 +1548,7 @@ func TestExternalOwnerConsumerExample(t *testing.T) { }) require.NoError(t, err) backend.Commit() - consumerAddress, _, consumer, err := vrf_external_sub_owner_example.DeployVRFExternalSubOwnerExample(owner, backend, coordinatorAddress, linkAddress) + consumerAddress, _, consumer, err := vrf_external_sub_owner_example.DeployVRFExternalSubOwnerExample(owner, backend.Client(), coordinatorAddress, linkAddress) require.NoError(t, err) backend.Commit() _, err = linkContract.Transfer(owner, consumerAddress, assets.Ether(2).ToInt()) @@ -1582,20 +1583,20 @@ func TestExternalOwnerConsumerExample(t *testing.T) { func TestSimpleConsumerExample(t *testing.T) { owner := testutils.MustNewSimTransactor(t) random := testutils.MustNewSimTransactor(t) - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ owner.From: {Balance: assets.Ether(10).ToInt()}, } backend := cltest.NewSimulatedBackend(t, genesisData, uint32(ethconfig.Defaults.Miner.GasCeil)) linkAddress, _, linkContract, err := link_token_interface.DeployLinkToken( - owner, backend) + owner, backend.Client()) require.NoError(t, err) backend.Commit() coordinatorAddress, _, _, err := vrf_coordinator_v2.DeployVRFCoordinatorV2( - owner, backend, linkAddress, common.Address{}, common.Address{}) + owner, backend.Client(), linkAddress, common.Address{}, common.Address{}) require.NoError(t, err) backend.Commit() - consumerAddress, _, consumer, err := vrf_single_consumer_example.DeployVRFSingleConsumerExample(owner, backend, coordinatorAddress, linkAddress, 1, 1, 1, [32]byte{}) + consumerAddress, _, consumer, err := vrf_single_consumer_example.DeployVRFSingleConsumerExample(owner, backend.Client(), coordinatorAddress, linkAddress, 1, 1, 1, [32]byte{}) require.NoError(t, err) backend.Commit() _, err = linkContract.Transfer(owner, consumerAddress, assets.Ether(2).ToInt()) @@ -1736,7 +1737,7 @@ func TestIntegrationVRFV2(t *testing.T) { return len(rf) == 1 }, testutils.WaitTimeout(t), 500*time.Millisecond).Should(gomega.BeTrue()) assert.True(t, rf[0].Success(), "expected callback to succeed") - fulfillReceipt, err := uni.backend.TransactionReceipt(ctx, rf[0].Raw().TxHash) + fulfillReceipt, err := uni.backend.Client().TransactionReceipt(ctx, rf[0].Raw().TxHash) require.NoError(t, err) // Assert all the random words received by the consumer are different and non-zero. @@ -1873,7 +1874,7 @@ func TestRequestCost(t *testing.T) { tx, err := consumerContract.CreateSubscriptionAndFund(consumerOwner, assets.Ether(5).ToInt()) require.NoError(tt, err) uni.backend.Commit() - r, err := uni.backend.TransactionReceipt(testutils.Context(t), tx.Hash()) + r, err := uni.backend.Client().TransactionReceipt(testutils.Context(t), tx.Hash()) require.NoError(tt, err) t.Log("gas used by proxied CreateSubscriptionAndFund:", r.GasUsed) @@ -2268,8 +2269,8 @@ func AssertLinkBalance(t *testing.T, linkContract *link_token_interface.LinkToke assert.Equal(t, balance.String(), b.String(), "invalid balance for %v", address) } -func AssertNativeBalance(t *testing.T, backend *backends.SimulatedBackend, address common.Address, balance *big.Int) { - b, err := backend.BalanceAt(testutils.Context(t), address, nil) +func AssertNativeBalance(t *testing.T, backend *simulated.Backend, address common.Address, balance *big.Int) { + b, err := backend.Client().BalanceAt(testutils.Context(t), address, nil) require.NoError(t, err) assert.Equal(t, balance.String(), b.String(), "invalid balance for %v", address) } @@ -2288,14 +2289,14 @@ func pair(x, y *big.Int) [2]*big.Int { return [2]*big.Int{x, y} } // estimateGas returns the estimated gas cost of running the given method on the // contract at address to, on the given backend, with the given args, and given // that the transaction is sent from the from address. -func estimateGas(t *testing.T, backend *backends.SimulatedBackend, +func estimateGas(t *testing.T, backend *simulated.Backend, from, to common.Address, abi *abi.ABI, method string, args ...interface{}, ) uint64 { rawData, err := abi.Pack(method, args...) require.NoError(t, err, "failed to construct raw %s transaction with args %s", method, args) callMsg := ethereum.CallMsg{From: from, To: &to, Data: rawData} - estimate, err := backend.EstimateGas(testutils.Context(t), callMsg) + estimate, err := backend.Client().EstimateGas(testutils.Context(t), callMsg) require.NoError(t, err, "failed to estimate gas from %s call with args %s", method, args) return estimate diff --git a/core/services/vrf/v2/listener_v2_log_listener_test.go b/core/services/vrf/v2/listener_v2_log_listener_test.go index 5c7ae20ac67..00b2d535825 100644 --- a/core/services/vrf/v2/listener_v2_log_listener_test.go +++ b/core/services/vrf/v2/listener_v2_log_listener_test.go @@ -10,9 +10,9 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/jmoiron/sqlx" "github.com/onsi/gomega" "github.com/stretchr/testify/assert" @@ -45,7 +45,7 @@ type vrfLogPollerListenerTH struct { ChainID *big.Int ORM logpoller.ORM LogPoller logpoller.LogPollerTest - Client *backends.SimulatedBackend + Backend *simulated.Backend Emitter *log_emitter.LogEmitter EmitterAddress common.Address VRFLogEmitter *vrf_log_emitter.VRFLogEmitter @@ -69,11 +69,12 @@ func setupVRFLogPollerListenerTH(t *testing.T, o := logpoller.NewORM(chainID, db, lggr) owner := testutils.MustNewSimTransactor(t) - ec := backends.NewSimulatedBackend(map[common.Address]core.GenesisAccount{ + backend := simulated.NewBackend(ethtypes.GenesisAlloc{ owner.From: { Balance: big.NewInt(0).Mul(big.NewInt(10), big.NewInt(1e18)), }, - }, 10e6) + }, simulated.WithBlockGasLimit(10e6)) + ec := backend.Client() // VRF Listener relies on block timestamps, but SimulatedBackend uses by default clock starting from 1970-01-01 // This trick is used to move the clock closer to the current time. We set first block to be X hours ago. // FirstBlockAge is used to compute first block's timestamp in SimulatedBackend (time.Now() - FirstBlockAge) @@ -81,11 +82,10 @@ func setupVRFLogPollerListenerTH(t *testing.T, h, err := ec.HeaderByNumber(testutils.Context(t), nil) require.NoError(t, err) blockTime := time.UnixMilli(int64(h.Time)) - err = ec.AdjustTime(time.Since(blockTime) - FirstBlockAge) + err = backend.AdjustTime(time.Since(blockTime) - FirstBlockAge) require.NoError(t, err) - ec.Commit() - esc := client.NewSimulatedBackendClient(t, ec, chainID) + esc := client.NewSimulatedBackendClient(t, backend, chainID) // Mark genesis block as finalized to avoid any nulls in the tests //TODO must we do this? //h, err := ec.HeaderByNumber(ctx, nil) @@ -109,7 +109,7 @@ func setupVRFLogPollerListenerTH(t *testing.T, require.NoError(t, err) vrfLogEmitterAddress, _, vrfLogEmitter, err := vrf_log_emitter.DeployVRFLogEmitter(owner, ec) require.NoError(t, err) - ec.Commit() + backend.Commit() // Log Poller Listener ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr) @@ -168,7 +168,7 @@ func setupVRFLogPollerListenerTH(t *testing.T, EmitterAddress: emitterAddress1, VRFLogEmitter: vrfLogEmitter, VRFEmitterAddress: vrfLogEmitterAddress, - Client: ec, + Backend: backend, Owner: owner, Db: db, Listener: listener, @@ -197,7 +197,7 @@ func TestInitProcessedBlock_NoVRFReqs(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Emit some logs from block 5 to 9 (Inclusive) @@ -207,7 +207,7 @@ func TestInitProcessedBlock_NoVRFReqs(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() } // Blocks till now: 2 (in SetupTH) + 2 (empty blocks) + 5 (EmitLog blocks) = 9 @@ -270,7 +270,7 @@ func TestInitProcessedBlock_NoUnfulfilledVRFReqs(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Create VRF request block and a fulfillment block @@ -281,10 +281,10 @@ func TestInitProcessedBlock_NoUnfulfilledVRFReqs(t *testing.T) { _, err2 := th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() _, err2 = th.VRFLogEmitter.EmitRandomWordsFulfilled(th.Owner, reqID, preSeed, big.NewInt(10), true) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() // Emit some logs in blocks to make the VRF req and fulfillment older than finalityDepth from latestBlock n := 5 @@ -293,7 +293,7 @@ func TestInitProcessedBlock_NoUnfulfilledVRFReqs(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() } // Calling Start() after RegisterFilter() simulates a node restart after job creation, should reload Filter from db. @@ -327,7 +327,7 @@ func TestInitProcessedBlock_OneUnfulfilledVRFReq(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Make a VRF request without fulfilling it @@ -338,17 +338,17 @@ func TestInitProcessedBlock_OneUnfulfilledVRFReq(t *testing.T) { _, err2 := th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() // Emit some logs in blocks to make the VRF req and fulfillment older than finalityDepth from latestBlock n := 5 - th.Client.Commit() + th.Backend.Commit() for i := 0; i < n; i++ { _, err1 := th.Emitter.EmitLog1(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() } // Calling Start() after RegisterFilter() simulates a node restart after job creation, should reload Filter from db. @@ -381,7 +381,7 @@ func TestInitProcessedBlock_SomeUnfulfilledVRFReqs(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Emit some logs in blocks with VRF reqs interspersed @@ -392,7 +392,7 @@ func TestInitProcessedBlock_SomeUnfulfilledVRFReqs(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() // Create 2 blocks with VRF requests in each iteration keyHash := [32]byte(th.Listener.job.VRFSpec.PublicKey.MustHash().Bytes()) @@ -402,13 +402,13 @@ func TestInitProcessedBlock_SomeUnfulfilledVRFReqs(t *testing.T) { _, err2 := th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID1, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() reqID2 := big.NewInt(int64(2*i + 1)) _, err2 = th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID2, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() } // Calling Start() after RegisterFilter() simulates a node restart after job creation, should reload Filter from db. @@ -443,7 +443,7 @@ func TestInitProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Emit some logs in blocks with VRF reqs interspersed @@ -454,7 +454,7 @@ func TestInitProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() // Create 2 blocks with VRF requests in each iteration and fulfill one // of them. This creates a mixed workload of fulfilled and unfulfilled @@ -466,7 +466,7 @@ func TestInitProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { _, err2 := th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID1, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() reqID2 := big.NewInt(int64(2*i + 1)) _, err2 = th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, @@ -475,7 +475,7 @@ func TestInitProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { _, err2 = th.VRFLogEmitter.EmitRandomWordsFulfilled(th.Owner, reqID1, preSeed, big.NewInt(10), true) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() } // Calling Start() after RegisterFilter() simulates a node restart after job creation, should reload Filter from db. @@ -518,7 +518,7 @@ func TestUpdateLastProcessedBlock_NoVRFReqs(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Create VRF request logs @@ -530,13 +530,13 @@ func TestUpdateLastProcessedBlock_NoVRFReqs(t *testing.T) { _, err2 := th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID1, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() reqID2 := big.NewInt(int64(2)) _, err2 = th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID2, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() // Emit some logs in blocks to make the VRF req and fulfillment older than finalityDepth from latestBlock n := 5 @@ -545,7 +545,7 @@ func TestUpdateLastProcessedBlock_NoVRFReqs(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() } // Blocks till now: 2 (in SetupTH) + 2 (empty blocks) + 2 (VRF req blocks) + 5 (EmitLog blocks) = 11 @@ -575,7 +575,7 @@ func TestUpdateLastProcessedBlock_NoUnfulfilledVRFReqs(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Create VRF request log block with a fulfillment log block @@ -587,11 +587,11 @@ func TestUpdateLastProcessedBlock_NoUnfulfilledVRFReqs(t *testing.T) { _, err2 := th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID1, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() _, err2 = th.VRFLogEmitter.EmitRandomWordsFulfilled(th.Owner, reqID1, preSeed, big.NewInt(10), true) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() // Emit some logs in blocks to make the VRF req and fulfillment older than finalityDepth from latestBlock n := 5 @@ -600,7 +600,7 @@ func TestUpdateLastProcessedBlock_NoUnfulfilledVRFReqs(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() } // Blocks till now: 2 (in SetupTH) + 2 (empty blocks) + 2 (VRF req/resp blocks) + 5 (EmitLog blocks) = 11 @@ -630,7 +630,7 @@ func TestUpdateLastProcessedBlock_OneUnfulfilledVRFReq(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Create VRF request logs without a fulfillment log block @@ -642,7 +642,7 @@ func TestUpdateLastProcessedBlock_OneUnfulfilledVRFReq(t *testing.T) { _, err2 := th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID1, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() // Emit some logs in blocks to make the VRF req and fulfillment older than finalityDepth from latestBlock n := 5 @@ -651,7 +651,7 @@ func TestUpdateLastProcessedBlock_OneUnfulfilledVRFReq(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() } // Blocks till now: 2 (in SetupTH) + 2 (empty blocks) + 1 (VRF req block) + 5 (EmitLog blocks) = 10 @@ -681,7 +681,7 @@ func TestUpdateLastProcessedBlock_SomeUnfulfilledVRFReqs(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Emit some logs in blocks to make the VRF req and fulfillment older than finalityDepth from latestBlock @@ -691,7 +691,7 @@ func TestUpdateLastProcessedBlock_SomeUnfulfilledVRFReqs(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() // Create 2 blocks with VRF requests in each iteration keyHash := [32]byte(th.Listener.job.VRFSpec.PublicKey.MustHash().Bytes()) @@ -702,13 +702,13 @@ func TestUpdateLastProcessedBlock_SomeUnfulfilledVRFReqs(t *testing.T) { _, err2 := th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID1, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() reqID2 := big.NewInt(int64(2*i + 1)) _, err2 = th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID2, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() } // Blocks till now: 2 (in SetupTH) + 2 (empty blocks) + 3*5 (EmitLog + VRF req blocks) = 19 @@ -738,7 +738,7 @@ func TestUpdateLastProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { // Block 3 to finalityDepth. Ensure we have finality number of blocks for i := 1; i < int(finalityDepth); i++ { - th.Client.Commit() + th.Backend.Commit() } // Emit some logs in blocks to make the VRF req and fulfillment older than finalityDepth from latestBlock @@ -748,7 +748,7 @@ func TestUpdateLastProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { require.NoError(t, err1) _, err1 = th.Emitter.EmitLog2(th.Owner, []*big.Int{big.NewInt(int64(i))}) require.NoError(t, err1) - th.Client.Commit() + th.Backend.Commit() // Create 2 blocks with VRF requests in each iteration and fulfill one // of them. This creates a mixed workload of fulfilled and unfulfilled @@ -761,7 +761,7 @@ func TestUpdateLastProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { _, err2 := th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, keyHash, reqID1, preSeed, subID, 10, 10000, 2, th.Owner.From) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() reqID2 := big.NewInt(int64(2*i + 1)) _, err2 = th.VRFLogEmitter.EmitRandomWordsRequested(th.Owner, @@ -769,7 +769,7 @@ func TestUpdateLastProcessedBlock_UnfulfilledNFulfilledVRFReqs(t *testing.T) { require.NoError(t, err2) _, err2 = th.VRFLogEmitter.EmitRandomWordsFulfilled(th.Owner, reqID1, preSeed, big.NewInt(10), true) require.NoError(t, err2) - th.Client.Commit() + th.Backend.Commit() } // Blocks till now: 2 (in SetupTH) + 2 (empty blocks) + 3*5 (EmitLog + VRF req blocks) = 19 @@ -812,15 +812,15 @@ func SetupGetUnfulfilledTH(t *testing.T) (*listenerV2, *ubig.Big) { // Construct CoordinatorV2_X object for VRF listener owner := testutils.MustNewSimTransactor(t) - ec := backends.NewSimulatedBackend(map[common.Address]core.GenesisAccount{ + b := simulated.NewBackend(ethtypes.GenesisAlloc{ owner.From: { Balance: big.NewInt(0).Mul(big.NewInt(10), big.NewInt(1e18)), }, - }, 10e6) - _, _, vrfLogEmitter, err := vrf_log_emitter.DeployVRFLogEmitter(owner, ec) + }, simulated.WithBlockGasLimit(10e6)) + _, _, vrfLogEmitter, err := vrf_log_emitter.DeployVRFLogEmitter(owner, b.Client()) require.NoError(t, err) - ec.Commit() - coordinatorV2, err := vrf_coordinator_v2.NewVRFCoordinatorV2(vrfLogEmitter.Address(), ec) + b.Commit() + coordinatorV2, err := vrf_coordinator_v2.NewVRFCoordinatorV2(vrfLogEmitter.Address(), b.Client()) require.Nil(t, err) coordinator := NewCoordinatorV2(coordinatorV2) diff --git a/core/services/vrf/vrftesthelpers/helpers.go b/core/services/vrf/vrftesthelpers/helpers.go index 33ad8470731..182e714c537 100644 --- a/core/services/vrf/vrftesthelpers/helpers.go +++ b/core/services/vrf/vrftesthelpers/helpers.go @@ -8,10 +8,10 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core" + gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth/ethconfig" + "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/google/uuid" "github.com/onsi/gomega" "github.com/shopspring/decimal" @@ -149,7 +149,7 @@ type CoordinatorUniverse struct { BHSContractAddress common.Address // Abstraction representation of the ethereum blockchain - Backend *backends.SimulatedBackend + Backend *simulated.Backend CoordinatorABI *abi.ABI ConsumerABI *abi.ABI // Cast of participants @@ -165,10 +165,10 @@ func NewVRFCoordinatorUniverseWithV08Consumer(t *testing.T, key ethkey.KeyV2) Co cu := NewVRFCoordinatorUniverse(t, key) consumerContractAddress, _, consumerContract, err := solidity_vrf_consumer_interface_v08.DeployVRFConsumer( - cu.Carol, cu.Backend, cu.RootContractAddress, cu.LinkContractAddress) + cu.Carol, cu.Backend.Client(), cu.RootContractAddress, cu.LinkContractAddress) require.NoError(t, err, "failed to deploy v08 VRFConsumer contract to simulated ethereum blockchain") _, _, requestIDBase, err := - solidity_vrf_request_id_v08.DeployVRFRequestIDBaseTestHelper(cu.Neil, cu.Backend) + solidity_vrf_request_id_v08.DeployVRFRequestIDBaseTestHelper(cu.Neil, cu.Backend.Client()) require.NoError(t, err, "failed to deploy v08 VRFRequestIDBaseTestHelper contract to simulated ethereum blockchain") cu.ConsumerContractAddressV08 = consumerContractAddress cu.RequestIDBaseV08 = requestIDBase @@ -195,7 +195,7 @@ func NewVRFCoordinatorUniverse(t *testing.T, keys ...ethkey.KeyV2) CoordinatorUn ned = testutils.MustNewSimTransactor(t) carol = testutils.MustNewSimTransactor(t) ) - genesisData := core.GenesisAlloc{ + genesisData := gethtypes.GenesisAlloc{ sergey.From: {Balance: assets.Ether(1000).ToInt()}, neil.From: {Balance: assets.Ether(1000).ToInt()}, ned.From: {Balance: assets.Ether(1000).ToInt()}, @@ -203,7 +203,7 @@ func NewVRFCoordinatorUniverse(t *testing.T, keys ...ethkey.KeyV2) CoordinatorUn } for _, t := range oracleTransactors { - genesisData[t.From] = core.GenesisAccount{Balance: assets.Ether(1000).ToInt()} + genesisData[t.From] = gethtypes.Account{Balance: assets.Ether(1000).ToInt()} } gasLimit := uint32(ethconfig.Defaults.Miner.GasCeil) @@ -215,20 +215,20 @@ func NewVRFCoordinatorUniverse(t *testing.T, keys ...ethkey.KeyV2) CoordinatorUn require.NoError(t, err) backend := cltest.NewSimulatedBackend(t, genesisData, gasLimit) linkAddress, _, linkContract, err := link_token_interface.DeployLinkToken( - sergey, backend) + sergey, backend.Client()) require.NoError(t, err, "failed to deploy link contract to simulated ethereum blockchain") - bhsAddress, _, bhsContract, err := blockhash_store.DeployBlockhashStore(neil, backend) + bhsAddress, _, bhsContract, err := blockhash_store.DeployBlockhashStore(neil, backend.Client()) require.NoError(t, err, "failed to deploy BlockhashStore contract to simulated ethereum blockchain") coordinatorAddress, _, coordinatorContract, err := solidity_vrf_coordinator_interface.DeployVRFCoordinator( - neil, backend, linkAddress, bhsAddress) + neil, backend.Client(), linkAddress, bhsAddress) require.NoError(t, err, "failed to deploy VRFCoordinator contract to simulated ethereum blockchain") consumerContractAddress, _, consumerContract, err := solidity_vrf_consumer_interface.DeployVRFConsumer( - carol, backend, coordinatorAddress, linkAddress) + carol, backend.Client(), coordinatorAddress, linkAddress) require.NoError(t, err, "failed to deploy VRFConsumer contract to simulated ethereum blockchain") _, _, requestIDBase, err := - solidity_vrf_request_id.DeployVRFRequestIDBaseTestHelper(neil, backend) + solidity_vrf_request_id.DeployVRFRequestIDBaseTestHelper(neil, backend.Client()) require.NoError(t, err, "failed to deploy VRFRequestIDBaseTestHelper contract to simulated ethereum blockchain") _, err = linkContract.Transfer(sergey, consumerContractAddress, oneEth) // Actually, LINK require.NoError(t, err, "failed to send LINK to VRFConsumer contract on simulated ethereum blockchain") diff --git a/go.mod b/go.mod index 81160f3fb26..9b181b288ca 100644 --- a/go.mod +++ b/go.mod @@ -67,6 +67,7 @@ require ( github.com/prometheus/prometheus v0.48.1 github.com/robfig/cron/v3 v3.0.1 github.com/rogpeppe/go-internal v1.11.0 + github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 github.com/scylladb/go-reflectx v1.0.1 github.com/shirou/gopsutil/v3 v3.24.3 github.com/shopspring/decimal v1.3.1 @@ -282,7 +283,6 @@ require ( github.com/rivo/uniseg v0.4.4 // indirect github.com/rs/cors v1.8.3 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/sethvargo/go-retry v0.2.4 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect