Store fixes

This commit is contained in:
Jim Hamill
2025-03-15 02:49:54 +00:00
parent 3284943bea
commit 38d0071a7b
2 changed files with 87 additions and 70 deletions
@@ -1,6 +1,11 @@
import { BaseStore } from './base-store.js';
import { Encrypter, SSEClient } from '../utils';
import { Bytes, PrivateKey, PublicKey } from '@xocash/primitives';
import {
Bytes,
PrivateKey,
PublicKey,
decodeExtendedJson,
} from '@xocash/primitives';
import { pack, unpack } from 'msgpackr';
import { z } from 'zod';
@@ -68,6 +73,7 @@ export class StoreRemoteHTTP extends BaseStore {
}
async subscribeEvents() {
// Compute our signature (to authenticate with the SSE endpoint).
const timestamp = Math.floor(Date.now() / 1000);
const signature = await StoreRemoteHTTP.signRequest(
this.privateKey.toHex(),
@@ -76,6 +82,7 @@ export class StoreRemoteHTTP extends BaseStore {
{},
);
// Define our headers.
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
@@ -84,13 +91,19 @@ export class StoreRemoteHTTP extends BaseStore {
'X-Timestamp': timestamp.toString(),
};
const sseClient = new SSEClient(`${this.baseURL}events`, {
// Create our SSE Client.
// NOTE: SSE only supports text-encoding, so we use Extended JSON instead of msgpackr (which is binary).
// TODO: It would be really nice to somehow be able to support msgpackr for consistency though.
// But, from a bandwidth point of view, this is not crucial: These payloads are "live" payloads (thus, there's not much data).
await SSEClient.from(`${this.baseURL}events`, {
method: 'POST',
headers,
onMessage: (e) => {
// Validate the payload using Zod.
// TODO: Use msgpackr
const payload = StoreRemoteHTTPEventSchema.parse(JSON.parse(e.data));
const payload = StoreRemoteHTTPEventSchema.parse(
decodeExtendedJson(e.data),
);
// Emit the event (update) to any listeners.
this.emit(payload.action, {
@@ -100,8 +113,6 @@ export class StoreRemoteHTTP extends BaseStore {
},
body: JSON.stringify({}),
});
await sseClient.connect();
}
private async makeRequest(endpoint: string, payload: object = {}) {