Calling a Smart Contract method using Web3 1.0 - blockchain

Presently, I have a smart contract successfully deployed to the Rinkeby testnet, I'm having trouble accessing the method in question using web3 version 1.0.
Here's my web3 code, which instantiates a contract instance and calls a contract method:
const contractInstance = new web3.eth.Contract(abiDefinition, contractAddress);
var value = web3.utils.toWei('1', 'ether')
var sentTransaction = contractInstance.methods.initiateScoreRetrieval().send({value: value, from: fromAddress})
console.log('event sent, now set listeners')
sentTransaction.on('confirmation', function(confirmationNumber, receipt){
console.log('method confirmation', confirmationNumber, receipt)
})
sentTransaction.on('error', console.error);
And here is my smart contract, or rather a version of it stripped down to the relevant bits:
contract myContract {
address private txInitiator;
uint256 private amount;
function initiateScoreRetrieval() public payable returns(bool) {
require(msg.value >= coralFeeInEth);
amount = msg.value;
txInitiator = msg.sender;
return true;
}
}
I am not able to get to the console.log that is setting the event listeners on the web3 side, and I am not getting an error of any kind thrown. I'm certainly not getting the consoles from the actual event listeners. I am guessing something is wrong with the way I'm sending the transaction, but I think I am correctly following the pattern documented below: https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-send
Does anyone have any insight on how to use web3 1.0 to make contract method calls correctly? Am I doing something wrong with how I'm passing options, etc.?
Thanks!

I believe you forgot to specify your HttpProvider for your web3, thus you're not connecting to live Rinkeby network, and by default web3 is running on you local host, which is why even if you provide the right contract address, there's nothing there.
To connect to live network, I would strongly encourage you to use Infura Node by ConsenSys.
const Web3 = require("web3");
const web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io"));
Then by now, everything should work perfectly fine.

