All files / src/api/methods/utils getTxValueAndSource.js

100% Statements 22/22
100% Branches 19/19
100% Functions 2/2
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 484x 4x   4x   11x 9x           2x 1x 1x           1x     4x 11x 11x 11x 6x 6x 6x 6x 5x 5x       11x   11x   11x              
const { Tx, Type, Util } = require('leap-core');
const { EMPTY_ADDRESS } = require('../../../utils/constants');
 
const txValue = (tx, prevTx) => {
  // assuming first output is transfer, second one is change
  if (tx.outputs && tx.outputs.length > 0) {
    return {
      value: tx.outputs[0].value,
      color: tx.outputs[0].color,
    };
  }
 
  if (tx.type === Type.EXIT && prevTx) {
    const output = prevTx.outputs[tx.inputs[0].prevout.index];
    return {
      value: output.value,
      color: output.color,
    };
  }
 
  return { value: 0, color: 0 };
};
 
module.exports = async (db, tx) => {
  let prevTx = null;
  let from = EMPTY_ADDRESS;
  if (tx.inputs && tx.inputs.length > 0 && tx.inputs[0].prevout) {
    const prevTxHash = tx.inputs[0].prevout.hash;
    const outputIndex = tx.inputs[0].prevout.index;
    const txDoc = await db.getTransaction(Util.toHexString(prevTxHash));
    if (txDoc) {
      prevTx = Tx.fromJSON(txDoc.txData);
      from = prevTx.outputs[outputIndex].address;
    }
  }
 
  const { value, color } = txValue(tx, prevTx);
 
  const to = tx.outputs && tx.outputs.length ? tx.outputs[0].address : EMPTY_ADDRESS;
 
  return {
    value,
    color,
    from,
    to
  };
};