nwaku/examples/v2/basic2.nim
Oskar Thorén 9518322198
Folder restructure (#274)
* Change folder structure to {v1,v2,common}/...

Addresses https://github.com/status-im/nim-waku/issues/261

* Update waku.nimble paths

* Flatten paths

* Fix import paths

* Pull out utils folder for nat

* Pull out waku_types to top level for v2

* Fix test import paths

* Remove old READMEs and replace with one liner

* Update README and split v1 and v2

* Skeleton READMEs

* Update README.md

Co-authored-by: Kim De Mey <kim.demey@gmail.com>

* Update README.md

Co-authored-by: Kim De Mey <kim.demey@gmail.com>

Co-authored-by: Kim De Mey <kim.demey@gmail.com>
2020-11-17 17:34:53 +08:00

49 lines
1.4 KiB
Nim

## Here's a basic example of how you would start a Waku node, subscribe to
## topics, and publish to them.
import
std/os,
confutils, chronicles, chronos,
stew/shims/net as stewNet,
libp2p/crypto/[crypto,secp],
eth/keys,
json_rpc/[rpcclient, rpcserver],
../../waku/v2/node/[config, wakunode2],
../../waku/common/utils/nat,
../../waku/v2/waku_types
type
Topic* = waku_types.Topic
# Node operations happens asynchronously
proc runBackground() {.async.} =
let
conf = WakuNodeConf.load()
(extIp, extTcpPort, extUdpPort) = setupNat(conf.nat, clientId,
Port(uint16(conf.tcpPort) + conf.portsShift),
Port(uint16(conf.udpPort) + conf.portsShift))
node = WakuNode.init(conf.nodeKey, conf.listenAddress,
Port(uint16(conf.tcpPort) + conf.portsShift), extIp, extTcpPort)
await node.start()
await node.mountRelay()
# Subscribe to a topic
let topic = cast[Topic]("foobar")
proc handler(topic: Topic, data: seq[byte]) {.async, gcsafe.} =
let message = WakuMessage.init(data).value
let payload = cast[string](message.payload)
info "Hit subscribe handler", topic=topic, payload=payload, contentTopic=message.contentTopic
await node.subscribe(topic, handler)
# Publish to a topic
let payload = cast[seq[byte]]("hello world")
let message = WakuMessage(payload: payload, contentTopic: ContentTopic(1))
node.publish(topic, message)
# TODO Await with try/except here
discard runBackground()
runForever()