TL;DR – BLOCKCHAIN SECURITY (3-MINUTE READ)
WHO NEEDS THIS GUIDE?
Anyone building a DApp (Decentralized App) or smart contract. Our Web3 development services ensure your blockchain applications are secure from day one. For payment-focused blockchain apps, see our guide on fintech compliance.
THE HARSH TRUTH
On traditional apps: • User clicks bad button → Refund user → Problem solved
On blockchain: • User calls bad function → $50M transferred to hacker → Permanent
On-chain is permanent. There's no undo button. BSH Technologies specializes in building secure blockchain applications with comprehensive security audits.
THE THREE RULES OF DAPP SECURITY
Rule 1: Code audit is mandatory, not optional • Professional security audit: $5K-50K • This is not optional. It's insurance. • Cost of hack (if it happens): $100K-$100M+
Rule 2: You will make mistakes • Best developers make mistakes • Assume your code has bugs • Test everything like your money depends on it (it does)
Professional DevOps services implement automated testing and continuous monitoring for your blockchain infrastructure.
Rule 3: On-chain data is public • Everyone can see transactions • Everyone can see smart contract code • Everyone can see user balances • Plan for this
QUICK VULNERABILITIES CHECKLIST
Before launch, audit for these: • Reentrancy attacks (recursive calls) • Integer overflow/underflow • Unchecked external calls • Front-running opportunities • Flash loan attacks • Time-dependent logic • Delegate call dangers • Access control gaps • Price oracle manipulation • Unbounded loops
If ANY of these exist → Don't launch until fixed
COST BREAKDOWN
Building secure blockchain applications requires careful technology choices. See our guide on choosing the right technology stack.
| Security Task | Cost | Timeline | Criticality |
|---|---|---|---|
| Code review (peer) | $0 | 1 day | HIGH |
| Automated testing | $5K | 1-2 weeks | HIGH |
| Security audit | $15K-50K | 2-4 weeks | CRITICAL |
| Bug bounty program | $5K-50K | Ongoing | HIGH |
Total security budget: $20K-100K (for $10M+ TVL protocol)
For small protocol: $5K-20K minimum
Our cloud services provide secure infrastructure for hosting blockchain nodes and DApp backends.
THE REAL QUESTION
Before building:
- Why does your protocol need to be on-chain?
- Could you solve this off-chain first?
- What's the maximum loss if exploited?
- Do you have security budget?
Our blockchain DApp development services help you evaluate and implement secure Web3 solutions.
If max loss is < $100K: Maybe you need less security If max loss is > $1M: Security is now $50K+ budgeted cost
INTRODUCTION: WHY SMART CONTRACT SECURITY MATTERS
June 17, 2016. The DAO hack.
Someone exploited a one-word vulnerability in The DAO smart contract.
Result: $50 million stolen.
The code was reviewed. The code was tested. The code was "secure."
But one line of code was wrong.
That single line cost The DAO $50M.
Fast forward to 2024. Bridges get hacked. DEXs get exploited. Users lose billions.
The pattern is always the same: • Smart contract has a bug • No one notices • Someone exploits it • Money is permanently gone • Users are permanently out of money
Why DApp Security is Different
Normal app: Bug exists → You deploy patch → Users update app → Fixed
Smart contract: Bug exists → Deployed on-chain → Anyone can exploit → Permanent loss
The fundamental problem: Once deployed, smart contract code cannot be changed.
This is a feature (immutability, trustlessness). But it's also a bug if your code has bugs.
The Security Industry Response
By 2026, the industry learned: • Audits are mandatory (not optional) • Audits need to be professional (not internal review) • Best practices must be followed • Testing must be comprehensive • Monitoring must be continuous
For comprehensive smart contract development resources, visit Ethereum.org.
This guide teaches you all of it.
WHAT ARE DAPPS? (BLOCKCHAIN APPS EXPLAINED)
Let's start with the basics.
Traditional App Architecture
Client (User's Phone): • User interface • User actions (tap, scroll, type)
↓ (Send request)
Server (Company's Computers): • Database • Business logic • Verification
Our custom software development services build secure traditional architectures with robust backend systems.
↓ (Send response)
Client (User's Phone): • Display result • Update UI
Example: Ordering food on DoorDash
- User opens app (client)
- User selects restaurant (client sends request to server)
- Server validates order, checks inventory, calculates price
- Server stores order in database
- Server sends confirmation to client
- User sees confirmation on phone
Learn more about building mobile apps with traditional architecture.
DApp Architecture (Decentralized)
Client (User's Wallet): • User interface • User actions
↓ (Send transaction)
Smart Contract (Blockchain): • Stored on thousands of computers • Everyone verifies transaction • Everyone agrees on result • Result is permanent
Client (User's Wallet): • Display result
Example: Swapping tokens on Uniswap (DEX)
- User connects wallet
- User specifies: "Swap 1 ETH for USDC"
- User approves transaction
- Smart contract receives transaction
- All blockchain nodes verify transaction
- All nodes execute smart contract code
- All nodes update blockchain
- Transaction is permanent
- User sees USDC in wallet
Key Difference: Decentralization
Traditional: • One server (one point of failure) • Company controls data • Company can change rules • Requires trust in company
Decentralized: • Thousands of servers (no single point of failure) • Code is the rules • Rules can't be changed (immutable) • No trust needed (math/cryptography)
The Security Implication
Because smart contracts are: • Public: Everyone can see the code • Immutable: Code can't be changed • Valuable: Often handles millions in assets
They become targets for attacks.
For comprehensive smart contract development resources, visit Ethereum.org and explore the official documentation.
SMART CONTRACT VULNERABILITIES (TOP 10)
These are the most common ways smart contracts get hacked.
Vulnerability #1: Reentrancy
What it is: Calling external function before updating internal state.
Example (BAD CODE): function withdraw(uint amount) public { // DANGER: Send ETH before updating balance! msg.sender.call{value: amount}(""); balance[msg.sender] -= amount; // Too late! }
Attack:
- Attacker calls withdraw(1 ETH)
- Smart contract sends 1 ETH to attacker
- Attacker's contract receives ETH
- Attacker's contract calls withdraw again (while first withdrawal still running)
- Smart contract hasn't updated balance yet
- Attacker withdraws again
- Repeat 10 times
- Attacker steals 10 ETH with only 1 ETH
The DAO hack used this.
Fix: function withdraw(uint amount) public { balance[msg.sender] -= amount; // Update first! msg.sender.call{value: amount}(""); }
Key lesson: Always update state BEFORE calling external functions.
Vulnerability #2: Integer Overflow/Underflow
What it is: Numbers wrap around unexpectedly.
Example (BAD CODE): uint balance = 100; balance -= 101; // Underflow! balance becomes huge number
In Solidity <0.8: Numbers wrap (100 - 101 = very large number) In Solidity 0.8+: Throws error (safe default)
Impact: Attacker can create infinite tokens, drain contracts, etc.
Fix: Use Solidity 0.8+ (has safe math built-in)
Vulnerability #3: Unchecked External Calls
What it is: Assuming external function calls always succeed.
Example (BAD CODE): function sendTokens() public { externalToken.transfer(user, amount); // What if this fails? // Code continues even if transfer fails }
Impact: Function says "transfer succeeded" but it didn't.
Fix: require(externalToken.transfer(user, amount), "Transfer failed");
Vulnerability #4: Front-Running
What it is: Someone seeing your transaction and executing first.
How it works:
- You broadcast transaction: "Swap 10 ETH for USDC"
- Transaction is in mempool (visible to everyone)
- Bot sees your transaction
- Bot submits same transaction with higher gas fee
- Bot's transaction executes first
- Bot swaps 10 ETH for USDC
- Price increases
- Your transaction executes
- You get less USDC because price is now higher
- Bot profits from your slippage
Impact: Millions lost to MEV (Miner Extractable Value)
Fix: Use private mempools (MEV protection services)
Vulnerability #5: Flash Loan Attacks
What it is: Borrowing huge amount of money, attacking protocol, repaying in same transaction.
Example:
- Attacker borrows 1,000,000 ETH (0 collateral!)
- Attacker uses ETH to manipulate prices
- Attacker exploits protocol
- Attacker repays loan + fee
- Net profit: $10M
The issue: Loan happens in same transaction (atomic). No time for safeguards.
Fix: Price oracles shouldn't rely on current block price. Use time-weighted prices.
Vulnerability #6: Time-Dependent Logic
What it is: Using block.timestamp for critical logic.
Example (DANGEROUS): function claimReward() public { require(block.timestamp > lockupEnd, "Locked"); // Reward user }
Issue: Miners can manipulate block.timestamp (within reason)
Fix: Use block.number instead for hard deadlines
Vulnerability #7: Delegate Call Dangers
What it is: Using delegatecall without understanding consequences.
delegatecall: • Calls external code • But executes in current contract's context • Can modify current contract's storage!
If you use delegatecall to untrusted code: • Attacker can steal entire contract • Attacker can modify state arbitrarily • Attacker can drain all funds
Fix: Never use delegatecall with untrusted code. Only with audited code.
Vulnerability #8: Access Control Gaps
What it is: Functions that should be restricted are public.
Example (DANGEROUS): function adminWithdraw(uint amount) public { // OOPS: public! msg.sender.transfer(amount); }
Attack: • Anyone can call this function • Anyone can withdraw
Fix: function adminWithdraw(uint amount) public onlyAdmin { msg.sender.transfer(amount); }
Vulnerability #9: Price Oracle Manipulation
What it is: Smart contract relies on prices that can be manipulated.
Example: uint price = uniswapPrice(); // Attacker can manipulate! require(msg.value >= (amount price), "Insufficient payment");
Attack: • Attacker manipulates Uniswap price • Contract uses wrong price • Attacker buys tokens at discount
Fix: Use Chainlink oracle (decentralized, manipulation-proof)
Vulnerability #10: Unbounded Loops
What it is: Loop that could iterate too many times.
Example (DANGEROUS): function distributeRewards() public { for (uint i = 0; i < users.length; i++) { // If 10,000 users? users[i].transfer(reward); } }
Issue: • Gas limit hit (transaction reverts) • Function becomes un-callable • Stuck state
Fix: Use pagination (distribute to 100 users per call, repeat)
SMART CONTRACT AUDITS
If you build a DApp, you need an audit.
What's an Audit?
Definition: Expert review of smart contract code to find security bugs.
Process:
- Security firm receives smart contract code
- Senior developers review line-by-line
- They look for all 10 vulnerabilities above (+ more)
- They write report with findings
- You fix findings
- Audit firm re-reviews
- Audit passes (or fails)
Duration: 2-4 weeks
Cost: $5K-50K depending on complexity
Why Audits Are Critical
Fact 1: Professional auditors find bugs that internal teams miss
Fact 2: One bug = millions in potential loss
Fact 3: Audits cost 0.1% of potential loss
Fact 4: Users trust audited protocols more
Types of Audits
Basic Audit ($5K-15K) • 1 auditor reviews code • 1 week timeline • Finds major bugs only • Not enough for >$10M TVL
Standard Audit ($15K-40K) • 2-3 auditors review • 2-3 weeks timeline • Finds majority of bugs • Recommended for most protocols
Deep Audit ($40K-100K+) • 5+ auditors review • 3-4 weeks • Finds subtle bugs • For protocols with >$100M TVL
Audit Checklist
Before auditing, ensure: • Code is clean (no console.log, TODOs) • Code is documented (comments explaining logic) • Tests pass (100% test coverage minimum) • No known vulnerabilities • Architecture is sound • Version control is set up (GitHub)
How to Choose Auditor
Red Flags: • Auditor hasn't done security before • Auditor does audit in 2 days (too fast) • Auditor doesn't ask questions about protocol • Auditor doesn't provide detailed report
Good Signs: • Auditor is well-known (CertiK, Trail of Bits, OpenZeppelin) • Auditor has done 100+ audits • Auditor has found real bugs • Auditor takes 2+ weeks • Auditor provides detailed report
Cost-Benefit
Protocol TVL: $1M • Audit cost: $10K • Max loss if exploited: $1M • Audit ROI: 100:1 (very worth it)
Protocol TVL: $100M • Audit cost: $50K • Max loss if exploited: $100M • Audit ROI: 2,000:1 (absolutely critical)
SECURE DEVELOPMENT TOOLS & FRAMEWORKS
Best tools for secure DApp development (2026):
Solidity Frameworks
Hardhat (Most popular) • Testing framework • Local blockchain simulation • Easy debugging • Great documentation
Foundry (Growing fast) • Faster than Hardhat • Written in Rust • Advanced features • Harder to learn
Truffle (Original, less popular now) • OG framework • Still solid • Better documentation • Slower than alternatives
Recommendation: Use Hardhat for most projects.
Testing Tools
Hardhat + Ethers.js • Unit testing • Integration testing • Gas profiling • Coverage reports
Foundry + Forge • Fuzz testing • Symbolic execution • Advanced features
Coverage.dev • Visual coverage reports • Integration with CI/CD
Static Analysis Tools
Slither (Most important) • Analyzes code for vulnerabilities • Catches common bugs automatically • Free & open source • Run before every commit
Mythril • Deep analysis • Finds complex bugs • Slower but thorough
Certora (Advanced) • Formal verification • Proves correctness • Expensive but ultimate safety
Monitoring Tools
Tenderly (Best overall) • Real-time monitoring • Simulates transactions • Alerts for abnormal activity
Dune Analytics • Post-exploit analysis • Understand what happened
OpenZeppelin Defender • Automated monitoring • Attack responses • Incident management
TESTING SMART CONTRACTS
Write tests for everything.
Unit Tests
Test individual functions: test_withdraw_with_valid_amount() { // Setup balance[user] = 100;
// Execute user.withdraw(50);
// Assert assert(balance[user] == 50); assert(user.balance == 50); }
Test edge cases: • Withdraw 0 (should work or fail?) • Withdraw more than balance (should fail) • Withdraw exactly balance (should work) • Withdraw twice in a row (should work) • Withdraw with no balance (should fail)
Coverage target: 100% of code lines
Integration Tests
Test features working together: test_stake_and_claim_rewards() { // User stakes tokens user.stake(100);
// Time passes advanceBlocks(1000);
// User claims rewards user.claimRewards();
// Check tokens + rewards received assert(user.balance == 100 + rewards); }
Fuzz Testing
Automatically generate random inputs:
test_withdraw_fuzz(uint randomAmount) { // Test with thousands of random amounts // Automatically finds edge cases }
Fuzz testing found many bugs that unit tests missed.
Gas Testing
Test gas consumption:
test_swap_gas_efficiency() { // Should use <150K gas // If gas increases, you have a problem }
BEST PRACTICES (SECURITY FROM DAY ONE)
Practice 1: Code Review
Before audit: • Have 2-3 developers review each line • Look specifically for vulnerabilities • Question assumptions • Test edge cases
Practice 2: Minimize Complexity
Simple code is safer code.
BAD: // 500 lines of nested logic // 10 external calls per transaction // Complex state transitions
GOOD: // 100 lines of clear logic // 1 external call per transaction // Simple state transitions
Practice 3: Use Battle-Tested Code
Don't write your own: • ✗ Don't write your own crypto • ✗ Don't write your own access control • ✗ Don't write your own token standard
Use libraries: • OpenZeppelin (battle-tested, audited) • Solmate (gas-optimized) • Safe Math (automatic overflow checks)
Practice 4: Documentation
Document every function: /// @dev Withdraws ETH balance /// @param amount Amount to withdraw /// @return success Whether withdrawal succeeded function withdraw(uint amount) public returns (bool success) {
Document assumptions: // ASSUMPTION: Price oracle is reliable // ASSUMPTION: External contract won't reentrancy attack
Practice 5: Upgradeable Architecture (With Caution)
Some contracts need upgrades: • Use proxy pattern (proxy contract + implementation) • But proxies add complexity • And proxies can be exploited • Only use if you really need upgrades
ON-CHAIN VS OFF-CHAIN SECURITY
Smart contract = on-chain Backend server = off-chain
On-Chain Security
Everything is public: • Code is visible • Transactions are visible • Balances are visible • All data is immutable
Advantages: • Trustless (don't need to trust anyone) • Transparent (everyone can verify) • Immutable (permanent record)
Disadvantages: • Slower (blockchain latency) • Expensive (gas fees) • Can't undo mistakes • Security is permanent
Off-Chain Security
Traditional web server approach: • Code is hidden • Transactions are private • Balances are in database • Company controls rules
Advantages: • Faster (instant execution) • Cheap (no fees) • Can undo mistakes • More flexible
Disadvantages: • Requires trust (trust company) • Single point of failure • Company can change rules • Can be hacked/shut down
Hybrid Approach (Best)
Move computation off-chain, settlement on-chain:
- Users interact with app (off-chain)
- Results are computed (off-chain)
- Final settlement happens on-chain
- Blockchain verifies integrity
Examples: • Optimistic Rollups (compute off-chain, verify on-chain) • Sidechains (fast off-chain, secured by main chain) • State channels (instant off-chain, final on-chain)
POST-LAUNCH MONITORING & INCIDENT RESPONSE
Real-Time Monitoring
Set up alerts for: • Unusual token transfers • Large withdrawals • Function calls that are abnormal • Price changes that don't make sense • Access control violations
Incident Response Plan
IF HACK HAPPENS:
Minute 1-5: • Confirm the hack (is it real?) • Pause contract if pauseable • Alert team and users
Hour 1: • Understand what was exploited • Calculate total loss • Begin investigation
Day 1: • Post-mortem report • Public communication • Engage law enforcement (if applicable) • Engage auditor for analysis
Week 1: • Root cause analysis • Fix the vulnerability • Get new audit • Plan recovery/compensation
The Pause Button
Best practice: Include pause functionality
modifier whenNotPaused { require(!paused, "Contract is paused"); _; }
function emergencyPause() public onlyAdmin { paused = true; }
If exploit happens: • Admin pauses contract • Limits damage • Buys time to fix • Protects remaining funds
But pauses are risky: • Can be abused • Users lose trust • Don't pause lightly
HACK CASE STUDIES
Learn from real disasters.
Case Study #1: The DAO Hack ($50M, 2016)
What happened: • The DAO had a reentrancy vulnerability • Attacker called withdraw function • Function transferred ETH before updating balance • Attacker's contract called back into withdraw • Attacker withdrew multiple times • $50M stolen
What it taught us: • Reentrancy is critical • Code review isn't enough • Audits are necessary • Design matters (should have checks-effects-interactions pattern)
Today's lesson: Always update state before external calls.
Case Study #2: Poly Network Hack ($611M, 2021)
What happened: • Access control vulnerability in cross-chain bridge • Anyone could call admin functions • Attacker minted tokens on multiple chains • $611M worth of tokens transferred
What it taught us: • Cross-chain is extremely complex • Access control must be airtight • Don't rush to launch • Multiple independent audits needed for critical functions
Today's lesson: Access control bugs are deadly.
Case Study #3: Ronin Bridge Hack ($625M, 2022)
What happened: • Attacker stole private keys • Used keys to forge transactions • Drained entire bridge contract • $625M stolen
What it taught us: • Key management is critical • Don't use single signing • Require multiple signers (M-of-N) • Secure keys properly
Today's lesson: Keys are the highest value target.
Case Study #4: Curve Finance Exploit ($60M, 2023)
What happened: • Price manipulation vulnerability • Attacker used large transactions to manipulate pricing • Exploited algorithmic pricing mechanism • $60M lost
What it taught us: • Pricing logic is complex • Price oracles can be manipulated • Use decentralized oracles (Chainlink) • Test edge cases in pricing
Today's lesson: Pricing and oracle manipulation is dangerous.
FINAL SECURITY CHECKLIST
Before launch:
Code Quality
✓ Code is clean (no console.log, test code removed) ✓ Code is commented (explain non-obvious logic) ✓ Code is documented (function descriptions) ✓ Code follows conventions (style guide) ✓ Code passes linter (Slither has no warnings)
Testing
✓ Unit test coverage 100% ✓ Integration tests for full workflows ✓ Edge case tests (0, max values, boundary conditions) ✓ Gas tests (no unexpected gas increases) ✓ Security-specific tests (reentrancy, overflow, etc.)
Review
✓ 2-3 internal code reviews completed ✓ All feedback addressed ✓ External audit scheduled and completed ✓ All audit findings fixed ✓ Audit re-review passes
Monitoring
✓ Monitoring system set up (Tenderly) ✓ Alerts configured ✓ Incident response plan drafted ✓ Team trained on response ✓ Pause mechanism tested
Documentation
✓ Architecture documented ✓ Assumptions documented ✓ Known limitations documented ✓ Deployment guide created ✓ Emergency procedures documented
Tags
