Pear Worklet WDK API Reference
API reference for Pear Worklet HRPC, JSON-RPC, module calls, request types, and suspend diagnostics
Package: @tetherto/pear-wrk-wdk
Top-level export: HRPC
Command Methods
| Method | Signature | Description |
|---|---|---|
log() | log(args: LogRequest): void | Sends a log payload over the HRPC stream. |
workletStart() | workletStart(args: WorkletStartRequest): Promise\<WorkletStartResponse\> | Deprecated empty startup handshake. The published request type is stale in beta.15. |
initializeWDK() | initializeWDK(args: WdkInitializeParams): Promise\<{ status: string }\> | Creates or reinitializes the worklet WDK instance and registers wallets and optional protocols from config. |
resetWdkWallets() | resetWdkWallets(args: WdkResetWalletParams): Promise\<{ status: string }\> | Selectively disposes and re-registers only the wallets listed in config.networks. |
generateEntropyAndEncrypt() | generateEntropyAndEncrypt(args: WdkGenerateEntropyParams): Promise\<WdkEntropyResult\> | Generates encrypted seed and entropy buffers inside the worklet. |
getMnemonicFromEntropy() | getMnemonicFromEntropy(args: WdkGetMnemonicParams): Promise\<{ mnemonic: string }\> | Decrypts an encrypted entropy payload and returns the mnemonic. |
getSeedAndEntropyFromMnemonic() | getSeedAndEntropyFromMnemonic(args: { mnemonic: string }): Promise\<WdkEntropyResult\> | Converts a mnemonic into encrypted seed and entropy buffers. |
dispose() | dispose(args: DisposeRequest): void | Sends a one-way full-disposal request over HRPC. The declared selective field is not encoded in beta.15. |
callMethod() | callMethod(args: CallMethodRequest): Promise\<CallMethodResponse\> | Looks up the target account and invokes one wallet or protocol method by name. |
registerWallet() | registerWallet(args: { config: string }): Promise\<{ status: string, blockchains: string }\> | Dynamically registers additional wallets from a JSON config string. |
registerProtocol() | registerProtocol(args: { config: string }): Promise\<{ status: string }\> | Dynamically registers additional protocols from a JSON config string. |
callModule() | callModule(args: CallModuleRequest): Promise\<CallModuleResponse\> | Calls a method on a configured generic module over HRPC. |
moduleEvent() | moduleEvent(args: ModuleEventRequest): void | Sends a generic-module event from the worklet to the HRPC host. |
Handler Registration Methods
| Method | Signature | Description |
|---|---|---|
onLog() | onLog(responseFn): void | Registers the server-side handler for log(). |
onWorkletStart() | onWorkletStart(responseFn): void | Registers the server-side handler for workletStart(). |
onInitializeWDK() | onInitializeWDK(responseFn): void | Registers the server-side handler for initializeWDK(). |
onResetWdkWallets() | onResetWdkWallets(responseFn): void | Registers the server-side handler for resetWdkWallets(). |
onGenerateEntropyAndEncrypt() | onGenerateEntropyAndEncrypt(responseFn): void | Registers the server-side handler for encrypted entropy generation. |
onGetMnemonicFromEntropy() | onGetMnemonicFromEntropy(responseFn): void | Registers the server-side handler for mnemonic recovery. |
onGetSeedAndEntropyFromMnemonic() | onGetSeedAndEntropyFromMnemonic(responseFn): void | Registers the server-side handler for mnemonic migration. |
onDispose() | onDispose(responseFn): void | Registers the server-side handler for dispose(). |
onCallMethod() | onCallMethod(responseFn): void | Registers the server-side handler for callMethod(). |
onRegisterWallet() | onRegisterWallet(responseFn): void | Registers the server-side handler for registerWallet(). |
onRegisterProtocol() | onRegisterProtocol(responseFn): void | Registers the server-side handler for registerProtocol(). |
onCallModule() | onCallModule(responseFn): void | Registers the worklet-side handler for generic-module calls. |
onModuleEvent() | onModuleEvent(responseFn): void | Registers the host-side handler for generic-module events. |
log
type?(LogType): Optional numeric log level.data?(string | null): Optional log payload.
workletStart
Deprecated startup request retained in the shipped type surface. Its runtime payload is {}. JavaScript callers can use workletStart({}). The published TypeScript type cannot express the empty runtime request, so isolate the mismatch behind a local compatibility wrapper until the declaration is corrected.
The beta.15 HRPC schema encodes an empty request and ignores enableDebugLogs, seedPhrase, seedBuffer, and config. The published WorkletStartRequest declaration still lists those obsolete fields and incorrectly requires config. JSON-RPC also treats workletStart as an empty handshake.
Returns:
status?(string | null)
initializeWDK
encryptionKey?(Buffer): Decryption key for the encrypted seed buffer.encryptedSeed?(Buffer): Encrypted seed buffer.config(string): JSON stringifiedWdkWorkletConfig.
The handler requires encryptionKey and encryptedSeed to be passed together or omitted together. HRPC carries both as native buffers; JSON-RPC accepts base64 strings for the same fields. When a seeded WDK instance already exists, the runtime closes its generic modules and calls wdk.dispose() before validating the new config. A replacement seed pair then causes the old retained buffer to be overwritten before the new seed is decrypted. Config-only reinitialization reuses the existing WDK object and seed buffer.
Generic modules on either transport are constructed from context.moduleManagers and config.modules only when that request includes the encrypted seed pair. A seedless reinitialization closes existing module instances without reconstructing them. Supply both seed fields on every initialization that must construct or reconstruct modules. See initialization and cleanup limits.
resetWdkWallets
config(string): JSON stringified object containing anetworksmap.
The runtime validates config.networks, extracts each target blockchain, calls wdk.dispose(targetChains), and re-registers only those wallet managers. This method does not re-register protocols or close generic modules; existing module instances keep running.
generateEntropyAndEncrypt
wordCount(12 | 24): The mnemonic word count to generate.
Returns:
encryptionKey(Buffer)encryptedSeedBuffer(Buffer)encryptedEntropyBuffer(Buffer)
These are live buffers returned to the HRPC caller. Overwrite them after their final use. JSON-RPC encodes the same three result fields as base64 strings.
getMnemonicFromEntropy
encryptedEntropy(Buffer): Encrypted entropy.encryptionKey(Buffer): Decryption key.
Returns:
mnemonic(string)
getSeedAndEntropyFromMnemonic
mnemonic(string): Source mnemonic to migrate into encrypted buffers.
Returns:
encryptionKey(Buffer)encryptedSeedBuffer(Buffer)encryptedEntropyBuffer(Buffer)
These are live buffers returned to the HRPC caller. Overwrite them after their final use. JSON-RPC encodes the same three result fields as base64 strings.
dispose
args(DisposeRequest): Pass{}for HRPC full disposal. The declaration's optionalblockchainsfield is stale for the beta.15 HRPC wire schema.
A full disposal closes all generic modules and clears the WDK instance. It also overwrites and releases context.wdkSeedBuffer. After module shutdown completes, this cleanup runs even if wdk.dispose() throws.
HRPC encodes no request fields, so dispose({ blockchains: [...] }) still performs full disposal. It sends the request without awaiting a response and returns void. Use resetWdkWallets() for selective HRPC disposal and re-registration.
JSON-RPC preserves a non-empty params.blockchains array and disposes only those wallets while retaining the WDK instance, seed buffer, and generic modules. It returns { status: 'disposed' } inside its response result when the handler completes successfully. See disposal limits.
callMethod
methodName(string): Account method to invoke.network(string): Target blockchain key used to resolve the account.accountIndex(number): Account index passed towdk.getAccount(network, accountIndex).args?(string): JSON string of the method arguments.options?(string): JSON string ofCallMethodOptions.
options.protocolType may be swap, swidge, bridge, lending, or fiat. When present, the runtime requires a non-empty options.protocolName and resolves the protocol-specific account wrapper before invoking methodName. Swidge calls resolve the wrapper with account.getSwidgeProtocol(protocolName).
When RpcContext.allowedMethods defines the target surface, methodName must appear in its methods array. Account restrictions are keyed by network; protocol restrictions are nested by network, protocol type, and protocol name. Omitted surfaces remain unrestricted, while methods: [] denies every call on that exact surface. Denied calls fail before dispatch with the runtime code METHOD_NOT_ALLOWED.
A missing wallet or protocol method fails with BAD_REQUEST. Beta.13 removes the options.defaultValue fallback from both runtime dispatch and CallMethodOptions; callers must handle unsupported methods themselves.
Beta.14 removes options.transformResult from CallMethodOptions and no longer invokes it in the handler. Transform results after receiving them in the host. Invalid JSON in args or options still fails with BAD_REQUEST, but no longer includes the native JSON parser's error detail.
registerWallet
config(string): JSON string of network config entries.
Returns:
status(string)blockchains(string): JSON stringified array of registered blockchain names.
registerProtocol
config(string): JSON string of protocol config entries.
Returns:
status(string)
callModule
Call one method on a configured generic module. Both HRPC and JSON-RPC support this operation since beta.13.
module(string): Module name shared byRpcContext.moduleManagersandWdkWorkletConfig.modules.method(string): Non-empty method name on the constructed module instance.args?(string): Optional JSON string of arguments. Arrays are spread as positional arguments; omitted or decodednullarguments call the method with no arguments. Other values are passed as one argument.
HRPC returns CallModuleResponse with optional result, a JSON string. JSON-RPC decodes that string and returns the value at response.result.result. The runtime awaits promises, materializes values with .toArray(), and recursively converts Uint8Array values to hex before serialization. A top-level undefined or null result becomes the HRPC string "null" and the decoded JSON-RPC value null. Other falsy results such as false, 0, and '' are preserved. This module normalization does not apply to wallet or protocol callMethod() results.
When RpcContext.allowedModuleMethods defines the target module, method must appear in that module's methods array. Omitted modules remain unrestricted, while methods: [] denies every method on that module. A denied call fails with METHOD_NOT_ALLOWED before instance lookup or dispatch.
moduleEvent
Send an HRPC module event to the host. JSON-RPC forwards the same event as a moduleEvent notification with decoded params.payload; it has no request id.
Beta.14 fixes HRPC event forwarding from hosted modules by preserving the RPC receiver when sending moduleEvent(). The event payload shape is unchanged.
module(string): Module name.event(string): Event name.payload?(string | null): Optional JSON string payload.
onLog
Registers the server-side handler used to service log() requests.
onWorkletStart
Registers the server-side handler used to service the deprecated workletStart() request.
onInitializeWDK
Registers the server-side handler used to service initializeWDK() requests on the worklet side.
onResetWdkWallets
Registers the server-side handler used to service resetWdkWallets() requests on the worklet side.
onGenerateEntropyAndEncrypt
Registers the server-side handler used to service encrypted entropy generation requests.
onGetMnemonicFromEntropy
Registers the server-side handler used to service mnemonic recovery requests.
onGetSeedAndEntropyFromMnemonic
Registers the server-side handler used to service mnemonic migration requests.
onDispose
Registers the server-side handler used to service dispose() requests.
onCallMethod
Registers the server-side handler used to service callMethod() requests.
onRegisterWallet
Registers the server-side handler used to service registerWallet() requests.
onRegisterProtocol
Registers the server-side handler used to service registerProtocol() requests.
onCallModule
Registers the worklet-side handler used to service callModule() requests.
onModuleEvent
Registers the host-side handler used to receive moduleEvent() messages.
Worklet export: registerRpcHandlers(rpc, context)
Import this helper from @tetherto/pear-wrk-wdk/worklet. It registers the package's server-side handlers on the provided RPC instance.
rpc(any): RPC server instance that supports the generated handler registration methods.context(RpcContext): Runtime context containingwdk,WDK,walletManagers,protocolManagers, andwdkLoadError. Generic modules on either transport can additionally supplymoduleManagersandcapabilities; the runtime managesmoduleRuntime,moduleInstances, andwdkSeedBuffer. OptionalallowedMethodsrestricts wallet and protocol dispatch on HRPC and JSON-RPC, whileallowedModuleMethodsrestricts generic-module dispatch on both transports.
Worklet utility exports
The @tetherto/pear-wrk-wdk/worklet and @tetherto/pear-wrk-wdk/jsonrpc runtime entrypoints expose utils.crypto and utils.validation. The top-level runtime entrypoint exports only HRPC, even though its beta.15 declaration also lists utility members.
utils.crypto
| Function | Signature | Ownership |
|---|---|---|
memzero() | (buffer: Buffer | Uint8Array | ArrayBuffer) => void | Overwrites the supplied mutable bytes. |
encrypt() | (data: Uint8Array | Buffer, key: Buffer) => Buffer | Leaves caller-owned inputs unchanged and returns a caller-owned buffer. |
decrypt() | (encryptedBuffer: Buffer, key: Buffer) => Buffer | Leaves both inputs unchanged and returns a caller-owned buffer. |
generateEntropy() | (wordCount: 12 | 24) => Uint8Array | Returns caller-owned entropy bytes. |
encryptSecrets() | (seed: Uint8Array | Buffer, entropy: Uint8Array | Buffer) => WdkEntropyResult | Leaves caller-owned inputs unchanged and returns caller-owned key, seed, and entropy buffers. |
Beta.15 removes generateEncryptionKey() and replaces the base64-string inputs or results of encrypt(), decrypt(), and encryptSecrets() with buffers. generateEntropy() still returns Uint8Array, and memzero() still returns void. Overwrite caller-owned inputs and returned buffers after their final use. This cannot remove immutable strings or extra copies created elsewhere.
utils.validation
Beta.15 replaces validateBase64(value, fieldName) with validateBuffer(value, fieldName). The new helper accepts only a non-empty Buffer.
Types
RpcContext.wdkSeedBuffer
wdkSeedBuffer?: Buffer | null is a runtime-managed field added in beta.14. It retains the decrypted buffer passed to the WDK constructor so the runtime can overwrite it on full disposal or seed replacement. Do not populate it manually. JSON-RPC selective disposal, resetWdkWallets(), and config-only reinitialization retain it. See initialization rules for failure-path limits.
RpcContext Method Restrictions
interface ProtocolAllowedMethods {
methods?: string[]
}
interface ProtocolNameAllowedMethods {
[protocolName: string]: ProtocolAllowedMethods
}
interface ProtocolTypeAllowedMethods {
[protocolType: string]: ProtocolNameAllowedMethods
}
interface NetworkAllowedMethods extends ProtocolAllowedMethods {
protocols?: ProtocolTypeAllowedMethods
}
interface RpcContext {
// Other runtime fields...
allowedMethods?: Record<string, NetworkAllowedMethods>
allowedModuleMethods?: Record<string, ProtocolAllowedMethods>
}The four allowlist helper interfaces are exported types in beta.13. Every omitted level remains unrestricted. Use an explicit empty methods array to deny all dynamic calls on one exact surface.
The runtime exposes METHOD_NOT_ALLOWED for denied calls, but the beta.15 published error-code declaration still does not include that member. Treat the literal runtime code as authoritative for this release.
WdkWorkletConfig
interface WdkWorkletConfig {
networks: {
[blockchain: string]: {
blockchain: string
config: unknown
}
}
protocols?: {
[protocolName: string]: {
blockchain: string
protocolName: string
config: unknown
}
}
modules?: {
[moduleName: string]: Record<string, unknown>
}
}The modules map contains runtime module configuration. Its names must match the module managers generated by Worklet Bundler or supplied manually in RpcContext.
WdkModuleManager
interface WdkModuleManager {
events?: string[]
createModule: (context: {
seed: any
config: any
capabilities: Record<string, any>
emit: (event: string, payload?: any) => void
}) => any | Promise<any>
}The factory must consume seed synchronously rather than retain it. Module instances can optionally implement close(), suspend(), and resume(). The runtime calls close() during full disposal or reinitialization; targeted blockchain disposal and resetWdkWallets() leave generic modules running. Manual Pear integrations must forward Bare lifecycle events to context.moduleRuntime.suspendAll() and resumeAll(); registering either transport alone does not install those listeners. Declared events are forwarded from the instance, and the injected emit() function can emit events directly.
Module request types
interface CallModuleRequest {
module: string
method: string
args?: string
}
interface CallModuleResponse {
result?: string | null
}
interface ModuleEventRequest {
module: string
event: string
payload?: string | null
}WdkResetWalletParams
interface WdkResetWalletParams {
config: string
}CallMethodOptions
enum ProtocolType {
SWAP = 'swap',
SWIDGE = 'swidge',
BRIDGE = 'bridge',
LENDING = 'lending',
FIAT = 'fiat'
}
interface CallMethodOptions {
protocolType: ProtocolType
protocolName: string
}The published declarations include ProtocolType, but the top-level JavaScript entry does not export that enum value at runtime. Pass the corresponding string literal, such as 'swidge', in serialized request options.
The published CallMethodOptions declaration marks both fields as required. The request's options string remains optional at runtime, and the handler reads fields only when their behavior is used. Beta.14 removes the former function-valued transformResult field; apply transformations in the host after decoding the response.
Diagnostic export: registerHandleLeakCheck(options?)
Import this helper from @tetherto/pear-wrk-wdk/diagnostics/handle-leak-check:
interface HandleLeakCheckOptions {
tickIntervalMs?: number
}
function registerHandleLeakCheck(options?: HandleLeakCheckOptions): voidtickIntervalMs is the sampling interval in milliseconds, defaulting to 1000. The helper logs immediately on Bare suspend, repeats with an unreferenced timer, and stops on idle or resume. Handle records include type, native address, isActive, isClosing, and hasRef; it reports rather than closes handles.
Register once per worklet. The helper performs no interval validation and returns without registering listeners when bare-walk-handles or Bare lifecycle events are unavailable. Logs use console.warn independently of LOG_LEVEL. This helper is opt-in; transport registration does not enable it.
JSON-RPC Transport
Import registerJsonRpcHandlers() from the separate JSON-RPC entrypoint:
const { registerJsonRpcHandlers } = require('@tetherto/pear-wrk-wdk/jsonrpc')
registerJsonRpcHandlers(ipc, context)The server reads UTF-8 JSON-RPC 2.0 messages framed with a four-byte unsigned big-endian payload length. Every request requires an ID, and an ID cannot be reused while its earlier request is still in flight. Malformed frames are dropped without a response. The package does not export a JSON-RPC client or native-host helper.
Beta.15 decodes known base64 secret fields before it rejects a missing, null, or duplicate in-flight request ID. Those early-rejected requests do not explicitly overwrite the decoded request buffers. Validate and allocate a unique ID before sending secret-bearing requests; an error response is not cleanup confirmation.
Beta.15 supports these JSON-RPC method names:
workletStartgenerateEntropyAndEncryptgetMnemonicFromEntropygetSeedAndEntropyFromMnemonicinitializeWDKcallMethodcallModuleregisterWalletregisterProtocoldispose
JSON-RPC does not support resetWdkWallets in this release. It does support selective dispose through a non-empty params.blockchains array. Use HRPC resetWdkWallets() when selected wallets must be disposed and then re-registered. Generic modules require context.moduleManagers and matching runtime config.modules; initializeWDK constructs them only when the request includes the encrypted seed pair.
The transports share the wallet/protocol handler and module runtime. Both support the swidge protocol type, enforce RpcContext.allowedMethods, and enforce allowedModuleMethods for generic-module calls. JSON-RPC callModule parameters match CallModuleRequest, including its JSON-string args. Results use response.result.result; events arrive as moduleEvent notifications with params: { module, event, payload } and a decoded payload. See the JSON-RPC examples.
Beta.15 redacts named secret fields in object arguments to the package logger. It does not scrub raw strings, typed-array arguments, or formatted Error stacks. Production defaults to ERROR logging; see logging configuration and limits.
HRPC returns secret payloads as live buffers owned by the caller. JSON-RPC sends the corresponding fields as base64 strings, and React Native Core also exposes base64 strings at its public wallet-hook boundary. Overwrite mutable buffers after use, discard string references promptly, and never log either form. These steps reduce retention but cannot prove that every runtime or application copy has been erased.