anvil

package
v0.17.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 2, 2024 License: MIT Imports: 41 Imported by: 2

README

Anvil

Anvil is ran as a docker image, with options passed in to the option builder being reflected in the anvil backend.

Notes:

Anything relying on an impersonated account that takes the form eth_getTransactionByHash will not work because geth will always try to recover the v, r, and s values.

Documentation

Overview

Package anvil is an anvil test backend. like the ganache backend, it is used primarily for fork tests.

Index

Constants

View Source
const (
	// Restart defines the restart policy for the docker container.
	Restart RestartPolicy = "always"
	// Failure defines the restart policy for the docker container.
	Failure = "on-failure"
	// UnlessStopped defines the restart policy for the docker container.
	UnlessStopped = "unless-stopped"
	// No defines the restart policy for the docker container.
	No = "no"
	// Autoremove removes the container when it's finished.
	Autoremove = "autoremove"
)
View Source
const BackendName = "anvil"

BackendName is the name of the anvil backend.

Variables

This section is empty.

Functions

func ImpersonatedSigner

func ImpersonatedSigner(address common.Address, transaction *types.Transaction) (*types.Transaction, error)

ImpersonatedSigner is a signer that does nothing for use in account impersonation w/ contracts.

Types

type Backend

type Backend struct {
	*base.Backend
	// contains filtered or unexported fields
}

Backend contains the anvil test backend.

func NewAnvilBackend

func NewAnvilBackend(ctx context.Context, t *testing.T, args *OptionBuilder) *Backend

NewAnvilBackend creates a test anvil backend. nolint: cyclop

func (*Backend) BackendName

func (b *Backend) BackendName() string

BackendName returns the name of the backend.

func (*Backend) BatchWithContext added in v0.1.7

func (b *Backend) BatchWithContext(ctx context.Context, calls ...w3types.Caller) error

func (*Backend) ChainConfig

func (f *Backend) ChainConfig() *params.ChainConfig

ChainConfig gets the chain config.

func (*Backend) FundAccount

func (f *Backend) FundAccount(ctx context.Context, address common.Address, amount big.Int)

FundAccount funds an account with the given amount.

func (*Backend) GetFundedAccount

func (f *Backend) GetFundedAccount(ctx context.Context, requestBalance *big.Int) *keystore.Key

GetFundedAccount gets a funded account.

func (*Backend) GetTxContext

func (f *Backend) GetTxContext(ctx context.Context, address *common.Address) (res backends.AuthType)

GetTxContext gets the tx context for the given address. TODO: dedupe w/ geth.

func (*Backend) ImpersonateAccount

func (f *Backend) ImpersonateAccount(ctx context.Context, address common.Address, transact func(opts *bind.TransactOpts) *types.Transaction) error

ImpersonateAccount impersonates an account.

Note *any* other call made to the backend will impersonate while this is being called in a future version, we'll wrap something like omnirpc to prevent other transactions submission calls from taking place in the meantime, this may cause race conditions.

We also print a warning message to the console as an added precaution.

func (*Backend) Signer

func (f *Backend) Signer() types.Signer

Signer gets the signer for the chain.

func (*Backend) TearDown added in v0.0.140

func (b *Backend) TearDown()

TearDown purges docker resources associated with the backend.

func (*Backend) WaitForConfirmation added in v0.0.52

func (f *Backend) WaitForConfirmation(ctx context.Context, tx *types.Transaction)

WaitForConfirmation checks confirmation if the transaction is signed. nolint: cyclop

type Client

type Client struct {
	*rpc.Client
}

Client is a client for interacting with anvil. Note: this should not be used directly unless dealing with an external anvil instance. Please use the Backend instead.

func Dial

func Dial(ctx context.Context, rpcURL string) (*Client, error)

Dial dials an anvil instance.

func (*Client) Close

func (c *Client) Close()

Close closes the conn.

func (*Client) DropTransaction

func (c *Client) DropTransaction(ctx context.Context, tx common.Hash) error

DropTransaction drops a transactions from the memopool.

func (*Client) DumpState

func (c *Client) DumpState(ctx context.Context) (string, error)

