10 geth的javascript控制台中运行自定义API

我需要在geth的控制台中使用自定义API,类似admin,eth,miner,personal等。现在操作如下: 1、自定义API为myAlgo,func为EchoNumber

type API struct {
chain consensus.ChainReader
myAlgo *MyAlgo

}

func (api *API) EchoNumber(ctx context.Context, number uint64) (uint64, error) {

fmt.Println("called echo number")

return number, nil

}

2、在internal/web3ext/web3ext.go中添加echoNumber方法

var Modules = map[string]string{

"admin": Admin_JS,

...

"txpool": TxPool_JS,

"myalgo": MyAlgo_JS,

}

const MyAlgo_JS = `

web3._extend({

property: 'myalgo',

methods: [

new web3._extend.Method({

name: 'echoNumber',

call: 'myalgo_echoNumber',

params: 1,

inputFormatter: [null]

}),

]

})

3、安装go-bindata,

go get github.com/jteeuwen/go-bindata
go install github.com/jteeuwen/go-bindata/go-bindata

并成功运行如下命令,更新bindata.go文件:

go-bindata -nometadata -pkg deps -o bindata.go bignumber.js web3.js
gofmt -w -s bindata.go

4、重新编译geth后运行进入javascript console控制台,无法运行myalgo及相关命令报错,is not defined:

> myalgo
ReferenceError: 'myalgo' is not defined
    at <anonymous>:1:1

> myalgo.echoNumber()
ReferenceError: 'myalgo' is not defined
    at <anonymous>:1:1

请问各位高手,如何解决?谢谢。

请先 登录 后评论

最佳答案 2020-04-22 20:50

你需要注册RPC服务才能使用,否则在控制台初始化时因为无法从已注册API中找到myalgo,而过滤掉myalgo。

做法:

internal/ethapi/backend.go文件中定义的 GetAPIs方法中添加注册:

{
Namespace: "myalgo",
Version:   "1.0",
Service:   &API{},
Public:    true,
},

另外不需要额外的执行 go-bindata。 重新使用make命令编译geth即可。

请先 登录 后评论

其它 0 个回答

  • 1 关注
  • 0 收藏,3516 浏览
  • 张雷 提出于 2020-04-17 12:51

相似问题