web3.eth.subscribe未针对web3版本1.0.0-beta.27实现

问题描述 投票:2回答:2

我在web3版本1.0.0-beta.27上,我正在运行一个私有的以太坊区块链用于测试目的。区块链是挖掘并有两个用户,现在我想subscribe到区块链中的事件并执行一些操作。代码如下:

var Web3 = require("web3");     

var ether_port = 'http://localhost:8545'
var web3       = new Web3(new Web3.providers.HttpProvider(ether_port));

web3.eth.subscribe("pendingTransactions"
                  , function(err, result){
    if (err){ console.log(err) }
    else { console.log("result: ", result) }
});

我有类似的东西:

Error: The current provider doesn't support subscriptions: HttpProvider
at Subscription.subscribe 

从某种意义上说,当我在web3.eth.subscribe控制台上执行node.js时,我得到的结果并不令人惊讶:

{ [Function] call: undefined }

即使web3-1.0.0的文档声明可以使用该函数:https://web3js.readthedocs.io/en/1.0/web3-eth-subscribe.html

  1. 那么这只是文档与实际实现不同步的问题吗?我用错了吗?
  2. 如果没有实现,那么收听链中变化的最佳方式是什么?例如,如果我想要实时更新用户的帐户余额?这是除了一个函数的天真实现,该函数每隔n分数对链进行ping操作。
node.js blockchain ethereum web3
2个回答
6
投票

正如错误所示,pub / sub不能通过HTTP获得。但是,您可以通过WS使用它。因此,您引用的文档不是100%错误,它只是省略了代码的提供程序部分。

尝试使用Web套接字连接启动节点(geth --ws --wsport 8545 ...,假设您正在使用geth),并更改为WebsocketProvider

var Web3 = require("web3");     

var ether_port = 'ws://localhost:8545'
var web3       = new Web3(new Web3.providers.WebsocketProvider(ether_port));

web3.eth.subscribe("pendingTransactions"
                  , function(err, result){
    if (err){ console.log(err) }
    else { console.log("result: ", result) }
});

查看关于此discussion ticket的第4条评论。


0
投票

使用附加的JS控制台打开它的更好方法

您可以使用> geth attach'ipc path'附加(即在我的情况下是/home/dev/.ethereum/geth.ipc)

之后,您将连接到运行geth节点并使用管理API ..现在您可以使用

admin.startWS(“localhost”,“端口号”)

当你想关闭连接时,你可以使用下面的命令

admin.stopWS()

关心开发

© www.soinside.com 2019 - 2024. All rights reserved.