DumpState returns a hex string representing the complete state of the chain. Can be re-imported into a fresh/restarted instance of Anvil to reattain the same state.

func (*Client) EnableTraces

func (c *Client) EnableTraces(ctx context.Context) error

EnableTraces enables call traces for transactions that are returned to the user when they execute a transaction.

func (*Client) EvmMine

func (c *Client) EvmMine(ctx context.Context) error

EvmMine mines a single block.

func (*Client) GetAutomine

func (c *Client) GetAutomine(ctx context.Context) (isAutomining bool, err error)

GetAutomine returns whether automine is enabled.

func (*Client) ImpersonateAccount

func (c *Client) ImpersonateAccount(ctx context.Context, address common.Address) error

ImpersonateAccount impersonates an account. Send transactions impersonating an externally owned account or contract. While impersonating a contract, the contract functions can not be called. anvil_stopImpersonatingAccount must be used if the contract's functions are to be called again. See also EIP-3607.

func (*Client) IncreaseTime

func (c *Client) IncreaseTime(ctx context.Context, seconds int64) error

IncreaseTime jumps forward in time by the given amount of time, in seconds.

func (*Client) LoadState

func (c *Client) LoadState(ctx context.Context, stateHex string) error

LoadState merges the contents of a hex string previously returned by DumpState into the current chain state. Will overwrite any colliding accounts/storage slots.

func (*Client) Mine

func (c *Client) Mine(ctx context.Context, blockCount uint) error

Mine mines a number of blocks.

func (*Client) NodeInfo

func (c *Client) NodeInfo(ctx context.Context) (map[string]interface{}, error)

NodeInfo retrieves the configuration params for the currently running Anvil node.

func (*Client) RemoveBlockTimestampInterval

func (c *Client) RemoveBlockTimestampInterval(ctx context.Context) error

RemoveBlockTimestampInterval removes an anvil_setBlockTimestampInterval if it exists.

func (*Client) Reset

func (c *Client) Reset(ctx context.Context) error

Reset the fork to a fresh forked state, and optionally update the fork config.

func (*Client) Revert

func (c *Client) Revert(ctx context.Context, snapshotID string) error

Revert reverts the state of the blockchain to a previous snapshot.

func (*Client) SendUnsignedTransaction

func (c *Client) SendUnsignedTransaction(ctx context.Context, from common.Address, tx *types.Transaction) error

SendUnsignedTransaction sends a transaction to the anvil node. It is the responsibility of the caller to call impersonateAccount and revertImpersonatedAccount.

func (*Client) SetAutomine

func (c *Client) SetAutomine(ctx context.Context, enabled bool) error

SetAutomine enables or disables automatic mining of new blocks with each new transaction.

func (*Client) SetBalance

func (c *Client) SetBalance(ctx context.Context, address common.Address, balance uint64) error

SetBalance sets the balance of an account.

func (*Client) SetBlockGasLimit

func (c *Client) SetBlockGasLimit(ctx context.Context, gasLimit uint64) error

SetBlockGasLimit sets the block gas limit for the following blocks.

func (*Client) SetBlockTimestampInterval

func (c *Client) SetBlockTimestampInterval(ctx context.Context, interval int64) error

SetBlockTimestampInterval sets a block timestamp interval.

func (*Client) SetCode

func (c *Client) SetCode(ctx context.Context, address common.Address, code []byte) error

SetCode sets the code of an account.

func (*Client) SetCoinbase

func (c *Client) SetCoinbase(ctx context.Context, coinbase common.Address) error

SetCoinbase sets the coinbase of the chain.

func (*Client) SetIntervalMining

func (c *Client) SetIntervalMining(ctx context.Context, interval int) error

SetIntervalMining sets the mining behavior to interval with the given interval (seconds).

func (*Client) SetLoggingEnabled

func (c *Client) SetLoggingEnabled(ctx context.Context, enabled bool) error

SetLoggingEnabled Enable or disable logging.

func (*Client) SetMinGasPrice

func (c *Client) SetMinGasPrice(ctx context.Context, minGasPrice *big.Int) error

SetMinGasPrice sets the minimum gas price. this is disabled when eip-1559 is enabled.

func (*Client) SetNextBlockBaseFeePerGas

