# @autonomys/auto-utils 中文文档

规范地址：https://npmcn.com/package/%40autonomys/auto-utils/

版本：1\.7\.0
npm 元数据更新时间：2026-11-04T13:59:39.283Z
中文译文更新时间：2026-11-07T07:05:05.987Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40autonomys/auto-utils
原文对照：https://npmcn.com/package/%40autonomys/auto-utils/?lang=original
项目主页：https://github.com/autonomys/auto-sdk#readme
源码仓库：https://github.com/autonomys/auto-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：301 kB，144 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2024-06-25T15:50:22.527Z
- 最新版本发布：2026-11-04T13:59:38.714Z
- 近 30 天下载量：4106（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：143（近 12 个月 24 个）

## 中文简介

![Autonomys Banner](https://github.com/autonomys/auto-sdk/blob/main/.github/images/autonomys-banner.webp)

## 安装

```sh
npm install @autonomys/auto-utils
```

也可以使用：`pnpm add @autonomys/auto-utils`、`yarn add @autonomys/auto-utils`、`bun add @autonomys/auto-utils`

## README

# 自动工具 SDK

![Autonomys Banner](https://github.com/autonomys/auto-sdk/blob/main/.github/images/autonomys-banner.webp)

[![Latest Github release](https://img.shields.io/github/v/tag/autonomys/auto-sdk.svg)](https://github.com/autonomys/auto-sdk/tags) [![Build status of the main branch on Linux/OSX](https://img.shields.io/github/actions/workflow/status/autonomys/auto-sdk/build.yaml?branch=main&label=Linux%2FOSX%20build)](https://github.com/autonomys/auto-sdk/actions/workflows/build.yaml) [![npm version](https://badge.fury.io/js/@autonomys%2Fauto-utils.svg)](https://badge.fury.io/js/@autonomys%2Fauto-utils)

## 概览

这个 **自动 SDK 工具** (单位:千美元)`@autonomys/auto-utils`提供与自主网络互动的核心功能。 它提供以下功能:

-   **钱包管理**: 使用mnemonics或URI来初始化和管理钱包.
-   **网络配置**: 访问并管理网络和域设置.
-   **数据存储**:从本地存储或文件系统保存并读取数据.
-   **密码操作**: 使用密码函数进行散列和数据操作.
-   **API 启动**: 激活和管理连接到自治网络API.
-   **地址公用事业**: 将地址转换和解码为标准格式.

这个软件包是自治生态系统内建立应用的基础层.

## 特征

-   **容易的钱包设置**: 快速初始化钱包并管理账户.
-   **灵活的网络管理**: 在不同的网络和域间选择容易.
-   **安全加密函数**: 利用强有力的散列和数据处理功能.
-   **简化 API 激活**: 简化网络API的连接.
-   **数据持久性**: 轻松保存和检索应用程序中的数据.
-   **类型脚本支持**: 为增强开发者经验而完全打入.

## 安装

通过 npm 或纱线安装软件包 :

```bash
# Using npm
npm install @autonomys/auto-utils

# Using yarn
yarn add @autonomys/auto-utils
```

## 开始

### 先决条件

-   **节点.js** (第14版或以上)
-   **类型脚本** (可选,但建议发展)
-   熟悉JavaScript/TypeScript中的ASync/await并许诺处理.

### 仅导入您需要的东西

根入点再出口一切,包括依赖 `@polkadot/api`. . . . . 每个模块也作为子路径发布,因此只能装入您使用的部分:

```typescript
import { NetworkId } from '@autonomys/auto-utils/constants'
import { shannonsToAi3 } from '@autonomys/auto-utils/number'
```

| 子路径 | 目录 | 装入 Polkadot |
| --- | --- | --- |
| `@autonomys/auto-utils/constants` | `NetworkId`, (中文(简体) ), `networks`符号和SS58常数 | 没有 |
| `@autonomys/auto-utils/network` | `getNetworkDetails`, (中文(简体) ), `getNetworkRpcUrls` 和域变量 | 没有 |
| `@autonomys/auto-utils/number` | `shannonsToAi3`, (中文(简体) ), `ai3ToShannons`, (中文(简体) ), `formatUnits`等 (中文(简体) ). | 没有 |
| `@autonomys/auto-utils/string` | `stringify`, (中文(简体) ), `shortString`等 (中文(简体) ). | 没有 |
| `@autonomys/auto-utils/types` | 共享类型脚本类型和 `CHAIN_TYPES` | 没有 |
| `@autonomys/auto-utils/address` | `address`, (中文(简体) ), `decode` | `@polkadot/keyring` |
| `@autonomys/auto-utils/crypto` | `blake2b_256`, (中文(简体) ), `stringToUint8Array`等 (中文(简体) ). | `@polkadot/util-crypto` |
| `@autonomys/auto-utils/keyring` | `Keyring` | `@polkadot/keyring` |
| `@autonomys/auto-utils/api` | `activate`, (中文(简体) ), `activateDomain`, (中文(简体) ), `createConnection`等 (中文(简体) ). | `@polkadot/api` |
| `@autonomys/auto-utils/utils` | `signAndSendTx`, (中文(简体) ), `signMessage`, (中文(简体) ), `createType` 帮助者等. | `@polkadot/types`, (中文(简体) ), `@polkadot/util-crypto` |
| `@autonomys/auto-utils/wallet` | `setupWallet`, (中文(简体) ), `activateWallet`, (中文(简体) ), `mockWallets`等 (中文(简体) ). | `@polkadot/api` |

从 `@autonomys/auto-utils/dist/...` 不支持; 使用上方的根或子路径之一.

## 用法实例

下面是实例,说明如何使用由下列机构提供的功能: `@autonomys/auto-utils`。 。 。 .

* * *

### 1\. 钱包管理

#### **激活钱包**

激活钱包时使用元词:

```typescript
// 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()
})()
```

**参数:**

-   `mnemonic` (字符串):钱包的元音短语.
-   `networkId` (弦,可选): 要连接的网络的ID.

**回返情况:**

-   包含:
    -   `api`: 实例 `ApiPromise` 与网络连接.
    -   `accounts`: 从元音中衍生出的一系列账户.

#### **使用 URI 激活钱包**

您也可以使用 URI 激活钱包(例如, `//Alice` 用于发展目的:

```typescript
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()
})()
```

#### **创建模拟钱包用于测试**

为测试目的创建模拟钱包 :

```typescript
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\. 网络管理

#### **获取可用的网络**

列出所有可用的网络 :

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

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

#### **获取网络细节**

获取特定网络的细节 :

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

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

#### **获取域细节**

获取网络内特定域的细节 :

```typescript
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\. 密码函数

#### **使用 BLAKE2b-256 的散列数据**

使用 BLAKE2b-256 来挂起字符串 :

```typescript
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
```

#### **将字符串转换为 Uint8 箭头**

将字符串转换为 `Uint8Array`数字 :

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

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

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

#### **连接的 Uint8 箭头**

二号 `Uint8Array` 实例 :

```typescript
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 启动

#### **激活网络 API**

连接到自治网络 :

```typescript
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()
})()
```

#### **激活域 API**

连接到网络内的特定域 :

```typescript
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()
})()
```

* * *

#### **用 Ethereum BIP44 设置钱包**

```typescript
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\. 地址公用事业

#### **转换地址格式**

将地址转换为标准格式并解码:

```typescript
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 参考

### 钱包管理函数

-   **`setupWallet(params: MnemonicOrURI): KeyringPair`**: 初始化钱包使用mnemonic或URI.
    
    -   **参数**数字 :
        
        -   `params` (对象):
            -   `mnemonic` (弦,可选): 释相句.
            -   `uri` (弦,可选): 引出路径或URI.
    -   **回返**数字 : `KeyringPair` - 初始化的钱包密钥对.
        
-   **`activateWallet(params: ActivateWalletParams): Promise<WalletActivated>`**: 激活钱包并返回 API 和账户.
    
    -   **参数**数字 :
        
        -   `params` (对象):
            -   `mnemonic` 或者说 `uri` (字符串):钱包证书.
            -   `networkId` (弦,可选): 要连接的网络ID .
    -   **回返**数字 :
        
        -   **`api`**已连接 `ApiPromise` 举个例子.
        -   **`accounts`**: 衍生账户的组合.
-   **`mockWallets(network: NetworkParams | DomainParams, api: ApiPromise): Promise<WalletActivated[]>`**: 创建用于测试的模拟钱包.
    
    -   **参数**数字 :
        
        -   `network` (对象):网络参数.
        -   `api` (单位:千美元)`ApiPromise`:连接的API实例.
    -   **回返**: 阵列 `WalletActivated` - 口袋钱包.
        
-   **`getMockWallet(name: string, wallets: WalletActivated[]): WalletActivated`**:按名取出一个模拟钱包.
    
    -   **参数**数字 :
        
        -   `name` (字符串):模拟钱包的名称(如"艾利斯","鲍勃"等).
        -   `wallets` (阵列): `WalletActivated`。 。 。 .
    -   **回返**: 单人 `WalletActivated` 匹配名称.
        

* * *

### 网络管理函数

-   **`getNetworkDetails(input?: NetworkParams): Network`**:获得网络细节.
    
    -   **参数**数字 :
        
        -   `input` (对象,可选):包含 `networkId`。 。 。 .
    -   **回返**数字 : `Network` -网络配置对象.
        
-   **`getNetworkRpcUrls(input?: NetworkParams): string[]`**: 获取网络 RPC URL.
    
    -   **参数**数字 :
        
        -   `input` (对象,可选):包含 `networkId`。 。 。 .
    -   **回返**: RPC URL 字符串的阵列.
        
-   **`getNetworkDomainDetails(params: DomainParams): Domain`**:获得域名细节.
    
    -   **参数**数字 :
        
        -   `params` (对象):包含 `domainId` 财务报告和审定财务报表 `networkId`。 。 。 .
    -   **回返**数字 : `Domain` - 域配置对象.
        
-   **`getNetworkDomainRpcUrls(params: DomainParams): string[]`**:获得域名RPC URL.
    
    -   **参数**数字 :
        
        -   `params` (对象):包含 `domainId` 财务报告和审定财务报表 `networkId`。 。 。 .
    -   **回返**: 域名RPC URL字符串的组合.
        

* * *

### 数据存储函数

-   **`save(key: string, value: any): void`**:将数据保存到本地存储或文件系统.
    
    -   **参数**数字 :
        
        -   `key` (字符串):数据的独特标识符.
        -   `value` 数据要存储.
    -   **回返**数字 : `void`
        
-   **`read(key: string): any`**: 从本地存储或文件系统读取数据.
    
    -   **参数**数字 :
        
        -   `key` (字符串):数据的独特标识符.
    -   **回返**: 检索到的数据.
        

* * *

### 加密函数

-   **`blake2b_256(data: Uint8Array): string`**: Hashes数据与 BLAKE2b-256.
    
    -   **参数**数字 :
        
        -   `data` (单位:千美元)`Uint8Array`:数据需要散列.
    -   **回返**: Hex弦表示散列.
        
-   **`stringToUint8Array(text: string): Uint8Array`**: 将字符串转换为 `Uint8Array`。 。 。 .
    
    -   **参数**数字 :
        
        -   `text` (字符串):输入字符串.
    -   **回返**数字 : `Uint8Array` 表示字符串.
        
-   **`concatenateUint8Arrays(array1: Uint8Array, array2: Uint8Array): Uint8Array`**: 二号组装 `Uint8Array` 实例.
    
    -   **参数**数字 :
        
        -   `array1` (单位:千美元)`Uint8Array`(中文(简体) )
        -   `array2` (单位:千美元)`Uint8Array`(中文(简体) )
    -   **回返**新设 `Uint8Array` 由协和制得.
        

* * *

### API 激活函数

-   **`activate(params?: ActivateParams<NetworkParams>): Promise<ApiPromise>`**:激活一个网络的API.
    
    -   **参数**数字 :
        
        -   `params` (对象,可选): 网络活化参数.
    -   **回返**数字 : `ApiPromise` 实例连接到网络.
        
-   **`activateDomain(params: ActivateParams<DomainParams>): Promise<ApiPromise>`**: 激活一个域的 API.
    
    -   **参数**数字 :
        
        -   `params` (对象):域活化参数.
    -   **回返**数字 : `ApiPromise` 实例链接到域.
        
-   **`disconnect(api: ApiPromise): Promise<void>`**: 断开API.
    
    -   **参数**数字 :
        
        -   `api` (单位:千美元)`ApiPromise`: API 实例中断 .
    -   **回返**数字 : `void`
        

* * *

### 地址公用事业

-   **`address(address: string | Uint8Array): string`**: 将地址转换为标准格式.
    
    -   **参数**数字 :
        
        -   `address` (弦声) `Uint8Array`(原始内容存档于2013-10-10). The 原始地址.
    -   **回返**:标准化地址字符串.
        
-   **`decode(address: string): Uint8Array`**: 将地址解码为 `Uint8Array`。 。 。 .
    
    -   **参数**数字 :
        
        -   `address` (字符串):解码地址.
    -   **回返**数字 : `Uint8Array` 代表该地址.
        

* * *

### 常数

-   **`networks`**:网络配置阵列.
    
    ```typescript
    import { networks } from '@autonomys/auto-utils'
    
    // Example usage
    networks.forEach((network) => {
      console.log(network.id, network.name)
    })
    ```
    
-   **`defaultNetwork`**: 默认网络配置.
    
    ```typescript
    import { defaultNetwork } from '@autonomys/auto-utils'
    
    console.log(`Default Network: ${defaultNetwork.name}`)
    ```
    
-   **`mockURIs`**:模拟URI系列.
    
    ```typescript
    import { mockURIs } from '@autonomys/auto-utils'
    
    console.log(`Available mock URIs: ${mockURIs.join(', ')}`)
    ```
    

* * *

### 类型

-   **`Network`**, (中文(简体) ), **`Domain`**, (中文(简体) ), **`Explorer`**, (中文(简体) ), **`NetworkParams`**, (中文(简体) ), **`DomainParams`**
-   **`Mnemonic`**, (中文(简体) ), **`URI`**, (中文(简体) ), **`AppName`**, (中文(简体) ), **`MnemonicOrURI`**

这些类型可供TypeScript用户使用,以确保类型安全和更好的开发经验.

* * *

## 处理错误

使用时 `@autonomys/auto-utils`,处理潜在出错很重要,特别是在处理网络连接或钱包活化等同步操作时. 利用 `try/catch` 块或适当处理拒绝承诺.

**示例**

```typescript
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)
  }
})()
```

* * *

## 捐款

我们欢迎社区的贡献! 如果您希望为 `@autonomys/auto-utils`请遵循这些准则:

1.  **叉子存储器** (原始内容存档于2018-09-29). on GitHub.
    
2.  **砍断你的叉子** 当地:
    
    ```bash
    git clone https://github.com/your-username/auto-sdk.git
    cd auto-sdk/packages/auto-utils
    ```
    
3.  **安装依赖关系**数字 :
    
    ```bash
    yarn install
    ```
    
4.  **做你的改变** 并确保所有测试通过:
    
    ```bash
    yarn test
    ```
    
5.  **提交更改** 有清晰和描述性的信息.
    
6.  **推到叉子边** 财务报告和审定财务报表 **创建拉动请求** 反对: `main` 原始寄存器的分支.
    

### 代码样式

-   使用 **类型脚本** 所有代码.
-   遵循现有的编码公约.
-   运行 `yarn lint` 确保代码样式的一致性.

### 测试

-   添加任何新特性或错误修正的测试 .
-   确保所有现有的考试通过.

* * *

## 许可证

这个项目根据麻省理工学院的许可证获得许可。 见 [自由主义](https://npmcn.com/package/%40autonomys/LICENSE) 详细文件.

* * *

## 额外资源

-   **自治学院**: 了解更多关于SDK自治及其背后的愿景 [自治学院](https://academy.autonomys.xyz/)。 。 。 .

## 联系人

如果您有任何问题或需要支持,请随意联系:

-   **GitHub 问题**数字 : [GitHub 问题页面](https://github.com/autonomys/auto-sdk/issues)

我们感谢你的反馈和贡献!

## 常见问题

### 如何安装 @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 和提交记录判断。

