1 of 54

push.org/bootcamp

2 of 54

Advanced Solidity:

Design, Optimization

And

Security

​

Session 3

push.org/bootcamp

3 of 54

Coming up…

3:30 PM

Solidity 101: Within the heart of Good Smart Contracts…

3:45 PM

Building and Testing a SC using Foundry

4:00 PM

Brief glance EVM and Opcodes

4:20 PM

Mental Models for Optimizing your Smart Contracts

4:50 PM

Break

5: 00 PM

Smart Contract Security & Bonus Tips for Smart Contract Devs

push.org/bootcamp

4 of 54

Stage 1:

Within the heart of a Good Smart Contract

push.org/bootcamp

5 of 54

Within the heart of Good Smart Contracts….

​

What does “Good Smart Contract” mean?

  • Readable, Understandable & Clear Code
  • Optimized for Low Gas Consumption
  • Highly Secure against vulnerabilities & attacks

push.org/bootcamp

6 of 54

Basics of a Good Smart Contract Codebase

​

What does a professional Solidity Code look like?

Step Zero: Be Specific

Smart Contracts are Immutable

​

Therefore, Be very specific.

​

Write SRS, before SOLIDITY

​

​

​

push.org/bootcamp

7 of 54

Solidity Contract Header

What does a professional Solidity Code look like?

  1. Solidity Compiler Version
  2. Solidity Pragma Statement:
  3. Locked
  4. Unlocked

3. Imports

​

​

​

push.org/bootcamp

8 of 54

Order of Layout

​

What does a professional Solidity Code look like?

  1. Type declarations
  2. State variables
  3. Events
  4. Errors
  5. Modifiers
  6. Functions

​

​

push.org/bootcamp

9 of 54

State Variables

​

What does a professional Solidity Code look like?

  • Use of consistent naming pattern
  • Use immutable/constant when necessary
  • Private isn’t Private
  • Use Solidity Keywords for time, units etc

​

​

push.org/bootcamp

10 of 54

Functions in Solidity

​

What does a Solidity Function look like?

push.org/bootcamp

11 of 54

Functions in Solidity

​

Anatomy of a Solidity Function

push.org/bootcamp

12 of 54

Order of Functions

​

How to order different types of function in a Smart Contract?

  • constructor
  • receive function (if exists)
  • fallback function (if exists)
  • external
  • public
  • internal
  • Private
  • Note: pure/view functions at least

​

push.org/bootcamp

13 of 54

Notes on Functions

​

Additional Notes on solidity functions

  • Function Keywords:
    • visibility > mutability > virtual > override > custom modifier
  • Use virtual only when necessary
  • Function naming is imperative.

​

push.org/bootcamp

14 of 54

Data Types in Solidity

​

Value Types

  • signed/unsigned Integers - uint or int
  • boolean - true or false
  • enums
  • bytes
  • addresses

​

Reference Types

  • arrays
  • strings
  • mappings
  • structs

​

push.org/bootcamp

15 of 54

Address Types in Solidity

​

Basic Details

  • Unique identifiers
  • Private and Secret - Controlled by a Secret Key
  • Two Different types of Addresses
    • Externally Owned Accounts, and
    • Contract Accounts
  • Stores balances, tokens, NFTS etc

​

​

​

​

Technical Details

  • these are 20 bytes long
  • Prefixed with 0x
  • Defined as:
    • address public owner = msg.sender;
  • Methods available for addresses:
    • address.balance
    • _address.transfer() and address.send()
    • address.call()

​

​

​

​

A (sort-of) unique data type that you might not have seen

push.org/bootcamp

16 of 54

Variable Types

​

State Variables

  • Values in State variables are stored permanently on Blockchain
  • Declared inside a contract but outside of Functions
  • Involves high gas consumption while reading from or writing to state variables.

​

​

​

​

​

push.org/bootcamp

17 of 54

Variable Types

​

Local Variables

  • Values in State variables are stored permanently on Blockchain
  • Declared inside a contract but outside of Functions
  • Comparatively cheaper to use than state variables

​

​

​

​

​

push.org/bootcamp

18 of 54

Variable Types

​

Global Variables

  • Special variables that exists in the Global scope.
  • Mainly provides information about the Blockchain or transactions
  • Examples:
    • msg.sender
    • msg.value
    • block.timestamp
    • block.number
    • block.chainId

​

​

​

​

​

push.org/bootcamp

19 of 54

Data Locations

​

What are events in Solidity?

  1. Storage
  2. Stores data on the chain in a permanently
  3. Contract’s state variables are stored in the storage location by default.
  4. Storage stores on blockchain itself, and is therefore the costliest data location.

​

​

​

​

​

push.org/bootcamp

20 of 54

Data Locations

​

What are events in Solidity?

