跳到主要内容

API 参考

这是 @ocap/util 包中所有可用工具函数的综合参考。它为数据转换、大数算术、UUID 生成和联合曲线计算提供了实用示例。

数字和 BigNumber 工具

这些函数提供了处理大数并在不同数值表示之间进行转换的稳健方法。

BN

bn.js 库的别名,用于处理任意精度的整数。所有处理大数的函数都接受或返回 BN 实例。

Bignumber Arithmetic

javascript
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

将各种输入类型转换为 BN 实例。它可以处理数字、字符串和十六进制字符串。

参数

  • num number | string | BN (required) — 要转换的值。
  • base number | 'hex' (default: 10) — 转换的数值基数,默认为 10。

返回

  • **** BN — BN 实例。

示例

Converting to BN

javascript
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

检查给定对象是否为 BN 实例。

参数

  • object any (required) — 要检查的对象。

返回

  • **** boolean — 如果对象是 BN 实例,则返回 true,否则返回 false

isBigNumber

检查给定对象是否为 BigNumber 实例(来自不同库,用于兼容性)。

参数

  • object any (required) — 要检查的对象。

返回

  • **** boolean — 如果对象是 BigNumber 实例,则返回 true,否则返回 false

numberToHex

将数字、字符串或 BN 实例转换为以 0x 为前缀的十六进制字符串表示。

参数

  • value string | number | BN (required) — 要转换的值。

返回

  • **** string — 十六进制字符串。

示例

Number to Hex

javascript
import { numberToHex } from '@ocap/util';

console.log(numberToHex(255));      // '0xff'
console.log(numberToHex('15'));     // '0xf'
console.log(numberToHex(-1));       // '-0x1'

hexToNumber

将十六进制字符串转换为标准的 JavaScript number

参数

  • value string | number | BN (required) — 要转换的十六进制值。

返回

  • **** number — 数字表示。

isHex / isHexStrict

  • isHex(str):检查字符串是否为十六进制值。它允许可选的 0x 前缀。
  • isHexStrict(str):检查字符串是否为严格的十六进制值,要求有 0x 前缀。

参数

  • hex string (required) — 要检查的字符串。

返回

  • **** boolean — 如果字符串是符合函数规则的有效十六进制值,则返回 true,否则返回 false

示例

Hex Validation

javascript
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

检查字符串是否以“0x”开头。

参数

  • str string (required) — 要检查的字符串。

返回

  • **** boolean — 如果字符串有“0x”前缀,则返回 true,否则返回 false

stripHexPrefix

如果存在,则从十六进制字符串中移除 0x 前缀。

参数

  • str string (required) — 要处理的字符串。

返回

  • **** string — 不带“0x”前缀的字符串。

示例

Stripping Hex Prefix

javascript
import { stripHexPrefix } from '@ocap/util';

console.log(stripHexPrefix('0xabcdef')); // 'abcdef'
console.log(stripHexPrefix('abcdef'));   // 'abcdef'

编码和解码

用于在不同格式(如 UTF-8、Hex、Base58 和 Base64)之间转换数据的函数。

toHex

自动将几乎任何类型的值(字符串、数字、布尔值、对象、Buffer)转换为其十六进制表示。

参数

  • value any (required) — 要转换的输入值。

返回

  • **** string — 结果十六进制字符串。

示例

Universal Hex Conversion

javascript
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):将 UTF-8 字符串转换为其十六进制表示。
  • hexToUtf8(hex):将十六进制字符串转换回 UTF-8 字符串。

参数

  • str or hex string (required) — 要转换的字符串。

返回

  • **** string — 转换后的字符串。

示例

UTF-8 and Hex Conversion

javascript
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):将字节数组转换为十六进制字符串。
  • hexToBytes(hex):将十六进制字符串转换为字节数组。

参数

  • bytes or hex Array<number> | string (required) — 要转换的数据。

返回

  • **** string | Array<number> — 转换后的数据。

toBase58 / fromBase58

  • toBase58(data):将数据编码为带有“z”前缀的 Base58 字符串。
  • fromBase58(str):将带有“z”前缀的 Base58 字符串解码为 Buffer。

参数

  • data or str any | string (required) — 要编码或解码的数据。

返回

  • **** string | Buffer — 编码后的字符串或解码后的 Buffer。

示例

Base58 Encoding

javascript
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

检查字符串是否为带有“z”前缀的有效 Base58 编码值。

参数

  • data any (required) — 要检查的值。

返回

  • **** boolean — 如果值是有效的 Base58 字符串,则返回 true,否则返回 false

