Skip to main content

Streaming routes

Read streaming routes as async iterables through the DALP TypeScript SDK, with decoded events, cancellation, and error handling.

Overview

A streaming route returns a stream of server-sent events instead of one body. A deployment reports progress across several minutes, a transaction moves through states, and an activity feed has no last item, so their routes stream.

In the SDK they are ordinary nodes on the same tree. What differs is what comes back: an async iterable of frames, one decoded frame per server-sent event, instead of a promise of one payload.

for await (const frame of dalp.api.transactionsV2.statusStream({ transactionId })) {
  console.log(frame);
}

Reading a stream

Frames arrive in order and are parsed as JSON when they carry JSON.

async function watchDeployment(deploymentId: string) {
  for await (const frame of dalp.api.platform.organizations.organizationsDeployStream({ deploymentId })) {
    render(frame);
  }
  // The loop ends when the platform closes the stream.
}

When the platform ends a stream with its reserved failure event, the loop throws a DalpApiError with the code sdk.stream.FAILED and retryable true. A client whose fetch cannot expose a streamed response body throws sdk.stream.UNREADABLE_BODY instead, and that error is not retryable. React Native covers the fetch that fixes it.

When reading the body fails after the stream opened, the loop throws sdk.transport.REQUEST_FAILED with retryable true. That happens when the connection breaks, or when your own fetch aborts the body of a stream that went quiet: the SDK sets no idle timeout of its own. When you abort through the signal you passed, the loop rethrows your abort reason unchanged.

The platform logs a stream under the X-Request-Id of the request that opened it. Three errors carry that identifier in data.requestId: sdk.stream.FAILED, sdk.response.MALFORMED_SUCCESS for a frame the SDK cannot read, and sdk.transport.REQUEST_FAILED. serverReferenceOf returns it as the reference to show.

The stream object holds the same identifier as requestId once the platform responds, and undefined before that. Use it to tie your own log lines to the platform's. Show the reference that serverReferenceOf returns, which is undefined for your own abort, because the platform logged no failure for it.

import { serverReferenceOf } from "@settlemint/dalp-sdk/server-reference";

const stream = dalp.api.transactionsV2.statusStream({ transactionId });
try {
  for await (const frame of stream) {
    render(frame);
  }
} catch (error) {
  log.warn("status stream ended", { platformRequestId: stream.requestId });
  showFailure(error, serverReferenceOf(error));
}

Breaking out of the loop closes the connection. So does an early return or a thrown error inside the body, because the iterator's cleanup runs either way and cancels the underlying read. You do not need to close anything by hand.

Cancelling

Pass an AbortSignal the same way you would on any other call:

const controller = new AbortController();

for await (const frame of dalp.api.assetPortfolioV2.v2.actions.stream({}, { signal: controller.signal })) {
  render(frame);
}

In React, abort in the effect's cleanup so a component that unmounts mid-stream does not hold a connection open:

useEffect(() => {
  const controller = new AbortController();

  void (async () => {
    try {
      for await (const frame of dalp.api.assetPortfolioV2.v2.actions.stream({}, { signal: controller.signal })) {
        setLatest(frame);
      }
    } catch (error) {
      if (!controller.signal.aborted) setError(error);
    }
  })();

  return () => controller.abort();
}, []);

The aborted check matters. An aborted stream rejects with the abort reason, and treating your own cleanup as a failure is how an unmount shows an error toast.

What the SDK does not do

It does not reconnect. One call opens one connection. When the stream ends, it has ended, and if it ended before the terminal event you were waiting for, that is a fact your code sees rather than a gap it never learns about.

If the connection ends before a terminal event, read the current status before deciding whether to reconnect. A missed event does not establish the transaction outcome.

The deployment, invitation, migration and token-creation streams send a complete frame only with the run's real verdict. When the server cannot read the run's progress or no run is recorded for the id, the stream ends with its declared failure event instead. Deployment, invitation and migration streams wait up to two minutes for a run to appear before ending this way.

On that failure event, the SDK throws DalpApiError with code sdk.stream.FAILED. That error means the outcome is unknown, not that the run failed: read the status route, then reopen the stream if the run is still active.

On a settlement stream, resuming from the live edge after a disconnect could miss a COMPLETED event and stall the caller. A status stream therefore sends the current row as its first frame on every subscription instead of resuming from a cursor. Use the stream to watch progress and the status route for the verdict. Because a status stream also closes after 180 seconds while in flight, reopen it to receive the current state as the first frame.

It does not classify frames. A frame is data. Whether a given frame is terminal, and whether terminal means success, is domain knowledge the route defines and your code applies.

Reconnecting

When you want a stream that survives a dropped connection, wrap the call. The SDK ships the wrapper the Console uses:

import { consumeSseUntilTerminal, SseLifecycleError } from "@settlemint/dalp-sdk";

const outcome = await consumeSseUntilTerminal({
  connect: async (signal) => ({
    stream: dalp.api.transactionsV2.statusStream({ transactionId }, { signal }),
  }),
  classify: (frame) => {
    if (frame.family !== "evm") {
      if (frame.submissionStatus === "settled") return "success";
      return frame.submissionStatus === "failed" || frame.submissionStatus === "expired" ? "failure" : "continue";
    }
    if (frame.status === "COMPLETED") return "success";
    // A dead letter that may still land is not an answer yet: keep following it.
    if (frame.status === "DEAD_LETTER" && frame.mayStillLand === true) return "continue";
    if (frame.status === "FAILED" || frame.status === "DEAD_LETTER" || frame.status === "CANCELLED") {
      return "failure";
    }
    return "continue";
  },
  signal: outerSignal,
});

