Calling contract function with private key

Hello Admin,

const transferToken = await token.methods
.transfer('0xd9c2dc0d5dff2261b6ff1b9e471ffd1a11add911', 1000)
.send({ from: accounts[0] });

From the above code the from is using the first account from infura which works fine with no issues.

My question is, how do i call a contract function using another ethereum address that’s not part of the accounts Array.

I have an address which includes privateKey and publicKey of the address, i want to use this address to call the contract function. Reason being, if i need to call allowance function of a contract, the call has to come from the owner address.

So please, any help would be highly appreciated

1 Like

Hi @1baga,

You can ask your question to the community rather than just admins. :smile:

You can use private keys with Truffle HDWallet Provider, see the Truffle documentation for details:

https://github.com/trufflesuite/truffle/tree/develop/packages/hdwallet-provider#private-keys

:warning: Don’t commit private keys

The following is an example with the private key kept in secrets.json.

// src/index.js
const Web3 = require('web3');
const { setupLoader } = require('@openzeppelin/contract-loader');

const { projectId, mnemonic, privateKey } = require('../secrets.json');
const HDWalletProvider = require('@truffle/hdwallet-provider');

const provider = new HDWalletProvider(privateKey, `https://ropsten.infura.io/v3/${projectId}`);

async function main() {
  // Set up web3 object
  const web3 = new Web3(provider);

  const loader = setupLoader({ provider: web3 }).web3;

  // Set up a web3 contract, representing a deployed ERC20, using the contract loader
  const address = '0xad6d458402f60fd3bd25163575031acdce07538d';
  const token = loader.fromArtifact('ERC20', address);

  // Retrieve accounts
  const accounts = await web3.eth.getAccounts();

  console.log(`Account: ${accounts[0]}`);

  // Call the deployed token contract
  const name = await token.methods.name().call();
  const symbol = await token.methods.symbol().call();
  const decimals = await token.methods.decimals().call();
  const totalSupply = await token.methods.totalSupply().call();
  console.log(`${name} (${symbol}) - Decimals:${decimals} Total Supply:${totalSupply}`);

  console.log('Please wait whilst approve transaction sent')
  const tx = await token.methods.approve("0xFFcf8FDEE72ac11b5c542428B35EEF5769C409f0", "10000000000000000000")
   .send({ from: accounts[0], gas: 50000, gasPrice: 10e9 });

  console.log(tx);

  const allowance = await token.methods.allowance(accounts[0], "0xFFcf8FDEE72ac11b5c542428B35EEF5769C409f0").call();
  console.log(`Allowance set by ${accounts[0]} of ${allowance} tokens for 0xFFcf8FDEE72ac11b5c542428B35EEF5769C409f0`)

  // At termination, `provider.engine.stop()' should be called to finish the process elegantly.
  provider.engine.stop();
}

main();

you are a live saver.

1 Like