Search code examples
transactionsethereumsmartcontractsweb3jshardhat

How to correctly sign the transfer of tokens through the smatcontract?


I have smartcontract with method transfer:

function transfer(address to, uint256 amount) external {
    require(balances[msg.sender] >= amount, "Not enough tokens");
    balances[msg.sender] -= amount;
    balances[to] += amount;
}

After deploy via HardHat with account alchemy: "https://eth-ropsten.alchemyapi.io/v2/iwxxx"

I got: Deploying contracts with the account: 0x5Cххх Account balance: 299502973995526766 Token address: 0xC1ххх

And run this code:

const acc_addr = "0x5Cxxx";
const address = "0xC1xxx"           
const receiverAddress  = "0x39xxx"  


var Web3 = require('web3')
var provider = "https://eth-ropsten.alchemyapi.io/v2/iwxxx";
var web3 = new Web3(new Web3.providers.HttpProvider(provider));

const token = new web3.eth.Contract(abi, address);
token.setProvider(web3.currentProvider)

token.methods.balanceOf(acc_addr).call((err, res) => {  
    log("balanse => ", res); 
});


token.methods.transfer(receiverAddress, "1").send({ "from": acc_addr }, (err, res) => {
    if (err) {
      console.log(err);
      return
    }
    console.log("Hash transaction: " + res);
});

So I got error:

Error: Returned error: Unsupported method: eth_sendTransaction. Alchemy does not hold users' private keys. See available methods at https://docs.alchemy.com/alchemy/documentation/apis

at Object.ErrorResponse (D:\node_modules\web3-core-helpers\lib\errors.js:28:19)

I understand that I somehow have to sign this transaction. But the question is, I don’t understand how?

Normal transactions of transferring ETH from an address to an address are very simple and obvious.


Solution

  • You need to pass the private key of the transaction sender (acc_addr in your case) to your local web3 instance using the wallet.add() method.

    web3.eth.accounts.wallet.add('0x<private_key>');
    

    Note: Web3 does not share the private key with the node provider - uses it only to sign the transaction locally.