> ## Documentation Index
> Fetch the complete documentation index at: https://seilabs-docs-evm-cookbook.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Read a price feed

> Read the latest SEI/USD price from the API3 data feed on Sei Mainnet with viem, ethers, or web3.py, and check that the price is fresh before you use it.

export const RunSnippet = props => {
  const {method = 'eth_blockNumber', params = [], network = 'testnet', endpoint, label, title, description, decode = 'auto'} = props || ({});
  const ENDPOINTS = {
    testnet: 'https://evm-rpc-testnet.sei-apis.com',
    mainnet: 'https://evm-rpc.sei-apis.com'
  };
  const rpcUrl = endpoint || ENDPOINTS[network] || ENDPOINTS.testnet;
  const networkLabel = network === 'mainnet' ? 'Sei Mainnet' : network === 'testnet' ? 'Sei Testnet' : network;
  const requestBody = {
    jsonrpc: '2.0',
    id: 1,
    method,
    params
  };
  const requestJson = JSON.stringify(requestBody, null, 2);
  const [phase, setPhase] = useState('idle');
  const [result, setResult] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [elapsed, setElapsed] = useState(null);
  const [copied, setCopied] = useState(false);
  const [btnHover, setBtnHover] = useState(false);
  const groupThousands = s => s.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  const hexToDecimal = value => {
    if (typeof value !== 'string' || !(/^0x[0-9a-fA-F]+$/).test(value)) return null;
    if (value.length > 66) return null;
    try {
      return groupThousands(BigInt(value).toString(10));
    } catch (e) {
      return null;
    }
  };
  const run = async () => {
    setPhase('loading');
    setErrorMsg(null);
    setResult(null);
    setElapsed(null);
    const startedAt = typeof performance !== 'undefined' ? performance.now() : null;
    try {
      const response = await fetch(rpcUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      });
      const data = await response.json();
      if (startedAt != null && typeof performance !== 'undefined') {
        setElapsed(Math.round(performance.now() - startedAt));
      }
      if (data && data.error) {
        setErrorMsg(data.error.message || 'RPC returned an error');
        setPhase('error');
        return;
      }
      setResult(data ? data.result : undefined);
      setPhase('success');
    } catch (err) {
      setErrorMsg(err && err.message ? err.message : 'Request failed');
      setPhase('error');
    }
  };
  const resultString = result === undefined ? 'undefined' : JSON.stringify(result, null, 2);
  const decoded = decode !== 'off' && typeof result === 'string' ? hexToDecimal(result) : null;
  const copyResult = () => {
    const flashCopied = () => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    };
    if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(resultString).then(flashCopied, () => {});
      return;
    }
    if (typeof document !== 'undefined') {
      try {
        const ta = document.createElement('textarea');
        ta.value = resultString;
        ta.style.position = 'fixed';
        ta.style.opacity = '0';
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        flashCopied();
      } catch (e) {}
    }
  };
  const HAIRLINE = 'rgba(128, 128, 128, 0.25)';
  const surfaceStyle = {
    backgroundColor: 'rgba(128, 128, 128, 0.08)'
  };
  const monoStyle = {
    fontFamily: 'var(--sei-font-mono)'
  };
  const codeStyle = {
    backgroundColor: 'rgba(128, 128, 128, 0.05)',
    fontFamily: 'var(--sei-font-mono)'
  };
  const buttonStyle = {
    backgroundColor: btnHover ? 'var(--sei-maroon-200)' : 'var(--sei-maroon-100)',
    color: '#ffffff',
    fontFamily: 'var(--sei-font-mono)',
    textTransform: 'uppercase',
    letterSpacing: '0.04em',
    fontSize: '10px',
    opacity: phase === 'loading' ? 0.7 : 1,
    cursor: phase === 'loading' ? 'default' : 'pointer'
  };
  return <div className="not-prose w-full rounded-lg border overflow-hidden my-4" style={{
    borderColor: HAIRLINE
  }}>
			<div className="flex items-center justify-between gap-3 px-4 py-2.5 border-b" style={{
    ...surfaceStyle,
    borderBottomColor: HAIRLINE
  }}>
				<div className="flex flex-col min-w-0">
					<span className="text-sm font-medium text-neutral-900 dark:text-white truncate" style={monoStyle}>
						{title || method}
					</span>
					<span className="text-xs text-neutral-600 dark:text-neutral-400">{networkLabel}</span>
				</div>
				<button type="button" onClick={run} disabled={phase === 'loading'} onMouseEnter={() => setBtnHover(true)} onMouseLeave={() => setBtnHover(false)} className="inline-flex items-center gap-1.5 px-3 py-1.5 shrink-0 transition-colors" style={buttonStyle}>
					{phase === 'loading' ? <svg className="animate-spin h-4 w-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
								<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
								<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 0 1 8-8v4a4 4 0 0 0-4 4H4z" />
							</svg> : <svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
								<path d="M8 5v14l11-7z" />
							</svg>}
					{phase === 'loading' ? 'Running…' : label || 'Run'}
				</button>
			</div>

			{description ? <div className="px-4 pt-3 text-sm text-neutral-600 dark:text-neutral-400">{description}</div> : null}

			<div className="px-4 pt-3 pb-1">
				<span className="text-xs uppercase tracking-wide text-neutral-600 dark:text-neutral-400">Request</span>
			</div>
			<pre className="m-0 px-4 py-3 text-sm overflow-x-auto text-neutral-700 dark:text-neutral-300" style={codeStyle}>
				{requestJson}
			</pre>

			{phase === 'success' ? <div className="border-t" style={{
    borderTopColor: HAIRLINE
  }}>
					<div className="flex items-center justify-between px-4 pt-3 pb-1">
						<span className="text-xs uppercase tracking-wide text-neutral-600 dark:text-neutral-400">Response{elapsed != null ? ` · ${elapsed} ms` : ''}</span>
						<button type="button" onClick={copyResult} className="text-xs text-neutral-500 hover:text-neutral-800 dark:text-neutral-400 dark:hover:text-neutral-200 transition-colors">
							{copied ? 'Copied' : 'Copy'}
						</button>
					</div>
					<pre className="m-0 px-4 py-3 text-sm overflow-x-auto text-neutral-700 dark:text-neutral-300" style={codeStyle}>
						{resultString}
					</pre>
					{decoded ? <div className="px-4 pb-3 text-xs text-neutral-600 dark:text-neutral-400" style={monoStyle}>
							= {decoded} (decimal)
						</div> : null}
				</div> : null}

			{phase === 'error' ? <div className="border-t" style={{
    borderTopColor: HAIRLINE
  }}>
					<div className="px-4 pt-3 pb-1">
						<span className="text-xs uppercase tracking-wide text-neutral-600 dark:text-neutral-400">Error</span>
					</div>
					<pre className="m-0 px-4 py-3 text-sm overflow-x-auto text-red-600 dark:text-red-400" style={codeStyle}>
						{errorMsg}
					</pre>
				</div> : null}
		</div>;
};

