ethutil

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2021 License: MIT Imports: 22 Imported by: 22

Documentation

Overview

Package ethutil provides utilities used for dealing with Ethereum concerns in the context of implementing cross-chain interfaces defined in pkg/chain.

Index

Constants

View Source
const (
	// DefaultSubscribeOptsTick is the default duration with which
	// past events are pulled from the chain by the subscription monitoring
	// mechanism if no other value is provided in SubscribeOpts when creating
	// the subscription.
	DefaultSubscribeOptsTick = 15 * time.Minute

	// DefaultSubscribeOptsPastBlocks is the default number of past blocks
	// pulled from the chain by the subscription monitoring mechanism if no
	// other value is provided in SubscribeOpts when creating the subscription.
	DefaultSubscribeOptsPastBlocks = 100

	// SubscriptionBackoffMax is the maximum backoff time between event
	// resubscription attempts.
	SubscriptionBackoffMax = 2 * time.Minute

	// SubscriptionAlertThreshold is time threshold below which event
	// resubscription emits an error to the logs.
	// WS connection can be dropped at any moment and event resubscription will
	// follow. However, if WS connection for event subscription is getting
	// dropped too often, it may indicate something is wrong with Ethereum
	// client. This constant defines the minimum lifetime of an event
	// subscription required before the subscription failure happens and
	// resubscription follows so that the resubscription does not emit an error
	// to the logs alerting about potential problems with Ethereum client
	// connection.
	SubscriptionAlertThreshold = 15 * time.Minute
)
View Source
const SignatureSize = 65

SignatureSize is a byte size of a signature calculated by Ethereum with recovery-id, V, included. The signature consists of three values (R,S,V) in the following order: R = [0:31] S = [32:63] V = [64]

Variables

This section is empty.

Functions

func AddressFromHex

func AddressFromHex(hex string) (common.Address, error)

AddressFromHex converts the passed string to a common.Address and returns it, unless it is not a valid address, in which case it returns an error. Compare to common.HexToAddress, which assumes the address is valid and does not provide for an error return.

func CallAtBlock

func CallAtBlock(
	fromAddress common.Address,
	blockNumber *big.Int,
	value *big.Int,
	contractABI *abi.ABI,
	caller bind.ContractCaller,
	errorResolver *ErrorResolver,
	contractAddress common.Address,
	method string,
	result interface{},
	parameters ...interface{},
) error

CallAtBlock allows the invocation of a particular contract method at a particular block. It papers over the fact that abigen bindings don't directly support calling at a particular block, and is mostly meant for use from generated contract code.

func ConnectClients

func ConnectClients(url string, urlRPC string) (*ethclient.Client, *rpc.Client, *rpc.Client, error)

ConnectClients takes HTTP and RPC URLs and returns initialized versions of standard, WebSocket, and RPC clients for the Ethereum node at that address.

func DecryptKeyFile

func DecryptKeyFile(keyFile, password string) (*keystore.Key, error)

DecryptKeyFile reads in a key file and uses the password to decrypt it.

func EstimateGas

func EstimateGas(
	from common.Address,
	to common.Address,
	method string,
	contractABI *abi.ABI,
	transactor bind.ContractTransactor,
	parameters ...interface{},
) (uint64, error)

EstimateGas tries to estimate the gas needed to execute a specific transaction based on the current pending state of the backend blockchain. There is no guarantee that this is the true gas limit requirement as other transactions may be added or removed by miners, but it should provide a basis for setting a reasonable default.

func NewBlockCounter added in v1.5.0

func NewBlockCounter(client EthereumClient) (*ethlike.BlockCounter, error)

NewBlockCounter creates a new BlockCounter instance for the provided Ethereum client.

func NewKeyedTransactorWithChainID added in v1.5.0

func NewKeyedTransactorWithChainID(
	privateKey *ecdsa.PrivateKey,
	chainID *big.Int,
) (*bind.TransactOpts, error)

NewKeyedTransactorWithChainID is a utility method to easily create a transaction signer from a single private key.

func NewMiningWaiter added in v1.1.0

func NewMiningWaiter(
	client EthereumClient,
	checkInterval time.Duration,
	maxGasPrice *big.Int,
) *ethlike.MiningWaiter

NewMiningWaiter creates a new MiningWaiter instance for the provided Ethereum client. It accepts two parameters setting up monitoring rules of the transaction mining status.

func NewNonceManager added in v1.0.0

func NewNonceManager(
	client EthereumClient,
	account common.Address,
) *ethlike.NonceManager

NewNonceManager creates NonceManager instance for the provided account using the provided Ethereum client.

func WithResubscription added in v1.4.0

func WithResubscription(
	backoffMax time.Duration,
	subscribeFn event.ResubscribeFunc,
	alertThreshold time.Duration,
	thresholdViolatedFn func(time.Duration),
	subscriptionFailedFn func(error),
) event.Subscription

WithResubscription wraps the subscribe function to call it repeatedly to keep a subscription alive. When a subscription is established, it is monitored and in the case of a failure, resubscribe is attempted by calling the subscribe function again.

The mechanism applies backoff between resubscription attempts. The time between calls is adapted based on the error rate, but will never exceed backoffMax.

The mechanism monitors the time elapsed between resubscription attempts and if it is shorter than the specificed alertThreshold, it calls thresholdViolatedFn passing the time elapsed between resubscription attempts. This function alarms about potential problems with the stability of the subscription.

In case of an error returned by the wrapped subscription function, subscriptionFailedFn is called with the underlying error.

thresholdViolatedFn and subscriptionFailedFn calls are executed in a separate goroutine and thus are non-blocking.

