1.0 Fuzz Testing (Fuzzing)
many security vulnerabilities arise from unexpected inputs or edge cases that developers never thought to test
fuzz testing is a technique where random inputs are supplied to a program in an attempt to discover bugs, crashes or unexpected behaviour
invariant is a property that must always remain true regardless of user input, function call order, contract state, number of transactions
1.0.1 stateless fuzzing
each test starts from a fresh contract deployment
every run is isolated, each run is a fresh state
1.0.2 stateful fuzzing
stateful fuzzing does not rest the contract after every function call
current contract state carries forward
every action changes state for next action
used for simulating real world usage
1.1 ERC-20 Token
erc-20 is a smart contract that represents a fungible digital asset on Ethereum blockchain and follows a predefined set of rules as the erc-20 standard.
ERC-20 tokens are fungible, meaning every unit of token is identical and interchangeable with every other unit
erc-20 became foundation for fungible tokens on Ethereum because it provides a universal interface, with erc-20 one wallet can support thousands of different tokens, smart contracts can interact with tokens in a standardized way, devs can build reusable tools that work with any erc-20 token
1.2 ERC-721 (NFT) standard
NFT = non fungible token, unlike ERC-20 every NFT is different. these tokens are implemented as Solidity smart contracts, smart contract manages ownership, transfers, minting, burning, metadata, tokenids.
NFTs were created to solve problem of proving ownership of unique digital assets
before NFTs digital files could be copied infinitely, original ownership was difficult to verify, artists struggled to monetize digital creations
1.2.1 Storage
off chain storage: metadata is stored outside the blockchain, IPFS, a decentralizd file storage network
+ much cheaper + supports large media
- centralized ke jitnay issues
on chain storage: metadata and (sometimes artwork) stored directly on the blockchain
+ permenant + resistant to censorship + no dependence on external servers
- very expensive - limited by blockchain storage
1.3 Token ID
every NFT has its own unique identifier
Ethereum storage is extremely expensive, gas costs would become very high
the contract stores only a reference to the image
1.4 Token URI
reference is called the token URI, it points to NFTs metadata
When a wallet or marketplace displays the NFT, it:
1. Reads the Token URI from the contract.
2. Fetches the metadata.
3. Loads the image and attributes.
4. Displays the NFT to the user.
1.5 Memory Primer
constant variables do not occupy storage slots, immutable are assigned values in constructor call.
full dynamic arrays are not stored in memory, only the arrays length is stored, actual values are stored somewhere else, Solidity uses keccak245(slot) to determine where dynamic array elements begin
dicts values are hashed and stored at hashed locations.
local variable lifetime exists only during function execution
memory is a temporary storage used during function execution. commonly used for strings, dynamic arrays, structs
function getString() public pure returns (string memory) {
return "this is a string!";
}without specifying memory or storage, Solidity would not know where the data should live.
1.6 receiving ETH primer
Solidity smart contracts reject ETH by default.
To allow a contract to receive ETH, implement:receive() fallback()

