calling smart contracts methods using web3 ethereum
You can call contract functions by either using contract.methodName.call()
, contract.methodName.sendTransaction()
, or contract.methodName()
methods. The last version simply delegates to one of the first two depending on the method type (ie, if it's a constant
). See the Contract Methods section in the docs.
The parameter list starts with the parameters for the function itself (if any), followed by an optional transaction object, followed by the callback. To call your createRandomAgency()
method, you would do this:
const contract = web3.eth.contract(contractAbi);
const contractInstance = contract.at(contractAddress);
const transactionObject = {
from: fromAccount,
gas: gasLimit
gasPrice: gasPriceInWei
};
contractInstance.createRandomAgency.sendTransaction('name', transactionObject, (error, result) => { // do something with error checking/result here });
The list of available options for the transaction object can be found here.
To call your public agencies
array, it would look like
contractInstance.agencies.call(0, (error, result) => {
if (!error) {
console.log(result.name);
console.log(result.dna);
}
}); // transaction object not needed
I think you should try something like this-:
var contractAbi= "" //here put your contract abi in json string
var deployedContract = web3.eth.contract(abi).at("contract address");
//now you should be able to access contract methods
deployedContract.agencies.call({from:address}, function(err,data){
console.log(data);
});
Test this out once.
Try using callbacks or promises. The following code worked for me, when I wanted to get the return value from one of my contract's methods:
const contract = web3.eth.contract(contractABI);
const contractInstance = contract.at(this.contractAddress);
return new Promise((resolve, reject) => {
contractInstance.**yourMethod**.call(function (error, result) {
if (error) {
console.log(error);
} else {
resolve(result);
}
});
}) as Promise<number>;
Also check out: https://github.com/ethereum/wiki/wiki/JavaScript-API#using-callbacks
It's 2022 now, and seems web3/contracts has some changes, so let me leave an answer here.
Assuming you are using truffle.
Step1. create a truffle project , and install a ganache network at your local machine.
Step2. create a contract and make it deployed. get its address and network (e.g. ganache )
truffle deploy --network=ganache
Step3. run the script file below by: truffle exec call.js --network=ganache
// Filename is: call.js
// you need an address of the contract
const CONTRACT_ADDRESS = "0x7545eCD147210f38EF88142cd94f5Dd0C98E418D"
// you also need the abi of the contract
const contractJson = require('./build/contracts/VeryGoodNftWithMaxSupply.json')
module.exports = async function (callback) {
// initialize the contract from web3,
const contract = new web3.eth.Contract( contractJson.abi, CONTRACT_ADDRESS );
// get the network
const network = await web3.eth.net.getNetworkType()
// call the `name` method. which is a view method.
let result = await contract.methods.name().call()
console.info("name: ", result)
// call the `mint` method. which need a TX operation,
const tx = contract.methods.mint('0xc0dD5021e298dB57bEF361C735cd1C04cef2E48A')
// send this tx.
const receipt = await tx
.send({
// used first account from your wallet.
from: (await web3.eth.getAccounts())[0],
gas: await tx.estimateGas(),
})
.on('transactionHash', (txhash) => {
console.log(`Mining transaction ... network: ${network}, tx: ${txhash}`)
})
.on('error', function(error){
console.error(`An error happened: ${error}`)
callback()
})
.then(function(receipt){
// Success, you've minted the NFT. The transaction is now on chain!
console.log(
`Success: The NFT has been minted and mined in block ${receipt.blockNumber}`)
callback()
})
}
conclusion
for "view" function, you should use "call"
for the function which need an tx, you should use "send" and "once", "on"
for more details, please check this demo: https://github.com/sg552/test_erc721_in_truffle_ganache
also refer to:http://siwei.me/blog/posts/blockchain-web3-contract