Types

type BalanceMonitor added in v1.5.0

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

BalanceMonitor provides the possibility to monitor balances for given accounts.

func NewBalanceMonitor added in v1.5.0

func NewBalanceMonitor(balanceSource BalanceSource) *BalanceMonitor

NewBalanceMonitor creates a new instance of the balance monitor.

func (*BalanceMonitor) Observe added in v1.5.0

func (bm *BalanceMonitor) Observe(
	ctx context.Context,
	address common.Address,
	alertThreshold *ethereum.Wei,
	tick time.Duration,
	retryTimeout time.Duration,
)

Observe starts a process which checks the address balance with the given tick and triggers an alert in case the balance falls below the alert threshold value. The balance check will be retried in case of an error up to the retry timeout.

type BalanceSource added in v1.5.0

type BalanceSource func(address common.Address) (*ethereum.Wei, error)

BalanceSource provides a balance info for the given address.

type ErrorResolver

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

ErrorResolver bundles up the bits needed to turn errors like "failed to estimate gas needed" that are triggered by contract reverts but don't include revert causes into proper revert error messages from a contract by calling the contract method without trying to commit it.

It has one method, ResolveError, that does the heavy lifting.

func NewErrorResolver

func NewErrorResolver(
	contractCaller ethereum.ContractCaller,
	abi *abi.ABI,
	address *common.Address,
) *ErrorResolver

NewErrorResolver returns an ErroResolver for the given Ethereum client, contract ABI, and contract address combination.

func (*ErrorResolver) ResolveError

func (er *ErrorResolver) ResolveError(
	originalErr error,
	from common.Address,
	value *big.Int,
	methodName string,
	parameters ...interface{},
) error

ResolveError resolves the given transaction error to a standard error that, if available, contains the error message the transaction produced when reverting.

ResolveError achieves this by re-calling the transaction (not submitting it for block inclusion, just calling it for its results). `value` is the value in gwei to send along with the simulated call.

type EthereumClient added in v1.3.0

type EthereumClient interface {
	bind.ContractBackend
	ethereum.ChainReader
	ethereum.TransactionReader

	BalanceAt(
		ctx context.Context,
		account common.Address,
		blockNumber *big.Int,
	) (*big.Int, error)
}

EthereumClient wraps the core `bind.ContractBackend` interface with some other interfaces allowing to expose additional methods provided by client implementations.

func WrapCallLogging

func WrapCallLogging(
	logger log.EventLogger,
	client EthereumClient,
) EthereumClient

WrapCallLogging wraps certain call-related methods on the given `client` with debug logging sent to the given `logger`. Actual functionality is delegated to the passed client.

func WrapRateLimiting added in v1.2.0

func WrapRateLimiting(
	client EthereumClient,
	config *rate.LimiterConfig,
) EthereumClient

WrapRateLimiting wraps the given contract backend with rate limiting capabilities with respect to the provided configuration. All types of requests to the contract are rate-limited, including view function calls.

type EthereumSigner added in v1.3.0

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

EthereumSigner provides functions to sign a message and verify a signature using the Ethereum-specific signature format. It also provides functions for conversion of a public key to an address.

func NewSigner added in v1.3.0

func NewSigner(privateKey *ecdsa.PrivateKey) *EthereumSigner

NewSigner creates a new EthereumSigner instance for the provided ECDSA private key.

func (*EthereumSigner) PublicKey added in v1.3.0

func (es *EthereumSigner) PublicKey() []byte

PublicKey returns byte representation of a public key for the private key signer was created with.

func (*EthereumSigner) PublicKeyBytesToAddress added in v1.3.0

func (es *EthereumSigner) PublicKeyBytesToAddress(publicKey []byte) []byte

PublicKeyBytesToAddress transforms the provided ECDSA public key in a bytes format into Ethereum address represented in bytes.

func (*EthereumSigner) PublicKeyToAddress added in v1.3.0

func (es *EthereumSigner) PublicKeyToAddress(publicKey ecdsa.PublicKey) []byte

PublicKeyToAddress transforms the provided ECDSA public key into Ethereum address represented in bytes.

func (*EthereumSigner) Sign added in v1.3.0

func (es *EthereumSigner) Sign(message []byte) ([]byte, error)

Sign signs the provided message using Ethereum-specific format.

func (*EthereumSigner) Verify added in v1.3.0

func (es *EthereumSigner) Verify(message []byte, signature []byte) (bool, error)

Verify verifies the provided message against a signature using the key EthereumSigner was created with. The signature has to be provided in Ethereum-specific format.

func (*EthereumSigner) VerifyWithPublicKey added in v1.3.0

func (es *EthereumSigner) VerifyWithPublicKey(
	message []byte,
	signature []byte,
	publicKey []byte,
) (bool, error)

VerifyWithPublicKey verifies the provided message against a signature and public key. The signature has to be provided in Ethereum-specific format.

type TransactionOptions

type TransactionOptions struct {
	// GasLimit specifies a gas limit to set on a transaction call; should be
	// ignored if set to 0.
	GasLimit uint64
	// GasPrice specifies a gas price to set on a transaction call; should be
	// ignored if set to nil.
	GasPrice *big.Int
}

TransactionOptions represents custom transaction options which can be used while invoking contracts methods.

func (TransactionOptions) Apply

func (to TransactionOptions) Apply(transactorOptions *bind.TransactOpts)

Apply takes a bind.TransactOpts pointer and applies the options described in TransactionOptions to it. Note that a GasLimit of 0 or a GasPrice of nil are not applied to the passed options; these values indicate that the options should remain unchanged.

Jump to

Keyboard shortcuts

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