Giter Site home page Giter Site logo

go-web3's Introduction

go-web3

Ethereum Golang API

Development Environment

The requirements to develop are:

  • Golang version 1.14 or later

API

NewWeb3()

Creates a new web3 instance with http provider.

// change to your rpc provider
var rpcProviderURL = "https://rpc.flashbots.net"
web3, err := web3.NewWeb3(rpcProviderURL)
if err != nil {
    panic(err)
}

GetBlockNumber()

Get current block number.

blockNumber, err := web3.Eth.GetBlockNumber()
if err != nil {
    panic(err)
}
fmt.Println("Current block number: ", blockNumber)
// => Current block number:  11997285

SetChainId(chainId int64)

Setup chainId for different network.

web3.Eth.SetChainId(1)

SetAccount(privateKey string) error

Setup default account with privateKey (hex format)

pv, err := crypto.GenerateKey()
if err != nil {
    panic(err)
}
privateKey := hex.EncodeToString(crypto.FromECDSA(pv))
err := web3.Eth.SetAccount(privateKey)
if err != nil {
    panic(err)
}

GetNonce(addr common.Address, blockNumber *big.Int) (uint64, error)

Get transaction nonce for address

nonce, err := web3.Eth.GetNonce(web3.Eth.Address(), nil)
if err != nil {
    panic(err)
}
fmt.Println("Latest nonce: ", nonce)
// => Latest nonce: 1 

NewContract(abiString string, contractAddr ...string) (*Contract, error)

Init contract api

abiString := `[
	{
		"constant": true,
		"inputs": [],
		"name": "totalSupply",
		"outputs": [
			{
				"name": "",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	}
]`
contractAddr := "0x6B175474E89094C44Da98b954EedeAC495271d0F" // contract address
contract, err := web3.Eth.NewContract(abiString, contractAddr)
if err != nil {
    panic(err)
}

Call(methodName string, args ...interface{}) (interface{}, error)

Contract call method

totalSupply, err := contract.Call("totalSupply")
if err != nil {
    panic(err)
}
fmt.Printf("Total supply %v\n", totalSupply)

// => Total supply  10000000000

EncodeABI(methodName string, args ...interface{}) ([]byte, error)

EncodeABI data

data, err := contract.EncodeABI("balanceOf", web3.Eth.Address())
if err != nil {
    panic(err)
}
fmt.Printf("Data %x\n", data)

// => Data 70a08231000000000000000000000000c13a163dd812ed7eb8bb9152651054eae5ee0999 

SendRawTransaction(to common.Address,amount *big.Int,gasLimit uint64,gasPrice *big.Int,data []byte) (common.Hash, error)

Send transaction

txHash, err := web3.Eth.SendRawTransaction(
    common.HexToAddress(tokenAddr),
    big.NewInt(0),
    gasLimit,
    web3.Utils.ToGWei(1),
    approveInputData,
)
if err != nil {
    panic(err)
}
fmt.Printf("Send approve tx hash %v\n", txHash)

// => Send approve tx hash  0x837136c8b6f34b519c049d1cf703d3bba47d32f6801c25d83d0113bdc0e6936a 

Examples

Contributing

Go-Web3 welcome contributions. Please follow the guidelines when opening issues and contributing code to the repo.

Contributing

We follow the fork-and-pull Git workflow:

  1. Fork the repo on GitHub
  2. Clone it to your own machine
  3. Commit changes to your fork
  4. Push changes to your fork
  5. Submit a Pull request for review

NOTE: Be sure to merge the latest changes before making a pull request!

Pull Requests

As outlined in Keavy McMinn's article "How to write the perfect pull request", you should include:

  1. The purpose of the PR
  2. A brief overview of what you did
  3. Tag any issues that the PR relates to and close issues with a keyword
  4. What kind of feedback you're looking for (if any)
  5. Tag individuals you want feedback from (if any)

Issues

Feel free to submit issues and enhancement requests here. Please consider how to ask a good question and take the time to research your issue before asking for help.

Duplicate questions will be closed.

License

The go-web3 source code is available under the LGPL-3.0 license.

go-web3's People

Contributors

chenzhijie avatar jsvisa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

go-web3's Issues

panic: invalid response [228922128185288425133 41075960353443875 1641275375]

contract, err := web3.Eth.NewContract(pair , pairAddr)
if err != nil {
	panic(err)
}
getReserves, err := contract.Call("getReserves")
if err != nil {
	panic(err)        
}

hello,I use it in pancake pair contract get the getReserves, the got the panic: invalid response [228922128185288425133 41075960353443875 1641275375]

Scam Pass Through

If you see this in the code, this is the pass through for scamming

会报错

panic: dial unix https://rpc.flashbots.net: connect: An invalid argument was supplied.

goroutine 1 [running]:
main.main()
操作系统是wind11,和wind2009,跟踪代码到最底层,发现好像是只能支持wind吗!

到底层协议是call FILE_FLAG_BACKUP_SEMANTICS 0x02000000,这里报错是WindowsError:[Error 123] 查询是 文件名、目录名或卷标语法不正确 有点懵了

是否考虑整合一下multicall

是否考虑整合一下multicall

我看app已经开始封装了常用对象,是否考虑整合一下multicall,太常用了因为。

minGW run failed

感觉 windows 上编译不过

# main
C:\Program Files\Go\pkg\tool\windows_amd64\link.exe: running gcc failed: exit status 1
c:/mingw/bin/../lib/gcc/x86_64-w64-mingw32/4.8.2/../../../../x86_64-w64-mingw32/bin/ld.exe: unrecognized option '--high-entropy-va'
c:/mingw/bin/../lib/gcc/x86_64-w64-mingw32/4.8.2/../../../../x86_64-w64-mingw32/bin/ld.exe: use the --help option for usage information
collect2.exe: error: ld returned 1 exit status

NewWeb3WithProxy函数是否可以避免必须手动设置ChainID

func (e *Eth) ChainID() (*big.Int, error)
中有调用 rpc 的 eth_chainId 的方法。

但是我在通过 NewWeb3WithProxy 构建对象时,需要设置 ChainID。这个设置会导致生成的 eth 对象被设置了 chainid,逻辑上就不会调用 rpc 的 eth_chainId,而是从设置缓存读取。

很多链是可以通过 rpc 的 eth_chainId 获取 chainid 的,
我们是否可以避免在 NewWeb3WithProxy 中粗糙的通过provider判断,而是自动从链上读取。

目前我NewWeb3WithProxy构建对象后,无法通过eth获得链chainid,必须自己知道是多少,从外部设置进去。感觉步骤很多余而且多链项目容易出错。

invalid sender error

Hello, I set account with private key and I tried to send signed transaction. but I got error when sending transaction.

{"code":-32000,"message":"invalid sender"}

Can you help me?

HI

在找类似web3.js的golang实现的时候看到了你这个库,我最近也在学习这方面的内容, 不知道方不方便加个QQ或者微信交流

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.