I am making a call to the Dai contract on the Kovan testnet to facilitate transactions between any two addresses entered as input. I was able to successfully make read calls but I realized I needed to sign transcations using a key for every write call. How do I do this using web3? I have my code below for clarity :

const Web3 = require("web3");
const axios = require('axios');
const WebSocket = require('ws');
const Web3Utils = require('web3-utils');

   if (typeof web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider);
    } else {
        // set the provider you want from Web3.providers
        web3 = new Web3(new Web3.providers.WebsocketProvider("wss://kovan.infura.io/ws/v3/d28ff5674c0848ada11af62d25c6a2f1"));
    web3.eth.defaultChain = 'kovan';
    var DaiContract = new web3.eth.Contract('ABI-HERE','0xC4375B7De8af5a38a93548eb8453a498222C4fF2');
$("#button").click(function() {
        DaiContract.methods.transferFrom($("#address1").val(), $("#address2").val(), $("#amount").val()).call()
            $("#result").html("Successfully transferred " + $("amount").val() + " Dai.");
                console.log('Remaining balance in address1 : ' + value);
                console.error('Error : ' + error);
            console.error('Error : ' + error);
            $("#result").html("Transfer failed");

Gives the following error :

enter image description here

1 Answer 1


With web3 v1.2.x, you can use this:

async function send(web3, privateKey, gasPrice, transaction, value = 0) {
    const address = web3.eth.accounts.privateKeyToAccount(privateKey).address;
    const options = {
        to      : transaction._parent._address,
        data    : transaction.encodeABI(),
        gas     : await transaction.estimateGas({from: address, value: value}),
        gasPrice: gasPrice,
        value   : value
    const signed  = await web3.eth.accounts.signTransaction(options, privateKey);
    const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
    return receipt;

Then, for example, you can call it from an async function as follows:

const transaction = DaiContract.methods.transferFrom($("#address1").val(), $("#address2").val(), $("#amount").val());
const receipt = await send(web3, YourPrivateKey, YourGasPrice, transaction);

Your Answer

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

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