web3

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 37 Imported by: 4 modules, 5 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

██╗    ██╗███████╗██████╗ ██████╗      ██████╗██╗     ██╗
██║    ██║██╔════╝██╔══██╗╚════██╗    ██╔════╝██║     ██║
██║ █╗ ██║█████╗  ██████╔╝ █████╔╝    ██║     ██║     ██║
██║███╗██║██╔══╝  ██╔══██╗ ╚═══██╗    ██║     ██║     ██║
╚███╔███╔╝███████╗██████╔╝██████╔╝    ╚██████╗███████╗██║
 ╚══╝╚══╝ ╚══════╝╚═════╝ ╚═════╝      ╚═════╝╚══════╝╚═╝

Zero-CGO, pure-Go command-line tool and SDK (package web3) for interacting with EVM blockchains — GoChain, Ethereum, Base, Arbitrum, Optimism, Polygon, BNB Chain, Avalanche, Sepolia, and more.

API Reference Test Release

web3 --help
NAME:
   web3 - Modern EVM & Web3 command-line tool

USAGE:
   web3 [global options] command [command options] [arguments...]

COMMANDS:
   block, bl        Block details for a block number (decimal) or hash (0x...). Omit for latest.
   transaction, tx  Transaction details for a tx hash
   receipt, rc      Transaction receipt for a tx hash
   address, addr    Account details for an address or WEB3_PRIVATE_KEY
   balance          Get native or ERC20 token balance for an address or WEB3_PRIVATE_KEY
   storage          Read a 32-byte contract storage slot (eth_getStorageAt)
   logs             Query event logs (eth_getLogs) with optional ABI event decoding
   transfer, send   Transfer native coins (GO/ETH) or ERC20 tokens (e.g. `web3 transfer 1.5 to 0xADDRESS`)
   increasegas      Speed up a pending transaction by bumping its gas price / priority fee
   cancel           Cancel a pending transaction by sending a 0-value self-transfer at the same nonce with higher gas
   replace          Replace a pending transaction at a specific nonce
   contract, c      Smart contract build, deploy, call, verify, events, and EIP-1967 proxy operations
   generate, g      Generate OpenZeppelin v5 smart contracts or Go ABI bindings
   account, a       Create accounts and manage Web3 Secret Storage V3 keystores
   myaddress        Print the EIP-55 address derived from WEB3_PRIVATE_KEY
   sign             Sign a message using EIP-191 personal_sign
   verify-sig       Recover signer (and optionally verify address) for an EIP-191 personal_sign signature
   keccak, hash     Compute the Keccak-256 hash of UTF-8 text or --hex bytes
   encode, calldata ABI-encode function calldata offline
   decode           ABI-decode function calldata, return values (--output), or Solidity reverts (--revert)
   units            Convert an amount across wei, gwei, and eth/go
   snapshot, sn     Clique consensus snapshot
   id               Network/Chain ID and genesis hash information
   start            Start a local GoChain development node via Docker
   env              List WEB3_* environment variables
   help, h          Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --network value, -n value  Target network (arbitrum/avalanche/base/base-sepolia/bsc/ethereum/gochain/holesky/localhost/optimism/polygon/sepolia/testnet). Default: "gochain" [$WEB3_NETWORK]
   --testnet                  Shorthand for '--network testnet'
   --rpc-url value            Custom JSON-RPC HTTP(S) or WS(S) URL [$WEB3_RPC_URL]
   --verbose                  Enable verbose logging
   --format value, -f value   Output format: json (default: human-readable)
   --help, -h                 show help
   --version, -v              print the version

Features

  • Pure Go (CGO_ENABLED=0): Zero full-node dependencies, fast static builds on Linux, macOS, and Windows.
  • EIP-1559 & Legacy Transactions: Auto-detects EIP-1559 (Type 2) chains via baseFeePerGas and falls back to EIP-155 (Type 0) on legacy networks like GoChain.
  • Automatic Gas Estimation: Estimates gas via eth_estimateGas automatically whenever --gas-limit is omitted.
  • Full Solidity ABI Engine: Supports dynamic tuples/structs, slices, fixed arrays, function overloads, human-readable inline signatures, and Error(string) / Panic(uint256) / custom Solidity error revert decoding.
  • Standard EIP-1967 Upgradeable Proxies: Deploy, inspect (target, admin), upgrade (upgradeTo / upgradeToAndCall), pause, and resume standard EIP-1967 proxies recognized by Etherscan and Blockscout.
  • OpenZeppelin v5 Contract Generation: Scaffold ERC-20, ERC-721, and ERC-1155 contracts in one command.

Install web3

Quick one-line install:

curl -fsSL https://raw.githubusercontent.com/gochain/web3/master/install.sh | sh

Or install with Go (1.26+):

go install github.com/gochain/web3/cmd/web3@latest

Quickstart

1. Pick a network

Built-in --network (WEB3_NETWORK) presets:

  • gochain (default), testnet, localhost
  • ethereum, sepolia, holesky
  • base, base-sepolia, arbitrum, optimism, polygon, bsc, avalanche
# Local development node
web3 start
export WEB3_NETWORK=localhost

# Built-in network preset
export WEB3_NETWORK=base

# Or any custom HTTP(S) / WS(S) RPC endpoint
export WEB3_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY

2. Set Private Key (optional — only needed for signing/writing)

export WEB3_PRIVATE_KEY=0x...

3. Build, Deploy & Call a Contract

Copy hello.sol into your working directory, then:

web3 contract build hello.sol
web3 contract deploy Hello.bin

Read from the contract (free eth_call):

web3 contract call --address 0xCONTRACT_ADDRESS --abi Hello.abi --function hello

Write to the contract (auto-estimates gas and uses EIP-1559 or Legacy fees automatically):

web3 contract call --address 0xCONTRACT_ADDRESS --abi Hello.abi --function setName "Johnny" --wait

You can also call contracts without an .abi file using an inline Solidity signature or bundled ABI (erc20, erc721, erc1155, proxy):

web3 contract call --address 0xUSDC --abi erc20 --function balanceOf 0xUSER_ADDRESS
web3 contract call --address 0xCONTRACT --function "hello():(string,string)"

Generating OpenZeppelin v5 Contracts