func (c *Client) SetNextBlockBaseFeePerGas(ctx context.Context, baseFee *big.Int) error

SetNextBlockBaseFeePerGas sets the base fee per gas for the next block.

func (*Client) SetNextBlockTimestamp

func (c *Client) SetNextBlockTimestamp(ctx context.Context, timestamp int64) error

SetNextBlockTimestamp sets the exact timestamp for the next block.

func (*Client) SetNonce

func (c *Client) SetNonce(ctx context.Context, address common.Address, nonce uint64) error

SetNonce sets the nonce of an account.

func (*Client) SetRPCURL

func (c *Client) SetRPCURL(ctx context.Context, rpcURL string) error

SetRPCURL sets the rpc url.

func (*Client) SetStorageAt

func (c *Client) SetStorageAt(ctx context.Context, address common.Address, key common.Hash, value common.Hash) error

SetStorageAt sets the storage of an account.

func (*Client) Snapshot

func (c *Client) Snapshot(ctx context.Context) (snapshotID string, err error)

Snapshot captures the state of the blockchain at the current block.

func (*Client) StopImpersonatingAccount

func (c *Client) StopImpersonatingAccount(ctx context.Context, address common.Address) error

StopImpersonatingAccount stops impersonating an account or contract if previously set with anvil_impersonateAccount.

type Hardfork

type Hardfork uint8

Hardfork indicates which chain should be hardforked by foundry see: https://github.com/foundry-rs/foundry/blob/master/anvil/src/hardfork.rs#L94 note: because of the way foundry does alias being incompatible w/ stringer, latest will have the wrong id when passed as an int

const (
	// Frontier is the initial release of the Ethereum protocol.
	Frontier Hardfork = iota + 1 // frontier
	// Homestead is the chain config corresponding to the homestead hardfork.
	Homestead // homestead
	// DAO is the chain config corresponding to the DAO hardfork.
	DAO // dao
	// Tangerine is the chain config corresponding to the tangerine hardfork.
	Tangerine // tangerine
	// Spurious is the chain config corresponding to the spurious hardfork.
	Spurious // spuriousdragon
	// Byzantium is the chain config corresponding to the byzantium hardfork.
	Byzantium // byzantium
	// Constantinople is the chain config corresponding to the constantinople hardfork.
	Constantinople // constantinople
	// Petersburg is the chain config corresponding to the petersburg hardfork.
	Petersburg // petersburg
	// Istanbul is the chain config corresponding to the istanbul hardfork.
	Istanbul // istanbul
	// MuirGlacier is the chain config corresponding to the muir glacier hardfork.
	MuirGlacier // muirglacier
	// Berlin is the chain config corresponding to the berlin hardfork.
	Berlin // berlin
	// London is the chain config corresponding to the london hardfork.
	London // london
	// ArrowGlacier is the chain config corresponding to the arrow glacier hardfork.
	ArrowGlacier // arrowglacier
	// GrayGlacier is the chain config corresponding to the glay glacier hardfork.
	GrayGlacier // grayglacier
	// Latest is the chain config corresponding to the latest hardfork.
	// the int of this is not correct (1 to hig), but it is not used in foundry option builder.
	Latest // latest
)

func (Hardfork) String

func (i Hardfork) String() string

func (Hardfork) ToChainConfig

func (h Hardfork) ToChainConfig(chainID *big.Int) *params.ChainConfig

ToChainConfig converts the hardfork to a chain config. it makes the assumption that the blocks start at 0 since we can't easily make assumptions about the underlying chain and this is used for tx submission only going forward. nolint: cyclop

type OptionBuilder

type OptionBuilder struct {
	// contains filtered or unexported fields
}

OptionBuilder is a builder for anvil options.

func NewAnvilOptionBuilder

func NewAnvilOptionBuilder() *OptionBuilder

NewAnvilOptionBuilder creates a new option builder.

func (*OptionBuilder) Build

func (o *OptionBuilder) Build() (args []string, err error)

Build converts the option builder into a list of command line parameters. for use in anvil.

func (*OptionBuilder) GetAccounts

func (o *OptionBuilder) GetAccounts() uint8

GetAccounts gets the number of accounts to use.

