status-lib/status/statusgo_backend/network.nim

43 lines
1.3 KiB
Nim
Raw Normal View History

import
json, chronicles, atomics
import json_serialization
from ./core import callPrivateRPC
2021-09-10 18:13:46 +00:00
from ../types/rpc_response import RpcResponseTyped, RpcException
2021-09-22 17:49:45 +00:00
from ../types/network import Network, toPayload
logScope:
topics = "wallet"
var
networks {.threadvar.}: seq[Network]
netowrksInited {.threadvar.}: bool
dirty: Atomic[bool]
dirty.store(true)
proc getNetworks*(useCached: bool = true): seq[Network] =
let cacheIsDirty = not netowrksInited or dirty.load
if useCached and not cacheIsDirty:
result = networks
else:
let payload = %* [false]
let responseStr = callPrivateRPC("wallet_getEthereumChains", payload)
2021-09-10 18:13:46 +00:00
let response = Json.decode(responseStr, RpcResponseTyped[JsonNode])
if not response.error.isNil:
raise newException(RpcException, "Error getting networks: " & response.error.message)
2021-09-10 18:13:46 +00:00
result = if response.result.isNil or response.result.kind == JNull: @[]
else: Json.decode($response.result, seq[Network])
dirty.store(false)
networks = result
netowrksInited = true
proc upsertNetwork*(network: Network) =
discard callPrivateRPC("wallet_addEthereumChain", network.toPayload())
dirty.store(true)
proc deleteNetwork*(network: Network) =
let payload = %* [network.chainId]
discard callPrivateRPC("wallet_deleteEthereumChain", payload)
dirty.store(true)