Generate an ERC-20 token:

web3 generate contract erc20 --name "Test Tokens" --symbol TEST --initial-supply 1000000

Generate an ERC-721 NFT collection:

web3 generate contract erc721 --name "Kitties" --symbol CAT

Generate an ERC-1155 multi-token contract:

web3 generate contract erc1155 --symbol ITEMS --uri "https://example.com/metadata/{id}.json"

Deploying an EIP-1967 Upgradeable Contract

Deploy any contract behind a standard EIP-1967 upgradeable proxy with --upgradeable:

web3 contract deploy --upgradeable Hello.bin
export WEB3_ADDRESS=0xPROXY_ADDRESS

Inspect, initialize, upgrade, pause, and resume:

# Read EIP-1967 implementation address (works on any EIP-1967 proxy!)
web3 contract target

# Initialize state through the proxy
web3 contract call --abi Hello.abi --function setName "World" --wait

# Upgrade to a new implementation contract
web3 contract build goodbye.sol
web3 contract deploy Goodbye.bin
web3 contract upgrade --to 0xGOODBYE_IMPLEMENTATION_ADDRESS

# Emergency pause & resume
web3 contract pause
web3 contract resume

Offline Crypto, ABI & Chain Inspection Utilities

# Sign & verify EIP-191 messages
web3 sign "Hello Web3!"
web3 verify-sig --message "Hello Web3!" --signature 0xSIG --address 0xEXPECTED

# Offline ABI calldata encoding, output decoding & revert decoding
web3 encode "transfer(address,uint256)" 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 1000000
web3 decode "transfer(address,uint256)" 0xa9059cbb...
web3 decode --revert --abi MyContract.abi 0x08c379a0...

# Keccak-256 & unit conversions
web3 keccak "Transfer(address,address,uint256)"
web3 units 1.5eth

# Storage slots, event logs, and pending transaction management
web3 storage 0xCONTRACT_ADDRESS 0
web3 logs --address 0xTOKEN --abi erc20 --event Transfer --from-block 20000000
web3 increasegas --tx 0xPENDING_HASH --amount 2.5
web3 cancel --tx 0xPENDING_HASH

JSON Output Mode

Pass --format json (-f json) on any command for machine-readable output in scripts and CI:

web3 --format json balance 0xADDRESS
web3 --format json contract call --address 0xCONTRACT --abi Hello.abi --function hello

Build from Source

git clone https://github.com/gochain/web3
cd web3
make build
make test

Documentation

Index

Constants

View Source
const (
	IntTy byte = iota
	UintTy
	BoolTy
	StringTy
	SliceTy
	ArrayTy
	TupleTy
	AddressTy
	FixedBytesTy
	BytesTy
	HashTy
)

ABI Type kinds (kept compatible with classic Kind constants).

View Source
const (
	AddressLength = 20
	HashLength    = 32
	BloomLength   = 256
)
View Source
const (
	TxTypeLegacy     uint8 = 0x00
	TxTypeAccessList uint8 = 0x01
	TxTypeDynamicFee uint8 = 0x02

	ReceiptStatusFailed     uint64 = 0
	ReceiptStatusSuccessful uint64 = 1
)
View Source
const DefaultUserAgent = "gochain-web3/1.0"

Variables