2. Memory

  • Stores data temporarily in the contract
  • Usage: To store temporary data like local variables, return values etc.
  • Since data isn’t stored permanently, it is cheaper to use memory

​

​

​

​

​

​

push.org/bootcamp

21 of 54

Data Locations

​

What are events in Solidity?

3. Calldata

  • Similar to memory but used for Function inputs/argument
  • Calldata is the special data location that mainly contains function arguments.
  • Value of calldata variables are immutate and non-persistent.
  • Since they are immutable, it can save gas - cheaper than memory

​

​

​

​

​

​

push.org/bootcamp

22 of 54

Time to build a Smart Contract

push.org/bootcamp

23 of 54

Let’s Build a Contract

​

Time to build

What to build?

  1. A staking contract that allows staking an ERC20 Token
  2. It should allow staking, unstaking token
  3. It should also have reward mechanism

​

​

​

push.org/bootcamp

24 of 54

Let’s Build a Contract

​

Time to build

What to build?

  1. A staking contract that allows staking an ERC20 Token
  2. It should allow staking, unstaking token
  3. It should also have reward mechanism

​

Questions:

  1. Does it have any lock-up period?
  2. Can a user stake twice? , more…..

​

Step Zero: Write a SRS Doc first

​

push.org/bootcamp

25 of 54

Building a SRS Doc

Time to build

  1. Initialization Requirement: “Users must be able to initialize their staking profile.”
  2. Staking Tokens: “Users should be able to stake ERC20 tokens in the contract.”
  3. Lockup Period: “A 7-day lockup period must be enforced before users can unstake their tokens.”
  4. Unstaking Tokens: “Users should be able to unstake their tokens after the 7-day lockup period.”
  5. Fixed Reward: “Upon successful unstaking after the lockup period, users should receive a fixed reward of 100 tokens.”
  6. Reward Addition by Admin: “The admin should be able to add tokens to the reward pool.”

​

​

push.org/bootcamp

26 of 54

Events in Solidity

​

What are events in Solidity?

  • Events are basically signals that a smart contract can fire.
  • Notifies users/front-ends of an important on-chain actions.
  • Events are stored in the transaction logs on the blockchain.
  • Events aren’t readable by smart contracts. Contract simply emit events and forget them.

​

​

​

push.org/bootcamp

27 of 54

Error Handling

​

How are errors handled in solidity?

Error handling indicates exceptions that lead to States completely being reverted.

​

Solidity provides 3 main ways to handling errors:

  • require()
  • revert()
  • Custom Errors ( 0.8.4)
  • assert()

​

push.org/bootcamp

28 of 54

Error Handling

​

How are errors handled in solidity?

require statements

  • Defines the pre-requisite for a successful function execution
  • Also allows passing ERROR messages to indicate the occurrence of an error
  • Refunds remaining Gas

require(msg.sender == owner, "Only owner can call this function");

Mainly Used for:

  • Input Validations in functions
  • Validations of external contract’s responses.
  • Verifications of State changes before final execution of a functions

​

​

push.org/bootcamp

29 of 54

Error Handling

​

How are errors handled in solidity?

Custom Errors statements

  • Usage: Define reusable error messages.
  • More gas efficient
  • Uses less storage space for error messages
  • Refunds remaining Gas

​

push.org/bootcamp

30 of 54

Foundry Tests

Imperative to write tests in foundry

  1. Initial Set Up of a foundry test file
    1. Import forge-std: A collection of utilities, cheats & base contracts for testing
    2. Import your contracts to be tested
    3. Write setUp function.
  2. setUp function in foundry test file
    • Called before each test case is executed
    • Acts as a initializer function
    • Creates a consistent test environment

​

push.org/bootcamp

31 of 54

Foundry Tests

Verbosity of foundry forge test

Adjusting details of test output using verbosity params

  1. -v: Minimal output, only shows test summary.
  2. -vv: Provides a bit more detail, including which tests passed and failed.
  3. -vvv: Includes logs and traces for failing tests.
  4. -vvvv: Maximum verbosity, shows detailed traces for all tests, including execution steps, storage changes, and more.

​

push.org/bootcamp

32 of 54

Foundry Tests

Helper functions for foundry tests

Assertions

    • assertEq
    • assertTrue
    • assertFalse
    • assertGt
    • assertLt

​

​

Pranks ( adjusting CALLER)

    • vm.prank()
    • vm.startPrank()
    • vm.stoapPrank()

​

​

​

Time ( adjusting timestamp)

    • vm.warp(): Sets timestamp to specific value
    • vm.roll : sets block number to specific value
    • skip(): skips time based on provided value
    • rewind(): rewinds time based on value

​

​

​

push.org/bootcamp

33 of 54

Stage 2:

EVM Opcodes &

Optimization of Gas

push.org/bootcamp

34 of 54

EVM and Opcodes

