Lesson 11: Payments (Crypto)
Embark on your journey to building production grade apps.
Your app can store data and authenticate users. But there's one more thing it needs before it can be a real product: accepting money. This lesson adds that — without a payment processor, a card network, or a bank account.
Taking money is the line between "hobby project" and "business." On the traditional web, that meant integrating Stripe, handing PCI compliance to someone else, waiting days for payouts, and paying ~3% on every charge. On Monad, it means something different: the user sends MON from their wallet to yours, the transaction settles on-chain in under a second, and your app verifies it happened by reading the blockchain.
You'll build the smallest app that demonstrates this end-to-end: a tip jar with three buttons, 0.01, 0.05, and 0.1 MON. Click a button, your wallet pops up asking you to confirm a transfer, the transaction lands on Monad testnet, and your server verifies it before thanking the user. The exact same flow powers on-chain checkouts, subscription products, and tipping features across the EVM ecosystem.
This is a testnet lesson. Everything you do in this lesson happens on Monad testnet. Testnet MON has no monetary value — it's free play money from a faucet, designed for exactly this kind of learning. No real funds move, no real cards are charged, and nothing in your wallet is at risk. The flow you build here works identically on mainnet later; only the chain config changes.
Security is a running theme in this lesson. Even on testnet, build the habits as if real money were on the line. The day you flip to mainnet, a bug stops being a learning moment and starts being a drained wallet or a free ride for the attacker.
Why Pay On-Chain Instead of With a Card?
A traditional payment processor (Stripe, Adyen, Braintree) sits between your app and the card networks. It handles card data, fraud scoring, PCI compliance, and payouts. Useful, but expensive: you pay ~3% per transaction, wait days for money to land, and live with chargebacks for months.
On-chain payments replace that whole stack with one primitive: a wallet-to-wallet transfer on a public ledger.
- No card data. There's no PAN, expiry, or CVC to store. The user signs a transaction in their wallet. Your server never sees a private key.
- No PCI DSS. The security standard for card data doesn't apply, because there is no card data.
- No processor, no middleman. The user's wallet talks to Monad directly. You read the result from the chain.
- Settlement in seconds. Monad finalizes blocks fast enough that the money is yours by the time the user sees the success page. No 3-day hold.
- Programmable. The payment is just a transaction on a blockchain. You can build refunds, splits, escrow, and subscriptions out of smart contracts instead of vendor APIs.
The tradeoff: the user needs a wallet, and the money is MON (a crypto asset), not USD. For users already in the ecosystem, that's a feature. For everyone else, it's a hurdle your UX has to solve. This lesson isn't going to solve the UX problem for you, but it is going to give you the backend the rest of your app can lean on.
Why doesn't PCI DSS apply to a Monad-based payment flow?
What's the main settlement difference between a card payment and a Monad payment?
What Happens During an On-Chain Payment
You don't need to implement any of this yourself. The user's wallet and Monad do the hard parts. But knowing the steps makes the security guidance click.
- Intent on the client. Your app says "transfer 0.05 MON from the user's wallet to the merchant's address." The user's wallet (MetaMask, Rabby, etc.) shows them what they're about to sign.
- Signature. The user confirms in their wallet. The wallet signs the transaction with the user's private key. Your app never sees that key.
- Broadcast. The signed transaction is sent to Monad via an RPC endpoint. A validator includes it in the next block.
- Confirmation. Monad finalizes the block. The transfer is now part of the permanent public ledger. Anyone can read it. No one can reverse it.
- Server-side verification. Your server takes the transaction hash the client reports, fetches the transaction from Monad itself, and checks that the recipient, amount, and chain are what you expect. Only then does your app credit the user.
The key insight: the client's claim of "I paid" is a UX hint. The chain is the truth. Never fulfill an order or credit an account based on a client message alone. Always re-read the transaction from the chain.
Before You Build: Your Receiving Wallet
To accept payments you need one thing: a wallet address to receive MON at. That's it. You do not need the private key on your server — addresses are public information, and nothing about receiving MON requires signing.
- Open MetaMask (or any EVM wallet) and create a new account specifically for this tip jar.
- Copy the public address (it starts with
0x…). This is what goes in your server env asRECIPIENT_ADDRESS. - Do not copy the private key. Do not put it in
.env. Do not paste it into an agent prompt. You don't need it to receive, only to spend — and this lesson never spends from the receiving wallet. - Make sure the wallet you'll use as the payer has some testnet MON. Get some from the Build Anything faucet.
Security, the receiving wallet's private key stays out of this project entirely. Public address in env: fine. Private key: never. On testnet the worst case is losing some free faucet MON, which doesn't matter. But build the habit now — on mainnet the same leak drains every tip the moment it lands, and that's real money. Treat the testnet wallet exactly like a production bank login, because the muscle memory is what carries over.
Where should the receiving wallet's private key live for this tip jar?
Let's Build a Tip Jar
We'll build the smallest app that completes an on-chain payment on Monad testnet — three buttons, 0.01, 0.05, and 0.1 MON. Click a button, your wallet pops up, you confirm the transfer, and you land on a /success page once the server has verified the transaction on-chain. Remember: testnet MON has no monetary value, so you're free to experiment.
Create a new Repl and open the AI panel. Paste:
I'm building a tip jar app to learn on-chain payments on Monad
testnet. The user connects a wallet and sees three tip buttons:
0.01, 0.05, and 0.1 MON. Clicking a button sends a MON transfer
from their wallet to my recipient address. After the transfer
confirms on-chain and my server verifies it, they land on a
/success page.
Rules:
- Target Monad testnet. Chain ID: 10143. RPC:
https://testnet-rpc.monad.xyz. Block explorer:
https://testnet.monadscan.com. Native token: MON.
- Use Next.js with wagmi + viem + RainbowKit on the client for
wallet connection and sending the transaction. Do NOT install
ethers.
- Read the recipient address from process.env.RECIPIENT_ADDRESS
on the server. Expose it to the client via a server endpoint,
not by hard-coding it in a component.
- Tip amounts MUST be defined in server code, not accepted from
the client. The client sends { button: 1 | 2 | 3 }; the server
maps that to the exact wei amount. Otherwise a malicious client
could claim "I paid 0.1 MON" for a 0.01 MON transaction.
- After the wallet confirms, the client POSTs
{ txHash, button } to /api/verify-payment. That route:
* Uses viem's createPublicClient({ chain: monadTestnet,
transport: http(MONAD_RPC) }) to fetch the transaction and
its receipt from Monad testnet.
* Asserts receipt.status === 'success'.
* Asserts tx.to (lowercased) === RECIPIENT_ADDRESS (lowercased).
* Asserts tx.value >= the expected wei amount for the button.
* Asserts tx.chainId matches 10143.
* Tracks seen tx hashes (in-memory Set for this lesson is
fine) and rejects duplicates — same hash cannot be reused.
Return 200 only when every check passes. 4xx otherwise with a
clear error message.
- Success URL: /success (a simple page that says "Thanks!" and
shows the tx hash + a link to the explorer).
- If RECIPIENT_ADDRESS is missing, show a clear error in place
of the buttons. Do not silently fail.
- Keep the UI minimal. Three buttons on a plain page, standard
system fonts, plain colors, no gradients.
Run it locally so I can test it in my browser.
Replit Agent will scaffold the app and pop up an environment-variables panel asking for RECIPIENT_ADDRESS. Paste the public address from your receiving wallet (starts with 0x…) and click Save Variables. Replit restarts the app and the agent wires it up.
Try It
Open the preview. Click Connect Wallet and connect a wallet that has some testnet MON (grab some from the Build Anything faucet if you don't). Click the 0.01 MON button. Your wallet pops up asking you to confirm a testnet transfer. Approve it — no real money is moving.
Once the transaction confirms, you'll land on /success with a link to the transaction on testnet.monadscan.com. Open the explorer — you can see your transfer, the sender, the recipient, and the amount, on the public testnet ledger.
Try these too:
- Reject the transaction in your wallet. Your app should show a clear error and leave the user on the tip jar page.
- Switch to the wrong network in your wallet. Your app should prompt you to switch back to Monad testnet before the transaction goes through.
- Try replaying a tx hash. Open devtools, grab a tx hash that already succeeded, POST it to
/api/verify-paymentagain with the same button. The server should reject it.
Why must tip amounts be defined on the server, not the client?
Where should the recipient wallet address come from?
Verify Payments On-Chain
The client's claim of "here's my tx hash, please credit me" is a UX hint. It is not proof. A malicious client can send any hash — an old one, a transaction to someone else's wallet, a transaction on a different chain, a transaction that reverted. Your server must re-read the transaction from Monad and check it matches exactly what you expect.
Here's the minimal shape of the verification logic your agent should have produced (look at /api/verify-payment in the code it wrote):
import { createPublicClient, http, parseEther } from 'viem'
import { defineChain } from 'viem'
const monadTestnet = defineChain({
id: 10143,
name: 'Monad Testnet',
nativeCurrency: { name: 'MON', symbol: 'MON', decimals: 18 },
rpcUrls: { default: { http: ['https://testnet-rpc.monad.xyz'] } },
})
const client = createPublicClient({ chain: monadTestnet, transport: http() })
const AMOUNTS_WEI = {
1: parseEther('0.01'),
2: parseEther('0.05'),
3: parseEther('0.1'),
} as const
const seen = new Set<string>()
export async function verify({ txHash, button }: { txHash: `0x${string}`, button: 1 | 2 | 3 }) {
if (seen.has(txHash)) throw new Error('tx hash already used')
const [tx, receipt] = await Promise.all([
client.getTransaction({ hash: txHash }),
client.getTransactionReceipt({ hash: txHash }),
])
if (receipt.status !== 'success') throw new Error('tx did not succeed')
if (tx.chainId !== 10143) throw new Error('wrong chain')
if (tx.to?.toLowerCase() !== process.env.RECIPIENT_ADDRESS!.toLowerCase())
throw new Error('wrong recipient')
if (tx.value < AMOUNTS_WEI[button]) throw new Error('amount too low')
seen.add(txHash)
}
Every one of those checks defends against a specific attack:
seen.has(txHash)blocks replay — the same successful tx can't be redeemed twice. In production, back this with a unique index on a database column; an in-memory set resets on every deploy.receipt.status === 'success'blocks reverted transactions from being credited.tx.chainIdblocks a user from paying 0.1 MON on some other cheap EVM and presenting that hash.tx.toblocks a user from paying themselves and submitting their own hash.tx.value >= expectedblocks a user from paying the 0.01 MON tier and claiming the 0.1 MON reward.
Security, verify on-chain server-side, always. The blockchain is the only source of truth for "did this payment actually happen?" Trusting the client here is the crypto-native equivalent of fulfilling a Stripe order because the success redirect loaded. The attacker just POSTs a made-up hash and walks away with the goods.
Why does the /api/verify-payment route re-fetch the transaction from Monad instead of trusting the client?
Why track previously-seen tx hashes and reject duplicates?
From Testnet to Mainnet
Everything so far has run on Monad testnet. No real value, free MON from the faucet, a sandbox to blow up in. To take real payments on Monad mainnet, when it's live and you're ready:
- Create a new receiving wallet specifically for mainnet. Do not reuse your testnet receiver — keep the environments separated so a leaked testnet key never touches real funds.
- Swap the chain config: mainnet chain ID, mainnet RPC URL, mainnet block explorer. (Check docs.monad.xyz for the current mainnet values.)
- Update your server env:
RECIPIENT_ADDRESSto the new mainnet address,MONAD_RPCto a mainnet RPC. - Do NOT swap these in local development. Keep testnet locally so you can't accidentally charge real wallets while debugging.
- Consider hosting behind a paid RPC provider in production (public RPCs get rate-limited under load) and setting up monitoring for failed verifications.
Unlike Stripe, there's no "activate your account" step — no KYC, no bank info, no weeks-long review. You're already able to receive. The tradeoff is that Monad also doesn't do KYC for you — if your product needs it for compliance reasons, that's a layer you build on top.
Security, keep testnet and mainnet configs in separate env files / projects. A single misconfigured env var that points your local dev at mainnet is all it takes to accidentally drain your faucet wallet or charge a real user in a test click-through.
Onramps and Offramps (Mainnet Only)
Once you're on mainnet, on-chain payments only work if your users have MON to send — and for you, the recipient, if you can convert MON back to fiat whenever you need to. That bridge between a bank account and a wallet is called an onramp (card or bank → MON in a wallet) or an offramp (MON → bank account). Embedding one in your checkout lets a first-time user pay without already owning crypto, and lets you cash out to USD on the other side. None of this applies on testnet — testnet MON comes from a faucet, has no monetary value, and can't be bought or sold. See docs.monad.xyz/tooling-and-infra/onramps for the current list of providers that support Monad mainnet.
Other On-Chain Payment Flows (Optional)
The tip jar is the easiest entry point. The ecosystem supports more:
- Subscriptions. Recurring payments are trickier on-chain (no "card on file" to charge). The usual patterns: require a new transaction per period, or deploy a smart contract with an ERC-20 allowance the contract can pull from on a schedule.
- Refunds. There's no processor to reverse the charge. A refund is a new transaction from your wallet back to the user's wallet. Track refunds alongside the original payment in your database.
- Splits / marketplaces. Build a smart contract that accepts the payment and forwards a cut to each party in the same transaction. Much simpler than reconciling Stripe Connect transfers after the fact.
- Stablecoins. If you want USD-denominated prices instead of MON-denominated, accept a stablecoin (e.g. USDC on Monad) using the ERC-20
transferFrompattern. Verification logic is similar but checks contract events instead of the nativevalue. - Tokenized access. Mint an NFT or a soulbound token to the payer. Your app checks wallet ownership to unlock features instead of looking up a subscription row.
For a first on-chain product, the native-MON transfer in this lesson is the right choice. It's the least code, the fewest moving parts, and the easiest to verify end-to-end.
Security Recap
- Receiving private key: stays completely out of the project. Only the public address goes in env.
- Testnet vs mainnet: always develop against testnet. Only swap to mainnet values in production env.
- Amounts: always defined on the server. The client picks a button; the server maps that to a wei amount and uses it as the minimum during verification.
- Recipient: read from server env on every request. Never trust a client-supplied address.
- Verification: re-fetch the tx from Monad. Check
status,chainId,to, andvalue. A "success" redirect or a client claim is not proof. - Replay protection: unique-constraint tx hashes in your database (or a durable store). A set in memory is a toy that resets on deploy.
- RPC trust: in production, use an RPC you pay for or control. A malicious RPC can lie about transactions.
- Success / cancel routes: hard-coded to paths on your own domain. Don't let user input decide where to redirect after payment.
What You Just Built
Your app now:
- Takes on-chain payments in testnet MON on Monad testnet
- Keeps the receiving private key out of the project entirely, because it's not needed to receive
- Defines prices server-side, so a malicious user can't pay the cheap tier and claim the expensive one
- Verifies every payment by reading Monad itself, so fake tx hashes and cross-chain spoofs don't grant access
That's the same machinery every on-chain checkout, tipping integration, and subscription flow is built on — minus a payment processor, minus PCI compliance, minus the 3% fee. When your project is live on Monad mainnet, the chain config changes and the same code starts moving real value.
What's Next
Your app can store data, authenticate users, and accept on-chain payments. Next up: put all of it together and build a newsletter app that charges for access, exactly like you'd ship a real product.
0/7 correct
0% — get all correct to complete