The native [Oracle precompile](/evm/precompiles/oracle) is retired, so price data on Sei comes from third-party oracles. This recipe reads [API3](/evm/oracles/api3)'s SEI/USD feed. API3 pushes new prices on-chain, so the latest price is already stored in a contract. Reading it is a free view call. You do not need a key, an API token, or SEI.

| Feed | Network | Proxy address | Decimals |
| - | - | - | - |
| SEI/USD | Sei Mainnet | `0x09c6e594DE2EB633902f00B87A43b27F80a31a60` | 18 |

<Warning>Read the feed on Sei Mainnet. When this recipe was tested, the same address on Sei Testnet returned a value that was months old. Always check the timestamp, as the examples below do.</Warning>

## Try it live

This call runs the proxy's `read()` function (selector `0x57de26a4`) from your browser. The response holds two 32-byte values. The first is the price with 18 decimals. The second is the Unix time of the last update.

<RunSnippet method="eth_call" params={[{ to: '0x09c6e594DE2EB633902f00B87A43b27F80a31a60', data: '0x57de26a4' }, 'latest']} network="mainnet" title="Api3ReaderProxy.read()" description="Latest SEI/USD value and its update time from the API3 proxy on Sei Mainnet." />

## Install

<CodeGroup>
  ```bash viem theme={null}
  npm install viem
  ```

  ```bash ethers theme={null}
  npm install ethers
  ```

  ```bash web3.py theme={null}
  pip install web3
  ```
