<p>Using <code>getrawtransaction</code>, you can get the <code>blockhash</code> of the transaction and then you can query the block to get the fee. To do that, use <code>getblock</code> with <code>verbosity=2</code> and you will have the fees for all transactions within the block.</p>

CC BY-SA 4.0
2023-03-24T08:50:41.233Z
2023-03-24T08:50:41.233Z
mbh86
<p>To calculate fees.
Take sum of all vouts.For every vin there will be prev txid and outputindex,
Get this txid with getrawtransaction or some other way,go to vouts of this new tx at index, here you will get amount,
Repeat this for every vin.
Take sum of this vins. 
Take difference between vin and vout you will get fees.</p>

<p>To avoid calling ever time you need to store txids somewhere or user something like insight.</p>

CC BY-SA 3.0
2017-03-07T09:47:59.633Z
2017-03-07T10:00:21.997Z
2017-03-07T10:00:21.997Z
Dhruvil Shah
<p>There is a way to make these calls more efficient and it's through doing some memoisation.</p>

<p>There's no way around having to make the getRawTransaction call on each unique transaction at least once - but that doesn't mean we need to do it again!</p>

<p>Here is how I've done it for the <a href="https://github.com/GrayedFox/blockscrape/tree/develop" rel="nofollow noreferrer">blockscrape project</a> I'm working on:</p>

<pre><code>const api = require('./api/api.js')

let transactions = {}

const storeTransaction = (tx, vout) =&gt; { transactions[tx] = vout }

const transactionExists = (tx) =&gt; transactions[tx] ? true : false

const retrieveTransacton = (tx) =&gt; transactions[tx]

// loop through the outputs of a tx, greedily returning the value of an output tx where n matches vOutIdx
const getMatchingTransactionValue = async (txHash, voutIndex) =&gt; {
  let tx = undefined
  let voutArray = undefined

  if (transactionExists(txHash)) {
    voutArray = retrieveTransacton(txHash)
  } else {
    tx = await api.getRawTransaction(txHash)
    voutArray = JSON.parse(tx).vout
    storeTransaction(txHash, voutArray)
  }

  for (let i = 0; i &lt; voutArray.length; i++) {
    if (voutArray[i].n === voutIndex) {
      return voutArray[i].value
    }
  }
}
</code></pre>

<p>The api file is just a wrapper for spawning a child process and executing api specific arguments (i.e. <code>litecoin-cli getrawtransaction txhash 1</code>) - which are themselves wrapped into a promise (hence using the <code>await</code> keyword).</p>

<p>The key to taking advantage of the memoisation is that you'll need to traverse whatever blocks you need <strong>backwards</strong> -- otherwise you'll be storing transactions in memory and never find a match. </p>

<p>This is because all transactions on the blockchain reference both inputs and outputs and we need to work with the outputs (later transactions) in order to calculate the fee - which means if we work backwards, we will likely store many transactions which are referenced by past blocks (but we won't ever find transactions which are referenced in the vout array of future blocks, since our program has no knowledge of them yet as they are in the "future").</p>

<p>Of course, this is one of the advantages of working with historical data - when we know, in reality, those transactions do exist, we just need to adapt our program to reflect this fact :)</p>

CC BY-SA 3.0
2018-03-14T13:35:52.900Z
Apologies for the technical nature of this answer - I just realised I'm on bitcoin.so and not the core stack overflow (programmers) section. I will leave it as it still might be of some use to the OP or readers.
GrayedFox
CC BY-SA 3.0
2018-03-14T13:31:44.460Z
2018-03-14T13:31:44.460Z
GrayedFox
<p>From experience, the vin and vout elements all have a "value" field - you just need to sum up the vin values and substract the sum of the vout values.</p>

CC BY-SA 3.0
2017-01-06T21:30:06.963Z
Only the transaction outputs have values.  The values of the inputs are inferred by the outputs they reference.
Jestin
CC BY-SA 3.0
2017-01-07T13:33:46.917Z
You are right - I was looking at the output from a 3rd party provider and got confused. Thanks for pointing this out.
Alex
CC BY-SA 3.0
2017-01-05T19:44:13.727Z
2017-01-05T19:44:13.727Z
Alex
<p>I would to get the <em>fee</em> when I search for a transaction using <code>getrawtransaction</code>, but the JSON-RPC does not return this.</p>

<p><a href="https://chainquery.com/bitcoin-api/getrawtransaction" rel="nofollow">https://chainquery.com/bitcoin-api/getrawtransaction</a></p>

<p>So to achieve this, my idea is to:</p>

<ol>
<li>Call getrawtransaction for each <code>vin</code>, and save the output value for each one.</li>
<li>Sum all the output value for the <code>vin</code>s, and subtract the sum of the <code>vout</code> values to give you the remainder.</li>
</ol>

<p>I know this will work, but I dislike having to call <code>getrawtransaction</code> for each <code>vin</code> (as this JSON-RPC call will be made 200+ times for some transactions).</p>

<p>Is there a more efficient way? Or is this currently the only way to calculate the fee for a transaction using bitcoin-cli?</p>

