92 lines
2.7 KiB
Nim
92 lines
2.7 KiB
Nim
import std/json
|
|
import pkg/asynctest
|
|
import pkg/json_rpc/rpcclient
|
|
import ethers/provider
|
|
import ethers/providers/jsonrpc/subscriptions
|
|
|
|
suite "JsonRpcSubscriptions":
|
|
|
|
test "can be instantiated with an http client":
|
|
let client = newRpcHttpClient()
|
|
let subscriptions = JsonRpcSubscriptions.new(client)
|
|
check not isNil subscriptions
|
|
|
|
test "can be instantiated with a websocket client":
|
|
let client = newRpcWebSocketClient()
|
|
let subscriptions = JsonRpcSubscriptions.new(client)
|
|
check not isNil subscriptions
|
|
|
|
template subscriptionTests(subscriptions, client) =
|
|
|
|
test "subscribes to new blocks":
|
|
var latestBlock: Block
|
|
proc callback(blck: Block) =
|
|
latestBlock = blck
|
|
let subscription = await subscriptions.subscribeBlocks(callback)
|
|
discard await client.call("evm_mine", newJArray())
|
|
check eventually latestBlock.number.isSome
|
|
check latestBlock.hash.isSome
|
|
check latestBlock.timestamp > 0.u256
|
|
await subscriptions.unsubscribe(subscription)
|
|
|
|
test "stops listening to new blocks when unsubscribed":
|
|
var count = 0
|
|
proc callback(blck: Block) =
|
|
inc count
|
|
let subscription = await subscriptions.subscribeBlocks(callback)
|
|
discard await client.call("evm_mine", newJArray())
|
|
check eventually count > 0
|
|
await subscriptions.unsubscribe(subscription)
|
|
count = 0
|
|
discard await client.call("evm_mine", newJArray())
|
|
await sleepAsync(100.millis)
|
|
check count == 0
|
|
|
|
test "stops listening to new blocks when provider is closed":
|
|
var count = 0
|
|
proc callback(blck: Block) =
|
|
inc count
|
|
discard await subscriptions.subscribeBlocks(callback)
|
|
discard await client.call("evm_mine", newJArray())
|
|
check eventually count > 0
|
|
await subscriptions.close()
|
|
count = 0
|
|
discard await client.call("evm_mine", newJArray())
|
|
await sleepAsync(100.millis)
|
|
check count == 0
|
|
|
|
suite "Web socket subscriptions":
|
|
|
|
var subscriptions: JsonRpcSubscriptions
|
|
var client: RpcWebSocketClient
|
|
|
|
setup:
|
|
client = newRpcWebSocketClient()
|
|
await client.connect("ws://localhost:8545")
|
|
subscriptions = JsonRpcSubscriptions.new(client)
|
|
subscriptions.start()
|
|
|
|
teardown:
|
|
await subscriptions.close()
|
|
await client.close()
|
|
|
|
subscriptionTests(subscriptions, client)
|
|
|
|
suite "HTTP polling subscriptions":
|
|
|
|
var subscriptions: JsonRpcSubscriptions
|
|
var client: RpcHttpClient
|
|
|
|
setup:
|
|
client = newRpcHttpClient()
|
|
await client.connect("http://localhost:8545")
|
|
subscriptions = JsonRpcSubscriptions.new(client,
|
|
pollingInterval = 100.millis)
|
|
subscriptions.start()
|
|
|
|
teardown:
|
|
await subscriptions.close()
|
|
await client.close()
|
|
|
|
subscriptionTests(subscriptions, client)
|