aftermath-ts-sdk
Version:
Aftermath TypeScript SDK
407 lines • 18 kB
TypeScript
import { DisplayFieldsResponse, SuiObjectResponse } from "@mysten/sui/client";
import { AnyObjectType, Balance, ObjectId, Slippage, ModuleName, MoveErrorCode, SuiAddress, CoinType, CoinGeckoChain } from "../../types";
import { DynamicFieldsApiHelpers } from "../apiHelpers/dynamicFieldsApiHelpers";
import { EventsApiHelpers } from "../apiHelpers/eventsApiHelpers";
import { InspectionsApiHelpers } from "../apiHelpers/inspectionsApiHelpers";
import { ObjectsApiHelpers } from "../apiHelpers/objectsApiHelpers";
import { TransactionsApiHelpers } from "../apiHelpers/transactionsApiHelpers";
import { Transaction, TransactionObjectArgument } from "@mysten/sui/transactions";
import { MoveErrors } from "../types/moveErrorsInterface";
import { Keypair } from "@mysten/sui/cryptography";
/**
* A utility class containing various helper functions for general use across
* the Aftermath TS ecosystem. This includes numeric operations, object field
* extraction, array transformations, slippage adjustments, and Move error parsing.
*/
export declare class Helpers {
/**
* Static reference to the `DynamicFieldsApiHelpers`, providing utility methods
* for working with dynamic fields in Sui objects.
*/
static readonly dynamicFields: typeof DynamicFieldsApiHelpers;
/**
* Static reference to the `EventsApiHelpers`, providing methods for
* querying and filtering Sui events.
*/
static readonly events: typeof EventsApiHelpers;
/**
* Static reference to the `InspectionsApiHelpers`, used for reading
* Summaries or inspection data from objects.
*/
static readonly inspections: typeof InspectionsApiHelpers;
/**
* Static reference to the `ObjectsApiHelpers`, providing direct
* retrieval or manipulation of on-chain Sui objects.
*/
static readonly objects: typeof ObjectsApiHelpers;
/**
* Static reference to the `TransactionsApiHelpers`, enabling easier
* queries for transaction data by digest or other criteria.
*/
static readonly transactions: typeof TransactionsApiHelpers;
/**
* Removes all leading zeroes (after the '0x') from a string that represents
* a Sui address or object type. For instance, "0x0000123" => "0x123".
*
* @param type - The hex string to process, potentially including "::" module syntax.
* @returns The same string with unnecessary leading zeroes stripped out.
*/
static stripLeadingZeroesFromType: (type: AnyObjectType) => AnyObjectType;
/**
* Ensures the given Sui address or object type is zero-padded to 64 hex digits
* after the "0x". If a "::" suffix is present, only the address portion is padded.
*
* @param type - The "0x..." string or extended type (0x..::module).
* @returns A new string normalized to a 64-hex-digit address or object ID.
* @throws If the address portion is already longer than 64 hex digits.
*/
static addLeadingZeroesToType: (type: AnyObjectType) => AnyObjectType;
/**
* Splits a non-SUI coin type string that may be prefixed by a chain ID for external usage,
* returning the chain and the coin type. If no chain is recognized, defaults to `"sui"`.
*
* @param coin - The coin string, which may look like `"bsc:0x<...>"` or just `"0x<...>"`.
* @returns An object with the `chain` (e.g. "bsc") and the `coinType`.
*/
static splitNonSuiCoinType: (coin: CoinType) => {
chain: CoinGeckoChain;
coinType: CoinType;
};
/**
* Checks if a given string represents a valid number (integer or decimal).
*
* @param str - The string to test.
* @returns `true` if it's a valid numeric string, otherwise `false`.
*/
static isNumber: (str: string) => boolean;
/**
* Sums an array of floating-point numbers, returning the numeric total.
*
* @param arr - The array of numbers to sum.
* @returns The total as a float.
*/
static sum: (arr: number[]) => number;
/**
* Sums an array of bigints, returning the total as a bigint.
*
* @param arr - The array of bigints to sum.
* @returns The resulting total as a bigint.
*/
static sumBigInt: (arr: bigint[]) => bigint;
/**
* Determines if two numbers are close within a given tolerance factor,
* i.e., `|a - b| <= tolerance * max(a, b)`.
*
* @param a - The first number.
* @param b - The second number.
* @param tolerance - A fraction representing the max allowed difference relative to max(a, b).
* @returns `true` if within tolerance, otherwise `false`.
*/
static closeEnough: (a: number, b: number, tolerance: number) => boolean;
/**
* Determines if two bigints are close within a given tolerance factor,
* by casting them to numbers internally.
*
* @param a - First bigint.
* @param b - Second bigint.
* @param tolerance - A fraction representing the max allowed difference relative to max(a, b).
* @returns `true` if within tolerance, otherwise `false`.
*/
static closeEnoughBigInt: (a: bigint, b: bigint, tolerance: number) => boolean;
/**
* Checks whether the integer divisions of `a` and `b` (by `fixedOne`) differ
* by at most 1. Typically used in fixed math scenarios to see if two scaled
* values are "very close."
*
* @param a - First number (scaled).
* @param b - Second number (scaled).
* @param fixedOne - The scaling factor representing 1.0 in the same scale as `a` and `b`.
* @returns `true` if the integer parts differ by <= 1, otherwise `false`.
*/
static veryCloseInt: (a: number, b: number, fixedOne: number) => boolean;
/**
* A small object containing "blended" math operations that handle
* mixed numeric types (number vs. bigint). This is primarily for
* internal usage in advanced math scenarios.
*/
static blendedOperations: {
/**
* Multiply two floating-point numbers.
*/
mulNNN: (a: number, b: number) => number;
/**
* Multiply a float and a bigint, returning a bigint (floor).
*/
mulNNB: (a: number, b: number) => bigint;
/**
* Multiply a float and a bigint, returning a float.
*/
mulNBN: (a: number, b: bigint) => number;
/**
* Multiply a float and a bigint, returning a bigint (floor).
*/
mulNBB: (a: number, b: bigint) => bigint;
/**
* Multiply two bigints, returning a float.
*/
mulBBN: (a: bigint, b: bigint) => number;
/**
* Multiply two bigints, returning a bigint.
*/
mulBBB: (a: bigint, b: bigint) => bigint;
};
/**
* Returns the maximum of multiple bigints.
*
* @param args - The bigints to compare.
* @returns The largest bigint.
*/
static maxBigInt: (...args: bigint[]) => bigint;
/**
* Returns the minimum of multiple bigints.
*
* @param args - The bigints to compare.
* @returns The smallest bigint.
*/
static minBigInt: (...args: bigint[]) => bigint;
/**
* Returns the absolute value of a bigint.
*
* @param num - The input bigint.
* @returns A bigint representing the absolute value of `num`.
*/
static absBigInt: (num: bigint) => bigint;
/**
* Capitalizes only the first letter of a string, making the rest lowercase.
* E.g., "HELLO" => "Hello".
*
* @param str - The input string to transform.
* @returns The resulting string with the first character in uppercase and the rest in lowercase.
*/
static capitalizeOnlyFirstLetter: (str: string) => string;
/**
* Parses a JSON string containing potential BigInt values.
* By default, it only converts strings ending in 'n' (like `"123n"`) to BigInts.
*
* @param json - The JSON string to parse.
* @param unsafeStringNumberConversion - If `true`, all numeric strings (e.g., "123") will also become BigInts.
* @returns The parsed JSON object with BigInt conversions where applicable.
*/
static parseJsonWithBigint: (json: string, unsafeStringNumberConversion?: boolean) => any;
/**
* Creates a deep copy of the given target, handling nested arrays and objects.
* Dates are cloned by their timestamp.
*
* @param target - The data to clone deeply.
* @returns A new object/array/date structure mirroring `target`.
*/
static deepCopy: <T>(target: T) => T;
/**
* Finds the index of the maximum value in an array. Returns -1 if the array is empty.
*
* @param arr - The input array.
* @returns The index of the maximum value, or -1 if the array is empty.
*/
static indexOfMax: (arr: any[]) => number;
/**
* Returns a new array with unique elements from the input array,
* preserving the order of first occurrences.
*
* @param arr - The original array.
* @returns An array of unique items.
*/
static uniqueArray: <T>(arr: T[]) => T[];
/**
* Returns a Promise that resolves after a specified number of milliseconds.
*
* @param ms - The delay time in milliseconds.
* @returns A promise that resolves after `ms` milliseconds.
*/
static sleep: (ms: number) => Promise<unknown>;
/**
* Creates a unique ID-like string by combining the current timestamp and random base36 digits.
*
* @returns A short random string (base36) that can serve as a unique identifier.
*/
static createUid: () => string;
/**
* Splits an array into two groups: those for which `func` returns `true` (or truthy),
* and those for which it returns `false`. The result is returned as a tuple `[trues, falses]`.
*
* @param array - The array to filter.
* @param func - The function used to test each element.
* @returns A tuple containing two arrays: `[elements that pass, elements that fail]`.
*/
static bifilter: <ArrayType>(array: ArrayType[], func: (item: ArrayType, index: number, arr: ArrayType[]) => boolean) => [trues: ArrayType[], falses: ArrayType[]];
/**
* An async version of `bifilter`, returning a tuple of `[trues, falses]`.
* Each element is tested asynchronously in parallel via `func`.
*
* @param array - The array to filter.
* @param func - An async function returning `true` or `false`.
* @returns A tuple `[trues, falses]` after asynchronous evaluation.
*/
static bifilterAsync: <ArrayType>(array: ArrayType[], func: (item: ArrayType, index: number, arr: ArrayType[]) => Promise<boolean>) => Promise<[trues: ArrayType[], falses: ArrayType[]]>;
/**
* Filters the entries of an object based on a predicate function,
* returning a new object with only those entries for which `predicate`
* returns `true`.
*
* @param obj - The original object to filter.
* @param predicate - A function taking `(key, value)` and returning a boolean.
* @returns A new object with only the entries that pass the predicate.
*/
static filterObject: <Value>(obj: Record<string, Value>, predicate: (key: string, value: Value) => boolean) => Record<string, Value>;
/**
* Applies downward slippage to a bigint amount by subtracting `slippage * amount`.
* For instance, for 1% slippage, we reduce the amount by 1%.
*
* @param amount - The original bigint amount.
* @param slippage - An integer percent (e.g., 1 => 1%).
* @returns The adjusted bigint after subtracting the slippage portion.
*/
static applySlippageBigInt: (amount: Balance, slippage: Slippage) => bigint;
/**
* Applies downward slippage to a floating-point amount. E.g., for 1% slippage,
* reduce by 1% of `amount`.
*
* @param amount - The original float value.
* @param slippage - An integer percent (e.g., 1 => 1%).
* @returns The float after applying slippage.
*/
static applySlippage: (amount: number, slippage: Slippage) => number;
/**
* Combines two arrays into a single array of pairs. The result length is the
* minimum of the two input arrays' lengths.
*
* @param firstCollection - The first array.
* @param lastCollection - The second array.
* @returns An array of `[firstCollection[i], lastCollection[i]]` pairs.
*/
static zip<S1, S2>(firstCollection: Array<S1>, lastCollection: Array<S2>): Array<[S1, S2]>;
/**
* Removes circular references from an object or array, returning a JSON-safe structure.
* Any cyclic references are replaced with `undefined`.
*
* @param obj - The object or array to remove circular references from.
* @param seen - Internal usage to track references that have already been visited.
* @returns A structure that can be safely JSON-stringified.
*/
static removeCircularReferences<T>(obj: T, seen?: WeakSet<object>): T | undefined;
/**
* Checks if an unknown value is an array of strings.
*
* @param value - The value to check.
* @returns `true` if `value` is a string array, otherwise `false`.
*/
static isArrayOfStrings(value: unknown): value is string[];
/**
* Roughly checks if a string is a valid Sui type (e.g., "0x2::sui::SUI").
* This is not guaranteed to be perfect, but covers common cases.
*
* @param str - The string to validate.
* @returns `true` if it meets the minimum structure, otherwise `false`.
*/
static isValidType: (str: string) => boolean;
/**
* Checks if a string is a valid hex representation, optionally prefixed with "0x".
*
* @param hexString - The string to check.
* @returns `true` if `hexString` is a valid hex, otherwise `false`.
*/
static isValidHex: (hexString: string) => boolean;
/**
* Extracts the fully qualified type (e.g., "0x2::coin::Coin<...>") from a `SuiObjectResponse`,
* normalizing it with leading zeroes if necessary.
*
* @param data - The object response from Sui.
* @returns The normalized object type string.
* @throws If the type is not found.
*/
static getObjectType(data: SuiObjectResponse): ObjectId;
/**
* Extracts the object ID from a `SuiObjectResponse`, normalizing it with leading zeroes.
*
* @param data - The object response from Sui.
* @returns A zero-padded `ObjectId`.
* @throws If the objectId is not found.
*/
static getObjectId(data: SuiObjectResponse): ObjectId;
/**
* Retrieves the fields of a Move object from a `SuiObjectResponse`.
*
* @param data - The Sui object response containing a Move object.
* @returns A record of fields for that object.
* @throws If no fields are found.
*/
static getObjectFields(data: SuiObjectResponse): Record<string, any>;
/**
* Retrieves display metadata from a Sui object response, if present.
*
* @param data - The Sui object response.
* @returns The display fields for that object.
* @throws If display fields are not found.
*/
static getObjectDisplay(data: SuiObjectResponse): DisplayFieldsResponse;
/**
* Utility for building transaction commands with either a string-based
* `ObjectId` or an existing transaction object argument. If it's a string,
* it's converted via `tx.object(...)`; if already a `TransactionObjectArgument`,
* it's returned as-is.
*
* @param tx - The current `Transaction` block to add the object to.
* @param object - Either an `ObjectId` or a `TransactionObjectArgument`.
* @returns A `TransactionObjectArgument` referencing the provided object.
*/
static addTxObject: (tx: Transaction, object: ObjectId | TransactionObjectArgument) => TransactionObjectArgument;
/**
* Checks if a given string is a valid Sui address by normalizing it to a
* 64-hex-digit form and calling `isValidSuiAddress`.
*
* @param address - The Sui address to validate.
* @returns `true` if valid, `false` otherwise.
*/
static isValidSuiAddress: (address: SuiAddress) => boolean;
/**
* Parses a MoveAbort error message from Sui into a possible `(errorCode, packageId, module)`,
* if the message follows a known pattern. Otherwise returns undefined.
*
* @param inputs - The object containing the raw `errorMessage` from Sui.
* @returns A partial structure of the error details or undefined.
*/
static parseMoveErrorMessage(inputs: {
errorMessage: string;
}): {
errorCode: MoveErrorCode;
packageId: ObjectId;
module: ModuleName;
} | undefined;
/**
* Translates a Move abort error message into a known error string if it matches
* entries in a given `moveErrors` table. This is used to map on-chain error codes
* to user-friendly messages.
*
* @param inputs - Includes the raw `errorMessage` and a `moveErrors` object keyed by package, module, and code.
* @returns A structure with `errorCode`, `packageId`, `module`, and a human-readable `error` string, or `undefined`.
*/
static translateMoveErrorMessage(inputs: {
errorMessage: string;
moveErrors: MoveErrors;
}): {
errorCode: MoveErrorCode;
packageId: ObjectId;
module: ModuleName;
error: string;
} | undefined;
/**
* Constructs a `Keypair` instance from a private key string. The `privateKey`
* may indicate the signing scheme (ED25519, Secp256k1, or Secp256r1) via prefix,
* as recognized by `decodeSuiPrivateKey`.
*
* @param privateKey - The full private key string (e.g., "0x<64_hex_chars>").
* @returns A new `Keypair` instance for signing transactions.
* @throws If the schema is unsupported.
*/
static keypairFromPrivateKey: (privateKey: string) => Keypair;
}
//# sourceMappingURL=helpers.d.ts.map