// from ripple-lib-extensions
function parseQuality(bookDirectory, base, counter) {
  var qualityHex = bookDirectory.substring(bookDirectory.length - 16);
  var mantissa = new BigNumber(qualityHex.substring(2), 16);
  var offset = parseInt(qualityHex.substring(0, 2), 16) - 100;
  var quality = mantissa.toString() + 'e' + offset.toString();
  return adjustQualityForXRP(quality, base, counter);
}
Пример #2
0
var getPaymentStatus = function(payment, confirmations, invoice) {
  confirmations = confirmations ? confirmations : 0; // Pending if there are no confs
  var minConfirmations = invoice.min_confirmations;
  var status = payment.status;
  var confirmationsMet = Number(confirmations) >= Number(minConfirmations);
  var expectedAmount = new BigNumber(payment.expected_amount);
  var amountPaid = new BigNumber(payment.amount_paid);
  if (confirmations === -1) {
    status = 'invalid';
  }
  else if (amountPaid.greaterThan(0) && !confirmationsMet) {
    status = 'pending';
  }
  else if (confirmationsMet) {
    var isUSD = invoice.currency.toUpperCase() === 'USD';
    var closeEnough = false;
    if (isUSD) {
      var actualPaid = new BigNumber(payment.amount_paid).times(payment.spot_rate);
      var expectedPaid = new BigNumber(payment.expected_amount).times(payment.spot_rate);
      actualPaid = roundToDecimal(actualPaid.valueOf(), 2);
      expectedPaid = roundToDecimal(expectedPaid.valueOf(), 2);
      closeEnough = new BigNumber(actualPaid).equals(expectedPaid);
    }
    if(amountPaid.equals(expectedAmount) || closeEnough) {
      status = 'paid';
    }
    else if (amountPaid.lessThan(expectedAmount)) {
      status = 'partial';
    }
    else if (amountPaid.greaterThan(expectedAmount)) {
      status = 'overpaid';
    }
  }
  return status;
};
Пример #3
0
 function(cb) {
   // Create New Invoice
   invoice._id = helper.pseudoRandomHex(32);
   invoice.api_key = undefined;
   invoice.created = new Date().getTime();
   invoice.type = 'invoice';
   var invoiceTotal = new BigNumber(0);
   invoice.line_items.forEach(function(item) {
     var lineCost = new BigNumber(item.amount).times(item.quantity);
     invoiceTotal = invoiceTotal.plus(lineCost);
   });
   var isUSD = invoice.currency.toUpperCase() === 'USD';
   var discountTotal = new BigNumber(0);
   if (invoice.discounts) {
     invoice.discounts.forEach(function(item) {
       var roundedAmount = 0;
       if (item.amount) {
         roundedAmount = isUSD ? helper.roundToDecimal(item.amount, 2) : item.amount;
       }
       else if (item.percentage) {
         var percentage = new BigNumber(item.percentage).dividedBy(100);
         var discountAmount = Number(invoiceTotal.times(percentage).valueOf());
         roundedAmount = isUSD ? helper.roundToDecimal(discountAmount, 2) : discountAmount;
       }
       discountTotal = discountTotal.plus(roundedAmount);
     });
   }
   invoiceTotal = invoiceTotal.minus(discountTotal);
   invoice.invoice_total = Number(invoiceTotal.valueOf());
   invoice.invoice_total = isUSD ? helper.roundToDecimal(invoice.invoice_total, 2) : Number(invoice.invoice_total);
   if (invoice.text) {
     invoice.text = sanitizeHtml(invoice.text); // remove hostile elements
   }
   baronDb.insert(invoice, cb);
 },
  /**
   * @param {Object} query
   * @param {String} query.sourceLedger
   * @param {String} query.sourceAmount
   * @param {String} query.destinationLedger
   * @param {String} query.destinationAmount
   * @returns {Quote}
   */
  * getQuote (query) {
    const info = {}
    const _nextHop = this._findNextHop(query)
    if (!_nextHop) throwAssetsNotTradedError()
    if (query.sourceAmount) {
      const amount = new BigNumber(_nextHop.finalAmount)
      const amountWithSlippage = amount.times(1 - this.slippage)
      _nextHop.finalAmount = amountWithSlippage.toString()
      info.slippage = (amount - amountWithSlippage).toString()
    } else { // fixed destinationAmount
      const amount = new BigNumber(_nextHop.sourceAmount)
      const amountWithSlippage = amount.times(1 + this.slippage)
      _nextHop.sourceAmount = amountWithSlippage.toString()
      info.slippage = (amount - amountWithSlippage).toString()
    }
    // Round in our favor to ensure that the adjustments don't fall off.
    const nextHop = yield this._roundHop(_nextHop, 'up', 'down')

    const quote = {
      source_connector_account:
        this.ledgers.getLedger(nextHop.sourceLedger).getAccount(),
      source_ledger: nextHop.sourceLedger,
      source_amount: nextHop.sourceAmount,
      destination_ledger: nextHop.finalLedger,
      destination_amount: nextHop.finalAmount,
      _hop: nextHop
    }

    if (query.explain) {
      quote.additional_info = _.assign({}, nextHop.additionalInfo, info)
    }

    return quote
  }
