Web3js

呼叫函式時 JSON RPC 響應無效

  • July 10, 2018

我在 wordpress 網站上製作了一個 web3js 腳本,但是在執行以下程式碼時,我得到一個無效的 JSON RPC 響應。

var Web3 = require("web3");
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider("https://ropsten.infura.io/xxxxxxxxxxx"));
var accounts = web3.eth.accounts;
var abi=[{"constant":false,"inputs":[{"name":"document","type":"string"},{"name":"timestamp","type":"uint256"}],"name":"notarize2","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"document","type":"string"}],"name":"checkDocument","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"proof","type":"bytes32"},{"name":"timestamp","type":"uint256"}],"name":"storeProof","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"source","type":"string"}],"name":"stringToBytes32","outputs":[{"name":"result","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"proof","type":"bytes32"}],"name":"hasProof","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}];
web3.eth.defaultAccount="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var poe = web3.eth.contract(abi).at("YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY");
console.log(poe.address);
result="test";
var today = new Date();
var todayI = today.getFullYear()*10000+ (today.getMonth()+1)*100+today.getDate();
console.log(todayI);                     
poe.notarize2(result,todayI,{gas:2000000});

該設置通過 testrpc (localhost) 和 Remix / Metamask 完美執行,我可以驗證合約是否正確部署在 Ropsten 上並且執行良好。

有任何想法嗎?這是我第一次嘗試這個。

嘗試將帳戶設置為字元串地址。作為 Smarx,作為 infura 的公共節點不處理像帳戶這樣的私有方法。此外,當使用元遮罩時,此帳戶集以及 web.accounts

$$ 0 $$

我不確定這是您唯一的問題,但您尚未指定用於進行此交易的帳戶。Infura 作為一個公共節點,不能持有任何人的私鑰,所以它不知道沒有賬戶。

如果您希望頁面的查看者進行交易,您需要使用 MetaMask 之類的東西,而不是直接連接到節點。

如果您想以某種方式使用自己的帳戶進行交易,則必須在伺服器端進行,因為您無法讓網站的查看者訪問您的私鑰。

https://programtheblockchain.com/posts/2017/12/13/building-decentralized-apps-with-ethereum-and-javascript/可能會有所幫助,尤其是“連接到節點”部分,它解釋了 MetaMask 的作用。

引用自:https://ethereum.stackexchange.com/questions/34655