Getting started¶
Run this example in the browser
Let's publish a note and receive it back from a relay. You'll need a key to sign with, a relay connection and a subscription for the incoming event.
In this guide, you will learn how to set up the project, then publish a note and receive it back from a relay.
Set up the project¶
Add org.ngengine:nostr4j and the matching platform adapter to your build. For the coordinates and requirements of each platform, follow the platform setup.
Publish and receive a note¶
Save the following as QuickStart.java and run it. Use a temporary identity: connect to a relay, subscribe to that identity's notes before publishing, then wait briefly so the subscription receives the note before the program exits.
import org.ngengine.nostr4j.NostrFilter;
import org.ngengine.nostr4j.NostrPool;
import org.ngengine.nostr4j.NostrSubscription;
import org.ngengine.nostr4j.event.SignedNostrEvent;
import org.ngengine.nostr4j.event.UnsignedNostrEvent;
import org.ngengine.nostr4j.keypair.NostrKeyPair;
import org.ngengine.nostr4j.signer.NostrKeyPairSigner;
import org.ngengine.platform.AsyncTask;
import org.ngengine.platform.NGEPlatform;
import org.ngengine.platform.jvm.JVMAsyncPlatform;
public class QuickStart {
public static void main(String[] args) throws Exception {
// snippet:start
NGEPlatform.set(new JVMAsyncPlatform());
NostrKeyPair keys = new NostrKeyPair();
NostrPool pool = new NostrPool();
NostrSubscription subscription = null;
try {
pool.ensureRelay("wss://relay.ngengine.org").await();
NostrFilter filter = new NostrFilter();
filter.withKind(1);
filter.withAuthor(keys.getPublicKey());
subscription = pool.subscribe(filter);
subscription.addEventListener((sub, event, stored) -> {
System.out.println("Received: " + event.getContent());
});
AsyncTask.awaitAll(subscription.open());
UnsignedNostrEvent draft = new UnsignedNostrEvent();
draft.withKind(1);
draft.withContent("Hello from Nostr4j!");
NostrKeyPairSigner signer = new NostrKeyPairSigner(keys);
SignedNostrEvent note = signer.sign(draft).await();
pool.publish(note).await();
System.out.println("Published: " + note.getId());
// Keep this standalone program alive briefly to receive the note.
Thread.sleep(5_000);
} finally {
if (subscription != null) subscription.close();
pool.close();
keys.close();
}
// snippet:end
}
}
After publish(note).await() returns, at least one relay has accepted the event. Seeing it in the subscription is a separate confirmation: a relay has sent the event back to you. In a running application, keep the pool open for as long as you need it.
For a persistent account, load an existing key or use a browser or remote signer. You can then change the filter to read other authors and choose how many relay acknowledgements to wait for when publishing.