It reconnects with backoff while frames are non-terminal, stops on the verdict classify returns, and throws SseLifecycleError when it gives up, with a reason distinguishing an abort from a terminal failure from a transport failure. The SseLifecycleError carries requestId, the X-Request-Id of the last attempt the platform responded to. When the stream closed again and again before its verdict, that identifier still points to a request the platform logged. It is undefined when no attempt got a response, or when the stream your connect returns does not expose requestId, as a stream you wrap yourself may not.

The reconnect budget is a wall-clock window rather than an attempt count, so fast failures do not exhaust the budget while a backend is recovering. The default window is 60 seconds, anchored at the first failure of a run and reset only after a connection stays up for 20 seconds.

The delay between attempts starts at 250 milliseconds, doubles on each retry, and caps at 5 seconds. Pass reconnectWindowMs, healthyConnectionMs, initialBackoffMs, and maxBackoffMs to tune these defaults, or maxReconnects to replace the window with a fixed attempt count. A long-lived stream that drops hours later still receives a full reconnect window.

Receiving events does not count as recovery, because a stream that replays its opening frame on every subscription would then clear the failure streak on each attempt and reconnect forever.

Which routes stream

A streaming route is typed as returning an async iterable, so awaiting one as a body is a type error. Streams exist for organisation and invitation deployment progress, migration progress, transaction status, the action inbox, API request logs, chain-health snapshots, token creation, the trading venue's market and operator order feeds, and custody account-request lifecycle.

The full list, with each route's frames, is in the API reference, where every streaming route is documented beside the routes that return a body.

Block progress and changed addresses

dalp.api.opsChainHealth.blockProgress, the GET /api/v2/events/block-progress route, sends one frame each time the index records a new block on a network. Any signed-in caller can open it. Each frame carries chainId and blockNumber, and usually changedAddresses, the addresses whose indexed records that block changed. Use the list to refresh only the reads that name one of those addresses.

The stream lists only the addresses the caller may read:

  • A platform administrator receives every address the block changed.
  • An organisation owner receives the addresses of the organisation's system contracts and tokens, its members' wallets, and the caller's own wallets.
  • Any other member receives the system address, the system's tokens and the caller's own wallets.
  • A caller with no active organisation receives only its own wallets.

Any caller other than a platform administrator never receives another organisation's addresses, and among those callers only an organisation owner receives other holders' wallets. When a block changes nothing the caller may read, the frame still arrives with an empty changedAddresses list so the block number keeps advancing and the client can skip targeted refreshes.

A frame without changedAddresses names no addresses at all: this happens on the initial frame per network when the stream opens (repeating the last indexed block) or when a block changed too many addresses to list. Refresh every read on that network when changedAddresses is absent. The chain-health snapshot stream (opsChainHealth.snapshotStream) filters its block-progress frames the same way.

Funding requirement roles in stream frames

The deployment, invitation, migration and token-creation streams can carry a funding requirement: a wallet that needs gas before the work can go on. A frame with type set to requirement-required carries a role at frame.payload.role. The role is the funding purpose of the requirement. The wallet that is short is frame.payload.address. Several requirements can share one role, so do not key requirements by role alone. A requirement-resolved frame has no role, so narrow on frame.type === "requirement-required" before you read frame.payload.role.

The stream sends a requirement-required frame again, under the same requirementId, when the requirement's amounts change or when the balance the wallet already holds, frame.payload.alreadySent, changes. Replace the requirement you hold with the newer frame.

The set of roles can grow, and the published API document lists the roles as a closed enum. The SDK checks every stream frame against that enum. A frame with a role that your SDK version does not know throws sdk.response.MALFORMED_SUCCESS before your loop sees the frame. The route methods of the SDK have no option to skip this check. You have two ways to handle a new role:

  • Upgrade the SDK when a new role ships. Each SDK release is built from the API document of that release.
  • Call the stream route yourself with an HTTP client. Send the same URL, credentials, and Accept: text/event-stream header that the SDK sends, then pass the response body (a ReadableStream<Uint8Array>) to decodeEventStream without a frame decoder. It parses each frame as JSON and does not check the enum. You handle request errors yourself on this path.

If you decode frames without the enum check, handle an unknown role like this:

  • Read role as a string.
  • Use the known values only to choose a label.
  • Show an unknown role as a generic funding requirement. Never drop the row. A wallet that is short is still short, and the operator needs to see it.
Role
Funding purpose
org-creator-eoa
Organisation creator wallet
member-admission-eoa
Wallet of the member being admitted
token-creator-eoa
Token creator wallet
org-vault-eoa
Organisation vault wallet
org-bundler-eoa
Bundler wallet that submits account abstraction operations
org-relayer-eoa
Relayer wallet
aa-runway-eoa
Account abstraction runway wallet
queued-write-eoa
Wallet that signs a queued write
smart-account
Smart wallet that needs a prefund
paymaster-deposit
Paymaster deposit at the EntryPoint

The funding requirements list route, GET /api/v2/organizations/funding-requirements, publishes role as a nullable open string. A stored requirement with no known role carries null, so treat null like an unknown role: show it as a generic funding requirement.

Next

Wiring calls into a React application: TanStack Query.

Was this page helpful?