|
from eth_abi import decode_abi, encode_abi |
|
# pip install eth_abi == 3.0.0 |
|
|
|
def encode(tax_id: str, loan_amount: float, json_payload): |
|
json_bytes = json.dumps(json_payload, separators=(',', ':')).encode("utf-8") |
|
hex_str = encode_abi(["string", "uint256", "bytes"], [tax_id, loan_amount, json_bytes]).hex() |
|
return f"0x{hex_str}" |
|
|
|
def decode(hex: str): |
|
binary = bytes.fromhex(hex[2:]) |
|
(tax_id, loan_amount, json_bytes) = decode_abi(["string", "uint256", "bytes"], binary) |
|
json_payload = json.loads(json_bytes.decode("utf-8")) |
|
return (tax_id, loan_amount, json_payload) |
|
|
|
# params |
|
tax_id = "26825555000166" |
|
loan_amount = 10000 |
|
api_response = { |
|
"tax_id": "26825555000166", |
|
"tax_id_type": "cnpj", |
|
"tax_id_active": True, |
|
"company": { |
|
"start_date": "2017-09-01", |
|
"social_capital": 10000 |
|
}, |
|
"data": [ |
|
{ |
|
"source": "serasa", |
|
"score": 800, |
|
"total_debt": 1000 |
|
}, |
|
{ |
|
"source": "scr", |
|
"score": 500, |
|
"total_debt": 2000 |
|
} |
|
] |
|
} |
|
|
|
# encode and decode |
|
encoded = encode(tax_id, loan_amount, api_response) |
|
print("encoded:", encoded) |
|
# encoded: 0x0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000271000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000e323638323535353530303031363600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ee7b227461785f6964223a223236383235353535303030313636222c227461785f69645f74797065223a22636e706a222c227461785f69645f616374697665223a747275652c22636f6d70616e79223a7b2273746172745f64617465223a22323031372d30392d3031222c22736f6369616c5f6361706974616c223a31303030302e307d2c2264617461223a5b7b22736f75726365223a22736572617361222c2273636f7265223a3830302c22746f74616c5f64656274223a313030307d2c7b22736f75726365223a22736372222c2273636f7265223a3530302c22746f74616c5f64656274223a323030307d5d7d000000000000000000000000000000000000 |
|
|
|
decoded = decode(encoded) |
|
print("decoded: ", decoded) |
|
# decoded: ('26825555000166', 10000, {'tax_id': '26825555000166', 'tax_id_type': 'cnpj', 'tax_id_active': True, 'company': {'start_date': '2017-09-01', 'social_capital': 10000.0}, 'data': [{'source': 'serasa', 'score': 800, 'total_debt': 1000}, {'source': 'scr', 'score': 500, 'total_debt': 2000}]}) |