Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: waku improvements #384

Merged
merged 1 commit into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/lib/adapters/waku/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import type { StorageChat, StorageChatEntry, StorageObjectEntry, StorageProfile
import { genRandomHex } from '$lib/utils'
import { walletStore } from '$lib/stores/wallet'

const MAX_MESSAGES = 100

interface QueuedMessage {
message: Message
address: string
Expand Down Expand Up @@ -96,7 +98,7 @@ async function addMessageToChat(
const unread = message.fromAddress !== address && message.type === 'user' ? 1 : 0
chats.updateChat(chatId, (chat) => ({
...chat,
messages: [...chat.messages, message],
messages: [...chat.messages.slice(-MAX_MESSAGES), message],
unread: chat.unread + unread,
}))
}
Expand Down Expand Up @@ -165,7 +167,14 @@ export default class WakuAdapter implements Adapter {

async onLogIn(wallet: BaseWallet): Promise<void> {
const address = wallet.address
this.waku = await connectWaku()
this.waku = await connectWaku({
onDisconnect: () => {
console.debug('❌ disconnected from waku')
},
onConnect: () => {
console.debug('✅ connected to waku')
},
})

const wakuObjectAdapter = makeWakuObjectAdapter(this, wallet)

Expand Down
12 changes: 9 additions & 3 deletions src/lib/adapters/waku/waku.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ function getTopic(contentTopic: ContentTopic, id: string | '' = '') {

interface ConnectWakuOptions {
onDisconnect?: () => void
onConnect?: (connections: unknown[]) => void
}

export async function connectWaku(options?: ConnectWakuOptions) {
Expand All @@ -48,6 +49,13 @@ export async function connectWaku(options?: ConnectWakuOptions) {
}
})

waku.libp2p.addEventListener('peer:connect', () => {
if (options?.onConnect && waku.libp2p.getConnections().length > 0) {
const connections = waku.libp2p.getConnections()
options.onConnect(connections)
}
})

await waku.start()
await waku.dial(peerMultiaddr)
await waitForRemotePeer(waku, [Protocols.Filter, Protocols.LightPush, Protocols.Store])
Expand Down Expand Up @@ -107,7 +115,5 @@ export async function sendMessage(waku: LightNode, id: string, message: unknown)
const encoder = createEncoder({ contentTopic })

const { error } = await waku.lightPush.send(encoder, { payload })
if (error) {
console.error(error)
}
return error
}
58 changes: 34 additions & 24 deletions src/lib/adapters/waku/wakustore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,27 @@ export function makeWakustore(waku: LightNode) {
return makeQuery(contentTopic, id, queryOptions)
}

function decodedMessageToTypedResult<T>(message: DecodedMessage): T {
const decodedPayload = decodeMessagePayload(message)
const typedPayload = JSON.parse(decodedPayload) as T & { timestamp?: number }

// HACK to use waku timestamp instead of the type T's
if (
typedPayload &&
typeof typedPayload === 'object' &&
!Array.isArray(typedPayload) &&
typedPayload.timestamp
) {
return {
...typedPayload,
timestamp: Number(message.timestamp),
origTimestamp: typedPayload.timestamp,
}
} else {
return typedPayload
}
}

async function parseQueryResults<T>(
results: QueryResult,
queryOptions?: QueryOptions,
Expand All @@ -52,24 +73,8 @@ export function makeWakustore(waku: LightNode) {
for (const messagePromise of messagePromises) {
const message = await messagePromise
if (message) {
const decodedPayload = decodeMessagePayload(message)
const typedPayload = JSON.parse(decodedPayload) as T & { timestamp?: number }

// HACK to use waku timestamp instead of the type T's
if (
typedPayload &&
typeof typedPayload === 'object' &&
!Array.isArray(typedPayload) &&
typedPayload.timestamp
) {
typedResults.push({
...typedPayload,
timestamp: Number(message.timestamp),
origTimestamp: typedPayload.timestamp,
})
} else {
typedResults.push(typedPayload)
}
const typedResult = decodedMessageToTypedResult<T>(message)
typedResults.push(typedResult)

// reached the limit
if (
Expand Down Expand Up @@ -104,6 +109,16 @@ export function makeWakustore(waku: LightNode) {
}

async function onSnapshot<T>(query: Query, callback: (value: T) => void): Promise<Unsubscribe> {
const subscription = await subscribe(
waku,
query.contentTopic,
query.id,
(msg: DecodedMessage) => {
const typedResult = decodedMessageToTypedResult<T>(msg)
callback(typedResult)
},
)

const queryOptions = {
...query.queryOptions,
pageSize: query.queryOptions?.pageSize ?? query.queryOptions?.limit,
Expand All @@ -115,12 +130,7 @@ export function makeWakustore(waku: LightNode) {
callback(value)
}

return await subscribe(waku, query.contentTopic, query.id, (msg: DecodedMessage) => {
const decodedPayload = decodeMessagePayload(msg)
const decodedValue = JSON.parse(decodedPayload) as T

callback(decodedValue)
})
return subscription
}

return {
Expand Down