> ## Documentation Index
> Fetch the complete documentation index at: https://polymarketcn.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 拆分 USDC 為條件代幣

> 學習如何將 USDC 拆分為 Yes 和 No 結果代幣

拆分（Splitting）是將 USDC 轉換為條件代幣的過程。這是參與 Polymarket 市場的第一步。

## 什麼是拆分？

拆分是將抵押品（USDC）轉換為代表不同結果的條件代幣的過程。在二元市場中，每 1 USDC 拆分成：

* **1 個 Yes 代幣**
* **1 個 No 代幣**

<Callout type="info">
  **價值守恆**：拆分後的代幣總價值始終等於拆分的 USDC 數量。即 1 USDC = 1 Yes + 1 No
</Callout>

## 為什麼要拆分？

### 1. 做市

做市商拆分 USDC 以在兩邊提供流動性：

```
存入: 1000 USDC
拆分: 1000 Yes + 1000 No
賣出 Yes @0.55: 獲得 550 USDC
賣出 No @0.47: 獲得 470 USDC
總計: 1020 USDC (20 USDC 利潤)
```

### 2. 套利

當市場價格和 > 1 時：

```
Yes 價格: 0.58 USDC
No 價格: 0.44 USDC
總和: 1.02 USDC (有套利機會!)

操作:
1. 拆分 1000 USDC → 1000 Yes + 1000 No
2. 賣出 Yes @0.58 → 580 USDC
3. 賣出 No @0.44 → 440 USDC
4. 總收入: 1020 USDC
5. 利潤: 20 USDC
```

### 3. 對衝

交易者可以拆分 USDC，賣出不看好的一方，保留看好的一方：

```
存入: 100 USDC
拆分: 100 Yes + 100 No
賣出 No @0.40: 獲得 40 USDC
保留: 100 Yes
成本: 100 - 40 = 60 USDC
相當於以 0.60 的價格買入 Yes
```

## 拆分流程

### 方法 1：通過 Polymarket 界面

最簡單的方法是使用 Polymarket 自帶的拆分功能：

1. 訪問任意市場
2. 點擊"Split Position"或類似選項
3. 輸入要拆分的 USDC 數量
4. 確認交易

<Warning>
  注意：Polymarket 網站界面可能隱藏了直接拆分選項，通常在下單時自動處理。
</Warning>

### 方法 2：直接調用智能合約

使用 Web3 庫直接與條件代幣合約交互。

#### 合約信息

```
網絡: Polygon
CTF 合約: 0x4D97DCd97eC945f40cF65F87097ACe5EA0476045
USDC 地址: 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174
```

#### Python 示例

```python theme={null}
from web3 import Web3
from eth_account import Account

# 連接到 Polygon
w3 = Web3(Web3.HTTPProvider('https://polygon-rpc.com'))

# CTF 合約
ctf_address = '0x4D97DCd97eC945f40cF65F87097ACe5EA0476045'
ctf_abi = [...]  # CTF ABI

ctf_contract = w3.eth.contract(address=ctf_address, abi=ctf_abi)

# USDC 合約
usdc_address = '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
usdc_abi = [...]  # ERC20 ABI

usdc_contract = w3.eth.contract(address=usdc_address, abi=usdc_abi)

# 1. 首先授權 CTF 合約使用你的 USDC
amount = 100 * 10**6  # 100 USDC (6位小數)

approve_tx = usdc_contract.functions.approve(
    ctf_address,
    amount
).build_transaction({
    'from': your_address,
    'nonce': w3.eth.get_transaction_count(your_address),
})

# 籤署並發送授權交易
signed_approve = w3.eth.account.sign_transaction(approve_tx, private_key)
approve_hash = w3.eth.send_raw_transaction(signed_approve.rawTransaction)
w3.eth.wait_for_transaction_receipt(approve_hash)

# 2. 拆分位置
partition = [1, 2]  # [Yes, No]
condition_id = '0x...'  # 市場的條件 ID

split_tx = ctf_contract.functions.splitPosition(
    usdc_address,      # 抵押品代幣 (USDC)
    '0x' + '0' * 64,  # 父集合 ID (0 表示頂層)
    condition_id,      # 條件 ID
    partition,         # [Yes, No]
    amount            # 數量
).build_transaction({
    'from': your_address,
    'nonce': w3.eth.get_transaction_count(your_address),
})

# 籤署並發送拆分交易
signed_split = w3.eth.account.sign_transaction(split_tx, private_key)
split_hash = w3.eth.send_raw_transaction(signed_split.rawTransaction)
receipt = w3.eth.wait_for_transaction_receipt(split_hash)

print(f"拆分成功! 交易哈希: {split_hash.hex()}")
```

#### TypeScript 示例

```typescript theme={null}
import { ethers } from 'ethers';

// 連接到 Polygon
const provider = new ethers.providers.JsonRpcProvider('https://polygon-rpc.com');
const wallet = new ethers.Wallet(privateKey, provider);

// CTF 合約
const ctfAddress = '0x4D97DCd97eC945f40cF65F87097ACe5EA0476045';
const ctfAbi = [...];  // CTF ABI
const ctfContract = new ethers.Contract(ctfAddress, ctfAbi, wallet);

// USDC 合約
const usdcAddress = '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174';
const usdcAbi = [...];  // ERC20 ABI
const usdcContract = new ethers.Contract(usdcAddress, usdcAbi, wallet);

async function splitPosition() {
  const amount = ethers.utils.parseUnits('100', 6); // 100 USDC
  
  // 1. 授權 CTF 合約
  const approveTx = await usdcContract.approve(ctfAddress, amount);
  await approveTx.wait();
  console.log('USDC 授權成功');
  
  // 2. 拆分位置
  const conditionId = '0x...';  // 市場的條件 ID
  const parentCollectionId = '0x' + '0'.repeat(64);
  const partition = [1, 2];  // [Yes, No]
  
  const splitTx = await ctfContract.splitPosition(
    usdcAddress,
    parentCollectionId,
    conditionId,
    partition,
    amount
  );
  
  const receipt = await splitTx.wait();
  console.log('拆分成功!', receipt.transactionHash);
}

splitPosition();
```

