> 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/th/phatthana/sung-khuen/nft/mint-rarible.md).

# Mint NFT ด้วย Rarible

Rarible คือ multichain NFT protocol และ marketplace ที่มี SDK และ API สำหรับสร้างแอปพลิเคชัน NFT บนหลาย EVM network

สำหรับการสร้าง NFT นั้น [Rarible Multichain SDK](https://docs.rarible.org/reference/getting-started) ช่วยให้คุณ mint ลงในคอลเลกชันของตัวเองหรือคอลเลกชันที่แชร์ร่วมกัน และสร้างคำสั่งขายได้ทันที

เนื่องจาก Rarible SDK ไม่รองรับการอัปโหลด IPFS โดยตรง ตัวอย่างในที่นี้จึงใช้ [Pinata](https://pinata.cloud/) เป็น IPFS host คุณจะต้องมีบัญชี Pinata เพื่อรับ JWT key

นอกจากนี้ คุณยังต้องมีสิ่งต่อไปนี้:

* smart contract ERC-721 ที่ปรับใช้แล้วบน Chiliz Chain คุณต้องปรับใช้ [smart contract ERC-721 จาก OpenZeppelin](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol) บน Chiliz Chain ด้วยตัวเอง [Remix IDE](https://remix.ethereum.org/) มี IDE ในเบราว์เซอร์ให้คุณใช้งาน อย่าลืมยืนยัน smart contract ผ่าน block explorer!
* Rarible API key ดูวิธีรับ key ได้จากคู่มือเริ่มต้นใช้งาน:

{% embed url="<https://docs.rarible.org/docs/rarible-protocol>" %}

หากต้องการใช้ Rarible SDK เราจำเป็นต้องติดตั้งแพ็กเกจต่างๆ ดังนี้:

```bash
npm i @rarible/sdk @rarible/types ethers dotenv pinata
```

{% hint style="warning" %}
คุณจะสังเกตว่าเราใช้ `ethers` ซึ่งเป็นทางเลือกแทน `viem` ที่เราใช้ในส่วนอื่นๆ\
จริงๆ แล้ว [Rarible แนะนำ](https://docs.rarible.org/reference/getting-started#interacting-with-evm-wallets) ให้นักพัฒนาใช้ ethers.js หรือ web3.js ในการทำงานกับ Web3 wallet — และ [web3.js](https://web3js.org/#/) [ได้หยุดให้บริการในเดือนมีนาคม 2025](https://blog.chainsafe.io/web3-js-sunset/) จึงเหลือแค่ `ethers` เป็นตัวเลือกหลัก
{% endhint %}

## การสร้าง NFT คอลเลกชัน

ขั้นแรก สร้างไฟล์ .env ของคุณ:

```
# Chiliz RPC
RPC_URL=https://spicy-rpc.chiliz.com       # หรือ Mainnet RPC
PRIVATE_KEY=0xabc...                       # คีย์ของผู้ mint (ฝั่งเซิร์ฟเวอร์เท่านั้น)

# Rarible
RARIBLE_API_KEY=your_rarible_api_key
COLLECTION_ADDRESS=0xYourCollectionOnChiliz
SUPPLY=1                                   # 1 = ERC-721, >1 = ERC-1155

# Pinata
PINATA_JWT=eyJhbGciOi...                   # Pinata JWT จาก dashboard
PINATA_GATEWAY=your-subdomain.mypinata.cloud

# ข้อมูลสื่อและ metadata
IMAGE_PATH=./art/image.png
NAME=My Chiliz NFT
DESCRIPTION=Minted on-chain via Rarible SDK

```

ขั้นตอนการทำงานที่เราเลือกใช้คือ:

1. อัปโหลดสื่อไปยัง IPFS ผ่าน Pinata
2. สร้างและอัปโหลดไฟล์ metadata
3. Rarible SDK + การ mint บน blockchain

นี่คือสคริปต์ตัวอย่างเต็มรูปแบบที่คุณสามารถนำไปประยุกต์ใช้:

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

```bash
import 'dotenv/config'
import fs from 'fs'
import path from 'path'
import { Wallet, JsonRpcProvider } from 'ethers'
import { createRaribleSdk } from '@rarible/sdk'
import { toCollectionId, toUnionAddress } from '@rarible/types'
import { PinataSDK } from 'pinata'

function guessMime(p: string) {
  const ext = path.extname(p).toLowerCase()
  if (ext === '.png') return 'image/png'
  if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg'
  if (ext === '.webp') return 'image/webp'
  if (ext === '.gif') return 'image/gif'
  if (ext === '.mp4') return 'video/mp4'
  if (ext === '.webm') return 'video/webm'
  return 'application/octet-stream'
}

async function main() {
  // Upload media to IPFS
  const pinata = new PinataSDK({
    pinataJwt: process.env.PINATA_JWT!,
  })

  const mediaPath = process.env.IMAGE_PATH!
  const mediaBlob = new Blob([fs.readFileSync(mediaPath)], { type: guessMime(mediaPath) })
  const mediaFile = new File([mediaBlob], path.basename(mediaPath), { type: guessMime(mediaPath) })

  const mediaUpload = await pinata.upload.public.file(mediaFile)
  const imageUri = `ipfs://${mediaUpload.cid}`
  // console.log('imageUri:', imageUri)

  // Build & upload metadata file
  const metadata = {
    name: process.env.NAME!,
    description: process.env.DESCRIPTION!,
    image: imageUri,
    // animation_url: "ipfs://<cid>/video.mp4",
    // attributes: [{ trait_type: "Tier", value: "Gold" }],
  }
  const metaUpload = await pinata.upload.public.json(metadata)
  const metadataUri = `ipfs://${metaUpload.cid}`
  // console.log('metadataUri:', metadataUri)

  // Rarible on-chain mint
  const provider = new JsonRpcProvider(process.env.RPC_URL!)
  const wallet = new Wallet(process.env.PRIVATE_KEY!, provider)
  const sdk = createRaribleSdk(wallet, 'prod', { apiKey: process.env.RARIBLE_API_KEY! })

  // Union IDs use "<BLOCKCHAIN>:<address>" — here BLOCKCHAIN is "CHILIZ"
  const collectionId = toCollectionId(`CHILIZ:${process.env.COLLECTION_ADDRESS}`)
  const creator = toUnionAddress(`CHILIZ:${wallet.address}`)

  const { transaction, itemId } = await sdk.nft.mint({
    collectionId,
    uri: metadataUri,
    supply: Number(process.env.SUPPLY || 1), // 1 for 721, >1 for 1155
  })

  const { hash } = await transaction.wait()
  console.log('Minted item:', itemId, 'tx:', hash)
}

main().catch((e) => (console.error(e), process.exit(1)))

```

{% endcode %}

## การ Lazy-mint คอลเลกชัน NFT

Lazy Minting เป็นตัวเลือกสำหรับผู้ที่ไม่ต้องการจ่าย gas ล่วงหน้าในการสร้าง NFT ก่อนนำออกขาย พวกเขาสามารถลิสต์ NFT เพื่อขาย แล้วค่อย mint เมื่อมีการซื้อหรือการโอนเกิดขึ้น ค่า gas จึงเป็นส่วนหนึ่งของกระบวนการสร้าง NFT และผู้ซื้อเป็นผู้รับผิดชอบค่าใช้จ่ายนั้น

โดยสรุป lazy-minting หมายถึงการนำ NFT ขึ้น blockchain เมื่อมีคนซื้อเท่านั้น ไม่ใช่ก่อนหน้านั้น

คุณจะต้องมีไฟล์ .env ที่กำหนดค่าอย่างถูกต้อง:

```
# Chiliz RPC / wallet
RPC_URL=https://spicy-rpc.chiliz.com
PRIVATE_KEY=0xabc...                         # คีย์ผู้สร้าง (เก็บเป็นความลับ)

# Rarible
RARIBLE_API_KEY=your_rarible_api_key
COLLECTION_ADDRESS=0xYourCollectionOnChiliz   # ERC-721 หรือ ERC-1155

# Pinata
PINATA_JWT=eyJhbGciOi...                      # Pinata JWT จาก dashboard
PINATA_GATEWAY=your-subdomain.mypinata.cloud  # ไม่บังคับ (สำหรับ preview)

# สื่อและ metadata
IMAGE_PATH=./art/image.png
NAME=My Chiliz NFT
DESCRIPTION=Lazy-minted on Rarible (Chiliz)
SUPPLY=1                                      # 1 สำหรับ 721; >1 สำหรับ 1155 editions

```

และนี่คือโค้ดตัวอย่างสำหรับ lazy-mint โปรเจกต์ของคุณ:

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

```typescript
import 'dotenv/config'
import fs from 'fs'
import path from 'path'
import { Wallet, JsonRpcProvider } from 'ethers'
import { createRaribleSdk } from '@rarible/sdk'
import { toCollectionId, toUnionAddress } from '@rarible/types'
import { PinataSDK } from 'pinata'

function guessMime(p: string) {
  const ext = path.extname(p).toLowerCase()
  if (ext === '.png') return 'image/png'
  if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg'
  if (ext === '.webp') return 'image/webp'
  if (ext === '.gif') return 'image/gif'
  if (ext === '.mp4') return 'video/mp4'
  if (ext === '.webm') return 'video/webm'
  return 'application/octet-stream'
}

async function main() {
  // Upload media to IPFS
  const pinata = new PinataSDK({
    pinataJwt: process.env.PINATA_JWT!,
  })

  const mediaPath = process.env.IMAGE_PATH!
  const mediaBlob = new Blob([fs.readFileSync(mediaPath)], { type: guessMime(mediaPath) })
  const mediaFile = new File([mediaBlob], path.basename(mediaPath), { type: guessMime(mediaPath) })
  const mediaUp = await pinata.upload.public.file(mediaFile)
  const imageUri = `ipfs://${mediaUp.cid}`

  const metadata = {
    name: process.env.NAME!,
    description: process.env.DESCRIPTION!,
    image: imageUri,
    // animation_url: "ipfs://<cid>/video.mp4",
    // attributes: [{ trait_type: "Tier", value: "Gold" }],
  }
  const metaUp = await pinata.upload.public.json(metadata)
  const metadataUri = `ipfs://${metaUp.cid}`

  // Rarible lazy mint
  const provider = new JsonRpcProvider(process.env.RPC_URL!)
  const wallet = new Wallet(process.env.PRIVATE_KEY!, provider)
  const sdk = createRaribleSdk(wallet, 'prod', { apiKey: process.env.RARIBLE_API_KEY! })
  const collectionId = toCollectionId(`CHILIZ:${process.env.COLLECTION_ADDRESS}`)
  const creator = toUnionAddress(`CHILIZ:${wallet.address}`)

  // Prepare & submit lazy mint (off-chain item; buyer mints on purchase)
  const prepared = await sdk.nft.mint.prepare({ collectionId })
  const result = await prepared.submit({
    uri: metadataUri,
    supply: Number(process.env.SUPPLY || 1),     // 1 for 721; >1 for 1155
    lazyMint: true,                              // Yes, make it lazy please
    creators: [{ account: creator, value: 10000 }], // 100% go to your wallet
    royalties: [],                               // e.g. [{ account: creator, value: 500 }] for 5%
  })

  // console.log('Lazy itemId:', result.itemId)
}

main().catch((e) => (console.error(e), process.exit(1)))

```

{% endcode %}


---

# 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/th/phatthana/sung-khuen/nft/mint-rarible.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.
