I want to execute a smart contract on the blockchain. As far as I understood this web3js offers two options
- call: executes the contract method locally without using gas
- execute: executes the contract method on the blockchain and requires gas
What I don't get how to use a specific wallet e.g.
const ABI = require('./contracts/abi.json');
const addressContract = "xyz";
const Web3 = require('web3');
const Tx = require('ethereumjs-tx');
const wallet = {
public: somePublicKey,
private: somePrivateKey
}
const web3 = new Web3(new Web3.providers.HttpProvider(config.provider));
const contract = new self.web3.eth.Contract(ABI, addressContract);
const options= {
from: wallet.public,
gasPrice: process.env.GAS
gasLimit: 250000
}
contract.methods.methodA(param1,param2,param3).send(options, (err, txHash)=> {
console.log("err",err)
console.log("txHash",txHash)
})
I found that to execute a contract there is a plugin called ethereumjs-tx which would modify my code to the following:
//options.data = ?
options.to = addressContract
options.nonce = someNonce
const tx = new Tx(options);
tx.sign(new Buffer(wallet.private, 'hex'));
const rawTx = `0x${tx.serialize().toString('hex')}`;
self.web3.eth.sendRawTransaction(rawTx, (err, result) => {
console.log("err",err)
console.log("txHash",txHash)
});
I'm struggling basically with the data property. Because contract.methods.methodA.getData does not exists.
Question
1) How to get my params into the data format? / Or do I just add them to options instead of options.data
EDIT: I guess I could feed all the params into: https://github.com/ethereumjs/ethereumjs-abi
var parameterTypes = ["address", "uint256", "address", "uint256", "uint256", "uint256", "address", "uint8", "bytes32", "bytes32", "uint256"];
var parameterValues = ["0x1234567812345678", 256, "0x1234567812345678", 256, 256, 256, "0x1234567812345678", 8, 32, 32, 256];
var encoded = abi.rawEncode(parameterTypes, parameterValues);
And attach the result to data with '0x'+encoded.
Invalid JSON RPC response: “”. I would prefer to work with the simpler solution. To unlock the wallet I need to rungethand download the blockchain, right? Currently, I usehttps://mainnet.infura.io/xyzasHttpProvider. Or can I unlock the wallet inweb3js? – Andi Giga Nov 29 '17 at 08:22web3.eth.getBlocknumber(console.log)or checking the balance of some accountweb3.eth.getBalance). If it’s an unlocking account issue, the error message will typically say your account is not unlocked/authorized. Are you trying directly on mainnet (from your infura url)? And to your question, yes. If you are not running a local node, then you would have to sign offline and use ethereumtx-js / send data as you had started to do. – carlolm Nov 29 '17 at 09:27options.data = contract.methods.methodA.encodeABI()– Andi Giga Nov 29 '17 at 14:15