> 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/jp/kaihatsu/kihon/smart-contract-kaku.md).

# Smart Contract を書く

Chiliz Chain上でdAppを作成すると決めた瞬間から、当ブロックチェーン特有の事項を考慮する必要があります。

Chiliz ChainはEVM互換ですが、Ethereumとまったく同じように扱うと、特にトークンのdecimalsやgasの仕組みに関して、使い勝手の問題を引き起こすことがあります。

さっそく見ていきましょう！

## Prerequisites

### Environment

コントラクトを書き始める前に、環境が整っていることを確認してください。

まず、Spicy Testnet（開発用）またはChiliz Chain Mainnet（本番用）向けに設定されたwalletが必要です。

Connect to Chiliz Chain

次に、TestnetとMainnetの両方で、gasによるdeploy費用を支払うための$CHZが必要です。Mainnetの$CHZは任意の暗号資産取引所で購入できますが、Testnetのトークンはfaucetを利用して入手できます。

Obtain Free Testnet Tokens

ツールに関しては、HardhatまたはRemixを利用できます。例として以下を参照してください：

[remix-deploy.md](/jp/kaihatsu/kihon/smart-contract-deploy/remix-deploy.md)

最後に、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標準です。

CAP-20はERC-20標準と技術的に同等です。2026年のDecimal Fan Token移行以降、CAP-20トークンは標準的なERC-20トークンと同様に18 decimalsの精度を使用するため、Fan Tokenの残高・送金・総供給量はトークンの最小単位で表され、分割された数量をサポートします。

{% hint style="info" %}
Fan Tokenは[2026年の小数対応Fan Tokenへの移行](/jp/gakushu/fan-tokens/2026-fan-token-iko.md)までは0 decimals（整数単位のみ）を使用していましたが、この移行によって18 decimals精度にアップグレードされました。古い整数単位を前提に書かれたコントラクトは更新が必要になる場合があります。
{% endhint %}

About Fan Tokens

## Best practices in writing a smart contract

### Use Battle-Tested Libraries (OpenZeppelin)

コントラクトをゼロから作成するのは避けてください。\
最も効果的なセキュリティ対策は、コミュニティによって監査された標準にコードを基づかせ、脆弱性のリスクを減らすことです。

Chiliz Chainの開発では、[OpenZeppelin Contracts](https://docs.openzeppelin.com/contracts)の使用を強く推奨します。これらは、トークンコントラクト向けに安全かつコミュニティで検証された実装を提供します。

標準コントラクトを使用することで、トークンが既知のwallet（MetaMaskなど）やChilizエコシステム（Socios.com）と互換性を持つことが保証されます。

### General EVM Best Practices

チェーンを問わず、安全なSolidity開発においてこれら3つのパターンは譲れません。

#### The "Checks-Effects-Interactions" Pattern

これは[Reentrancy Attacks](https://solidity-by-example.org/hacks/re-entrancy/)に対する第一の防御策です。関数は常にこの順序で構成してください：

1. Checks：入力と条件を検証する（例：`require`文）。
2. Effects：コントラクトの状態を更新する（例：残高を減らす）。
3. Interactions：他のコントラクトとやり取りする、または資金を送る（例：`transfer`）。

#### Robust Access Control

機密性の高い関数を保護しないままにしてはいけません。トークンをmintする、手数料を変更する、ロジックをアップグレードするといった関数は、必ず制限する必要があります。

* シンプル：単一管理者のコントラクトには`Ownable`を使用する。
* 複雑：複数のロール（例：`MINTER_ROLE`、`ADMIN_ROLE`）を必要とするコントラクトには`AccessControl`を使用する。

#### Input Validation

すべての入力は悪意あるものと想定してください。関数の冒頭で`require()`文を使用してパラメータを検証します。

例えば：

* ゼロアドレス（`address(0)`）をチェックする。
* 送金時にゼロ額をチェックする。
* 複数の配列を渡す場合、配列の長さが一致するか検証する。
* など。

### Chiliz-Specific Implementation Details

Chiliz ChainはEVM互換ですが、特にトークンのdecimalsに関して、一定の「ローカルルール」が適用されます。

#### CAP-20 Compliance (Fan Tokens)

Fan Tokensとやり取りするコントラクト（例：$PSGや$BAR向けのStaking Pool）を書く場合、固定値を想定するのではなく、それぞれのdecimalsを考慮してください。

2026年のDecimal Fan Token移行以降、Fan Tokensは18 decimalsを使用するため、ほとんどのERC-20トークンと同様に`1 Token = 10^18 units`となります。古いFan Tokenコントラクトは0 decimals（`1 Token = 1 unit`）を使用しており、一部は現在もオンチェーン上で見つかることがあります。

* トークンのdecimalsをハードコードしないこと。`token.decimals()`を動的に読み取り、トークンが18 decimalsを使用する場合でも、レガシーな0 decimals構成の場合でも、コントラクトが動作するようにしてください。
* `1e18`を想定する代わりに、`decimals()`が返す値を使用して数量をスケールしてください。

### Gas Optimization on Chiliz

Chiliz Chain上のトランザクションはEthereumよりも大幅に安価ですが、最適化されていないコードは、トラフィックの多いイベント（例：試合のライブ中継中）に依然として混雑やトランザクション失敗を引き起こす可能性があります。

gasを節約する方法を3つ紹介します：

* Custom Errorsを使用する：`require`内の長い文字列メッセージの代わりに、`error`定義を使用してgasを節約する。
* state変数を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/jp/kaihatsu/kihon/smart-contract-kaku.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.
