ethcli

package module
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2023 License: BSD-2-Clause Imports: 15 Imported by: 2

README

ethcli

Ethereum node client implementing basic interface to RPC-JSON API

Package ethcli implements a simple client interface to an Ethereum node using RPC-JSON API calls as described in https://github.com/ethereum/wiki/wiki/JSON-RPC.

The client simplifies using the Ethereum RPC interface by providing simple methods to call the most used functionality, such as asking for the balance of an address, getting name or decimals of an ERC20 token and sending and getting transactions. The client connects to the node's endpoint (often http://localhost:8545) or you can use third party providers such as infura.io. To connect to infura.io ethereum infrastructure, you need to provide your infura endpoint and a secret password if you are using Infura API v3.

When calling methods, input arguments like addresses, tokens, hashes and amounts need to be "0x"-prefixed strings in hexadecimal (see the tests for reference).

Documentation

Overview

Package ethcli implements a simple client interface to an Ethereum node using RPC-JSON API calls.

The client simplifies using the Ethereum RPC interface by providing simple methods to call the most used functionality, such as asking for the balance of an address, getting name or decimals of an ERC20 token and sending and getting transactions. The client connects to the node's endpoint (often http://localhost:8545) or you can use third party providers such as infura.io. To connect to infura.io ethereum infrastructure, you need to provide your infura endpoint and a secret password if you are using Infura API v3.

When calling methods, input arguments like addresses, tokens, hashes and amounts need to be "0x"-prefixed strings in hexadecimal (see the tests for reference).

Ethereum's RPC-JSON API is described in https://github.com/ethereum/wiki/wiki/JSON-RPC.

Index

Constants

View Source
const (
	ERC20transfer256     = "a9059cbb" // transfer(address,uint256)
	ERC20transferFrom256 = "23b872dd" // transferFrom(address,address,uint256)
	ERC20transfer        = "6cb927d8" // transfer(address,uint)
	ERC20transferFrom    = "a978501e" // transferFrom(address,address,uint)
)

Ethereum ERC20 token methodID (keccak-256 of the function name and arguments).

View Source
const (
	// Gas needed for an ether transfer.
	GasTransferEther uint64 = 21000
	// Gas needed for an ERC20 token transfer.
	GasTransferToken uint64 = 100000
)
View Source
const (
	TrxPending uint8 = 0
	TrxFailed  uint8 = 1
	TrxSuccess uint8 = 2
)

Transaction status constants.

Variables

View Source
var (
	ErrBadKey         = errors.New("bad format key")
	ErrBadTo          = errors.New("bad format to address")
	ErrBadToken       = errors.New("bad format token address")
	ErrBadFrom        = errors.New("bad format from address")
	ErrBadAmt         = errors.New("error converting value returned by node")
	ErrNoBlock        = errors.New("block not available yet")
	ErrNoTrx          = errors.New("transaction receipt not available yet")
	ErrNoToken        = errors.New("address has no valid token defined")
	ErrWrongAmt       = errors.New("bad amount format or amount cannot be over 32 bytes")
	ErrWrongHash      = errors.New("hash of transaction does not match with requested hash")
	ErrInvalidTrxData = errors.New("transaction data received from node is invalid")
	ErrSendTokenData  = errors.New("cannot send token and data at same time")
)

Error codes defined.

Functions

This section is empty.

Types

type EthCli

type EthCli struct {
	*jsonrpc2.Client
}

EthCli is a JSON RPC client.

func Init

func Init(nodeURL, secret string) *EthCli

Init initializes the client connecting to the ethereum node url. A secret password is optional. "secret" is needed for Infura's v3 API.

func (*EthCli) DecodeGetTransactionResponse added in v1.1.0

func (c *EthCli) DecodeGetTransactionResponse(
	hash string, response map[string]interface{},
) (uint64, uint64, []byte, []byte, string, string, string, error)

DecodeGetTransactionResponse returns the block number, gas price and data of the transaction. If the transaction has not been mined block number is 0.

func (*EthCli) End

func (c *EthCli) End() error

End closes the client.

func (*EthCli) EstimateGas

func (c *EthCli) EstimateGas(to, value, data string) (gas uint64, err error)

EstimateGas makes an RPC call to get the estimated gas needed for a transaction that sends "value" to address "to". Optionally, data may be filled and it is also taken into account. To get gasLimit execute in a terminal:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_estimateGas","params":[{"to":"0x1CD434711fBAe1f2d9C70001409Fd82d71fDCCAa", "value":"0xb1a2bc2ec50000", "data":"0xfffe3031"}],"id":1}' -u <user:secret> https://ropsten.infura.io/v3/projectId

func (*EthCli) GasPrice

func (c *EthCli) GasPrice() (price uint64, err error)

GasPrice makes an RPC call to get the current gasPrice. To get gasPrice execute in a terminal:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":1}' http://localhost:8545

There are gasPrice providers for mainNet, for instance:

curl -X POST https://www.ethgasstation.info/json/ethgasAPI.json

func (*EthCli) GetBalance

func (c *EthCli) GetBalance(address, token string) (*big.Int, *big.Int, error)

