跳到主要內容

API 參考

這是 @ocap/util 套件中所有可用工具函式的綜合參考。它提供了資料轉換、大數運算、UUID 生成和 bonding curve 計算的實用範例。

數字與 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

代幣單位轉換

這些函式對於在代幣的最小單位(如以太坊中的 wei)與其更易於人類閱讀的表示之間進行轉換至關重要。

fromUnitToToken

將一個值從其最小單位(例如,一個 BN 實例)轉換為人類可讀的十進位字串。

參數

  • input string | number | BN (required) — 以其最小單位表示的值。
  • decimal number (default: 18) — 代幣擁有的小數位數。

返回值

  • **** string — 人類可讀的代幣金額。

範例

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

將人類可讀的代幣金額(以字串或數字形式)轉換為其最小單位表示的 BN 實例。

參數

  • input string | number (required) — 人類可讀的代幣金額。
  • decimal number (default: 18) — 代幣擁有的小數位數。

返回值

  • **** 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

Bonding Curve 計算

這些函式用於根據不同的數學曲線計算鑄造或銷毀代幣的價格和成本。這是代幣經濟模型的核心組成部分。

Direction (Enum)

在成本計算函式中用於指定操作方向的列舉。

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

常數曲線

  • calcConstantPrice({ fixedPrice }):計算價格,價格始終為 fixedPrice
  • calcConstantCost({ amount, fixedPrice, decimal }):計算成本,成本為 amount * fixedPrice

calcConstantPrice 的參數

  • fixedPrice string (required) — 每個代幣以其最小單位表示的固定價格。

calcConstantCost 的參數

  • amount string (required) — 要鑄造/銷毀的代幣數量。
  • fixedPrice string (required) — 每個代幣的固定價格。
  • decimal number (required) — 代幣的小數位數。

返回值

  • **** BN — 計算出的價格或成本。

線性曲線

  • calcLinearPrice({ basePrice, slope, currentSupply, decimal }):根據公式 價格 = 基礎價格 + 斜率 * 當前供應量 計算價格。
  • calcLinearCost({ amount, currentSupply, basePrice, slope, decimal, direction }):計算沿著線性價格曲線鑄造或銷毀代幣的積分成本。

calcLinearPrice 的參數

  • basePrice string (required) — 代幣的起始價格。
  • slope string (required) — 價格隨供應量增加的速率。
  • currentSupply string (required) — 代幣當前的總供應量。
  • decimal number (required) — 代幣的小數位數。

calcLinearCost 的參數

  • params object (required) — 一個包含計算參數的物件。
    • amount string (required) — 代幣的數量。
    • currentSupply string (required) — 當前的代幣供應量。
    • basePrice string (required) — 基礎價格。
    • slope string (required) — 價格斜率。
    • decimal number (required) — 代幣的小數位數。
    • direction Direction (required) — 操作方向(Direction.MintDirection.Burn)。

返回值

  • **** BN — 計算出的價格或成本。

二次曲線

  • calcQuadraticPrice({ basePrice, currentSupply, constant, decimal }):根據公式 價格 = 基礎價格 + 當前供應量^2 / 常數 計算價格。
  • calcQuadraticCost({ amount, currentSupply, basePrice, constant, decimal, direction }):計算沿著二次價格曲線鑄造或銷毀代幣的積分成本。

calcQuadraticPrice 的參數

  • basePrice string (required) — 起始價格。
  • currentSupply string (required) — 當前的代幣供應量。
  • constant string (required) — 一個調節價格曲線的常數。
  • decimal number (required) — 代幣的小數位數。

calcQuadraticCost 的參數

  • params object (required) — 一個包含計算參數的物件。
    • amount string (required) — 代幣的數量。
    • currentSupply string (required) — 當前的代幣供應量。
    • basePrice string (required) — 基礎價格。
    • constant string (required) — 曲線常數。
    • decimal number (required) — 代幣的小數位數。
    • 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) — 當前的代幣供應量。
  • decimal number (required) — 代幣的小數位數。
  • curve object (required) — 一個帶有 type 和其他相關參數的曲線設定物件。

calcCost 的參數

  • amount string (required) — 代幣的數量。
  • decimal number (required) — 代幣的小數位數。
  • currentSupply string (required) — 當前的代幣供應量。
  • 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 雜湊值,以十六進位字串形式表示。