toBase64 / fromBase64

  • toBase64(data):将数据编码为 URL 安全的 Base64 字符串。
  • fromBase64(str):将 URL 安全的 Base64 字符串解码为 Buffer。

参数

  • data or str any | string (required) — 要编码或解码的数据。

返回

  • **** string | Buffer — 编码后的字符串或解码后的 Buffer。

示例

Base64 Encoding

javascript
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'

数据类型转换

toUint8Array

尽力将各种输入类型(Hex、Base58、Buffer、字符串)转换为 Uint8Array

参数

  • v any (required) — 要转换的值。

返回

  • **** Uint8Array — 结果 Uint8Array。

toBuffer

将各种输入类型转换为 Node.js Buffer

参数

  • v any (required) — 要转换的值。

返回

  • **** Buffer — 结果 Buffer。

isUint8Array

验证一个值是否为 Uint8Array

参数

  • value any (required) — 要检查的值。

返回

  • **** boolean — 如果值是 Uint8Array,则返回 true,否则返回 false

Token 单位转换

这些函数对于在 Token 的最小单位(如以太坊中的 wei)与其更易读的表示之间进行转换至关重要。

fromUnitToToken

将一个值从其最小单位(例如,一个 BN 实例)转换为人类可读的十进制字符串。

参数

  • input string | number | BN (required) — 以最小单位表示的值。
  • decimal number (default: 18) — Token 的小数位数。

返回

  • **** string — 人类可读的 Token 数量。

示例

Token Unit Conversion

javascript
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

将人类可读的 Token 数量(作为字符串或数字)转换为其最小单位表示,即一个 BN 实例。

参数

  • input string | number (required) — 人类可读的 Token 数量。
  • decimal number (default: 18) — Token 的小数位数。

返回

  • **** BN — 以最小单位表示的值。

示例

Token to Smallest Unit

javascript
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 工具

用于处理 ArcBlock DID 和地址的辅助函数。

toAddress / toDid

  • toAddress(did):通过移除 did:abt: 前缀,将完整的 DID 字符串(例如 did:abt:z...)转换为其对应的地址。
  • toDid(address):通过添加 did:abt: 前缀,将地址转换为完整的 DID 字符串。

参数

  • did or address string (required) — 要转换的 DID 或地址。

返回

  • **** string — 转换后的地址或 DID。

isSameDid

将两个 DID 字符串转换为地址后,以不区分大小写的方式比较它们是否相等。

参数

  • a string (required) — 要比较的第一个 DID。
  • b string (required) — 要比较的第二个 DID。

返回

  • **** boolean — 如果 DID 相同,则返回 true,否则返回 false

交易工具

formatTxType

将交易类型字符串格式化为 UpperCamelCase(首字母大写的驼峰式命名)。

参数

  • type string (required) — 交易类型字符串(例如 'transfer')。

返回

  • **** string — 格式化后的字符串(例如 'Transfer')。

UUID 工具

UUID

生成一个随机的第 4 版 UUID。

参数

无。

返回

  • **** string — 一个新的 UUID 字符串。

isUUID

检查给定字符串是否为有效的 UUID。

参数

  • str string (required) — 要检查的字符串。

返回

  • **** boolean — 如果字符串是有效的 UUID,则返回 true,否则返回 false

联合曲线计算

这些函数用于根据不同的数学曲线计算铸造或销毁 Token 的价格和成本。这是 Token 经济模型的核心组成部分。

Direction (枚举)

一个在成本计算函数中使用的枚举,用于指定操作的方向。

  • Direction.Mint: 'mint'
  • Direction.Burn: 'burn'

恒定曲线

  • calcConstantPrice({ fixedPrice }):计算价格,该价格始终为 fixedPrice
  • calcConstantCost({ amount, fixedPrice, decimal }):计算成本,即 amount * fixedPrice

calcConstantPrice 的参数

  • fixedPrice string (required) — 每个 Token 的固定价格,以其最小单位表示。

calcConstantCost 的参数

  • amount string (required) — 要铸造/销毁的 Token 数量。
  • fixedPrice string (required) — 每个 Token 的固定价格。
  • decimal number (required) — Token 的小数位数。

返回

  • **** BN — 计算出的价格或成本。

线性曲线

  • calcLinearPrice({ basePrice, slope, currentSupply, decimal }):根据公式 价格 = 基础价格 + 斜率 * 当前供应量 计算价格。
  • calcLinearCost({ amount, currentSupply, basePrice, slope, decimal, direction }):计算沿线性价格曲线铸造或销毁 Token 的积分成本。

