209 похожих чатов

А кто-то разбирался как работает web3py? Не могу найти, как именно

они там типы преобразуют. Например есть JSON RPC запрос eth_getLogs
Там в ответе массив объектов, у которого int поля в виде hex строк, например 'logIndex': '0x49'

И w3.eth.get_logs() дает ответ в виде class LogEntry(TypedDict) с полем logIndex: int
И я не могу найти где произошла магия преобразования из hex строки logIndex="0x49", в нормальный int. И такое не только по eth_getLogs запросу, а по очень многим json rpc запросам.

Вообще у меня задача такая: я хотел бы использовать типы из библиотеке web3py, которые лежат в модуле types. Но с json rpc серверами я работаю сам, и я хотел бы этот json ответ автоматически конвертировать в types.* классы библиотеки, как types.LogEntry и т.п. А не для каждого писать преобразователь типов.

Может быть кто-то вникал как работает web3py и может подсказать, где именно происходит трансформация json ответа в правильные TypedDict классы? Где-то есть один универсальный метод, который берет json ответ и на выходе по определению TypeDict класса делает все необходимые трансформации как, наприvер hex str -> int для всех нужных полей.

3 ответов

26 просмотров

может в этом дело

Lex- Автор вопроса
Pro Logic 🍓
screenshot может в этом дело

И как можно автоматом на питоне преобразовать строки где числа в виде строк в hex в формате в инты? Вот пример лога, json ответ: data = {'address': '0xdac17f958d2ee523a2206206994597c13d831ec7', 'blockHash': '0x9dc915cbbd9a6e66f843870934af26d2fc8a2600a6f9c442ee4518453df25977', 'blockNumber': '0x1137e53', 'data': '0x0000000000000000000000000000000000000000000000000000000039a6c230', 'logIndex': '0xe', 'removed': False, 'topics': ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', '0x000000000000000000000000d1b40cbaffa93347a5164d6ffdc3af2885fe097a', '0x00000000000000000000000071626b6e2e2c5e281ce4c7912e0d3131cba17398'], 'transactionHash': '0x1ebd3748ed458d40b1d50ca62f2f83e2b89b0f7aa0486b6572bfdde35faff042', 'transactionIndex': '0x4'} class Log(TypedDict): blockHash: str blockNumber: int logIndex: int -- вот частично описаный класс. И если сделать просто log=Log(**data), то не получится log["logIndex"] в виде int, а будет по прежнему строка.

в web3py есть отдельные методы конвертации https://web3py.readthedocs.io/en/stable/web3.main.html#encoding-and-decoding-helpers А какой тип выбрать. решается на основе abi контракта

Похожие вопросы

Обсуждают сегодня

@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Hello, Is iExec also part of the "inception program" or another one ? Would it be a name to qualified the nature of the relationship between iExec and Nvidia? And does Secret ...
Ñïķøłäś
8
Ready for some fun AND a chance to win TKO Tokens? Join us for exciting minigames in our Telegram group! 🕒 Don’t miss out—games start on today 25 October 2024, at 8 PM! Ge...
Milkyway | Tokocrypto
255
any reference of this implementation?
BitBuddha
29
Also, why can’t the community have a vote/ say when it comes to initiatives like buybacks. Isn’t the point of crypto decentralisation? Don’t we deserve input as long term supp...
👨🏽‍🦰
13
Hi guys, any problem with Pulsebrige? Trying to transfer from wETH to ETH. First it tells me to connect my metamask "through mobile app" not desktop. Then I did and confirmed ...
Snowflakecrypto
13
Карта сайта