2024-01-03 20:06:53 +07:00
|
|
|
import
|
|
|
|
|
std/json,
|
|
|
|
|
stint,
|
2024-01-04 11:40:22 +07:00
|
|
|
../../json_rpc/jsonmarshal
|
2024-01-03 20:06:53 +07:00
|
|
|
|
|
|
|
|
{.push gcsafe, raises: [].}
|
2018-05-30 16:05:53 +01:00
|
|
|
|
|
|
|
|
template stintStr(n: UInt256|Int256): JsonNode =
|
|
|
|
|
var s = n.toHex
|
|
|
|
|
if s.len mod 2 != 0: s = "0" & s
|
|
|
|
|
s = "0x" & s
|
|
|
|
|
%s
|
|
|
|
|
|
|
|
|
|
proc `%`*(n: UInt256): JsonNode = n.stintStr
|
|
|
|
|
|
|
|
|
|
proc `%`*(n: Int256): JsonNode = n.stintStr
|
|
|
|
|
|
2024-01-03 20:06:53 +07:00
|
|
|
proc writeValue*(w: var JsonWriter[JrpcConv], val: UInt256)
|
|
|
|
|
{.gcsafe, raises: [IOError].} =
|
2023-12-14 01:29:11 +00:00
|
|
|
writeValue(w, val.stintStr)
|
|
|
|
|
|
2024-01-03 20:06:53 +07:00
|
|
|
proc writeValue*(w: var JsonWriter[JrpcConv], val: ref UInt256)
|
|
|
|
|
{.gcsafe, raises: [IOError].} =
|
2023-12-14 01:29:11 +00:00
|
|
|
writeValue(w, val[].stintStr)
|
|
|
|
|
|
2024-01-03 20:06:53 +07:00
|
|
|
proc readValue*(r: var JsonReader[JrpcConv], v: var UInt256)
|
|
|
|
|
{.gcsafe, raises: [JsonReaderError].} =
|
2023-12-14 01:29:11 +00:00
|
|
|
## Allows UInt256 to be passed as a json string.
|
|
|
|
|
## Expects base 16 string, starting with "0x".
|
|
|
|
|
try:
|
|
|
|
|
let hexStr = r.readValue string
|
|
|
|
|
if hexStr.len > 64 + 2: # including "0x"
|
|
|
|
|
raise newException(ValueError, "Value for '" & $v.type & "' too long for UInt256: " & $hexStr.len)
|
|
|
|
|
v = hexStr.parse(StUint[256], 16) # TODO: Handle errors
|
|
|
|
|
except Exception as err:
|
|
|
|
|
r.raiseUnexpectedValue("Error deserializing for '" & $v.type & "' stream: " & err.msg)
|
|
|
|
|
|
2024-01-03 20:06:53 +07:00
|
|
|
proc readValue*(r: var JsonReader[JrpcConv], v: var ref UInt256)
|
|
|
|
|
{.gcsafe, raises: [JsonReaderError].} =
|
2023-12-14 01:29:11 +00:00
|
|
|
## Allows ref UInt256 to be passed as a json string.
|
|
|
|
|
## Expects base 16 string, starting with "0x".
|
|
|
|
|
readValue(r, v[])
|
2018-05-30 16:05:53 +01:00
|
|
|
|
2024-01-03 20:06:53 +07:00
|
|
|
{.pop.}
|