これは、@ocap/util パッケージで利用可能なすべてのユーティリティ関数の包括的なリファレンスです。データ変換、大きな数値の算術、UUIDの生成、ボンディングカーブの計算に関する実用的な例を提供します。
数値とBigNumberユーティリティ
これらの関数は、大きな数値を扱い、異なる数値表現間で変換するための堅牢な方法を提供します。
BN
bn.js ライブラリのエイリアスで、任意精度の整数を扱うために使用されます。大きな数値を扱うすべての関数は、BN インスタンスを受け入れるか、返します。
Bignumber Arithmetic
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 インスタンスに変換します。数値、文字列、16進文字列を扱うことができます。
パラメータ
- num
number | string | BN(required) — 変換する値。 - base
number | 'hex'(default:10) — 変換の基数。デフォルトは10です。
戻り値
- ****
BN— BNインスタンス。
例
Converting to BN
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 プレフィックス付きの16進数文字列表現に変換します。
パラメータ
- value
string | number | BN(required) — 変換する値。
戻り値
- ****
string— 16進数文字列。
例
Number to Hex
import { numberToHex } from '@ocap/util';
console.log(numberToHex(255)); // '0xff'
console.log(numberToHex('15')); // '0xf'
console.log(numberToHex(-1)); // '-0x1'hexToNumber
16進数文字列を標準のJavaScriptの number に変換します。
パラメータ
- value
string | number | BN(required) — 変換する16進数値。
戻り値
- ****
number— 数値表現。
isHex / isHexStrict
isHex(str): 文字列が16進数値であるかどうかをチェックします。オプションの0xプレフィックスを許可します。isHexStrict(str): 文字列が厳密な16進数値であるかどうかをチェックし、0xプレフィックスを要求します。
パラメータ
- hex
string(required) — チェックする文字列。
戻り値
- ****
boolean— 文字列が関数のルールに従って有効な16進数値である場合はtrueを、そうでない場合はfalseを返します。
例
Hex Validation
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')); // falseisHexPrefixed
文字列が '0x' で始まるかどうかをチェックします。
パラメータ
- str
string(required) — チェックする文字列。
戻り値
- ****
boolean— 文字列に '0x' プレフィックスがある場合はtrueを、そうでない場合はfalseを返します。
stripHexPrefix
16進数文字列から 0x プレフィックスが存在する場合に削除します。
パラメータ
- str
string(required) — 処理する文字列。
戻り値
- ****
string— '0x' プレフィックスのない文字列。
例
Stripping Hex Prefix
import { stripHexPrefix } from '@ocap/util';
console.log(stripHexPrefix('0xabcdef')); // 'abcdef'
console.log(stripHexPrefix('abcdef')); // 'abcdef'エンコーディングとデコーディング
UTF-8、Hex、Base58、Base64などの異なる形式間でデータを変換するための関数です。
toHex
ほぼすべてのタイプの値(文字列、数値、ブール値、オブジェクト、Buffer)をその16進数表現に自動的に変換します。
パラメータ
- value
any(required) — 変換する入力値。
戻り値
- ****
string— 結果の16進数文字列。
例
Universal Hex Conversion
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文字列をその16進数表現に変換します。hexToUtf8(hex): 16進数文字列をUTF-8文字列に戻します。
パラメータ
- str or hex
string(required) — 変換する文字列。
戻り値
- ****
string— 変換された文字列。
例
UTF-8 and Hex Conversion
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): バイト配列を16進数文字列に変換します。hexToBytes(hex): 16進数文字列をバイト配列に変換します。
パラメータ
- 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
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
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 インスタンス)から人間が読みやすい10進数の文字列に変換します。
パラメータ
- input
string | number | BN(required) — 最小単位での値。 - decimal
number(default:18) — トークンが持つ小数点以下の桁数。
戻り値
- ****
string— 人間が読みやすいトークンの量。
例
Token Unit Conversion
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
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文字列(例:did:abt:z...)を、did:abt:プレフィックスを削除して対応するアドレスに変換します。toDid(address): アドレスをdid:abt:プレフィックスを追加して完全なDID文字列に変換します。
パラメータ
- did or address
string(required) — 変換するDIDまたはアドレス。
戻り値
- ****
string— 変換されたアドレスまたはDID。
isSameDid
2つのDID文字列をアドレスに変換した後、大文字と小文字を区別せずに等しいかどうかを比較します。
パラメータ
- a
string(required) — 比較する最初のDID。 - b
string(required) — 比較する2番目の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を返します。
ボンディングカーブ計算
これらの関数は、異なる数学的曲線に基づいてトークンを発行または焼却するための価格とコストを計算するために使用されます。これはトークノミクスモデルの中核となるコンポーネントです。
Direction (Enum)
コスト計算関数で使用される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 }):Price = basePrice + slope * currentSupplyの式に基づいて価格を計算します。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.MintまたはDirection.Burn)。
- amount
戻り値
- ****
BN— 計算された価格またはコスト。
二次曲線
calcQuadraticPrice({ basePrice, currentSupply, constant, decimal }):Price = basePrice + currentSupply^2 / constantの式に基づいて価格を計算します。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.MintまたはDirection.Burn)。
- amount
戻り値
- ****
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
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) — ベーシスポイント単位の手数料率(例: 5%の場合は '500')。
戻り値
- ****
BN— 計算された手数料額。
非同期ユーティリティ
withRetry
非同期操作をラップし、失敗時に自動的に再試行する高階関数です。
パラメータ
- handle
() => Promise<T>(required) — 実行および再試行する非同期関数。 - options
object— 再試行ロジックの設定。- retryLimit
number(default:30) — 最大再試行回数。 - backoff
object— 指数バックオフ設定。- baseDelay
number(default:20) — ミリ秒単位の基本遅延。 - maxDelay
number(default:1000) — ミリ秒単位の最大遅延。
- baseDelay
- shouldRetry
(error: unknown) => boolean(default:() => true) — エラーに基づいて再試行すべきかどうかを判断する関数。 - onError
(error: unknown, attempt: number) => void— 失敗した試行ごとに実行されるコールバック関数。
- retryLimit
戻り値
- ****
Promise<T>—handle関数の結果で解決されるプロミス。
例
Auto-Retry Operation
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— 16進数文字列としてのMD5ハッシュ。