Skip to content

Use discriminated unions to allow checking for tx broadcast success #1755

Open
@aryzing

Description

@aryzing

Problem

The way the types are currently constructed for TxBroadcastResult,

export type TxBroadcastResult = TxBroadcastResultOk | TxBroadcastResultRejected;

makes it "impossible" to check for success or error with TS. The union only has the txid prop common among all possible types, and therefore it's the only prop TS allows checking:

const res = broadcastTransaction(tx);

console.log(res.txid); // ok

if (res.error) {} // TS Error, prop `error` doesn't exist on all instances of TxBroadcastResult

Solution

Use discriminated unions for success vs error, and for each of the error types. Perhaps something like:

type TxBroadcastResult = // Key `"type"` is the discriminator
  | { type: "success"; txid: string }
  | { type: "error"; detail: ErrorDetail };

type ErrorDetail = // Key `"reason"` is the discriminator
  | {
      reason: "Serialization";
      txid: string;
      // other useful fields
    }
  | {
      reason: "SignatureValidation";
      txid: string;
      // other useful fields
    };
// ... other error types

Additional context

Image

Metadata

Metadata

Assignees

Labels

featureBrand new functionality. New pages, workflows, endpoints, etc.

Type

No type

Projects

Status

📋 Backlog

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions