web3

package module
v0.0.0-...-84bdd1a Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2022 License: MPL-2.0 Imports: 8 Imported by: 0

README

Go-Web3

JsonRPC

package main

import (
	"fmt"
	
	web3 "github.com/0xhelloweb3/go-web3"
	"github.com/0xhelloweb3/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)
}

erc20 代币转账

测试: rinkey 测试网

  • UNI 合约地址: 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984T
  • WETH 合约地址: 0xc778417E063141139Fce010982780140Aa0cD5Ab

目标:在rinkey测试网完成erc20代币转账


import (
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"os"

	web3 "github.com/0xhelloweb3/go-web3"
	"github.com/0xhelloweb3/go-web3/abi"
	"github.com/0xhelloweb3/go-web3/contract"
	"github.com/0xhelloweb3/go-web3/jsonrpc"
	"github.com/0xhelloweb3/go-web3/wallet"
)

var (
	privateKeyHex = ""
	//rinkey 测试网合约地址,bsc等其他evm同理
	RpcUrl                       = "https://rinkeby.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"
	chainID                      = uint64(4)
	UniSwapRouterContractAddress = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
	RinKeyWETH                   = "0xc778417E063141139Fce010982780140Aa0cD5Ab"
	RinKeyUni                    = "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984"
)

func main() {
	// 从私钥初始化钱包
	hextseed, _ := hex.DecodeString(privateKeyHex)
	walletkey, _ := wallet.NewWalletFromPrivKey(hextseed)

	// 初始化jsonRpc
	web3Client, err := jsonrpc.NewClient(RpcUrl)
	if err != nil {
		fmt.Printf("Error creating web3 client: %v\n", err)
		os.Exit(1)
	}
	// 获取eth余额
	found, _ := web3Client.Eth().GetBalance(walletkey.Address(), web3.Latest)

	fmt.Printf("eth 代币余额: %v", found)
	// uni 代币合约地址
	web3ContractAddress := web3.HexToAddress(RinKeyUni)
	//erc20合约abi文件所在目录,也可以加载任意合约abi
	// [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_upgradedAddress","type":"address"}],"name":"deprecate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"deprecated","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_evilUser","type":"address"}],"name":"addBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"upgradedAddress","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maximumFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"_totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_maker","type":"address"}],"name":"getBlackListStatus","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newBasisPoints","type":"uint256"},{"name":"newMaxFee","type":"uint256"}],"name":"setParams","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"issue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"redeem","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"basisPointsRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBlackListed","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_clearedUser","type":"address"}],"name":"removeBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"MAX_UINT","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_blackListedUser","type":"address"}],"name":"destroyBlackFunds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_initialSupply","type":"uint256"},{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Issue","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newAddress","type":"address"}],"name":"Deprecate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"feeBasisPoints","type":"uint256"},{"indexed":false,"name":"maxFee","type":"uint256"}],"name":"Params","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_blackListedUser","type":"address"},{"indexed":false,"name":"_balance","type":"uint256"}],"name":"DestroyedBlackFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"AddedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"RemovedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"}]

	abiBytes, err := ioutil.ReadFile("abi/erc20ABI.json")
	if err != nil {
		fmt.Println("Error when reading ERC20 ABI from file.")
	}
	// 创建web3 abi 实例
	abi, err := abi.NewABI(string(abiBytes))
	if err != nil {
		fmt.Println("Error when creating ERC20ABI", err)
		return
	}
	contractInstance := contract.NewContract(web3ContractAddress, abi, web3Client)
	contractInstance.SetFrom(web3.HexToAddress(walletkey.Address().String()))
	TransferTxn := contractInstance.Txn("transfer",
		web3.HexToAddress("transfer地址"), 100000)

	// 这里可以重新定义gasprice,limit,nonce等
	web3Txn, _ := TransferTxn.BuildTx()

        // 也可以:chainID,_ := web3Client.Eth().ChainID() 来根据rpc获取chainId
	signer := wallet.NewEIP155Signer(chainID)
	signWeb3Txn, err := signer.SignTx(web3Txn, walletkey)
	if err != nil {
		fmt.Printf("Error when signing transaction: %v\n", err)
	}
	data, _ := signWeb3Txn.MarshalRLPTo(nil)

	// send the transaction
	hash, err := web3Client.Eth().SendRawTransaction(data)
	if err != nil {
		fmt.Printf("Error when sending transaction: %v\n", err)
	}
	fmt.Printf("hash:%v", hash)
}

Documentation

Index

Constants

This section is empty.

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

func Keccak256

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

Keccak256 calculates the Keccak256

Types

type AccessEntry

type AccessEntry struct {
	Address Address
	Storage []Hash
}

type AccessList

type AccessList []AccessEntry

func (*AccessList) MarshalRLPTo

func (a *AccessList) MarshalRLPTo(dst []byte) ([]byte, error)

func (*AccessList) MarshalRLPWith

func (a *AccessList) MarshalRLPWith(arena *fastrlp.Arena) (*fastrlp.Value, error)

func (*AccessList) UnmarshalRLP

func (a *AccessList) UnmarshalRLP(buf []byte) error

func (*AccessList) UnmarshalRLPWith

func (a *AccessList) UnmarshalRLPWith(v *fastrlp.Value) error

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

func (a Address) Bytes() []byte

Bytes returns the bytes of the Address

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
const (
	Latest   BlockNumber = -1
	Earliest BlockNumber = -2
	Pending  BlockNumber = -3
)

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
	Gas      *big.Int
	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) Bytes

func (h Hash) Bytes() []byte

Bytes returns the bytes of the Hash

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 Key

type Key interface {
	Address() Address
	Sign(hash []byte) ([]byte, error)
}

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)

func (*LogFilter) UnmarshalJSON

func (lf *LogFilter) UnmarshalJSON(buf []byte) error

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 Network = 5
)

type Receipt

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

func (*Receipt) UnmarshalJSON

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

UnmarshalJSON implements the unmarshal interface

type Transaction

type Transaction struct {
	Type TransactionType

	// legacy values
	Hash     Hash
	From     Address
	To       *Address
	Input    []byte
	GasPrice uint64
	Gas      uint64
	Value    *big.Int
	Nonce    uint64
	V        []byte
	R        []byte
	S        []byte

	// jsonrpc values
	BlockHash   Hash
	BlockNumber uint64
	TxnIndex    uint64

	// eip-2930 values
	ChainID    *big.Int
	AccessList AccessList

	// eip-1559 values
	MaxPriorityFeePerGas *big.Int
	MaxFeePerGas         *big.Int
}

func (*Transaction) GetHash

func (t *Transaction) GetHash() (hash Hash, err error)

GetHash returns the Hash of the transaction

func (*Transaction) MarshalJSON

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

MarshalJSON implements the Marshal interface.

func (*Transaction) MarshalRLPTo

func (t *Transaction) MarshalRLPTo(dst []byte) ([]byte, error)

MarshalRLPTo marshals the transaction to a []byte destination

func (*Transaction) MarshalRLPWith

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

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

func (*Transaction) UnmarshalRLP

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

func (*Transaction) UnmarshalRLPWith

func (t *Transaction) UnmarshalRLPWith(v *fastrlp.Value) error

type TransactionType

type TransactionType int
const (
	TransactionLegacy TransactionType = 0
	// eip-2930
	TransactionAccessList TransactionType = 1
	// eip-1559
	TransactionDynamicFee TransactionType = 2
)

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