web3

package module
v0.0.0-...-2d71d60 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2021 License: MPL-2.0 Imports: 7 Imported by: 0

README

Go-Web3

JsonRPC

package main

import (
	"fmt"
	
	web3 "github.com/cybersis2020/go-web3"
	"github.com/cybersis2020/go-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/cybersis2020/go-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"
    
	web3 "github.com/cybersis2020/go-web3"
	"github.com/cybersis2020/go-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"

    web3 "github.com/cybersis2020/go-web3"
    "github.com/cybersis2020/go-web3/jsonrpc"
    "github.com/cybersis2020/go-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)
}

Block tracker

import (
    "fmt"

    web3 "github.com/cybersis2020/go-web3"
    "github.com/cybersis2020/go-web3/jsonrpc"
    "github.com/cybersis2020/go-web3/contract/builtin/ens"
)

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

	tracker = blocktracker.NewBlockTracker(client, WithBlockMaxBacklog(1000))
	if err := tracker.Init(); err != nil {
		panic(err)
	}
	go tracker.Start()

	sub := tracker.Subscribe()
	go func() {
		for {
			select {
			case evnt := <-sub:
				fmt.Println(evnt)
			case <-ctx.Done():
				return
			}
		}
	}
}

Tracker

Complete example of the tracker here

Documentation

Index

Constants

View Source
const (
	Latest   BlockNumber = -1
	Earliest             = -2
	Pending              = -3
)

Variables

View Source
var (
	// ZeroAddress is an address of all zeros
	ZeroAddress = Address{}

	// ZeroHash is a hash of all zeros
	ZeroHash = Hash{}
)

Functions

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

Types

type Address

type Address [20]byte

Address is an Ethereum address

func BytesToAddress

func BytesToAddress(b []byte) Address

BytesToAddress converts bytes to an address object

func HexToAddress

func HexToAddress(str string) Address

HexToAddress converts an hex string value to an address object

func (Address) MarshalText

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

MarshalText implements the marshal interface

func (Address) String

func (a Address) String() string

func (*Address) UnmarshalText

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

UnmarshalText implements the unmarshal interface

type Block

type Block struct {
	Number             uint64
	Hash               Hash
	ParentHash         Hash
	Sha3Uncles         Hash
	TransactionsRoot   Hash
	StateRoot          Hash
	ReceiptsRoot       Hash
	Miner              Address
	Difficulty         *big.Int
	ExtraData          []byte
	GasLimit           uint64
	GasUsed            uint64
	Timestamp          uint64
	Transactions       []*Transaction
	TransactionsHashes []Hash
	Uncles             []Hash
}

func (*Block) Copy

func (b *Block) Copy() *Block

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) Location

func (b BlockNumber) Location() string

func (BlockNumber) String

func (b BlockNumber) String() string

type BlockNumberOrHash

type BlockNumberOrHash interface {
	Location() 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 Hash

type Hash [32]byte

Hash is an Ethereum hash

func BytesToHash

func BytesToHash(b []byte) Hash

BytesToHash converts bytes to a hash object

func HexToHash

func HexToHash(str string) Hash

HexToHash converts an hex string value to a hash object

func (Hash) Location

func (h Hash) Location() string

func (Hash) MarshalText

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

MarshalText implements the marshal interface

func (Hash) String

func (h Hash) String() string

func (*Hash) UnmarshalText

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

UnmarshalText implements the unmarshal interface

type Log

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

func (*Log) MarshalJSON

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

MarshalJSON implements the marshal interface

func (*Log) UnmarshalJSON

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

UnmarshalJSON implements the unmarshal interface

type LogFilter

type LogFilter struct {
	Address   []Address
	Topics    []*Hash
	BlockHash *Hash
	From      *BlockNumber
	To        *BlockNumber
}

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 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 Receipt

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

func (*Receipt) UnmarshalJSON

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

UnmarshalJSON implements the unmarshal interface

type Transaction

type Transaction struct {
	Hash        Hash
	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
}

func (*Transaction) MarshalJSON

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

MarshalJSON implements the Marshal interface.

func (*Transaction) MarshalRLP

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

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) UnmarshalJSON

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

UnmarshalJSON implements the unmarshal interface

Directories

Path Synopsis
builtin/ens
Code generated by go-web3/abigen.
Code generated by go-web3/abigen.
builtin/erc20
Code generated by go-web3/abigen.
Code generated by go-web3/abigen.

Jump to

Keyboard shortcuts

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