</CodeGroup>

## Read the price

<CodeGroup>
  ```ts viem theme={null}
  import { createPublicClient, http, parseAbi, formatUnits } from 'viem';
  import { sei } from 'viem/chains';

  const client = createPublicClient({ chain: sei, transport: http() });

  const SEI_USD = '0x09c6e594DE2EB633902f00B87A43b27F80a31a60';
  const abi = parseAbi(['function read() view returns (int224 value, uint32 timestamp)']);

  const [value, timestamp] = await client.readContract({ address: SEI_USD, abi, functionName: 'read' });

  const ageSeconds = Math.floor(Date.now() / 1000) - timestamp;
  if (value <= 0n || ageSeconds > 24 * 60 * 60) {
    throw new Error(`Unusable price: ${value} (updated ${ageSeconds} seconds ago)`);
  }
  console.log(`SEI/USD: ${formatUnits(value, 18)} (updated ${ageSeconds} seconds ago)`);
  ```

  ```ts ethers theme={null}
  import { ethers } from 'ethers';

  const provider = new ethers.JsonRpcProvider('https://evm-rpc.sei-apis.com');

  const SEI_USD = '0x09c6e594DE2EB633902f00B87A43b27F80a31a60';
  const feed = new ethers.Contract(
    SEI_USD,
    ['function read() view returns (int224 value, uint32 timestamp)'],
    provider
  );

  const [value, timestamp] = await feed.read();

  const ageSeconds = Math.floor(Date.now() / 1000) - Number(timestamp);
  if (value <= 0n || ageSeconds > 24 * 60 * 60) {
    throw new Error(`Unusable price: ${value} (updated ${ageSeconds} seconds ago)`);
  }
  console.log(`SEI/USD: ${ethers.formatUnits(value, 18)} (updated ${ageSeconds} seconds ago)`);
  ```

  ```python web3.py theme={null}
  import time
  from decimal import Decimal
  from web3 import Web3

  w3 = Web3(Web3.HTTPProvider("https://evm-rpc.sei-apis.com"))

  SEI_USD = "0x09c6e594DE2EB633902f00B87A43b27F80a31a60"
  abi = [{
      "type": "function", "name": "read", "stateMutability": "view", "inputs": [],
      "outputs": [{"name": "value", "type": "int224"}, {"name": "timestamp", "type": "uint32"}],
  }]
  feed = w3.eth.contract(address=SEI_USD, abi=abi)

  value, timestamp = feed.functions.read().call()

  age_seconds = int(time.time()) - timestamp
  if value <= 0 or age_seconds > 24 * 60 * 60:
      raise ValueError(f"Unusable price: {value} (updated {age_seconds} seconds ago)")
  print(f"SEI/USD: {Decimal(value) / 10**18} (updated {age_seconds} seconds ago)")
  ```
</CodeGroup>

**You are done when you see:**

```text theme={null}
SEI/USD: 0.0721 (updated 181 seconds ago)
```

The price is illustrative. API3 updates a feed when the price moves past the feed's deviation threshold, and at least once every 24 hours when the price is flat. The examples therefore reject a value that is not positive or is more than 24 hours old. See API3's [update parameters](https://docs.api3.org/dapps/integration/#update-parameters) for details.

## Use the price in a contract

A contract reads the same proxy through API3's `IApi3ReaderProxy` interface and should apply the same checks. The [API3 guide](/evm/oracles/api3) has a complete consumer contract.

## Other oracles on Sei

[Chainlink Data Streams](/evm/oracles/chainlink), [Pyth](/evm/oracles/pyth-network), and [RedStone](/evm/oracles/redstone) are pull oracles. Your transaction carries a signed, current price with it. A view call on its own returns either nothing or the last price that someone else submitted, which can be old. Follow their guides to use them.

## Related recipes

* [Read a balance](/evm/cookbook/read-a-balance): other read-only contract calls
* [Multicall](/evm/evm-parity/examples/multicall): read a price feed and other data in one request


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.