1.7 ABI encoding in Solidity
abi.encode and abi.encodePacked are used to encode/concatenate data into binary format.abi.encode → returns binary encoding of provided argumentsabi.encodePacked → returns binary encoding of provided arguments in a compressed format
contract Encoding {
function combineStrings() public pure returns (string memory) {
return string(abi.encodePacked("Hi Mom! ", "Miss you."));
}
}
Hi Mom! Miss you.
// Both strings are converted into binary, The binary values are concatenated.abi.decode → used to decode previously encoded data
Since Solidity 0.8.12, string.concat() can also concatenate strings.
1.8 Compilation output
solc compiler generates two outputs, Solidity produces contract.abi, contract.bincontract.abi → describes how to interact with contractcontract.bin → binary representation of the contract, this is the actual code deployed to blockchain
The EVM executes bytecode as a sequence of opcodes.
tx = {
nonce: nonce,
gasPrice: 10000000000,
gasLimit: 1000000,
to: null,
value: 0,
data: "SMART CONTRACT BINARY GOES HERE",
chainId: 1337,
};during contract deployment the data field will contain contract initilization code,
during a function call, the data will contain the function to execute, the encoded arguments for that function
1.9 Sending encoded transactions
when we transfer tokens, Solidity compiler automatically converts these into low level call or staticcall operations behind the scenes. call() → used to ccall functions that change blockchain statestaticcall() →used to call view and pure functions
1.10 Proxy Pattern
smart contracts are immutable after deployment, bugs cannot be fixed directly, new features cannot be added to an already deployed contract, use proxy pattern, proxy allows contracts logic to be upgraded while preserving its state
upgrading process:
1. deploy a new implementation contract
2. update proxy to point to new implementation
3. users continue interacting with same proxy address
3. contract state remains unchanged because its stored in the proxy
delegatecall - executes code from another contract
//Normally,
A.call(B)
//Code runs in B, B's storage is modified
//...with
A.delegatecall(B)
// code from B runs, and A's storage is modified
// msg.sender remains the original caller.
// msg.value remains the original value sent.Note! the proxy and implementation contracts must have identical storage layouts.
if storage layouts differ, wrong storage slots may be overwritten, state corruption can occur. can lead to critical vulnerabilities.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// NOTE: Deploy this contract first
contract B {
// NOTE: storage layout must be the same as contract A
uint256 public num;
address public sender;
uint256 public value;
function setVars(uint256 _num) public payable {
num = _num;
sender = msg.sender;
value = msg.value;
}
}
contract A {
uint256 public num;
address public sender;
uint256 public value;
function setVars(address _contractB, uint256 _num) public payable {
// A's storage is set, B is not modified.
(bool success, ) = _contractB.delegatecall(
abi.encodeWithSignature("setVars(uint256)", _num)
);
require(success, "delegatecall failed");
}
}1.10.1 proxy contract
holds all contract storage, has the permenant contract address users interact with, forwards function calls to the implmenetation contract
1.10.2 Implementation contract
contains applications business logic, does not store the application state, can be replaced during upgrades
1.11 selfdestruct()
destroys a smart contract, before being destroyed, contract sends all ETH to a specified address
normally if a contract contract cannot receive ETH, sending ETH to it will fail, selfdestruct bypasses this restriction and forces ETH into the target contract. This can break protocols that rely on address(this).balance for their logic.
2.0 Smart contract Audit
smart contract audit/security review are interchangeable.
security review → time boxed, security focused review of a smart contract system.
auditors objectives are to find as many vulnerabilities as possible, help improve protocol’s security, recommend better coding practices
phases of a security review:
1a. scoping → define scope of review
1b. reconnaissance → understand codebase and protocol
1c. vulnerability identification → search for bugs and security issues
1d. reporting → prepare initial audit report
2a. fix issues → protocol team fixes the reported vulnerabilities
2b. add tests and verify the fixes
3a. reconnaissance → review updated code
3b. verify if issues have been properly fixed
3c. produce final mitigation report
2.1 Rekt Test (Wrecked test)
issa questionnaire used to evaluate whether a protocol is ready for security audit
encourages teams to think proactively about security
a few questions:
a. are all acctors and privileges documented
b. are external sevices, contracts/oracles documented?
c. is there a written and tested response plan
d. are the best ways to attack the system documented?
e. are employee identities and backgrounds verified?
f. is there a team member responsible for security?
g. are hardware security keys required for production systems
h. does key management require multiple people and physical steps?
i. are kye system invariants defined and tested on every commit
j. are automated security tools used to identify vulnerabilities?
k. does protocl undergo external audits
l. is there a vulnerability disclosure or bug bounty program
devs should be able to answer all of rekt test questions before requesting an audit
2.2 Formal verification
converting codebase into mathematical experssions and deploying proofs to authenticate that code does or doesnt do something specific. e.g. maniticore, certora, Z3
usually a successful exploit is a result of multiple failures, not just a missed vulnerability during the audit
3.0 Scoping
a client may initially provide only a etherscan link to a deployed contract. auditors should look if there is a deployment framework/test suite/good dev practices followed.
before starting the audit, check if the codebase is rekt ready.
if codebase isnt ready, dont audit it ccuz if the exploit shows up, you are blamed for it
once client provides codebase with source folder, deployment script, better project structure.
understand what the protocol does, what its intentions. collect information about lines of code/scope/complexity
obtain exact commit hash, github repo and contracts that are in scope
3.0.1 Stats
stats section of protocol provides information about codebase size, codebase complexity
nSLOC counts actual sourcce code in the project
CLOC counts source code lines, blank lines, comment lines
3.1 Tincho auditing method
focuses on understanding the protocol, systematically reviewing the code, thinking like an attacker, taking detailed notes throughout the review.
read all available documentations, understand protocol’s purpose, learn protocols terminology, understand expected behavior
constantly ask: how can i break this, what assumptions does this code makes, can those assumptions be voilated?
avoid losing the big picture, regularly step back and review the protocol as a whole
3.2 Solidity Metrics
use inheritence graph, shows relationships between contracts. helps understand contract hieracrchy
use a call graph to show which functions call other functions.
3.3 Invariants
condition that must always remain true
3.4 Reporting
Before submitting any audit finding, ask yourself:
Title: Does it clearly state the root cause and impact?
Description: Have I explained why the vulnerability exists?
Impact: Have I explained the real-world consequences?
Proof of Concept: Can someone else reproduce the issue?
Mitigation: Does my recommendation address the root cause rather than just the symptom?
3.5 Severity
depends on two things
impact = what happens if the bug is exploited, direct loss of funds/protocol becomes unstable/permanent corruption
likelihood = how easy it is to exploit
auditors focus on realistic threats rather than theoretical edge cases