Complete guide • Programming • Applications • Examples
Smart contracts are self-executing contracts with terms directly written into code. They automatically execute when predetermined conditions are met, eliminating the need for intermediaries and ensuring trustless, transparent transactions.
Key smart contract features:
Smart contracts power DeFi, NFTs, DAOs, and many other blockchain applications.
Smart contracts are computer programs that automatically execute, control, or document legally relevant events and actions according to the terms of a contract or agreement. They run on blockchain networks and execute when predetermined conditions are met.
Key Features: Automated execution, trustless operation, transparency, immutability, and decentralization.
Smart contracts work by following "if/when...then..." statements written into code. When predetermined conditions are met, the contract executes automatically. The blockchain network verifies the transaction and updates the ledger.
Process: Agreement terms coded → Conditions monitored → Automatic execution → Blockchain update.
\( \text{Smart Contract} = \text{Logic} + \text{State} + \text{Execution} \)
Smart contracts are written in specialized programming languages designed for blockchain environments. The most common is Solidity for Ethereum, but other languages like Vyper and Rust are also used.
Popular Languages: Solidity, Vyper, Rust, Move, Cairo.
Ethereum's primary language, similar to JavaScript. Most widely used for smart contract development.
Features: Object-oriented, statically typed, supports inheritance
Python-based language for Ethereum, emphasizing security and simplicity over performance.
Features: Security-focused, Python-like syntax
Used for Solana and other blockchains, known for memory safety and performance.
Features: Memory-safe, high-performance, concurrent
Smart contracts typically include: state variables, functions, events, modifiers, and inheritance structures. The contract lifecycle involves creation, deployment, execution, and interaction with other contracts.
Predetermined requirements that must be met for contract execution. Examples: payment received, time elapsed, specific data provided.
Verification: Checked against blockchain state
Functions executed when conditions are met. Examples: transfer funds, update records, trigger other contracts.
Execution: Automated and deterministic
Outcomes of contract execution. Examples: updated blockchain state, transferred assets, emitted events.
Recording: Permanent and immutable
Automated financial services without traditional intermediaries. Includes lending, borrowing, trading, and yield farming.
Examples: Uniswap, Aave, Compound, MakerDAO
Ownership of digital assets, in-game items, and play-to-earn mechanics. Players truly own their assets.
Examples: Axie Infinity, CryptoKitties, NBA Top Shot
Organizations governed by smart contracts and member voting, without traditional management structures.
Examples: MakerDAO, Uniswap DAO, Aave Grants
Verifiable credentials, digital identity, and transparent supply chain tracking with immutable records.
Examples: ENS, VeChain, Civic
What makes smart contracts "trustless"?
Smart contracts are "trustless" because they execute automatically based on predetermined conditions, eliminating the need to trust intermediaries or counterparties. The code enforces the agreement, not human trust.
The answer is B) No need to trust a third party for execution.
The "trustless" nature is a fundamental innovation of smart contracts. Traditional contracts rely on trust in institutions, lawyers, or courts to enforce agreements. Smart contracts replace trust with code and cryptography, creating verifiable and automatic execution.
Trustless: No need to trust third parties
Automated Execution: Code runs without human intervention
Self-Enforcing: Agreement enforced by code
• Code is law in smart contracts
• No human intervention needed
• Deterministic execution
• Think of code as law
• Verify contract code
• Understand the terms
• Confusing with traditional contracts
• Not understanding automation
• Ignoring code verification
Explain the main security risks associated with smart contracts and how they can be mitigated.
Main Security Risks:
• Reentrancy Attacks: Contract calls back into itself before updating state
• Integer Overflow/Underflow: Arithmetic errors causing unexpected behavior
• Access Control Issues: Unauthorized access to privileged functions
• Logic Errors: Flaws in contract logic leading to unintended behavior
Mitigation Strategies:
• Use established patterns like Checks-Effects-Interactions
• Employ SafeMath libraries for arithmetic operations
• Implement proper access controls with modifiers
• Conduct thorough testing and audits
• Use formal verification for critical contracts
Smart contract security is critical because bugs can lead to loss of funds and cannot be easily fixed after deployment. The immutable nature of blockchain means security must be built in from the start through careful design, testing, and auditing.
Reentrancy: Recursive contract calls during execution
Formal Verification: Mathematical proof of correctness
Immutable: Cannot be changed after deployment
• Test thoroughly before deployment
• Audit critical contracts
• Use established patterns
• Use OpenZeppelin libraries
• Follow security best practices
• Get professional audits
• Not testing edge cases
• Ignoring security audits
• Using untrusted libraries
You're building a decentralized lending smart contract where users can deposit ETH as collateral and borrow DAI tokens. Design the core functions and explain how you would handle liquidation when collateral value drops below the loan value.
Core Functions:
• depositCollateral(): Accept ETH deposits and mint loan tokens
• borrow(): Allow borrowing DAI up to collateralization ratio
• repay(): Repay borrowed amount plus interest
• liquidate(): Liquidate undercollateralized loans
Liquidation Mechanism:
• Monitor collateral-to-debt ratio in real-time
• When ratio falls below threshold (e.g., 150%), allow liquidation
• Liquidator repays debt, receives collateral at discount
• Protocol keeps liquidation penalty as fee
Security: Use Chainlink oracles for accurate pricing, implement circuit breakers.
This example demonstrates how smart contracts can recreate traditional financial services without intermediaries. The liquidation mechanism ensures protocol solvency by automatically enforcing collateral requirements, showcasing the power of programmable money.
Collateralization: Ratio of collateral to loan value
Liquidation: Forced sale of collateral
Oracle: Data feed for real-world information
• Maintain adequate collateralization
• Secure price feeds
• Implement liquidation incentives
• Use multiple oracles
• Conservative parameters
• Emergency functions
• Insufficient liquidation incentives
• Oracle manipulation
• No emergency controls
Design an NFT smart contract that allows artists to mint unique digital artworks with built-in royalty payments to the original creator. Explain how you would implement the royalty system and ensure it works across different marketplaces.
Contract Design:
• Inherit from ERC-721 standard for NFT compatibility
• Store creator address and royalty percentage for each token
• Implement royaltyInfo() function following EIP-2981
Royalty Implementation:
• Define royalty basis points (e.g., 500 = 5%) for each token
• When tokens are sold, calculate royalty amount from sale price
• Transfer royalty to original creator automatically
Marketplace Integration:
• Marketplaces query royaltyInfo() to determine payment amounts
• Standard ensures compatibility across platforms
• Creators receive ongoing revenue from secondary sales
Benefits: Artists earn passive income from resales, standardized across platforms.
This example shows how smart contracts can revolutionize creative industries by ensuring creators receive ongoing compensation. The programmable nature of royalties creates new economic models for digital art and content.
NFT: Non-fungible token representing unique assets
ERC-721: Standard for NFT implementation
EIP-2981: Standard for royalty payments
• Follow NFT standards
• Standardize royalty interfaces
• Consider gas costs
• Use established libraries
• Consider marketplace compatibility
• Optimize for gas efficiency
• Not following standards
• Complex royalty logic
• Ignoring marketplace integration
Which of the following is the most effective way to reduce gas costs in smart contracts?
Storing data off-chain when possible is the most effective gas optimization technique. Blockchain storage is expensive, so keeping large data sets off-chain and storing only references on-chain significantly reduces gas costs. Other techniques include using mappings efficiently, minimizing external calls, and optimizing loops.
The answer is B) Storing data off-chain when possible.
Gas optimization is crucial for making smart contracts economically viable. The blockchain is expensive for storage and computation, so efficient coding practices and architectural decisions (like storing data off-chain) are essential for cost-effective contracts.
Gas: Fee paid for blockchain computation
On-chain: Stored directly on blockchain
Off-chain: Stored externally, referenced on-chain
• Minimize storage operations
• Reduce external calls
• Optimize computational complexity
• Use efficient data structures
• Cache frequently accessed data
• Batch multiple operations
• Storing large data on-chain
• Unnecessary external calls
• Inefficient loops


Q: How do I test smart contracts before deploying them?
A: Test smart contracts using development frameworks like Hardhat, Truffle, or Foundry. Write unit tests for each function, test edge cases, and use testnets (Rinkeby, Ropsten) before mainnet deployment. Consider formal verification for critical contracts. Always conduct security audits before mainnet deployment.
Q: Can smart contracts be changed after they are deployed?
A: Generally, smart contracts cannot be changed after deployment due to blockchain immutability. However, some contracts are designed with upgradeability patterns using proxy contracts. This allows upgrading the logic while maintaining the same address. This approach requires careful security considerations and introduces trust assumptions.