First, you need to generate your transaction ABI using encodeABI(), here is an example:
let tx_builder = contractInstance.methods.myMethod(arg1, arg2, ...);
let encoded_tx = tx_builder.encodeABI();
let transactionObject = {
gas: amountOfGas,
data: encoded_tx,
from: from_address,
to: contract_address
};
Then you have to sign the transaction using signTransaction() using private key of sender. Later you can sendSignedTransaction()
web3.eth.accounts.signTransaction(transactionObject, private_key, function (error, signedTx) {
if (error) {
console.log(error);
// handle error
} else {
web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('receipt', function (receipt) {
//do something
});
}

Related

Unable to call safeTransferFrom method from a JS api file

I have deployed my ERC721 contract on polygon testnet from owner(ox43b....81). I have created a small node server to interact with my contract through web3. I m using truffle config
//truffle-config.js
polygon-testnet: {
provider: new HDWalletProvider(privateKey, https://rpc-mumbai.maticvigil.com),
network_id: 80001,
gas: 6000000,
gasPrice: 10000000000,
confirmations: 2,
timeoutBlocks: 200,
skipDryRun: true
}
//index.js file
function test(){
const owner = await myContract.methods.owner().call()
console.log('contract owner', owner) //ox43b....81
//miniting token
const mint = await myContract.methods
.safeMint(owner,1001, 'google.com')
.send({ from: owner, gas: 100000 }) // is this the write way of calling ??
//token transfer
const transfer = await myContract.methods
.safeTransferFrom(acc1, acc2, 1003)
.send({ from: acc1, gas: 1000000 }) // is this the write way of calling ??
}
bcz i m getting err in both function calling: Error: Returned error: unknown account.
NOTE: I am not calling my contract func from truffle console. I m calling through a JS api file index.js
I know there is another way by using web3.eth.accounts.signTransaction() to mint & transfer the token.
Q.1 Is signing is reqd? Can't we access the contract method directly as i did above ?
Q.2 By using web3.eth.accounts.signTransaction() method i can able to mint the tokens successfully but i am facing issue in token transfer (using safeTransferFrom()). There are two cases:
case 1: i am transferring the token which is created/minted by contract owner(ox43b....81) to any other individual user address.
const fromAddress = 'ox43b....81' //owner of the contract
const toAddress = '0x26....7D'
const tokenId = 10001 // created by owner(ox43b....81)
const tx = {
from: ownerAddress, // ox43b....81 --> owner who created contract
to: contractAddress,// 0xfe.....24
nonce: nonce, // nonce with the no of transactions from our owner address
gas: 1000000, // fee estimate to complete the transaction
data: await myContract.methods
.safeTransferFrom(fromAddress, toAddress, tokenId)
.encodeABI()
}
// do signing stuff & send it
so in this case i m able to transfer the token successfully.
case 2: i am transferring the token which is created/minted by another(not contract owner) user(0x26....7D) to any other individual user address / or to owner.
const fromAddress = '0x26....7D' (not the owner of contract)
const toAnyAddress = '0x5e....5a' // any other user
const tokenId = 10002 // created by user '0x26....7D' (not the owner of contract)
const nonce = await web3.eth.getTransactionCount(fromAddress, 'latest')
const tx = {
from: fromAddress, // 0x26....7D -> is this right? or i put contract owner adr?
to: contractAddress,// 0xfe.....24
nonce: nonce,
gas: 1000000, // fee estimate to complete the transaction
data: await this.myContract.methods
.safeTransferFrom(fromAddress, toAnyAddress, tokenId)
.encodeABI()
}
// do signing stuff & send it
so in this case i m getting err - Fail with error 'ERC721: transfer caller is not owner nor approved'.
I need solution for my case 2. Is there something related with locked/unlocked accounts? How can i fix it?
Please help! Thanks in advance.
Q.1 Is signing is reqd? Can't we access the contract method directly as i did above ?
The .send() method of the web3 Contract instance performs/requests the signature in the background. So it's always signed - just not with an explicit "sign" keyword in the code in this case.
Q.2 There are two cases:
This is not related to the way you sign the transaction.
The second case fails because the token holder has not approved the spender (i.e. the transaction sender) to spend their tokens.
You need to invoke the approve(<spender>, <tokenId>) function from the token holder address first, to be able to successfully use the transferFrom().
// assuming `acc1` is holder of the token ID `1003`
// approve the `owner` to spend the `acc1`'s token
await myContract.methods.approve(owner, 1003).send({from: acc1});
// transfer token `1003` held by `acc1` ... and send the transaction from the `owner` address
await myContract.methods.transferFrom(acc1, recipient, 1003).send({from: owner});

Error creating contract after getting contract ABI from Etherscan API

I am trying to get the contract ABI using the Etherscan API, and then create a contract instance and call a method. I am able to get the ABI from Etherscan but when creating the contract object I am getting this error: "You must provide the json interface of the contract when instantiating a contract object."
This is what my code looks like
let url = 'https://api.etherscan.io/api?module=contract&action=getabi&address=0x672C1f1C978b8FD1E9AE18e25D0E55176824989c&apikey=<api-key>';
request(url, (err, res, body) => {
if (err) {
console.log(err);
}
let data = JSON.parse(body);
let contract_abi = data.result;
console.log(contract_abi)
let contract_address = '0x672C1f1C978b8FD1E9AE18e25D0E55176824989';
const contract = new web3.eth.Contract(contract_abi);
const contract_instance = contract.at(contract_address);
// Call contract method
})
When I console.log the contract_abi I see the ABI data. I've also tried creating the contract by doing
const contract = new web3.eth.Contract(contract_abi, contract_address)
Thanks!
data.result contains the JSON ABI as a string. You need to decode it as well to an object.
let contract_abi = JSON.parse(data.result);
Also, it's possible that you're using a deprecated version of Web3 that supports the contract.at() syntax.
But if you're using the current version, you'd get the contract.at is not a function error. In that case, you need to pass the address as the second argument of the Contract constructor.
const contract = new web3.eth.Contract(contract_abi, contract_address);

web3.eth.getAccounts() returns empty array when using Infura provider. Why?

I was trying to use Infura api to make an Ethereum web app. First I compiled a solidity contract and then deployed it using infura api on rinkeby network. Here is my deploy script which seems to be running successfully.
const HDWalletProvider = require("truffle-hdwallet-provider");
const Web3 = require('Web3');
const compileFactory = require('./build/CampaignFactory.json');
const provider = new HDWalletProvider(
"MY_SECRET_MNEMONIC",
"https://rinkeby.infura.io/v3/363ea9633bcb40bc8a857d908ee27094"
);
const web3 = new Web3(provider);
console.log("provider info: " + provider);
const deploy = async () => {
const accounts = await web3.eth.getAccounts();
console.log("account used: " + accounts[0]);
result = await new web3.eth.Contract(JSON.parse(compileFactory.interface))
.deploy({data: "0x"+compileFactory.bytecode})
.send({from: accounts[0]});
console.log("deployed to address: " + result.options.address);
};
deploy();
Then I created another script web3.js which creates a web3 provider using Infura api:
import Web3 from 'web3';
let web3;
if (typeof window !== 'undefined' && typeof window.web3!=='undefined') {
// we are in the browser and metamask is running.
web3 = new Web3(window.web3.currentProvider);
console.log("using metamask");
}
else {
// we are in server OR user without metamask.
const provider = new Web3.providers.HttpProvider(
"https://rinkeby.infura.io/v3/363ea9633bcb40bc8a857d908ee27094"
);
web3 = new Web3(provider);
console.log("using infura");
}
export default web3;
but when I import this web3.js file somewhere and then try to use 'web3' object, it returns empty array of accounts. For example:
import web3 from '../../ethereum/web3';
...
const accounts = await web3.eth.getAccounts();
console.log("Account list: "+accounts); // returns empty array.
But ideally it should return the accounts list associated with my mnemonic. What is the problem?
A naive solution is to use the HDWalletProvider in your second script, instead of the HttpProvider.
What exactly do you want to do with the second script? I suspect that the second script is something that you want to deploy with a DApp, so including your mnemonic there is a good way to give away all your ether to the first user who knows how to "view source".
If so, in the first script, display the addresses associated with your mnemonic using: provider.getAddresses() and then hard-code those addresses into the second script, for later usage. Naturally, you won't be able to sign any transactions in the second script, but at least you can read data associated with those addresses.
Put await window.ethereum.enable() before web3.eth.getAccounts(),
Or use requestAccounts() instead of getAccounts() :
await web3.eth.requestAccounts();

Ethereum Web3.js Invalid JSON RPC response: ""

I am using web3.js module for ethereum. While executing a transaction I am getting error response.
Error:
"Error: Invalid JSON RPC response: ""
at Object.InvalidResponse (/home/akshay/WS/ethereum/node_modules/web3-core-helpers/src/errors.js:42:16)
at XMLHttpRequest.request.onreadystatechange (/home/akshay/WS/ethereum/node_modules/web3-providers-http/src/index.js:73:32)
at XMLHttpRequestEventTarget.dispatchEvent (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)"
I am using ropsten test network url for testing my smart contract:
https://ropsten.infura.io/API_KEY_HERE
When I call the balanceOf function, it works fine but when I try to call function transfer it send me this error. The code is mentioned below:
router.post('/transfer', (req, res, next)=>{
contractInstance.methods.transfer(req.body.address, req.body.amount).send({from:ownerAccountAddress})
.on('transactionHash',(hash)=>{
console.log(hash)
}).on('confirmation',(confirmationNumber, receipt)=>{
console.log(confirmationNumber)
console.log(receipt)
}).on('receipt', (receipt)=>{
console.log(receipt)
}).on('error',(err)=>{
console.log(err)
})
})
Please let me know where I am wrong.
EDIT: I am using web3js version "web3": "^1.0.0-beta.34"
To add to what maptuhec said, while calling a "state-changing" function in Web3 or a state-changing transaction, it MUST be SIGNED!
Below is an example of when you're trying to call a public function (or even a public contract variable), which is only reading (or "view"ing) and returning a value from your smart contract and NOT changing its state, in this we don't need to necessarily specify a transaction body and then sign it as a transaction, because it doesn't change the state of our contract.
contractInstance.methods.aPublicFunctionOrVariableName().call().then( (result) => {console.log(result);})
**
State-Changing Transactions
**
Now, consider the example below, here we're trying to invoke a "state-changing" function and hence we'll be specifying a proper transaction structure for it.
web3.eth.getTransactionCount(functioncalleraddress).then( (nonce) => {
let encodedABI = contractInstance.methods.statechangingfunction().encodeABI();
contractInstance.methods.statechangingfunction().estimateGas({ from: calleraddress }, (error, gasEstimate) => {
let tx = {
to: contractAddress,
gas: gasEstimate,
data: encodedABI,
nonce: nonce
};
web3.eth.accounts.signTransaction(tx, privateKey, (err, resp) => {
if (resp == null) {console.log("Error!");
} else {
let tran = web3.eth.sendSignedTransaction(resp.rawTransaction);
tran.on('transactionHash', (txhash) => {console.log("Tx Hash: "+ txhash);});
For more on signTransaction, sendSignedTransaction, getTransactionCount and estimateGas
when using Web3.js you should sign the transactions. When you call functions which are non-constant, like transfer, you should sign the transaction and after that send the signed transaction (there is a method called sendSignedTransaction). This is very hard using web3js, I recommend using ehtersjs, with it everything is a lot easier.
in my case, it's the network problem.
I set the HTTP_PROXY and HTTPS_PROXY in my terminal and can successfully curl google.com, however I got this error.
solution:
I ssh to another server (located in HK where network is good to connect everywhere in the world ) and everything is fine.

Openzepplin crowdsale contract got: VM Exception while processing transaction: revert error

I am developing smart contract based on openzeppelin-solidity and I want to write an easy Crowdsale contract, only I did is inherit Contract.sol:
// FloatFlowerTokenCrowdsale.sol
pragma solidity 0.4.23;
import "openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol";
contract FloatFlowerTokenCrowdsale is Crowdsale{
constructor(ERC20 _token) public Crowdsale(1000, msg.sender, _token)
{
}
}
Here is my FloatFlowerToken.sol
// FloatFlowerToken.sol
pragma solidity 0.4.23;
import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
contract FloatFlowerToken is StandardToken {
string public name = "FLOATFLOWER TOKEN";
string public symbol = "FFT";
uint8 public decimals = 18;
constructor() public {
totalSupply_ = 36000000;
balances[msg.sender] = totalSupply_;
}
}
And this is my 2_deploy_contract.js
const FloatFlowerToken = artifacts.require('./FloatFlowerToken.sol');
const FloatFlowerTokenCrowdsale =
artifacts.require('./FloatFlowerTokenCrowdsale.sol');
module.exports = function(deployer, network, accounts) {
return deployer
.then(() => {
return deployer.deploy(FloatFlowerToken);
})
.then(() => {
return deployer.deploy(FloatFlowerTokenCrowdsale, FloatFlowerToken.address);
})
};
After I execute the truffle test and I got the error Error: VM Exception while processing transaction: revert
And here is my test code:
it('one ETH should buy 1000 FLOATFLOWER TOKEN in Crowdsale', function(done) {
FloatFlowerTokenCrowdsale.deployed().then(async function(instance) {
const data = await instance.sendTransaction({from: accounts[7], value: web3.toWei(1, "ether")}, function(error, txhash) {
console.log(error);
});
const tokenAddress = await instance.token.call();
const FloatFlowerToken = FloatFlowerToken.at(tokenAddress);
const tokenAmount = await FloatFlowerToken.balanceOf(accounts[7]);
assert.equal(tokenAmount.toNumber(), 1000000000000000000000, 'The sender didn\'t receive the tokens as crowdsale rate.');
})
})
I don't know how to check the error log and to know which line cause this problem.
You have 2 issues:
First, the units you're working with aren't correct. You've initialized your crowdsale to sell 1000 tokens for every Wei sent. From the documentation in the Zeppelin contract:
#param _rate Number of token units a buyer gets per wei
#param _wallet Address where collected funds will be forwarded to
#param _token Address of the token being sold
You're passing in 1 ether in your transaction, which means you're attempting to buy 1000 * (10^18) token units, but you've only allocated 36000000 total supply. You need to increase your total supply and/or lower your rate.
Second, only token owners can do a transfer unless an approve has been done first. When you deploy the token contract, all of the tokens are owned by msg.sender. However, when someone makes a purchase through your crowdsale contract, the request to do the transfer is coming from the address of the crowdsale contract, not the token owner when your token contract was deployed. The simplest way around this is after deploying your contracts, transfer enough tokens for the crowdsale from the address you used to create the token contract over to the address of the crowdsale contract.