## 獲取條件 ID

要拆分位置，你需要知道市場的條件 ID。可以通過以下方式獲取：

### 從 Gamma API

```python theme={null}
import requests

# 獲取市場信息
market_response = requests.get(
    'https://gamma-api.polymarket.com/markets',
    params={'slug': 'your-market-slug'}
)

market = market_response.json()[0]
condition_id = market['condition_id']
print(f"條件 ID: {condition_id}")
```

### 從 CLOB API

```python theme={null}
from py_clob_client.client import ClobClient

client = ClobClient(...)
markets = client.get_markets()

for market in markets:
    if market['question'] == 'Your Market Question':
        condition_id = market['condition_id']
        print(f"條件 ID: {condition_id}")
        break
```

## 計算位置 ID

拆分後，你需要知道代幣的位置 ID 來進行轉移或交易：

```python theme={null}
from web3 import Web3

def get_position_id(collateral_token, condition_id, index_set):
    """
    計算位置 ID
    
    Args:
        collateral_token: USDC 地址
        condition_id: 條件 ID
        index_set: 結果索引 (1 for Yes, 2 for No)
    """
    parent_collection_id = '0x' + '0' * 64
    
    # 編碼索引集
    index_set_encoded = index_set.to_bytes(32, 'big')
    
    # 計算集合 ID
    collection_id = Web3.keccak(
        bytes.fromhex(parent_collection_id[2:]) + 
        bytes.fromhex(condition_id[2:]) + 
        index_set_encoded
    )
    
    # 計算位置 ID
    position_id = Web3.keccak(
        bytes.fromhex(collateral_token[2:].lower().zfill(64)) + 
        collection_id
    )
    
    return position_id.hex()

# 使用示例
usdc = '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
condition_id = '0x...'

yes_position_id = get_position_id(usdc, condition_id, 1)
no_position_id = get_position_id(usdc, condition_id, 2)

print(f"Yes 代幣 ID: {yes_position_id}")
print(f"No 代幣 ID: {no_position_id}")
```

## Gas 成本

拆分操作的典型 Gas 成本（Polygon）：

| 操作      | Gas 使用量   | 成本 @ 100 Gwei |
| ------- | --------- | ------------- |
| USDC 授權 | \~45,000  | \$0.005       |
| 拆分位置    | \~120,000 | \$0.012       |
| **總計**  | \~165,000 | **\~\$0.017** |

<Callout type="success">
  Polygon 網絡的 Gas 費用非常低，使得頻繁拆分和合併操作在經濟上可行。
</Callout>

## 注意事項

<Warning>
  **重要提示**：

  1. **授權額度**：確保你已授權足夠的 USDC 給 CTF 合約
  2. **條件 ID 正確**：使用錯誤的條件 ID 會導致拆分到錯誤的市場
  3. **精度問題**：USDC 使用 6 位小數，計算時注意單位轉換
  4. **Gas 費用**：雖然低，但仍需要一些 MATIC 支付 Gas
  5. **網絡擁堵**：在高峰期，交易可能需要更長時間確認
</Warning>

## 驗證拆分

拆分後，驗證你的代幣餘額：

```python theme={null}
from web3 import Web3

# CTF 合約的 balanceOf 函數
balance_yes = ctf_contract.functions.balanceOf(
    your_address,
    int(yes_position_id, 16)
).call()

balance_no = ctf_contract.functions.balanceOf(
    your_address,
    int(no_position_id, 16)
).call()

print(f"Yes 代幣餘額: {balance_yes / 10**6}")
print(f"No 代幣餘額: {balance_no / 10**6}")
```

## 常見問題

### Q: 拆分後能否退回 USDC？

A: 可以！如果你同時持有 Yes 和 No 代幣，可以合併回 USDC。詳見[合併代幣](/api-tutorial/conditional-tokens/merging)。

### Q: 必須拆分才能交易嗎？

A: 不必！你可以直接在 CLOB 上購買代幣，Polymarket 會自動處理拆分。

### Q: 拆分有最小金額嗎？

A: 技術上沒有，但考慮到 Gas 費用，建議至少拆分 10 USDC 以上。

### Q: 拆分的代幣在哪裡？

A: 代幣在你的錢包地址中，但它們是 ERC-1155 代幣，不是標準的 ERC-20。

## 下一步

<CardGroup cols={2}>
  <Card title="合併代幣" icon="layer-group" href="/api-tutorial/conditional-tokens/merging">
    將代幣合併回 USDC
  </Card>

  <Card title="贖回代幣" icon="coins" href="/api-tutorial/conditional-tokens/redeeming">
    市場結算後贖回
  </Card>

  <Card title="CTF 概覽" icon="book" href="/api-tutorial/conditional-tokens/overview">
    返回條件代幣概覽
  </Card>

  <Card title="CLOB 交易" icon="chart-line" href="/api-tutorial/clob/quickstart">
    在 CLOB 上交易代幣
  </Card>
</CardGroup>
