> ## 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.

# 数据访问

> 在 Function 中读取 Chaintable 表，并通过 Leafage 查询余额和合约状态。

Function 可以在计算过程中读取已有数据。表查询使用 BlockDB SDK，链上余额和合约调用使用 Leafage。将导入写在函数体内，查询结果通过 `return` 交给调用方。

## 读取 Chaintable 表

下面的函数读取以太坊价格表中原生 ETH 的最新记录。在自己的 Space 创建 Function，填入代码并点击 **Run**，无需设置参数。

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

    return TimeTable('price.price.eth').get(
        '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
    )
```

记录包含 `id`、`time_at` 和 `value`，分别表示代币 ID、价格时间和价格。

根据表类型选择 SDK 类：

| 表类型   | 读取入口                                     |
| ----- | ---------------------------------------- |
| 普通表   | `NormalTable(table_id).get(id)`          |
| 区块事件表 | `EventTable(table_id, block_id).get(id)` |
| 区块状态表 | `StateTable(table_id, block_id).get(id)` |
| 时间表   | `TimeTable(table_id, time_at).get(id)`   |

省略区块或时间参数时读取的是最新值，不会退回共识高度；各类表的默认读取行为见[工作原理](/zh/guides/tables/model#区块数据与处理进度)。

**在区块处理函数中**，应传入当前处理的区块 ID，读取该区块的数据。服务端会检查表的共识高度是否已覆盖该区块。

查不到记录时，`get()` 返回 `None`。在访问 `row['value']` 等字段前，根据业务需要处理缺失记录。

完整参数和批量读取见 [blockdb-py](/zh/reference/sdk/blockdb-py)。

## 查询链上余额

Leafage 用 Chaintable 链 ID 和区块 ID 定位链上状态。以太坊的 Chaintable 链 ID 为 `eth`。

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

    block = ChainState.get_latest_block('eth')
    chain = ChainState('eth', block['id'])
    return {
        'block': block,
        'balance_wei': str(chain.get_address_balance(address)),
    }
```

设置 `address` 参数为 `ADDRESS`，使用地址 `0xd8da6bf26964af9d7eed9e03e53415d37aa96045` 测试。余额单位为 wei；返回字符串可以保留整数精度。

## 调用合约

下面读取指定历史区块的 Uniswap V2 USDC–ETH 池储备：

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

    block = ChainState.get_block_by_height('eth', 25939934)
    chain = ChainState('eth', block['id'])
    usdc, weth, timestamp = chain.call(
        '0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc',
        'getReserves()(uint112,uint112,uint32)',
        [],
    )
    return {
        'reserve_usdc': str(usdc),
        'reserve_weth': str(weth),
        'timestamp': timestamp,
    }
```

方法签名同时写出输入类型和返回类型。`getReserves()` 没有输入参数，因此传入空列表；它返回两项储备和合约记录的更新时间。
