> 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/>" %}

### Fan Tokens / CAP-20

Chiliz Chainの最も特有な側面は、Fan Tokensに使用されるCAP-20標準です。

CAP-20トークンはコードレベルではERC-20標準と技術的に同一ですが、decimalsに関して特有の設定を持ちます。簡単に言うと、通常のERC-20トークンが18 decimalsを使用するのに対し、CAP-20は0 decimalsを使用します。

About Fan Tokens

そのため、18 decimalsでFan Tokenをdeployすると、エコシステムのwalletで正しく表示されなかったり、将来のSocios.com統合との互換性がなくなったりする可能性があります。

## 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やEVMバージョンに関して、一定の「ローカルルール」が適用されます。

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

Fan Tokensとやり取りするコントラクト（例：$PSGや$BAR向けのStaking Pool）を書く場合、0 decimalsを扱う必要があります。

つまり：

* `1 Token = 10^18 units`と想定しないこと。Fan Tokensの場合、`1 Token = 1 unit`です。
* コントラクトを汎用的にする場合、計算に`1e18`をハードコードするのは避けること。`token.decimals()`関数を動的に使用してください。

#### EVM Version & Compiler

Chiliz Chainは「Shanghai」EVMバージョンと互換性があります。\
推奨されるSolidityバージョンは`0.8.24`です。

### 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:

```
GET https://docs.chiliz.com/jp/kaihatsu/kihon/smart-contract-kaku.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
