> 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/gibon/seumateu-keonteulaekteu-jaksseong.md).

# 스마트 컨트랙트 작성

Chiliz Chain에서 dApp을 만들기로 결정했다면 블록체인의 특성을 고려해야 합니다.

Chiliz Chain은 EVM 호환이지만, Ethereum과 동일하게 취급하면 특히 토큰 소수점과 가스 메커니즘과 관련하여 사용성 문제가 발생할 수 있습니다.

자세히 알아보겠습니다!

## 사전 요구사항

### 개발 환경

컨트랙트 작성을 시작하기 전에 환경이 준비되어 있는지 확인하세요.

먼저, 개발용 Spicy Testnet 또는 프로덕션용 Chiliz Chain Mainnet에 구성된 지갑이 있어야 합니다.

{% content-ref url="/pages/VYs29f1UN2O40ilUYbHs" %}
[Chiliz Chain 연결](/ko/gaebal/gibon/chiliz-chain-yeongyeol.md)
{% endcontent-ref %}

다음으로, Testnet과 Mainnet 모두에서 가스 배포 비용을 지불하기 위해 $CHZ가 필요합니다. Mainnet $CHZ는 암호화폐 거래소에서 구매할 수 있으며, Testnet 토큰은 Faucet을 이용하세요.

{% content-ref url="/pages/qiix4G9ofyknkfg1PvVE" %}
[무료 Testnet 토큰 받기](/ko/gaebal/gibon/teseuteuseunet-token.md)
{% endcontent-ref %}

툴링 측면에서는 Hardhat 또는 Remix를 사용할 수 있습니다. 예를 들어:

{% content-ref url="/pages/d8ZuNOnK6BjrTnPOPcIK" %}
[Remix로 배포](/ko/gaebal/gibon/seumateu-keonteulaekteu-baepoe/remix-baepoe.md)
{% endcontent-ref %}

마지막으로, Chiliz Chain 컨트랙트는 Solidity 언어로 작성됩니다.

{% embed url="<https://www.soliditylang.org/>" %}

{% embed url="<https://solidity-by-example.org/>" %}

권장 Solidity 및 EVM 버전을 사용하세요:

{% hint style="info" %}
**Chiliz Chain 권장 Solidity 및 EVM 버전:**

* **Solidity 컴파일러 버전:** `0.8.30` (또는 그 이하)
* **대상 EVM 버전:** `prague`
  {% endhint %}

### Fan Tokens / CAP-20

Chiliz Chain의 가장 특징적인 측면은 Fan Tokens에 사용되는 CAP-20 표준입니다.

기술적으로는 ERC-20 표준과 코드가 동일하지만, CAP-20 토큰은 소수점에 특정 구성을 사용합니다. 간단히 말해, 일반 ERC-20 토큰이 18자리 소수점을 사용하는 반면 CAP-20은 0자리 소수점을 사용합니다.

{% content-ref url="<https://github.com/chiliz-chain/docs/tree/master/baeuggi/paen-token/README.md>" %}
<https://github.com/chiliz-chain/docs/tree/master/baeuggi/paen-token/README.md>
{% endcontent-ref %}

따라서 18자리 소수점으로 Fan Token을 배포하면 생태계 지갑에서 올바르게 표시되지 않거나 향후 Socios.com 통합과 호환되지 않을 수 있습니다.

## 스마트 컨트랙트 작성 모범 사례

### 검증된 라이브러리 사용 (OpenZeppelin)

컨트랙트를 처음부터 작성하지 마세요.\
가장 효과적인 보안 방법은 커뮤니티에서 감사를 받은 표준을 기반으로 코드를 작성하여 취약점 위험을 줄이는 것입니다.

Chiliz Chain 개발에는 [OpenZeppelin Contracts](https://docs.openzeppelin.com/contracts) 사용을 강력히 권장합니다. 토큰 컨트랙트에 대한 안전하고 커뮤니티에서 검증된 구현체를 제공합니다.

표준 컨트랙트를 사용하면 MetaMask 같은 알려진 지갑 및 Chiliz 생태계(Socios.com)와의 토큰 호환성을 보장할 수 있습니다.

### 일반 EVM 모범 사례

체인에 관계없이 다음 세 가지 패턴은 안전한 Solidity 개발에서 필수적입니다.

#### "검사-효과-상호작용(Checks-Effects-Interactions)" 패턴

이는 [재진입 공격(Reentrancy Attacks)](https://solidity-by-example.org/hacks/re-entrancy/)에 대한 주요 방어 수단입니다. 항상 다음 순서로 함수를 구성하세요.

1. 검사(Checks): 입력 및 조건 검증 (예: `require` 구문).
2. 효과(Effects): 컨트랙트 상태 업데이트 (예: 잔액 감소).
3. 상호작용(Interactions): 다른 컨트랙트와 상호작용하거나 자금 전송 (예: `transfer`).

#### 강력한 접근 제어

민감한 함수를 보호되지 않은 상태로 두지 마세요. 토큰 발행, 수수료 변경, 로직 업그레이드 등의 함수는 반드시 제한되어야 합니다.

* 단순한 경우: 단일 관리자 컨트랙트에는 `Ownable`을 사용합니다.
* 복잡한 경우: 여러 역할이 필요한 컨트랙트(예: `MINTER_ROLE`, `ADMIN_ROLE`)에는 `AccessControl`을 사용합니다.

#### 입력 검증

모든 입력이 악의적일 수 있다고 가정하세요. 함수 시작 부분에 `require()` 구문을 사용하여 파라미터를 검증하세요.

예를 들어:

* 제로 주소 (`address(0)`) 확인.
* 전송 시 제로 금액 확인.
* 여러 배열을 전달할 경우 배열 길이 일치 여부 확인.
* 기타.

### Chiliz 특화 구현 세부사항

Chiliz Chain은 EVM 호환이지만 특히 토큰 소수점에 관한 "로컬 규칙"이 적용됩니다.

#### CAP-20 준수 (Fan Tokens)

Fan Tokens와 상호작용하는 컨트랙트(예: $PSG 또는 $BAR 스테이킹 풀)를 작성하는 경우 0자리 소수점을 처리해야 합니다.

이는 다음을 의미합니다.

* `1 Token = 10^18 units`로 가정하지 마세요. Fan Tokens의 경우 `1 Token = 1 unit`입니다.
* 컨트랙트가 범용적으로 설계된 경우 수식에 `1e18`을 하드코딩하지 마세요. `token.decimals()` 함수를 동적으로 사용하세요.

### Chiliz에서의 가스 최적화

Chiliz Chain의 트랜잭션 비용은 Ethereum보다 훨씬 저렴하지만, 최적화되지 않은 코드는 고트래픽 이벤트(예: 경기 중) 동안 혼잡이나 트랜잭션 실패로 이어질 수 있습니다.

가스를 절약하는 세 가지 방법:

* 커스텀 오류 사용: `require`의 긴 문자열 메시지 대신 `error` 정의를 사용하여 가스를 절약합니다.
* 상태 변수를 32바이트 슬롯에 맞게 정렬합니다. 가능한 경우 `uint128`, `address`, `bool`을 나란히 배치합니다.
* 컨트랙트 내부에서 호출되지 않는 함수에는 `external`을 사용합니다.


---

# 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/gibon/seumateu-keonteulaekteu-jaksseong.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.
