w3

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2024 License: MIT Imports: 16 Imported by: 20

README

w3: Enhanced Ethereum Integration for Go

Go Reference Go Report Card Coverage Status Latest Release W3 Gopher

w3 is your toolbelt for integrating with Ethereum in Go. Closely linked to go‑ethereum, it provides an ergonomic wrapper for working with RPC, ABI's, and the EVM.

go get github.com/lmittmann/w3

At a Glance

  • Use w3.Client to connect to an RPC endpoint. The client features batch request support for up to 80x faster requests and easy extendibility. learn more ↗
  • Use w3vm.VM to simulate EVM execution with optional tracing and Mainnet state forking, or test Smart Contracts. learn more ↗
  • Use w3.Func and w3.Event to create ABI bindings from Solidity function and event signatures. learn more ↗
  • Use w3.A, w3.H, and many other utility functions to parse addresses, hashes, and other common types from strings. learn more ↗

Getting Started

RPC Client

w3.Client is a batch request focused RPC client that can be used to connect to an Ethereum node via HTTP, WebSocket, or IPC. Its modular API allows to create custom RPC method integrations that can be used alongside the common methods implemented by this package.

Example: Batch Request (Playground)

// 1. Connect to an RPC endpoint
client, err := w3.Dial("https://rpc.ankr.com/eth")
if err != nil {
    // handle error
}
defer client.Close()

// 2. Make a batch request
var (
    balance big.Int
    nonce   uint64
)
if err := client.Call(
    eth.Balance(addr, nil).Returns(&balance),
    eth.Nonce(addr, nil).Returns(&nonce),
); err != nil {
    // handle error
}

[!NOTE]

why send batch requests?

Most of the time you need to call multiple RPC methods to get the data you need. When you make separate requests per RPC call you need a single round trip to the server for each call. This can be slow, especially for remote endpoints. Batching multiple RPC calls into a single request only requires a single round trip, and speeds up RPC calls significantly.

Learn More
VM

w3vm.VM is a high-level EVM environment with a simple but powerful API to simulate EVM execution, test Smart Contracts, or trace transactions. It supports Mainnet state forking via RPC and state caching for faster testing.

Example: Simulate an Uniswap v3 swap (Playground)

// 1. Create a VM that forks the Mainnet state from the latest block,
// disables the base fee, and has a fake WETH balance and approval for the router
vm, err := w3vm.New(
    w3vm.WithFork(client, nil),
    w3vm.WithNoBaseFee(),
    w3vm.WithState(w3types.State{
        addrWETH: {Storage: w3types.Storage{
            w3vm.WETHBalanceSlot(addrEOA):               common.BigToHash(w3.I("1 ether")),
            w3vm.WETHAllowanceSlot(addrEOA, addrRouter): common.BigToHash(w3.I("1 ether")),
        }},
    }),
)
if err != nil {
    // handle error
}

// 2. Simulate a Uniswap v3 swap
receipt, err := vm.Apply(&w3types.Message{
    From: addrEOA,
    To:   &addrRouter,
    Func: funcExactInput,
    Args: []any{&ExactInputParams{
        Path:             encodePath(addrWETH, 500, addrUNI),
        Recipient:        addrEOA,
        Deadline:         big.NewInt(time.Now().Unix()),
        AmountIn:         w3.I("1 ether"),
        AmountOutMinimum: w3.Big0,
    }},
})
if err != nil {
    // handle error
}

// 3. Decode output amount
var amountOut *big.Int
if err := receipt.DecodeReturns(&amountOut); err != nil {
    // handle error
}
ABI Bindings

ABI bindings in w3 are specified for individual functions using Solidity syntax and are usable for any contract that supports that function.

Example: ABI binding for the ERC20 balanceOf function (Playground)

funcBalanceOf := w3.MustNewFunc("balanceOf(address)", "uint256")

Example: ABI binding for the Uniswap v4 swap function (Playground)

funcSwap := w3.MustNewFunc(`swap(
    (address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key,
    (bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96) params,
    bytes hookData
)`, "int256 delta")

A Func can be used to

Utils

