@autonomys/auto-utils

中文文档
1.7.0发布于 2026/11/04MITTypeScriptESM + CJS构建来源已验证近 30 天下载 4106

Autonomys Banner

原始使用文档
文档目录28 节
  1. Overview
  2. Features
  3. Installation
  4. Getting Started
  5. Prerequisites
  6. Importing Only What You Need
  7. Usage Examples
  8. 1. Wallet Management
  9. 2. Network Management
  10. 3. Cryptographic Functions
  11. 4. API Activation
  12. 5. Address Utilities
  13. API Reference
  14. Wallet Management Functions
  15. Network Management Functions
  16. Data Storage Functions
  17. Cryptographic Functions
  18. API Activation Functions
  19. Address Utilities
  20. Constants
  21. Types
  22. Error Handling
  23. Contributing
  24. Code Style
  25. Testing
  26. License
  27. Additional Resources
  28. Contact

Autonomys Auto Utility SDK

Autonomys Banner

Latest Github release Build status of the main branch on Linux/OSX npm version

Overview

The Autonomys Auto SDK Utility (@autonomys/auto-utils) provides core utility functions for interacting with the Autonomys Network. It offers functionalities for:

  • Wallet Management: Initialize and manage wallets using mnemonics or URIs.
  • Network Configuration: Access and manage network and domain settings.
  • Data Storage: Save and read data to and from local storage or the file system.
  • Cryptographic Operations: Perform hashing and data manipulation using cryptographic functions.
  • API Activation: Activate and manage connections to the Autonomys Network APIs.
  • Address Utilities: Convert and decode addresses to and from standardized formats.

This package serves as the foundational layer for building applications within the Autonomys ecosystem.

Features

  • Easy Wallet Setup: Quickly initialize wallets and manage accounts.
  • Flexible Network Management: Choose between different networks and domains easily.
  • Secure Cryptographic Functions: Utilize robust hashing and data handling functions.
  • Simplified API Activation: Streamline connections to network APIs.
  • Data Persistence: Easily save and retrieve data within your applications.
  • TypeScript Support: Fully typed for enhanced developer experience.

Installation

Install the package via npm or yarn:

# Using npm
npm install @autonomys/auto-utils

# Using yarn
yarn add @autonomys/auto-utils

Getting Started

Prerequisites

  • Node.js (version 14 or higher)
  • TypeScript (optional, but recommended for development)
  • Familiarity with async/await and promise handling in JavaScript/TypeScript.

Importing Only What You Need

The root entry point re-exports everything, including helpers that depend on @polkadot/api. Bundlers such as webpack, Rollup, esbuild and Vite tree-shake it, but Node.js and Jest load the whole module graph. Each module is also published as a subpath, so you can load only the part you use:

import { NetworkId } from '@autonomys/auto-utils/constants'
import { shannonsToAi3 } from '@autonomys/auto-utils/number'
SubpathContentsLoads Polkadot
@autonomys/auto-utils/constantsNetworkId, networks, token and SS58 constantsNo
@autonomys/auto-utils/networkgetNetworkDetails, getNetworkRpcUrls and domain variantsNo
@autonomys/auto-utils/numbershannonsToAi3, ai3ToShannons, formatUnits, etc.No
@autonomys/auto-utils/stringstringify, shortString, etc.No
@autonomys/auto-utils/typesShared TypeScript types and CHAIN_TYPESNo
@autonomys/auto-utils/addressaddress, decode@polkadot/keyring
@autonomys/auto-utils/cryptoblake2b_256, stringToUint8Array, etc.@polkadot/util-crypto
@autonomys/auto-utils/keyringKeyring@polkadot/keyring
@autonomys/auto-utils/apiactivate, activateDomain, createConnection, etc.@polkadot/api
@autonomys/auto-utils/utilssignAndSendTx, signMessage, createType helpers, etc.@polkadot/types, @polkadot/util-crypto
@autonomys/auto-utils/walletsetupWallet, activateWallet, mockWallets, etc.@polkadot/api

Importing from @autonomys/auto-utils/dist/... is not supported; use the root or one of the subpaths above.

Usage Examples

Below are examples demonstrating how to use the functions provided by @autonomys/auto-utils.


1. Wallet Management

Activate a Wallet

Activate a wallet using a mnemonic phrase:

