> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/qu-kuai-lian/scene-blockchain-operations.md).

# 场景区块链操作

了解 SDK 提供了哪些用于执行以太坊区块链操作的功能

Decentraland 场景可以与 Ethereum 区块链交互。这可用于获取有关玩家钱包及其中代币的数据，也可以触发涉及任意 Ethereum 代币（同质化或非同质化）的交易。此功能有多种用途，例如出售代币、将代币作为游戏机制的一部分发放奖励，或在玩家持有特定代币时改变其与场景的交互方式等。

请注意，场景在 Ethereum 主网上触发的所有交易都需要玩家批准并支付 Gas 费。

所有区块链操作还必须以 [异步函数](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/async-functions.md)的形式执行，因为执行时机取决于外部事件。

## 获取玩家的 Ethereum 账户

要获取玩家的 Ethereum 账户，请使用 `getPlayer()` 函数。

```ts
import { getPlayer } from "@dcl/sdk/src/players";

export function main() {
  let userData = getPlayer();
  if (!userData) return;
  if (!userData.isGuest) {
    console.log(userData.userId);
  } else {
    console.log("Player is not connected with Web3");
  }
}
```

请注意，如果玩家以访客身份进入 Decentraland，他们将没有连接的 Ethereum 钱包。如果玩家以访客身份连接，响应中的 `isGuest` 字段（来自 `getPlayer()` ）将为 true。否则，可以从 `userId` 字段获取玩家的钱包地址。有关可从玩家获取的数据的更多信息，请参阅 [获取玩家数据](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/user-data.md#get-player-data)

{% hint style="warning" %}
**📔 注意**：尽管 Ethereum 地址可能包含大写字母，但某些浏览器会自动将返回的字符串转换为小写。如果希望比较地址值并确保代码在所有浏览器中都能正常工作，请使用 `.toLowerCase()` 方法将值转换为小写。
{% endhint %}

## 检查 Gas 价格

导入 `eth-connect` 库后，必须实例化一个 Web3 提供程序和一个请求管理器，以便通过 Web3 连接到玩家浏览器中的 Metamask。

以下函数会获取 Ethereum 主网上当前的 Gas 价格并将其打印出来。

```ts
import { RequestManager } from "eth-connect";
import { createEthereumProvider } from "@dcl/sdk/ethereum-provider";

executeTask(async function () {
  // 创建 Web3 提供程序实例，以便与 Metamask 交互
  const provider = createEthereumProvider();
  // 创建用于发送和接收 RPC 消息的对象
  const requestManager = new RequestManager(provider);
  // 检查 Ethereum 网络上的当前 Gas 价格
  const gasPrice = await requestManager.eth_gasPrice();
  // 记录响应
  console.log({ gasPrice });
});
```

{% hint style="info" %}
**💡 提示**：请注意， `requestManager` 处理的函数必须使用 `await`调用，因为这些函数依赖于获取外部数据，可能需要一些时间才能完成。
{% endhint %}

## 导入合约 ABI

ABI（应用程序二进制接口）描述了与以太坊合约交互的方式，决定了合约提供哪些函数、这些函数接受哪些输入以及会输出什么。每个以太坊合约都有自己的 ABI，因此你应该在项目中导入所有需要使用的合约的 ABI。

例如，以下是 MANA ABI 中一个函数的示例：

```ts
{
  anonymous: false,
  inputs: [
    {
      indexed: true,
      name: 'burner',
      type: 'address'
    },
    {
      indexed: false,
      name: 'value',
      type: 'uint256'
    }
  ],
  name: 'Burn',
  type: 'event'
}
```

ABI 定义可能相当冗长，因为通常包含许多函数，因此我们建议将 ABI 文件的 JSON 内容粘贴到单独的 `.ts` 文件中，然后从其他场景文件中导入。我们还建议将所有 ABI 文件放在场景中的单独文件夹内，并将其命名为 `/contracts`.

```ts
import { abi } from "../contracts/mana";
```

以下是 Decentraland 各类合约的链接。点击 *导出 ABI* 并选择 *JSON 格式*.

* [MANA 代币 ABI](https://etherscan.io/address/0x0f5d2fb29fb7d3cfee444a200298f468908cc942#code)
* [Decentraland 市场](https://etherscan.io/address/0x19a8ed4860007a66805782ed7e0bed4e44fc6717#code)
* [LAND ABI](https://etherscan.io/address/0xf87e31492faf9a91b02ee0deaad50d51d56d5d4d#code)
* [Estate ABI](https://etherscan.io/address/0x959e104e1a4db6317fa58f8295f586e1a978c297#code)
* [AvatarNameRegistry ABI](https://etherscan.io/address/0x894b883905bfEe2CC448880F1b59f4A762E67566)
* [Catalyst ABI](https://etherscan.io/address/0xcc054fab08127c19f621ab83ade5962cd10584ec)

以下是各种可穿戴物品系列对应的合约：（每个系列都作为单独的合约发布）

* [ExclusiveMasksCollection ABI](https://etherscan.io/address/0xc04528c14c8ffd84c7c1fb6719b4a89853035cdd)
* [Halloween2019Collection ABI](https://etherscan.io/address/0xc1f4b0eea2bd6690930e6c66efd3e197d620b9c2)
* [Halloween2019CollectionFactory ABI](https://etherscan.io/address/0x07ccfd0fbada4ac3c22ecd38037ca5e5c0ad8cfa)
* [Xmas2019Collection ABI](https://etherscan.io/address/0xc3af02c0fd486c8e9da5788b915d6fff3f049866)
* [MCHCollection ABI](https://etherscan.io/address/0xf64dc33a192e056bb5f0e5049356a0498b502d50)
* [CommunityContestCollection ABI](https://etherscan.io/address/0x32b7495895264ac9d0b12d32afd435453458b1c6)
* [DCLLaunchCollection ABI](https://etherscan.io/address/0xd35147be6401dcb20811f2104c33de8e97ed6818)
* [DCGCollection ABI](https://etherscan.io/address/0x3163d2cfee3183f9874e2869942cc62649eeb004)

{% hint style="info" %}
**💡 提示**：要清楚查看合约公开的函数，请在 [abitopic.io](https://abitopic.io)中打开合约。只需粘贴合约地址，然后打开 *函数* 选项卡，即可查看受支持函数及其参数的完整列表。你还可以通过该网页使用不同参数测试调用这些函数。
{% endhint %}

配置 TypeScript 以便从 JSON 文件导入内容并不容易。建议采用一种更简单的变通方法：将 `ABI.JSON` 文件的扩展名改为 `.ts` 并稍作修改，使文件内容以 `export default`.

开头。例如，如果 ABI 文件的内容以 `[{"constant":true,"inputs":[{"internalType":"bytes4" ...etc`，将其修改为以以下内容开头 `export default [{"constant":true,"inputs":[{"internalType":"bytes4" ...etc`.

### 实例化合约

导入 `eth-connect` 库和合约的 *abi*后，你必须实例化几个对象，才能使用合约中的函数，并连接到玩家浏览器中的 Metamask。

你还必须导入 web3 提供程序。这是因为玩家浏览器中的 Metamask 使用 web3，因此我们需要一种与之交互的方式。

```ts
import { RequestManager, ContractFactory } from "eth-connect";
import { createEthereumProvider } from "@dcl/sdk/ethereum-provider";
import { abi } from "../contracts/mana";

executeTask(async () => {
  // 创建 Web3 提供程序实例，以便与 Metamask 交互
  const provider = createEthereumProvider();
  // 创建用于发送和接收 RPC 消息的对象
  const requestManager = new RequestManager(provider);
  // Create a factory object based on the abi
  const factory = new ContractFactory(requestManager, abi);
  // Use the factory object to instance a `contract` object, referencing a specific contract
  const contract = (await factory.at(
    "0x2a8fd99c19271f4f04b1b7b9c4f7cf264b626edb"
  )) as any;
});
```

{% hint style="info" %}
**💡 提示**：对于遵循相同标准（例如 ERC20 或 ERC721）的合约，可以为它们全部导入一个通用 ABI。然后，你只需用该 ABI 创建一个 `ContractFactory` 对象，并使用同一个工厂为每个合约实例化接口。
{% endhint %}

### 调用合约中的方法

创建 `contract` 对象后，你可以轻松调用其 ABI 中定义的函数，并传入指定的输入参数。

```ts
import { getPlayer } from "@dcl/sdk/src/players";
import { createEthereumProvider } from "@dcl/sdk/ethereum-provider";
import { RequestManager, ContractFactory } from "eth-connect";
import { abi } from "../contracts/mana";

executeTask(async () => {
  try {
    // Setup steps explained in the section above
    const provider = createEthereumProvider();
    const requestManager = new RequestManager(provider);
    const factory = new ContractFactory(requestManager, abi);
    const contract = (await factory.at(
      "0x2a8fd99c19271f4f04b1b7b9c4f7cf264b626edb"
    )) as any;
    let userData = getPlayer();
    if (!userData || userData.isGuest) {
      return;
    }

    // Perform a function from the contract
    const res = await contract.setBalance(
      "0xaFA48Fad27C7cAB28dC6E970E4BFda7F7c8D60Fb",
      100,
      {
        from: userData.userId,
      }
    );
    // Log response
    console.log(res);
  } catch (error: any) {
    console.log(error.toString());
  }
});
```

上面的示例使用了一个 *虚假的 MANA* 测试合约的 ABI，并调用其 `setBalance` 方法向一个账户发放 100 个 *虚假的 MANA* 。根据需要调整此示例时，请将地址和 ABI 替换为你要调用的合约对应的地址和 ABI，并调用其 ABI 中定义的方法。

### 其他函数

eth-connect 库还包含许多其他可用的辅助工具。例如，你可以：

* 获取预估 Gas 价格
* 获取指定地址的余额
* 获取交易回执
* 获取从某个地址发出的交易数量
* 在各种格式之间进行转换，包括十六进制、二进制、UTF-8 等。

## 使用以太坊测试网络

在测试场景时，为避免转移真实的 MANA 或其他货币，你可以使用 *Ethereum Sepolia 测试网络* ，转而转移假的测试网 MANA。

要使用测试网络，你必须将 Metamask Chrome 扩展程序设置为使用 *Sepolia 测试网络* ，而不是 *主网络*.

你必须获取 Sepolia Ether。你可以从各种外部水龙头免费获取，例如 [这个水龙头](https://www.alchemy.com/faucets/ethereum-sepolia/).

{% hint style="info" %}
**💡 提示**：要执行将 Sepolia MANA 转入钱包的交易，你需要支付 Sepolia Ether 作为 Gas 费。
{% endhint %}

要使用测试网络预览场景，请将以下 URL 粘贴到浏览器标签页中。这会在 Decentraland 桌面客户端中打开场景：

`decentraland://realm=http://127.0.0.1:8000&local-scene=true&debug=true&dclenv=zone&position=0,0`

{% hint style="info" %}
**💡 提示**：将 position 参数更改为场景坐标，即可直接加载到场景中。
{% endhint %}

在此模式下查看场景时，你确认的任何交易都只会在测试网络上发生，不会影响真实钱包中的 MANA 余额。

如果你需要在 Polygon 测试网上测试交易，并且需要在该测试网上拥有 MANA，那么在 Sepolia 获取 MANA 后，你需要将其兑换到该网络。要将 Sepolia MANA 跨链桥接到 Polygon 测试网，请访问你的 [Sepolia 中的 Decentraland 账户页面](https://account.decentraland.zone/) ，然后点击 Ethereum MANA 一侧的“swap”。

在旧版 Web 客户端中预览使用某个以太坊库的场景时，你必须在单独的浏览器窗口中打开预览，在浏览器中打开 Metamask，并手动添加字符串 `&ENABLE_WEB3`.

## 发送自定义 RPC 消息

使用函数 `sendAsync()` 通过 [RPC 协议](https://en.wikipedia.org/wiki/Remote_procedure_call).

```ts
import { sendAsync } from "~system/EthereumController";

// 发送消息
await sendAsync({
  id: 1,
  method: "myMethod",
  jsonParams: "{ myParam: myValue }",
});
```

## Decentraland 智能合约

以下链接列出了与 Decentraland 生态系统相关的以太坊智能合约。该列表包含主网上以及其他以太坊测试网络上的合约。

[contracts.decentraland.org](https://contracts.decentraland.org/links)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/qu-kuai-lian/scene-blockchain-operations.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
