9

I have account private key, contract address and abi and I need to call contract function with this account. Is it possible?

3
  • 2
    This is not actually a duplicate, and the other question has a very good accepted answer that does not answer this one.
    – qwertyboy
    Jan 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
    – Klesun
    May 1, 2020 at 9:32
  • This should be reopened, it's not a duplicate of linked question. It needs moderator intervention. Flagged. Jun 23, 2021 at 10:46

1 Answer 1

12

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);
});
1
  • How can I use Buffer in my simple web page? Apr 21, 2018 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.