1

Using web3 version 1 beta 27, connected to a remote Parity node that's connected to the Ropsten network.

I have created an account with public and private keys, I have sent some test Eth to that address. That all works fine.

Now trying to actually invoke a function on my contract I get the message

Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer

I don't have access to the node via CLI so need to use Trusted Signer.

Looking at the docs for web3.eth.accounts.sign I see the following

sign

web3.eth.accounts.sign(data, privateKey);

Signs arbitrary data. This data is before UTF-8 HEX decoded and enveloped as follows: "\x19Ethereum Signed Message:\n" + message.length + message.

Parameters

  1. data - String: The data to sign. If its a string it will be
  2. privateKey - String: The private key to sign with.

which quite frankly doesn't make any sense.

Assuming the function I am calling is

TestContract.methods.test(testAddress).send()

How exactly do I use web3.eth.accounts.sign in this context?

2

I've worked this out now. First up I need to ensure I have access to the private key for the address, as well as the sender's address.

Given that information I can do the following.

const testFn = TestContract.methods.test(testAddress)
const gas = await testFn.estimateGas()
const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY)
const data = testFn.encodeABI()
const nonce = await web3.eth.getTransactionCount(SENDER_ADDRESS, 'pending')
const payload = {
  nonce,
  data,
  gas,
  from: SENDER_ADDRESS,
  to: testContractAddress
}
const signedTx = await account.signTransaction(payload, account.privateKey)
const { rawTransaction } = signedTx
const response = await web3.eth.sendSignedTransaction(rawTransaction)

This works fine.

Obviously this is only suitable for code running in NodeJS as you never want the private key to be exposed in a public web interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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