Пример #5
0
var getTotalPaid = function(invoice, paymentsArr) {
  var isUSD = invoice.currency.toUpperCase() === 'USD';
  var totalPaid = new BigNumber(0);
  paymentsArr.forEach(function(payment) {
    if (payment.status.toLowerCase() === 'invalid') {
      return;
    }
    var paidAmount = payment.amount_paid;
    if (paidAmount) {
      paidAmount = new BigNumber(paidAmount);
      // If invoice is in USD then we must multiply the amount paid (BTC) by the spot rate (USD)
      if (isUSD) {
        var usdAmount = helper.roundToDecimal(paidAmount.times(payment.spot_rate).valueOf(), 2);
        totalPaid = totalPaid.plus(usdAmount);
      }
      else {
        totalPaid = totalPaid.plus(paidAmount);
      }
    }
  });
  totalPaid = Number(totalPaid.valueOf());
  if (isUSD) {
    totalPaid = helper.roundToDecimal(totalPaid, 2);
  }
  else if (helper.decimalPlaces(totalPaid) > 8) {
    totalPaid = helper.roundToDecimal(totalPaid, 8);
  }
  return totalPaid;
};
export function best_r(number) {
  number = new BigNumber(number);
  var a;
  var f;
  var fractions = [
    [new BigNumber(0), new BigNumber(1)],
    [new BigNumber(1), new BigNumber(0)]
  ];
  var i = 2;
  while (true) {
    if (number.gt(MAX_INT)) {
      break;
    }
    a = number.floor();
    f = number.sub(a);
    var h = a.mul(fractions[i - 1][0]).add(fractions[i - 2][0]);
    var k = a.mul(fractions[i - 1][1]).add(fractions[i - 2][1]);
    if (h.gt(MAX_INT) || k.gt(MAX_INT)) {
      break;
    }
    fractions.push([h, k]);
    if (f.eq(0)) {
      break;
    }
    number = new BigNumber(1).div(f);
    i++;
  }
  let [n, d] = fractions[fractions.length - 1];

  if (n.isZero() || d.isZero()) {
    throw new Error("Couldn't find approximation");
  }

  return [n.toNumber(), d.toNumber()];
}
Пример #7
0
function sum (arr, key) {
  let total = new BigNumber(0)
  for (let item of arr) {
    total = total.plus(item[key])
  }
  return total
}
Пример #8
0
  onWRGChange(v) {
    v = v.replace(",", ".");
    var wrg = new BigNumber(v);
    var BTC = wrg.mul(this.props.exchangeRate).div(Const.WRG_UNIT);

    return this.setAmount(BTC.toString(), v);
  }
Пример #9
0
  let numPartition = function (x) {
    let sq, len, d, a, left, right;

    if (x.lessThan(10)) {
      return (x.equals(1)) ? true : false;
    }

    sq = x.sqrt();

    x = x.toString();
    len = x.length;

    d = Math.round(len / 2);
    a = [d, len - d];

    for (let i = 0; i < a.length; i++) {
      left = new BigNumber(x.substring(0, a[i]));
      right = new BigNumber(x.substring(a[i], len));

      if (left.equals(0) || right.equals(0)) {
        return false;
      } else if ((left.plus(right)).equals(sq)) {
        return true;
      }
    }
    return false;
  }