View Source
var (
	ZeroAddress Address
	ZeroHash    Hash
)
View Source
var (
	EmptyRootHash  = HexToHash("0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
	EmptyUncleHash = HexToHash("0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347")
)
View Source
var Networks = map[string]Network{
	"gochain": {
		Name:        "gochain",
		URL:         mainnetURL,
		ChainID:     big.NewInt(60),
		Unit:        "GO",
		ExplorerURL: mainnetExplorerURL,
	},
	"testnet": {
		Name:        "testnet",
		URL:         testnetURL,
		ChainID:     big.NewInt(31337),
		Unit:        "GO",
		ExplorerURL: testnetExplorerURL,
	},
	"localhost": {
		Name: "localhost",
		URL:  "http://localhost:8545",
		Unit: "ETH",
	},
	"ethereum": {
		Name:        "ethereum",
		URL:         "https://ethereum-rpc.publicnode.com",
		ChainID:     big.NewInt(1),
		Unit:        "ETH",
		ExplorerURL: "https://etherscan.io",
	},
	"sepolia": {
		Name:        "sepolia",
		URL:         "https://ethereum-sepolia-rpc.publicnode.com",
		ChainID:     big.NewInt(11155111),
		Unit:        "ETH",
		ExplorerURL: "https://sepolia.etherscan.io",
	},
	"holesky": {
		Name:        "holesky",
		URL:         "https://ethereum-holesky-rpc.publicnode.com",
		ChainID:     big.NewInt(17000),
		Unit:        "ETH",
		ExplorerURL: "https://holesky.etherscan.io",
	},
	"base": {
		Name:        "base",
		URL:         "https://mainnet.base.org",
		ChainID:     big.NewInt(8453),
		Unit:        "ETH",
		ExplorerURL: "https://basescan.org",
	},
	"base-sepolia": {
		Name:        "base-sepolia",
		URL:         "https://sepolia.base.org",
		ChainID:     big.NewInt(84532),
		Unit:        "ETH",
		ExplorerURL: "https://sepolia.basescan.org",
	},
	"arbitrum": {
		Name:        "arbitrum",
		URL:         "https://arb1.arbitrum.io/rpc",
		ChainID:     big.NewInt(42161),
		Unit:        "ETH",
		ExplorerURL: "https://arbiscan.io",
	},
	"optimism": {
		Name:        "optimism",
		URL:         "https://mainnet.optimism.io",
		ChainID:     big.NewInt(10),
		Unit:        "ETH",
		ExplorerURL: "https://optimistic.etherscan.io",
	},
	"polygon": {
		Name:        "polygon",
		URL:         "https://polygon-rpc.com",
		ChainID:     big.NewInt(137),
		Unit:        "POL",
		ExplorerURL: "https://polygonscan.com",
	},
	"bsc": {
		Name:        "bsc",
		URL:         "https://bsc-dataseed.binance.org",
		ChainID:     big.NewInt(56),
		Unit:        "BNB",
		ExplorerURL: "https://bscscan.com",
	},
	"avalanche": {
		Name:        "avalanche",
		URL:         "https://api.avax.network/ext/bc/C/rpc",
		ChainID:     big.NewInt(43114),
		Unit:        "AVAX",
		ExplorerURL: "https://snowtrace.io",
	},
}
View Source
var NotFoundErr = errors.New("not found")

Functions

func Base

func Base(b int64) *big.Int

Base converts b base units (ETH/GO) to wei (*1e18).

func CallConstantFunction

func CallConstantFunction(ctx context.Context, client Client, myabi ABI, address string, functionName string, params ...interface{}) ([]interface{}, error)

CallConstantFunction executes a read-only contract call (eth_call) and unpacks the outputs.

func CompileSolidityString

func CompileSolidityString(ctx context.Context, source, solcVersion, evmVersion string, optimize bool) (map[string]*Contract, error)

CompileSolidityString compiles Solidity source using a local solc binary if compatible or Docker ethereum/solc.

func ConvertArgument

func ConvertArgument(abiType ABIType, param interface{}) (interface{}, error)

ConvertArgument converts param to the Go representation expected by abiType.

func ConvertArguments

func ConvertArguments(args ABIArguments, params []interface{}) ([]interface{}, error)

ConvertArguments converts CLI strings, JSON numbers/arrays/objects, or Go values to ABI-ready Go types.

func ConvertInt

func ConvertInt(signed bool, size int, i *big.Int) (interface{}, error)

ConvertInt converts i into the exact Go integer type corresponding to signedness and ABI bit size, validating both overflow AND underflow bounds.

func DecToInt

func DecToInt(d decimal.Decimal, decimals int32) *big.Int

DecToInt scales decimal d by 10^decimals and returns the truncated *big.Int.

func DecodeBig added in v1.0.0

func DecodeBig(s string) (*big.Int, error)

DecodeBig parses a 0x-prefixed quantity hex string into *big.Int.

func DecodeHex added in v1.0.0

func DecodeHex(s string) ([]byte, error)

DecodeHex decodes a 0x-prefixed (or unprefixed) even-length hex string.

func DecodeRevert added in v1.0.0

func DecodeRevert(data []byte, myabi *ABI) (string, bool)

DecodeRevert decodes EVM revert return data into a human-readable message, handling standard Error(string), Panic(uint256), and custom ABI errors when myabi is provided.

func DecodeUint64 added in v1.0.0

func DecodeUint64(s string) (uint64, error)

DecodeUint64 parses a 0x-prefixed quantity hex string into uint64.

func EncodeBig added in v1.0.0

func EncodeBig(bigint *big.Int) string

EncodeBig encodes bigint as a 0x-prefixed quantity hex string.

func EncodeHex added in v1.0.0

func EncodeHex(b []byte) string

EncodeHex encodes b as a hex string with 0x prefix.

func EncodeRawTransaction added in v1.0.0

func EncodeRawTransaction(tx *Transaction) ([]byte, error)

EncodeRawTransaction encodes a signed Transaction into raw wire bytes.

func EncodeUint64 added in v1.0.0

func EncodeUint64(i uint64) string

EncodeUint64 encodes i as a 0x-prefixed quantity hex string (0x0 for zero).

func EncryptKeystore added in v1.0.0

func EncryptKeystore(acc *Account, auth string, scryptN, scryptP int) ([]byte, error)

EncryptKeystore encrypts an Account into Web3 Secret Storage V3 JSON (scrypt N=4096, r=8, p=6 for fast CLI usage or standard N).

func FloatAsInt

func FloatAsInt(amountF *big.Float, decimals int) *big.Int

FloatAsInt scales *big.Float amountF by 10^decimals into *big.Int.

func FormatRPCError added in v1.0.0

func FormatRPCError(err error, myabi *ABI) error

FormatRPCError enriches an RPCError with decoded Solidity revert details if revert data is present.

func FromECDSA added in v1.0.0

func FromECDSA(priv *ecdsa.PrivateKey) []byte

FromECDSA exports a private key as a 32-byte big-endian slice.

func FromECDSAPub added in v1.0.0

func FromECDSAPub(pub *ecdsa.PublicKey) []byte

FromECDSAPub serializes a secp256k1 public key in 65-byte uncompressed format (0x04 || X || Y).

func FromHex added in v1.0.0

func FromHex(s string) []byte

FromHex decodes hex string s (ignoring errors, returning empty slice on invalid hex).

func GenerateGoBinding added in v1.0.0

func GenerateGoBinding(pkgName, typeName, abiJSON, binHex string) ([]byte, error)

GenerateGoBinding generates a gofmt-formatted Go contract wrapper using package web3.

func GenerateKey added in v1.0.0

func GenerateKey() (*ecdsa.PrivateKey, error)

GenerateKey generates a new secp256k1 ECDSA private key.

func Gwei

func Gwei(g int64) *big.Int

Gwei converts g gwei to wei (*1e9).

func HexToECDSA added in v1.0.0

func HexToECDSA(hexKey string) (*ecdsa.PrivateKey, error)

HexToECDSA parses a 32-byte hex-encoded secp256k1 private key (with or without 0x prefix).

func IntAsFloat

func IntAsFloat(i *big.Int, decimals int) *big.Float

IntAsFloat converts a *big.Int (wei) to *big.Float given decimals.

func IntToDec

func IntToDec(i *big.Int, decimals int32) decimal.Decimal

IntToDec divides *big.Int i by 10^decimals into a decimal.Decimal.

func IsHexAddress added in v1.0.0

func IsHexAddress(s string) bool

IsHexAddress reports whether s is a valid 40-hex-character EVM address (with optional 0x prefix).

func Keccak256 added in v1.0.0

func Keccak256(data ...[]byte) []byte

Keccak256 computes the Ethereum Keccak-256 hash of the concatenated input slices.

func NetworkNames added in v1.0.0

func NetworkNames() []string

NetworkNames returns sorted built-in network names.

func ParseAmount

func ParseAmount(amount string) (*big.Int, error)

ParseAmount parses a human-readable amount with optional unit suffix (wei, attogo, gwei, nanogo, eth, go) into wei.

func ParseBase

func ParseBase(b string) (*big.Int, error)

ParseBase parses a decimal ETH/GO string (up to 18 fractional digits) into wei.

func ParseBigInt

func ParseBigInt(value string) (*big.Int, error)

ParseBigInt parses a base-10 integer string into *big.Int.

func ParseCombinedJSON

func ParseCombinedJSON(combinedJSON []byte, source, languageVersion, compilerVersion, compilerOptions string) (map[string]*Contract, error)

func ParseGwei

func ParseGwei(g string) (*big.Int, error)

ParseGwei parses a decimal gwei string (up to 9 fractional digits) into wei.

func PersonalSign added in v1.0.0

func PersonalSign(message []byte, prv *ecdsa.PrivateKey) ([]byte, error)

PersonalSign signs message using EIP-191 personal_sign, returning a 65-byte signature with V in {27, 28}.

func RLPEncode added in v1.0.0

func RLPEncode(val interface{}) ([]byte, error)

RLPEncode encodes val using Ethereum Recursive Length Prefix (RLP) encoding.

func RecoverPubkey added in v1.0.0

func RecoverPubkey(digestHash, sig []byte) (*ecdsa.PublicKey, error)

RecoverPubkey recovers the secp256k1 public key from a 32-byte digest and 65-byte [R || S || V] signature (accepting V in {0, 1} or {27, 28}).

func SendTransaction

func SendTransaction(ctx context.Context, client Client, signedTx *Transaction) error

SendTransaction encodes and broadcasts a pre-signed Transaction.

func SignHash added in v1.0.0

func SignHash(digestHash []byte, prv *ecdsa.PrivateKey) ([]byte, error)

SignHash produces a 65-byte recoverable secp256k1 signature in [R(32) || S(32) || V(1)] format, where V is 0 or 1 (recovery ID) and S is canonical low-S (EIP-2).

func SignTransaction added in v1.0.0

func SignTransaction(tx *Transaction, chainID *big.Int, prv *ecdsa.PrivateKey) ([]byte, error)

SignTransaction signs tx with prv for the given chainID, sets From/ChainID/V/R/S/Hash on tx, and returns the raw EIP-2718 or RLP transaction wire bytes ready for eth_sendRawTransaction.

func ToECDSA added in v1.0.0

func ToECDSA(d []byte) (*ecdsa.PrivateKey, error)

ToECDSA converts raw 32-byte secret scalar bytes into an *ecdsa.PrivateKey on secp256k1.

func WeiAsBase

func WeiAsBase(w *big.Int) string

WeiAsBase formats w wei in base units (ETH/GO) with 18 decimals.

func WeiAsGwei

func WeiAsGwei(w *big.Int) string

WeiAsGwei formats w wei in gwei with 9 decimals.

Types

type ABI added in v1.0.0

type ABI struct {
	Constructor ABIMethod
	Methods     map[string]ABIMethod
	Overloads   map[string][]ABIMethod
	Events      map[string]ABIEvent
	Errors      map[string]ABIError
}

ABI holds parsed methods, constructor, events, and custom errors of a smart contract.

func ABIBuiltIn

func ABIBuiltIn(name string) (*ABI, error)

func ABIOpenFile

func ABIOpenFile(abiFile string) (*ABI, error)

func ABIOpenURL

func ABIOpenURL(abiURL string) (*ABI, error)

func GetABI

func GetABI(abiSpec string) (*ABI, error)

GetABI resolves a built-in ABI name ("erc20", "erc721", "erc1155", "proxy"), an inline JSON ABI array, a human-readable signature, a local file path, or an HTTP(S) URL.

func ParseABI added in v1.0.0

func ParseABI(abiJSON string) (ABI, error)

ParseABI parses a JSON ABI string.

func ParseABIJSON added in v1.0.0

func ParseABIJSON(r io.Reader) (ABI, error)

ParseABIJSON parses a JSON ABI from reader.

func (ABI) Pack added in v1.0.0

func (a ABI) Pack(name string, args ...interface{}) ([]byte, error)

Pack ABI-encodes a call to name (or constructor when name == "") with args.

func (ABI) ResolveMethod added in v1.0.0

func (a ABI) ResolveMethod(name string, argCount int) (ABIMethod, bool)

ResolveMethod looks up a method by exact name, canonical signature ("transfer(address,uint256)"), or overload matching argCount when multiple methods share the same name.

func (ABI) Unpack added in v1.0.0

func (a ABI) Unpack(name string, data []byte) ([]interface{}, error)

Unpack decodes output bytes for a named method or event.

type ABIArgument added in v1.0.0

type ABIArgument struct {
	Name         string  `json:"name"`
	Type         ABIType `json:"-"`
	RawType      string  `json:"type"`
	InternalType string  `json:"internalType,omitempty"`
	Indexed      bool    `json:"indexed,omitempty"`
}

ABIArgument describes a named ABI input/output/event/error parameter.

type ABIArguments added in v1.0.0

type ABIArguments []ABIArgument

func (ABIArguments) Pack added in v1.0.0

func (args ABIArguments) Pack(values ...interface{}) ([]byte, error)

Pack ABI-encodes values matching the ABIArguments specification.

func (ABIArguments) UnpackValues added in v1.0.0

func (args ABIArguments) UnpackValues(data []byte) ([]interface{}, error)

UnpackValues decodes ABI-encoded output bytes according to args.

type ABIError added in v1.0.0

type ABIError struct {
	Name   string       `json:"name"`
	Inputs ABIArguments `json:"inputs"`
	ID     [4]byte      `json:"-"` // 4-byte error selector
}

ABIError represents a Solidity custom error definition in an ABI.

func (ABIError) Sig added in v1.0.0

func (e ABIError) Sig() string

type ABIEvent added in v1.0.0

type ABIEvent struct {
	Name      string       `json:"name"`
	RawName   string       `json:"-"`
	Anonymous bool         `json:"anonymous"`
	Inputs    ABIArguments `json:"inputs"`
	ID        Hash         `json:"-"` // 32-byte topic0 hash
}

ABIEvent represents an event definition in an ABI.

func FindEventById

func FindEventById(myabi ABI, id Hash) *ABIEvent

FindEventById finds an event in myabi matching topic0 id, or nil if unknown.

func (ABIEvent) Sig added in v1.0.0

func (e ABIEvent) Sig() string

type ABIMethod added in v1.0.0

type ABIMethod struct {
	Name            string       `json:"name"`
	RawName         string       `json:"-"`
	Type            string       `json:"type"`
	StateMutability string       `json:"stateMutability,omitempty"`
	Constant        bool         `json:"constant,omitempty"`
	Payable         bool         `json:"payable,omitempty"`
	Inputs          ABIArguments `json:"inputs"`
	Outputs         ABIArguments `json:"outputs"`
	ID              []byte       `json:"-"` // 4-byte function selector
}

ABIMethod represents a function, constructor, fallback, or receive entry in an ABI.

func ParseHumanSignature added in v1.0.0

func ParseHumanSignature(sig string) (ABIMethod, error)

ParseHumanSignature parses a human-readable Solidity function signature such as "transfer(address to, uint256 amount) returns (bool)" or "balanceOf(address):(uint256)".

func (ABIMethod) IsConstant added in v1.0.0

func (m ABIMethod) IsConstant() bool

IsConstant reports whether the method is read-only (view, pure, or legacy constant: true).

func (ABIMethod) Sig added in v1.0.0

func (m ABIMethod) Sig() string

Sig returns the canonical signature string, e.g. "transfer(address,uint256)".

func (ABIMethod) String added in v1.0.0

func (m ABIMethod) String() string

type ABIType added in v1.0.0

type ABIType struct {
	T          byte
	Size       int           // Bit size for int/uint (8..256), byte length for FixedBytesTy (1..32), array length for ArrayTy
	Elem       *ABIType      // Element type for SliceTy / ArrayTy
	TupleElems []ABIArgument // Fields for TupleTy
	TupleRaw   string        // Optional internal struct name
}

ABIType represents a parsed Solidity ABI parameter type.

func ParseABIType added in v1.0.0

func ParseABIType(typeStr string, components []ABIArgument) (ABIType, error)

ParseABIType parses a Solidity ABI type string (including arrays and inline tuples like "(string,uint64)[]") with optional JSON components for "tuple" types.

func (ABIType) CanonicalString added in v1.0.0

func (t ABIType) CanonicalString() string

CanonicalString returns the canonical Solidity ABI signature representation of t (used in selectors).

func (ABIType) String added in v1.0.0

func (t ABIType) String() string

type AccessTuple added in v1.0.0

type AccessTuple struct {
	Address     Address `json:"address"`
	StorageKeys []Hash  `json:"storageKeys"`
}

type Account

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

func CreateAccount

func CreateAccount() (*Account, error)

func DecryptKeystore added in v1.0.0

func DecryptKeystore(keyJSON []byte, auth string) (*Account, error)

DecryptKeystore decrypts a Web3 Secret Storage V3 keystore JSON payload into an *Account.

func NewAccountFromKey added in v1.0.0

func NewAccountFromKey(key *ecdsa.PrivateKey) *Account

func ParsePrivateKey

func ParsePrivateKey(pkHex string) (*Account, error)

func (*Account) Address added in v0.2.61

func (a *Account) Address() Address

func (*Account) Key

func (a *Account) Key() *ecdsa.PrivateKey

func (*Account) PrivateKey

func (a *Account) PrivateKey() string

func (*Account) PublicKey

func (a *Account) PublicKey() string

type Address added in v1.0.0

type Address [AddressLength]byte

Address represents a 20-byte EVM account or contract address.

func BytesToAddress added in v1.0.0

func BytesToAddress(b []byte) Address

BytesToAddress right-aligns b into a 20-byte Address.

func CreateAddress added in v1.0.0

func CreateAddress(caller Address, nonce uint64) Address

CreateAddress computes the deterministic contract address deployed by caller at nonce (RLP([caller, nonce])).

func HexToAddress added in v1.0.0

func HexToAddress(s string) Address

HexToAddress parses a hex string (with or without 0x prefix) into an Address.

func PersonalRecover added in v1.0.0

func PersonalRecover(message, sig []byte) (Address, error)

PersonalRecover recovers the EVM address that produced an EIP-191 personal_sign signature.

func PubkeyToAddress added in v1.0.0

func PubkeyToAddress(p ecdsa.PublicKey) Address

PubkeyToAddress derives the 20-byte EVM address from a secp256k1 public key.

func RecoverAddress added in v1.0.0

func RecoverAddress(digestHash, sig []byte) (Address, error)

RecoverAddress recovers the signer's EVM Address from a 32-byte digest and 65-byte signature.

func RecoverTransactionSender added in v1.0.0

func RecoverTransactionSender(tx *Transaction) (Address, error)

RecoverTransactionSender recovers the sender Address from a signed Transaction.

func (Address) Bytes added in v1.0.0

func (a Address) Bytes() []byte

func (Address) Hex added in v1.0.0

func (a Address) Hex() string

Hex returns the EIP-55 checksummed hex representation of the address.

func (Address) IsZero added in v1.0.0

func (a Address) IsZero() bool

func (Address) MarshalJSON added in v1.0.0

func (a Address) MarshalJSON() ([]byte, error)

func (Address) MarshalText added in v1.0.0

func (a Address) MarshalText() ([]byte, error)

func (Address) String added in v1.0.0

func (a Address) String() string

func (*Address) UnmarshalJSON added in v1.0.0

func (a *Address) UnmarshalJSON(input []byte) error

func (*Address) UnmarshalText added in v1.0.0

func (a *Address) UnmarshalText(input []byte) error

type BatchElem added in v1.0.0

type BatchElem struct {
	Method string
	Args   []interface{}
	Result interface{}
	Error  error
}

BatchElem is an element in a JSON-RPC batch request.

type Block

type Block struct {
	ParentHash      Hash
	Sha3Uncles      Hash
	Miner           Address
	Signers         []Address
	Voters          []Address
	Signer          []byte
	StateRoot       Hash
	TxsRoot         Hash
	ReceiptsRoot    Hash
	LogsBloom       *Bloom
	Difficulty      *big.Int
	TotalDifficulty *big.Int
	Number          *big.Int
	GasLimit        uint64
	GasUsed         uint64
	BaseFeePerGas   *big.Int
	Timestamp       time.Time
	ExtraData       []byte
	MixHash         Hash
	Nonce           BlockNonce
	Hash            Hash

	// Only one of TxHashes or TxDetails will be populated.
	TxHashes  []Hash
	TxDetails []*Transaction

	Uncles []Hash
}

func (*Block) ExtraVanity

func (b *Block) ExtraVanity() string

func (*Block) MarshalJSON

func (b *Block) MarshalJSON() ([]byte, error)

func (*Block) TxCount

func (b *Block) TxCount() int

func (*Block) UnmarshalJSON

func (b *Block) UnmarshalJSON(data []byte) error

type BlockNonce added in v1.0.0

type BlockNonce [8]byte

BlockNonce represents an 8-byte block header nonce.

func (BlockNonce) MarshalText added in v1.0.0

func (n BlockNonce) MarshalText() ([]byte, error)

func (BlockNonce) Uint64 added in v1.0.0

func (n BlockNonce) Uint64() uint64

func (*BlockNonce) UnmarshalText added in v1.0.0

func (n *BlockNonce) UnmarshalText(input []byte) error

type Bloom added in v1.0.0

type Bloom [BloomLength]byte

Bloom represents a 2048-bit (256-byte) logs bloom filter.

func (Bloom) Bytes added in v1.0.0

func (b Bloom) Bytes() []byte

func (Bloom) Hex added in v1.0.0

func (b Bloom) Hex() string

func (Bloom) MarshalText added in v1.0.0

func (b Bloom) MarshalText() ([]byte, error)

func (*Bloom) UnmarshalText added in v1.0.0

func (b *Bloom) UnmarshalText(input []byte) error

type CallMsg

type CallMsg struct {
	From                 *Address
	To                   *Address
	Gas                  uint64
	GasPrice             *big.Int
	MaxFeePerGas         *big.Int
	MaxPriorityFeePerGas *big.Int
	Value                *big.Int
	Data                 []byte
}

type Client

type Client interface {
	GetBalance(ctx context.Context, address string, blockNumber *big.Int) (*big.Int, error)
	GetCode(ctx context.Context, address string, blockNumber *big.Int) ([]byte, error)
	GetStorageAt(ctx context.Context, address Address, slot Hash, blockNumber *big.Int) (Hash, error)
	GetBlockNumber(ctx context.Context) (uint64, error)
	GetBlockByNumber(ctx context.Context, number *big.Int, includeTxs bool) (*Block, error)
	GetBlockByHash(ctx context.Context, hash string, includeTxs bool) (*Block, error)
	GetTransactionByHash(ctx context.Context, hash Hash) (*Transaction, error)
	GetTransactionReceipt(ctx context.Context, hash Hash) (*Receipt, error)
	GetLogs(ctx context.Context, q FilterQuery) ([]Log, error)
	GetSnapshot(ctx context.Context) (*Snapshot, error)
	GetID(ctx context.Context) (*ID, error)
	GetChainID(ctx context.Context) (*big.Int, error)
	GetNetworkID(ctx context.Context) (*big.Int, error)
	GetGasPrice(ctx context.Context) (*big.Int, error)
	MaxPriorityFeePerGas(ctx context.Context) (*big.Int, error)
	EstimateGas(ctx context.Context, msg CallMsg) (uint64, error)
	GetPendingTransactionCount(ctx context.Context, account Address) (uint64, error)
	GetTransactionCount(ctx context.Context, account Address, blockNumber *big.Int) (uint64, error)
	SendRawTransaction(ctx context.Context, tx []byte) error
	Call(ctx context.Context, msg CallMsg) ([]byte, error)
	Close()
	SetChainID(*big.Int)
}

Client is the interface for interacting with an EVM JSON-RPC node.

func Dial

func Dial(url string) (Client, error)

Dial returns a new Client connected to url ("http", "https", "ws", or "wss").

func NewClient

func NewClient(r *RPCClient) Client

NewClient wraps an *RPCClient in a web3 Client.

type Contract

type Contract struct {
	Code        string            `json:"code"`
	RuntimeCode string            `json:"runtime-code"`
	Info        ContractInfo      `json:"info"`
	Hashes      map[string]string `json:"hashes"`
}

Contract contains information about a compiled contract, alongside its creation and runtime bytecode.

type ContractInfo

type ContractInfo struct {
	Source          string      `json:"source"`
	Language        string      `json:"language"`
	LanguageVersion string      `json:"languageVersion"`
	CompilerVersion string      `json:"compilerVersion"`
	CompilerOptions string      `json:"compilerOptions"`
	SrcMap          interface{} `json:"srcMap"`
	SrcMapRuntime   string      `json:"srcMapRuntime"`
	AbiDefinition   interface{} `json:"abiDefinition"`
	UserDoc         interface{} `json:"userDoc"`
	DeveloperDoc    interface{} `json:"developerDoc"`
	Metadata        string      `json:"metadata"`
}

ContractInfo contains ABI, source maps, docs, and compiler metadata for a compiled contract.

type Event

type Event struct {
	Name   string                 `json:"name"`
	Fields map[string]interface{} `json:"fields"`
}

func ParseLogs

func ParseLogs(myabi ABI, logs []*Log) ([]Event, error)

ParseLogs decodes matching events from logs, safely skipping anonymous or unrecognized external events.

type FilterQuery added in v1.0.0

type FilterQuery struct {
	BlockHash *Hash
	FromBlock *big.Int // nil = latest
	ToBlock   *big.Int // nil = latest
	Addresses []Address
	Topics    [][]Hash
}

type Hash added in v1.0.0

type Hash [HashLength]byte

Hash represents a 32-byte Keccak-256 hash.

func BytesToHash added in v1.0.0

func BytesToHash(b []byte) Hash

func HexToHash added in v1.0.0

func HexToHash(s string) Hash

func Keccak256Hash added in v1.0.0

func Keccak256Hash(data ...[]byte) Hash

Keccak256Hash computes the Ethereum Keccak-256 hash and returns it as a Hash.

func PersonalMessageHash added in v1.0.0

func PersonalMessageHash(message []byte) Hash

PersonalMessageHash computes the EIP-191 personal_sign digest ("\x19Ethereum Signed Message:\n" + len + msg).

func TxSigningHash added in v1.0.0

func TxSigningHash(tx *Transaction, chainID *big.Int) (Hash, error)

TxSigningHash computes the digest hash that is signed for tx.

func (Hash) Bytes added in v1.0.0

func (h Hash) Bytes() []byte

func (Hash) Hex added in v1.0.0

func (h Hash) Hex() string

func (Hash) IsZero added in v1.0.0

func (h Hash) IsZero() bool

func (Hash) MarshalJSON added in v1.0.0

func (h Hash) MarshalJSON() ([]byte, error)

func (Hash) MarshalText added in v1.0.0

func (h Hash) MarshalText() ([]byte, error)

func (Hash) String added in v1.0.0

func (h Hash) String() string

func (*Hash) UnmarshalJSON added in v1.0.0

func (h *Hash) UnmarshalJSON(input []byte) error

func (*Hash) UnmarshalText added in v1.0.0

func (h *Hash) UnmarshalText(input []byte) error

type HexBig added in v1.0.0

type HexBig big.Int

HexBig marshals/unmarshals big.Int as 0x-prefixed quantity hex in JSON.

func (*HexBig) MarshalText added in v1.0.0

func (b *HexBig) MarshalText() ([]byte, error)

func (*HexBig) ToInt added in v1.0.0

func (b *HexBig) ToInt() *big.Int

func (*HexBig) UnmarshalText added in v1.0.0

func (b *HexBig) UnmarshalText(input []byte) error

type HexBytes added in v1.0.0

type HexBytes []byte

HexBytes marshals/unmarshals byte slices as 0x-prefixed hex strings in JSON.

func (HexBytes) MarshalText added in v1.0.0

func (b HexBytes) MarshalText() ([]byte, error)

func (HexBytes) String added in v1.0.0

func (b HexBytes) String() string

func (*HexBytes) UnmarshalText added in v1.0.0

func (b *HexBytes) UnmarshalText(input []byte) error

type HexUint64 added in v1.0.0

type HexUint64 uint64

HexUint64 marshals/unmarshals uint64 as 0x-prefixed quantity hex in JSON.

func (HexUint64) MarshalText added in v1.0.0

func (u HexUint64) MarshalText() ([]byte, error)

func (*HexUint64) UnmarshalText added in v1.0.0

func (u *HexUint64) UnmarshalText(input []byte) error

type ID

type ID struct {
	NetworkID   *big.Int `json:"network_id"`
	ChainID     *big.Int `json:"chain_id"`
	GenesisHash Hash     `json:"genesis_hash"`
}

type Log added in v1.0.0

type Log struct {
	Address     Address
	Topics      []Hash
	Data        []byte
	BlockNumber uint64
	TxHash      Hash
	TxIndex     uint
	BlockHash   Hash
	Index       uint
	Removed     bool
}

func (Log) MarshalJSON added in v1.0.0

func (l Log) MarshalJSON() ([]byte, error)

func (*Log) UnmarshalJSON added in v1.0.0

func (l *Log) UnmarshalJSON(data []byte) error

type Network

type Network struct {
	Name        string
	URL         string
	ExplorerURL string
	Unit        string
	ChainID     *big.Int
}

type RLPItem added in v1.0.0

type RLPItem struct {
	IsList bool
	Bytes  []byte
	List   []RLPItem
}

RLPItem represents a decoded RLP element (either Bytes or a List of RLPItems).

func RLPDecode added in v1.0.0

func RLPDecode(data []byte) (RLPItem, error)

RLPDecode decodes a full RLP byte slice into an RLPItem.

func (RLPItem) BigInt added in v1.0.0

func (it RLPItem) BigInt() (*big.Int, error)

func (RLPItem) Uint64 added in v1.0.0

func (it RLPItem) Uint64() (uint64, error)

type RPCClient added in v1.0.0

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

RPCClient is a pure-Go JSON-RPC 2.0 client supporting HTTP(S) and WS(S).

func DialRPC added in v1.0.0

func DialRPC(rawURL string) (*RPCClient, error)

DialRPC connects to an HTTP(S) or WS(S) JSON-RPC endpoint.

func DialRPCContext added in v1.0.0

func DialRPCContext(ctx context.Context, rawURL string) (*RPCClient, error)

DialRPCContext connects to an HTTP(S) or WS(S) JSON-RPC endpoint using ctx.

func (*RPCClient) BatchCallContext added in v1.0.0

func (c *RPCClient) BatchCallContext(ctx context.Context, b []BatchElem) error

BatchCallContext executes a batch of JSON-RPC calls in a single round-trip.

func (*RPCClient) CallContext added in v1.0.0

func (c *RPCClient) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error

CallContext executes a single JSON-RPC method call.

func (*RPCClient) Close added in v1.0.0

func (c *RPCClient) Close()

Close closes any underlying WebSocket or idle HTTP connections.

func (*RPCClient) SetHeader added in v1.0.0

func (c *RPCClient) SetHeader(key, value string)

SetHeader sets a custom HTTP header on outgoing requests.

type RPCError added in v1.0.0

type RPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

RPCError represents a JSON-RPC 2.0 error response, including optional revert data.

func (*RPCError) Error added in v1.0.0

func (e *RPCError) Error() string

func (*RPCError) RevertData added in v1.0.0

func (e *RPCError) RevertData() []byte

RevertData extracts raw revert bytes from an RPCError if present (common on eth_call / eth_estimateGas).

type Receipt

type Receipt struct {
	Type              uint8
	PostState         []byte
	Status            uint64
	CumulativeGasUsed uint64
	EffectiveGasPrice *big.Int
	Bloom             Bloom
	Logs              []*Log
	TxHash            Hash
	TxIndex           uint64
	ContractAddress   Address
	GasUsed           uint64
	ParsedLogs        []Event
	BlockHash         Hash
	BlockNumber       uint64
	From              Address
	To                *Address
}

func WaitForReceipt

func WaitForReceipt(ctx context.Context, client Client, hash Hash) (*Receipt, error)

WaitForReceipt polls for a transaction receipt until available or ctx is cancelled.

func (*Receipt) MarshalJSON

func (r *Receipt) MarshalJSON() ([]byte, error)

func (*Receipt) UnmarshalJSON

func (r *Receipt) UnmarshalJSON(data []byte) error

type Snapshot

type Snapshot struct {
	Number  uint64               `json:"number"`
	Hash    Hash                 `json:"hash"`
	Signers map[Address]uint64   `json:"signers"`
	Voters  map[Address]struct{} `json:"voters"`
	Votes   []*Vote              `json:"votes"`
	Tally   map[Address]Tally    `json:"tally"`
}

type Solidity

type Solidity struct {
	Path, Version, EVMVersion string
	Major, Minor, Patch       int
	Optimize                  bool
	UseDocker                 bool
}

Solidity specifies the Solidity compiler configuration.

func SolidityVersion

func SolidityVersion(source string) (*Solidity, error)

SolidityVersion extracts a concrete Solidity compiler version from pragma solidity in source.

type Tally

type Tally struct {
	Authorize bool `json:"authorize"`
	Votes     int  `json:"votes"`
}

type Transaction

type Transaction struct {
	Type                 uint8
	ChainID              *big.Int
	Nonce                uint64
	GasPrice             *big.Int // wei (Legacy / EIP-2930, or effective gasPrice returned by RPC)
	MaxPriorityFeePerGas *big.Int // wei (EIP-1559)
	MaxFeePerGas         *big.Int // wei (EIP-1559)
	GasLimit             uint64
	To                   *Address
	Value                *big.Int // wei
	Input                []byte
	AccessList           []AccessTuple
	From                 Address
	V                    *big.Int
	R                    *big.Int
	S                    *big.Int
	Hash                 Hash

	BlockNumber      *big.Int
	BlockHash        Hash
	TransactionIndex uint64
}

func CallFunctionWithArgs added in v0.2.69

func CallFunctionWithArgs(ctx context.Context, client Client, privateKeyHex, address string,
	amount *big.Int, gasPrice *big.Int, gasLimit uint64, myabi ABI, functionName string, params ...interface{}) (*Transaction, error)

CallFunctionWithArgs submits a contract transaction with legacy gasPrice/gasLimit parameters (0 gasLimit auto-estimates).

func CallFunctionWithData added in v0.2.69

func CallFunctionWithData(ctx context.Context, client Client, privateKeyHex, address string,
	amount *big.Int, gasPrice *big.Int, gasLimit uint64, data []byte) (*Transaction, error)

CallFunctionWithData submits pre-encoded calldata to address.

func CallFunctionWithDataOpts added in v1.0.0

func CallFunctionWithDataOpts(ctx context.Context, client Client, privateKeyHex, address string, opts TxOptions, data []byte) (*Transaction, error)

CallFunctionWithDataOpts submits pre-encoded calldata to address with full TxOptions.

func CallFunctionWithOpts added in v1.0.0

func CallFunctionWithOpts(ctx context.Context, client Client, privateKeyHex, address string,
	opts TxOptions, myabi ABI, functionName string, params ...interface{}) (*Transaction, error)

CallFunctionWithOpts submits a contract transaction supporting EIP-1559 fees, auto gas estimation, and revert decoding.

func CallTransactFunction

func CallTransactFunction(ctx context.Context, client Client, myabi ABI, address, privateKeyHex, functionName string,
	amount *big.Int, gasPrice *big.Int, gasLimit uint64, params ...interface{}) (*Transaction, error)

CallTransactFunction submits a transaction to execute a smart contract function call. Deprecated: prefer CallFunctionWithArgs or CallFunctionWithOpts.

func DeployBin

func DeployBin(ctx context.Context, client Client, privateKeyHex, binFilename, abiFilename string,
	gasPrice *big.Int, gasLimit uint64, constructorArgs ...interface{}) (*Transaction, error)

DeployBin deploys a .bin file (local path or URL) with optional .abi file and constructor arguments.

func DeployContract

func DeployContract(ctx context.Context, client Client, privateKeyHex, binHex, abiJSON string, gasPrice *big.Int, gasLimit uint64, constructorArgs ...interface{}) (*Transaction, error)

DeployContract submits a contract creation transaction (0 gasLimit auto-estimates).

func DeployContractWithOpts added in v1.0.0

func DeployContractWithOpts(ctx context.Context, client Client, privateKeyHex, binHex, abiJSON string, opts TxOptions, constructorArgs ...interface{}) (*Transaction, error)

DeployContractWithOpts submits a contract creation transaction with full TxOptions.

func DeployEIP1967Proxy added in v1.0.0

func DeployEIP1967Proxy(ctx context.Context, client Client, privateKeyHex string, implementationAddr, adminAddr Address, initData []byte, opts TxOptions) (*Transaction, error)

DeployEIP1967Proxy deploys a standard EIP-1967 upgradeable proxy pointing at implementationAddr with optional initData.

func Send

func Send(ctx context.Context, client Client, privateKeyHex string, to Address, amount *big.Int, gasPrice *big.Int, gasLimit uint64) (*Transaction, error)

Send performs a native coin transfer (GO/ETH).

func SendWithOpts added in v1.0.0

func SendWithOpts(ctx context.Context, client Client, privateKeyHex string, to Address, opts TxOptions) (*Transaction, error)

SendWithOpts performs a native coin transfer supporting EIP-1559 and auto gas estimation.

func (*Transaction) MarshalJSON

func (t *Transaction) MarshalJSON() ([]byte, error)

func (*Transaction) UnmarshalJSON

func (t *Transaction) UnmarshalJSON(data []byte) error

type TxOptions added in v1.0.0

type TxOptions struct {
	Value                *big.Int
	GasPrice             *big.Int // Explicit legacy gasPrice (wei)
	MaxFeePerGas         *big.Int // Explicit EIP-1559 maxFeePerGas (wei)
	MaxPriorityFeePerGas *big.Int // Explicit EIP-1559 maxPriorityFeePerGas (wei)
	GasLimit             uint64   // 0 = auto-estimate via eth_estimateGas
	Nonce                *uint64  // nil = auto-fetch pending nonce
}

TxOptions configures gas fees, gas limit, value, and nonce when submitting a transaction.

type Vote

type Vote struct {
	Signer    Address `json:"signer"`
	Block     uint64  `json:"block"`
	Address   Address `json:"address"`
	Authorize bool    `json:"authorize"`
}

Directories

Path Synopsis
cmd
web3 command

Jump to

Keyboard shortcuts

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