// Import necessary functions
import { activateWallet } from '@autonomys/auto-utils'
;(async () => {
  // Replace with your mnemonic
  const mnemonic = 'your mnemonic phrase here'

  // Activate the wallet
  const { api, accounts } = await activateWallet({
    mnemonic,
    networkId: 'mainnet', // Optional: specify the network ID
    // Optional derivation path (useful for ethereum BIP44):
    // derivationPath: "m/44'/60'/0'/0/0",
  })

  const account = accounts[0]
  console.log(`Connected with account address: ${account.address}`)

  // Perform actions with the account...

  // Disconnect when done
  await api.disconnect()
})()

Parameters:

  • mnemonic (string): The mnemonic phrase of the wallet.
  • networkId (string, optional): The ID of the network to connect to.

Returns:

  • An object containing:
    • api: An instance of ApiPromise connected to the network.
    • accounts: An array of accounts derived from the mnemonic.

Activate a Wallet Using URI

You can also activate a wallet using a URI (e.g., //Alice for development purposes):

import { activateWallet } from '@autonomys/auto-utils'
;(async () => {
  const { api, accounts } = await activateWallet({
    uri: '//Alice',
    networkId: 'localhost', // Connect to a local network
  })

  const account = accounts[0]
  console.log(`Connected with account address: ${account.address}`)

  // Disconnect when done
  await api.disconnect()
})()

Create Mock Wallets for Testing

Create mock wallets for testing purposes:

import { activate, mockWallets, getMockWallet } from '@autonomys/auto-utils'
;(async () => {
  const api = await activate({ networkId: 'mainnet' })

  const wallets = await mockWallets({}, api)
  const aliceWallet = getMockWallet('Alice', wallets)
  const bobWallet = getMockWallet('Bob', wallets)

  console.log(`Alice's address: ${aliceWallet.accounts[0].address}`)
  console.log(`Bob's address: ${bobWallet.accounts[0].address}`)

  // Disconnect when done
  await api.disconnect()
})()

2. Network Management

Get Available Networks

List all available networks:

import { networks } from '@autonomys/auto-utils'

networks.forEach((network) => {
  console.log(`Network ID: ${network.id}, Name: ${network.name}`)
})

Get Network Details

Retrieve details of a specific network:

import { getNetworkDetails } from '@autonomys/auto-utils'

const network = getNetworkDetails({ networkId: 'mainnet' })
console.log(`Network Name: ${network.name}`)
console.log(`RPC URLs: ${network.rpcUrls.join(', ')}`)

Get Domain Details

Retrieve details of a specific domain within a network:

import { getNetworkDomainDetails } from '@autonomys/auto-utils'

const domain = getNetworkDomainDetails({ domainId: '0', networkId: 'mainnet' })
console.log(`Domain Name: ${domain.name}`)
console.log(`RPC URLs: ${domain.rpcUrls.join(', ')}`)

3. Cryptographic Functions

Hash Data Using BLAKE2b-256

Hash a string using BLAKE2b-256:

import { blake2b_256, stringToUint8Array } from '@autonomys/auto-utils'

const data = 'Hello, Autonomys!'
const dataBytes = stringToUint8Array(data)
const hash = blake2b_256(dataBytes)

console.log(`Hash: ${hash}`) // Outputs the hash of the input string

Convert String to Uint8Array

Convert a string to a Uint8Array:

import { stringToUint8Array } from '@autonomys/auto-utils'

const text = 'Sample text'
const byteArray = stringToUint8Array(text)

console.log(byteArray) // Outputs Uint8Array representation of the string

Concatenate Uint8Arrays

Concatenate two Uint8Array instances:

import { stringToUint8Array, concatenateUint8Arrays } from '@autonomys/auto-utils'

const array1 = stringToUint8Array('First part ')
const array2 = stringToUint8Array('Second part')

const concatenated = concatenateUint8Arrays(array1, array2)
console.log(`Concatenated Result: ${new TextDecoder().decode(concatenated)}`)
// Outputs: "First part Second part"

4. API Activation

Activate the Network API

Connect to the Autonomys Network:

import { activate } from '@autonomys/auto-utils'
;(async () => {
  const api = await activate({ networkId: 'mainnet' })

  console.log('API connected')

  // Perform API calls...

  // Disconnect when done
  await api.disconnect()
})()

Activate a Domain API

Connect to a specific domain within the network:

import { activateDomain } from '@autonomys/auto-utils'
;(async () => {
  const api = await activateDomain({ domainId: '0', networkId: 'mainnet' })

  console.log('Domain API connected')

  // Perform domain-specific API calls...

  // Disconnect when done
  await api.disconnect()
})()

Setup a Wallet with Ethereum BIP44

import { setupWallet } from '@autonomys/auto-utils'

const mnemonic = 'your mnemonic phrase here'

// Default behavior derives from master (m)
const ethMaster = setupWallet({ mnemonic, type: 'ethereum' })

// To derive using BIP44 path
const ethBip44 = setupWallet({
  mnemonic,
  type: 'ethereum',
  derivationPath: "m/44'/60'/0'/0/0",
})

console.log(ethMaster.address)
console.log(ethBip44.address)

5. Address Utilities

Convert Address Formats

Convert an address to a standardized format and decode it:

import { address, decode } from '@autonomys/auto-utils'

const originalAddress = '5GmS1wtCfR4tK5SSgnZbVT4kYw5W8NmxmijcsxCQE6oLW6A8'
const standardizedAddress = address(originalAddress)
const decodedAddress = decode(originalAddress)

console.log(`Standardized Address: ${standardizedAddress}`)
console.log(`Decoded Address:`, decodedAddress)

API Reference

Wallet Management Functions

  • setupWallet(params: MnemonicOrURI): KeyringPair: Initializes a wallet using a mnemonic or URI.

    • Parameters:

      • params (object):
        • mnemonic (string, optional): The mnemonic phrase.
        • uri (string, optional): The derivation path or URI.
    • Returns: KeyringPair - The initialized wallet key pair.

  • activateWallet(params: ActivateWalletParams): Promise<WalletActivated>: Activates a wallet and returns API and accounts.

    • Parameters:

      • params (object):
        • mnemonic or uri (string): Wallet credentials.
        • networkId (string, optional): The network ID to connect to.
    • Returns:

      • api: Connected ApiPromise instance.
      • accounts: Array of derived accounts.
  • mockWallets(network: NetworkParams | DomainParams, api: ApiPromise): Promise<WalletActivated[]>: Creates mock wallets for testing.

    • Parameters:

      • network (object): Network parameters.
      • api (ApiPromise): Connected API instance.
    • Returns: Array of WalletActivated - Mock wallets.

  • getMockWallet(name: string, wallets: WalletActivated[]): WalletActivated: Retrieves a mock wallet by name.

    • Parameters:

      • name (string): Name of the mock wallet (e.g., 'Alice', 'Bob').
      • wallets (array): Array of WalletActivated.
    • Returns: A single WalletActivated matching the name.


Network Management Functions

  • getNetworkDetails(input?: NetworkParams): Network: Gets network details.

    • Parameters:

      • input (object, optional): Contains networkId.
    • Returns: Network - Network configuration object.

  • getNetworkRpcUrls(input?: NetworkParams): string[]: Gets network RPC URLs.

    • Parameters:

      • input (object, optional): Contains networkId.
    • Returns: Array of RPC URL strings.

  • getNetworkDomainDetails(params: DomainParams): Domain: Gets domain details.

    • Parameters:

      • params (object): Contains domainId and networkId.
    • Returns: Domain - Domain configuration object.

  • getNetworkDomainRpcUrls(params: DomainParams): string[]: Gets domain RPC URLs.

    • Parameters:

      • params (object): Contains domainId and networkId.
    • Returns: Array of domain RPC URL strings.


Data Storage Functions

  • save(key: string, value: any): void: Saves data to local storage or file system.

    • Parameters:

      • key (string): Unique identifier for the data.
      • value (any): Data to be stored.
    • Returns: void

  • read(key: string): any: Reads data from local storage or file system.

    • Parameters:

      • key (string): Unique identifier for the data.
    • Returns: The retrieved data.


Cryptographic Functions

  • blake2b_256(data: Uint8Array): string: Hashes data with BLAKE2b-256.

    • Parameters:

      • data (Uint8Array): Data to be hashed.
    • Returns: Hex string representation of the hash.

  • stringToUint8Array(text: string): Uint8Array: Converts a string to a Uint8Array.

    • Parameters:

      • text (string): The input string.
    • Returns: Uint8Array representation of the string.

  • concatenateUint8Arrays(array1: Uint8Array, array2: Uint8Array): Uint8Array: Concatenates two Uint8Array instances.

    • Parameters:

      • array1 (Uint8Array)
      • array2 (Uint8Array)
    • Returns: New Uint8Array resulting from concatenation.


API Activation Functions

  • activate(params?: ActivateParams<NetworkParams>): Promise<ApiPromise>: Activates the API for a network.

    • Parameters:

      • params (object, optional): Network activation parameters.
    • Returns: ApiPromise instance connected to the network.

  • activateDomain(params: ActivateParams<DomainParams>): Promise<ApiPromise>: Activates the API for a domain.

    • Parameters:

      • params (object): Domain activation parameters.
    • Returns: ApiPromise instance connected to the domain.

  • disconnect(api: ApiPromise): Promise<void>: Disconnects the API.

    • Parameters:

      • api (ApiPromise): The API instance to disconnect.
    • Returns: void


Address Utilities

  • address(address: string | Uint8Array): string: Converts an address to a standardized format.

    • Parameters:

      • address (string | Uint8Array): The original address.
    • Returns: Standardized address string.

  • decode(address: string): Uint8Array: Decodes an address into a Uint8Array.

    • Parameters:

      • address (string): The address to decode.
    • Returns: Uint8Array representation of the address.


Constants

  • networks: Array of network configurations.

    import { networks } from '@autonomys/auto-utils'
    
    // Example usage
    networks.forEach((network) => {
      console.log(network.id, network.name)
    })
    
  • defaultNetwork: Default network configuration.

    import { defaultNetwork } from '@autonomys/auto-utils'
    
    console.log(`Default Network: ${defaultNetwork.name}`)
    
  • mockURIs: Array of mock URIs.

    import { mockURIs } from '@autonomys/auto-utils'
    
    console.log(`Available mock URIs: ${mockURIs.join(', ')}`)
    

Types

  • Network, Domain, Explorer, NetworkParams, DomainParams
  • Mnemonic, URI, AppName, MnemonicOrURI

These types are available for TypeScript users to ensure type safety and better development experience.


Error Handling

When using @autonomys/auto-utils, it's important to handle potential errors, especially when dealing with asynchronous operations like network connections or wallet activations. Make use of try/catch blocks or handle promise rejections appropriately.

Example:

import { activateWallet } from '@autonomys/auto-utils'
;(async () => {
  try {
    const { api, accounts } = await activateWallet({
      mnemonic: 'your mnemonic',
    })

    // Proceed with using the api and accounts
  } catch (error) {
    console.error('Error activating wallet:', error)
  }
})()

Contributing

We welcome community contributions! If you wish to contribute to @autonomys/auto-utils, please follow these guidelines:

  1. Fork the repository on GitHub.

  2. Clone your fork locally:

    git clone https://github.com/your-username/auto-sdk.git
    cd auto-sdk/packages/auto-utils
    
  3. Install dependencies:

    yarn install
    
  4. Make your changes and ensure all tests pass:

    yarn test
    
  5. Commit your changes with clear and descriptive messages.

  6. Push to your fork and create a pull request against the main branch of the original repository.

Code Style

  • Use TypeScript for all code.
  • Follow the existing coding conventions.
  • Run yarn lint to ensure code style consistency.

Testing

  • Add tests for any new features or bug fixes.
  • Ensure all existing tests pass.

License

This project is licensed under the MIT License. See the LICENSE file for details.


Additional Resources

  • Autonomys Academy: Learn more about the Autonomys SDK and the vision behind it at Autonomys Academy.

Contact

If you have any questions or need support, feel free to reach out:

We appreciate your feedback and contributions!

版本与发布记录

@autonomys/auto-utils 共发布 143 个版本,首次发布于 2024/06/25;过去 12 个月发布了 24 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.7.0latest2026/11/043 天前
1.6.162026/10/2019 天前
1.6.152026/10/011 个月前
1.6.142026/06/045 个月前
1.6.132026/05/295 个月前
1.6.122026/05/295 个月前

其他发布通道:beta → 1.6.4-beta.1。

关于 @autonomys/auto-utils 的常见问题

如何安装 @autonomys/auto-utils?

在项目目录运行 npm install @autonomys/auto-utils,或使用 pnpm add / yarn add / bun add。

@autonomys/auto-utils 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@autonomys/auto-utils 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@autonomys/auto-utils 可以商用吗?

@autonomys/auto-utils 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@autonomys/auto-utils 的下载量有多少?

根据 npm 官方下载统计,@autonomys/auto-utils 在 2026/10/07 – 2026/11/05 这 30 天内被下载 4,106 次,日均约 137 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@autonomys/auto-utils 还在维护吗?

最新版本 1.7.0 发布于 2026/11/04(3 天前);至今共发布 143 个版本,其中过去 12 个月发布了 24 个;首次发布于 2024/06/25。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。