web3

package module
v0.1.15 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2023 License: MPL-2.0 Imports: 14 Imported by: 41

README

Web3

forked from "github.com/umbracle/go-web3"

JsonRPC

package main

import (
	"fmt"
	
	"github.com/laizy/web3"
	"github.com/laizy/web3/jsonrpc"
)

func main() {
	client, err := jsonrpc.NewClient("https://mainnet.infura.io")
	if err != nil {
		panic(err)
	}

	number, err := client.Eth().BlockNumber()
	if err != nil {
		panic(err)
	}

	header, err := client.Eth().GetBlockByNumber(web3.BlockNumber(number), true)
	if err != nil {
		panic(err)
	}

	fmt.Println(header)
}

ABI

The ABI codifier uses randomized tests with e2e integration tests with a real Geth client to ensure that the codification is correct and provides the same results as the AbiEncoder from Solidity.

To use the library import:

"github.com/laizy/web3/abi"

Declare basic objects:

typ, err := abi.NewType("uint256")

or

typ = abi.MustNewType("uint256")

and use it to encode/decode the data:

num := big.NewInt(1)

encoded, err := typ.Encode(num)
if err != nil {
    panic(err)
}

decoded, err := typ.Decode(encoded) // decoded as interface
if err != nil {
    panic(err)
}

num2 := decoded.(*big.Int)
fmt.Println(num.Cmp(num2) == 0) // num == num2

You can also codify structs as Solidity tuples:

import (
	"fmt"
    
	"github.com/laizy/web3"
	"github.com/laizy/web3/abi"
	"math/big"
)

func main() {
	typ := abi.MustNewType("tuple(address a, uint256 b)")

	type Obj struct {
		A web3.Address
		B *big.Int
	}
	obj := &Obj{
		A: web3.Address{0x1},
		B: big.NewInt(1),
	}

	// Encode
	encoded, err := typ.Encode(obj)
	if err != nil {
		panic(err)
	}

	// Decode output into a map
	res, err := typ.Decode(encoded)
	if err != nil {
		panic(err)
	}

	// Decode into a struct
	var obj2 Obj
	if err := typ.DecodeStruct(encoded, &obj2); err != nil {
		panic(err)
	}

	fmt.Println(res)
	fmt.Println(obj)
}

Wallet

As for now the library only provides primitive abstractions to send signed abstractions. The intended goal is to abstract the next steps inside the contract package.

// Generate a random wallet
key, _ := wallet.GenerateKey()

to := web3.Address{0x1}
transferVal := big.NewInt(1000)

// Create the transaction
txn := &web3.Transaction{
	To:    &to,
	Value: transferVal,
	Gas:   100000,
}

// Create the signer object and sign
signer := wallet.NewEIP155Signer(chainID)
txn, _ = signer.SignTx(txn, key)

// Send the signed transaction
data := txn.MarshalRLP()
hash, _ := c.Eth().SendRawTransaction(data)

ENS

Resolve names on the Ethereum Name Service registrar.

import (
    "fmt"

    "github.com/laizy/web3"
    "github.com/laizy/web3/jsonrpc"
    "github.com/laizy/web3/contract/builtin/ens"
)

var mainnetAddress = web3.HexToAddress("0x314159265dD8dbb310642f98f50C066173C1259b")

func main() {
	client, err := jsonrpc.NewClient("https://mainnet.infura.io")
    if err != nil {
        panic(err)
    }

	resolver := ens.NewENSResolver(mainnetAddress, client)
	addr, err := resolver.Resolve("ens_address")
	if err != nil {
		panic(err)
	}

    fmt.Println(addr)
}

Tracker

Complete example of the tracker here

Documentation

Index

Constants

View Source
const (
	// HashLength is the expected length of the hash
	HashLength = 32
	// AddressLength is the expected length of the address
	AddressLength = 20
)

Lengths of hashes and addresses in bytes.

View Source
const (
	Latest   BlockNumber = -1
	Earliest             = -2
	Pending              = -3
)
View Source
const (
	// ReceiptStatusSuccessful is the status code of a transaction if execution succeeded.
	ReceiptStatusSuccessful = uint64(1)
)

