# Frappage avec viem

Pour les développeurs qui préfèrent un contrôle granulaire sur le processus de mint, vous pouvez utiliser TypeScript pur avec [viem](https://viem.sh/) , une interface TypeScript pour les projets basés sur EVM. La [bibliothèque Ethers.js](https://ethers.org/) est également une approche robuste.

Passer *vanille* nécessite d’effectuer un peu plus de travail que lorsque vous vous appuyez sur des frameworks tels que thirdweb. Par exemple, à moins d’exécuter votre propre nœud IPFS, vous devrez vous reposer sur une plateforme de stockage NFT, qui est payante.

{% hint style="success" %}
Cet exemple utilise [Pinata](https://pinata.cloud/) comme hôte IPFS.\
Vous devrez également déployer un [contrat OpenZeppelin ERC-721](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol) sur Chiliz Chain. [Remix IDE](https://remix.ethereum.org/) vous permet de le faire dans le navigateur. N’oubliez pas de vérifier le contrat à l’aide d’un explorateur de blocs !
{% endhint %}

Maintenant, installons `viem`la `SDK Pinata`et le `dotenv` module :

```bash
npm i viem pinata dotenv
```

Configurez votre `.env` fichier pour répondre à vos besoins :

```
# Portefeuille / contrat
PRIVATE_KEY=0xabc...                      # côté serveur uniquement
CONTRACT_ADDRESS=0xYourErc721Address
RECIPIENT=0xRecipientOrLeaveEmpty         # facultatif ; valeur par défaut : minteur

# Pinata
PINATA_JWT=eyJhbGciOi...                  # JWT provenant du tableau de bord Pinata
PINATA_GATEWAY=your-subdomain.mypinata.cloud

# Mint unique
IMAGE_PATH=./art/image.png
NAME=Mon NFT Chiliz
DESCRIPTION=Minté sur Chiliz avec viem

# Mint par lots
IMAGES_DIR=./art
NAME_PREFIX=Mon NFT Chiliz
BATCH_DESCRIPTION=Minté par lots sur Chiliz avec viem
```

Maintenant, plongeons dans le code.\
\&#xNAN;*Inspirez-vous-en, ne l’utilisez pas tel quel !*

## Minter un NFT unique

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

```typescript
import 'dotenv/config';
import fs from 'fs';
import path from 'path';

import { createWalletClient, createPublicClient, http, parseEventLogs } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import type { Address } from 'viem';
import { chiliz, spicy } from 'viem/chains';
import { PinataSDK } from 'pinata';

// ABI minimal : safeMint(to, uri) + tokenURI + Transfer
const abi = [
  { type: 'function', name: 'safeMint', stateMutability: 'nonpayable',
    inputs: [{ name: 'to', type: 'address' }, { name: 'uri', type: 'string' }], outputs: [] },
  { type: 'function', name: 'tokenURI', stateMutability: 'view',
    inputs: [{ name: 'tokenId', type: 'uint256' }], outputs: [{ type: 'string' }] },
  { type: 'event', name: 'Transfer',
    inputs: [
      { name: 'from', type: 'address', indexed: true },
      { name: 'to', type: 'address', indexed: true },
      { name: 'tokenId', type: 'uint256', indexed: true },
    ]},
] as const;

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() {
  // Choisissez votre réseau : utilisez `spicy` pour le testnet Chiliz, basculez vers `chiliz` pour le Mainnet Chiliz Chain.
  const chain = spicy; // Passez à `chiliz` pour le Mainnet

  const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
  const walletClient = createWalletClient({ account, chain, transport: http() });
  const publicClient = createPublicClient({ chain, transport: http() });

  const address = process.env.CONTRACT_ADDRESS as Address;
  const recipient = (process.env.RECIPIENT as Address) || account.address;

  // Téléversement IPFS (Pinata)
  const pinata = new PinataSDK({
    pinataJwt: process.env.PINATA_JWT!,
    pinataGateway: process.env.PINATA_GATEWAY!,
  });

  const filePath = process.env.IMAGE_PATH!;
  const fileBlob = new Blob([fs.readFileSync(filePath)], { type: guessMime(filePath) });
  const fileObj = new File([fileBlob], path.basename(filePath), { type: guessMime(filePath) });

  const up = await pinata.upload.public.file(fileObj);
  const imageUri = `ipfs://${up.cid}`;

  const meta = await pinata.upload.public.json({
    name: process.env.NAME!,
    description: process.env.DESCRIPTION!,
    image: imageUri,
  });
  const metadataUri = `ipfs://${meta.cid}`;

  // Mint on-chain via viem
  const txHash = await walletClient.writeContract({
    address,
    abi,
    functionName: 'safeMint',
    args: [recipient, metadataUri],
  });

  const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });

  const ZERO = '0x0000000000000000000000000000000000000000';
  const logs = parseEventLogs({ abi, logs: receipt.logs, eventName: 'Transfer' });
  const mintLog = logs.find(l => (l.args as any).from?.toLowerCase?.() === ZERO);
  const tokenId = mintLog ? (mintLog.args as any).tokenId : undefined;

  console.log('tx:', txHash, '| tokenId:', tokenId ?? '(not parsed)', '| tokenURI:', metadataUri);
}

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

