Skip to content

Commit

Permalink
js: use redb (WIP)
Browse files Browse the repository at this point in the history
Signed-off-by: Yuki Kishimoto <[email protected]>
  • Loading branch information
yukibtc committed Jan 2, 2025
1 parent f8dfd70 commit 50ef965
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 35 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion bindings/nostr-sdk-js/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ crate-type = ["cdylib"]
console_error_panic_hook = "0.1"
js-sys.workspace = true
nostr-connect.workspace = true
nostr-sdk = { workspace = true, default-features = false, features = ["all-nips", "indexeddb", "webln"] }
nostr-redb.workspace = true
nostr-sdk = { workspace = true, default-features = false, features = ["all-nips", "webln"] }
nwc.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
Expand Down
14 changes: 9 additions & 5 deletions bindings/nostr-sdk-js/examples/negentropy.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
const { loadWasmAsync, initLogger, LogLevel, SyncOptions, SyncDirection, Filter, Client, NostrDatabase } = require("../");

// NOTE: this code work only on browser (due to indexeddb)!
const { loadWasmAsync, initLogger, LogLevel, SyncOptions, SyncDirection, Filter, Client, NostrDatabase, Kind } = require("../");

async function main() {
await loadWasmAsync();

initLogger(LogLevel.info());

let db = await NostrDatabase.indexeddb("js-test");
let db = await NostrDatabase.inMemory();
let client = Client.builder().database(db).build();

await client.addRelay("wss://relay.damus.io");

await client.connect();

let filter = new Filter().kind(1).limit(1000);
let filter = new Filter().kind(new Kind(1)).limit(1000);
let opts = new SyncOptions().direction(SyncDirection.Down);
await client.sync(filter, opts);

let f = new Filter().limit(2);
let events = await db.query([f]);
events.forEach((e) => {
console.log(e.asJson())
})
}

main();
2 changes: 1 addition & 1 deletion bindings/nostr-sdk-js/examples/webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@rust-nostr/nostr-sdk": "^0.33.0",
"@rust-nostr/nostr-sdk": "file:../../rust-nostr-nostr-sdk-0.37.0.tgz",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
Expand Down
38 changes: 21 additions & 17 deletions bindings/nostr-sdk-js/examples/webapp/src/App.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import React, { Component } from "react";
import { ClientBuilder, NostrSigner, NostrZapper, Filter, LogLevel, NegentropyOptions, Nip07Signer, NostrDatabase, PublicKey, ZapDetails, ZapEntity, ZapType, initLogger, loadWasmAsync } from '@rust-nostr/nostr-sdk'
import { ClientBuilder, EventBuilder, NostrSigner, NostrZapper, Filter, LogLevel, SyncOptions, Nip07Signer, NostrDatabase, PublicKey, ZapDetails, ZapEntity, ZapType, initLogger, loadWasmAsync } from '@rust-nostr/nostr-sdk'
import './App.css';
import {EventBuilder} from "../../../pkg/nostr_sdk_js";

class App extends Component {
constructor() {
super();
this.state = {
this.state = {
public_key: null,
nip07_signer: null,
client: null
Expand All @@ -19,7 +18,8 @@ class App extends Component {

// Try to initialize log
try {
initLogger(LogLevel.info());
initLogger(LogLevel.debug());
console.log("Logger initialized");
} catch (error) {}
}

Expand All @@ -29,33 +29,37 @@ class App extends Component {
let nip07_signer = new Nip07Signer();
let signer = NostrSigner.nip07(nip07_signer);
let zapper = await NostrZapper.webln();
let db = await NostrDatabase.indexeddb("nostr-sdk-webapp-example");

console.log("Opening database...");
let db = await NostrDatabase.web("nostr-sdk-webapp-example-2");
console.log("Database opened.");

let client = new ClientBuilder().signer(signer).zapper(zapper).database(db).build();

let public_key = await nip07_signer.getPublicKey();

// Add relays
await client.addRelay("wss://relay.damus.io");
await client.addRelay("wss://nos.lol");
await client.addRelay("wss://nostr.oxtr.dev");

// Connect to relays
await client.connect();

// Save client to state
this.setState({ client, nip07_signer, public_key });
} catch (error) {
console.log(error)
console.log(error)
}
};

handleReconcile = async () => {
try {
let filter = new Filter().author(this.state.public_key);
let opts = new NegentropyOptions();
let opts = new SyncOptions();
await this.state.client.sync(filter, opts);
} catch (error) {
console.log(error)
console.log(error)
}
}

Expand All @@ -66,29 +70,29 @@ class App extends Component {
console.time("query");
let events = await database.query([filter]);
console.timeEnd("query");
console.log("Got", events.length, "events");
console.log("Got", events.len(), "events");
} catch (error) {
console.log(error)
}
}

handlePublishTextNote = async () => {
try {
let builder = EventBuilder.textNote("Test from rust-nostr JavaScript bindings with NIP07 signer!", []);
let builder = EventBuilder.textNote("Test from rust-nostr JavaScript bindings with NIP07 signer!");
await this.state.client.sendEventBuilder(builder);
} catch (error) {
console.log(error)
console.log(error)
}
};

handleZap = async () => {
try {
let pk = PublicKey.fromBech32("npub1drvpzev3syqt0kjrls50050uzf25gehpz9vgdw08hvex7e0vgfeq0eseet");
let pk = PublicKey.parse("npub1drvpzev3syqt0kjrls50050uzf25gehpz9vgdw08hvex7e0vgfeq0eseet");
let entity = ZapEntity.publicKey(pk);
let details = new ZapDetails(ZapType.Public).message("Zap for Rust Nostr!");
await this.state.client.zap(entity, 1000, details);
} catch (error) {
console.log(error)
console.log(error)
}
};

Expand All @@ -98,7 +102,7 @@ class App extends Component {
this.setState({ client: null });
console.log("Logout done");
} catch (error) {
console.log(error)
console.log(error)
}
};

Expand Down
18 changes: 7 additions & 11 deletions bindings/nostr-sdk-js/src/database/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::ops::Deref;
use std::sync::Arc;

use js_sys::Array;
use nostr_redb::NostrRedb;
use nostr_sdk::prelude::*;
use wasm_bindgen::prelude::*;

Expand Down Expand Up @@ -75,22 +76,17 @@ impl From<Arc<dyn NostrDatabase>> for JsNostrDatabase {

#[wasm_bindgen(js_class = NostrDatabase)]
impl JsNostrDatabase {
/// Open/Create database with **unlimited** capacity
pub async fn indexeddb(name: &str) -> Result<JsNostrDatabase> {
let db = WebDatabase::open(name).await.map_err(into_err)?;
/// Open (or create) persistent web database
pub async fn web(name: &str) -> Result<JsNostrDatabase> {
let db = NostrRedb::web(name).await.map_err(into_err)?;
Ok(Self {
inner: db.into_nostr_database(),
})
}

/// Open/Create database with **limited** capacity
#[wasm_bindgen(js_name = indexeddbBounded)]
pub async fn indexeddb_bounded(name: &str, max_capacity: u64) -> Result<JsNostrDatabase> {
let db = Arc::new(
WebDatabase::open_bounded(name, max_capacity as usize)
.await
.map_err(into_err)?,
);
#[wasm_bindgen(js_name = inMemory)]
pub fn in_memory() -> Result<JsNostrDatabase> {
let db = NostrRedb::in_memory().map_err(into_err)?;
Ok(Self {
inner: db.into_nostr_database(),
})
Expand Down

0 comments on commit 50ef965

Please sign in to comment.