Variables

View Source
var TraceRpc = false // trace all rpc request response

Functions

func CopyBytes

func CopyBytes(b []byte) (copiedBytes []byte)

func Ether

func Ether(i uint64) *big.Int

Ether converts a value to the ether unit with 18 decimals

func Gwei

func Gwei(i uint64) *big.Int

Gwei converts a value to the gwei unit with 9 decimals

func Hex2Bytes

func Hex2Bytes(str string) []byte

func RegisterParser

func RegisterParser(p LogParser)

Types

type Address

type Address [20]byte

Address is an Ethereum address

func BytesToAddress

func BytesToAddress(b []byte) Address

func HexToAddress

func HexToAddress(str string) Address

HexToAddress converts an hex string value to an address object

func (Address) Bytes

func (a Address) Bytes() []byte

func (*Address) IsZero

func (a *Address) IsZero() bool

func (Address) MarshalText

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

MarshalText implements the marshal interface

func (*Address) SetBytes

func (a *Address) SetBytes(b []byte)

SetBytes sets the address to the value of b. If b is larger than len(a), b will be cropped from the left.

func (Address) String

func (a Address) String() string

func (Address) ToHash

func (self Address) ToHash() Hash

func (*Address) UnmarshalText

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

UnmarshalText implements the unmarshal interface

type Block

type Block struct {
	Header
	Hash               Hash
	Transactions       []*Transaction
	TransactionsHashes []Hash
	Uncles             []Hash
}

func (*Block) MarshalJSON

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

MarshalJSON implements the marshal interface

func (*Block) UnmarshalJSON

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

UnmarshalJSON implements the unmarshal interface

type BlockNumber

type BlockNumber int

func EncodeBlock

func EncodeBlock(block ...BlockNumber) BlockNumber

func (BlockNumber) MarshalText added in v0.1.2

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

func (BlockNumber) String

func (b BlockNumber) String() string

type CallMsg

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

func (*CallMsg) MarshalJSON

func (c *CallMsg) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshal interface.

type ExecutionResult

type ExecutionResult struct {
	UsedGas      uint64        // Total used gas but include the refunded gas
	Err          error         // Any error encountered during the execution(listed in core/vm/errors.go)
	ReturnData   hexutil.Bytes // Returned data from evm(function result or data supplied with revert opcode)
	RevertReason string
}

ExecutionResult includes all output after executing given evm message no matter the execution itself is successful or not.

func (*ExecutionResult) Failed

func (result *ExecutionResult) Failed() bool

Failed returns the indicator whether the execution is successful or not

func (*ExecutionResult) Return

func (result *ExecutionResult) Return() []byte

Return is a helper function to help caller distinguish between revert reason and function return. Return returns the data after execution if no error occurs.

func (*ExecutionResult) Revert

func (result *ExecutionResult) Revert() []byte

Revert returns the concrete revert reason if the execution is aborted by `REVERT` opcode. Note the reason can be nil if no data supplied with revert opcode.

func (*ExecutionResult) Unwrap

func (result *ExecutionResult) Unwrap() error

Unwrap returns the internal evm error which allows us for further analysis outside.

type FilterOpts

type FilterOpts struct {
	Start uint64  // Start of the queried range
	End   *uint64 // End of the range (nil = latest)
}

type Hash

type Hash [32]byte

Hash is an Ethereum hash

func BytesToHash

func BytesToHash(b []byte) Hash

BytesToHash sets b to hash. If b is larger than len(h), b will be cropped from the left.

func HexToHash

func HexToHash(str string) Hash

HexToHash converts an hex string value to a hash object

func (Hash) Bytes

func (h Hash) Bytes() []byte

func (Hash) IsEmpty

func (h Hash) IsEmpty() bool

func (Hash) MarshalText

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

MarshalText implements the marshal interface

func (*Hash) SetBytes

func (h *Hash) SetBytes(b []byte)

