Skip to content

docs: add comprehensive JSDoc documentation for @autonomys/auto-utils package #434

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions packages/auto-utils/src/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,63 @@
import { decodeAddress, encodeAddress } from '@polkadot/keyring'
import { DEFAULT_SS58_FORMAT } from './constants/wallet'

/**
* Converts an address to the standard Autonomys Network format with SS58 encoding.
*
* This function standardizes addresses across the Autonomys Network by encoding them
* using the SS58 format. It accepts both string addresses and Uint8Array representations,
* making it flexible for various use cases.
*
* @param address - The address to convert. Can be a string address or Uint8Array public key.
* @param ss58Format - The SS58 format number to use for encoding. Defaults to the mainnet format.
* @returns The standardized address string in SS58 format.
*
* @example
* import { address } from '@autonomys/auto-utils'
*
* // Convert a raw address to mainnet format
* const mainnetAddress = address('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')
* console.log(mainnetAddress) // Output: standardized mainnet address
*
* // Convert using custom SS58 format
* const customAddress = address('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 42)
* console.log(customAddress) // Output: address in format 42
*
* // Convert from Uint8Array public key
* const publicKey = new Uint8Array(32) // 32-byte public key
* const addressFromPubKey = address(publicKey)
* console.log(addressFromPubKey) // Output: standardized address
*
* @throws {Error} When the input address is invalid or cannot be encoded.
*/
export const address = (
address: string | Uint8Array,
ss58Format: number = DEFAULT_SS58_FORMAT,
): string => encodeAddress(address, ss58Format)

/**
* Decodes an SS58 address to its raw Uint8Array representation.
*
* This function extracts the underlying public key bytes from an SS58-encoded address.
* It's useful when you need to work with the raw address data for cryptographic operations
* or when interfacing with lower-level blockchain functions.
*
* @param address - The SS58-encoded address string to decode.
* @returns The decoded address as a Uint8Array (32 bytes for most address types).
*
* @example
* import { decode } from '@autonomys/auto-utils'
*
* // Decode a mainnet address
* const addressString = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'
* const publicKeyBytes = decode(addressString)
* console.log(publicKeyBytes) // Output: Uint8Array(32) [...]
* console.log(publicKeyBytes.length) // Output: 32
*
* // Use decoded bytes for cryptographic operations
* const decoded = decode('5GmS1wtCfR4tK5SSgnZbVT4kYw5W8NmxmijcsxCQE6oLW6A8')
* // decoded can now be used with other crypto functions
*
* @throws {Error} When the address is invalid, malformed, or has an incorrect checksum.
*/
export const decode = (address: string): Uint8Array => decodeAddress(address)
148 changes: 148 additions & 0 deletions packages/auto-utils/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,45 @@ import {
NetworkParams,
} from './types/network'

