我在一个名为Rinkeby的HelloWorld测试网上部署了一个简单的MyEtherWallet稳固契约,当然,我可以与它交互。现在,我想通过web3.jsAPI方法(如果可能的话,用javascript代码)与该契约进行交互。我有谷歌这个,但不知道从哪里开始。
在这里,我想通过web3.jsapi在javascript中调用getWord()函数。
pragma solidity ^0.4.0
contract HelloWorld{
string word = "Hello world";
function getWord() constant returns(string){
return word;
}
}发布于 2017-09-28 17:58:49
首先,项目中需要有web3.js模块。您可以参考这里作为指南。
一旦添加了web3,您就可以使用web3对象通过运行本地节点或通过注入web3与诸如元问句之类的服务与Ethereum网络进行交互。
用于检查元掩码或连接到本地节点的示例代码段是,
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use Mist/MetaMask's provider
window.web3 = new Web3(web3.currentProvider);
} else {
console.log('No web3? You should consider trying MetaMask!')
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}注意,要使用,
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))需要在端口8545上启用rpc的节点在本地运行,可以通过运行以下命令来完成:
geth --rpc --rpcaddr <ip> --rpcport <portnumber><ip>为localhost,<portnumber>为8545。
由于您希望具体地连接到Rinkeby网络,您可以在这里查找如何将完整节点与Rinkeby同步,如果使用元问询,您可以从插件-UI可用的下拉列表中选择网络。
在初始化了web3对象之后,您可以使用JavaScript Web3 API作为文档化的这里与ethereum网络进行交互。
希望这能有所帮助!
https://ethereum.stackexchange.com/questions/27334
复制相似问题