```

{% endcode %}

## Minter une collection de NFT

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

```typescript
import 'dotenv/config';
import fs from 'fs';
import path from 'path';
// import { Blob } from 'buffer'; // Node 18 : décommentez la ligne suivante pour obtenir Blob.

import { createWalletClient, createPublicClient, http, parseEventLogs } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import type { Address } from 'viem';
import { chiliz, spicy } from 'viem/chains';
import { PinataSDK } from 'pinata';

// ABI minimal : safeMint(to, uri) + tokenURI + Transfer
const abi = [
  { type: 'function', name: 'safeMint', stateMutability: 'nonpayable',
    inputs: [{ name: 'to', type: 'address' }, { name: 'uri', type: 'string' }], outputs: [] },
  { type: 'function', name: 'tokenURI', stateMutability: 'view',
    inputs: [{ name: 'tokenId', type: 'uint256' }], outputs: [{ type: 'string' }] },
  { type: 'event', name: 'Transfer',
    inputs: [
      { name: 'from', type: 'address', indexed: true },
      { name: 'to', type: 'address', indexed: true },
      { name: 'tokenId', type: 'uint256', indexed: true },
    ]},
] as const;

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() {
  // Choisissez votre réseau : utilisez `spicy` pour le testnet Chiliz, basculez vers `chiliz` pour le Mainnet.
  const chain = spicy; // Passez à `chiliz` pour le Mainnet

  const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
  const walletClient = createWalletClient({ account, chain, transport: http() });
  const publicClient = createPublicClient({ chain, transport: http() });

  const address = process.env.CONTRACT_ADDRESS as Address;
  const recipient = (process.env.RECIPIENT as Address) || account.address;

  // Téléversement IPFS (Pinata)
  const pinata = new PinataSDK({
    pinataJwt: process.env.PINATA_JWT!,
    pinataGateway: process.env.PINATA_GATEWAY!, // facultatif ; non nécessaire pour les URI ipfs://
  });

  const filePath = process.env.IMAGE_PATH!;
  const fileBlob = new Blob([fs.readFileSync(filePath)], { type: guessMime(filePath) });

  // Passez directement un Blob
  const up = await pinata.upload.public.file(fileBlob);
  const imageUri = `ipfs://${up.cid}`;

  const meta = await pinata.upload.public.json({
    name: process.env.NAME!,
    description: process.env.DESCRIPTION!,
    image: imageUri,
  });
  const metadataUri = `ipfs://${meta.cid}`;

  // Mint on-chain via viem
  const txHash = await walletClient.writeContract({
    address,
    abi,
    functionName: 'safeMint',
    args: [recipient, metadataUri],
  });

  const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });

  const ZERO = '0x0000000000000000000000000000000000000000';
  const logs = parseEventLogs({ abi, logs: receipt.logs, eventName: 'Transfer' });
  const mintLog = logs.find(l => (l.args as any).from?.toLowerCase?.() === ZERO);
  const tokenId = mintLog ? (mintLog.args as any).tokenId : undefined;

  console.log('tx:', txHash, '| tokenId:', tokenId ?? '(not parsed)', '| tokenURI:', metadataUri);
}

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

```

{% endcode %}


---

# Agent Instructions: 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/fr-ai/develop/advanced/work-with-nfts/minting-with-viem.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.
