반응형

 

🧮 BigNumber

BigNumber은 일반 JavaScript 숫자로 표현하기에는 너무 큰 큰 숫자로 작업할 수 있는 방법을 제공하는 ethers.js 라이브러리의 모듈입니다. BigNumber은 최대 256비트의 정밀도로 임의로 큰 정수를 나타내는 불변 개체입니다. 자바스크립트의 기본 자료형의 연산은 정확하지 않은 경우가 많기 때문에 높은 수준의 정밀도가 필요한 Ether와 같은 암호화폐를 다룰 때는 BigNumber을 통해 정확한 연산이 가능하게 됩니다.

 

🚀 사용 방법

const { BigNumber } = require('ethers');

const bigNumber = BigNumber.from('12345678901234567890');
console.log(bigNumber.toString()); // '12345678901234567890

BigNumber.from(BigNumberish) → BigNumber
BigNumber.from은 BigNumberish에 대한 BigNumber 인스턴스를 반환하는 메서드입니다.

BigNumberish

ethers.js에는 BigNumberish라는 타입이 있으며 아래와 같이 지정될 수 있습니다.

  • string : hexString 또는 10진수 문자열
  • ByteLike : 배열 또는 Uint8Array와 같은 BytesLike 객체
  • BigNumber : BigNumber 인스턴스
  • number : safe range에 있는 자바스크립트 숫자 (Number.MAX_SAFE_INTEGER === 9007199254740991 === 2^53-1)
  • BigInt : 자바스크립트의 BigInt 객체

 

사용 예제

console.log(BigNumber.from('42').toString());
// Output: 42
console.log(BigNumber.from('0x2a').toString());
// Output: 42
console.log(BigNumber.from('-0x2a').toString());
// Output: -42
console.log(BigNumber.from([42]).toString());
// Output: 42
console.log(BigNumber.from(42).toString());
// Output: 42
console.log(BigNumber.from(BigInt(42)).toString());
// Output: 42
console.log(BigNumber.from(Number.MAX_SAFE_INTEGER - 1).toString());
// Output: 9007199254740990

BigNumber 사칙연산 예제

// 10^18 ==> "1000000000000000000"
const bigNumber = BigNumber.from('1000000000000000000');

console.log(bigNumber.add(100).toString());
// Output: "1000000000000000100"
console.log(bigNumber.sub(50).toString());
// Output: "999999999999999950"
console.log(bigNumber.mul(2).toString());
// Output: "2000000000000000000"
console.log(bigNumber.div(3).toString());
// Output: "333333333333333333"
console.log(bigNumber.mul(2).div(2).add(2).sub(2).toString());
// Output: "1000000000000000000"

비교 메서드

BigNumber.eq( otherValue ) ⇒ boolean
Returns true if and only if the value of BigNumber is equal to otherValue.

BigNumber.lt( otherValue ) ⇒ boolean
Returns true if and only if the value of BigNumber < otherValue.

BigNumber.lte( otherValue ) ⇒ boolean
Returns true if and only if the value of BigNumber ≤ otherValue.

BigNumber.gt( otherValue ) ⇒ boolean
Returns true if and only if the value of BigNumber > otherValue.

BigNumber.gte( otherValue ) ⇒ boolean
Returns true if and only if the value of BigNumber ≥ otherValue.

BigNumber.isZero( ) ⇒ boolean
Returns true if and only if the value of BigNumber is zero.

 

🚫 가장 흔한 NUMERIC_FAULT

1. overflow

자바스크립트의 숫자는 IEEE754로 규정된 64비트 부동소수점 숫자를 사용하여 값을 나타내는데 결과적으로 9,007,199,254,740,991 이상의 값부터는 오차가 있으며, 안전 범위를 벗어난 숫자를 사용하는 것을 방지하기 위해 overflow 오류를 발생시킵니다.

 

2. underflow

underflow오류는 값의 정밀도를 현재 데이터 유형으로 안전하게 표현할 수 없을 때 발생하는 오류입니다.

  • BigNumber은 소수점이 있는 숫자를 생성할 수 없습니다.

  • utils.parseUnits(value, decimal)에서 decimal보다 긴 소수점 자릿수를 가진 value를 생성할 수 없습니다.

 

3. Division by zero

0으로 나누려고 할 때 에러가 발생합니다.

 

 

💡 추가로 알아두면 좋은 정보

단위

1이더 = 1000000000000000000 Wei (0이 18개)
1이더 = 1000000000000000 Kwei (0이 15개)
1이더 = 1000000000000 Mwei (0이 12개)
1이더 = 1000000000 Gwei (0이 9개)
1이더 = 1000000 Szabo
1이더 = 1000 Finney
1이더 = 0.001 Kether
1이더 = 0.000001 Mether
1이더 = 0.000000001 Gether
1이더 = 0.000000000001 Tether

ethers.utils 라이브러리 내에 구현되어 있는 메서드 캡처

 

1.parseUnits(value: string, decimals) → BigNumber

parseUnits 함수는 value 문자열과 숫자를 인수로 사용하고 소수 자릿수를 기준으로 토큰의 최소 단위로 입력 값을 나타내는 BigNumber 객체를 반환합니다.

console.log(utils.parseUnits('1.5', 18).toString());
// Output: "1500000000000000000"

parseUnits('1.5', 18)은 1500000000000000000(Wei의 1.5 ETH)인 BigNumber 객체를 반환합니다.

 

2. parseEther(value: string) → BigNumber

parseUnits(value, 18)의 줄임말입니다. value 문자열을 받고 Ether의 최소 단위인 Wei로 나타내는 BigNumber 객체를 반환합니다.

console.log(utils.parseEther('1.5').toString());
// Output: "1500000000000000000"

 

3. formatUnits(value: BigNumberish, decimals) → string

formatUnits 함수는 BigNumberish인 value와 decimals 숫자를 인수로 사용하고 소수 자릿수를 기준으로 토큰의 최대 단위로 입력 값의 문자열 표현을 반환합니다.

console.log(utils.formatUnits('1500000000000000000', 18));
// Output: "1.5"

formatUnits("1500000000000000000", 18)은 값이 "1.5"(1.5 ETH)인 문자열을 반환합니다.

 

4. formatEther(value: BigNumberish) → string

formatEther 함수는 formatUnits(value, 18)의 줄임말입니다. BigNumberish인 value를 인수로 받아 ETH값을 문자열로 표현해 반환합니다

console.log(utils.formatUnits(BigNumber.from('1500000000000000000')));
// Output: "1.5"

 

📚 참고 문헌

https://docs.ethers.org/v5/api/utils/bignumber/

 

BigNumber

Documentation for ethers, a complete, tiny and simple Ethereum library.

docs.ethers.org

https://docs.ethers.org/v5/troubleshooting/errors/#help-NUMERIC_FAULT-overflow

 

Error Codes

Documentation for ethers, a complete, tiny and simple Ethereum library.

docs.ethers.org

https://docs.ethers.org/v5/api/utils/display-logic/#utils-parseUnits

 

Display Logic and Input

Documentation for ethers, a complete, tiny and simple Ethereum library.

docs.ethers.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER#description

 

Number.MAX_SAFE_INTEGER - JavaScript | MDN

The Number.MAX_SAFE_INTEGER static data property represents the maximum safe integer in JavaScript (253 – 1).

developer.mozilla.org

 

 

 

반응형

+ Recent posts