SetBytes sets the hash to the value of b. If b is larger than len(h), b will be cropped from the left.

func (Hash) String

func (h Hash) String() string

func (*Hash) UnmarshalText

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

UnmarshalText implements the unmarshal interface

type Header struct {
	ParentHash       Hash
	Sha3Uncles       Hash
	Miner            Address
	StateRoot        Hash
	TransactionsRoot Hash
	ReceiptsRoot     Hash
	LogsBloom        [256]byte
	Difficulty       *big.Int
	Number           uint64
	GasLimit         uint64
	GasUsed          uint64
	Timestamp        uint64
	ExtraData        []byte
	MixHash          Hash
	Nonce            [8]byte
}

type Log

type Log struct {
	Removed          bool
	LogIndex         uint64
	TransactionIndex uint64
	TransactionHash  Hash
	BlockHash        Hash
	BlockNumber      uint64
	Address          Address
	Topics           []Hash
	Data             []byte
	Event            *ParsedEvent
}

func (*Log) MarshalJSON

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

MarshalJSON implements the marshal interface

func (*Log) ParseEvent

func (self *Log) ParseEvent()

func (*Log) UnmarshalJSON

func (r *Log) UnmarshalJSON(buf []byte) error

UnmarshalJSON implements the unmarshal interface

type LogFilter

type LogFilter struct {
	BlockHash *Hash        // used by eth_getLogs, return logs only from block with this hash
	From      *BlockNumber // beginning of the queried range, nil means genesis block
	To        *BlockNumber // end of the range, nil means latest block
	Address   []Address    // restricts matches to event created by specific contracts

	// The Topic list restricts matches to particular event topics. Each event has a list
	// of topics. Topics matches a prefix of that list. An empty element slice matches any
	// topic. Non-empty elements represent an alternative that matches any of the
	// contained topics.
	//
	// Examples:
	// {} or nil          matches any topic list
	// {{A}}              matches topic A in first position
	// {{}, {B}}          matches any topic in first position AND B in second position
	// {{A}, {B}}         matches topic A in first position AND B in second position
	// {{A, B}, {C, D}}   matches topic (A OR B) in first position AND (C OR D) in second position
	Topics [][]Hash
}

func (*LogFilter) MarshalJSON

func (l *LogFilter) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshal interface.

func (*LogFilter) SetFromUint64

func (l *LogFilter) SetFromUint64(num uint64)

func (*LogFilter) SetTo

func (l *LogFilter) SetTo(b BlockNumber)

func (*LogFilter) SetToUint64

func (l *LogFilter) SetToUint64(num uint64)

type LogParser

type LogParser interface {
	ParseLog(log *Log) (*ParsedEvent, error)
}

func GetParser

func GetParser() LogParser

type Network

type Network uint64

Network is a chain id

const (
	// Mainnet is the mainnet network
	Mainnet Network = 1

	// Ropsten is the POW testnet
	Ropsten Network = 3

	// Rinkeby is a POW testnet
	Rinkeby Network = 4

	// Goerli is the Clique testnet
	Goerli = 5
)

type NilParser

type NilParser struct{}

func (*NilParser) ParseLog

func (self *NilParser) ParseLog(log *Log) (*ParsedEvent, error)

type ParsedEvent

type ParsedEvent struct {
	Contract string
	Sig      string
	Values   map[string]interface{}
}

type Receipt

type Receipt struct {
	Status            uint64
	TransactionHash   Hash
	TransactionIndex  uint64
	ContractAddress   Address
	BlockHash         Hash
	From              Address
	BlockNumber       uint64
	GasUsed           uint64
	CumulativeGasUsed uint64
	LogsBloom         []byte
	Logs              []*Log
}

func (*Receipt) AddStorageLogs

func (self *Receipt) AddStorageLogs(logs []*StorageLog)

func (*Receipt) EnsureNoRevert added in v0.1.14

func (self *Receipt) EnsureNoRevert() *Receipt

func (*Receipt) IsReverted

func (self *Receipt) IsReverted() bool

func (*Receipt) MarshalJSON added in v0.1.7

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