<blockquote>
  <p><strong>Aside:</strong> Why doesn't <code>getrawtransaction</code> return a <em>fee</em> field, like the transactions in <code>getrawmempool</code> and <code>getblocktemplate</code> do?</p>
</blockquote>

CC BY-SA 3.0
2018-03-14T07:07:52.627Z
Also looking at how to do this more efficiently... I'm wondering if we trawl the blockchain backwards (say from block 500 down to 200) we might be able to practise some sort of memoisation?
GrayedFox
<bitcoin-cli>
Most efficient way to calculate fee from getrawtransaction?
inersha
# Most efficient way to calculate fee from getrawtransaction?

(Asked by: username_0 on 2016-06-26)

I would to get the *fee* when I search for a transaction using `getrawtransaction`, but the JSON-RPC does not return this.

<https://chainquery.com/bitcoin-api/getrawtransaction>

So to achieve this, my idea is to:

1. Call getrawtransaction for each `vin`, and save the output value for each one.
2. Sum all the output value for the `vin`s, and subtract the sum of the `vout` values to give you the remainder.

I know this will work, but I dislike having to call `getrawtransaction` for each `vin` (as this JSON-RPC call will be made 200+ times for some transactions).

Is there a more efficient way? Or is this currently the only way to calculate the fee for a transaction using bitcoin-cli?

> **Aside:** Why doesn't `getrawtransaction` return a *fee* field, like the transactions in `getrawmempool` and `getblocktemplate` do?

**Tags:** bitcoin-cli

> **Comments:**
> **username_1**: Also looking at how to do this more efficiently... I'm wondering if we trawl the blockchain backwards (say from block 500 down to 200) we might be able to practise some sort of memoisation?  

---

## 4 answers

### Answer by username_2 on 2023-03-24. Score: 1

Using `getrawtransaction`, you can get the `blockhash` of the transaction and then you can query the block to get the fee. To do that, use `getblock` with `verbosity=2` and you will have the fees for all transactions within the block.


---

### Answer by username_3 on 2017-03-07. Score: 1

To calculate fees.
Take sum of all vouts.For every vin there will be prev txid and outputindex,
Get this txid with getrawtransaction or some other way,go to vouts of this new tx at index, here you will get amount,
Repeat this for every vin.
Take sum of this vins.
Take difference between vin and vout you will get fees.

To avoid calling ever time you need to store txids somewhere or user something like insight.


---

### Answer by username_1 on 2018-03-14. Score: 0

There is a way to make these calls more efficient and it's through doing some memoisation.

There's no way around having to make the getRawTransaction call on each unique transaction at least once - but that doesn't mean we need to do it again!

Here is how I've done it for the [blockscrape project](https://github.com/username_1/blockscrape/tree/develop) I'm working on:

```
const api = require('./api/api.js')

let transactions = {}

const storeTransaction = (tx, vout) => { transactions[tx] = vout }

const transactionExists = (tx) => transactions[tx] ? true : false

const retrieveTransacton = (tx) => transactions[tx]

// loop through the outputs of a tx, greedily returning the value of an output tx where n matches vOutIdx
const getMatchingTransactionValue = async (txHash, voutIndex) => {
  let tx = undefined
  let voutArray = undefined

  if (transactionExists(txHash)) {
    voutArray = retrieveTransacton(txHash)
  } else {
    tx = await api.getRawTransaction(txHash)
    voutArray = JSON.parse(tx).vout
    storeTransaction(txHash, voutArray)
  }

  for (let i = 0; i < voutArray.length; i++) {
    if (voutArray[i].n === voutIndex) {
      return voutArray[i].value
    }
  }
}

```

The api file is just a wrapper for spawning a child process and executing api specific arguments (i.e. `litecoin-cli getrawtransaction txhash 1`) - which are themselves wrapped into a promise (hence using the `await` keyword).

The key to taking advantage of the memoisation is that you'll need to traverse whatever blocks you need **backwards** -- otherwise you'll be storing transactions in memory and never find a match.

This is because all transactions on the blockchain reference both inputs and outputs and we need to work with the outputs (later transactions) in order to calculate the fee - which means if we work backwards, we will likely store many transactions which are referenced by past blocks (but we won't ever find transactions which are referenced in the vout array of future blocks, since our program has no knowledge of them yet as they are in the "future").

Of course, this is one of the advantages of working with historical data - when we know, in reality, those transactions do exist, we just need to adapt our program to reflect this fact :)

> **Comments:**
> **username_1**: Apologies for the technical nature of this answer - I just realised I'm on bitcoin.so and not the core stack overflow (programmers) section. I will leave it as it still might be of some use to the OP or readers.  

---

### Answer by username_4 on 2017-01-05. Score: 0

From experience, the vin and vout elements all have a "value" field - you just need to sum up the vin values and substract the sum of the vout values.

> **Comments:**
> **username_5**: Only the transaction outputs have values.  The values of the inputs are inferred by the outputs they reference.  
> **username_4**: You are right - I was looking at the output from a 3rd party provider and got confused. Thanks for pointing this out.  

---