func (*OptionBuilder) GetDerivationPath

func (o *OptionBuilder) GetDerivationPath() accounts.DerivationPath

GetDerivationPath returns the derivation path to use for the Accounts.

func (*OptionBuilder) GetHardfork

func (o *OptionBuilder) GetHardfork() Hardfork

GetHardfork returns the Hardfork to use for the chain.

func (*OptionBuilder) GetMnemonic

func (o *OptionBuilder) GetMnemonic() string

GetMnemonic returns the mnemonic to use for the chain.

func (*OptionBuilder) OtterscanEnabled added in v0.0.119

func (o *OptionBuilder) OtterscanEnabled(enabled bool)

OtterscanEnabled sets whether or not to enable otterscan. Note: for this to work correctly, the underlying node we fork from must also support the ots namespace.

func (*OptionBuilder) SetAccounts

func (o *OptionBuilder) SetAccounts(accountCount uint8)

SetAccounts sets the number of Accounts to create (defaults to 10).

func (*OptionBuilder) SetAllowOrigin

func (o *OptionBuilder) SetAllowOrigin(allowOrigin string)

SetAllowOrigin sets the allow origin for the chain. defaults to "*".

func (*OptionBuilder) SetBalance

func (o *OptionBuilder) SetBalance(balance uint64)

SetBalance sets the Balance of each account in ether (defaults to 1000 ether).

func (*OptionBuilder) SetBaseFee

func (o *OptionBuilder) SetBaseFee(baseFee uint64)

SetBaseFee sets the base fee for the chain.

func (*OptionBuilder) SetBlockBaseFeePerGas

func (o *OptionBuilder) SetBlockBaseFeePerGas(baseFee uint64)

SetBlockBaseFeePerGas sets the block base fee per gas for the chain.

func (*OptionBuilder) SetBlockTime

func (o *OptionBuilder) SetBlockTime(blockTime time.Duration)

SetBlockTime sets the block time (defaults to 1 second). if block time is 0 or less than a second, no mining is used.

func (*OptionBuilder) SetChainID

func (o *OptionBuilder) SetChainID(chainID uint64)

SetChainID sets the chain id to use in foundry.

func (*OptionBuilder) SetCodeSizeLimit

func (o *OptionBuilder) SetCodeSizeLimit(codeSizeLimit uint64)

SetCodeSizeLimit sets the code size limit for the chain.

func (*OptionBuilder) SetComputeUnitsPerSecond

func (o *OptionBuilder) SetComputeUnitsPerSecond(units uint64)

SetComputeUnitsPerSecond sets the CUPS per second, see: https://docs.alchemy.com/reference/compute-units

func (*OptionBuilder) SetDerivationPath

func (o *OptionBuilder) SetDerivationPath(derivationPath accounts.DerivationPath)

SetDerivationPath sets the derivation path to use for the Accounts. defaults to m/44'/60'/0'/0.

func (*OptionBuilder) SetDisableCors

func (o *OptionBuilder) SetDisableCors(disableCors bool)

SetDisableCors disables cors for the chain.

func (*OptionBuilder) SetExpirySeconds added in v0.0.59

func (o *OptionBuilder) SetExpirySeconds(expirySeconds uint)

SetExpirySeconds sets the expiry seconds for the docker containers(s) to be removed.

func (*OptionBuilder) SetForkBlockNumber

func (o *OptionBuilder) SetForkBlockNumber(block uint64)

SetForkBlockNumber sets the fork block number to use for the chain. only valid if SetForkURL is also called.

func (*OptionBuilder) SetForkRetryBackoff

func (o *OptionBuilder) SetForkRetryBackoff(backoff uint)

SetForkRetryBackoff sets the fork retry backoff to use for the chain.

func (*OptionBuilder) SetForkURL

func (o *OptionBuilder) SetForkURL(url string) error

SetForkURL sets the fork URL to use for the chain.

func (*OptionBuilder) SetGasLimit

func (o *OptionBuilder) SetGasLimit(gasLimit uint64)

SetGasLimit sets the gas limit per block for the chain.

func (*OptionBuilder) SetGasPrice

func (o *OptionBuilder) SetGasPrice(gasPrice uint64)

