nim-ethers/ethers/providers/conversions.nim

77 lines
1.9 KiB
Nim
Raw Normal View History

2022-01-18 11:42:58 +00:00
import std/json
import pkg/json_rpc/jsonmarshal
2022-01-20 11:56:18 +00:00
import pkg/stew/byteutils
import ../basics
import ../transaction
import ../blocktag
import ../provider
export jsonmarshal
func fromJson*(T: type, json: JsonNode, name = ""): T =
fromJson(json, name, result)
2022-01-20 11:56:18 +00:00
# byte sequence
func `%`*(bytes: seq[byte]): JsonNode =
%("0x" & bytes.toHex)
func fromJson*(json: JsonNode, name: string, result: var seq[byte]) =
result = hexToSeqByte(json.getStr())
2022-01-18 11:42:58 +00:00
2022-01-25 14:07:16 +00:00
# byte arrays
func `%`*[N](bytes: array[N, byte]): JsonNode =
%("0x" & bytes.toHex)
func fromJson*[N](json: JsonNode, name: string, result: var array[N, byte]) =
hexToByteArray(json.getStr(), result)
2022-01-18 13:26:41 +00:00
# Address
2022-01-18 11:42:58 +00:00
func `%`*(address: Address): JsonNode =
%($address)
2022-01-18 13:26:41 +00:00
func fromJson*(json: JsonNode, name: string, result: var Address) =
2022-01-18 11:42:58 +00:00
if address =? Address.init(json.getStr()):
result = address
else:
2022-01-18 13:26:41 +00:00
raise newException(ValueError, "\"" & name & "\"is not an Address")
# UInt256
func `%`*(integer: UInt256): JsonNode =
2022-01-25 09:25:09 +00:00
%("0x" & toHex(integer))
2022-01-18 13:26:41 +00:00
func fromJson*(json: JsonNode, name: string, result: var UInt256) =
result = UInt256.fromHex(json.getStr())
2022-01-20 11:56:18 +00:00
# Transaction
2022-01-25 09:25:09 +00:00
func `%`*(transaction: Transaction): JsonNode =
result = %{ "to": %transaction.to, "data": %transaction.data }
if sender =? transaction.sender:
2022-01-24 13:40:47 +00:00
result["from"] = %sender
2022-01-25 09:25:09 +00:00
if nonce =? transaction.nonce:
result["nonce"] = %nonce
if chainId =? transaction.chainId:
result["chainId"] = %chainId
if gasPrice =? transaction.gasPrice:
result["gasPrice"] = %gasPrice
if gasLimit =? transaction.gasLimit:
result["gas"] = %gasLimit
2022-01-24 11:14:31 +00:00
# BlockTag
func `%`*(blockTag: BlockTag): JsonNode =
%($blockTag)
# Log
func fromJson*(json: JsonNode, name: string, result: var Log) =
var data: seq[byte]
var topics: seq[Topic]
fromJson(json["data"], "data", data)
fromJson(json["topics"], "topics", topics)
result = Log(data: data, topics: topics)