How to use the BigNumber function from bignumber.js

Find comprehensive JavaScript bignumber.js.BigNumber code examples handpicked from public code repositorys.

Bignumber.js.BigNumber is a JavaScript library that allows for precise mathematical operations with very large or very small numbers.

329
330
331
332
333
334
335
336
337
338
339
 More info: https://en.bitcoin.it/wiki/Target
 */


exports.bignumFromBitsBuffer = function (bitsBuff) {
  var numBytes = bitsBuff.readUInt8(0);
  var bigBits = new BigNumber("0x" + bitsBuff.slice(1).toString("hex"));
  var target = bigBits.times(
    new BigNumber(2).pow(new BigNumber(8).times(numBytes - 3))
  );
  return target;
fork icon3
star icon2
watch icon2

249
250
251
252
253
254
255
256
257
258

//Check if share is a block candidate (matched network difficulty)
//console.log("in jobManager, coinbase buffer:" + coinbaseBuffer.toString('hex'));
console.log("target: ", job.target.toString());
console.log("header bignum:", headerBigNum.toNumber());
if (new BigNumber(job.target.toString()).gte(headerBigNum)) {
  blockHex = job
    .serializeBlock(headerBuffer, coinbaseBuffer)
    .toString("hex");
  // print binary
fork icon3
star icon2
watch icon2

+ 17 other calls in file

How does bignumber.js.BigNumber work?

Bignumber.js.BigNumber works by representing numbers as strings of digits, rather than as binary numbers like the built-in JavaScript Number type. This allows Bignumber.js to support much larger numbers with greater precision, as it can handle arbitrarily long strings of digits without rounding or truncating. The library also includes a variety of methods for performing mathematical operations on these string representations of numbers, such as addition, subtraction, multiplication, and division, as well as more advanced operations like exponentiation and trigonometric functions. Bignumber.js also provides options for configuring the precision and rounding behavior of these operations, allowing developers to tailor the library to their specific needs.

10
11
12
13
14
15
16
17
18
19
 * Returns the UTXO balance
 * @returns UTXO balance
 */
async getUTXOBalance() {
    const address = await this.wallet.get(0).getAddress();
    return new bignumber_js_1.BigNumber(await this.wallet.get(0).client.address.getBalance(address));
}
/**
 * Get balance of specified token
 * @param symbol Symbol of the dToken
fork icon0
star icon0
watch icon1

+ 11 other calls in file

70
71
72
73
74
75
76
77
78
        this.transaction = new transaction_1.Transaction(wallet);
    }
    async run() {
        console.log(Helper.getISODate() + ' ' + text_json_1.default.UTXO_BALANCE + await this.transaction.getUTXOBalance()); //Output UTXO balance
        console.log(Helper.getISODate() + ' ' + text_json_1.default.TOKEN_BALANCE + await this.transaction.getTokenBalance('DFI', new bignumber_js_1.BigNumber(0))); //Output token balance
        console.log(Helper.getISODate() + ' ' + text_json_1.default.UTXO_TO_ACCOUNT + await this.transaction.utxoToAccount(new bignumber_js_1.BigNumber(500), new bignumber_js_1.BigNumber(0.1))); //UTXO to Account
    }
}
exports.Bot = Bot;
fork icon0
star icon0
watch icon1

+ 7 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Import the BigNumber.js library
const BigNumber = require("bignumber.js");

// Create two BigNumber objects with very large numbers
const num1 = new BigNumber("123456789012345678901234567890");
const num2 = new BigNumber("987654321098765432109876543210");

// Perform some mathematical operations with these numbers
const sum = num1.plus(num2);
const difference = num1.minus(num2);
const product = num1.times(num2);
const quotient = num1.dividedBy(num2);

// Output the results
console.log("Sum:", sum.toString());
console.log("Difference:", difference.toString());
console.log("Product:", product.toString());
console.log("Quotient:", quotient.toString());

In this example, we create two BigNumber objects (num1 and num2) with very large numbers. We then use the plus(), minus(), times(), and dividedBy() methods to perform basic arithmetic operations with these numbers. Finally, we output the results of these operations using the toString() method to convert the BigNumber objects back to regular JavaScript strings. Note that without Bignumber.js, JavaScript would not be able to perform accurate calculations with these very large numbers, and may return incorrect results due to limitations with its built-in Number type.

21
22
23
24
25
26
27
28
29
30
 * @returns first appearance of the dToken will be returned
 */
async getTokenBalance(symbol, minBalance) {
    const address = await this.wallet.get(0).getAddress();
    const tokenList = await this.wallet.get(0).client.address.listToken(address);
    const token = tokenList.find((token) => { return token.isDAT && token.symbol === symbol && new bignumber_js_1.BigNumber(token.amount).gte(minBalance); });
    if (token === undefined) {
        return undefined;
    }
    else {
fork icon0
star icon0
watch icon1

+ 39 other calls in file

30
31
32
33
34
35
36
37
38
39
    .get(0)
    .client.address.listToken(address);
const token = tokenList.find((token) => {
    return (token.isDAT &&
        token.symbol === symbol &&
        new bignumber_js_1.BigNumber(token.amount).gte(minBalance));
});
if (token === undefined) {
    return undefined;
}
fork icon0
star icon0
watch icon1

+ 89 other calls in file

76
77
78
79
80
81
82
83
84
85
}
else if (tokenASymbol === poolData.tokenB.symbol) {
    tokenBAmount = new bignumber_js_1.BigNumber(tokenAAmount.toNumber() * Number(poolData.priceRatio.ab));
    if (tokenBAmount > tokenBBalance) {
        tokenBAmount = tokenBBalance;
        tokenAAmount = new bignumber_js_1.BigNumber(tokenBAmount.toNumber() * Number(poolData.priceRatio.ba));
    }
    console.log(text_json_1.default.ADD_LIQUIDITY + ' ' + tokenBSymbol + '-' + tokenASymbol + ' with ' +
        tokenBAmount + ' ' + tokenBSymbol + ' and ' + tokenAAmount + ' ' + tokenASymbol);
    return await this.sendTx(() => {
fork icon0
star icon0
watch icon1

+ 59 other calls in file

72
73
74
75
76
77
78
79
80
81
    this.transaction = new transaction_1.Transaction(wallet);
    this.sequencer = new sequencer_1.Sequencer(this.transaction);
}
async run() {
    console.log(Helper.getISODate() + ' ' + text_json_1.default.UTXO_BALANCE + ': ' + await this.sequencer.transaction.getUTXOBalance()); //Output UTXO balance
    console.log(Helper.getISODate() + ' ' + text_json_1.default.TOKEN_BALANCE + ': ' + await this.sequencer.transaction.getTokenBalance('DFI', new bignumber_js_1.BigNumber(0))); //Output token balance
    //await this.sequencer.sendTx(() => {return this.transaction.utxoToAccount(new BigNumber(2000),new BigNumber(0.1))},Text.UTXO_TO_ACCOUNT)
    //await this.sequencer.sendTx(() => {return this.transaction.accountToUTXO(new BigNumber(500),new BigNumber(0))},Text.ACCOUNT_TO_UTXO)
    //await this.sequencer.sendTx(() => {return this.transaction.swapToken('DFI',new BigNumber(1000),'DUSD')},Text.SWAP)
    await this.sequencer.addPoolLiquidity('DFI', 'DUSD', new bignumber_js_1.BigNumber(2000));
fork icon0
star icon0
watch icon1

+ 19 other calls in file

121
122
123
124
125
126
127
128
129
130
        let dustToken = dustTokenList[i];
        if (Number(dustToken.amount) < Number(dustTokenMinBalance[i])) {
            console.log(Helper.getISODate() + ' ' + text_json_1.default.NO_ENOUGH_BALANCE + ' of token ' + dustToken.symbol);
        }
        else if (dustToken.isDAT && Number(dustToken.amount) > dustTokenMinBalance[i].toNumber()) {
            returnValue = returnValue && await this.sendTx(() => { return this.transaction.swapToken(dustToken.symbol, new bignumber_js_1.BigNumber(0.0001), outputTokenSymbol); }, text_json_1.default.SWAP + ' ' + dustToken.symbol + ' to ' + outputTokenSymbol);
        }
    }
    return returnValue;
}
fork icon0
star icon0
watch icon2

+ 13 other calls in file

80
81
82
83
84
85
86
87
88
89
        //await this.sequencer.sendTx(() => {return this.transaction.swapToken('DFI',new BigNumber(1000),'EUROC')},Text.SWAP)
        //await this.sequencer.addPoolLiquidity('EUROC','DFI',new BigNumber(2000))
        //Task: Collect crypto dust and reinvest in pool
        //----------------------------------------------
        //1) Swap Crypto dust to Token A
        await this.sequencer.collectCryptoDust(['EUROC', 'DUSD'], [new bignumber_js_1.BigNumber(0.0001), new bignumber_js_1.BigNumber(0.0001)], 'DFI', text_json_1.default.COLLECT_CRYPTO_DUST);
        //2) Swap 50% of DFI to Token B
        //3) Add Token A and Token B to Pool
    }
}
fork icon0
star icon0
watch icon2

+ 3 other calls in file

152
153
154
155
156
157
158
159
160
161
if (tokenABalance < tokenAMinBalance.toNumber()) {
    console.log(Helper.getISODate() + ' ' + text_json_1.default.NOT_ENOUGH_BALANCE + ' of token ' + tokenASymbol);
    return false;
}
if (tokenAAmount.toNumber() > Number(tokenABalance)) {
    tokenAAmount = new bignumber_js_1.BigNumber(Number(tokenABalance));
}
const poolData = await this.transaction.getPoolData(tokenASymbol, tokenBSymbol);
if (tokenASymbol === poolData.tokenA.symbol) {
    if (tokenAAmount.toNumber() * Number(poolData.priceRatio.ba) < Number(tokenBBalance)) {
fork icon0
star icon0
watch icon2

+ 194 other calls in file

51
52
53
54
55
56
57
58
59
60
const saveHeaven = new bignumber_js_1.BigNumber(0.1);
const utxoBalance = await this.getUTXOBalance();
if (utxoBalance.lte(minBalance) || utxoBalance.lte(saveHeaven)) {
    return undefined;
}
amount = new bignumber_js_1.BigNumber(Math.min(amount.toNumber(), utxoBalance.toNumber()) - Math.max(minBalance.toNumber(), saveHeaven.toNumber()));
const script = await this.wallet.get(0).getScript();
const txn = await this.wallet.get(0).withTransactionBuilder().account.utxosToAccount({
    to: [
        {
fork icon0
star icon0
watch icon2

+ 149 other calls in file

84
85
86
87
88
89
90
91
92
93
    await this.sequencer.sendTx(() => { return this.transaction.utxoToAccount(utxoBalance, new bignumber_js_1.BigNumber(1)); }, text_json_1.default.UTXO_TO_ACCOUNT);
    //3) Swap Crypto dust to Token A
    await this.sequencer.collectCryptoDust(['EUROC'], [new bignumber_js_1.BigNumber(10)], 'DFI', text_json_1.default.COLLECT_CRYPTO_DUST);
    //4) Swap 50% of DFI to Token B & Add Token A and Token B to Pool
    await this.sequencer.swapTokenToAddPoolLiquidity('DFI', 'DUSD', new bignumber_js_1.BigNumber(10000), new bignumber_js_1.BigNumber(100), text_json_1.default.SWAP + ' DFI to DUSD');
    let accountDFIBalance = await this.sequencer.transaction.getTokenBalance('DFI', new bignumber_js_1.BigNumber(0));
    await this.sequencer.addPoolLiquidity('DFI', 'DUSD', accountDFIBalance, new bignumber_js_1.BigNumber(45), text_json_1.default.ADD_LIQUIDITY + ' DFI-DUSD');
    console.log(Helper.getISODate() + ' ' + "<<<task finished>>>");
};
//let intervalID: NodeJS.Timeout = setInterval(() => {task()}, 600000)
fork icon0
star icon0
watch icon2

+ 89 other calls in file

83
84
85
86
87
88
89
90
91
92
        //----------------------------------------------
        //1) Swap Crypto dust to Token A
        //await this.sequencer.collectCryptoDust(['EUROC','DUSD'],[new BigNumber(0.0001),new BigNumber(0.0001)],'DFI',Text.COLLECT_CRYPTO_DUST)
        //2) Swap 50% of DFI to Token B
        //await this.sequencer.swapTokenToAddPoolLiquidity('DFI','DUSD',new BigNumber(100))
        await this.sequencer.addPoolLiquidity('DFI', 'DUSD', new bignumber_js_1.BigNumber(100));
        //3) Add Token A and Token B to Pool
    }
}
exports.Bot = Bot;
fork icon0
star icon0
watch icon2

+ 7 other calls in file

129
130
131
132
133
134
135
136
137
138
async swapTokenToAddPoolLiquidity(tokenASymbol, tokenBSymbol, tokenAAmount) {
    let returnValue = true;
    const tokenAData = (await this.transaction.getAddressTokenData([tokenASymbol]))[0];
    const tokenBData = (await this.transaction.getAddressTokenData([tokenBSymbol]))[0];
    if (tokenAAmount.toNumber() > Number(tokenAData.amount)) {
        tokenAAmount = new bignumber_js_1.BigNumber(Number(tokenAData.amount));
    }
    const poolData = await this.transaction.getPoolData(tokenASymbol, tokenBSymbol);
    if (tokenASymbol === poolData.tokenA.symbol) {
        if (tokenAAmount.toNumber() * Number(poolData.priceRatio.ba) < Number(tokenBData.amount)) {
fork icon0
star icon0
watch icon2

+ 35 other calls in file