4

I have deployed a simple HelloWorld Solidity contract on one of the Ethereum Testnet called Rinkeby with MyEtherWallet and of-course I can interact with it. Now I want to interact with that contract through web3.js API methods, if possible, in javascript code. I have Google this but could not get any idea where to start.

Here I want to call getWord() function in javascript through web3.js API.

pragma solidity ^0.4.0

contract HelloWorld{
    string word = "Hello world";

    function getWord() constant returns(string){
       return word;
    }

}
2
  • When you want to post a code, better not to use images. You can format text indicate codes. You may refer here Commented Sep 28, 2017 at 15:10
  • 1
    will be careful next time.
    – Hafiz Atif
    Commented Sep 28, 2017 at 17:23

1 Answer 1

1

First you need to have web3.js module in your project. You may refer here for guide.

Once you have added web3 you can use the web3 object to interact with an Ethereum network by running an local node or via injected web3 with services like metamask.

Sample code snippet to check for metmask or connect to local node is,

// 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"));
  }

You may refer metamask faq and this post for more details.

Note that to use,

window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))

you need to have a node running locally with the rpc enabled at the port:8545, you can do it by running the command:

geth --rpc --rpcaddr <ip> --rpcport <portnumber>

with the <ip> being localhost and <portnumber> being 8545.

Since you want to specifically connect to Rinkeby network, you may refer here to find how to synchronize a full-node with Rinkeby and if using metamask you can select the network from the dropdown available with the plugin-UI.

And with the web3 object initialized, you can use JavaScript Web3 API to interact with the ethereum network as documented here.

Hope this helps!

2
  • very thanks sir. One more thing, only metamask extension is enough to work with web3.js? or I need to install web3 too?
    – Hafiz Atif
    Commented Sep 28, 2017 at 18:54
  • you re welcome, you need Web3 . Commented Sep 29, 2017 at 0:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.