I have account private key, contract address and abi and I need to call contract function with this account. Is it possible?
-
2This is not actually a duplicate, and the other question has a very good accepted answer that does not answer this one.– qwertyboyJan 18, 2018 at 12:59
-
2+1, this is not a duplicate, the other question asnwers say absolutely nothing about using the private key. I'd like to post a solution that does not require creating a raw transaction here, but I can't since question is closed ;c– KlesunMay 1, 2020 at 9:32
-
This should be reopened, it's not a duplicate of linked question. It needs moderator intervention. Flagged.– Daniel KmakJun 23, 2021 at 10:46
1 Answer
Along with web3 you have to use ethereumjs-tx to sign the transaction and you can send web3.eth.sendRawTransaction to the network. Below code for your reference.
const Web3 = require("web3");
const solc = require("solc");
const Tx = require('ethereumjs-tx')
const web3 = new Web3(new
Web3.providers.HttpProvider("https://ropsten.infura.io"));
var account = "Your Account #";
var key = new Buffer('Your Account # Private key', 'hex')
var abi = ABI of the Contract
var bytecode = Bytecode of compiled contract
var Contract = web3.eth.contract(abi)
const gasPrice = web3.eth.gasPrice;
const gasPriceHex = web3.toHex(gasPrice);
const gasLimitHex = web3.toHex(3000000);
var tra = {
gasPrice: gasPriceHex,
gasLimit: gasLimitHex,
data: bytecode,
from: account
};
var tx = new Tx(tra);
tx.sign(key);
var stx = tx.serialize();
web3.eth.sendRawTransaction('0x' + stx.toString('hex'), (err, hash) => {
if (err) { console.log(err); return; }
console.log('contract creation tx: ' + hash);
});