Static addresses, hashes, bytes or integers can be parsed from (hex-)strings with the following utility functions that panic if the string is not valid.

addr := w3.A("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")
hash := w3.H("0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3")
bytes := w3.B("0x27c5342c")
amount := w3.I("12.34 ether")

Use go-ethereum/common to parse strings that may not be valid instead.

RPC Methods

List of supported RPC methods for w3.Client.

eth
Method Go Code
eth_blockNumber eth.BlockNumber().Returns(blockNumber *big.Int)
eth_call eth.Call(msg *w3types.Message, blockNumber *big.Int, overrides w3types.State).Returns(output *[]byte)
eth.CallFunc(contract common.Address, f w3types.Func, args ...any).Returns(returns ...any)
eth_chainId eth.ChainID().Returns(chainID *uint64)
eth_createAccessList eth.AccessList(msg *w3types.Message, blockNumber *big.Int).Returns(resp *eth.AccessListResponse)
eth_estimateGas eth.EstimateGas(msg *w3types.Message, blockNumber *big.Int).Returns(gas *uint64)
eth_gasPrice eth.GasPrice().Returns(gasPrice *big.Int)
eth_maxPriorityFeePerGas eth.GasTipCap().Returns(gasTipCap *big.Int)
eth_getBalance eth.Balance(addr common.Address, blockNumber *big.Int).Returns(balance *big.Int)
eth_getBlockByHash eth.BlockByHash(hash common.Hash).Returns(block *types.Block)
eth.HeaderByHash(hash common.Hash).Returns(header *types.Header)
eth_getBlockByNumber eth.BlockByNumber(number *big.Int).Returns(block *types.Block)
eth.HeaderByNumber(number *big.Int).Returns(header *types.Header)
eth_getBlockReceipts eth.BlockReceipts(blockNumber *big.Int).Returns(receipts *types.Receipts)
eth_getBlockTransactionCountByHash eth.BlockTxCountByHash(hash common.Hash).Returns(count *uint)
eth_getBlockTransactionCountByNumber eth.BlockTxCountByNumber(number *big.Int).Returns(count *uint)
eth_getCode eth.Code(addr common.Address, blockNumber *big.Int).Returns(code *[]byte)
eth_getLogs eth.Logs(q ethereum.FilterQuery).Returns(logs *[]types.Log)
eth_getStorageAt eth.StorageAt(addr common.Address, slot common.Hash, blockNumber *big.Int).Returns(storage *common.Hash)
eth_getTransactionByHash eth.Tx(hash common.Hash).Returns(tx *types.Transaction)
eth_getTransactionByBlockHashAndIndex eth.TxByBlockHashAndIndex(blockHash common.Hash, index uint).Returns(tx *types.Transaction)
eth_getTransactionByBlockNumberAndIndex eth.TxByBlockNumberAndIndex(blockNumber *big.Int, index uint).Returns(tx *types.Transaction)
eth_getTransactionCount eth.Nonce(addr common.Address, blockNumber *big.Int).Returns(nonce *uint)
eth_getTransactionReceipt eth.TxReceipt(txHash common.Hash).Returns(receipt *types.Receipt)
eth_sendRawTransaction eth.SendRawTx(rawTx []byte).Returns(hash *common.Hash)
eth.SendTx(tx *types.Transaction).Returns(hash *common.Hash)
eth_getUncleByBlockHashAndIndex eth.UncleByBlockHashAndIndex(hash common.Hash, index uint).Returns(uncle *types.Header)
eth_getUncleByBlockNumberAndIndex eth.UncleByBlockNumberAndIndex(number *big.Int, index uint).Returns(uncle *types.Header)
eth_getUncleCountByBlockHash eth.UncleCountByBlockHash(hash common.Hash).Returns(count *uint)
eth_getUncleCountByBlockNumber eth.UncleCountByBlockNumber(number *big.Int).Returns(count *uint)
debug
Method Go Code
debug_traceCall debug.TraceCall(msg *w3types.Message, blockNumber *big.Int, config *debug.TraceConfig).Returns(trace *debug.Trace)
debug.CallTraceCall(msg *w3types.Message, blockNumber *big.Int, overrides w3types.State).Returns(trace *debug.CallTrace)
debug_traceTransaction debug.TraceTx(txHash common.Hash, config *debug.TraceConfig).Returns(trace *debug.Trace)
debug.CallTraceTx(txHash common.Hash, overrides w3types.State).Returns(trace *debug.CallTrace)
txpool
Method Go Code
txpool_content txpool.Content().Returns(resp *txpool.ContentResponse)
txpool_contentFrom txpool.ContentFrom(addr common.Address).Returns(resp *txpool.ContentFromResponse)
txpool_status txpool.Status().Returns(resp *txpool.StatusResponse)
web3
Method Go Code
web3_clientVersion web3.ClientVersion().Returns(clientVersion *string)
Third Party RPC Method Packages
Package Description
github.com/lmittmann/flashbots Package flashbots implements RPC API bindings for the Flashbots relay and mev-geth.

