Smart contracts are deterministic programs, but they are not automatically safe. Once deployed on a public blockchain, a coding error can be exploited at internet speed, often with irreversible financial consequences. Smart-contract security is the discipline of preventing, detecting, and containing these failures across the entire contract lifecycle—from architecture and coding to deployment, upgrades, and incident response.
For Indian Web3 startups, security is also a business requirement. A protocol may need to satisfy users, token holders, enterprise partners, investors, exchanges, and compliance stakeholders while operating across public, permissioned, or Layer 2 networks. This guide explains the technical foundations, common attack classes, audit process, testing strategy, and practical controls founders can implement before handling real value.
What Is Smart-Contract Security?
Smart-contract security combines secure software engineering, blockchain-specific threat modelling, formal reasoning, and operational controls. It aims to ensure that a contract:
- Enforces its intended business rules under valid and adversarial inputs.
- Cannot be manipulated through unexpected transaction ordering or external calls.
- Protects assets, permissions, accounting state, and user balances.
- Remains safe during upgrades, pauses, migrations, and emergency actions.
- Fails predictably when assumptions are violated.
Security is broader than obtaining an audit report. An audit is a point-in-time review; security is an ongoing process involving specifications, code review, automated testing, independent verification, deployment controls, monitoring, and response planning.
Why Smart-Contract Security Is Difficult
Blockchain execution creates constraints that differ from conventional web applications. Transactions are publicly observable, state transitions are replicated by network participants, and deployed bytecode is difficult or impossible to modify without an upgrade mechanism. Attackers can inspect source code, simulate transactions, purchase block space, and exploit a vulnerability immediately after deployment.
Several properties make the problem harder:
- Immutability: A vulnerable contract may continue operating until users or administrators can pause it.
- Composability: A contract can interact with tokens, bridges, oracles, wallets, and protocols that have their own assumptions.
- Transaction ordering: Arbitrageurs and attackers may observe pending transactions and influence execution order.
- Economic complexity: A function can be logically correct but economically exploitable under volatile prices or low liquidity.
- Privileged control: Admin keys, upgrade proxies, and emergency roles can become single points of failure.
- Irreversible settlement: Confirmed transactions generally cannot be rolled back by a central operator.
Common Smart-Contract Vulnerabilities
Reentrancy
Reentrancy occurs when a contract makes an external call before completing its internal state update, allowing the called contract to call back into the original function. The classic defence is the checks-effects-interactions pattern: validate conditions, update state, and only then interact externally. A reentrancy guard can add protection, but it should not replace correct state design.
Developers should consider cross-function and cross-contract reentrancy, not only repeated calls to one function. ERC-777-style hooks, callbacks, token receivers, and arbitrary external calls deserve special review.
Access-Control Failures
Incorrect permissions can allow an attacker to mint tokens, change an oracle, upgrade implementation logic, withdraw funds, or pause a protocol. Review every privileged function and document:
- Which role can call it.
- Whether the role is a wallet, multisig, timelock, or contract.
- Whether the action needs separation of duties.
- Whether the role can be revoked or rotated.
- What happens if the key is compromised.
Use explicit role-based access control rather than relying on informal conventions or hidden assumptions about msg.sender.
Arithmetic and Accounting Errors
Modern Solidity versions include checked arithmetic by default, but accounting vulnerabilities remain common. Examples include incorrect decimal conversions, rounding in favour of users, share-price manipulation, double counting, and inconsistent asset and liability updates.
Test boundary conditions such as zero values, maximum integers, repeated deposits, partial withdrawals, fee deductions, and tokens with non-standard decimals. In financial contracts, define conservation properties: total assets, liabilities, shares, and claims should reconcile after every state transition.
Oracle Manipulation
Protocols that use prices, exchange rates, collateral valuations, or randomness depend on external data. A spot price from a low-liquidity pool may be manipulated within one transaction. A stale, delayed, or incorrectly scaled oracle can also create insolvency.
Mitigations include time-weighted prices, multiple independent sources, deviation limits, heartbeat checks, circuit breakers, conservative collateral factors, and explicit handling of unavailable data. Oracle assumptions should be tested against flash-loan liquidity, volatile markets, and sequencer outages on Layer 2 networks.
Front-Running and MEV
Public mempools expose transactions before execution. Attackers may reorder, insert, or back-run transactions to extract value. Common examples include sandwich attacks, priority manipulation, liquidation races, and auction sniping.
Possible controls include commit-reveal schemes, slippage limits, batch auctions, private transaction routing, deadlines, minimum output checks, and designs that do not expose sensitive intent prematurely. No single mitigation works for every protocol; model the actual value-extraction path.
Flash-Loan and Economic Attacks
Flash loans allow attackers to obtain substantial temporary liquidity without collateral, execute a series of operations, and repay within one transaction. The loan itself is not a vulnerability. It becomes dangerous when a protocol trusts manipulable prices, temporary balances, shallow liquidity, or one-block assumptions.
Evaluate economic invariants under adversarial capital. Test whether an attacker can distort a market, borrow against inflated collateral, manipulate governance voting, or exploit a temporarily favourable exchange rate.
Unsafe Upgradeability
Proxy patterns enable bug fixes but introduce administrative and storage risks. Common failures include unprotected upgrade functions, incorrect implementation initialization, storage-layout collisions, delegatecall misuse, and upgrades that silently change economic rules.
Use well-understood proxy standards, initialize implementations safely, validate storage layouts, place upgrades behind a multisig and timelock where appropriate, and publish upgrade procedures. Users should know who can upgrade the contract and what notice or emergency process applies.
Denial of Service and Gas Griefing
Loops over unbounded arrays, failed external calls, gas-sensitive logic, and storage-heavy operations can make a function unusable. A malicious participant may deliberately create enough state to exceed block gas limits or force a batch operation to fail.
Prefer pull-based withdrawals, bounded loops, pagination, incremental processing, and failure isolation. Estimate gas for worst-case state, not only for a clean deployment.
A Secure Smart-Contract Development Lifecycle
1. Write a Security-Critical Specification
Before coding, describe assets, actors, trust boundaries, privileged operations, state transitions, and failure modes. Define what must always be true. Examples include:
- Only authorised roles can mint or upgrade.
- Total claims cannot exceed available assets, subject to documented liabilities.
- Withdrawals cannot exceed a user’s balance.
- A paused system cannot execute restricted economic actions.
- An oracle value must be fresh and within accepted bounds.
A written specification gives auditors and testers something more precise than a repository and a product pitch.
2. Model Threats and Trust Assumptions
Use a threat model that identifies attackers, capabilities, incentives, and dependencies. Consider external users, malicious token contracts, compromised administrators, oracle failures, chain reorganisations, sequencer downtime, bridge messages, and governance capture.
Record assumptions explicitly. For example, “the oracle is honest” is too broad; specify its update mechanism, freshness requirement, deviation tolerance, and failure response.
3. Implement Conservatively
Keep contracts modular and minimise external calls. Use established libraries, compiler versions, interfaces, and patterns rather than copying unaudited snippets. Emit events for important state changes, validate function inputs, and avoid unnecessary complexity.
NatSpec documentation is useful for communicating intent, especially around units, permissions, invariants, and upgrade behaviour. Clear code improves both human review and automated analysis.
4. Test Beyond Happy Paths
A robust test suite should include unit tests, integration tests, fuzz tests, invariant tests, fork tests, and deployment tests. Test malicious tokens, unusual return values, fee-on-transfer behaviour, rebasing assets, failed calls, stale prices, and unexpected callback paths.
Fuzzing generates broad input combinations, while invariant testing checks whether properties remain true across sequences of actions. Foundry, Hardhat, Echidna, Slither, Mythril, and commercial tools can support this process, but tools require correctly defined properties and human interpretation.
5. Perform Independent Reviews
Use multiple review layers where risk justifies the cost:
- Internal peer review for architecture and business logic.
- Automated static analysis for known coding patterns.
- Specialist review for cryptography, bridges, oracles, and token economics.
- Independent audit before mainnet deployment.
- Contest or bug bounty review for broader adversarial coverage.
An audit should result in reproducible findings, severity ratings, remediation evidence, and a clear statement of scope. Verify that deployed bytecode matches the reviewed commit.
What a Smart-Contract Audit Should Cover
A meaningful audit is not merely a scan for compiler warnings. It should examine:
- Business logic and accounting invariants.
- Access control and role administration.
- Reentrancy and external-call behaviour.
- Upgradeability and storage compatibility.
- Oracle and pricing assumptions.
- Token-standard compatibility.
- Gas, denial-of-service, and griefing risks.
- MEV and transaction-ordering exposure.
- Chain-specific behaviour and deployment configuration.
- Events, emergency controls, and operational procedures.
Before engaging an auditor, provide architecture diagrams, specifications, threat models, test instructions, known limitations, deployment addresses, and dependency details. Freeze the code scope and avoid treating an audit as a substitute for an unfinished design.
Deployment and Operations Checklist
Security continues after the audit. Before mainnet:
- Deploy with a reproducible, documented process.
- Verify source code and compiler settings on the relevant explorer.
- Confirm constructor and initializer parameters.
- Use hardware-secured signer infrastructure where appropriate.
- Place high-impact administration behind a properly configured multisig.
- Test pause, rescue, and recovery procedures on a staging or forked network.
- Set transaction simulation and approval policies for privileged actions.
- Monitor balances, role changes, oracle updates, abnormal gas, and large withdrawals.
- Publish contract addresses, risks, limits, and support channels.
For Indian teams, maintain an auditable record of grants, treasury movements, vendor access, and deployment approvals. Security governance should align engineering, finance, legal, and founder responsibilities rather than leaving all control with one developer wallet.
Bug Bounties and Incident Response
A bug bounty can improve coverage, but it needs clear scope, severity definitions, safe-harbour language reviewed for the relevant jurisdictions, response targets, and payment criteria. Include deployed contracts and meaningful economic attack surfaces; excluding the core system can make the programme ineffective.
Prepare an incident runbook before an incident occurs. It should identify who can pause the system, how to revoke roles, how to communicate with users, how to preserve evidence, and how to coordinate with exchanges, infrastructure providers, auditors, and legal advisers. A fast, rehearsed response may limit losses even when prevention fails.
Smart-Contract Security for Indian AI and Web3 Startups
AI products increasingly intersect with smart contracts through tokenised data access, agent wallets, decentralised compute, model licensing, provenance, payments, and autonomous on-chain actions. These systems combine model uncertainty with deterministic settlement, creating additional risks.
Keep AI decisions separate from irreversible fund movement where possible. Use spending limits, allowlists, human approval thresholds, rate limits, simulation, and circuit breakers for autonomous agents. Do not assume that an AI model’s output is trustworthy merely because the transaction is signed. Validate inputs and constrain actions at the contract and wallet layers.
Indian founders should also assess tax, consumer protection, data governance, cybersecurity, foreign exchange, and virtual digital asset implications with qualified advisers. Technical security does not by itself establish regulatory compliance, and regulatory status can depend on the product, users, assets, custody model, and jurisdictions involved.
Practical Pre-Mainnet Checklist
Use this condensed checklist before accepting meaningful value:
- [ ] Security specification and threat model are documented.
- [ ] All privileged roles and upgrade paths are mapped.
- [ ] Critical invariants have automated tests.
- [ ] Fuzzing and invariant testing cover adversarial sequences.
- [ ] Oracle, MEV, flash-loan, and economic risks are assessed.
- [ ] External calls and callback behaviour are reviewed.
- [ ] Upgrade and storage-layout checks are complete.
- [ ] Independent audit findings are fixed and retested.
- [ ] Deployed bytecode matches the reviewed source.
- [ ] Multisig, timelock, monitoring, and alerting are operational.
- [ ] Pause and incident-response procedures have been exercised.
- [ ] Users can understand key limitations and admin powers.
FAQ: Smart-Contract Security
Is a smart-contract audit enough?
No. An audit improves confidence but is limited by scope, time, code version, and reviewer assumptions. Secure development also requires testing, formalised invariants, operational controls, monitoring, and post-deployment review.
How much does smart-contract security cost in India?
Costs vary substantially with protocol complexity, chain count, code size, financial exposure, and auditor reputation. Budget for specification, testing, independent review, remediation, deployment controls, monitoring, and a continuing bounty—not only the initial audit.
When should a startup get an audit?
Obtain an audit after the architecture and code are sufficiently stable but before mainnet launch or material funds are accepted. Significant post-audit changes require review and may invalidate earlier conclusions.
Can formal verification replace an audit?
Formal verification can prove specified properties under defined assumptions, but it does not automatically validate business requirements, oracle design, economic incentives, deployment configuration, or operational security. It complements expert review.
What is the first security step for a new protocol?
Write down the assets, trust assumptions, privileged actions, attacker capabilities, and invariants. A precise security specification prevents many design-level vulnerabilities before they become code-level defects.
Apply for AI Grants India
If you are an Indian AI founder building secure Web3 infrastructure, autonomous agents, or blockchain-enabled AI products, apply for support through AI Grants India. Share your technical approach, security roadmap, and innovation clearly so your project can be evaluated for relevant grant opportunities.