This question already has an answer here:

An api will call the smart contract function. It should sign the transaction on its own instead of human intervention.

I think raw transaction can work here. Are there any other options?

Any help is much appreciated. Thanks!

--Edit-- The question is updated!

marked as duplicate by Ismael, shane, Richard Horrocks, eth Sep 23 at 3:01

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I have updated the question. thanks – Shubham Chadokar Sep 14 at 10:26
  • Do you mean contract should sign its own transaction? – asvisosila Sep 14 at 11:04
  • 1
    Yes! it should complete the transaction on its own. – Shubham Chadokar Sep 14 at 11:12
  • So why did you tag the question under web3.js? – goodvibration Sep 14 at 11:12
  • It should sign the transaction on its own - the API or the contract? (I don't see how the contract could possibly do that, but you just wrote it in a comment above). – goodvibration Sep 14 at 11:13

Try this (using web3.js v1):

let Web3 = require("web3");
let web3 = new Web3(NODE_ADDRESS);

async function send(transaction, reestimate = function(gas) {return gas;}) {
    let gas = await transaction.estimateGas({from: PUBLIC_KEY});
    let options = {
        to  : transaction._parent._address,
        data: transaction.encodeABI(),
        gas : reestimate(gas)
    };
    let signedTransaction = await web3.eth.accounts.signTransaction(options, PRIVATE_KEY);
    return await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);
}

Usage example #1:

let receipt = await send(myContract.methods.myFunc(arg1, arg2, arg3));
...

Usage example #2:

let reestimate = function(gas) {return gas * 2;};
let receipt = await send(myContract.methods.myFunc(arg1, arg2, arg3), reestimate);
...

A contract can not sign transaction by its own. The transaction must be signed by externally owned accounts. If a transaction is not signed by an externally owned account then it won't be included in the blockchain.

  • This is why I'm pretty sure that this user doesn't really mean to ask how the contract can sign its own transaction, but how the (external) API should sign the transaction (even though he/she stated the opposite in response to your comment). An evidence to that is the fact that the question is tagged under web3.js. In addition, there's no sense in asking how to sign a transaction from the on-chain, because signing a transaction is performed from the off-chain by definition. – goodvibration Sep 14 at 11:40
  • @goodvibration I agree with you. Even I was confused after reading the question and asked for more clarification. – asvisosila Sep 14 at 12:51

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