casualprogrammer
casualprogrammer

Reputation: 363

How to call a contract function from a specific address

I want to use web3 to call a contract function(sendTransaction not call) from a specific address that I hold the private key to. I also have the contract instance connected. I know I have to dio something like web3.personal.unlockAccount(address,password,duration) And then specify the from address. So my question is, is "password" where I enter my private key? And how do I pass that address into fromAddress once I unlock it. Or is there a more streamlined way to go about it?

Upvotes: 1

Views: 1713

Answers (1)

Roman Frolov
Roman Frolov

Reputation: 1008

is "password" where I enter my private key?

No, it's not. Actually it is a password, which you entered when you were creating account and which was used to generate your keystore file.


If you use web3.personal.unlockAccount(address,password,duration) you need to have your keystore file in the keystore folder near chaindata of geth.


Another way will be to use web3.eth.sendRawTransaction from web3.py, but it will be a little bit clunky to call contract method from it.

key = '0x' + 'YOUR-PRIVATE-KEY
transaction = {
    'to': _to,
    'value': 0,
    'gas': 300000,
    'gasPrice': 23000000000,
    'nonce': web3.eth.getTransactionCount(_from),
    'chainId': int(web3.admin.nodeInfo['protocols']['eth']['network']),
    'data': b''
}

signed = web3.eth.account.signTransaction(transaction, key)
print("Transaction Hash: " + web3.toHex(web3.eth.sendRawTransaction(signed.rawTransaction)))

My suggestion will be to create keyfile recognisable by Ethereum clients by using web3.eth.account.encrypt (web3.py because web3.js yet lack this functionality) and after you generate it put it in the right folder and try simply to unlock account.

Upvotes: 2

Related Questions