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

# 查询地址 ETH 余额

> 在 Function 中查询钱包 ETH 余额，读取已有价格并计算美元价值。

本教程查询以太坊主网地址 `0xd8da6bf26964af9d7eed9e03e53415d37aa96045` 的 ETH 余额，再从 `price.price.eth` 读取 ETH 价格，计算美元价值。

登录 [Chaintable 控制台](https://chaintable.com/spaces)，进入自己的 Space。本文使用 `demo`，操作时替换为你的 Space ID。

## 1. 创建 Function

在 **Functions** 中点击右上角 **+**，名称填 `wallet_eth_value`，点击 **Save and open**。将默认代码替换为：

```python theme={null}
def _(address):
    from blockdb import TimeTable
    from leafage import ChainState

    block = ChainState.get_latest_block('eth')
    chain = ChainState('eth', block['id'])
    balance_wei = chain.get_address_balance(address)
    price = TimeTable('price.price.eth').get(
        '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
    )
    balance_eth = balance_wei / 10 ** 18
    return {
        'address': address,
        'block_id': block['id'],
        'balance_wei': str(balance_wei),
        'balance_eth': balance_eth,
        'eth_price_usd': price['value'],
        'price_time': price['time_at'],
        'value_usd': balance_eth * float(price['value']),
    }
```

`ChainState` 读取最新区块的钱包余额，`TimeTable` 读取 ETH 价格。余额的原始单位是 wei，除以 `10 ** 18` 得到 ETH。

## 2. 设置测试参数

在编辑器下方的参数栏点击 **+**，添加：

| 设置                 | 值         |
| ------------------ | --------- |
| **Parameter name** | `address` |
| **Parameter Type** | `ADDRESS` |

保存参数并保存 Function。在 `address` 输入框中填入：

```text theme={null}
0xd8da6bf26964af9d7eed9e03e53415d37aa96045
```

离开输入框后点击 **Run**。

## 3. 查看结果

**Return** 显示余额、读取的区块、价格及其时间，以及计算出的美元价值。

<Frame>
  <img src="https://mintcdn.com/opcodelabspteltd/TOA0bb8_WqdBuVVN/images/quickstart/query-wallet-eth-balance/result.png?fit=max&auto=format&n=TOA0bb8_WqdBuVVN&q=85&s=6be7f840d21163098926f50e68b9ae78" alt="wallet_eth_value 返回指定钱包的 ETH 余额、ETH 价格、价格时间和美元价值" width="1920" height="1080" data-path="images/quickstart/query-wallet-eth-balance/result.png" />
</Frame>

| 字段              | 含义                  |
| --------------- | ------------------- |
| `balance_wei`   | 原始余额，以字符串返回，保留大整数精度 |
| `balance_eth`   | 换算后的 ETH 数量         |
| `block_id`      | 本次余额查询使用的区块 ID      |
| `eth_price_usd` | 价格表当前记录的 ETH 美元价格   |
| `price_time`    | 该价格记录的时间            |
| `value_usd`     | ETH 数量乘以美元价格        |

图中的余额约为 `6.71215 ETH`，实际结果会随链上余额变化。美元价值按价格表的最新记录估算，价格时间见 `price_time`。

## 可选：从外部调用

保存后的 Function ID 为 `demo.wallet_eth_value`。在其他应用中调用时，通过 OpenAPI 传入钱包地址，见[调用其他 Function](/zh/guides/openapi/calling#调用其他-function)。
