How to do it...

In order to read data from smart contracts, we will have to perform these steps:

  1. Create a contract instance with the ABI and the deployed address. If you are using web3.js v0.2x.x, use the following methods to create an instance:
// Create a contract object
var
MyContract = web3.eth.contract(<ABI>); // Create an instance with address var contractInstance = MyContract.at("<Address>");

For those who are using the upcoming version of web3js ( v1.x.x), use the following method to create an instance:

var contractInstance = new web3.eth.Contract(
"<ABI>",

"<Address>"
);
  1. Read data from the smart contract using the call method. This executes the code in the Ethereum Virtual Machine (EVM) and returns the value. This method does not modify the state of the contract.

  2. Consider the following contract method, which accepts a parameter and returns a value:
// Solidity contract
contract Test {
function sample (uint _a) pure public returns (uint) {
return _a * 2;
}
}
  1. Call the sample function from the preceding contract using the contract instance, as illustrated here:
// For v0.2x.x
var result = contractInstance.sample(10); console.log(result) // 20

// For v1.x.x
MyContract.methods.sample(10).call()
.then(console.log); // 20
  1. Let's examine another example, which returns multiple values:
// Solidity contract
contract Test {
function sample () pure public
returns (string testString, uint testNumber) {
return ("hello", 100);
}
}
  1. The following web3.js script can be used to call the sample() method in the preceding Test contract:
// For v0.2x.x
var result = contractInstance.sample(); console.log(result);
// Output
> {
'0': 'hello',
'1': '100'

}


// For v1.x.x
MyContract.methods.sample().call()
.then(console.log);
// Output
> Result {
'0': 'hello',
'1': '100',
testString: 'hello',
testNumber: '100'
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.169