How to calculate crypto cost basis and capital gains
Crypto cost basis methods (FIFO, LIFO, HIFO, average cost), how gains and DeFi rewards are taxed, and code that computes FIFO gains from onchain data.
On this page
- What cost basis and capital gains are
- Cost basis methods: FIFO, LIFO, HIFO, specific ID and average cost
- A worked example
- DeFi activity: which transfers matter
- What you need
- Step 1: Get every transfer of one token
- Step 2: Fill in missing prices
- Step 3: Match each disposal to lots with FIFO
- Run it on a real wallet
- What this code doesn't do
- What it costs
- Frequently asked questions
- Next steps
Cost basis is what you paid for a crypto asset. Capital gain is what you got for it minus that cost. The arithmetic is simple; the work is in the records: every lot you acquired, what each was worth that day, and which lots each sale used up. This guide explains the cost basis methods, then computes FIFO gains for one token from a wallet's onchain history with the GoldRush Foundational API.
This guide is not tax advice. Rules differ by country and change; check them with a tax professional or your tax authority.
What cost basis and capital gains are
- Cost basis is what you spent to acquire an asset, including fees. The IRS virtual currency FAQ defines it that way for crypto bought with dollars (A8). Crypto received for services has a basis of its fair market value when received (A13).
- Capital gain or loss is the amount you received minus your adjusted basis in the units you gave up (A7). Swapping one crypto asset for another counts too: the amount received is the fair market value of what you got (A16, A17).
- Holding period decides the rate in many systems. Under the IRS FAQ, units held one year or less give a short-term gain or loss, and units held more than one year a long-term one (A6).
- Not every outgoing transfer is a sale. Moving crypto between wallets you own is not a taxable event (A38).
The hard part is that you rarely sell a whole purchase. You buy in several lots at different prices, then sell part of your holding, and the method you use decides which lots that sale used up.
Cost basis methods: FIFO, LIFO, HIFO, specific ID and average cost
| Method | Which units a sale uses | Effect when prices have risen |
|---|---|---|
| FIFO (first in, first out) | The oldest units still held | Larger gains |
| LIFO (last in, first out) | The newest units | Smaller gains, more short-term |
| HIFO (highest in, first out) | The most expensive units | Smallest gains |
| Specific identification | The units you name, with records | Whatever you choose |
| Average cost (adjusted cost base) | Every unit at the average cost of all units held | Between FIFO and HIFO |
What the IRS FAQ says about choosing:
- Specific identification is allowed if you can identify the units and substantiate their basis (A39). The records must show when each unit was acquired, its basis and value then, when it was disposed of, and its value and what you received for it (A40).
- FIFO is the default. If you don't identify units, they are treated as disposed of in the order you acquired them (A41).
- LIFO and HIFO are ways of picking units, so under that FAQ they are specific identification and need the same records.
- Average cost, also called adjusted cost base (ACB), spreads the total cost evenly over every unit held: each purchase adds to the pool, and each sale takes cost out at the current average. The IRS FAQ describes only specific identification and FIFO, so check whether average cost is allowed where you file.
A worked example
You buy 1 token for $100 in January, 1 for $300 in March and 1 for $200 in June. In December you sell 1 for $250. The gain depends on the method:
| Method | Cost basis of the unit sold | Gain |
|---|---|---|
| FIFO | $100 (January) | +$150 |
| LIFO | $200 (June) | +$50 |
| HIFO | $300 (March) | −$50 |
| Average cost | $200 ($600 ÷ 3) | +$50 |
Same trades, three different results. The lots you keep differ too: after FIFO, you hold the $300 and $200 units, so the next sale starts from a higher basis.
DeFi activity: which transfers matter
DeFi taxes start from the same records as any other crypto: what came in, what went out, and what each was worth that day. What changes is how many kinds of transaction a wallet makes, and which of them count.
- Swaps on a DEX are disposals. Trading one token for another on a decentralized exchange is an exchange like any other: you dispose of what you gave up, and the amount received is the fair market value of what you got (IRS FAQ A16, A17; see What cost basis and capital gains are).
- Rewards are usually income when received. The IRS says staking rewards are gross income at their fair market value on the date and time you gain control of them (Rev. Rul. 2023-14). Lending interest and liquidity-mining or yield-farming reward tokens are often treated the same way, but check with your tax authority. Where a reward is income, that value is also the cost basis of the new lot, as for crypto received for services (A13), so a reward is an
INwhose price is the price on the day it arrived. - Liquidity pools, wrapping and bridging are where rules differ most. Depositing tokens into a pool for LP tokens, wrapping ETH into WETH, or bridging a token to another chain may or may not be a disposal depending on where you file. Check with your tax authority before treating any of them as a sale or as a transfer.
The data problem is that one wallet touches many protocols, and each records its activity in its own format: a lending deposit, a pool withdrawal and a reward claim emit different events from different contracts. Token transfers are the common thread, since every one of these moves tokens in or out of the wallet; the decoded log events of each transaction tell you which protocol action caused them. That is why this guide works from transfers_v2, and why a crypto tax API needs both transfers and decoded events, from the wallet's transaction history, to label each one.
What you need
To compute cost basis from onchain data, you need three things for every lot: the amount, the date, and the price that day. GoldRush gives you all three from two endpoints:
- ERC-20 token transfers (
transfers_v2): every transfer of one token in or out of a wallet, each withtransfer_type(INorOUT), the raw amount indelta,contract_decimals, andquote_rate, the token's price on the day of the transfer. Each transaction also carries the gas it cost ingas_quote. - Historical token prices (
historical_by_addresses_v2): a token's daily price for a date range, to fill in a transfer that came back without aquote_rate.
You also need a GoldRush API key: sign up for the free trial. The examples use Node.js 18 or later, which has fetch built in.
Step 1: Get every transfer of one token
transfers_v2 takes the wallet, the chain and the token's contract address, and returns 100 transactions per page, newest first. This function pages through all of them and keeps what cost basis needs, oldest first:
const API = "https://api.covalenthq.com/v1";const headers = { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` }; // Every movement of one token in or out of a wallet, oldest first, with the token's price// that day and the gas the wallet paid.async function getTransfers(chain, wallet, token) { const transfers = []; for (let page = 0; ; page++) { const url = `${API}/${chain}/address/${wallet}/transfers_v2/` + `?contract-address=${token}"e-currency=USD&page-size=100&page-number=${page}`; const res = await fetch(url, { headers }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); const { data } = await res.json(); for (const tx of data.items) { if (!tx.successful) continue; // Gas is the wallet's cost only when it sent the transaction; count it once. let fee = tx.from_address === data.address ? tx.gas_quote : 0; for (const t of tx.transfers) { if (t.contract_address !== token.toLowerCase()) continue; transfers.push({ date: t.block_signed_at, type: t.transfer_type, // "IN" or "OUT" amount: BigInt(t.delta), // raw units: divide by 10^decimals for tokens decimals: t.contract_decimals, price: t.quote_rate, // USD per token on the day of the transfer fee, }); fee = 0; } } if (!data.pagination?.has_more) break; } return transfers.sort((a, b) => a.date.localeCompare(b.date));}- Amounts stay as
BigIntraw units, so matching lots never leaves rounding dust. They become token amounts only when multiplied by a price. data.addressis the wallet's resolved address, so an ENS name such asvitalik.ethworks as thewalletargument.quote-currencytakesUSD,EUR,GBP,CADand a dozen more. Use the currency you report in.
Step 2: Fill in missing prices
If a transfer comes back with quote_rate set to null, look that day up with historical token prices. Its response is a list with one entry per token, and the daily prices are in that entry's prices array:
// The token's USD price on one day (YYYY-MM-DD), cached.const prices = new Map(); async function priceOn(chain, token, day) { const key = `${chain}:${token}:${day}`; if (!prices.has(key)) { const url = `${API}/pricing/historical_by_addresses_v2/${chain}/USD/${token}/?from=${day}&to=${day}`; const res = await fetch(url, { headers }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); const { data } = await res.json(); prices.set(key, data[0]?.prices?.[0]?.price ?? null); } return prices.get(key);} async function fillMissingPrices(chain, token, transfers) { for (const t of transfers) { t.price ??= await priceOn(chain, token, t.date.slice(0, 10)); if (t.price == null) throw new Error(`No price for ${token} on ${t.date}`); } return transfers;}Both endpoints give one price per day. On the days we checked, a transfer's quote_rate was the same figure historical token prices returned for that date. If you need the price at the minute of a trade, you need another source.
Step 3: Match each disposal to lots with FIFO
Each IN becomes a lot with its cost: amount times price, plus any gas the wallet paid. Each OUT uses up the oldest lots first, and every lot (or part of a lot) it uses becomes one row with its proceeds, cost basis, gain and holding period:
const units = (raw, decimals) => Number(raw) / 10 ** decimals; // Long term means held for more than one year.function isLongTerm(acquired, sold) { const anniversary = new Date(acquired); anniversary.setUTCFullYear(anniversary.getUTCFullYear() + 1); return new Date(sold) > anniversary;} // FIFO: each OUT uses up the oldest lots first. Returns one row per lot (or part of a lot)// disposed of, and the lots still held with their remaining cost basis.function fifo(transfers) { const lots = []; const rows = []; for (const t of transfers) { if (t.type === "IN") { const cost = units(t.amount, t.decimals) * t.price + t.fee; lots.push({ acquired: t.date, amount: t.amount, cost }); continue; } const proceeds = units(t.amount, t.decimals) * t.price - t.fee; let left = t.amount; while (left > 0n) { const lot = lots[0]; if (!lot) throw new Error(`${t.date}: more went out than came in`); const take = lot.amount < left ? lot.amount : left; const costBasis = (lot.cost * Number(take)) / Number(lot.amount); const share = (proceeds * Number(take)) / Number(t.amount); rows.push({ acquired: lot.acquired.slice(0, 10), disposed: t.date.slice(0, 10), amount: units(take, t.decimals), proceeds: share, costBasis, gain: share - costBasis, term: isLongTerm(lot.acquired, t.date) ? "long" : "short", }); lot.amount -= take; lot.cost -= costBasis; left -= take; if (lot.amount === 0n) lots.shift(); } } return { rows, lots };}For another method, change only which lot the loop takes. LIFO takes the last lot (lots.at(-1), removed with lots.pop()). HIFO takes the lot with the highest cost per unit. Average cost keeps one pool: total amount and total cost, with each OUT removing cost in proportion to the amount sold.
Run it on a real wallet
This runs the three steps for SHIB in vitalik.eth on Ethereum, a public wallet whose SHIB history has 15 transactions, and prints the rows with totals by holding period:
const SHIB = "0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE"; const transfers = await getTransfers("eth-mainnet", "vitalik.eth", SHIB);await fillMissingPrices("eth-mainnet", SHIB, transfers);const { rows, lots } = fifo(transfers); const usd = (n) => n.toFixed(2);console.table(rows.map((r) => ({ ...r, proceeds: usd(r.proceeds), costBasis: usd(r.costBasis), gain: usd(r.gain) })));const net = (term) => rows.filter((r) => r.term === term).reduce((sum, r) => sum + r.gain, 0);console.log("long-term:", usd(net("long")), "short-term:", usd(net("short")));console.log( "still held:", lots.map((l) => ({ acquired: l.acquired.slice(0, 10), cost: usd(l.cost) })));Run on the API's responses from 19 November 2026, it prints 12 rows. The wallet's one OUT, a swap of its whole SHIB balance on 30 April 2026, used up every lot it held. Abridged to the rows worth more than a cent, with amounts rounded:
acquired disposed amount proceeds costBasis gain term2024-01-16 2026-04-30 100000 0.61 0.98 -0.37 long2024-03-18 2026-04-30 5289872.84 32.01 154.47 -122.46 long2024-11-24 2026-04-30 1111 0.01 0.03 -0.02 long long-term: -122.85 short-term: -0.00still held: [ { acquired: '2026-06-02', cost: '0.00' }, { acquired: '2026-07-29', cost: '0.00' } ]Two lots, from May and October 2025, had been held less than a year, so their rows are short-term; they were worth less than a cent. The two transfers received after the swap are the lots still held.
What this code doesn't do
The code computes the arithmetic. Deciding what each transfer was is up to you:
- Classify transfers. An
OUTto your own wallet is not a sale (IRS FAQ A38), and anINfrom your own wallet is not a purchase: it carries its original lots. Airdrops, rewards and payments are often income when received (see DeFi activity). Merge the histories of all the wallets you own before running FIFO, and treat the moves between them as transfers. - Value swaps by what you received. The code values an
OUTat the sold token's daily price. The IRS FAQ values an exchange at the fair market value of what you received (A17), which may differ. - Native tokens.
transfers_v2covers ERC-20 tokens. For ETH and other native tokens, read the wallet's transaction history, where each transaction carries itsvalueand gas. - Check the result. Lots still held should add up to the wallet's balance. Token balances returns it, and a mismatch means a missing transfer.
For the full picture across many wallets and chains, the crypto tax and accounting page covers the GoldRush endpoints tax and accounting software builds on.
What it costs
ERC-20 token transfers costs 0.05 per item, one item per transaction, so a token history of 1,000 transactions costs 50 credits to read. Historical token prices costs 1 per call, and Token balances 1 per call. The pricing calculator estimates a month of calls.
Frequently asked questions
How do I calculate the cost basis of crypto?
Add up what you paid for each lot, including fees, and note when you acquired it. When you sell, pick which lots the sale used up (FIFO, LIFO, HIFO, specific identification or average cost); the cost of those units is the sale's cost basis.
How are capital gains on crypto calculated?
Gain is what you received for the units minus their adjusted basis. If you received another crypto asset, what you received is its fair market value. The IRS FAQ treats units held more than one year as long-term and the rest as short-term.
Which cost basis method does the IRS use for crypto by default?
FIFO. If you don't specifically identify the units you sold, the IRS virtual currency FAQ treats them as the earliest units you acquired (A41). Specific identification, which covers LIFO and HIFO choices, needs records of each unit's dates, basis and values (A39, A40).
What is adjusted cost base (ACB)?
An average cost method: the cost of all units held is pooled, and each sale takes cost out at the current average per unit. Whether you may use it depends on where you file; the IRS FAQ describes only specific identification and FIFO.
Are DeFi transactions taxable?
Many are. Swapping one token for another on a DEX is a disposal, valued at the fair market value of what you received. Staking rewards are income when you gain control of them under IRS Rev. Rul. 2023-14, and lending interest and farming rewards often are too. Liquidity pool deposits, wrapping and bridging are treated differently in different countries, so check with your tax authority.
Can I get cost basis from an API?
GoldRush gives you the inputs: every transfer of a token with the token's price that day, and historical prices for any day. It doesn't return a cost basis or gains figure; you apply the method, as in the code above.
Is this tax advice?
No. This guide explains methods and code. Tax rules differ by country and change over time, so check your figures with a tax professional or your tax authority.
Next steps
- ERC-20 token transfers reference: every parameter and response field.
- Historical token prices reference: daily prices for one or many tokens.
- Crypto tax and accounting: wallet history, prices and balances on any date for tax software.
- GoldRush Foundational API: every endpoint and its credit cost.