stellar-sdk
Version:
A library for working with the Stellar network, including communication with the Horizon and Soroban RPC servers.
72 lines (71 loc) • 2.85 kB
TypeScript
/**
* A minimal implementation of Rust's `Result` type. Used for contract
* methods that return Results, to maintain their distinction from methods
* that simply either return a value or throw.
*
* **Why is this needed?**
*
* This is used by `ContractSpec` and `AssembledTransaction` when parsing
* values return by contracts.
*
* Contract methods can be implemented to return simple values, in which case
* they can also throw errors. This matches JavaScript's most idiomatic
* workflow, using `try...catch` blocks.
*
* But Rust also gives the flexibility of returning `Result` types. And Soroban
* contracts further support this with the `#[contracterror]` macro. Should
* JavaScript calls to such methods ignore all of that, and just flatten this
* extra info down to the same `try...catch` flow as other methods? We're not
* sure.
*
* For now, we've added this minimal implementation of Rust's `Result` logic,
* which exports the `Result` interface and its associated implementations,
* `Ok` and `Err`. This allows `ContractSpec` and `AssembledTransaction` to
* work together to duplicate the contract's Rust logic, always returning
* `Result` types for contract methods that are implemented to do so.
*
* In the future, if this feels too un-idiomatic for JavaScript, we can always
* remove this and flatten all JS calls to `try...catch`. Easier to remove this
* logic later than it would be to add it.
*/
export interface Result<T, E extends ErrorMessage = ErrorMessage> {
unwrap(): T;
unwrapErr(): E;
isOk(): boolean;
isErr(): boolean;
}
/**
* Error interface containing the error message. Matches Rust's implementation.
* Part of implementing {@link Result}, a minimal implementation of Rust's
* `Result` type. Used for contract methods that return Results, to maintain
* their distinction from methods that simply either return a value or throw.
*/
export interface ErrorMessage {
message: string;
}
/**
* Part of implementing {@link Result}, a minimal implementation of Rust's
* `Result` type. Used for contract methods that return Results, to maintain
* their distinction from methods that simply either return a value or throw.
*/
export declare class Ok<T> implements Result<T, never> {
readonly value: T;
constructor(value: T);
unwrapErr(): never;
unwrap(): T;
isOk(): boolean;
isErr(): boolean;
}
/**
* Part of implementing {@link Result}, a minimal implementation of Rust's
* `Result` type. Used for contract methods that return Results, to maintain
* their distinction from methods that simply either return a value or throw.
*/
export declare class Err<E extends ErrorMessage> implements Result<never, E> {
readonly error: E;
constructor(error: E);
unwrapErr(): E;
unwrap(): never;
isOk(): boolean;
isErr(): boolean;
}