> For the complete documentation index, see [llms.txt](https://docs.chiliz.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.chiliz.com/ko/gaebal/goseup/omnicheun-token/chiliz-base-beuriji.md).

# Chiliz Chain에서 Base로 브리지

Chiliz Chain에서 Base로 기존 토큰을 브릿징하려면 두 개의 별도 스마트 컨트랙트를 작성하고 배포해야 합니다: 토큰이 이미 존재하는 체인(Chiliz Chain)에 OFT 어댑터를, 대상 체인(Base)에 네이티브 OFT를 배포합니다.

{% hint style="info" %}
LayerZero는 [OFT 컨트랙트에 대한 자체 QuickStart](https://docs.layerzero.network/v2/developers/evm/oft/quickstart)와 Base 같은 [다른 EVM 체인으로의 민팅 방법 튜토리얼](https://docs.layerzero.network/v2/deployments/evm-chains/chiliz-mainnet-oft-quickstart)을 제공합니다. 해당 튜토리얼은 Optimism을 대상 체인으로 사용하지만, [Base의 세부 정보](https://docs.layerzero.network/v2/deployments/chains/base)로 대체할 수 있습니다.
{% endhint %}

## 사전 요구사항

이 가이드에는 다음이 필요합니다:

* Chiliz Chain의 ERC20 토큰 컨트랙트 주소.
* Chiliz Chain과 Base 모두에서 작동하도록 설정된 Web3 지갑(예: MetaMask).
  * [Chiliz Chain RPC 구성은 여기를 참조하세요](/ko/gaebal/gibon/chiliz-chain-yeongyeol/rpc-yeongyeol.md).
  * [Base Mainnet RPC 구성은 여기를 참조하세요](https://docs.base.org/base-chain/quickstart/connecting-to-base).
* 컨트랙트 배포 및 메시지 전송을 위한 가스 요금을 지불할 충분한 각 체인의 가스 토큰.
  * Chiliz Chain: CHZ 토큰.
  * Base: ETH 토큰.

개발 환경으로는 [Hardhat](https://hardhat.org/)과 Node/npx를 사용합니다.

## 1단계: 컨트랙트 개발

### Chiliz Chain에서 `OFTAdapter` 준비하기

{% hint style="warning" %}
이것은 준비 단계입니다. 지금 바로 배포하지 마세요!\
3단계에서 배포합니다.
{% endhint %}

`OFTAdapter` 컨트랙트는 기존 토큰의 잠금 상자 역할을 합니다. 사용자가 Chiliz Chain에서 토큰을 브릿징할 때, 이 컨트랙트가 원래 ERC20 토큰을 잠급니다.

contracts 폴더에 `ChilizTokenAdapter.sol` 파일을 새로 만드세요:

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

import { OFTAdapter } from "@layerzerolabs/lz-evm-oapp-v2/contracts/oft/OFTAdapter.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

contract ChilizTokenAdapter is OFTAdapter {
    constructor(
        address _token,      // The address of your EXISTING Token on Chiliz Chain
        address _lzEndpoint, // The LayerZero V2 Endpoint address on Chiliz
        address _delegate    // The address capable of making configuration changes (usually your wallet)
    ) OFTAdapter(_token, _lzEndpoint, _delegate) Ownable(_delegate) {}
}
```

{% hint style="info" %}
이 컨트랙트는 [LayerZero OFT 어댑터 컨트랙트](https://github.com/LayerZero-Labs/LayerZero-v2/blob/main/packages/layerzero-v2/evm/oapp/contracts/oft/OFTAdapter.sol)와 관리 키를 제공하기 위한 표준 `Ownable.sol` 컨트랙트를 확장합니다. 체인을 안전하게 연결하려면 두 가지 모두 필요합니다.
{% endhint %}

Chiliz Chain Mainnet에 배포할 때, `_token`으로 기존 토큰의 컨트랙트 주소를, `_lzEndpoint`로 Chiliz Endpoint V2 주소(`0x6F475642a6e85809B1c36Fa62763669b1b48DD5B`)를 전달해야 합니다.

Chiliz Chain에서 사용 가능한 모든 엔드포인트를 확인하세요:

{% embed url="<https://docs.layerzero.network/v2/deployments/chains/chiliz>" %}

### Base에서 `OFT` 준비하기

토큰이 Base에 아직 네이티브로 존재하지 않으므로, 표준 OFT 컨트랙트를 배포해야 합니다. 이 컨트랙트는 Chiliz에 배포된 OFT 어댑터로부터 유효한 메시지를 받을 때 새 토큰을 민팅하고, 사용자가 다시 브릿징할 때 소각하는 권한을 갖습니다.

contracts 폴더에 `BaseTokenOFT.sol` 파일을 새로 만드세요:

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

import { OFT } from "@layerzerolabs/lz-evm-oapp-v2/contracts/oft/OFT.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

contract BaseTokenOFT is OFT {
    constructor(
        string memory _name,   // The name of the token (Should match your Chiliz Token)
        string memory _symbol, // The symbol of the token (Should match your Chiliz Token)
        address _lzEndpoint,   // The LayerZero V2 Endpoint address on Base
        address _delegate      // The address capable of making configuration changes
    ) OFT(_name, _symbol, _lzEndpoint, _delegate) Ownable(_delegate) {}
}
```

{% hint style="info" %}
이 컨트랙트는 [LayerZero OFT 컨트랙트](https://github.com/LayerZero-Labs/LayerZero-v2/blob/main/packages/layerzero-v2/evm/oapp/contracts/oft/OFT.sol)와 위에서 언급한 이유로 표준 `Ownable.sol` 컨트랙트를 확장합니다.
{% endhint %}

Base에 배포할 때, 사용자가 혼동하지 않도록 `_name`과 `_symbol`이 Chiliz Chain의 원래 토큰과 일치하는지 확인하세요. `_lzEndpoint`로 Base Endpoint V2 주소(`0x1a44076050125825900e736c501f859c50fE728c`)를 전달합니다.

Base에서 사용 가능한 모든 엔드포인트를 확인하세요:

{% embed url="<https://docs.layerzero.network/v2/deployments/chains/base>" %}

## 2단계: LayerZero 구성

컨트랙트가 준비되면, LayerZero 도구에 연결 방법을 알려야 합니다. 이는 Hardhat 프로젝트의 루트에 있는 `layerzero.config.ts` 파일을 사용하여 수행됩니다.

이 구성 파일은 교차 체인 아키텍처의 청사진 역할을 합니다. 배포된 스마트 컨트랙트를 각각의 LayerZero Endpoint ID(EID)에 매핑하고 둘 사이의 경로(연결)를 정의합니다.

[Simple Config Generator](https://docs.layerzero.network/v2/tools/simple-config)는 양방향 배선을 자동화하고 권장 보안 구성을 자동으로 적용하므로 권장되는 배선 구성 생성 방법입니다.

Hardhat 프로젝트 루트에서 `layerzero.config.ts` 파일을 생성하거나 업데이트하세요:

```typescript
import { ExecutorOptionType } from '@layerzerolabs/lz-v2-utilities';
import { OAppEnforcedOption, OmniPointHardhat } from '@layerzerolabs/toolbox-hardhat';
import { EndpointId } from '@layerzerolabs/lz-definitions';
import { generateConnectionsConfig } from '@layerzerolabs/metadata-tools';

// Define the Contracts
const chilizContract: OmniPointHardhat = {
    eid: EndpointId.CHILIZ_V2_MAINNET,
    contractName: 'ChilizTokenAdapter',
};

const baseContract: OmniPointHardhat = {
    eid: EndpointId.BASE_V2_MAINNET,
    contractName: 'BaseFanTokenOFT',
};

// Define standard EVM Gas Limits (Enforced Options)
const EVM_ENFORCED_OPTIONS: OAppEnforcedOption[] = [
    {
        msgType: 1,  // Standard OFT Transfer
        optionType: ExecutorOptionType.LZ_RECEIVE,
        gas: 200000, // Safe baseline gas limit for minting/unlocking
        value: 0,    
    },
];

// Export the Generated Configuration
export default async function () {
    return {
        contracts: [
            { contract: chilizContract },
            { contract: baseContract },
        ],
        connections: await generateConnectionsConfig([
            [
                chilizContract,  // Source
                baseContract,    // Destination
                [['LayerZero Labs'], []], // Default DVN Configuration
                [1, 1],                   // Block confirmations
                [EVM_ENFORCED_OPTIONS, EVM_ENFORCED_OPTIONS], // Execution Options [To Chiliz, To Base]
            ],
        ]),
    };
}
```

## 3단계: 배포 워크플로우

컨트랙트를 작성하고 `layerzero.config.ts`를 준비했다면, 이제 각 네트워크에 컨트랙트를 배포할 차례입니다. LayerZero V2 도구는 배포를 효율적으로 관리하기 위해 `hardhat-deploy` 플러그인을 사용합니다.

프로젝트의 `deploy/` 디렉토리에 두 개의 배포 스크립트를 생성해야 합니다: Chiliz Chain Mainnet용과 Base Mainnet용.

### Chiliz 어댑터 배포 스크립트

`deploy/` 폴더에 `01_deploy_chiliz_adapter.ts` 파일을 생성합니다. 이 스크립트는 기존 토큰 주소와 Chiliz Endpoint V2 주소를 생성자에 전달합니다.

```typescript
import { DeployFunction } from 'hardhat-deploy/types';

const deployAdapter: DeployFunction = async ({ getNamedAccounts, deployments }) => {
    const { deploy } = deployments;
    const { deployer } = await getNamedAccounts();

    // The address of your existing ERC-20 token on Chiliz
    const TOKEN_ADDRESS = "0xYourTokenAddressHere"; 
    
    // The Chiliz Mainnet Endpoint V2 Address
    const CHILIZ_ENDPOINT_V2 = "0x6F475642a6e85809B1c36Fa62763669b1b48DD5B";

    console.log("Deploying OFTAdapter to Chiliz Mainnet...");

    await deploy('ChilizTokenAdapter', {
        from: deployer,
        args: [
            TOKEN_ADDRESS,   // _token
            CHILIZ_ENDPOINT_V2,  // _lzEndpoint
            deployer             // _delegate (Owner)
        ],
        log: true,
        waitConfirmations: 2,
    });
};

export default deployAdapter;
deployAdapter.tags = ['ChilizTokenAdapter'];
```

### Base OFT 배포 스크립트

`deploy/` 폴더에 두 번째 파일 `02_deploy_base_oft.ts`를 생성합니다. 이 스크립트는 Base에서 새 네이티브 OFT를 초기화합니다.

```typescript
import { DeployFunction } from 'hardhat-deploy/types';

const deployOFT: DeployFunction = async ({ getNamedAccounts, deployments }) => {
    const { deploy } = deployments;
    const { deployer } = await getNamedAccounts();

    // Token Details (Must match your Chiliz Token)
    const TOKEN_NAME = "My Token";
    const TOKEN_SYMBOL = "TKN";

    // The Base Mainnet Endpoint V2 Address 
    const BASE_ENDPOINT_V2 = "0x1a44076050125825900e736c501f859c50fE728c";

    console.log("Deploying Native OFT to Base Mainnet...");

    await deploy('BaseTokenOFT', {
        from: deployer,
        args: [
            TOKEN_NAME,         // _name
            TOKEN_SYMBOL,       // _symbol
            BASE_ENDPOINT_V2,   // _lzEndpoint
            deployer            // _delegate (Owner)
        ],
        log: true,
        waitConfirmations: 2,
    });
};

export default deployOFT;
deployOFT.tags = ['BaseTokenOFT'];
```

### 배포 실행

`hardhat.config.ts`에 Chiliz Chain과 Base 모두에 대한 RPC URL과 개인 키가 올바르게 구성되어 있는지 확인하세요.

{% content-ref url="/pages/l3L799OGCd4EyD9g04AH" %}
[RPC로 연결](/ko/gaebal/gibon/chiliz-chain-yeongyeol/rpc-yeongyeol.md)
{% endcontent-ref %}

{% embed url="<https://docs.base.org/base-chain/quickstart/connecting-to-base>" %}

터미널에서 다음 명령어를 실행하여 컨트랙트를 배포합니다:

```bash
# 1. Deploy the Adapter to Chiliz Chain
npx hardhat deploy --network chiliz --tags ChilizTokenAdapter

# 2. Deploy the Native OFT to Base
npx hardhat deploy --network base --tags BaseTokenOFT
```

배포가 완료되면, Hardhat이 `deployments/` 폴더에 컨트랙트 주소를 저장합니다. LayerZero 도구는 다음 단계에서 배선 명령을 실행할 때 이 주소들을 자동으로 읽습니다.

## 4단계: 배선 및 피어링

이 단계에서 `ChilizTokenAdapter`와 `BaseTokenOFT` 컨트랙트가 각 체인에 배포되었지만 완전히 격리된 상태입니다.\
Base 컨트랙트가 토큰을 민팅하도록 지시하는 메시지를 받으면, 해당 메시지가 악의적인 행위자가 아닌 *귀하의* Chiliz 어댑터에서 실제로 발신된 것인지 확인해야 합니다.

컨트랙트를 암호화 방식으로 "배선"하여 피어로 연결함으로써 이 신뢰를 확립해야 합니다.

이는 Chiliz와 Base 모두에서 트랜잭션을 생성하고 실행하는 `wire` 명령을 실행하여 수행됩니다.

{% hint style="info" %}
**내부적으로 무슨 일이 일어나나요?**

완전한 LayerZero V2 경로 구성에는 각 체인에서 실제로 6개의 트랜잭션이 필요합니다:

* `setSendLibrary`: 메시지 전송을 담당하는 LayerZero MessageLib를 할당합니다.
* `setReceiveLibrary`: 메시지 수신을 담당하는 MessageLib를 할당합니다.
* `setConfig` (Send Library): 아웃바운드 메시지에 대한 특정 DVN과 Executor를 설정합니다.
* `setConfig` (Receive Library): 인바운드 메시지를 검증하는 데 필요한 특정 DVN을 설정합니다.
* `setEnforcedOptions`: 필요한 실행 가스 한도를 설정합니다. 사용자가 Chiliz Chain에서 메시지를 보내면, 목적지 가스를 선불로 지불합니다. Enforced 옵션을 설정하면 LayerZero Executor가 Chiliz Chain에서 트랜잭션을 성공적으로 처리하기에 충분한 가스를 지불하는지 확인합니다.
* `setPeer`: 목적지 Endpoint ID(EID)를 신뢰할 수 있는 컨트랙트 주소에 연결합니다. Chiliz Chain 컨트랙트가 Base 컨트랙트를 신뢰하고, Base 컨트랙트가 Chiliz Chain 컨트랙트를 신뢰하도록 설정해야 합니다.
  {% endhint %}

### 배선 작업 실행

터미널에서 다음 명령을 실행합니다:

```bash
npx hardhat lz:oapp:wire --oapp-config layerzero.config.ts
```

도구체인이 필요한 파라미터를 자동으로 계산하고, 실행하려는 트랜잭션 표를 표시한 후, 배포자 지갑을 사용하여 Chiliz와 Base에 제출합니다.

두 네트워크에서 트랜잭션이 확인되면, 토큰 브릿지가 공식적으로 활성화되고 완전히 구성됩니다! Chiliz 어댑터는 이제 Base에 민팅 명령을 보낼 수 있는 권한을 갖게 되고, Base는 Chiliz로 잠금 해제 명령을 보낼 수 있는 권한을 갖게 됩니다.

## 5단계: 운영 및 테스트

컨트랙트가 배포되고 안전하게 배선되었다면, 토큰은 이제 옴니체인입니다. 마지막 단계는 Chiliz Chain Mainnet에서 Base Mainnet으로 교차 체인 전송을 실행하는 것입니다.

### 1) 교차 체인 전송 실행

LayerZero V2 도구는 터미널에서 직접 OFT 전송을 테스트하기 위한 내장 Hardhat 작업을 제공합니다. 이 명령은 교차 체인 가스 요금을 추정하고, 소스 체인의 네이티브 가스 토큰인 $CHZ로 지갑에 청구하며 전송을 시작합니다.

{% hint style="info" %}
`ChilizTokenAdapter`가 기존 Fan Token을 잠그는 권한이 필요하므로, ERC-20 `approve()` 트랜잭션이 필요합니다.

LayerZero CLI가 이를 감지하고 메시지를 보내기 전에 자동으로 승인을 처리합니다.
{% endhint %}

다음 명령을 실행합니다:

{% code overflow="wrap" lineNumbers="true" %}

```bash
npx hardhat lz:oft:send --oapp-config layerzero.config.ts --from-eid 30409 --to-eid 30184 --amount 10
```

{% endcode %}

이 명령이 수행하는 작업:

1. 구성에서 Chiliz Mainnet(`30409`)과 Base Mainnet(`30184`)을 찾습니다.
2. LayerZero Executor가 요구하는 교차 체인 요금을 견적합니다.
3. Chiliz 어댑터에서 `send()` 함수를 호출합니다.
4. 어댑터가 10개의 토큰을 잠그고 LayerZero Endpoint에 패킷을 전송합니다.

### 2) LayerZero Scan에서 패킷 추적

교차 체인 트랜잭션은 비동기식입니다. Chiliz 트랜잭션이 몇 초 안에 확인되지만, 메시지는 여전히 Base에서 검증되고 실행되어야 합니다.

이 과정을 실시간으로 추적하려면, CLI 출력에 나타나는 LayerZero Scan 링크를 클릭하세요.

이 도구에 대해 자세히 알아보세요:

{% embed url="<https://docs.layerzero.network/v2/developers/evm/tooling/layerzeroscan>" %}

## 가스 한도 설정

가스 한도를 설정하는 것은 매우 중요합니다. 설정하지 않으면 교차 체인 메시지가 목적지 네트워크에서 실패할 수 있습니다.

사용자가 Chiliz Chain에서 Base로 토큰을 브릿징할 때, Chiliz의 단일 트랜잭션에서 *두* 체인 모두의 가스 요금을 선불로 지불합니다($CHZ 사용). LayerZero는 그 요금의 일부를 사용하여 Base에서 민팅 트랜잭션을 실행하는 데 필요한 실제 ETH 가스를 지불합니다.

LayerZero가 목적지 체인에서 `lzReceive` 함수를 성공적으로 처리하기에 충분한 가스를 갖도록 Enforced Options를 설정해야 합니다. 설정하지 않으면 "가스 부족" 오류로 인해 트랜잭션이 목적지 체인에서 되돌아갈 수 있습니다.

### **옵션 구성**

이 옵션은 `layerzero.config.ts` 파일에서 설정합니다. `connections` 배열을 업데이트하여 각 경로에 `enforcedOptions` 블록을 포함시키세요:

{% code overflow="wrap" %}

```typescript
import { EndpointId } from '@layerzerolabs/lz-definitions';

// ... (contract definitions as before)

connections: [
    {
        from: 'ChilizTokenAdapter',
        to: 'BaseTokenOFT',
        config: {
            enforcedOptions: [
                {
                    msgType: 1,        // 1 = Standard OFT Transfer (SEND)
                    optionType: 1,     // 1 = lzReceive Option
                    gas: 200000,       // Estimated gas limit to mint on Base
                },
                {
                    msgType: 2,        // 2 = OFT Transfer with payload (SEND_AND_CALL)
                    optionType: 1,
                    gas: 250000,       // Slightly higher gas limit for complex calls
                }
            ]
        },
    },
    {
        from: 'BaseTokenOFT',
        to: 'ChilizTokenAdapter',
        config: {
            enforcedOptions: [
                {
                    msgType: 1,
                    optionType: 1,
                    gas: 200000,       // Estimated gas limit to unlock on Chiliz
                }
            ]
        },
    },
],
// ...
```

{% endcode %}

파라미터 설명:

* `msgType: 1`: 표준 토큰 전송을 나타냅니다. `msgType: 2`는 "composed" 호출(예: 토큰을 브릿징하고 즉시 스테이킹)에 사용됩니다.
* `optionType: 1`: Executor에게 단순히 `lzReceive` 함수를 실행하도록 지시합니다.
* `gas: 200000`: 표준 OFT 민팅 및 잠금 해제를 위한 안전한 기준 가스 한도입니다. 배포된 컨트랙트의 특정 가스 소비에 따라 조정할 수 있습니다.

이미 체인을 배선한 후에 이 옵션을 설정한 경우, 동일한 명령으로 옵션을 포함하여 재배선할 수 있습니다:

{% code overflow="wrap" %}

```bash
npx hardhat lz:oapp:wire --oapp-config layerzero.config.ts
```

{% endcode %}

도구는 변경 사항을 자동으로 감지하고 Chiliz와 Base 양쪽 컨트랙트에 `setEnforcedOptions()` 트랜잭션을 제출합니다. 이제 사용자가 브릿지를 트리거할 때마다 컨트랙트는 사용자가 목적지 체인에서 최소 200,000 가스 단위를 지불하도록 강제하여 안정적인 전달을 보장합니다.


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.chiliz.com/ko/gaebal/goseup/omnicheun-token/chiliz-base-beuriji.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
