web3

package module
v1.1.6 Latest Latest
Warning

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

Go to latest
Published: May 29, 2023 License: MIT Imports: 11 Imported by: 0

README

golang-web3

install

go get -u github.com/mover-code/golang-web3.git@latest

go get -u github.com/btcsuite/btcd@v0.22.0-beta 遇到ambiguous import

desc

使用go操作区块链账户,发起交易,查询账户资产、合约交互、部署,事件监听等功能

use

  • 创建一个web3实例
// It creates a new client for the given url.
//
// Args:
//   url (string): The address of the RPC service.
func NewCli(url string) *jsonrpc.Client {
    cli, err := jsonrpc.NewClient(url)
    if err != nil {
        panic(fmt.Sprintf("error:%s", url))
    }
    return cli
}
  • 数据签名示例
    privateKey, _ := crypto.HexToECDSA(key)  // 账户私钥
    u256, _ := abi.NewType("uint256")
    account, _ := abi.NewType("address")
    type Ord struct {
        Id      *big.Int
        Account web3.Address
        Amount  *big.Int
        Fee     *big.Int
        Solt    *big.Int
        End     *big.Int
        Type    *big.Int
        State   *big.Int
    }

     argumentInfo := []*abi.TupleElem{
        &abi.TupleElem{
            Name: "id",
            Elem: u256,
        },
        &abi.TupleElem{
            Name: "account",
            Elem: account,
        },
        &abi.TupleElem{
            Name: "amount",
            Elem: u256,
        },
        &abi.TupleElem{
            Name: "solt",
            Elem: u256,
        },
        &abi.TupleElem{
            Name: "end",
            Elem: u256,
        },
        &abi.TupleElem{
            Name: "type",
            Elem: u256,
        },
    }

    param := abi.NewTupleType(argumentInfo)
    
    // 数据hash
    hash, _ := param.Encode(&Ord{ 
        Id:      id,
        Account: addr,
        Amount:  withDrawAmount,
        Fee:     big.NewInt(0),
        Solt:    solt,
        End:     endTime,
        Type:    wType,
        State:   big.NewInt(0),
    })

    hashs := crypto.Keccak256Hash(signString(""), crypto.Keccak256(hash)) // 按照合约中的方式组装数据
    signature, _ := crypto.Sign(hashs.Bytes(), privateKey) // 使用私钥签名获取签名后的数据
    r,s,v := SignRSV(signature) // 签名后的rsv数据
  • 验证签名信息示例
func VerifySig(msg, from, sigHex string) bool {

    sig := hexutil.MustDecode(sigHex)
    if sig[64] != 27 && sig[64] != 28 {
        return false
    }
    sig[64] -= 27

    addr, _ := wallet.Ecrecover(web3.SignHash([]byte(msg)), sig)
    return addr == web3.HexToAddress(from)
}
  • 代币转账示例 主币

import(
    web3 "github.com/mover-code/golang-web3"
    "github.com/mover-code/golang-web3/jsonrpc"
    "github.com/mover-code/golang-web3/wallet"

)
     // rpc地址
    cli, err := jsonrpc.NewClient(url)
    if err != nil {
        panic(fmt.Sprintf("error:%s", url))
    }

    block, _ := cli.Eth().BlockNumber() // 获取当前区块
    balance, _ := cli.Eth().GetBalance(web3.HexToAddress(addr), web3.BlockNumber(block)) // 查询账户余额

    nonce, err := cli.Eth().GetNonce(sender, web3.BlockNumber(block)) // 发起交易账户的序号
    gas, _ := cli.Eth().GasPrice() // 当前gas
    gasLimit, err := cli.Eth().EstimateGas(&web3.CallMsg{
        From:     sender,    // 发起账户
        To:       &receiver, // 接收账户
        GasPrice: gas,
        Value:    big.NewInt(amount), // 转账金额
    })
    // 组装交易信息
    t := &web3.Transaction{
        From:        sender,
        To:          &receiver,
        Value:       big.NewInt(100000000000000000),
        Nonce:       nonce,
        BlockNumber: uint64(block),
        GasPrice:    gas,
        Gas:         gasLimit,
    }

    chainId, _ := cli.Eth().ChainID()
    signer := wallet.NewEIP155Signer(chainId.Uint64()) 
    byteKey, _ := hex.DecodeString(private_hash) // 发起交易账户 私钥
    key, _ := wallet.NewWalletFromPrivKey(byteKey)
    data, err := signer.SignTx(t, key) // 签名数据
    cli.Eth().SenSignTransaction(data) // 发起交易

Documentation

Overview

* @Author: small_ant xms.chnb@gmail.com * @Time: 2022-01-15 13:50:16 * @LastAuthor: small_ant xms.chnb@gmail.com * @lastTime: 2022-12-08 14:14:42 * @FileName: units * @Desc: * * Copyright (c) 2022 by small_ant xms.chnb@gmail.com, All Rights Reserved.

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 FWei

func FWei(i *big.Int) *big.Int

`FWei` converts a `big.Int` from wei to ether

Args:

i: The amount of Wei you want to convert.

func Gwei

func Gwei(i uint64) *big.Int

func Keccak256 added in v1.1.4

func Keccak256(buf []byte) []byte

It takes a byte array, and returns a byte array

Args:

buf ([]byte): The data to be hashed.

Returns:

The hash of the input buffer.

func Keccak256HashData added in v1.1.4

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

It takes a variable number of byte slices and returns a single byte slice

Returns:

The hash of the data.

func SignHash added in v1.1.4

func SignHash(data []byte) []byte

It takes a byte array, converts it to a string, prepends a string to it, and then hashes the result

Args:

data ([]byte): The data to sign.

Returns:

The hash of the message.

func SignRSV added in v1.1.3

func SignRSV(isig interface{}) ([32]byte, [32]byte, uint8)

It takes a signature in the form of a byte array or hex string, and returns the R, S, and V values as byte arrays and a uint8

Args:

isig: signature

func SignString added in v1.1.4

func SignString(data string) []byte

It takes a string and returns a byte array

Args:

data (string): The data to sign.

Returns:

The return value is a byte array.

func ToDecimal added in v1.1.3

func ToDecimal(ivalue interface{}, decimals int) decimal.Decimal

It takes an interface{} and converts it to a decimal.Decimal

Args:

ivalue: The value to convert to a decimal.
decimals (int): The number of decimal places to round to.

func ToWei added in v1.1.3

func ToWei(iamount interface{}, decimals int) *big.Int

It takes an amount and a decimal count, and returns the amount in wei

Args:

iamount: The amount of tokens you want to send.
decimals (int): The number of decimals the token uses.

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) CheckSum added in v1.1.2

func (a Address) CheckSum() string

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
	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.
fastrlp module

Jump to

Keyboard shortcuts

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