Custom RPC Method Bindings

Custom RPC method bindings can be created by implementing the w3types.RPCCaller interface.

Example: RPC binding for the Otterscan ots_getTransactionBySenderAndNonce method (Playground)

// TxBySenderAndNonceFactory requests the senders transaction hash by the nonce.
func TxBySenderAndNonceFactory(sender common.Address, nonce uint64) w3types.RPCCallerFactory[common.Hash] {
    return &getTransactionBySenderAndNonceFactory{
        sender: sender,
        nonce:  nonce,
    }
}

// getTransactionBySenderAndNonceFactory implements the w3types.RPCCaller and
// w3types.RPCCallerFactory interfaces. It stores the method parameters and
// the the reference to the return value.
type getTransactionBySenderAndNonceFactory struct {
    // params
    sender common.Address
    nonce  uint64

    // returns
    returns *common.Hash
}

// Returns sets the reference to the return value.
func (f *getTransactionBySenderAndNonceFactory) Returns(txHash *common.Hash) w3types.RPCCaller {
    f.returns = txHash
    return f
}

// CreateRequest creates a batch request element for the Otterscan getTransactionBySenderAndNonce method.
func (f *getTransactionBySenderAndNonceFactory) CreateRequest() (rpc.BatchElem, error) {
    return rpc.BatchElem{
        Method: "ots_getTransactionBySenderAndNonce",
        Args:   []any{f.sender, f.nonce},
        Result: f.returns,
    }, nil
}

// HandleResponse handles the response of the Otterscan getTransactionBySenderAndNonce method.
func (f *getTransactionBySenderAndNonceFactory) HandleResponse(elem rpc.BatchElem) error {
    if err := elem.Error; err != nil {
        return err
    }
    return nil
}

Documentation

Overview

Package w3 implements a blazing fast and modular Ethereum JSON RPC client with first-class ABI support.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidABI       = errors.New("w3: invalid ABI")
	ErrArgumentMismatch = errors.New("w3: argument mismatch")
	ErrReturnsMismatch  = errors.New("w3: returns mismatch")
	ErrInvalidType      = errors.New("w3: invalid type")
	ErrEvmRevert        = errors.New("w3: evm reverted")
)
View Source
var (
	Big0          = new(big.Int)
	Big1          = big.NewInt(1)
	Big2          = big.NewInt(2)
	BigGwei       = big.NewInt(1_000000000)
	BigEther      = big.NewInt(1_000000000_000000000)
	BigMaxUint256 = new(big.Int).Sub(new(big.Int).Lsh(Big1, 256), Big1)
)

Common big.Int's.

Functions

func A

func A(hexAddress string) (addr common.Address)

A returns an address from a hexstring or panics if the hexstring does not represent a valid address.

Use common.HexToAddress to get the address from a hexstring without panicking.

func APtr

func APtr(hexAddress string) *common.Address

APtr returns an address pointer from a hexstring or panics if the hexstring does not represent a valid address.

func B

func B(hexBytes ...string) (bytes []byte)

B returns a byte slice from a hexstring or panics if the hexstring does not represent a valid byte slice.

Use common.FromHex to get the byte slice from a hexstring without panicking.

func FromWei

func FromWei(wei *big.Int, decimals uint8) string

FromWei returns the given Wei as decimal with the given number of decimals.

Example
package main

import (
	"fmt"
	"math/big"

	"github.com/lmittmann/w3"
)

func main() {
	wei := big.NewInt(1_230000000_000000000)
	fmt.Printf("%s Ether\n", w3.FromWei(wei, 18))
}
Output:

1.23 Ether

func H

func H(hexHash string) (hash common.Hash)

H returns a hash from a hexstring or panics if the hexstring does not represent a valid hash.

Use common.HexToHash to get the hash from a hexstring without panicking.

func I

func I(strInt string) *big.Int

I returns a big.Int from a hexstring or decimal number string (with optional unit) or panics if the parsing fails.

I supports the units "ether" or "eth" and "gwei" for decimal number strings. E.g.:

w3.I("1 ether")   -> 1000000000000000000
w3.I("10 gwei")   -> 10000000000

Fractional digits that exceed the units maximum number of fractional digits are ignored. E.g.:

w3.I("0.000000123456 gwei") -> 123
Example
package main

import (
	"fmt"

	"github.com/lmittmann/w3"
)

func main() {
	fmt.Printf("%v wei\n", w3.I("0x1111d67bb1bb0000"))
	fmt.Printf("%v wei\n", w3.I("1230000000000000000"))
	fmt.Printf("%v wei\n", w3.I("1.23 ether"))
	fmt.Printf("%v wei\n", w3.I("1.23 gwei"))
}
Output:

1230000000000000000 wei
1230000000000000000 wei
1230000000000000000 wei
1230000000 wei

Types

type CallErrors added in v0.10.0

type CallErrors []error

CallErrors is an error type that contains the errors of multiple calls. The length of the error slice is equal to the number of calls. Each error at a given index corresponds to the call at the same index. An error is nil if the corresponding call was successful.

func (CallErrors) Error added in v0.10.0

func (e CallErrors) Error() string

func (CallErrors) Is added in v0.10.0

func (e CallErrors) Is(target error) bool

type Client

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

Client represents a connection to an RPC endpoint.

Example
package main

import (
	"fmt"
	"math/big"

	"github.com/lmittmann/w3"
	"github.com/lmittmann/w3/module/eth"
)

func main() {
	addr := w3.A("0x0000000000000000000000000000000000000000")

	// 1. Connect to an RPC endpoint
	client, err := w3.Dial("https://rpc.ankr.com/eth")
	if err != nil {
		// handle error
	}
	defer client.Close()

	// 2. Make a batch request
	var (
		balance big.Int
		nonce   uint64
	)
	if err := client.Call(
		eth.Balance(addr, nil).Returns(&balance),
		eth.Nonce(addr, nil).Returns(&nonce),
	); err != nil {
		// handle error
	}

	fmt.Printf("balance: %s\nnonce: %d\n", w3.FromWei(&balance, 18), nonce)
}
Output:

func Dial

func Dial(rawurl string, opts ...Option) (*Client, error)

Dial returns a new Client connected to the URL rawurl. An error is returned if the connection establishment fails.

The supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a file name with no URL scheme, a local IPC socket connection is established.

func MustDial

func MustDial(rawurl string, opts ...Option) *Client

MustDial is like Dial but panics if the connection establishment fails.

func NewClient

func NewClient(client *rpc.Client, opts ...Option) *Client

NewClient returns a new Client given an rpc.Client client.

func (*Client) Call

func (c *Client) Call(calls ...w3types.RPCCaller) error

Call is like Client.CallCtx with ctx equal to context.Background().

Example (BalanceOf)
package main

import (
	"fmt"
	"math/big"

	"github.com/lmittmann/w3"
	"github.com/lmittmann/w3/module/eth"
)

func main() {
	// Connect to RPC endpoint (or panic on error) and
	// close the connection when you are done.
	client := w3.MustDial("https://rpc.ankr.com/eth")
	defer client.Close()

	var (
		addr  = w3.A("0x000000000000000000000000000000000000dEaD")
		weth9 = w3.A("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")

		// Declare a Smart Contract function using Solidity syntax,
		// no "abigen" and ABI JSON file needed.
		balanceOf = w3.MustNewFunc("balanceOf(address)", "uint256")

		// Declare variables for the RPC responses.
		ethBalance   big.Int
		weth9Balance big.Int
	)

	// Do batch request (both RPC requests are send in the same
	// HTTP request).
	if err := client.Call(
		eth.Balance(addr, nil).Returns(&ethBalance),
		eth.CallFunc(weth9, balanceOf, addr).Returns(&weth9Balance),
	); err != nil {
		fmt.Printf("Request failed: %v\n", err)
		return
	}

	fmt.Printf("Combined balance: %v wei",
		new(big.Int).Add(&ethBalance, &weth9Balance),
	)
}
Output:

Example (NonceAndBalance)
package main

import (
	"fmt"
	"math/big"

	"github.com/lmittmann/w3"
	"github.com/lmittmann/w3/module/eth"
)

func main() {
	client := w3.MustDial("https://rpc.ankr.com/eth")
	defer client.Close()

	var (
		addr = w3.A("0x000000000000000000000000000000000000c0Fe")

		nonce   uint64
		balance big.Int
	)

	if err := client.Call(
		eth.Nonce(addr, nil).Returns(&nonce),
		eth.Balance(addr, nil).Returns(&balance),
	); err != nil {
		fmt.Printf("Request failed: %v\n", err)
		return
	}

	fmt.Printf("%s: Nonce: %d, Balance: ♦%s\n", addr, nonce, w3.FromWei(&balance, 18))
}
Output:

Example (SendERC20transferTx)
package main

import (
	"fmt"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/params"
	"github.com/lmittmann/w3"
	"github.com/lmittmann/w3/module/eth"
)

func main() {
	client := w3.MustDial("https://rpc.ankr.com/eth")
	defer client.Close()

	var (
		weth9     = w3.A("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")
		receiver  = w3.A("0x000000000000000000000000000000000000c0Fe")
		eoaPrv, _ = crypto.GenerateKey()
	)

	funcTransfer := w3.MustNewFunc("transfer(address receiver, uint256 amount)", "bool")
	input, err := funcTransfer.EncodeArgs(receiver, w3.I("1 ether"))
	if err != nil {
		fmt.Printf("Failed to encode args: %v\n", err)
		return
	}

	signer := types.LatestSigner(params.MainnetChainConfig)
	var txHash common.Hash
	if err := client.Call(
		eth.SendTx(types.MustSignNewTx(eoaPrv, signer, &types.DynamicFeeTx{
			Nonce:     0,
			To:        &weth9,
			Data:      input,
			GasTipCap: w3.I("1 gwei"),
			GasFeeCap: w3.I("100 gwei"),
			Gas:       100_000,
		})).Returns(&txHash),
	); err != nil {
		fmt.Printf("Failed to send tx: %v\n", err)
		return
	}

	fmt.Printf("Sent tx: %s\n", txHash)
}
Output:

func (*Client) CallCtx

func (c *Client) CallCtx(ctx context.Context, calls ...w3types.RPCCaller) error

CallCtx creates the final RPC request, sends it, and handles the RPC response.

An error is returned if RPC request creation, networking, or RPC response handling fails.

func (*Client) Close

func (c *Client) Close() error

Close closes the RPC connection and cancels any in-flight requests.

Close implements the io.Closer interface.

type Event added in v0.3.0

type Event struct {
	Signature string        // Event signature
	Topic0    common.Hash   // Hash of event signature (Topic 0)
	Args      abi.Arguments // Arguments
	// contains filtered or unexported fields
}

Event represents a Smart Contract event decoder.

func MustNewEvent added in v0.3.0

func MustNewEvent(signature string) *Event

MustNewEvent is like NewEvent but panics if the signature parsing fails.

func NewEvent added in v0.3.0

func NewEvent(signature string) (*Event, error)

NewEvent returns a new Smart Contract event log decoder from the given Solidity event signature.

An error is returned if the signature parsing fails.

func (*Event) DecodeArgs added in v0.3.0

func (e *Event) DecodeArgs(log *types.Log, args ...any) error

DecodeArgs decodes the topics and data of the given log to the given args.

Example
package main

import (
	"fmt"
	"math/big"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/lmittmann/w3"
)

func main() {
	var (
		eventTransfer = w3.MustNewEvent("Transfer(address indexed from, address indexed to, uint256 value)")
		log           = &types.Log{
			Address: w3.A("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
			Topics: []common.Hash{
				w3.H("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"),
				w3.H("0x000000000000000000000000000000000000000000000000000000000000c0fe"),
				w3.H("0x000000000000000000000000000000000000000000000000000000000000dead"),
			},
			Data: w3.B("0x0000000000000000000000000000000000000000000000001111d67bb1bb0000"),
		}

		from  common.Address
		to    common.Address
		value big.Int
	)

	if err := eventTransfer.DecodeArgs(log, &from, &to, &value); err != nil {
		fmt.Printf("Failed to decode event log: %v\n", err)
		return
	}
	fmt.Printf("Transferred %s WETH9 from %s to %s", w3.FromWei(&value, 18), from, to)
}
Output:

Transferred 1.23 WETH9 from 0x000000000000000000000000000000000000c0Fe to 0x000000000000000000000000000000000000dEaD

type Func added in v0.1.1

type Func struct {
	Signature string        // Function signature
	Selector  [4]byte       // 4-byte selector
	Args      abi.Arguments // Arguments (input)
	Returns   abi.Arguments // Returns (output)
	// contains filtered or unexported fields
}

Func represents a Smart Contract function ABI binding.

Func implements the w3types.Func interface.

func MustNewFunc

func MustNewFunc(signature, returns string) *Func

MustNewFunc is like NewFunc but panics if the signature or returns parsing fails.

func NewFunc

func NewFunc(signature, returns string) (*Func, error)

NewFunc returns a new Smart Contract function ABI binding from the given Solidity function signature and its returns.

An error is returned if the signature or returns parsing fails.

Example (BalanceOf)
package main

import (
	"fmt"
	"math/big"

	"github.com/ethereum/go-ethereum/common"
	"github.com/lmittmann/w3"
)

func main() {
	// ABI binding to the balanceOf function of an ERC20 Token.
	funcBalanceOf, _ := w3.NewFunc("balanceOf(address)", "uint256")

	// Optionally names can be specified for function arguments. This is
	// especially useful for more complex functions with many arguments.
	funcBalanceOf, _ = w3.NewFunc("balanceOf(address who)", "uint256 amount")

	// ABI-encode the functions args.
	input, _ := funcBalanceOf.EncodeArgs(w3.A("0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B"))
	fmt.Printf("balanceOf input: 0x%x\n", input)

	// ABI-decode the functions args from a given input.
	var (
		who common.Address
	)
	funcBalanceOf.DecodeArgs(input, &who)
	fmt.Printf("balanceOf args: %v\n", who)

	// ABI-decode the functions output.
	var (
		output = w3.B("0x000000000000000000000000000000000000000000000000000000000000c0fe")
		amount = new(big.Int)
	)
	funcBalanceOf.DecodeReturns(output, amount)
	fmt.Printf("balanceOf returns: %v\n", amount)
}
Output:

balanceOf input: 0x70a08231000000000000000000000000ab5801a7d398351b8be11c439e05c5b3259aec9b
balanceOf args: 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B
balanceOf returns: 49406
Example (UniswapV4Swap)
package main

import (
	"fmt"
	"math/big"

	"github.com/ethereum/go-ethereum/common"
	"github.com/lmittmann/w3"
)

func main() {
	// ABI binding for the Uniswap v4 swap function.
	funcSwap, _ := w3.NewFunc(`swap(
		(address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key,
		(bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96) params,
		bytes hookData
	)`, "int256 delta")

	// ABI binding for the PoolKey struct.
	type PoolKey struct {
		Currency0   common.Address
		Currency1   common.Address
		Fee         *big.Int
		TickSpacing *big.Int
		Hooks       common.Address
	}

	// ABI binding for the SwapParams struct.
	type SwapParams struct {
		ZeroForOne        bool
		AmountSpecified   *big.Int
		SqrtPriceLimitX96 *big.Int
	}

	// ABI-encode the functions args.
	input, _ := funcSwap.EncodeArgs(
		&PoolKey{
			Currency0:   w3.A("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
			Currency1:   w3.A("0x6B175474E89094C44Da98b954EedeAC495271d0F"),
			Fee:         big.NewInt(0),
			TickSpacing: big.NewInt(0),
		},
		&SwapParams{
			ZeroForOne:        false,
			AmountSpecified:   big.NewInt(0),
			SqrtPriceLimitX96: big.NewInt(0),
		},
		[]byte{},
	)
	fmt.Printf("swap input: 0x%x\n", input)
}
Output:

swap input: 0xf3cd914c000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000006b175474e89094c44da98b954eedeac495271d0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000000

func (*Func) DecodeArgs added in v0.1.1

func (f *Func) DecodeArgs(input []byte, args ...any) error

DecodeArgs ABI-decodes the given input to the given args.

func (*Func) DecodeReturns added in v0.1.1

func (f *Func) DecodeReturns(output []byte, returns ...any) error

DecodeReturns ABI-decodes the given output to the given returns.

func (*Func) EncodeArgs added in v0.1.1

func (f *Func) EncodeArgs(args ...any) ([]byte, error)

EncodeArgs ABI-encodes the given args and prepends the Func's 4-byte selector.

type Option added in v0.12.0

type Option func(*Client)

An Option configures a Client.

func WithRateLimiter added in v0.12.0

func WithRateLimiter(rl *rate.Limiter, costFunc func(methods []string) (cost int)) Option

WithRateLimiter sets the rate limiter for the client. Set the optional argument costFunc to nil to limit the number of requests. Supply a costFunc to limit the the number of requests based on individual RPC calls for advanced rate limiting by e.g. Compute Units (CUs). Note that only if len(methods) > 1, the calls are sent in a batch request.

Example
package main

import (
	"time"

	"github.com/lmittmann/w3"
	"golang.org/x/time/rate"
)

func main() {
	// Limit the client to 30 requests per second and allow bursts of up to
	// 100 requests.
	client := w3.MustDial("https://rpc.ankr.com/eth",
		w3.WithRateLimiter(rate.NewLimiter(rate.Every(time.Second/30), 100), nil),
	)
	defer client.Close()
}
Output:

Example (CostFunc)
package main

import (
	"time"

	"github.com/lmittmann/w3"
	"golang.org/x/time/rate"
)

func main() {
	// Limit the client to 30 calls per second and allow bursts of up to
	// 100 calls using a cost function. Batch requests have an additional charge.
	client := w3.MustDial("https://rpc.ankr.com/eth",
		w3.WithRateLimiter(rate.NewLimiter(rate.Every(time.Second/30), 100),
			func(methods []string) (cost int) {
				cost = len(methods) // charge 1 CU per call
				if len(methods) > 1 {
					cost += 1 // charge 1 CU extra for the batch itself
				}
				return cost
			},
		))
	defer client.Close()
}
Output:

Directories

Path Synopsis
abi
Package abi implements a Solidity ABI lexer and parser.
Package abi implements a Solidity ABI lexer and parser.
mod
module
debug
Package debug implements RPC API bindings for methods in the "debug" namespace.
Package debug implements RPC API bindings for methods in the "debug" namespace.
eth
Package eth implements RPC API bindings for methods in the "eth" namespace.
Package eth implements RPC API bindings for methods in the "eth" namespace.
txpool
Package txpool implements RPC API bindings for methods in the "txpool" namespace.
Package txpool implements RPC API bindings for methods in the "txpool" namespace.
web3
Package web3 implements RPC API bindings for methods in the "web3" namespace.
Package web3 implements RPC API bindings for methods in the "web3" namespace.
Package rpctest provides utilities for testing RPC methods.
Package rpctest provides utilities for testing RPC methods.
Package w3types implements common types.
Package w3types implements common types.
Package w3vm provides a VM for executing EVM messages.
Package w3vm provides a VM for executing EVM messages.

Jump to

Keyboard shortcuts

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