首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使web3.eth.sendTransaction()正常工作。此功能不触发。

无法使web3.eth.sendTransaction()正常工作。此功能不触发。
EN

Ethereum用户
提问于 2018-03-06 16:07:13
回答 1查看 1.2K关注 0票数 1

我正在创建这个非常简单的程序,将ETH从一个地址发送到另一个地址。我正在使用rinkeby.infura.io获得免费的乙醚和测试目的。

我的代码似乎运行良好,因为当我在http://localhost:8545上用testrpc测试它并使用虚拟帐户地址时,一切都运行得非常好。但是,当我更改为真实帐户地址并将HttpProvider更改为https://rinkeby.infura.io/时,会出现以下错误:

错误:无效的JSON响应:"“at (D:\Documents\Projects\Eth\node_modules\web3\lib\web3\errors.js:38:16) at HttpProvider.send (D:\Documents\Projects\Eth\node_modules\web3\lib\web3\httpprovider.js:91:22) at RequestManager.send (D:\Documents\Projects\Eth\node_modules\web3\lib\web3\requestmanager.js:58:32) at Eth(D:\Documents\Projects\Eth\routes\index.js:57:11) at D:\Documents\Projects\Eth\routes\index.js:80:12 at Layer.handle 作为手柄_请求 next (D:\Documents\Projects\Eth\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (D:\Documents\Projects\Eth\node_modules\express\lib\( router\route.js:112:3)在Layer.handle 作为手柄_请求

我注意到代码web3.eth.sendTransaction({})中忘记了包含回调函数,因此我将其更改为类似于web3.eth.sendTransaction({}、函数(err、散列){})。它删除了无效的JSON错误消息,但它根本不执行整个sendTransaction(),因为我可以看到余额未被触及。

下面是使用rinkeby.infura.io和回调函数的输出:

下面是我的代码的两个版本:(1)带有sendTransaction()的回调函数,(2)没有回调函数

具有回调函数的(1)

代码语言:javascript
复制
var express = require('express');
var router = express.Router();

var util = require('ethereumjs-util');
var tx = require('ethereumjs-tx');
try {
    var lightwallet = require('eth-lightwallet');
} catch (err) {
delete global._bitcore
    var lightwallet = require('eth-lightwallet');
}
var txutils = lightwallet.txutils;

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/'));

function balance(addr) {
    var start = Date.now();
    var latestBalance = web3.eth.getBalance(addr, "latest");
    var nonce = web3.eth.getTransactionCount(addr, "latest");
    var end = Date.now();
    return nonce;
}

function showBalance(addr) {
    var start = Date.now();
    var latestBalance = web3.eth.getBalance(addr, "latest");
    var nonce = web3.eth.getTransactionCount(addr, "latest");
    var end = Date.now();
    var res = {
        "address": addr,
        "balance": latestBalance + " Wei / " + web3.fromWei(latestBalance).toString() + " ETH",
        "nonce": nonce.toString(),
        "timestamp": (end - start).toString() + "ms"
    }
    return res;
}

function sendBalance(_from, _to) {
    var nonce = balance(_from);
    var amount = 0.05;
    var rawTx = {
        nonce: web3.toHex(nonce),
        gasPrice: web3.toHex(10),
        gasLimit: web3.toHex(21000),
        to: _to,
        value: web3.toHex(amount * 1000000000),
        data: "",
        chainId: 1
    }

    var addFromPrivateKey = new Buffer('4ce80ef53f9c13e5d68737ff078e0660e803f87735fab9c79bf408335be8963d', 'hex');
    var transaction = new tx(rawTx);
    transaction.sign(addFromPrivateKey);
    var res ="";
    var serializedTx = transaction.serialize().toString('hex');
    web3.eth.sendTransaction({ 
        from: _from, 
        to: _to,
        value: web3.toWei(amount, "ether"),
        gas: rawTx.gasLimit,
        price: rawTx.gasPrice,
        nonce: rawTx.nonce
    }, function(error, hash){res = error;});
    var txLog = "";
    // web3.eth.sendRawTransaction('0x' + serializedTx, function(err, result) {
    //  if(err) {
    //      txLog = err;
    //  } else {
    //      txLog = result;
    //  }
    // });
    res = "Status: " + res + " |||| from: " + _from + "\nsendValueETH: " + amount + "\nrawTx: " + JSON.stringify(rawTx, null, 4) + " " + txLog; 
    return res;
}

// Get Homepage
router.get('/', function(req, res) {

    var dti = sendBalance('0xa5d1274a05ab92e3830d81e0e4302498ccb5b22f', '0x6a1366a19b6dbb4d9fe4781f38538e9dc2ec0698');
    dto = showBalance('0xa5d1274a05ab92e3830d81e0e4302498ccb5b22f');
    dtt = showBalance('0x6a1366a19b6dbb4d9fe4781f38538e9dc2ec0698');

    data = {
        "dta": {
            "sender": dto,
            "recipient": dtt,
            "transaction": dti
        }
    }
    res.render('index', {data});
});


module.exports = router;