Tricks to optimize gas in solidity

  • Designed to process smart contract transactions
  • Defines the rules for State Changes
  • Not bound to a single OS or location
  • Determines the overall state of the Ethereum blockchain.

push.org/bootcamp

35 of 54

Journey of a Smart Contract

push.org/bootcamp

36 of 54

Bytecodes

  • Low-Level Language that Solidity gets translated to

​

  • Made of opcodes ( machine codes) which are instructions on how a smart contract should behave

​

  • EVM only understands bytecode

push.org/bootcamp

37 of 54

Opcodes

push.org/bootcamp

38 of 54

Optimizing Gas

Basic Rule of thumb when saving gas

  1. Lesser Opcodes > Lesser Instructions > Lesser gas
  2. Avoid/Minimize storage read/writes
  3. Redundant logic should be avoided
  4. Loops should be carefully designed
  5. Fixed Size variables are always cheaper than dynamic ones

push.org/bootcamp

39 of 54

Optimizing Gas

Tricks to optimize gas in solidity

​

Mapping vs Array

​

push.org/bootcamp

40 of 54

Optimizing Gas

Tricks to optimize gas in solidity

​

Arrangement of IF-ELSE Conditional Blocks

(Short-Circuit Evaluation)

​

push.org/bootcamp

41 of 54

Optimizing Gas

Tricks to optimize gas in solidity

​

Avoiding Storage Reads

​

push.org/bootcamp

42 of 54

Optimizing Gas

Tricks to optimize gas in solidity

​

Avoiding Storage Reads in Loops

​

push.org/bootcamp

43 of 54

Stage 3:

Smart Contract Security & Audits

push.org/bootcamp

44 of 54

Limitations of Smart Contracts

​

  • SECURITY
  • Immutability in Smart Contracts
  • Dependency on the Underlying Chain
  • Nascent Stages
  • Inability to interact with the Real World Data

push.org/bootcamp

45 of 54

Introduction to Smart Contract Security

Why is it important ?

push.org/bootcamp

46 of 54

Possible Solutions

​

Following Best Security Practices while Development of Smart Contracts

​

Performing extensive Smart Contract Security Audits

​

push.org/bootcamp

47 of 54

Best Security Practices

​

  • Beware of External Calls. Use Re-entrancy protections
  • Follow CEI Pattern
  • Input Validations checks are imperative
  • Access Control should be rechecked
  • Avoid Potential Asset-Locking Scenario
  • Extensive Test Coverage
  • Security Audits

push.org/bootcamp

48 of 54

Brief glance at Smart Contract Audits

​

Smart contract audits usually have 5 Imperative Steps

    • Audit Scope and Documentation Gathering
    • Evaluation of Test Cases
    • Automated Testing
    • Manual Code Review
    • Adequate Documentation of Reports

​

​

push.org/bootcamp

49 of 54

Bonus Section:

​

Recommendations, Advices and Tips

push.org/bootcamp

50 of 54

With Great Power, Comes Great Responsibility

​

push.org/bootcamp

51 of 54

Tips for Solidity Developers

  1. Experiment more while learning Solidity
  2. Provide Value to Development Community ( however, you can ).
  3. Security of Smart Contract is the Developer’s Job too ( Not just the auditors )
  4. Find the right balance between Work & Noise
  5. Writing Solidity is easy….Writing Efficient & Secure Solidity is HARD.

Work on the HARD Problem

push.org/bootcamp

52 of 54

Raising the Bar - As a SC Dev

​

Imperative ERC Standards

  • ERC-20 - Token contract for fungible assets.
  • ERC-721 - Token standard for non-fungible assets.
  • ERC-1155 - Token standard for semi-fungible tokens
  • ERC-918 - Mineable Token Standard.

ERC’s Upgradeable Proxy Standards

  • ERC1967Proxy - Transparent Upgradeable Proxy
  • ERC1822Proxy - Universal Upgradeable Proxy Standard

​

Crucial DEFI Terms & Projects

  • Lending & Borrowing in Defi
  • Flash Loans
  • On-Chain Governance mechanisms
  • Staking
  • Tokenomics

Important Projects

  • Uniswap - Decentralized Crypto Exchange
  • Aave & Compound
  • ENS
  • L2 Solutions like Polygon etc

​

​

​

push.org/bootcamp

53 of 54

Raising the Bar - As a SC Security Researcher

​

What to Learn - Where to learn

Play, Participate & Learn

  • Ethernaut
  • Damn Vulnerable Defi
  • Contests - Code4ena, Immunefi, etc.

​

Security Tools

  • Foundry
  • Slither - for automated testing of contracts
  • Echindna - Fuzz Testing tool
  • Mythril - Security Analysis Tools
  • Surya - Contract Visualization Tool
  • Tenderly - Real-Time Smart Contract Monitoring & Debugging Tool

​

​

​

push.org/bootcamp

54 of 54

push.org/bootcamp