/**
* Creates a connection to a Polkadot.js API instance with WebSocket provider.
*
* This function establishes a WebSocket connection to the Autonomys Network or domain
* and returns a fully initialized ApiPromise instance. It automatically includes
* the necessary chain types and waits for the API to be ready before returning.
*
* @param endpoint - The WebSocket endpoint URL(s) to connect to. Can be a single URL or array of URLs.
* @param options - Optional configuration for the API instance.
* @returns A Promise that resolves to an initialized ApiPromise instance.
*
* @example
* import { createConnection } from '@autonomys/auto-utils'
*
* // Connect to single endpoint
* const api = await createConnection('wss://rpc-0.taurus.autonomys.xyz/ws')
* console.log('Connected to API')
*
* // Connect with multiple endpoints for failover
* const endpoints = [
* 'wss://rpc-0.taurus.autonomys.xyz/ws',
* 'wss://rpc-1.taurus.autonomys.xyz/ws'
* ]
* const apiWithFailover = await createConnection(endpoints)
*
* // Connect with custom options
* const customApi = await createConnection(
* 'wss://rpc-0.taurus.autonomys.xyz/ws',
* {
* noInitWarn: false,
* types: { CustomType: 'u32' }
* }
* )
*
* // Always disconnect when done
* await api.disconnect()
*
* @throws {Error} When connection fails or API initialization fails.
*/
export const createConnection = async (
endpoint: string | string[],
options?: ApiOptions,
Expand All @@ -26,6 +65,43 @@ export const createConnection = async (
return api
}

/**
* Activates a connection to the Autonomys Network consensus layer.
*
* This function simplifies connecting to the Autonomys Network by automatically
* resolving the network RPC URLs and establishing a connection. It supports all
* available networks including mainnet, testnet, and local development networks.
*
* @param params - Optional network activation parameters including networkId and API options.
* @returns A Promise that resolves to an initialized ApiPromise instance for the consensus layer.
*
* @example
* import { activate } from '@autonomys/auto-utils'
*
* // Connect to default network (mainnet)
* const api = await activate()
* console.log('Connected to mainnet')
*
* // Connect to specific network
* const taurusApi = await activate({ networkId: 'taurus' })
* console.log('Connected to Taurus testnet')
*
* // Connect to local development network
* const localApi = await activate({ networkId: 'localhost' })
* console.log('Connected to localhost')
*
* // Connect with custom API options
* const customApi = await activate({
* networkId: 'gemini-3h',
* noInitWarn: false,
* types: { CustomType: 'u64' }
* })
*
* // Always disconnect when done
* await api.disconnect()
*
* @throws {Error} When the specified network is not found or connection fails.
*/
export const activate = async (params?: ActivateParams<NetworkParams>): Promise<ApiPromise> => {
// Get the first rpc urls for the network
const endpoint = getNetworkRpcUrls(params)
Expand All @@ -35,6 +111,51 @@ export const activate = async (params?: ActivateParams<NetworkParams>): Promise<
return await createConnection(endpoint, params)
}

/**
* Activates a connection to a specific domain within the Autonomys Network.
*
* This function connects to domain-specific networks like Auto-EVM or Auto-ID
* which run as domains on top of the Autonomys consensus layer. Each domain
* has its own RPC endpoints and may have domain-specific functionality.
*
* @param params - Domain activation parameters including networkId, domainId, and API options.
* @returns A Promise that resolves to an initialized ApiPromise instance for the specified domain.
*
* @example
* import { activateDomain } from '@autonomys/auto-utils'
*
* // Connect to Auto-EVM domain on Taurus testnet
* const evmApi = await activateDomain({
* networkId: 'taurus',
* domainId: '0'
* })
* console.log('Connected to Auto-EVM domain')
*
* // Connect to Auto-ID domain on Gemini-3H
* const autoIdApi = await activateDomain({
* networkId: 'gemini-3h',
* domainId: '1'
* })
* console.log('Connected to Auto-ID domain')
*
* // Connect to localhost domain for development
* const localDomainApi = await activateDomain({
* networkId: 'localhost',
* domainId: '0'
* })
*
* // Connect with custom API options
* const customDomainApi = await activateDomain({
* networkId: 'taurus',
* domainId: '0',
* noInitWarn: false
* })
*
* // Always disconnect when done
* await evmApi.disconnect()
*
* @throws {Error} When the specified network or domain is not found, or connection fails.
*/
export const activateDomain = async (params: ActivateParams<DomainParams>): Promise<ApiPromise> => {
// Get the first rpc urls for the network
const endpoint = getNetworkDomainRpcUrls(params)
Expand All @@ -45,6 +166,33 @@ export const activateDomain = async (params: ActivateParams<DomainParams>): Prom
return await createConnection(endpoint, rest)
}

/**
* Disconnects an active API connection and cleans up resources.
*
* This function properly closes the WebSocket connection and cleans up any
* resources associated with the API instance. It should always be called
* when you're done using an API connection to prevent resource leaks.
*
* @param api - The ApiPromise instance to disconnect.
* @returns A Promise that resolves when the disconnection is complete.
*
* @example
* import { activate, disconnect } from '@autonomys/auto-utils'
*
* // Connect and then disconnect
* const api = await activate({ networkId: 'taurus' })
*
* // Use the API for operations...
* const chainInfo = await api.rpc.system.chain()
* console.log('Chain:', chainInfo.toString())
*
* // Always disconnect when done
* await disconnect(api)
* console.log('API disconnected')
*
* // Or use the API instance method directly
* // await api.disconnect()
*/
export const disconnect = async (api: ApiPromise): Promise<void> => {
// Disconnect the API instance and the provider
await api.disconnect()
Expand Down
28 changes: 28 additions & 0 deletions packages/auto-utils/src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,34 @@ export function stringToUint8Array(text: string): Uint8Array {

/**
* Concatenates two Uint8Array instances into a single Uint8Array.
*
* This function efficiently combines two byte arrays into a single array, preserving
* the order of the input arrays. It's commonly used for combining data before hashing,
* creating composite data structures, or preparing data for cryptographic operations.
*
* @param array1 - The first Uint8Array to concatenate.
* @param array2 - The second Uint8Array to concatenate.
* @returns A new Uint8Array containing all bytes from array1 followed by all bytes from array2.
*
* @example
* import { stringToUint8Array, concatenateUint8Arrays } from '@autonomys/auto-utils'
*
* // Concatenate two strings as byte arrays
* const part1 = stringToUint8Array('Hello, ')
* const part2 = stringToUint8Array('Autonomys!')
* const combined = concatenateUint8Arrays(part1, part2)
*
* // Convert back to string to verify
* const result = new TextDecoder().decode(combined)
* console.log(result) // Output: "Hello, Autonomys!"
* console.log(combined.length) // Output: 16 (total length of both arrays)
*
* // Concatenate with hash data
* const data1 = stringToUint8Array('message1')
* const data2 = stringToUint8Array('message2')
* const combinedData = concatenateUint8Arrays(data1, data2)
* const hash = blake2b_256(combinedData)
* console.log(hash) // Output: hash of combined data
*/
export function concatenateUint8Arrays(array1: Uint8Array, array2: Uint8Array): Uint8Array {
const combined = new Uint8Array(array1.length + array2.length)
Expand Down
Loading