---
eip: 5219
label: ERC-5219
title: Contract Resource Requests
status: Final
type: Standards Track
category: ERC
created: 2022-07-10
official: https://eips.ethereum.org/EIPS/eip-5219
source: https://github.com/ethereum/ERCs/blob/master/ERCS/erc-5219.md
canonical: https://eips.huatuo.xyz/zh/eip-5219/
lang: zh
tldr: 让智能合约通过一个 view 函数响应类似 HTTP 的 GET 请求，使 dApp 的前端可以直接从链上提供。
tags: [web3-url, frontend, decentralization, http]
---

# ERC-5219: Contract Resource Requests

> Allows the requesting of resources from contracts

**TL;DR:** 让智能合约通过一个 view 函数响应类似 HTTP 的 GET 请求，使 dApp 的前端可以直接从链上提供。

## 它解决什么问题？

大多数"去中心化"应用都是通过一个中心化网站访问的。合约也许无法被阻止，但前端可能被审查、下线、被悄悄篡改，或者干脆消失，用户必须信任托管它的人。

ERC-5219 为合约提供了一种自己提供资源的标准方式。客户端（浏览器扩展、网关或钱包）向合约请求某个路径，合约像 HTTP 服务器一样返回状态码、响应头和正文。这样，该界面就可以像合约本身一样持久且抗审查。

## 它如何运作

合规的合约实现一个只读函数：

```solidity
struct KeyValue { string key; string value; }

interface IDecentralizedApp {
    function request(string[] memory resource, KeyValue[] memory params)
        external view
        returns (uint16 statusCode, string memory body, KeyValue[] memory headers);
}
```

- `resource` 是按段拆分后的路径：`/asdf/1234` 变为 `["asdf", "1234"]`。
- `params` 是查询参数：`?foo=bar` 变为 `[{key: "foo", value: "bar"}]`。
- 响应与 HTTP 对应：状态码如 `200`、`404` 或 `307`，响应头如 `Content-Type`，以及正文。

设计选择：

- 只有类似 `GET` 的语义。该函数是 `view`，因此请求是免费的 `eth_call`，无需等待区块。状态变更通过普通交易进行，也可以用 `307` 重定向来提示。
- 在链上存储大型资源很昂贵，所以规范建议使用 `message/external-body` 响应指向其他位置的数据（例如 IPFS）。
- 建议把前端合约与应用逻辑合约分开。
- 名称解析交给其他标准。客户端也可以支持普通 DNS。

## 示例代码

一个微型链上网站：

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

struct KeyValue { string key; string value; }

contract HelloSite {
    function request(string[] memory resource, KeyValue[] memory)
        external pure
        returns (uint16 statusCode, string memory body, KeyValue[] memory headers)
    {
        headers = new KeyValue[](1);
        headers[0] = KeyValue("Content-Type", "text/html");
        if (resource.length == 0) {
            return (200, "<h1>Hello from a contract</h1>", headers);
        }
        return (404, "<h1>Not found</h1>", headers);
    }
}
```

从客户端调用它（ethers v6）：

```ts
const site = new Contract(address, [
  "function request(string[] resource, tuple(string key, string value)[] params) view returns (uint16, string, tuple(string key, string value)[])",
], provider);

const [status, body, headers] = await site.request([], []);
console.log(status, headers, body);
```

## 需要注意

- 状态为 **Final**。
- 通常的 URL 注意事项依然适用：跟随 `3xx` 重定向可能泄露隐私，或把用户带到链下。
- `view` 调用仍然受到节点对 gas 和响应大小的限制，因此大型页面需要分块或使用链下存储。
- Web3 URL 标准建立在它之上：[ERC-4804](/eip-4804/) 及其处于 Draft 状态的后继者 [ERC-6860](/eip-6860/) 把 `web3://` URL 映射为合约调用，[ERC-6944](/eip-6944/)（Draft）增加了返回 `"5219"` 的 `resolveMode()`，使这些 URL 通过 `request()` 路由。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-5219