GetBalance makes an RPC call to get the balance of an address. Returns the balance in ether, and if a token has been specified, it returns the balance of the token too using the ERC20 function balanceOf(address). To check balance (ether):

curl -X POST --data '{"jsonrpc":"2.0", "method":"eth_getBalance", "params": ["0x357dd3856d856197c1a000bbAb4aBCB97Dfc92c4", "latest"], "id":1}' http://localhost:8545

To check balance (ERC20):

curl -X POST --data '{"jsonrpc":"2.0", "method":"eth_call", "params": [{"data":"0x70a08231000000000000000000000000cba75F167B03e34B8a572c50273C082401b073Ed", "to":"0xa34de7bd2b4270c0b12d5fd7a0c219a4d68d732f"},"latest"], "id":1}' http://localhost:8545

func (*EthCli) GetBlockByNumber

func (c *EthCli) GetBlockByNumber(block uint64, full bool, response *map[string]interface{}) (err error)

GetBlockByNumber makes an RPC call to get block data from the node. Arguments:

block: number of the block to get
full: true (gets full data for each transaction in the block), false (only the block hash is provided)
response: pointer to the blockData received from the node

func (*EthCli) GetLatestBlock

func (c *EthCli) GetLatestBlock() (uint64, error)

GetLatestBlock makes an RPC call to get the number of the latest block mined.

func (*EthCli) GetTokenDecimals

func (c *EthCli) GetTokenDecimals(token string) (dec uint64, err error)

GetTokenDecimals makes an RPC call to get a token (identified by contract address) decimals. token: address of the contract that defines the token. It must be ERC20 compliant Executes:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0xa34de7bd2b4270c0b12d5fd7a0c219a4d68d732f","data":"0x313ce567"},"latest"],"id":4}' http://localhost:8545

func (*EthCli) GetTokenIcoOffer

func (c *EthCli) GetTokenIcoOffer(token string) (ico uint64, err error)

GetTokenIcoOffer makes an RPC call to get a token (identified by contract address) unitsOneEthCanBuy. token: address of the contract that defines the token. It must be ERC20 compliant Executes:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0xa34de7bd2b4270c0b12d5fd7a0c219a4d68d732f","data":"0x65f2bc2e"},"latest"],"id":4}' http://localhost:8545

func (*EthCli) GetTokenName

func (c *EthCli) GetTokenName(token string) (string, error)

GetTokenName makes an RPC call to get a token (identified by contract address) name. token: address of the contract that defines the token. It must be ERC20 compliant Executes:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0xa34de7bd2b4270c0b12d5fd7a0c219a4d68d732f","data":"0x06fdde03"},"latest"],"id":4}' http://localhost:8545

func (*EthCli) GetTokenSymbol

func (c *EthCli) GetTokenSymbol(token string) (sym string, err error)

GetTokenSymbol makes an RPC call to get a token (identified by contract address) symbol. token: address of the contract that defines the token. It must be ERC20 compliant Executes:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0xa34de7bd2b4270c0b12d5fd7a0c219a4d68d732f","data":"0x95d89b41"},"latest"],"id":4}' http://localhost:8545

func (*EthCli) GetTransactionByHash

func (c *EthCli) GetTransactionByHash(hash string, response *map[string]interface{}) (err error)

GetTransactionByHash makes an RPC call to get a transaction detail. Arguments:

hash: hash of the transaction to get
response: pointer to the receipt received from the node

func (*EthCli) GetTransactionCount

func (c *EthCli) GetTransactionCount(address, block string) (nonce uint64, err error)

GetTransactionCount makes an RPC call to get the number of transactions ("nonce") sent from an account ("address") at the block number ("block"). Possible values for block are a hexadecimal number, "earliest", "latest" or "pending".

func (*EthCli) GetTransactionReceipt

func (c *EthCli) GetTransactionReceipt(hash string, response *map[string]interface{}) (err error)

GetTransactionReceipt makes an RPC call to get a transaction receipt (status). Arguments:

hash: hash of the transaction to get
response: pointer to the receipt received from the node

func (*EthCli) GetTrx

func (c *EthCli) GetTrx(hash string) (*Trx, error)

GetTrx returns the transaction data for the given hash.

func (*EthCli) SendTrx

func (c *EthCli) SendTrx(fromAddress, toAddress, token, amount string, data []byte, key string, priceRequested uint64, dryRun bool,
) (uint64, uint64, []byte, error)

SendTrx sends a transaction to the blockchain returning the gas price and limit and the tx hash or an error. If sending an ERC20 token, the argument token must be a valid 20-byte address and data empty. If priceRequested is 0, a suggested gas price will be sought from the blockchain. Use dryRun = true for testing (it will not send the transaction to the blockchain but still provide a valid hash).

type Trx added in v1.1.0

type Trx struct {
	Hash                 string
	To, From             string
	Amount               string
	Token, Data          []byte
	Status               uint8
	TS                   int32
	Blk, Price, Gas, Fee uint64
}

Trx is an ethereum transaction.

Jump to

Keyboard shortcuts

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