calcLinearPrice 的参数

  • basePrice string (required) — Token 的起始价格。
  • slope string (required) — 价格随供应量增加的速率。
  • currentSupply string (required) — Token 的当前总供应量。
  • decimal number (required) — Token 的小数位数。

calcLinearCost 的参数

  • params object (required) — 一个包含计算参数的对象。
    • amount string (required) — Token 的数量。
    • currentSupply string (required) — 当前 Token 供应量。
    • basePrice string (required) — 基础价格。
    • slope string (required) — 价格斜率。
    • decimal number (required) — Token 的小数位数。
    • direction Direction (required) — 操作方向(Direction.MintDirection.Burn)。

返回

  • **** BN — 计算出的价格或成本。

二次曲线

  • calcQuadraticPrice({ basePrice, currentSupply, constant, decimal }):根据公式 价格 = 基础价格 + 当前供应量^2 / 常量 计算价格。
  • calcQuadraticCost({ amount, currentSupply, basePrice, constant, decimal, direction }):计算沿二次价格曲线铸造或销毁 Token 的积分成本。

calcQuadraticPrice 的参数

  • basePrice string (required) — 起始价格。
  • currentSupply string (required) — 当前 Token 供应量。
  • constant string (required) — 一个调节价格曲线的常量。
  • decimal number (required) — Token 的小数位数。

calcQuadraticCost 的参数

  • params object (required) — 一个包含计算参数的对象。
    • amount string (required) — Token 的数量。
    • currentSupply string (required) — 当前 Token 供应量。
    • basePrice string (required) — 基础价格。
    • constant string (required) — 曲线常量。
    • decimal number (required) — Token 的小数位数。
    • direction Direction (required) — 操作方向(Direction.MintDirection.Burn)。

返回

  • **** BN — 计算出的价格或成本。

通用计算器

  • calcPrice({ currentSupply, decimal, curve }):一个分发函数,根据提供的 curve 对象计算当前价格。curve.type 属性('constant''linear''quadratic')决定使用哪种计算方法。
  • calcCost({ amount, decimal, currentSupply, direction, curve }):一个分发函数,根据 curve 对象计算操作的总成本。

calcPrice 的参数

  • currentSupply string (required) — 当前 Token 供应量。
  • decimal number (required) — Token 的小数位数。
  • curve object (required) — 一个包含 type 和其他相关参数的曲线配置对象。

calcCost 的参数

  • amount string (required) — Token 的数量。
  • decimal number (required) — Token 的小数位数。
  • currentSupply string (required) — 当前 Token 供应量。
  • direction Direction (required) — 操作方向。
  • curve object (required) — 一个曲线配置对象。

返回

  • **** BN — 计算出的价格或成本,作为 BN 实例。

示例:使用 calcCost 分发器

Generic Cost Calculator

javascript
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

根据准备金金额和费率计算费用。

参数

  • reserveAmount string (required) — 计算费用的总金额。
  • feeRate string (required) — 以基点表示的费率(例如,'500' 代表 5%)。

返回

  • **** BN — 计算出的费用金额。

异步工具

withRetry

一个高阶函数,它包装一个异步操作,在失败时自动重试。

参数

  • handle () => Promise<T> (required) — 要执行和重试的异步函数。
  • options object — 重试逻辑的配置。
    • retryLimit number (default: 30) — 最大重试次数。
    • backoff object — 指数退避配置。
      • baseDelay number (default: 20) — 基础延迟(毫秒)。
      • maxDelay number (default: 1000) — 最大延迟(毫秒)。
    • shouldRetry (error: unknown) => boolean (default: () => true) — 一个函数,用于根据错误决定是否应尝试重试。
    • onError (error: unknown, attempt: number) => void — 在每次失败尝试时执行的回调函数。

返回

  • **** Promise<T> — 一个 promise,它会解析为 handle 函数的结果。

示例

Auto-Retry Operation

javascript
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();

自定义错误

CustomError / PersistError

扩展了原生 Error 对象的自定义错误类。它们包含用于程序化错误处理的 code 和用于提供额外上下文的 props 对象。PersistError 是一个变体,表示该错误应被持久化。

构造函数参数

  • code string (required) — 错误代码字符串。
  • message string (required) — 错误消息。
  • props object — 与错误相关的附加属性。

哈希

md5

计算给定输入的 MD5 哈希值。

参数

  • data any (required) — 要哈希的数据。

返回

  • **** string — MD5 哈希值,以十六进制字符串表示。