From 60f8749ca336ab29dd03f183dbe92d3929bf6c1b Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Tue, 19 Apr 2022 17:48:27 +0200 Subject: [PATCH] Fix crash when connection fails Removes asyncSpawn call to handleSubscriptions(), to ensure that when the RpcClient can't connect, we don't crash. --- ethers/providers/jsonrpc.nim | 48 +++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/ethers/providers/jsonrpc.nim b/ethers/providers/jsonrpc.nim index f33df34..a06dd41 100644 --- a/ethers/providers/jsonrpc.nim +++ b/ethers/providers/jsonrpc.nim @@ -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):