New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@decentralchain/bignumber

Package Overview
Dependencies
Maintainers
3
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@decentralchain/bignumber

Official arbitrary-precision BigNumber library for the DecentralChain blockchain SDK — safe arithmetic and byte serialization for token amounts, transaction fees, and on-chain financial computations

latest
Source
npmnpm
Version
1.2.0
Version published
Maintainers
3
Created
Source

DecentralChain

@decentralchain/bignumber

Arbitrary-precision arithmetic for the DecentralChain blockchain ecosystem.

npm license bundle size node

Overview

Part of the DecentralChain SDK.

@decentralchain/bignumber is the official arbitrary-precision number library for the DecentralChain SDK. It provides safe, precise arithmetic for blockchain token amounts, transaction fees, and financial computations that exceed JavaScript's native Number.MAX_SAFE_INTEGER (2⁵³ − 1) limit.

Built on top of the battle-tested bignumber.js engine, this library wraps it with a clean, chainable, immutable API specifically designed for blockchain and decentralized finance (DeFi) use cases — including binary serialization for on-chain transaction encoding.

Installation

npm install @decentralchain/bignumber

Quick Start

import { BigNumber } from '@decentralchain/bignumber';

const amount = new BigNumber('100000000');
const fee = new BigNumber('100000');

const total = amount.add(fee);
console.log(total.toString()); // '100100000'

// Safe comparison without floating-point issues
console.log(amount.gt(fee)); // true
console.log(total.eq('100100000')); // true

// Byte serialization for blockchain transactions
const bytes = amount.toBytes(); // Uint8Array(8)
const restored = BigNumber.fromBytes(bytes);
console.log(restored.eq(amount)); // true

DecentralChain Integration

This library is a foundational component of the DecentralChain SDK and is used across the ecosystem wherever precise numeric handling is required.

Role in the SDK

The DecentralChain blockchain uses 8 decimal places of precision for token amounts. All on-chain values are represented as integers (e.g., 1 DC = 100000000 smallest units). @decentralchain/bignumber is purpose-built for this model:

import { BigNumber } from '@decentralchain/bignumber';

// Convert a human-readable amount to the on-chain integer representation
const DECIMALS = 8;
const humanAmount = '1.5'; // 1.5 DC
const onChainAmount = new BigNumber(humanAmount)
  .mul(new BigNumber(10).pow(DECIMALS));

console.log(onChainAmount.toString()); // '150000000'

Transaction Building

When constructing DecentralChain transactions, amounts and fees must be serialized as signed 64-bit big-endian byte arrays for inclusion in the binary transaction body. The toBytes() and fromBytes() methods handle this encoding directly:

import { BigNumber } from '@decentralchain/bignumber';

// Serialize a transaction amount for the wire format
const amount = new BigNumber('1000000000'); // 10 DC
const amountBytes = amount.toBytes(); // Uint8Array(8) — ready for transaction body

// Deserialize bytes received from the blockchain
const decoded = BigNumber.fromBytes(amountBytes);
console.log(decoded.toString()); // '1000000000'

Common Blockchain Operations

import { BigNumber } from '@decentralchain/bignumber';

// Fee calculation with safe arithmetic
const baseFee = new BigNumber('100000');
const extraFee = new BigNumber('400000');
const totalFee = baseFee.add(extraFee); // '500000'

// Balance validation before transfer
const balance = new BigNumber('50000000000');
const transferAmount = new BigNumber('10000000000');
if (balance.gte(transferAmount.add(totalFee))) {
  console.log('Sufficient balance for transfer');
}

// Aggregate multiple token amounts
const amounts = ['100000000', '250000000', '75000000'];
const total = BigNumber.sum(...amounts); // '425000000'

// Validate that a value fits in a signed 64-bit integer (required by protocol)
const value = new BigNumber('9223372036854775807');
console.log(value.isInSignedRange()); // true — safe for on-chain use

Architecture

┌─────────────────────────────────────────────────────┐
│                 Your Application                     │
├─────────────────────────────────────────────────────┤
│              DecentralChain SDK                      │
│  ┌──────────┐  ┌──────────┐  ┌───────────────────┐  │
│  │  Crypto  │  │   Core   │  │  @decentralchain/ │  │
│  │  module  │  │  module  │  │    bignumber       │  │
│  └──────────┘  └──────────┘  └───────────────────┘  │
├─────────────────────────────────────────────────────┤
│          DecentralChain Blockchain Network           │
└─────────────────────────────────────────────────────┘

@decentralchain/bignumber sits at the data layer of the SDK, ensuring that every numeric value flowing between your application and the blockchain is handled with full precision and correct binary encoding.

API Reference

Constructor

new BigNumber(value)

Creates a new BigNumber instance.

ParameterTypeDescription
valuestring | number | BigNumberThe numeric value
new BigNumber('9223372036854775807');
new BigNumber(42);
new BigNumber(existingBigNumber);

Arithmetic Methods

All arithmetic methods return a new BigNumber instance (immutable).

MethodSignatureDescription
add(other) → BigNumberAddition
sub(other) → BigNumberSubtraction
mul(other) → BigNumberMultiplication
div(other) → BigNumberDivision
mod(other) → BigNumberModulo
pow(exp) → BigNumberExponentiation
sqrt() → BigNumberSquare root
abs() → BigNumberAbsolute value
roundTo(decimals?, mode?) → BigNumberRound to decimal places
clone() → BigNumberDeep copy
const a = new BigNumber('1000000000000000000');
const b = new BigNumber('2');

a.add(b); // 1000000000000000002
a.mul(b); // 2000000000000000000
a.pow(2); // 1000000000000000000000000000000000000
a.roundTo(2, BigNumber.ROUND_MODE.ROUND_HALF_UP);

Comparison Methods

MethodSignatureDescription
eq(other) → booleanEqual to
lt(other) → booleanLess than
gt(other) → booleanGreater than
lte(other) → booleanLess than or equal
gte(other) → booleanGreater than or equal

Inspection Methods

MethodSignatureDescription
isNaN() → booleanCheck if NaN
isFinite() → booleanCheck if finite
isZero() → booleanCheck if zero
isPositive() → booleanCheck if positive
isNegative() → booleanCheck if negative
isInt() → booleanCheck if integer
isEven() → booleanCheck if even
isOdd() → booleanCheck if odd
isInSignedRange() → booleanWithin signed 64-bit range
isInUnsignedRange() → booleanWithin unsigned 64-bit range
getDecimalsCount() → number | nullNumber of decimal places

Conversion Methods

MethodSignatureDescription
toString(base?) → stringString representation (optional base)
toFixed(dp?, mode?) → stringFixed-point string
toFormat(dp?, mode?, fmt?) → stringFormatted string with separators
toNumber() → numberJavaScript number (may lose precision!)
toJSON() → stringJSON serialization
valueOf() → stringPrimitive value
const n = new BigNumber('1000000.123');
n.toString(); // '1000000.123'
n.toString(16); // hex representation
n.toFixed(2); // '1000000.12'
n.toFormat(); // '1,000,000.123'

Byte Serialization

For blockchain wire format encoding/decoding.

toBytes(options?)

OptionTypeDefaultDescription
isSignedbooleantrueTwo's complement signed encoding
isLongbooleantrueFixed 8-byte output

BigNumber.fromBytes(bytes, options?)

Inverse of toBytes. Same options.

const value = new BigNumber('9223372036854775807'); // Long.MAX_VALUE
const bytes = value.toBytes(); // Uint8Array [127, 255, 255, 255, 255, 255, 255, 255]
BigNumber.fromBytes(bytes).eq(value); // true

Static Methods

MethodSignatureDescription
BigNumber.max(...values) → BigNumberMaximum of values
BigNumber.min(...values) → BigNumberMinimum of values
BigNumber.sum(...values) → BigNumberSum of values
BigNumber.toBigNumber(value) → BigNumberConvert value(s) to BigNumber
BigNumber.isBigNumber(value) → booleanType guard

Static Constants

ConstantValueDescription
BigNumber.MIN_VALUE-9223372036854775808Signed 64-bit minimum
BigNumber.MAX_VALUE9223372036854775807Signed 64-bit maximum
BigNumber.MIN_UNSIGNED_VALUE0Unsigned 64-bit minimum
BigNumber.MAX_UNSIGNED_VALUE18446744073709551615Unsigned 64-bit maximum

Configuration

// Change number formatting globally
BigNumber.config.set({
  FORMAT: {
    groupSeparator: ' ',
    decimalSeparator: ',',
  },
});

new BigNumber('1000000.5').toFormat(); // '1 000 000,5'

Rounding Modes

Available via BigNumber.ROUND_MODE:

ModeDescription
ROUND_UPAway from zero
ROUND_DOWNTowards zero
ROUND_CEILTowards +Infinity
ROUND_FLOORTowards -Infinity
ROUND_HALF_UPTo nearest, 0.5 away from zero
ROUND_HALF_DOWNTo nearest, 0.5 towards zero
ROUND_HALF_EVENTo nearest, 0.5 to even (banker's rounding)
ROUND_HALF_CEILTo nearest, 0.5 towards +Infinity
ROUND_HALF_FLOORTo nearest, 0.5 towards -Infinity

Development

Prerequisites

  • Node.js >= 24 (see .node-version)
  • npm >= 11

Setup

git clone https://github.com/Decentral-America/bignumber.git
cd bignumber
npm install

Scripts

CommandDescription
npm run buildBuild distribution files
npm testRun tests with Vitest
npm run test:watchTests in watch mode
npm run test:coverageTests with V8 coverage
npm run typecheckTypeScript type checking
npm run lintESLint
npm run lint:fixESLint with auto-fix
npm run formatFormat with Prettier
npm run validateFull CI validation pipeline
npm run bulletproofFormat + lint fix + typecheck + test
npm run bulletproof:checkCI-safe: check format + lint + tc + test

Quality Gates

This project enforces strict quality standards to ensure reliability for production blockchain applications:

  • Coverage: 90%+ threshold for branches, functions, lines, and statements
  • Bundle size: Enforced via size-limit to keep the library lightweight
  • Type exports: Validated with publint and @arethetypeswrong/cli to ensure correct type resolution across all module systems
  • Formatting: Prettier enforced on commit via Husky + lint-staged
  • CI Pipeline: Automated testing on every push and pull request via GitHub Actions

Technology Stack

CategoryTechnology
LanguageTypeScript 5.9 (strict mode)
RuntimeNode.js >= 24
Module FormatPure ESM
Build Tooltsup
Test FrameworkVitest
LinterESLint (flat config)
FormatterPrettier
CI/CDGitHub Actions
PackageDescription
@decentralchain/ts-typesCore TypeScript type definitions
@decentralchain/marshallBinary serialization for blockchain data
@decentralchain/ts-lib-cryptoCryptographic primitives
@decentralchain/transactionsTransaction builder

Contributing

See CONTRIBUTING.md for development setup and guidelines.

Security

See SECURITY.md for the security policy and reporting instructions.

License

MITDecentralChain

Keywords

bignumber

FAQs

Package last updated on 11 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts