# All files / src/api/methods txResponse.js

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

    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
    48
    49
    50
    51
    52
    53
    543x

    3x

    10x
    8x

    2x
    1x
    1x

    1x

    3x
    10x
    10x
    10x
    5x
    5x
    5x
    5x
    4x
    4x

    10x

    10x

     const { Tx, Type, Util } = require('leap-core');

    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, blockHash, height, txPos) => {
      let prevTx = null;
      let from = '';
      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);

      return {
        value: `0x${value.toString(16)}`,
        color,
        hash: tx.hash(),
        from,
        raw: tx.hex(),
        blockHash,
        blockNumber: `0x${height.toString(16)}`,
        transactionIndex: txPos,
        to: tx.outputs && tx.outputs.length ? tx.outputs[0].address : null,
        gas: '0x0',
        gasPrice: '0x0',
        nonce: 0,
        input: '0x',
      };
    };