Skip to content

Commit e954862

Browse files
authored
fix: ensure wasm loaded (#6)
* fix: ensure wasm loaded * chore: remove withWasm function * fix: use correct await when initialization * fix: catch error for initialization
1 parent 3cc911c commit e954862

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

packages/sdk/src/index.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
Transaction,
1313
payToAddressScript,
1414
} from "./wasm/kaspa";
15-
import { rpcClient, watchBalanceChanged } from "./rpc-client";
15+
import { rpcClient, watchBalanceChanged, wasmReady } from "./rpc-client";
1616
import { IWalletEventHandler, NetworkId } from "./interfaces";
1717
import { listeners, ListenerMethod } from "./listener";
1818
import { sleep } from "./utils";
@@ -583,4 +583,29 @@ export const removeEventListener = (
583583
listeners[method].delete(handler);
584584
};
585585

586+
// ------------------------------------------------------------------------
587+
// --------------------------WASM Utilities--------------------------------
588+
// ------------------------------------------------------------------------
589+
590+
/**
591+
* Promise that resolves when the Kaspa WASM module is fully loaded and initialized
592+
* @example
593+
* ```typescript
594+
* await wasmReady;
595+
* const tx = kaspaWasm.createTransaction(...);
596+
* ```
597+
*/
598+
export { wasmReady } from "./rpc-client";
599+
600+
/**
601+
* The Kaspa WASM module
602+
* Note: Ensure wasmReady Promise is resolved before using this
603+
* @example
604+
* ```typescript
605+
* import { kaspaWasm, wasmReady } from 'kastle-sdk';
606+
*
607+
* await wasmReady;
608+
* const address = kaspaWasm.addressFromScriptPublicKey(...);
609+
* ```
610+
*/
586611
export const kaspaWasm = wasm;

packages/sdk/src/rpc-client.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,21 @@ import { config } from "./config";
33
import { getNetwork } from "./index";
44
import { sleep } from "./utils";
55

6+
// Initialize WASM module independently
7+
let wasmInitialized = false;
8+
export const wasmReady: Promise<void> = (async () => {
9+
if (!wasmInitialized) {
10+
await init(config.wasm);
11+
wasmInitialized = true;
12+
}
13+
})();
14+
615
export let rpcClient: RpcClient | undefined;
716

817
export const connectToRPC = async () => {
18+
// Ensure WASM is initialized before connecting to RPC
19+
await wasmReady;
20+
921
if (rpcClient?.isConnected) {
1022
rpcClient.removeAllEventListeners();
1123
await rpcClient.disconnect();
@@ -58,5 +70,5 @@ export const watchBalanceChanged = async (address: string | null) => {
5870
};
5971

6072
(async () => {
61-
await init(config.wasm).then(connectToRPC);
73+
await wasmReady.then(connectToRPC).catch(console.error);
6274
})();

0 commit comments

Comments
 (0)