SetGasPrice sets the gas price for the chain.

func (*OptionBuilder) SetHardfork

func (o *OptionBuilder) SetHardfork(hardfork Hardfork) error

SetHardfork sets the Hardfork to use for the chain.

func (*OptionBuilder) SetHost

func (o *OptionBuilder) SetHost(host string)

SetHost sets the host to listen on.

func (*OptionBuilder) SetIPC

func (o *OptionBuilder) SetIPC(path string) error

SetIPC sets the IPC path to use for the chain. This option is not currently supported.

func (*OptionBuilder) SetInit

func (o *OptionBuilder) SetInit(_ string) error

SetInit sets the genesis file to use for the chain. Warning: this option is not currently supported.

func (*OptionBuilder) SetMaxWaitTime added in v0.0.59

func (o *OptionBuilder) SetMaxWaitTime(maxWait time.Duration)

SetMaxWaitTime sets the max wait time for the docker container(s) to start.

func (*OptionBuilder) SetMnemonic

func (o *OptionBuilder) SetMnemonic(mnemonic string) error

SetMnemonic sets the mnemonic to use for the chain.

func (*OptionBuilder) SetNoMining

func (o *OptionBuilder) SetNoMining(noMining bool)

SetNoMining sets whether or not to mine blocks. this is automatically set and must be disabled for other options to be sent. if disabled, this can cause concurrency issues since only one account can be impersonated at a time.

func (*OptionBuilder) SetOrder

func (o *OptionBuilder) SetOrder(order Order) error

SetOrder sets the transaction Order to use for the chain. Defaults to Fees.

func (*OptionBuilder) SetProcessLogOptions added in v0.0.76

func (o *OptionBuilder) SetProcessLogOptions(customOpts ...processlog.StdStreamLogArgsOption)

SetProcessLogOptions sets the process log options for the docker container(s).

func (*OptionBuilder) SetPruneHistory

func (o *OptionBuilder) SetPruneHistory(pruneHistory bool)

SetPruneHistory enables or disables pruning of history. defaults to false.

func (*OptionBuilder) SetRateLimitUnitsPerSecondEnabled

func (o *OptionBuilder) SetRateLimitUnitsPerSecondEnabled(enabled bool)

SetRateLimitUnitsPerSecondEnabled enables or disables rate limiting of CUPS.

func (*OptionBuilder) SetRestartPolicy added in v0.0.61

func (o *OptionBuilder) SetRestartPolicy(restartPolicy RestartPolicy)

SetRestartPolicy sets the restart policy for the docker container(s).

func (*OptionBuilder) SetRetries

func (o *OptionBuilder) SetRetries(retries uint16)

SetRetries sets the number of retries to use for forked rpc requests.

func (*OptionBuilder) SetSilent

func (o *OptionBuilder) SetSilent(silent bool)

SetSilent enables or disables Silent boot.

func (*OptionBuilder) SetStepsTracing

func (o *OptionBuilder) SetStepsTracing(enabled bool)

SetStepsTracing enables or disables steps tracing. Defaults to enabled.

func (*OptionBuilder) SetStorageCachingEnabled

func (o *OptionBuilder) SetStorageCachingEnabled(enabled bool)

SetStorageCachingEnabled enables or disables storage caching.

func (*OptionBuilder) SetTimeout

func (o *OptionBuilder) SetTimeout(timeout time.Duration)

SetTimeout sets the timeout to use for forked rpc requests in milliseconds.

func (*OptionBuilder) SetTimestamp

func (o *OptionBuilder) SetTimestamp(timestamp uint64)

SetTimestamp sets the Timestamp of the genesis block. This option is ignored if set to 0.

type Order

type Order uint8

Order is the Order of transactions to use. see: https://github.com/foundry-rs/foundry/blob/master/anvil/src/eth/pool/transactions.rs#L56

const (
	// Fees orders transactions by fees in the mempool.
	Fees Order = iota + 1 // fees
	// Fifo orders transactions by first in first out in the mempool ignoring fees.
	Fifo // fifo
)

func (Order) String

func (i Order) String() string

type RestartPolicy added in v0.0.61

type RestartPolicy string

RestartPolicy defines the restart policy for the docker container.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL