w3

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2022 License: MIT Imports: 13 Imported by: 23

README

w3

Go Reference Go Report Card

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

  • Modular API allows to create custom RPC method integrations that can be used alongside the methods implemented by the package.
  • Batch request support significantly reduces the duration of requests to both remote and local endpoints.
  • ABI bindings are specified for individual functions with Solidity syntax. No need for abigen and ABI JSON files.

Install

go get github.com/lmittmann/w3@latest

Getting Started

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

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

	// Declare a Smart Contract function with 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).Returns(&ethBalance),
	eth.CallFunc(balanceOf, weth9, addr).Returns(&weth9Balance),
); err != nil {
	fmt.Printf("Requst failed: %v\n", err)
	return
}

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

Documentation

Overview

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

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrRequestCreation is returned by Client.CallCtx and Client.Call when the
	// creation of the RPC request failes.
	ErrRequestCreation = errors.New("w3: request creation failed")

	// ErrResponseHandling is returned by Client.CallCtx and Client.Call when
	// the handeling of the RPC response failes.
	ErrResponseHandling = errors.New("w3: response handling failed")
)
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     = big.NewInt(0)
	Big1     = big.NewInt(1)
	Big2     = big.NewInt(2)
	BigGwei  = big.NewInt(1_000000000)
	BigEther = big.NewInt(1_000000000_000000000)
)

Common big.Int's.

Functions

func A

func A(hexAddress string) common.Address

A returns an address from a hexstring. It is short for common.HexToAddress(…).

func APtr

func APtr(hexAddress string) *common.Address

APtr returns an address pointer from a hexstring. The returned address is nil, if the hexstring address equals the zero address 0x00…00.

func B

func B(hexBytes string) []byte

B returns a byte slice from a hexstring. It is short for common.FromHex(…).

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) common.Hash

H returns a hash from a hexstring. It is short for common.HexToHash(…).

func I

func I(strInt string) *big.Int

I returns a big.Int from a number string in decimal or hex format. Nil is returned if the number parsing fails.

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

w3.I("1 ether")   -> 1000000000000000000
w3.I("1.2 ether") -> 1200000000000000000

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("0x2b98d99b09e3c000"))
	fmt.Printf("%v wei\n", w3.I("3141500000000000000"))
	fmt.Printf("%v wei\n", w3.I("3.1415 ether"))
	fmt.Printf("%v wei\n", w3.I("31.415 gwei"))

}
Output:

3141500000000000000 wei
3141500000000000000 wei
3141500000000000000 wei
31415000000 wei

func Keccak

func Keccak(data []byte) common.Hash

Keccak returns the Keccak256 hash of data. It is short for crypto.Keccak256Hash(…)

Types

type Client

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

Client represents a connection to an RPC endpoint.

func Dial

func Dial(rawurl string) (*Client, error)

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

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.

Example
package main

import (
	"log"

	"github.com/lmittmann/w3"
)

func main() {
	client, err := w3.Dial("https://cloudflare-eth.com")
	if err != nil {
		log.Fatalf("Failed to connect to RPC endpoint: %v", err)
	}
	defer client.Close()
}
Output:

func MustDial

func MustDial(rawurl string) *Client

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

func NewClient

func NewClient(client *rpc.Client) *Client

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

func (*Client) Call

func (c *Client) Call(requests ...core.RequestCreaterResponseHandler) error

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

Example
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://cloudflare-eth.com")
	defer client.Close()

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

		// Declare a Smart Contract function with 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).Returns(&ethBalance),
		eth.CallFunc(balanceOf, weth9, addr).Returns(&weth9Balance),
	); err != nil {
		fmt.Printf("Requst failed: %v\n", err)
		return
	}

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

func (*Client) CallCtx

func (c *Client) CallCtx(ctx context.Context, requests ...core.RequestCreaterResponseHandler) 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 handeling 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 Func added in v0.1.1

type Func struct {
	Signature string        // Function signature
	Selector  [4]byte       // 4-byte selector
	Args      abi.Arguments // Input arguments
	Returns   abi.Arguments // Output returns
}

Func represents a Smart Contract function ABI binding.

Func implements the core.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
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

func (*Func) DecodeArgs added in v0.1.1

func (f *Func) DecodeArgs(input []byte, args ...interface{}) 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 ...interface{}) error

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

func (*Func) EncodeArgs added in v0.1.1

func (f *Func) EncodeArgs(args ...interface{}) ([]byte, error)

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

Directories

Path Synopsis
internal
abi
rpctest
Package rpctest provides utilities for RPC testing.
Package rpctest provides utilities for RPC testing.
module
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.

Jump to

Keyboard shortcuts

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