API Reference
This is a comprehensive reference for all utility functions available in the @ocap/util package. It provides practical examples for data conversion, big number arithmetic, UUID generation, and bonding curve calculations.
Number & BigNumber Utilities#
These functions provide robust ways to handle large numbers and perform conversions between different numerical representations.
BN#
An alias for the bn.js library, used for handling arbitrary-precision integers. All functions that work with large numbers either accept or return BN instances.
Bignumber Arithmetic
import { BN } from '@ocap/util';
const a = new BN('1000000000000000000');
const b = new BN('2000000000000000000');
const result = a.add(b);
console.log(result.toString()); // '3000000000000000000'toBN#
Converts various input types into a BN instance. It can handle numbers, strings, and hexadecimal strings.
Parameters
Returns
Example
Converting to BN
import { toBN } from '@ocap/util';
// From number
console.log(toBN(15).toString(10)); // '15'
// From hex string
console.log(toBN('0xf').toString(10)); // '15'
// From negative number
console.log(toBN(-15).toString(10)); // '-15'
// From large number string
const largeNumber = '115792089237316195423570985008687907853269984665640564039457584007913129639935';
console.log(toBN(largeNumber).toString(10));isBN#
Checks if a given object is a BN instance.
Parameters
Returns
isBigNumber#
Checks if a given object is a BigNumber instance (from a different library, for compatibility).
Parameters
Returns
numberToHex#
Converts a number, string, or BN instance into a hexadecimal string representation, prefixed with 0x.
Parameters
Returns
Example
Number to Hex
import { numberToHex } from '@ocap/util';
console.log(numberToHex(255)); // '0xff'
console.log(numberToHex('15')); // '0xf'
console.log(numberToHex(-1)); // '-0x1'hexToNumber#
Converts a hexadecimal string into a standard JavaScript number.
Parameters
Returns
isHex / isHexStrict#
isHex(str): Checks if a string is a hexadecimal value. It allows for an optional0xprefix.isHexStrict(str): Checks if a string is a strict hexadecimal value, requiring a0xprefix.
Parameters
Returns
Example
Hex Validation
import { isHex, isHexStrict } from '@ocap/util';
console.log(isHex('0xff')); // true
console.log(isHex('ff')); // true
console.log(isHexStrict('0xff')); // true
console.log(isHexStrict('ff')); // falseisHexPrefixed#
Checks if a string starts with '0x'.
Parameters
Returns
stripHexPrefix#
Removes the 0x prefix from a hexadecimal string if it exists.
Parameters
Returns
Example
Stripping Hex Prefix
import { stripHexPrefix } from '@ocap/util';
console.log(stripHexPrefix('0xabcdef')); // 'abcdef'
console.log(stripHexPrefix('abcdef')); // 'abcdef'Encoding & Decoding#
Functions for converting data between different formats like UTF-8, Hex, Base58, and Base64.
toHex#
Automatically converts a value of almost any type (string, number, boolean, object, Buffer) into its hexadecimal representation.
Parameters
Returns
Example
Universal Hex Conversion
import { toHex } from '@ocap/util';
console.log(toHex('myString')); // '0x6d79537472696e67'
console.log(toHex(255)); // '0xff'
console.log(toHex(true)); // '0x01'
console.log(toHex({ a: 1 })); // '0x7b2261223a317d'
console.log(toHex(Buffer.from('hello'))); // '0x68656c6c6f'utf8ToHex / hexToUtf8#
utf8ToHex(str): Converts a UTF-8 string to its hex representation.hexToUtf8(hex): Converts a hex string back to a UTF-8 string.
Parameters
Returns
Example
UTF-8 and Hex Conversion
import { utf8ToHex, hexToUtf8 } from '@ocap/util';
const originalString = 'Hello World!';
const hexString = utf8ToHex(originalString);
console.log(hexString); // '0x48656c6c6f20576f726c6421'
const decodedString = hexToUtf8(hexString);
console.log(decodedString); // 'Hello World!'bytesToHex / hexToBytes#
bytesToHex(bytes): Converts a byte array to a hex string.hexToBytes(hex): Converts a hex string to a byte array.
Parameters
Returns
toBase58 / fromBase58#
toBase58(data): Encodes data into a Base58 string with a 'z' prefix.fromBase58(str): Decodes a 'z' prefixed Base58 string into a Buffer.
Parameters
Returns
Example
Base58 Encoding
import { toBase58, fromBase58 } from '@ocap/util';
const hexData = '0x15D0014A9CF581EC068B67500683A2784A15E1F6';
const base58String = toBase58(hexData);
console.log(base58String); // 'z2y82i5n5aD62x28s44j32hA73P41B5o1i411C'
const decodedBuffer = fromBase58(base58String);
console.log(decodedBuffer.toString('hex')); // '15d0014a9cf581ec068b67500683a2784a15e1f6'isBase58btc#
Checks if a string is a valid Base58 encoded value with the 'z' prefix.
Parameters
Returns
toBase64 / fromBase64#
toBase64(data): Encodes data into a URL-safe Base64 string.fromBase64(str): Decodes a URL-safe Base64 string into a Buffer.
Parameters
Returns
Example
Base64 Encoding
import { toBase64, fromBase64 } from '@ocap/util';
const hexData = '0xeb82b4eab08020eca09cec9dbc20ec9e9820eb8298eab082';
const base64String = toBase64(hexData);
console.log(base64String); // '64K06rCAIOygnOydvCDsnpgg64KY6rCC'
const decodedBuffer = fromBase64(base64String);
console.log('0x' + decodedBuffer.toString('hex')); // '0xeb82b4eab08020eca09cec9dbc20ec9e9820eb8298eab082'Data Type Conversion#
toUint8Array#
Converts various input types (Hex, Base58, Buffer, string) into a Uint8Array on a best-effort basis.
Parameters
Returns
toBuffer#
Converts various input types into a Node.js Buffer.
Parameters
Returns
isUint8Array#
Validates if a value is a Uint8Array.
Parameters
Returns
Token Unit Conversion#
These functions are essential for converting between the smallest unit of a token (like wei in Ethereum) and its more human-readable representation.
fromUnitToToken#
Converts a value from its smallest unit (e.g., a BN instance) to a human-readable decimal string.
Parameters
Returns
Example
Token Unit Conversion
import { fromUnitToToken } from '@ocap/util';
// 1 Ether (10^18 wei)
console.log(fromUnitToToken('1000000000000000000', 18)); // '1'
// 1.2345 tokens
console.log(fromUnitToToken('1234500000000000000', 18)); // '1.2345'fromTokenToUnit#
Converts a human-readable token amount (as a string or number) into its smallest unit representation as a BN instance.
Parameters
Returns
Example
Token to Smallest Unit
import { fromTokenToUnit } from '@ocap/util';
// 1 token to its smallest unit
console.log(fromTokenToUnit('1', 18).toString()); // '1000000000000000000'
// 0.5 tokens
console.log(fromTokenToUnit('0.5', 18).toString()); // '500000000000000000'DID Utilities#
Helper functions for working with ArcBlock DIDs and addresses.
toAddress / toDid#
toAddress(did): Converts a full DID string (e.g.,did:abt:z...) to its corresponding address by removing thedid:abt:prefix.toDid(address): Converts an address to a full DID string by adding thedid:abt:prefix.
Parameters
Returns
isSameDid#
Compares two DID strings for equality in a case-insensitive manner after converting them to addresses.
Parameters
Returns
Transaction Utilities#
formatTxType#
Formats a transaction type string into UpperCamelCase.
Parameters
Returns
UUID Utilities#
UUID#
Generates a random Version 4 UUID.
Parameters
None.
Returns
isUUID#
Checks if a given string is a valid UUID.
Parameters
Returns
Bonding Curve Calculations#
These functions are used to calculate the price and cost for minting or burning tokens based on different mathematical curves. This is a core component of tokenomics models.
Direction (Enum)#
An enum used in cost calculation functions to specify the direction of the operation.
Direction.Mint: 'mint'Direction.Burn: 'burn'
Constant Curve#
calcConstantPrice({ fixedPrice }): Calculates the price, which is always thefixedPrice.calcConstantCost({ amount, fixedPrice, decimal }): Calculates the cost, which isamount * fixedPrice.
Parameters for calcConstantPrice
Parameters for calcConstantCost
Returns
Linear Curve#
calcLinearPrice({ basePrice, slope, currentSupply, decimal }): Calculates price based on the formulaPrice = basePrice + slope * currentSupply.calcLinearCost({ amount, currentSupply, basePrice, slope, decimal, direction }): Calculates the integral cost of minting or burning tokens along the linear price curve.
Parameters for calcLinearPrice
Parameters for calcLinearCost
Returns
Quadratic Curve#
calcQuadraticPrice({ basePrice, currentSupply, constant, decimal }): Calculates price based on the formulaPrice = basePrice + currentSupply^2 / constant.calcQuadraticCost({ amount, currentSupply, basePrice, constant, decimal, direction }): Calculates the integral cost of minting or burning tokens along the quadratic price curve.
Parameters for calcQuadraticPrice
Parameters for calcQuadraticCost
Returns
Generic Calculators#
calcPrice({ currentSupply, decimal, curve }): A dispatcher function that calculates the current price based on thecurveobject provided. Thecurve.typeproperty ('constant','linear', or'quadratic') determines which calculation to use.calcCost({ amount, decimal, currentSupply, direction, curve }): A dispatcher function that calculates the total cost for an operation based on thecurveobject.
Parameters for calcPrice
Parameters for calcCost
Returns
Example: Using calcCost dispatcher
Generic Cost Calculator
import { calcCost, Direction } from '@ocap/util';
const linearCurve = {
type: 'linear',
basePrice: '1000000000000000000', // 1 token
slope: '100000000000000000', // 0.1
};
const cost = calcCost({
amount: '10000000000000000000', // 10 tokens
decimal: 18,
currentSupply: '0',
direction: Direction.Mint,
curve: linearCurve,
});
// Cost should be 10.5 tokens
console.log(cost.toString()); // '10500000000000000000'calcFee#
Calculates the fee based on a reserve amount and a fee rate.
Parameters
Returns
Asynchronous Utilities#
withRetry#
A higher-order function that wraps an async operation, automatically retrying it upon failure.
Parameters
Returns
Example
Auto-Retry Operation
import { withRetry } from '@ocap/util';
let attempts = 0;
async function flakyFetch() {
attempts++;
console.log(`Attempting to fetch, attempt #${attempts}...`);
if (attempts < 3) {
throw new Error('Network failed');
}
return { data: 'Success!' };
}
async function main() {
try {
const result = await withRetry(flakyFetch, {
retryLimit: 5,
onError: (err, attempt) => console.log(`Attempt ${attempt} failed: ${err.message}`),
});
console.log(result); // { data: 'Success!' }
} catch (error) {
console.error('Operation failed permanently:', error.message);
}
}
main();Custom Errors#
CustomError / PersistError#
Custom error classes that extend the native Error object. They include a code for programmatic error handling and a props object for additional context. PersistError is a variant that signals the error should be persisted.
Constructor Parameters
Hashing#
md5#
Computes the MD5 hash of a given input.
Parameters
Returns