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

num
number | string | BN
required
The value to convert.
base
number | 'hex'
default:10
The numerical base for conversion, defaults to 10.

Returns

BN
The BN instance.

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

object
any
required
The object to check.

Returns

boolean
Returns `true` if the object is a BN instance, otherwise `false`.

isBigNumber#

Checks if a given object is a BigNumber instance (from a different library, for compatibility).

Parameters

object
any
required
The object to check.

Returns

boolean
Returns `true` if the object is a BigNumber instance, otherwise `false`.

numberToHex#

Converts a number, string, or BN instance into a hexadecimal string representation, prefixed with 0x.

Parameters

value
string | number | BN
required
The value to convert.

Returns

string
The hexadecimal string.

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

value
string | number | BN
required
The hexadecimal value to convert.

Returns

number
The number representation.

isHex / isHexStrict#

  • isHex(str): Checks if a string is a hexadecimal value. It allows for an optional 0x prefix.
  • isHexStrict(str): Checks if a string is a strict hexadecimal value, requiring a 0x prefix.

Parameters

hex
string
required
The string to check.

Returns

boolean
Returns `true` if the string is a valid hex value according to the function's rules, otherwise `false`.

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'));   // false

isHexPrefixed#

Checks if a string starts with '0x'.

Parameters

str
string
required
The string to check.

Returns

boolean
Returns `true` if the string has a '0x' prefix, otherwise `false`.

stripHexPrefix#

Removes the 0x prefix from a hexadecimal string if it exists.

Parameters

str
string
required
The string to process.

Returns

string
The string without the '0x' prefix.

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

value
any
required
The input value to convert.

Returns

string
The resulting hexadecimal string.

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

str or hex
string
required
The string to convert.

Returns

string
The converted string.

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

bytes or hex
Array<number> | string
required
The data to convert.

Returns

string | Array<number>
The converted data.

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

data or str
any | string
required
The data to encode or decode.

Returns

string | Buffer
The encoded string or decoded Buffer.

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

data
any
required
The value to check.

Returns

boolean
Returns `true` if the value is a valid Base58 string, otherwise `false`.

toBase64 / fromBase64#

  • toBase64(data): Encodes data into a URL-safe Base64 string.
  • fromBase64(str): Decodes a URL-safe Base64 string into a Buffer.

Parameters

data or str
any | string
required
The data to encode or decode.

Returns

string | Buffer
The encoded string or decoded Buffer.

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

v
any
required
The value to convert.

Returns

Uint8Array
The resulting Uint8Array.

toBuffer#

Converts various input types into a Node.js Buffer.

Parameters

v
any
required
The value to convert.

Returns

Buffer
The resulting Buffer.

isUint8Array#

Validates if a value is a Uint8Array.

Parameters

value
any
required
The value to check.

Returns

boolean
Returns `true` if the value is a Uint8Array, otherwise `false`.

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

input
string | number | BN
required
The value in its smallest unit.
decimal
number
default:18
The number of decimal places the token has.

Returns

string
The human-readable token amount.

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

input
string | number
required
The human-readable token amount.
decimal
number
default:18
The number of decimal places the token has.

Returns

BN
The value in its smallest unit.

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 the did:abt: prefix.
  • toDid(address): Converts an address to a full DID string by adding the did:abt: prefix.

Parameters

did or address
string
required
The DID or address to convert.

Returns

string
The converted address or DID.

isSameDid#

Compares two DID strings for equality in a case-insensitive manner after converting them to addresses.

Parameters

a
string
required
The first DID to compare.
b
string
required
The second DID to compare.

Returns

boolean
Returns `true` if the DIDs are the same, otherwise `false`.

Transaction Utilities#

formatTxType#

Formats a transaction type string into UpperCamelCase.

Parameters

type
string
required
The transaction type string (e.g., 'transfer').

Returns

string
The formatted string (e.g., 'Transfer').

UUID Utilities#

UUID#

Generates a random Version 4 UUID.

Parameters

None.

Returns

string
A new UUID string.

isUUID#

Checks if a given string is a valid UUID.

Parameters

str
string
required
The string to check.

Returns

boolean
Returns `true` if the string is a valid UUID, otherwise `false`.

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 the fixedPrice.
  • calcConstantCost({ amount, fixedPrice, decimal }): Calculates the cost, which is amount * fixedPrice.

Parameters for calcConstantPrice

fixedPrice
string
required
The fixed price per token in its smallest unit.

Parameters for calcConstantCost

amount
string
required
The amount of tokens to mint/burn.
fixedPrice
string
required
The fixed price per token.
decimal
number
required
The token's decimal places.

Returns

BN
The calculated price or cost.

Linear Curve#

  • calcLinearPrice({ basePrice, slope, currentSupply, decimal }): Calculates price based on the formula Price = 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

basePrice
string
required
The starting price of the token.
slope
string
required
The rate at which the price increases with supply.
currentSupply
string
required
The current total supply of the token.
decimal
number
required
The token's decimal places.

Parameters for calcLinearCost

params
object
required
An object containing calculation parameters.
6 subfields

Returns

BN
The calculated price or cost.

Quadratic Curve#

  • calcQuadraticPrice({ basePrice, currentSupply, constant, decimal }): Calculates price based on the formula Price = 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

basePrice
string
required
The starting price.
currentSupply
string
required
The current token supply.
constant
string
required
A constant that moderates the price curve.
decimal
number
required
The token's decimal places.

Parameters for calcQuadraticCost

params
object
required
An object containing calculation parameters.
6 subfields

Returns

BN
The calculated price or cost.

Generic Calculators#

  • calcPrice({ currentSupply, decimal, curve }): A dispatcher function that calculates the current price based on the curve object provided. The curve.type property ('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 the curve object.

Parameters for calcPrice

currentSupply
string
required
The current token supply.
decimal
number
required
The token's decimal places.
curve
object
required
A curve configuration object with `type` and other relevant parameters.

Parameters for calcCost

amount
string
required
The amount of tokens.
decimal
number
required
The token's decimal places.
currentSupply
string
required
The current token supply.
direction
Direction
required
The operation direction.
curve
object
required
A curve configuration object.

Returns

BN
The calculated price or cost as a BN instance.

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

reserveAmount
string
required
The total amount from which the fee is calculated.
feeRate
string
required
The fee rate in basis points (e.g., '500' for 5%).

Returns

BN
The calculated fee amount.

Asynchronous Utilities#

withRetry#

A higher-order function that wraps an async operation, automatically retrying it upon failure.

Parameters

handle
() => Promise<T>
required
The async function to execute and retry.
options
object
Configuration for the retry logic.
4 subfields

Returns

Promise<T>
A promise that resolves with the result of the `handle` function.

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

code
string
required
An error code string.
message
string
required
The error message.
props
object
Additional properties associated with the error.

Hashing#

md5#

Computes the MD5 hash of a given input.

Parameters

data
any
required
The data to hash.

Returns

string
The MD5 hash as a hex string.