<#>(2)不带回调函数

代码语言:javascript
复制
var express = require('express');
var router = express.Router();

var util = require('ethereumjs-util');
var tx = require('ethereumjs-tx');
try {
    var lightwallet = require('eth-lightwallet');
} catch (err) {
delete global._bitcore
    var lightwallet = require('eth-lightwallet');
}
var txutils = lightwallet.txutils;

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/'));

function balance(addr) {
    var start = Date.now();
    var latestBalance = web3.eth.getBalance(addr, "latest");
    var nonce = web3.eth.getTransactionCount(addr, "latest");
    var end = Date.now();
    return nonce;
}

function showBalance(addr) {
    var start = Date.now();
    var latestBalance = web3.eth.getBalance(addr, "latest");
    var nonce = web3.eth.getTransactionCount(addr, "latest");
    var end = Date.now();
    var res = {
        "address": addr,
        "balance": latestBalance + " Wei / " + web3.fromWei(latestBalance).toString() + " ETH",
        "nonce": nonce.toString(),
        "timestamp": (end - start).toString() + "ms"
    }
    return res;
}

function sendBalance(_from, _to) {
    var nonce = balance(_from);
    var amount = 0.05;
    var rawTx = {
        nonce: web3.toHex(nonce),
        gasPrice: web3.toHex(10),
        gasLimit: web3.toHex(21000),
        to: _to,
        value: web3.toHex(amount * 1000000000),
        data: "",
        chainId: 1
    }

    var addFromPrivateKey = new Buffer('4ce80ef53f9c13e5d68737ff078e0660e803f87735fab9c79bf408335be8963d', 'hex');
    var transaction = new tx(rawTx);
    transaction.sign(addFromPrivateKey);
    var res ="";
    var serializedTx = transaction.serialize().toString('hex');
    web3.eth.sendTransaction({ 
        from: _from, 
        to: _to,
        value: web3.toWei(amount, "ether"),
        gas: rawTx.gasLimit,
        price: rawTx.gasPrice,
        nonce: rawTx.nonce
    });
    var txLog = "";
    // web3.eth.sendRawTransaction('0x' + serializedTx, function(err, result) {
    //  if(err) {
    //      txLog = err;
    //  } else {
    //      txLog = result;
    //  }
    // });
    res = "Status: " + res + " |||| from: " + _from + "\nsendValueETH: " + amount + "\nrawTx: " + JSON.stringify(rawTx, null, 4) + " " + txLog; 
    return res;
}

// Get Homepage
router.get('/', function(req, res) {

    var dti = sendBalance('0xa5d1274a05ab92e3830d81e0e4302498ccb5b22f', '0x6a1366a19b6dbb4d9fe4781f38538e9dc2ec0698');
    dto = showBalance('0xa5d1274a05ab92e3830d81e0e4302498ccb5b22f');
    dtt = showBalance('0x6a1366a19b6dbb4d9fe4781f38538e9dc2ec0698');

    data = {
        "dta": {
            "sender": dto,
            "recipient": dtt,
            "transaction": dti
        }
    }
    res.render('index', {data});
});


module.exports = router;

值得一提的是,这些都是示例私钥,地址仅用于这里的演示。而且,您也可以忽略rawTx的任何内容:)

下面是一个使用testrpc的成功输出示例:

同样,它可以在testrpc上工作,但不能在rinkeby.infura上工作。我认为它肯定不会在真正的ethereum网络上起作用。我对ethereum和区块链的开发很陌生。任何帮助,即解决我的问题,对我的代码的建议,我会非常感谢各位!提前感谢!

EN

回答 1

Ethereum用户

发布于 2018-11-29 09:55:18

错误消息仍然存在。在包含回调函数之后,它碰巧没有作为结果的一部分呈现,因为error是异步设置的。例如,如果将res = error更改为console.error(error),则可以在现场看到它:Error: Invalid JSON RPC response: ""

之所以使用Invalid JSON RPC response,是因为因弗拉不支持sendTransaction方法,因为它取决于帐户的详细信息。根据文档

INFURA支持Ethereum的JSON方法的子集。大多数不受支持的方法都与私钥有关。

除了直接从sendTransaction回调中读取错误之外,还可以使用类似于curl的方法来发出请求并确认该方法确实不可用。示例:

代码语言:javascript
复制
curl -i -X POST -H "Content-Type: application/json" \
    --data '{"jsonrpc": "2.0", "id": 1, "method": "eth_sendTransaction", "params": []}' \
    "https://rinkeby.infura.io/"

产出:

代码语言:javascript
复制
HTTP/1.1 405 Method Not Allowed
[...]

这种行为也有记录:

如果尝试使用不在此列表中的方法,则将收到不允许的HTTP响应的405方法。

您应该选择使用sendRawTransaction,正如您前面提到的,它位于提供的代码中,可以将已经签名的事务数据发送到恩弗拉。

<#> https://github.com/INFURA/infura/blob/master/docs/source/index.html.md#supported-json-rpc-methods

保持超能力!

/Javi

票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/41906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档