MarshalJSON implements the Marshal interface.

func (*Receipt) Thin

func (self *Receipt) Thin() *ThinReceipt

func (*Receipt) UnmarshalJSON

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

UnmarshalJSON implements the unmarshal interface

type StorageLog

type StorageLog struct {
	Address Address
	Topics  []Hash
	Data    []byte
}

type ThinLog

type ThinLog struct {
	Address Address
	Topics  []Hash `json:"topics,omitempty"`
	Data    []byte `json:"data,omitempty"`
	Event   *ParsedEvent
}

type ThinReceipt

type ThinReceipt struct {
	Status          uint64
	TransactionHash Hash
	ContractAddress Address
	From            Address
	GasUsed         uint64
	Logs            []*ThinLog
}

type Transaction

type Transaction struct {
	From        Address
	To          *Address
	Input       []byte
	GasPrice    uint64
	Gas         uint64
	Value       *big.Int
	Nonce       uint64
	V           []byte
	R           []byte
	S           []byte
	BlockHash   Hash
	BlockNumber uint64
	TxnIndex    uint64
	// contains filtered or unexported fields
}

func TransactionFromRlp added in v0.1.7

func TransactionFromRlp(data []byte) (*Transaction, error)

func (*Transaction) Hash

func (t *Transaction) Hash() Hash

func (*Transaction) MarshalJSON

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

MarshalJSON implements the Marshal interface.

func (*Transaction) MarshalRLP

func (t *Transaction) MarshalRLP() []byte

func (*Transaction) MarshalRLPUnsignedWith added in v0.1.7

func (t *Transaction) MarshalRLPUnsignedWith(arena *fastrlp.Arena) *fastrlp.Value

func (*Transaction) MarshalRLPWith

func (t *Transaction) MarshalRLPWith(arena *fastrlp.Arena) *fastrlp.Value

MarshalRLPWith marshals the transaction to RLP with a specific fastrlp.Arena

func (*Transaction) SignHash added in v0.1.7

func (tx *Transaction) SignHash(chainId uint64) Hash

func (*Transaction) ToCallMsg

func (t *Transaction) ToCallMsg() *CallMsg

func (*Transaction) UnmarshalJSON

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

UnmarshalJSON implements the unmarshal interface

func (*Transaction) UnmarshalRLP added in v0.1.7

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

Directories

Path Synopsis
cmd
blake2b
Package blake2b implements the BLAKE2b hash algorithm defined by RFC 7693 and the extendable output function (XOF) BLAKE2Xb.
Package blake2b implements the BLAKE2b hash algorithm defined by RFC 7693 and the extendable output function (XOF) BLAKE2Xb.
bn256
Package bn256 implements the Optimal Ate pairing over a 256-bit Barreto-Naehrig curve.
Package bn256 implements the Optimal Ate pairing over a 256-bit Barreto-Naehrig curve.
bn256/google
Package bn256 implements a particular bilinear group.
Package bn256 implements a particular bilinear group.
evm
Package vm implements the Ethereum Virtual Machine.
Package vm implements the Ethereum Virtual Machine.
runtime
Package runtime provides a basic execution model for executing EVM code.
Package runtime provides a basic execution model for executing EVM code.
storage/overlaydb
* Copyright (C) 2018 The ontology Authors * This file is part of The ontology library.
* Copyright (C) 2018 The ontology Authors * This file is part of The ontology library.
storage/schema
* Copyright (C) 2018 The ontology Authors * This file is part of The ontology library.
* Copyright (C) 2018 The ontology Authors * This file is part of The ontology library.
codec
* Copyright (C) 2018 The ontology Authors * This file is part of The ontology library.
* Copyright (C) 2018 The ontology Authors * This file is part of The ontology library.
common
Package common contains various helper functions.
Package common contains various helper functions.
common/hexutil
Package hexutil implements hex encoding with 0x prefix.
Package hexutil implements hex encoding with 0x prefix.
common/math
Package math provides integer math utilities.
Package math provides integer math utilities.

Jump to

Keyboard shortcuts

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