Пример #10
0
Int.prototype.__pow__ = function(other) {
    var types = require('../types');

    if (types.isinstance(other, types.Bool)) {
        if (other.valueOf()) {
            return this;
        } else {
            return new Int(1);
        }
    } else if (types.isinstance(other, Int)) {
        if (other.val.isNegative()) {
            return this.__float__().__pow__(other);
        } else {
            var y = other.val.toString(2).split('');
            var result = new BigNumber(1);
            var base = this.val.add(0);
            while (y.length > 0) {
                var bit = y.pop();
                if (bit == 1) {
                    result = result.mul(base);
                }
                base = base.mul(base);
            }
            return new Int(result);
        }
    } else if (types.isinstance(other, types.Float)) {
        return this.__float__().__pow__(other);
    } else {
        throw new exceptions.TypeError("unsupported operand type(s) for ** or pow(): 'int' and '" + type_name(other) + "'");
    }
}
Пример #11
0
var constructInterestingObject = (offers, cb) => {
  var balances = {}; // mapping (address => token => balance)
  offers.forEach(offer => {
    // ensure we are aware of the owner
    if (!(offer.owner in balances)) balances[offer.owner] = {};
    // in case we are (ower => token) aware
    // => we add the token to the known balance
    // in case we are not token aware
    // => we simply add it
    if (offer.token in balances[offer.owner]) {
      balances[offer.owner][offer.token] =
        balances[offer.owner][offer.token].plus(offer.ammount);
    } else {
      balances[offer.owner][offer.token] =
        offer.ammount;
    }
  });
  var totalETHBalance = new BigNumber(0);
  // after this we also format the balance to decimals and save it 
  // as simpleMarket.json
  console.log('\nResults for SimpleMarket:');
  _.each(balances, (tokens, owner) => {
    _.each(tokens, (balance, token) => {
      if(token === 'ETH') totalETHBalance = totalETHBalance.plus(balance);
      balances[owner][token] = balance.toString(10);
      console.log(owner, token, balance.toString(10));
    });
  });
  console.log("Total ETH Balance: "+totalETHBalance.toString(10));

  fs.writeFileSync('simpleMarket.json', JSON.stringify(balances, false, 2));

  cb(null, balances);
}
Пример #12
0
const parseRevenue = financialmetrics => {
  const storagerevenue = new BigNumber(financialmetrics.storagerevenue)
  const bwrevenue = new BigNumber(
    financialmetrics.downloadbandwidthrevenue
  ).add(financialmetrics.uploadbandwidthrevenue)
  const contractrevenue = new BigNumber(financialmetrics.contractcompensation)
  return storagerevenue.add(bwrevenue).add(contractrevenue)
}
Пример #13
0
	it('sets storage cost and size on calculateStorageCost', async () => {
		testCost = new BigNumber('1337')
		store.dispatch(actions.calculateStorageCost('100'))
		await sleep(10)
		expect(store.getState().allowancedialog.get('storageSize')).to.equal('100')
		expect(store.getState().allowancedialog.get('storageCost')).to.equal(testCost.round(3).toString())
		expect(SiaAPI.showError.called).to.be.false
	})
