Mint an NFT by calling a smart contract’s mint function with the embedded wallet.
Implementation
import { useSendTransaction } from '@moon-key/react-auth/ethereum';
import { encodeFunctionData } from 'viem';
const NFT_MINT_ABI = [
{
name: 'mint',
type: 'function',
stateMutability: 'payable',
inputs: [{ name: 'quantity', type: 'uint256' }],
outputs: []
}
] as const;
export default function MintNFT() {
const { sendTransaction } = useSendTransaction();
const handleMint = async () => {
const nftContractAddress = '0x...'; // Your NFT contract
const mintPrice = '10000000000000000'; // 0.01 ETH in wei
try {
const data = encodeFunctionData({
abi: NFT_MINT_ABI,
functionName: 'mint',
args: [1n] // Mint 1 NFT
});
const txHash = await sendTransaction({
to: nftContractAddress,
value: mintPrice,
data
});
console.log('NFT minted:', txHash);
} catch (error) {
console.error('Minting failed:', error);
}
};
return (
<div>
<h2>Mint NFT</h2>
<button onClick={handleMint}>Mint NFT (0.01 ETH)</button>
</div>
);
}
Key concepts
- Payable function - The mint function accepts ETH (specified in
value)
- Function encoding - Encodes the mint function call with quantity parameter
- Value in wei - ETH amount must be specified in wei (1 ETH = 10^18 wei)
- Contract call - Sends transaction to NFT contract with both value and data
Common patterns
Dynamic quantity
const [quantity, setQuantity] = useState(1);
const handleMint = async () => {
const data = encodeFunctionData({
abi: NFT_MINT_ABI,
functionName: 'mint',
args: [BigInt(quantity)]
});
const txHash = await sendTransaction({
to: nftContractAddress,
value: (parseFloat(mintPrice) * quantity).toString(),
data
});
};
With status tracking
const [mintStatus, setMintStatus] = useState<'idle' | 'minting' | 'success' | 'error'>('idle');
const handleMint = async () => {
setMintStatus('minting');
try {
await sendTransaction({...});
setMintStatus('success');
} catch (error) {
setMintStatus('error');
}
};
Important notes
Make sure the user has sufficient ETH balance to cover both the mint price and gas fees.
The ABI should match your NFT contract’s mint function signature. Common variations include mint(), mint(uint256 quantity), or mint(address to, uint256 quantity).
Next steps