Fix crash when connection fails

Removes asyncSpawn call to handleSubscriptions(), to ensure
that when the RpcClient can't connect, we don't crash.
This commit is contained in:
Mark Spanbroek 2022-04-19 17:48:27 +02:00 committed by markspanbroek
parent a0dca2674d
commit 60f8749ca3
1 changed files with 25 additions and 23 deletions

View File

@ -44,11 +44,33 @@ proc connect(_: type RpcClient, url: string): Future[RpcClient] {.async.} =
await client.connect(url)
return client
proc handleSubscriptions(provider: JsonRpcProvider) {.async.}
proc connect(provider: JsonRpcProvider, url: string) =
proc getLogHandler(subscriptionId: JsonNode): ?LogHandler =
try:
if provider.subscriptions.hasKey(subscriptionId):
provider.subscriptions[subscriptionId].some
else:
LogHandler.none
except Exception:
LogHandler.none
proc handleSubscription(arguments: JsonNode) {.upraises: [].} =
if id =? arguments["subscription"].catch and
handler =? getLogHandler(id) and
log =? Log.fromJson(arguments["result"]).catch:
handler(log)
proc subscribe: Future[RpcClient] {.async.} =
let client = await RpcClient.connect(url)
client.setMethodHandler("eth_subscription", handleSubscription)
return client
provider.client = subscribe()
proc new*(_: type JsonRpcProvider, url=defaultUrl): JsonRpcProvider =
let provider = JsonRpcProvider(client: RpcClient.connect(url))
asyncSpawn provider.handleSubscriptions()
let provider = JsonRpcProvider()
provider.connect(url)
provider
proc send*(provider: JsonRpcProvider,
@ -105,26 +127,6 @@ method getChainId*(provider: JsonRpcProvider): Future[UInt256] {.async.} =
except CatchableError:
return parse(await client.net_version(), UInt256)
proc handleSubscriptions(provider: JsonRpcProvider) {.async.} =
proc getLogHandler(id: JsonNode): ?LogHandler =
try:
if provider.subscriptions.hasKey(id):
provider.subscriptions[id].some
else:
LogHandler.none
except Exception:
LogHandler.none
proc handleSubscription(arguments: JsonNode) {.upraises: [].} =
if id =? arguments["subscription"].catch and
handler =? getLogHandler(id) and
log =? Log.fromJson(arguments["result"]).catch:
handler(log)
let client = await provider.client
client.setMethodHandler("eth_subscription", handleSubscription)
method subscribe*(provider: JsonRpcProvider,
filter: Filter,
callback: LogHandler):