Пример #14
0
function BigNumberWrapper(value, base) {
  // reset config every time a BigNumber is instantiated so that
  // these global settings won't be overridden if another file tries
  // to set them at require-time.
  BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_HALF_UP,
                     DECIMAL_PLACES: 40 });
  BigNumber.call(this, value, base);
}
Пример #15
0
OrderBuilder.prototype.setTimestamp = function(timestamp) {
    var bTimestamp = new BigNumber(timestamp);
    if (!bTimestamp.isInteger()) {
        throw new TypeError('Timestamp is not a number.');
    }
    this.timestamp = timestamp;
    return this;
};
Пример #16
0
function factor(n){
    var mult = new BigNumber(1)
    while(n){
        mult = mult.times(n)
        n--;
    }
    return mult
}
Пример #17
0
module.exports = function total(cart) {

	var t = new Big(0);
	t = t.plus(subtotal(cart));
		t = t.plus(delivery(cart));
	return t.toString();

};
Пример #18
0
  /**
   * Given a source transfer with an embedded final transfer, get the next
   * transfer in the chain.
   *
   * It works as follows:
   * Given `sourceTransfer` A→C, find the next hop B on the route from A to C.
   * If the next hop is the final one (B == C), return the final transfer.
   * Otherwise, return a transfer at B, with the final transfer C embedded.
   *
   * @param {Transfer} sourceTransfer
   * @returns {Transfer} destinationTransfer
   */
  * getDestinationTransfer (sourceTransfer) {
    const ilpHeader = sourceTransfer.data && sourceTransfer.data.ilp_header
    if (!ilpHeader) {
      throw new Error('source transfer is missing ilp_header in memo')
    }

    const sourceLedger = sourceTransfer.ledger
    const finalLedger = ilpHeader.ledger
    // Use `findBestHopForSourceAmount` since the source amount includes the slippage.
    const _nextHopBySourceAmount = this.routingTables.findBestHopForSourceAmount(
      sourceLedger, finalLedger, sourceTransfer.amount)
    if (!_nextHopBySourceAmount) throwAssetsNotTradedError()
    // Round against ourselves since the quote rate was overestimated in our favor.
    const nextHop = yield this._roundHop(_nextHopBySourceAmount, 'down', 'up')

    // Check if this connector can authorize the final transfer.
    if (nextHop.isFinal) {
      // Verify ilpHeader.amount ≤ nextHop.finalAmount
      const expectedFinalAmount = new BigNumber(ilpHeader.amount)
      if (expectedFinalAmount.greaterThan(nextHop.finalAmount)) {
        throw new UnacceptableRateError('Payment rate does not match the rate currently offered')
      }
      // TODO: Verify atomic mode notaries are trusted
      // TODO: Verify expiry is acceptable

      nextHop.destinationCreditAccount = ilpHeader.account
      nextHop.destinationAmount = ilpHeader.amount
    }

    const noteToSelf = {
      source_transfer_ledger: sourceTransfer.ledger,
      source_transfer_id: sourceTransfer.id
    }

    return _.omitBy({
      // The ID for the next transfer should be deterministically generated, so
      // that the connector doesn't send duplicate outgoing transfers if it
      // receives duplicate notifications.
      //
      // The deterministic generation should ideally be impossible for a third
      // party to predict. Otherwise an attacker might be able to squat on a
      // predicted ID in order to interfere with a payment or make a connector
      // look unreliable. In order to assure this, the connector may use a
      // secret that seeds the deterministic ID generation.
      // TODO: Use a real secret
      id: getDeterministicUuid('secret', sourceTransfer.ledger + '/' + sourceTransfer.id),
      ledger: nextHop.destinationLedger,
      direction: 'outgoing',
      account: nextHop.destinationCreditAccount,
      amount: nextHop.destinationAmount,
      data: nextHop.isFinal ? ilpHeader.data : { ilp_header: ilpHeader },
      noteToSelf: noteToSelf,
      executionCondition: sourceTransfer.executionCondition,
      cancellationCondition: sourceTransfer.cancellationCondition,
      expiresAt: this._getDestinationExpiry(sourceTransfer.expiresAt),
      cases: sourceTransfer.cases
    }, _.isUndefined)
  }
