Ethers.js – How to Call ethers.utils.defaultAbiCoder.encode(types, values) in Python

ethers.jspythonsignature

I want to create a signature based on a hash value and a wallet address.
In nodejs I would do it like follows:

        const types = ["address", "bytes32"];

        const values = [address, hash];
        const message = ethers.utils.defaultAbiCoder.encode(types, values);
        const hash = ethers.utils.keccak256(message);

        const sig = await wallet.signMessage(ethers.utils.arrayify(hash));

But how do I do this in python?
I tried using the eth_abi module but it does not return the same message, hash or signature.

        types = ["address", "bytes32"]
        values = [address, codecs.decode(hash, 'hex')]
        encoded_message = encode_packed(types, values)
        hash_message = Web3.keccak(encoded_message)

        signed_message = account.signHash(hash_message)
        signature = signed_message['signature'].hex()

How can I mimic the process in nodejs in python?

Best Answer

from web3 import Web3
from eth_account import Account
from eth_abi import encode_abi_packed
import codecs

types = ["address", "bytes32"]
values = [address, codecs.decode(hash, 'hex')]
encoded_message = encode_abi_packed(types, values)
hash_message = Web3.keccak(encoded_message)

signed_message = Account.signHash(hash_message, private_key=private_key)
signature = signed_message['signature'].hex()
Related Topic