UNPKG

aftermath-ts-sdk

Version:
275 lines (274 loc) 11.3 kB
"use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.Casting = void 0; const bcs_1 = require("@mysten/sui/bcs"); const suiFrensApiCasting_1 = require("../../packages/suiFrens/api/suiFrensApiCasting"); const faucetApiCasting_1 = require("../../packages/faucet/api/faucetApiCasting"); const nftAmmApiCasting_1 = require("../../packages/nftAmm/api/nftAmmApiCasting"); const poolsApiCasting_1 = require("../../packages/pools/api/poolsApiCasting"); const stakingApiCasting_1 = require("../../packages/staking/api/stakingApiCasting"); const routerApiCasting_1 = require("../../packages/router/api/routerApiCasting"); const fixedUtils_1 = require("./fixedUtils"); const iFixedUtils_1 = require("./iFixedUtils"); const perpetualsApiCasting_1 = require("../../packages/perpetuals/api/perpetualsApiCasting"); const farmsApiCasting_1 = require("../../packages/farms/api/farmsApiCasting"); const leveragedStakingApiCasting_1 = require("../../packages/leveragedStaking/api/leveragedStakingApiCasting"); const __1 = require("../.."); const nftsApiCasting_1 = require("../nfts/nftsApiCasting"); const oracleApiCasting_1 = require("../../packages/oracle/api/oracleApiCasting"); /** * A central utility class for casting and conversion routines across * different Aftermath modules. Provides both direct numeric transformations * (e.g., fixed-point arithmetic) and advanced BCS-based object deserialization. */ class Casting { // ========================================================================= // Percentage <-> Bps // ========================================================================= /** * Converts a decimal percentage into basis points (bps), returned as a bigint. * For example, 0.05 => 500 bps. * * @param percentage - The decimal percentage to convert (e.g., 0.05 for 5%). * @returns A bigint representing basis points. */ static percentageToBps(percentage) { // Convert decimal percentage to basis points const bps = percentage * 10000; // Convert basis points to bigint return BigInt(Math.round(bps)); } /** * Converts a bigint basis points value back to a decimal percentage. * For example, 500n => 0.05 (5%). * * @param bps - The bigint basis points to convert (e.g., 500n). * @returns The decimal percentage (0.05). */ static bpsToPercentage(bps) { // Convert bigint basis points to number const bpsNumber = Number(bps); // Convert basis points to decimal percentage const percentage = bpsNumber / 10000; return percentage; } /** * Extracts base64 BCS bytes from a `SuiObjectResponse` if present. Throws an error otherwise. * * @param suiObjectResponse - The Sui object response containing `bcsBytes`. * @returns A base64 string representing the object's BCS data. * @throws If the object response does not contain `bcsBytes`. */ static bcsBytesFromSuiObjectResponse(suiObjectResponse) { var _b, _c; const rawData = (_b = suiObjectResponse.data) === null || _b === void 0 ? void 0 : _b.bcs; if (rawData && "bcsBytes" in rawData) return rawData.bcsBytes; throw new Error(`no bcs bytes found on object: ${(_c = suiObjectResponse.data) === null || _c === void 0 ? void 0 : _c.objectId}`); } } exports.Casting = Casting; _a = Casting; // ========================================================================= // Api Casting // ========================================================================= /** * Casting utilities for pools-related data (AMM pools, liquidity, etc.). */ Casting.pools = poolsApiCasting_1.PoolsApiCasting; /** * Casting utilities for SuiFrens-related data or objects. */ Casting.suiFrens = suiFrensApiCasting_1.SuiFrensApiCasting; /** * Casting utilities for faucet-related data, typically for devnet or testnet tokens. */ Casting.faucet = faucetApiCasting_1.FaucetApiCasting; /** * Casting utilities for staking-related data (positions, pools, etc.). */ Casting.staking = stakingApiCasting_1.StakingApiCasting; /** * Casting utilities for leveraged staking data structures. */ Casting.leveragedStaking = leveragedStakingApiCasting_1.LeveragedStakingApiCasting; /** * Casting utilities for NFT AMM objects and events. */ Casting.nftAmm = nftAmmApiCasting_1.NftAmmApiCasting; /** * Casting utilities for router-based data, such as trade routes and DEX interactions. */ Casting.router = routerApiCasting_1.RouterApiCasting; /** * Casting utilities for perpetuals/futures data. */ Casting.perpetuals = perpetualsApiCasting_1.PerpetualsApiCasting; /** * Casting utilities for oracle-based data or price feed objects. */ Casting.oracle = oracleApiCasting_1.OracleApiCasting; /** * Casting utilities for farming data (yield farms, locked positions, etc.). */ Casting.farms = farmsApiCasting_1.FarmsApiCasting; /** * Casting utilities for NFT structures and data retrieval logic. */ Casting.nfts = nftsApiCasting_1.NftsApiCasting; // ========================================================================= // Constants // ========================================================================= /** * Reference to the standard fixed-point arithmetic utilities (18 decimals). */ Casting.Fixed = fixedUtils_1.FixedUtils; /** * Reference to the intermediate fixed type (signed 18 decimals). */ Casting.IFixed = iFixedUtils_1.IFixedUtils; /** * The maximum unsigned 64-bit integer value as a bigint (0xFFFFFFFFFFFFFFFF). */ Casting.u64MaxBigInt = BigInt("0xFFFFFFFFFFFFFFFF"); // ========================================================================= // Functions // ========================================================================= // ========================================================================= // Fixed / IFixed // ========================================================================= /** * Converts a floating-point number to a fixed bigint with 18 decimals. * For example, `1.23` => `1230000000000000000n` if we consider 18 decimals. * * @param a - The number to convert. * @returns A bigint representing the number in 18-decimal fixed format. */ Casting.numberToFixedBigInt = (a) => BigInt(Math.floor(a * _a.Fixed.fixedOneN)); /** * Converts an 18-decimal fixed bigint to a floating-point number. * For example, `1230000000000000000n` => `1.23`. * * @param a - The fixed bigint to convert. * @returns A floating-point representation of the 18-decimal fixed value. */ Casting.bigIntToFixedNumber = (a) => Number(a) / _a.Fixed.fixedOneN; /** * Scales a bigint by a floating-point scalar. For instance, a scalar of 0.5 * and a bigint of 100 => 50n. * * @param scalar - The floating-point multiplier (e.g., 0.5). * @param int - The bigint to be scaled. * @returns A bigint result after scaling. */ Casting.scaleNumberByBigInt = (scalar, int) => BigInt(Math.floor(scalar * Number(int))); // ========================================================================= // Bytes / BCS // ========================================================================= /** * Converts an array of bytes into a string by interpreting each byte as a character code. * * @param bytes - An array of bytes to convert. * @returns The resulting ASCII string. */ Casting.stringFromBytes = (bytes) => String.fromCharCode.apply(null, bytes); /** * Interprets an array of bytes as a little-endian hex string, converting * that string into a bigint. For example, `[0x01, 0x02]` => `0x0201` => `513n`. * * @param bytes - An array of bytes. * @returns The resulting bigint from the hex. */ Casting.bigIntFromBytes = (bytes) => BigInt("0x" + bytes .reverse() .map((byte) => byte.toString(16).padStart(2, "0")) .join("")); /** * Converts BCS-encoded address bytes into a SuiAddress (0x...) string, * preserving any needed leading zeroes. * * @param bytes - The address bytes in BCS-encoded form. * @returns A normalized Sui address string (e.g., "0x000123..."). */ Casting.addressFromBcsBytes = (bytes) => __1.Helpers.addLeadingZeroesToType(bcs_1.bcs.Address.parse(new Uint8Array(bytes))); /** * Converts an array of bytes directly to a Sui address string in "0x..." format, * adding any leading zeros if needed. * * @param bytes - The raw bytes for the address. * @returns A normalized Sui address. */ Casting.addressFromBytes = (bytes) => __1.Helpers.addLeadingZeroesToType("0x" + bytes .map((byte) => { const hex = byte.toString(16); return hex.length === 1 ? "0" + hex : hex; }) .join("")); /** * Converts an array of hex string bytes into a Sui address. Each element of * the array is a string representing a byte (e.g., `["255", "0", ...]`). * * @param bytes - An array of stringified bytes to convert. * @returns A normalized Sui address. */ Casting.addressFromStringBytes = (bytes) => _a.addressFromBytes(_a.bytesFromStringBytes(bytes)); /** * Converts an array of decimal-encoded string bytes (e.g., `["255", "0"]`) * into a numeric `Byte[]` array. * * @param bytes - The string array representing decimal values. * @returns A numeric array of bytes. */ Casting.bytesFromStringBytes = (bytes) => bytes.map((byte) => Number(byte)); /** * Unwraps a deserialized "Option" type from the BCS, returning its contents * if present, or `undefined` if not. * * @param deserializedData - The BCS-deserialized structure that might contain `{ Some: value }` or `{ None: true }`. * @returns The unwrapped data if present, or `undefined`. */ Casting.unwrapDeserializedOption = (deserializedData) => { return "Some" in deserializedData ? deserializedData.Some : undefined; }; /** * Encodes a JavaScript string into a UTF-8 `Uint8Array`, suitable for * on-chain usage or hashing. * * @param str - The string to encode. * @returns An array of numeric bytes representing the UTF-8 encoded string. */ Casting.u8VectorFromString = (str) => { const textEncode = new TextEncoder(); const encodedStr = textEncode.encode(str); const uint8s = []; for (const uint8 of encodedStr.values()) { uint8s.push(uint8); } return uint8s; }; /** * Normalizes a user-provided slippage tolerance from an integer percentage * into a decimal fraction. E.g., `1 => 0.01`. * * @param slippageTolerance - The slippage in integer percent form (e.g., 1 for 1%). * @returns A decimal fraction (e.g., 0.01). */ Casting.normalizeSlippageTolerance = (slippageTolerance) => { return slippageTolerance / 100; }; /** * Deserializes a `SuiObjectResponse`'s BCS bytes into an object of type `T` using * a specified `bcsType`. Typically used for on-chain object decoding. * * @param inputs - The inputs including `suiObjectResponse`, `bcsType`, and a `fromDeserialized` transform function. * @returns The transformed object of type `T` after BCS deserialization. * @throws If no BCS bytes are found in the object. */ Casting.castObjectBcs = (inputs) => { const { suiObjectResponse, bcsType, fromDeserialized } = inputs; const deserialized = bcsType.fromBase64(_a.bcsBytesFromSuiObjectResponse(suiObjectResponse)); return fromDeserialized(deserialized); };