Пример #19
0
    bitstamped.getTicker(paidTime, function(err, docs) {
      if (!err && docs.rows && docs.rows.length > 0) {
        var tickerData = docs.rows[0].value;
        var rate = new BigNumber(tickerData.vwap);
        var totalPaid = new BigNumber(invoiceHelper.getTotalPaid(invoice, paymentsArr));
        var remainingBalance = new BigNumber(invoice.balance_due).minus(totalPaid);
        var isUSD = invoice.currency.toUpperCase() === 'USD';
        if (isUSD) {
          var actualPaid = helper.roundToDecimal(rate.times(transaction.amount).valueOf(), 2);
          var closeEnough = new BigNumber(actualPaid).equals(helper.roundToDecimal(remainingBalance, 2));
          if (closeEnough) {
            remainingBalance = transaction.amount;
          }
          else {
            remainingBalance = Number(remainingBalance.dividedBy(rate).valueOf());
          }
        }
        remainingBalance = helper.roundToDecimal(remainingBalance, 8);
        var payment = {
          _id: invoiceId + '_' + transaction.txid,
          invoice_id: invoiceId,
          address: transaction.address,
          amount_paid: Number(transaction.amount),
          expected_amount: Number(remainingBalance),
          block_hash: transaction.blockhash ? transaction.blockhash : null,
          spot_rate: Number(rate.valueOf()), // Exchange rate at time of payment
          created: new Date().getTime(),
          paid_timestamp: paidTime,
          txid: transaction.txid, // Bitcoind txid for transaction
          watched: true,
          type: 'payment'
        };
        payment.status = helper.getPaymentStatus(payment, transaction.confirmations, invoice);

        // New transaction to known address has wallet conflicts. This indicates that 
        // this transaction is a mutated tx of a known payment.
        if (transaction.walletconflicts.length > 0) {
          payment.double_spent_history = transaction.walletconflicts;
          var latestConflictingTx = transaction.walletconflicts[transaction.walletconflicts.length - 1];
          // Need to grab spot rate and expected_amount from conflicting payment
          paymentsArr.forEach(function(curPayment) {
            if (curPayment.txid === latestConflictingTx) {
              payment.expected_amount = curPayment.expected_amount;
              payment.spot_rate = curPayment.spot_rate;
            }
          });
        }
        db.insert(payment, function(err) {
          if (err && err.error === 'conflict' ) {
            console.log('createNewPaymentWithTransaction: Document update conflict: ' + require('util').inspect(err.request.body));
            return cb();
          }
        });
      }
      else {
        return cb(err);
      }
    });
Пример #20
0
      .map((tokenId) => {
        const token = tokens[tokenId];
        const balanceValue = balance[tokenId];

        const isEthToken = token.native;
        const isFullToken = !showOnlyEth || isEthToken;
        const hasBalance = (balanceValue instanceof BigNumber) && balanceValue.gt(0);

        if (!hasBalance && !isEthToken) {
          return null;
        }

        const bnf = new BigNumber(token.format || 1);
        let decimals = 0;

        if (bnf.gte(1000)) {
          decimals = 3;
        } else if (bnf.gte(100)) {
          decimals = 2;
        } else if (bnf.gte(10)) {
          decimals = 1;
        }

        const value = new BigNumber(balanceValue).div(bnf).toFormat(decimals);

        const classNames = [styles.balance];
        let details = null;

        if (isFullToken) {
          classNames.push(styles.full);
          details = [
            <div
              className={ styles.value }
              key='value'
            >
              <span title={ value }>
                { value }
              </span>
            </div>,
            <div
              className={ styles.tag }
              key='tag'
            >
              { token.tag }
            </div>
          ];
        }

        return (
          <div
            className={ classNames.join(' ') }
            key={ tokenId }
          >
            <TokenImage token={ token } />
            { details }
          </div>
        );
      })
Пример #21
0
  static * handlerDepositArrived(action) {
    let currency = action.deposit.currency;

    let amount = new BigNumber(AccountsService.accounts[currency].amount);
    amount = amount.plus(action.deposit.amount);
    AccountsService.accounts[currency].amount = amount.toString();

    yield put(accountUpdated(AccountsService.accounts[currency]));
  }
Пример #22
0
  static * handleWithdrawalCreated(action) {
    let currency = action.withdrawal.currency;

    let amount = new BigNumber(AccountsService.accounts[currency].amount);
    amount = amount.minus(action.withdrawal.amount);
    AccountsService.accounts[currency].amount = amount.toString();

    yield put(accountUpdated(AccountsService.accounts[currency]));
  }
