> 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-ko/sdk7/blockchain/scene-blockchain-operations.md).

# 씬 블록체인 작업

Ethereum 블록체인에서 작업을 수행하기 위해 SDK가 제공하는 기능을 알아봅니다

Decentraland 씬은 Ethereum 블록체인과 연동할 수 있습니다. 이를 통해 사용자의 지갑과 그 안에 있는 토큰에 대한 데이터를 가져오거나, 대체 가능 또는 대체 불가능한 모든 Ethereum 토큰이 관련된 트랜잭션을 실행할 수 있습니다. 예를 들어 토큰을 판매하거나, 게임 메커니즘의 일부로 토큰을 보상으로 지급하거나, 플레이어가 특정 토큰을 소유한 경우 씬과 상호작용하는 방식을 변경하는 등 다양한 용도로 활용할 수 있습니다.

씬에서 실행하는 Ethereum 메인넷의 모든 트랜잭션은 플레이어의 승인과 가스비 지불이 필요합니다.

또한 모든 블록체인 작업은 [비동기 함수](https://docs.decentraland.org/creator/content-creator-ko/sdk7/programming-patterns/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-ko/sdk7/interactivity/user-data.md#get-player-data)

{% hint style="warning" %}
**📔 참고**: Ethereum 주소에 대문자가 포함되어 있더라도 일부 브라우저는 반환된 문자열을 자동으로 소문자로 변환합니다. 모든 브라우저에서 주소 값을 비교하려면 `.toLowerCase()` 메서드를 사용하여 값을 소문자로 변환하세요.
{% endhint %}

## 가스 가격 확인하기

먼저 `eth-connect` 라이브러리를 가져온 후 web3 공급자와 요청 관리자 인스턴스를 생성해야 합니다. 이를 통해 플레이어의 브라우저에 있는 MetaMask에 web3로 연결할 수 있습니다.

다음 함수는 Ethereum 메인넷의 현재 가스 가격을 가져와 출력합니다.

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

executeTask(async function () {
  // MetaMask와 연동할 web3 공급자 인스턴스 생성
  const provider = createEthereumProvider();
  // RPC 메시지 송수신을 처리할 객체 생성
  const requestManager = new RequestManager(provider);
  // Ethereum 네트워크의 현재 가스 가격 확인
  const gasPrice = await requestManager.eth_gasPrice();
  // 응답 로그 출력
  console.log({ gasPrice });
});
```

{% hint style="info" %}
**💡 팁**: `requestManager` 가 처리하는 함수는 외부 데이터를 가져와야 하므로 완료까지 시간이 걸릴 수 있습니다. 따라서 `await`를 사용하여 호출해야 합니다.
{% endhint %}

## 컨트랙트 ABI 가져오기

ABI(Application Binary Interface, 애플리케이션 바이너리 인터페이스)는 이더리움 컨트랙트와 상호작용하는 방법을 설명하며, 사용할 수 있는 함수와 각 함수가 받는 입력 및 반환하는 출력을 정의합니다. 이더리움 컨트랙트마다 고유한 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를 얻으려면 *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 %}

JSON 파일을 가져올 수 있도록 TypeScript를 설정하는 데는 어려움이 따릅니다. 더 간단한 해결 방법으로는 `ABI.JSON` 파일의 확장자를 `.ts` 로 변경하고, 내용이 다음으로 시작하도록 약간 수정하는 방법을 권장합니다. `export default`.

예를 들어 ABI 파일의 내용이 다음으로 시작한다면 `[{"constant":true,"inputs":[{"internalType":"bytes4" ...etc`, 다음으로 시작하도록 수정합니다 `export default [{"constant":true,"inputs":[{"internalType":"bytes4" ...etc`.

### 컨트랙트 인스턴스 생성

다음을 가져온 후 `eth-connect` 라이브러리와 컨트랙트의 *abi*, 컨트랙트의 함수를 사용하고 플레이어의 브라우저에서 Metamask에 연결할 수 있도록 여러 객체를 인스턴스화해야 합니다.

웹3 프로바이더도 가져와야 합니다. 플레이어의 브라우저에서 Metamask가 web3를 사용하기 때문에, 이와 상호작용할 방법이 필요합니다.

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

executeTask(async () => {
  // MetaMask와 연동할 web3 공급자 인스턴스 생성
  const provider = createEthereumProvider();
  // RPC 메시지 송수신을 처리할 객체 생성
  const requestManager = new RequestManager(provider);
  // abi를 기반으로 팩토리 객체 생성
  const factory = new ContractFactory(requestManager, abi);
  // 팩토리 객체를 사용해 특정 컨트랙트를 참조하는 `contract` 객체 인스턴스화
  const contract = (await factory.at(
    "0x2a8fd99c19271f4f04b1b7b9c4f7cf264b626edb"
  )) as any;
});
```

{% hint style="info" %}
**💡 팁**: ERC20 또는 ERC721처럼 동일한 표준을 따르는 컨트랙트의 경우, 모두에 사용할 수 있는 단일 범용 ABI를 가져올 수 있습니다. 그런 다음 해당 ABI로 단일 `ContractFactory` 객체를 생성하고, 같은 팩토리로 각 컨트랙트의 인터페이스를 인스턴스화할 수 있습니다.
{% endhint %}

### 컨트랙트의 메서드 호출

contract `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 {
    // 위 섹션에서 설명한 설정 단계
    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;
    }

    // 컨트랙트 함수 실행
    const res = await contract.setBalance(
      "0xaFA48Fad27C7cAB28dC6E970E4BFda7F7c8D60Fb",
      100,
      {
        from: userData.userId,
      }
    );
    // 응답 기록
    console.log(res);
  } catch (error: any) {
    console.log(error.toString());
  }
});
```

위 예제에서는 *가짜 MANA* 테스트 컨트랙트의 abi를 사용하고, 해당 컨트랙트의 `setBalance` 메서드를 호출해 계정에 100 *가짜 MANA* 을 부여합니다. 이 예제를 적용할 때는 주소와 abi를 호출하려는 컨트랙트의 것으로 바꾸고, 해당 abi에 정의된 메서드를 호출하세요.

### 기타 함수

eth-connect 라이브러리에는 사용할 수 있는 여러 헬퍼가 포함되어 있습니다. 예를 들면 다음과 같습니다.

* 예상 가스 가격 가져오기
* 지정된 주소의 잔액 가져오기
* 트랜잭션 영수증 가져오기
* 주소에서 전송된 트랜잭션 수 가져오기
* 16진수, 이진수, utf8 등 다양한 형식 간 변환

## 이더리움 테스트 네트워크 사용

씬을 테스트하는 동안 실제 MANA나 다른 통화를 전송하지 않으려면 *Ethereum Sepolia 테스트 네트워크* 를 사용해 실제 가치가 없는 테스트넷 MANA를 전송할 수 있습니다.

테스트 네트워크를 사용하려면 Metamask Chrome 확장 프로그램에서 *Sepolia 테스트 네트워크* 대신 *메인 네트워크*.

Sepolia Ether를 확보해야 합니다. Sepolia Ether는 다음과 같은 여러 외부 수도꼭지에서 무료로 받을 수 있습니다. [여기](https://www.alchemy.com/faucets/ethereum-sepolia/).

{% hint style="info" %}
**💡 팁**: Sepolia MANA를 지갑으로 전송하는 트랜잭션을 실행하려면 Sepolia Ether로 가스 수수료를 지불해야 합니다.
{% 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 쪽에서 ‘스왑’을 클릭하세요.

Ethereum 라이브러리를 사용하는 씬을 레거시 웹 클라이언트에서 미리 보려면, 별도의 브라우저 창에서 미리보기를 열고 브라우저에서 Metamask를 실행한 다음 문자열을 직접 추가해야 합니다. `&ENABLE_WEB3`.

## 사용자 지정 RPC 메시지 보내기

RPC 프로토콜을 통해 메시지를 보내려면 `sendAsync()` 함수를 사용하세요. [RPC 프로토콜](https://en.wikipedia.org/wiki/Remote_procedure_call).

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

// send a message
await sendAsync({
  id: 1,
  method: "myMethod",
  jsonParams: "{ myParam: myValue }",
});
```

## Decentraland 스마트 계약

다음 링크에서 Decentraland 생태계와 관련된 Ethereum 스마트 계약 목록을 확인할 수 있습니다. 이 목록에는 메인넷과 다른 Ethereum 테스트 네트워크의 계약이 모두 포함되어 있습니다.

[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-ko/sdk7/blockchain/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.
