> ## Documentation Index
> Fetch the complete documentation index at: https://voltaire.tevm.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# GasUsed

> Gas consumed by transaction execution

<Card title="Try it Live" icon="play" href="https://playground.tevm.sh?example=primitives/gas-used.ts">
  Run GasUsed examples in the interactive playground
</Card>

# GasUsed

`GasUsed` represents the actual amount of gas consumed by a transaction during execution. Found in transaction receipts as `receipt.gasUsed`.

## Type Definition

```typescript theme={null}
type GasUsedType = bigint & { readonly [brand]: "GasUsed" };
```

Branded bigint representing gas consumed (always non-negative).

## Gas Mechanics

### Yellow Paper

Gas mechanics defined in Yellow Paper Section 6 (Transaction Execution):

* **Gas vs Gas Price**: Total cost = `gasUsed × gasPrice` (in Wei)
* **Gas Limit**: Maximum gas transaction can consume (`gasUsed ≤ gasLimit`)
* **Refund**: Unused gas refunded: `(gasLimit - gasUsed) × gasPrice`

### Gas Ranges

* **Minimum**: 21,000 gas (simple ETH transfer)
* **Typical**: 50,000 - 200,000 gas (contract interactions)
* **Maximum**: Block gas limit (\~30M on mainnet)

## API

### Constructors

#### `from(value)`

Create GasUsed from number, bigint, or string.

```typescript theme={null}
import { GasUsed } from '@tevm/primitives';

// From transaction receipt
const gasUsed = GasUsed.from(receipt.gasUsed);

// From bigint
const gas = GasUsed.from(51234n);

// From number
const gas2 = GasUsed.from(21000);

// From hex string
const gas3 = GasUsed.from("0xc822");
```

**Throws**: `InvalidFormatError` if value is negative.

### Conversions

#### `toNumber(gasUsed)`

Convert to number.

```typescript theme={null}
const gasUsed = GasUsed.from(51234n);
GasUsed.toNumber(gasUsed); // 51234
```

#### `toBigInt(gasUsed)`

Convert to bigint (identity operation).

```typescript theme={null}
const gasUsed = GasUsed.from(51234n);
GasUsed.toBigInt(gasUsed); // 51234n
```

#### `toHex(gasUsed)`

Convert to hex string.

```typescript theme={null}
const gasUsed = GasUsed.from(51234n);
GasUsed.toHex(gasUsed); // "0xc822"
```

### Comparisons

#### `equals(gas1, gas2)`

Check equality.

```typescript theme={null}
GasUsed.equals(51234n, 51234n); // true
GasUsed.equals(51234n, 21000n); // false
```

#### `compare(gas1, gas2)`

Compare values (-1, 0, 1).

```typescript theme={null}
GasUsed.compare(21000n, 51234n); // -1 (first < second)
GasUsed.compare(51234n, 51234n); // 0 (equal)
GasUsed.compare(51234n, 21000n); // 1 (first > second)
```

### Utilities

#### `calculateCost(gasUsed, gasPrice)`

Calculate transaction cost in Wei.

```typescript theme={null}
const gasUsed = GasUsed.from(51234n);
const gasPrice = 20_000_000_000n; // 20 gwei

const cost = GasUsed.calculateCost(gasUsed, gasPrice);
// 1,024,680,000,000,000n Wei (0.00102468 ETH)
```

## Common Gas Costs

### Basic Operations

| Operation         | Gas Cost  |
| ----------------- | --------- |
| Simple transfer   | 21,000    |
| ERC20 transfer    | \~65,000  |
| Uniswap V2 swap   | \~150,000 |
| Contract creation | 32,000+   |

### Opcodes

| Opcode         | Gas Cost    |
| -------------- | ----------- |
| SLOAD (cold)   | 2,100       |
| SSTORE (set)   | 20,000      |
| SSTORE (reset) | 5,000       |
| CALL           | 100+        |
| CREATE         | 32,000+     |
| LOG0           | 375         |
| KECCAK256      | 30 + 6/word |

See [GasCosts](/primitives/gas-costs) for complete list.

## Usage Examples

### Calculate Transaction Cost

```typescript theme={null}
import { GasUsed } from '@tevm/primitives';

// Get from receipt
const receipt = await provider.getTransactionReceipt(txHash);
const gasUsed = GasUsed.from(receipt.gasUsed);

// Calculate cost
const gasPrice = receipt.effectiveGasPrice;
const cost = GasUsed.calculateCost(gasUsed, gasPrice);

console.log(`Gas used: ${GasUsed.toNumber(gasUsed)}`);
console.log(`Cost: ${cost} Wei`);
```

### Compare Gas Usage

```typescript theme={null}
import { GasUsed } from '@tevm/primitives';

const tx1Gas = GasUsed.from(receipt1.gasUsed);
const tx2Gas = GasUsed.from(receipt2.gasUsed);

if (GasUsed.compare(tx1Gas, tx2Gas) > 0) {
  console.log('Transaction 1 used more gas');
}
```

### Analyze Block Gas Usage

```typescript theme={null}
import { GasUsed } from '@tevm/primitives';

const block = await provider.getBlock(blockNumber, true);
let totalGas = 0n;

for (const tx of block.transactions) {
  const receipt = await provider.getTransactionReceipt(tx.hash);
  const gasUsed = GasUsed.from(receipt.gasUsed);
  totalGas += GasUsed.toBigInt(gasUsed);
}

console.log(`Block ${blockNumber} total gas: ${totalGas}`);
console.log(`Block utilization: ${(Number(totalGas) / 30_000_000 * 100).toFixed(2)}%`);
```

## Block Gas Limit

Ethereum blocks have a gas limit (\~30M on mainnet):

* Individual transaction: `gasUsed ≤ gasLimit` (set in tx)
* Block total: `Σ gasUsed ≤ blockGasLimit`
* Full block: High priority transactions fill blocks

## EIPs

* **EIP-2929**: Gas cost increases for state access opcodes
* **EIP-1559**: Fee market change (doesn't affect gasUsed, but introduces base fee)
* **EIP-3529**: Reduction in gas refunds (affects net cost but not gasUsed)

## See Also

* [GasEstimate](/primitives/gas-estimate) - Estimate gas before execution
* [GasRefund](/primitives/gas-refund) - Gas refunds after execution
* [GasCosts](/primitives/gas-costs) - Gas cost constants
* [Yellow Paper Section 6](https://ethereum.github.io/yellowpaper/paper.pdf) - Transaction execution