Пример #23
0
 _wallets.forEach(function(_wallet){
   for (var currency in totals) {
     if (_wallet.currencies[currency] && _wallet.currencies[currency].amount) {
       var totalAmount = new BigNumber(totals[currency].amount);
       totals[currency].amount = totalAmount.plus(new BigNumber(_wallet.currencies[currency].amount));
       totals[currency].amount = totals[currency].amount.toString();
     }
   }
 });
Пример #24
0
Iban.prototype.address = function () {
    if (this.isDirect()) {
        var base36 = this._iban.substr(4);
        var asBn = new BigNumber(base36, 36);
        return padLeft(asBn.toString(16), 20);
    } 

    return '';
};
Пример #25
0
 transforms.forEach(t => {
     const div = val.dividedToIntegerBy(t[1]);
     if (div.toNumber() > 0) {
         //If div value is 1, slice the "s" from the unit name
         const unit = div > 1 ? t[0] : t[0].slice(0, -1);  
         results.push(div + ' ' + unit);
     }
     val = val.modulo(t[1]);
 });
Пример #26
0
  chai.Assertion.addProperty('address', function() {
    this.assert(this._obj.length === 42, 'expected #{this} to be a 42 character address (0x...)', 'expected #{this} to not be a 42 character address (0x...)');

    // Convert address to a number. Make sure it's not zero.
    // Controversial: Technically there is that edge case where
    // all zeroes could be a valid address. But: This catches all
    // those cases where Ethereum returns 0x0000... if something fails.
    var number = new BigNumber(this._obj, 16);
    this.assert(number.equals(0) === false, 'expected address #{this} to not be zero', 'you shouldn\'t ever see this.');
  });
Пример #27
0
BigNumber.prototype.gcd = function (y) {
    y = new BigNumber(y);
    var x = new BigNumber(this);
    while (!y.eq(0)) {
        var c = x.mod(y);
        x = y;
        y = c;
    }
    return x.abs();
};
Пример #28
0
export const allowanceStorage = (funds, hosts, period) => {
	const allowanceFunds = new BigNumber(funds)
	let costPerB = estimatedStoragePriceH(hosts).times(period)
	// If costPerB is zero, set it to some sane, low, amount instead
	if (costPerB.isZero()) {
		costPerB = new BigNumber('10000')
	}
	const storageBytes = Math.min(maxEstimatedStorage, allowanceFunds.dividedBy(costPerB).toNumber())
	return readableFilesize(storageBytes)
}
Пример #29
0
/**
 * publicTrade/publicTakeBestOrder will continue to execute as long as sufficient gas remains and
 * there are still orders to fill (or create).  This prevents eth_estimateGas from working properly.
 * The gas supplied to these transactions is instead based on the current block gas limit.
 * @return {BigNumber} Amount of gas to include.
 */
function calculateTradeGas() {
  var currentBlock = ethrpc.getCurrentBlock();
  if (currentBlock == null) return constants.MINIMUM_TRADE_GAS;
  var blockGasLimit = new BigNumber(currentBlock.gasLimit, 16);
  var tradeGasLowerBound = blockGasLimit.times(constants.TRADE_GAS_LOWER_BOUND_MULTIPLIER).integerValue(BigNumber.ROUND_UP);
  var tradeGasUpperBound = blockGasLimit.times(constants.TRADE_GAS_UPPER_BOUND_MULTIPLIER).integerValue(BigNumber.ROUND_DOWN);
  if (tradeGasUpperBound.lt(constants.MINIMUM_TRADE_GAS)) return constants.MINIMUM_TRADE_GAS;
  if (tradeGasLowerBound.gt(constants.MINIMUM_TRADE_GAS)) return tradeGasLowerBound;
  return tradeGasUpperBound;
}
Пример #30
0
const parseExpectedRevenue = financialmetrics => {
  const storagerevenue = new BigNumber(financialmetrics.potentialstoragerevenue)
  const bwrevenue = new BigNumber(
    financialmetrics.potentialdownloadbandwidthrevenue
  ).add(financialmetrics.potentialuploadbandwidthrevenue)
  const contractrevenue = new BigNumber(
    financialmetrics.potentialcontractcompensation
  )
  return storagerevenue.add(bwrevenue).add(contractrevenue)
}