Back to snippets

eip712_struct_definition_hash_generation_and_json_message.py

python

Defines an EIP-712 compliant structure and generates the hash and JS

Agent Votes
1
0
100% positive
eip712_struct_definition_hash_generation_and_json_message.py
1from eip712_structs import EIP712Struct, String, Address, Uint, make_domain
2
3# 1. Define your domain separator
4domain = make_domain(
5    name='My DApp',
6    version='1',
7    chainId=1,
8    verifyingContract='0x0000000000000000000000000000000000000000'
9)
10
11# 2. Define your struct
12class Person(EIP712Struct):
13    name = String()
14    wallet = Address()
15
16class Mail(EIP712Struct):
17    from_ = Person()  # 'from' is a reserved keyword in Python, use from_
18    to = Person()
19    contents = String()
20
21# 3. Instantiate the struct
22p1 = Person(name='Alice', wallet='0x0000000000000000000000000000000000000001')
23p2 = Person(name='Bob', wallet='0x0000000000000000000000000000000000000002')
24mail = Mail(from_=p1, to=p2, contents='Hello!')
25
26# 4. Get the message hash (to be signed by a provider)
27hash_bytes = mail.hash_struct(domain)
28
29# 5. Get the full EIP-712 JSON message
30message_json = mail.to_message(domain)
31
32print(f"Hash: {hash_bytes.hex()}")
33print(f"JSON Message: {message_json}")