Opinionated coding, testing, and security standards for building production-grade Web3 applications (smart contracts + TypeScript dApps) with Solidity, Hardhat/Foundry, React/Next.js, and Ethers.js.
You're building the future of decentralized applications, but your development workflow is stuck in the past. Context-switching between smart contract debugging, frontend state management, security audits, and cross-chain deployments is killing your productivity. While you're manually tracking gas optimizations and praying your contracts pass audit, competitors are shipping production-grade dApps faster than ever.
Building production-ready Web3 applications means juggling an overwhelming technical stack: Solidity smart contracts, TypeScript frontends, multiple testnets, Layer-2 integrations, security audits, and regulatory compliance. Each component has its own tooling, testing patterns, and deployment requirements.
The real problems killing your development velocity:
These aren't just inconveniences—they're productivity killers that turn simple features into week-long implementations.
This ruleset transforms Cursor into your Web3 development command center, handling the complex orchestration between smart contracts, frontends, testing frameworks, and deployment pipelines. Instead of manually configuring each tool and remembering every security pattern, you get instant access to production-grade Web3 development practices.
What you get immediately:
// Before: Manual security pattern implementation
function transfer(address to, uint256 amount) external {
require(balanceOf[msg.sender] >= amount, "Insufficient balance");
// Missing reentrancy protection, custom errors, events...
}
// After: Production-ready security patterns applied automatically
function transfer(address to, uint256 amount) external nonReentrant {
if (to == address(0)) revert InvalidRecipient();
if (amount == 0) revert ZeroAmount();
if (balanceOf[msg.sender] < amount)
revert InsufficientBalance(balanceOf[msg.sender], amount);
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
emit Transfer(msg.sender, to, amount);
}
// Before: Manual Web3 integration complexity
const handleTransfer = async () => {
try {
const tx = await contract.transfer(recipient, amount);
// Missing proper error handling, event parsing, gas estimation...
} catch (error) {
console.log(error); // Useless for debugging
}
};
// After: Production-grade Web3 integration patterns
const handleTransfer = async () => {
try {
const gasEstimate = await contract.transfer.estimateGas(recipient, parseEther(amount));
const tx = await contract.transfer(recipient, parseEther(amount), {
gasLimit: gasEstimate.mul(120).div(100) // 20% buffer
});
const receipt = await tx.wait(1);
const transferEvent = receipt.events?.find(e => e.event === 'Transfer');
toast.success(`Transfer completed: ${transferEvent?.args?.amount}`);
await refetchBalance();
} catch (error) {
const errorMsg = parseContractError(error);
toast.error(errorMsg.userMessage);
logError('transfer_failed', {
chainId: await signer.getChainId(),
txHash: error.transaction?.hash,
userWallet: await signer.getAddress(),
error: errorMsg.fullError
});
}
};
Smart Contract Development Speed: Cut contract development time by 60% with built-in security patterns, gas optimization techniques, and comprehensive testing frameworks that generate the boilerplate you always write.
Cross-Chain Deployment Efficiency: Deploy to multiple networks in minutes instead of hours. Automated deployment scripts handle network detection, gas price optimization, and Etherscan verification across Ethereum, Polygon, Arbitrum, and other supported chains.
Frontend Integration Velocity: TypeScript integration becomes seamless with auto-generated type-safe contract interfaces, proper BigInt handling, and error management patterns that actually help users understand what went wrong.
Testing & Security Confidence: Achieve audit-ready code faster with built-in fuzzing patterns, invariant testing, and security checklist automation. Your CI pipeline runs Slither analysis, coverage reports, and gas benchmarks automatically.
Before: Building a liquidity pool required manually implementing dozens of security patterns, writing custom error handling, managing cross-chain state, and creating comprehensive test suites. A simple staking contract took 2-3 weeks to reach audit-ready state.
After: Generate production-grade DeFi contracts with CEI patterns, reentrancy guards, proper event emission, and comprehensive test coverage in hours. Built-in patterns for common DeFi primitives like AMMs, lending protocols, and yield farming contracts.
// Auto-generated with security patterns, events, and gas optimizations
contract LiquidityPool is ReentrancyGuard, AccessControl {
using SafeERC20 for IERC20;
error InsufficientLiquidity(uint256 available, uint256 requested);
error InvalidTokenRatio(uint256 tokenA, uint256 tokenB);
error DeadlineExpired(uint256 deadline, uint256 current);
event LiquidityAdded(address indexed provider, uint256 tokenA, uint256 tokenB, uint256 liquidity);
event LiquidityRemoved(address indexed provider, uint256 tokenA, uint256 tokenB, uint256 liquidity);
// Production-ready implementation with gas optimizations...
}
Before: Creating an NFT marketplace meant juggling complex state management between smart contracts and frontend, handling IPFS metadata, managing wallet connections, and implementing proper error handling for failed transactions.
After: Complete NFT marketplace stack with smart contract patterns for auctions, offers, and royalties, plus TypeScript frontend components that handle wallet integration, metadata loading, and transaction state management.
Before: Implementing cross-chain functionality required deep knowledge of bridge protocols, managing state across multiple networks, handling failed transactions, and extensive testing across different chains.
After: Built-in patterns for CCIP and LayerZero integration, automated cross-chain testing, and frontend components that handle multi-chain state management and bridge transaction tracking.
Create a new Web3 project or open your existing one:
# Initialize new Web3 project with proper structure
mkdir my-web3-app && cd my-web3-app
npx create-next-app@latest frontend --typescript --tailwind --app
mkdir contracts && cd contracts
npm init -y && npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
Ask Cursor: "Set up a production-ready Web3 development environment with Hardhat, Next.js, and proper TypeScript configuration"
Instead of starting from scratch, ask Cursor:
"Create an ERC-20 token contract with built-in security patterns, gas optimizations, and comprehensive test suite"
You'll get a complete implementation with:
Ask Cursor: "Generate TypeScript React components for interacting with my token contract, including proper error handling and state management"
Get production-ready components with:
Week 1: Your smart contracts now include proper security patterns by default. No more missing events, improper error handling, or reentrancy vulnerabilities. Your test coverage jumps to 100% with minimal effort.
Week 2: Cross-chain deployments become routine. Deploy to Ethereum mainnet, Polygon, and Arbitrum with a single command. Your deployment scripts handle gas optimization, contract verification, and address management automatically.
Month 1: You're shipping Web3 features 3x faster than before. Your frontend seamlessly handles wallet connections, transaction states, and error scenarios. Your contracts pass external audits with minimal changes required.
Month 3: You've built production-grade DeFi protocols, NFT marketplaces, or DAO governance systems using battle-tested patterns. Your development workflow is optimized for security-first, gas-efficient, and audit-ready code.
Stop fighting your development tools and start building the decentralized future. Your Web3 development acceleration starts now.
You are an expert in Solidity, TypeScript, Hardhat, Foundry, Ethers.js, React 18/Next.js 14, GraphQL, Postgres, IPFS, AWS.
Key Principles
- Design for decentralization first: minimise on-chain state, move heavy logic to Layer-2 or off-chain.
- Embrace sustainability: favour Proof-of-Stake chains and compress calldata (EIP-4844 blobs).
- Always optimise for security; gas comes second, readability third.
- Use immutable, deterministic deployments; version contracts (v1, v2) rather than mutating.
- Prefer composition over inheritance; deploy small, single-purpose contracts.
- Off-chain code MUST verify on-chain data – never trust the RPC.
- Write exhaustive tests; 100 % branch/require coverage is mandatory before mainnet.
- Any deployable artefact (contract, subgraph, frontend build) must be reproducible from CI.
- All monetary values are represented as uint256 with 18 decimals (canonical wei) or ERC-20 decimals via helper.
- Regulatory compliance: record chainId and user signatures for KYC/AML audits.
Solidity
- ^0.8.x compiler only – disable `unsafe-allow` pragmas.
- Layout order: pragma → imports → errors → interfaces → libraries → contracts.
- Naming
• Contracts, libraries, errors: PascalCase (e.g., `LiquidityPool`).
• Constants: UPPER_SNAKE (e.g., `MAX_BPS`).
• Private vars: `_camelCase`. Public vars: `camelCase`.
- Use custom errors (`error InsufficientBalance(uint256 available, uint256 required);`) – never string reverts.
- Visibility explicitly stated for EVERYTHING (`public`, `internal`, `private`).
- State-changing functions MUST emit events.
- Follow CEI (Checks-Effects-Interactions) & ReentrancyGuard; use `nonReentrant` modifier.
- Use OpenZeppelin contracts; never re-implement ERC standards.
- Gas patterns
• Pack structs & storage slots.
• Use `uint256 immutable` over `constant` when value set in constructor.
• External view functions are `view` not `pure` unless totally stateless.
- Upgradeability
• Prefer transparent proxy via OZ; store gap `uint256[50] private __gap;`.
• No self-destruct.
- Cross-chain
• Use CCIP / LayerZero libraries; always validate `chainSelector`.
TypeScript (Node & React)
- `strict`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes` must be enabled.
- Type-safe ABIs via `@typechain/ethers-v6`; avoid `any`.
- Directory keel: `src/{contracts,abis,generated,graph,components,hooks,lib}`.
- Use React function components with hooks; never class components.
- State: use `zustand` or `wagmi` store; no Redux.
- Async calls: always `await` `tx.wait(1)` then parse events.
- Big numbers: use `viem` or `ethers` `BigInt`; never JS number.
- ENV separation: `NEXT_PUBLIC_` for public, others server-side only.
Error Handling & Validation
- Smart contract: revert early with custom error; include minimal data.
- Off-chain:
• Wrap provider errors: `InvariantError`, `RpcError`, `DecodeError`.
• Use `zod` to validate JSON, REST, GraphQL responses.
- Frontend: toast user-readable message; send full stack to Sentry.
- All caught errors MUST be logged with `chainId`, `txHash`, and userWallet.
Hardhat Rules
- One task file per domain (`deploy-pool.ts`).
- Deploy scripts MUST:
• Use `const { deploy } = deployments`.
• Verify on Etherscan automatically.
• Write addresses to `deployments/<network>.json`.
- Gas reporter and coverage plugins required in CI.
- Don’t run `console.log` on live networks.
Foundry Rules
- Use forge for fuzzing & invariant tests; min 100 runs.
- Snapshot mainnet state (`fork( blockNumber )`) for integration tests.
- Keep unit tests in `test/Unit` and forks in `test/Fork`.
React/Next.js Rules
- Use App Router with Server Components for data fetching.
- All wallet interactions in Client Components only.
- Configure CSP: disallow `eval`, only connect to known RPC endpoints.
- Generate metadata from on-chain data server-side (`getMetadata(contract)`).
Testing
- Solidity
• Unit: 1 function = 1 test file.
• Fuzz critical math.
• Invariant: `totalSupply >= collateral`.
- TypeScript
• Jest + viem mocks; snapshot event logs.
- Use Kubernetes job to run test matrix across forks (Ethereum, Polygon, Arbitrum).
Performance & Gas Optimisation
- Strive <35k gas for standard ERC-20 `transfer`.
- Cache `sload` values into memory in loops.
- Move signature verification off-chain (EIP-712 typed data + `permit`).
- Batch operations via multicall or rollup bridge.
Security
- Mandatory external audit (Certik/OpenZeppelin) before mainnet.
- Double-audit if TVL > $1 M.
- Integrate Slither + MythX in pre-push git hook.
- Bug bounty via Immunefi with ≥5 % of pre-sale allocation.
- Keys stored in AWS KMS; no private key in CI.
- DAO Governance: timelock ≥48 h, emergency pause role, no single-sig privilege.
Compliance & Regulatory
- Log user signature + IP in analytics DB for KYC countries.
- Automatic OFAC address screening by Chainalysis API.
Documentation
- Use Natspec for every external/public function.
- Autogenerate markdown via `npm run doc` into `docs/api`.
CI/CD
- Pre-push: lint (eslint + solhint), tests, slither.
- Main branch: forge coverage ≥90 %, build static site, IPFS pin, Arweave backup.
- Tag releases: `vX.Y.Z-chain`. Deploy via GitHub Actions & Hardhat tasks.