Rpc
sync.rpc is request/response messaging between transport nodes. A request sends a req envelope and returns a promise; the matching res envelope resolves or rejects it.
Because responses are just more script events, every request carries a tick-based timeout, so a peer that never answers (or was never there) can never leak a pending promise or hang your code.
Import
import type { RequestHandler, RequestOptions, RpcOptions, TypedClient, RPCHandlerMap } from '@bedrock-core/sync';
TypedClient and RPCHandlerMap belong to the standalone Sync transport package.
Usage
// Expose a method
sync.rpc.onRequest('getBalance', (params, from) => {
const { player } = params as { player: string };
return lookupBalance(player);
});
// Call another addon — the target is its namespace
const balance = await sync.rpc.request('drav0011_economy', 'getBalance', { player: 'Steve' });
Serving
onRequest
onRequest(method: string, handler: RequestHandler): Unsubscribe
type RequestHandler = (params: unknown, from: string) => unknown | Promise<unknown>;
Register the handler for one method name. from is the requester's addon id. The handler may be async; whatever it returns (or resolves with) becomes the response. Registering the same method again replaces the previous handler.
The unsubscribe function removes the method only while that handler function remains installed. Disposing an older handler does not remove a replacement installed with a different function.
Throwing inside a handler rejects the caller's promise with your error message — which is the right way to refuse a request, because the caller learns why instead of watching it time out.
sync.rpc.onRequest('buy', (params, from) => {
const { itemId } = params as { itemId: string };
if (!isSellable(itemId)) { throw new Error(`'${itemId}' is not for sale`); }
return purchase(itemId, from);
});
An unknown method is answered automatically with unknown method '<name>' — the caller rejects rather than waiting for the timeout.
serve
serve<T>(handlers: RPCHandlerMap<T>): Unsubscribe
Register a whole typed handler map at once. Each key is type-checked against the interface, and the single returned function removes every handler.
export interface EconomyRPC {
getBalance(params: { player: string }): number;
transfer(params: { from: string; to: string; amount: number }): boolean;
}
sync.rpc.serve<EconomyRPC>({
getBalance: ({ player }) => balances.get(player) ?? 0,
transfer: ({ from, to, amount }) => moveFunds(from, to, amount),
});
RPCHandlerMap<T> maps each (params: P) => R in the interface to (params: P, from: string) => R | Promise<Awaited<R>>, so handlers get typed params and may still be async.
Calling
request
request(dst: string, method: string, params?: unknown, options?: RequestOptions): Promise<unknown>
interface RequestOptions { timeoutTicks?: number; instanceId?: string }
Call method on addon dst. Resolves with its response, or rejects on a handler error or a timeout. instanceId restricts accepted replies to that running instance; replies from another addon are ignored. Core API bindings supply the current instance automatically:
RPC 'getBalance' to 'drav0011_economy' timed out
The default timeout is 100 ticks (5 seconds at 20 tps). Raise it per call for something genuinely slow:
await sync.rpc.request('drav0011_economy', 'rebuildIndex', {}, { timeoutTicks: 400 });
RpcOptions.defaultTimeoutTicks changes the default when constructing an Rpc yourself. The read-only sync.rpc.defaultTimeoutTicks property exposes that configured lifetime, allowing resources owned by a call to use the same deadline.
Parameters and results follow the structured data contract. Encoding unsupported parameters, or sending structured parameters to a known legacy peer, can throw before request() returns its promise. A handler result that cannot be encoded is converted into an RPC error reply.
Replies must have a matching request id and sender, plus the requested instanceId when supplied. Malformed error fields and mismatched replies are ignored without settling the request or cancelling its timeout.
typed
typed<T>(targetId: string): TypedClient<T>
A Proxy-backed client whose methods dispatch to request(targetId, methodName, params). This is the ergonomic way to call a peer whose interface you have.
const economy = sync.rpc.typed<EconomyRPC>('drav0011_economy');
const balance = await economy.getBalance({ player: 'Steve' }); // Promise<number>
TypedClient<T> maps each (params: P) => R to (params: P) => Promise<Awaited<R>>.
Use public addon API exports for normal typed imports from peer packages. Builder supplies the RPC bindings. Direct typed<T>() and serve<T>() remain useful for dynamic targets and explicitly named endpoints; share their interface through a type export. TypeScript checks parameters and results at compile time; providers remain responsible for validating incoming data and authorization.
Calling yourself
A node may call itself:
await sync.rpc.request(sync.id, 'getBalance', { player: 'Steve' });
Self-addressed messages are delivered locally on the next tick rather than going over the wire, so the timing is the same as a real hop. That keeps one "always go through RPC" model even when the target turns out to be the caller.
Patterns
Never assume the peer is there
if (sync.discovery.getPeer('peer_namespace') !== undefined) {
sync.rpc.request('peer_namespace', 'getBalance', { player: player.id })
.catch((error: unknown) => console.warn(String(error)));
}
Always handle rejection
Every request can reject — timeout, unknown method, or a handler that threw. An unhandled rejection in a Bedrock script realm is noisy and easy to miss, so attach a .catch (or wrap in try/catch) at every call site.
Namespace your method names
Method names are per-node. A prefix such as myaddon:getBalance keeps application endpoints distinct from library endpoints installed on the same node.
Lifecycle
rpc.start() installs request/response handlers; rpc.stop() releases them and rejects pending requests with RPC stopped. SyncNode.start() and SyncNode.stop() own this lifecycle. Discovery departure or replacement also rejects pending calls to that running instance. Synchronous throws, rejected promises and unsupported return data use the same RPC error reply.
Request timers are cleared when a valid reply settles the request, the target departs or RPC stops. Served method registrations are retained across an RPC stop/start; their unsubscribe functions remain owned by the caller.