Skip to content

the-vegetarian-vampire/Smart-Contract-Resources

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Solidity | DeFi | and Blockchain Resources

Resources for Solidity, Defi, and blockchain technologies.
🔖 = bookmark

🔖 Remix - for testing and deploying smart contracts
Ethereum unit converter

🔖 Solidity Documentation and Cheatsheet
🔖 Solidity Best practices
🔖 Solidity By example

Ethereum Documentation
ERC20 Docs via OpenZeppelin library

🔖 Solidity Contract Layout
🔖 Awesome Foundry
🔖 RareSkills Git

Tutorial Resources

1. Patrick Collins Courses:

2. Smart Contract Programmer:

3. Guardian Audits - Advanced Web3 Security Course

🔖 Secureum Mind Map
🔖 Teachyourselfcrypto.com (great links to DeFi)


General Blockchain Knowledge

Blockchain Developer Roadmap - more detailed (tons on Twitter)
Blockchain 101 (video)
How Bitcoin Works (video)
Whiteboard Crypto
Finematics
Why Hexadecimal and 256 Bit Computing


News

🔖 Rekt
Web3isgoinggreat


Youtube Resources

🔖 Andy Li - interviews
Johnny Time - interviews
OpenSense - Free Ethereum Security

Blockchain and Money (MIT Fall 2018) ...taught by Gary Gensler...

Campbell Harvey (Prof. Duke) author of DeFi and the Future of Finance
Berkeley -- Berkeley DeFi class (for the AMA’s) and subscribe to RDI
Ethereum Engineering Group (Peter Robinson - Head of Blockchain at Immutable X)


Reading

Mastering Ethereum - essential guide both general and technical (FREE)
Mastering Bitcoin - bit more technical (and perhaps duller) than Mastering Ethereum (FREE)
Deconstructing Solidity - breaks down Solidity to its byte code

The Infinite Machine - historical context how Ethereum started, think The Social Network meets Silicon Valley
The Art of Invisibility - (David M) about online anonymity
Tracers in the Dark by Andy Greenberg - covers transparency of Bitcoin and cybercrime - 10/10 recommend!

How to DeFi: Beginner and/or Advanced
DeFi and the Future of Finance - particularly Chapter 6: deep dive

Matt Levine: Bloomberg Opinion Columnist per Dan Robinson


Podcasts

Bankless
Unchained
Scraping Bits


Interactive (CTF, Capture the Flags)

🔖 Ethernaut Challenges via OpenZeppelin

🔖 Damn Vulnerable DeFi

Paradigm CTFs
Crypto Zombies (old)
Speed Run Ethereum via Austin Griffith
JumpCryptoHQ exercises


Interviews and Questions


Opcodes | Gas Optimization | Storage and Memory

🔖 Layout in memory
🔖 Solidity Optimizer
🔖 Opcodes Updated vs. - Old Git and video
🔖 Ethereum Signature Database or Open Chain
🔖 EVM Storage

Solady and Solmate

Patrick Collins walkthrough - FunWithStorage contract
Brief storage video
Storage vs Memory
Foundry Debugger 7:01:10
Ethernaut Lvl 19 MagicNumber
Gas-optimization course by Jeffrey Scholz Medium and RareSkills Git
Harrison on Twitter

Play with opcodes

Block limit ~30 million gas. New block every 15 seconds; memory explosion due to quadratic growth
BaseFee - is burned; determined by network; Solidity can access via block.basefee
Max Fee - most willing to pay; upper bound of gas price
Max priority fee - most you are willing to give to the miner
Priority fee - most willing to give to miner out of what’s left when max fee is subtracted from basefee, aka miner tip
cold access vs warm access - cold access the first time you read a storage slot, warm access when you read it again

type address bool uint8 uint16 uint32 uint64 uint128 uint256
bytes 20 1 1 2 4 8 16 32

0x40 - the free memory pointer; a "pointer" is an address within memory and the free memory pointer is the address pointing to the start of unallocated, free memory. 
0x80 - action begins
scratch space slots - [0x00-0x-20), [0x20-0x40)
offset - determines where within the 256-bit slot a particular piece of data begins; eg. if you have two uint128 variables (128 bits in size), the first will start at an offset of 0 and the second will start at an offset of 128.

bit masking - defines which bits you want to keep, and which bits you want to clear
short circuiting — order matters, cheaper operation first for performance
bit shifting - using << (left shift for multiplication) and >> (right shift for division)

A transaction costs a base of 21,000 gas; each computational step costs ~2-10 gas (usually); each byte of data costs 16 gas (4 if zero byte); editing a storage slot costs 5,000 gas (20,000 if not yet filled)

  • check != 0 rather than > because <= and >= compile to multiple opcodes (LT/GT followed by ISZERO for inversion), whereas strict inequalities (< and >) only need a single opcode (LT or GT).

  • struct packing - using a smaller-sized uint when possible will allow Solidity to pack these variables together

  • custom errors - more gas efficient, denoted with __ two underscores: error FundMe__NotOwner();

    • Custom Error vs. Require Encoding: both logged but have different topic signatures at the EVM level. Custom errors use own error signature, while requires use a Keccak-256 hash of the error string.
  • constant - naming convention ALL_CAPS; more gas efficient

  • immutable - set inside the constructor but cannot be modified after, more gas efficient: i_owner, i meaning immutable

  • in testing it's common to prepend storage variables with s_

  • unchecked arithmetic is ok if you know overflowing uint256 is near impossible

  • function names and optimized

  • ++i vs i++

  • Hardhat gas reporter and Foundry Snapshot

  • 5 places to save gas

    1. On deployment
    2. During computation
    3. Transaction data
    4. Memory
    5. Storage

Set optimizer as high as possible until improvement stops; Uniswap optimizer


Hacks and Security

🔖 Vulnerabilities types
Defillama Hacks

2022 Auditor Rewind by Patrickd (Secureum)
Top 10 Vulnerabilities In Web3
Attacks via Consensys Best Practices

  • Access Control

  • Reentrancy Attacks - relies on a certain order of operations; a reentrant procedure can be interrupted in the middle of its execution. Following the interruption, the procedure can be called again (“reentered”) before its previous invocations complete execution; exploits “fallback”

    • single-function
    • cross-function
    • cross-contract: swaps; creator of swap enters into manager contract getting both end of swaps
    • cross-chain
    • read-Only - a contract is re-entered during a call, but the reentrant call only reads data and doesn't modify state. Even if no state changes, it can still be a vulnerability depending on how the read data is used afterward.
  • Front Running: batch overfow - gas price pumping - prioritized mining

  • Flash loans - pump and arbitrage attack

  • Double spending - 51% is one of the most commonly cited attacks

  • Denial of service (DoS; DDoS attack)

  • Oracle Manipulation - Awesome-oracle-manipulation

  • Replay attack - a replay of a transaction primarily taken place while a hard fork is being implemented; a delay or intercept data transmission that occurs over a network. This information can then be processed and repeated numerous times to effectively duplicate transactions

Quick vulnerabilities walkthrough
DeFiHackLabs - to produce DeFi hack incidents using Foundry.
DeFiVulnLabs -learn common smart contract vulnerabilities using Foundry.

Known Exploiter addresses:


Audits

What is an audit? - security focused code review; it is a best effort endeavor, not a guarantee
Audit Techniques & Tools 101 by Secureum
What are the Actual Flaws in Important Smart Contracts
Cantina

🔖 Weird ERC20
🔖 The Solcurity Standard audit checklist

🔖 Daily Warden - active and upcoming security contests

Reports

  1. solidity/evm oriented bugs, this include bugs based on compiler version or certain evm specific bugs
  2. Logical bugs, this is arguably the biggest surface for attacks as it can be very project-specific
  3. Ecosystem oriented bugs, includes projects explicit and implicit interaction with whole blockchain: frontrunning/sandwiching, oracle manipulations, incorrect integrations, flashloan attacks, all go here

Build a racing bot via 4naly3er - open source static analyzer to build on top of

Most auditor discussions are on Twitter.

Simple-security-toolkit
Auditing heuristics

  1. Find a project, search for bugs
  2. Find a bug, search for projects
  3. Be fast with new updates
  4. Know tools

Typical Risk classification:

Severity level Impact: High Impact: Medium Impact: Low
Likelihood: high Critical High Medium
Likelihood: medium High Medium Low
Likelihood: low Medium Low Low

High - leads to a loss of significant portion (>10%) of assets in protocol, harms a majority of users.
Medium - global losses <10% or losses to only a subset of users, but still unacceptable.

  • High and Medium - severity issues ("HM issues”)

Low - losses will be annoying but bearable--applies to things like griefing attacks that can be easily repaired or even gas inefficiencies.
Informational - findings to improve efficiency
Gas efficiencies - findings to improve efficiency
Quality Assurance (QA) - ensure the functionality, security, and efficiency of the smart contract code.


Testing

Fuzzing

Fuzzing - to identify fuzzable functions to successfully fuzz a target, one must comprehend how it functions, establish a basic threat model and decide how to test its security.
- stateless fuzzing where the state of the previous run is discarded for every new run
- stateful fuzzing fuzzing where final state of previous run is the starting state of the next run

In 𝗳𝗼𝘂𝗻𝗱𝗿𝘆.𝘁𝗼𝗺𝗹 and add: 𝙫𝙞𝙖_𝙞𝙧 = 𝙛𝙖𝙡𝙨𝙚 to opt-out of Solidity's IR compilation.
Cloc - will count lines of code: once installed: cloc .

Exploiting Precision Loss via Fuzz Testing Article

Invariant Testing

  1. Function Level Invariant
    • Doesn't rely on system OR could be stateless
    • Can be tested in isolation: Associative property of addition OR depositing tokens in a contract
  2. Syetem Level Invariant
    • Relies on deployment of a large part or entire system
    • Usually stateful: User's balance < total supply OR yield is monotonically increasing

Formal Verifcation - proving or disproving the validity of a system using a mathematical model

  • symbolic execution - explore different execution paths
  • solc --model-checker-engine chc --model-checker-targets overflow contract.sol
  • smtChecker - built into Solidity

CEI - Checks Effects Interactions Arrange Act and Assert

Test types: 28:43 - Unit//Integration//Forked//Staging
- Using modifiers 1:21:05

--no-commit flag tool will simulate the transaction without committing any changes to the blockchain. This can be useful for testing how a contract will behave when certain functions are called, without having to spend gas to actually perform the transaction on the network.

mutation testing is a type of software testing where small changes (mutations) are deliberately introduced into the source code at a single point in time. The purpose is to validate the quality of the existing test cases, ensuring that they are robust enough to detect the changes. Changes that result in test failures indicate adequate test coverage, while changes that do not result in test failures indicate gaps in test coverage. Although mutation testing is a slow process, it allows auditors to focus their review on areas of the codebase that are most likely to contain latent bugs, and it allows developers to identify and add missing tests. See Necessist

Trail of Bits Automated Testing
Echidna uses more advanced techniques like generating random transactions with random inputs and also keeps track of those transactions to achieve high coverage. On the other hand, Foundry focuses on generating random inputs for your test functions and has support for excluding certain values.


Bug Bounty


Defi

🔖 Layer2 Beat
🔖 Defi Llama

Eigenphi - tracking data
DeFi vs TradeFi
Three-part article on Medium:

Teach Yourself Crypto good links; also Khan Acad.

Exchanges Video Documentaion Supported Assets LP Token Details
Uniswap video docs ETH & ERC20 Yes (for bookeeping Auto router or client side router//Trading fees 0.3%
Curve video docs
Sushiswap video docs
Balancer video docs Yes (functional ERC Token) weighted math; allows own ratios: liquidity bootstrapping pool (LBP); up to 8 assets
PancakeSwap video docs offers limit orders

Lenders Video Documentaion Details
Aave video docs Finnish for ghost, alludes to anonymity of transactions; Aave Tesnet
Compound video docs

Dex Aggregators - a service that brings together liquidity from different decentralized exchanges and market makers, helping users find the best price for a given trade

Derivatives exchange

Lido - staking
Bancor

APY - annual percentage yield
LTV - Loan To Value
LP - liquidty providers
LSTs - liquid staking tokens
LSDs - liquid staking derivatives
PnL - profit and loss

order book model - an electronic list of buy and sell orders for a specific security or financial instrument organized by price level; lists the number of shares being bid on or offered at each price point, or market depth

relayer - a participant or node that facilitates off-chain matching of orders and assists with on-chain settlement, play a crucial role in decentralized exchange (DEX) protocols and Layer 2 scaling solutions; off-chain order books where they collect and match buy and sell orders from users. By keeping the order book off-chain, relayers can reduce the amount of data that needs to be stored on the blockchain, thereby lowering costs and increasing efficiency; submitting the matched orders to a smart contract that completes the trade on the blockchain itself; enhance liquidity and maybe some compliance with regulatory requirements.

liquidity threshold - minimum amount of liquidity needed for market/protocol to function efficiently and avoid excessive price slippage


  • All protocols define their thresholds as some function of collateral:debt (be it a ratio or a difference)
  • All protocols leave some room for governance to decide the value of per collateral risk parameter in response to changes in market conditions, as some assets are more volatile than others.
  • All protocols denominate their collateral and debt prices using an oracle, in a widely accepted currency (e.g., ETH, USD, DAI).

bonding curve - a mathematical curve that defines the relationship between the price and the supply of tokens. Often used in automated market makers.

Constant product automated makes maker (CPMMs) are based on the function x*y=k which establishes a range of prices for two tokens according to the available quantities (liquidity) of each token. When the supply of token X increases, the token supply of Y must decrease, and vice-versa, to maintain the constant product K.

kink parameter - the point in the interest rate model of Compound Finance where the interest rate stops increasing linearly and starts increasing polynomially.

Collateralized Debt Position CDP - the unit of accounting used to track a specific borrowed debt amount, the respective collateral that backs it, as well as the ratio between the value of these two assets, known as the Individual Collateral Ratio (ICR).

Slippage Attacks
Build a liquidation bot (docs)/video
Block stuffing (video) and finding
Aave decoupling logic from state

DeFi Reports

Toxic Liquidation Spirals
Gauntlet’s Aave Market Risk Assessment
Uniswap V3 TWAP Oracle Risk
yAudit Trade Review


Maximal extractable value: as a pending transaction sits in a mempool, miners and validators have found ways to profit from them by including, excluding or reordering transactions in a block.

  1. Simple MEV bot
  2. Jared from Subway’s bot

Flashbots.net
Solid Quant Articles

Flashbots Searcher - repository contains a simple Flashbots "searcher" for submitting a transaction from an executor account, but paying for the transaction from a sponsor account.

Uncle-block Attack - miners can deliberately exclude certain transactions to later include them in an uncle block, profiting from MEV without executing the transactions.

Geth - official Go implementation of Ethereum protocol; one of many Ethereum clients available, popular and widely used
Lighthouse - one of several Ethereum 2.0 clients being developed to support the new Eth2 protocol. Other Eth2 clients include Nimbus, Teku, and Prysm.


Stablecoins

Investopedia and Whiteboard Crypto
Types

  1. Fiat based
  2. Crypto based
  3. Algorithmic

soft peg - value not strictly fixed but is instead kept within a certain range relative to another asset.

Dai - MakerDAO
Frax

Stablecoin Trilemma: scalable, decentralized, stable.

Rebase — adding tokens
Debase — removing tokens

seigniorage - Revenue or a profit taken from the minting of coins; the difference between the face value of money, such as a $10 bill or a quarter coin, and the cost to produce it. In other words, the cost of producing a currency within a given economy or country is lower than the actual exchange value, which generally accrues to governments that mint the money.

evergreen - incremental addition of money into a business by investors; the company receives capital on an established schedule or as the need for funds arises. video

Spot price - the current price in the marketplace at which a given asset—such as a security, commodity, or currency—can be bought or sold for immediate delivery

Spot Price Manipulation - A smart contract needs to determine the price of an asset, e.g., when a user deposits ETH into its system. To achieve this price discovery, the protocol consults its respective Uniswap pool as a source. Exploiting this behavior, an attacker can take out a flash loan to drain one side of the Uniswap pool. Due to the lack of data source diversity, the protocol's internal price is directly manipulated, e.g., to 100 times the original value. The attacker can now perform an action to capture this additional value. For example, an arbitrage trade on top of the newly created price difference or an advantageous position in the system can be gained.


DeFi Wallets to track (TODO add more)


Central Banking Reading

Susanne Trimbath - Naked, Short and Greedy: Wall Street's Failure to Deliver
Michael Lewis - Flash Boys and The Big Short
Nomi Prins - Collusion: How Central Bankers Rigged the World


🔖 Tools

Metadock - extends Etherscan; "Proxy Upgrade Log"
Visualizer tool


Wallets

Rabby
Metamask
Loopring
Ledger


Teams to Connect With


Jobs


Abstracts: In Depth Understanding

Bitcoin whitepaper
Ethereum whitepaper (periodically updated)
Uniswap V3 whitepaper

Merkle Trees

Improving the Efficiency and Reliability of Digital Time-Stamping
Secure Names for Bit-Strings
Anonymous Payments Lecture

Academic Smart_Contract_Papers

More Resources from Patrick Collins


Tokens

Ethereum Request for Comment (ERC)

  • ERC-20 - for fungible assets.
  • ERC-721 - for non-fungible assets.
  • ERC-1155 - Multi Token Standard to to create fungibility-agnostic and gas-efficient token contract (gaming, batch minting, batch balance; batch transfer, batch approve) video
  • ERC-4626 - to optimize and unify the technical parameters of yield-bearing vaults
  • ERC-3156 - flash Loans
  • ERC-918 - Mineable Token Standard.
  • ERC-165 - standard method to publish and detect what interfaces a smart contract implements.
  • ERC-725 - interface for a simple proxy account.
  • ERC-173 - interface for ownership of contracts.
  • ERC-2981 - to retrieve royalty payment information across all NFT marketplaces and ecosystem participants
  • ERC-1167 - Minimal Proxy Contract to simply and cheaply clone contract functionality in an immutable way

NFT's and Atomic NFT's lecture with Ari Juels of whom with Sergey Nazarov co-authored a white paper introducing the Chainlink protocol.


Dictionary of Key Terms (Solidity)

Broader Crypto dictionary of terms or General

Aave - decentralised non-custodial liquidity market protocol where users can participate as suppliers or borrowers. Suppliers provide liquidity to the market to earn a passive income, while borrowers are able to borrow in an overcollateralised (perpetually) or undercollateralised (one-block liquidity) fashion; Stani Kulechov interview by Haseeb Qureshi -- Aave website

ABI - application binary interface specifies set of functions that can be accessed outside of smart contract; similar to a JSON; Abi.encodePacked - breaks down, via cheatsheet; Abi.decode; Great Patrick Collins section 22:16:31 and ABI encoding and difference between encoding

address - (Ethereum; other blockchains will be different) 42-character hexadecimal address derived from the last 20 bytes of the public key controlling the account with 0x appended in front 0x0cE446255506E92DF41614C46F1d6df9Cc969183

airdrop - involve blockchain-based projects and developers sending out free tokens to members of their communities as part of a broader marketing initiative.

Alpha - in finance it refers to excess return of an investment relative to the return of a benchmark index

AMM - Automated Market Maker; underlying protocol that powers all decentralized exchanges (DEXs), DEXs help users exchange cryptocurrencies by connecting users directly, without an intermediary; autonomous trading mechanisms that eliminate the need for centralized exchanges; drawback: susceptible to front running because of publicity in mempool

Application-specific integrated circuit or ASIC - The most powerful computer has the greatest chance of solving the puzzle, and so ASIC mining was created to maximize the possibility of mining; see also GPU

arrays - fixed [2] length of 2 elements and dynamic [] arrays with no fixed size; can also create an array of structs or 2D array

assertEQ - Assert a is equal to b

atomic swap - an exchange of cryptocurrencies from separate blockchains; the term "atomic state" in which a state has no substates; it either happens or it doesn't—there is no other alternative.

Beacon Chain - introduced proof-of-stake to the Ethereum ecosystem; was a separate chain from the original Ethereum Mainnet, running side-by-side that merged with the original Ethereum proof-of-work chain in September 2022; withdrawals

Beacon in Proxies - a beacon is a contract that provides the implementation address for proxies, allowing multiple proxies to upgrade their logic by just updating the beacon.

Black Thursday article - Thursday March 12th, 2020: cryptocurrency markets suddenly collapsed (in tandem with traditional markets), with bitcoin prices getting halved in less than a day.

blob - binary large object is a collection of data of an arbitrary size. Blobs do not have to follow a given format or have any metadata associated with them. They are a series of bytes, with each byte made up of 8 bits (a 1 or a 0, hence the "binary" descriptor). Any type of data can go in a blob; efficient and cheap transaction.

block.timestamp - convert a uint of the number of seconds in that length of time. So 1 minutes is 60, 1 hours is 3600 (60 seconds x 60 minutes), 1 days is 86400 (24 hours x 60 minutes x 60 seconds), find on cheatsheet

bridges - a blockchain bridge: and Youtube connects two blockchain ecosystems. Bridges facilitate communication between blockchains through the transfer of information and assets.

Byzantine fault or Byzantine generals problem - a condition of a computer system, particularly distributed computing systems, where components may fail and there is imperfect information on whether a component has failed; thus the reason for Proof of Work

CFMM - Constant Function Market Makers: article

clustering - tracing bitcoin via blockchain analysis; tracing Bitcoin user wallets by tracking wallet “change” creation; using tags; peel chains How to Peel a Million: Validating and Expanding Bitcoin Clusters Sarah Meiklejohn and team; also A Fistful of Bitcoins: Characterizing Payments Among Men with No Names

codecopy - copying code from one place to another is handled by the opcode codecopy, see article

Compound - a DeFi lending protocol that allows users to earn interest on their cryptocurrencies by depositing them into one of several pools

coinbase transaction - the first transaction in a block. Miners use it to collect the block reward, and any additional transaction fees.

commit-reveal scheme - two-step process where users first commit to a choice without revealing it. Later, they reveal their choice. This prevents others from seeing the original choice until the reveal stage. Used for voting, random number generation, etc.
- Rock-Paper-Scissors Game Design: Use a commit-reveal scheme. Players first commit (send hash of their choice + secret) and then reveal in the next step.

constant - naming convention ALL_CAPS; more gas efficient

constructor - called once when contract is deployed

creation code - only executed by the EVM once during the transaction that creates the contract. gets executed in a transaction, which returns a copy of the runtime code, which is the actual code of the contract. The contract’s constructor is part of the creation code; it will not be present in the contract’s code once it is deployed.

custom errors - declared at top, more gas efficient

DAI - stablecoin on the Ethereum blockchain whose value is pegged to $US

dark forest - “all people with nodes on major blockchains grinding on mempool transactions” - 9:40 Andrew Miller AMA and later mentions David Chaum Dan Robinson’s blog post

data Locations - Storage, Memory and Calldata

  1. storage - variable is a state variable (store on blockchain)
  2. memory - variable is in memory and it exists while a function is being called
  3. calldata - special data location that contains function arguments: decoding calldata - Cost for setting a storage slot from zero to non-zero (higher gas cost).
    • Cost for modifying a storage slot that is already non-zero (medium gas cost).

delegatcall - identical to a message call apart from the fact that the code at the target address is executed in the context; a contract can dynamically load code from a different address at runtime. Storage, current address and balance still refer to the calling contract, only the code is taken from the called address. Pattick Collins explanation 1:05:07:37; shorter video

describe () - function in Jasmine framework used for testing

deterministic algorithm - an algorithm that, given a particular input, will always produce the same output, with the underlying machine always passing through the same sequence of states

dutch auction - a descending price auction; an auctioneer starts with a very high price, incrementally lowering the price until someone places a bid

elliptic curve - elliptic curve cryptography with fastecdsa library; also OZ's ECDSA - Elliptic Curve Digital Signature Algorithm (ECDSA) operations used to verify a message was signed by the holder of the private keys of a given address.

enums - useful to model choice and keep track of state/can be declared outside of a contract

ENS - Ethereum Name Service - distributed, open, and extensible naming system based on the Ethereum blockchain; documents and video

EIP - (Ethereum Improvement Proposal) a formal proposal to alter some element of the Ethereum network

EOA - Externally Owned Account; in general, there are two types of accounts: externally owned accounts, controlled by private keys, and contract accounts, controlled by their contract code

events - allow logging to the Ethereum blockchain; Use cases for events are: Listening for events and updating user interface; cheap form of storage - Anonymous Solidity Event - does not store its signature in the topics list of the log. Instead, only the arguments are stored.

EVM - Ethereum is a stack based architecture, single threaded.

fallback - special function executed either when a function that does not exist is called or Ether is sent directly to a contract but receive() does not exist or msg.data is not empty; fallback has a 2300 gas limit when called by transfer or send

flashbots - independent project which extends execution clients with a service allowing searchers to submit MEV transactions to validators without revealing them to the public mempool; prevents transactions from being frontrun by generalized frontrunners; video

flash loan - a smart contract transaction in which a lender smart contract lends assets to a borrower smart contract with the condition that the assets are returned, plus an optional fee, before the end of the transaction. This ERC specifies interfaces for lenders to accept flash loan requests, and for borrowers to take temporary control of the transaction within the lender execution. The process for the safe execution of flash loans is also specified.

flash-swap - all trades must occur during single transaction: opportunity for arbitragers

floating point arithmetic - Solidity doesn't support floating point arithmetic natively due to the deterministic nature of the Ethereum Virtual Machine (EVM). Floating point operations can lead to imprecise calculations, which are not suitable for financial operations on a blockchain where exactness is paramount. However, developers can use fixed-point arithmetic libraries to achieve decimal-like precision.

flooding - routing

fork - investopedia "To fork or not to fork? - a radical change to a network's protocol that makes previously invalid blocks and transactions valid, or vice-versa. A hard fork requires all nodes or users to upgrade to the latest version of the protocol software; twitter status

function selector - first 4 bytes of the function signature: ex: 0xa9059cbb; excellent Patrick Collins section 22:46:43; shorter video; there can be function selector clashes
function signature - string that defines function name & parameters: ex: “transfer(address, uint256)”

function modifiers

  • public makes the function callable from any contract. If no visibility is specified for a function, it defaults to public.
  • external makes the function callable only from other contracts. These functions are often used for interactions between contracts. Note that they cannot be called internally, i.e., from within the same contract.
  • private makes the function callable only from within the contract where it is defined.
  • internal makes the function callable only from within the contract where it is defined, or from contracts that derive from it (i.e., contracts that inherit from it).
  • view used for functions that do not alter the state of the contract (i.e., they don't change any state variables).
  • pure used for functions that not only do not alter the state of the contract, but also do not access any data in the contract. These functions solely operate on their input parameters.
  • payable allows a function to receive Ether together with a call. If a function is not marked payable, it will reject any Ether sent to it.
  • Public state variables automatically generate getter functions.

fuzzing - or fuzz testing involves providing invalid, unexpected, or random data as inputs in an attempt to break/crash the system

gas - transactions with higher gas price have higher priority to be included in a block;

genesis block- the first block mined on a blockchain

Graph, The - Google for the blockchain; querying and indexing the blockchain

griefing - malicious/trollish behavior where an actor intentionally disrupts or harms the user experience without benefit to themselves

hashcash - a proof-of-work system invented by Adam Back in 1997 as a way to prevent email spam precursor to Bitcoin

Hashed Timelock Contract or (HTLC) reduces counterparty risk by creating a time-based escrow that requires a cryptographic passphrase for unlocking via investopedia

heartbeat, oracle click show more details - refers to an oracle providing regular updates at fixed intervals

Howey Test - refers to the U.S. Supreme Court case for determining whether a transaction qualifies as an "investment contract," and therefore would be considered a security; (per Infinite Machine Chp. White-Shoe Lawyers) Ether presale was classified as a utility, a function of ethereum and therefore not a security; manner distribution of a product and not as a speculative investment; essentially a utility token

immutable - can be set inside the constructor but cannot be modified afterwards, more gas efficient: i_owner - i meaning immutable

impermanent loss - a temporary loss of funds occurring when providing liquidity; occurs when the mathematical formula adjusts the asset ratio in a pool to ensure they remain at 50:50 in terms of value and the liquidity provider loses out on gains from a deposited asset that outperforms; whiteboard crypto video

interface - a list of function definitions without implementation. In other words, an interface is a description of all functions that an object must have for it to operate; convention preface I as in IERC721; video

internal - can't be called directly from outside the contract; same as private, except it's accessible to contracts that inherit

interoperability - the ability of independent distributed ledger networks to communicate with each other, exchange and make use of data; ability to move a digital asset between two or more blockchains while maintaining the state and uniqueness of the asset consistent throughout the process

invariant - invariant a computer programming construct consisting of a set of invariant properties that remain uncompromised regardless of the state of the object; a property of a system that should always hold

  • Stateless fuzzing: where the state of the previous run is discarded for every new run
  • Stateful fuzzing: fuzzing where final state of previous run is the starting state of the next run

IPFS - InterPlanetary File System (IPFS) a set of composable, peer-to-peer protocols for addressing, routing, and transferring content-addressed data in a decentralized file system; see also Swarm

it() - defined by the jasmine testing framework, to declare the expected output and have a fair check if it matches the coded conditions

import path resolution - name import

Keccak256 - SHA-3/Secure Hash Algorithm; using it in a contract

Know Your Customer or KYC - guidelines and regulations in financial services that require professionals to verify the identity, suitability, and risks involved with maintaining a business relationship with a customer; providing documents AML (anti money laundering)

layer 0 - the underlying infrastructure upon which multiple Layer 1 blockchains can be built; a network framework running beneath the blockchain. It is made up of protocols, connections, hardware, miners, and more that forms the foundation of the blockchain ecosystem. Layer: 0, 1, 2, 3 etc.

linting - the process of running a program that will analyze code for potential errors (verifying code quality) eslint

liquidity pool - a smart contract containing large portions of cryptocurrency, digital assets, tokens, or virtual coins locked up and ready to provide essential liquidity for networks that facilitate decentralized trading

magic number wiki unique value with unexplained meaning or multiple occurrences which could (preferably) be replaced with a named constant

memepool - or memory pool is a dynamic staging area in front of the blockchain that enables transaction ordering, fee prioritization, and general block construction; a list of pending transactions waiting for validation from a node before it is committed to a block on the blockchain

MEV - maximal (formerly miner) extractable value; referred to as an “invisible tax” that miners can collect from users – essentially, the maximum value a miner can extract from moving around transactions when producing a block on a blockchain network; video

mocking- creating objects that simulate the behaviour of real objects; primarily used in unit testing; Patrick Collins mocks

modifier - _; check requirements prior to execution code that can be run before and/or after a function call

  1. Restrict access
  2. Validate inputs
  3. Guard against reentrancy hack

msg.sender - there will always be a msg.sender; one who call contract

Named imports

NatSpec - Ethereum Natural Language Specification Format @title and @author are straightforward; @notice explains the contract function does; @dev is for explaining extra details to developers; @param and @return are for describing what each parameter and return value of a function are for

Nick Szabo - Nick Szabo coined the phrase and concept of "smart contracts"

node - blockchains are decentralized, immutable, digital ledgers shared across a peer-to-peer network. Acting as a database, transaction data is permanently recorded, stored and encrypted onto the “blocks” that are then “chained” together. The physical, electronic devices (a computer, typically) that maintain copies of the chains webbing a network together, keeping the blockchain operational, are called nodes

  • lightweight nodes - are downloaded wallets connected to full nodes for validating the data stored on the blockchain. Simple Payment Verification (SPV) node or lightweight node is used in day-to-day crypto operations.

nonce - transaction code for this account starting with 0; makes transactions unique; important regarding concurrency; If the account is an externally owned account, this number represents the number of transactions sent from the account’s address. If the account is a contract account, the nonce is the number of contracts created by the account; short video

Omner blocks - previously Uncle, it's possible for two blocks to be created simultaneously by a network. When this happens, one block will be left out. This leftover block is called an ommer block. In the past, they were called uncle blocks, referring to the familial relationships used to describe block positions within a blockchain

Opcode - operation code; the portion of a machine language instruction that specifies the operation to be performed; see gas Opcode

oracle - entities that connect blockchains to external systems, thereby enabling smart contracts to execute based upon inputs and outputs from the real world; a way for the decentralized ecosystem to access existing data sources, legacy systems, and advanced computations (blockchain middleware); also oracle manipulation via flash loans etc...

ownable - an owner who has special privileges

permission vs permissionless - comparison permissioned blockchains are distributed ledger technology (DLT) that sacrifice some degree of decentralization and anonymity to better suit business needs as well as achieve higher network speed and efficiency.

PII - personal Identifying information.

proof of concept - piece of code that demonstrates the vulnerability is exploitable; 100Proof's sample

private functions - it's convention to start private function names with an underscore (_): function _functionname() private {}

private relayers - "flashbots protect; no one sees transaction and can't front run it" per 32:50 of Dan Robinson AMA (e.g., Flashbots, Bloxroute, Ethermine, Eden)

Proxies - abstract contract implementing the core delegation functionality (upgrading a smart contract with a new one via delegatecall) dangers include: storage clashes and function selector clashes; Patrick Collins sample 1:05:16:02; shorter video

  • implementation contract
  • proxy contract --> points to correct implementation
  • the user makes calls to proxy
  • the admin decides which contract to upgrade etc
  • small proxies, usually referred to as clones can be used to deploy code only once and re-use it over and over again.

pure - static, does not effect or modify state, more computational [free function]

Quality Assurance (QA) - ensure the functionality, security, and efficiency of the smart contract code.

relayer - meta-transactions, a third-party (called a relayer) can send another user’s transactions and pay themselves for the gas cost. In this scheme, users sign messages (not transactions) containing information about a transaction they would like to execute. Relayers are then responsible for signing valid Ethereum transactions with this information and sending them to the network, paying for the gas cost. A base contract preserves the identity of the user that originally requested the transaction. In this way, users can interact directly with smart contracts without needing to have a wallet or own Ether.

revert - gives back gas but loses some in process; 1. revert reason strings

remote procedure call or RPC - when a computer program causes a procedure (subroutine) to execute in a different address space (commonly on another computer on a shared network), which is written as if it were a normal (local) procedure call, without the programmer explicitly writing the details for the remote interaction

ring signature - type of digital signature that can be performed by any member of a set of users that each have keys. Therefore, a message signed with a ring signature is endorsed by someone in a particular set of people

safeMath - before 0.8.0. there were overflow and underflow issues; prior to that version, solidity's "+" operator wouldn't check for overflows, leading to type(uint256).max + 1 = 0, and the safeMath library would avoid it. Now, type(uint256).max + 1 reverts with Panic(0x11), and safeMath isnt needed.

self destruct - leaves a blank account; costs negative gas, does not remove transaction history: only can be self destructed if contract has self destruct programmed in

sequencer - responsible for sorting transactions and it records the (batch) transactions on its local blockchain platform; Layer 2: Arbitrum, Optimism - Schnorr - introduces a commitment scheme for transaction ordering that enables transaction-level commitments instead of batching transactions together.  - Espresso Sequencer - a decentralized sequencing network for rollups. Its primary objective is to deliver secure, high throughput, and low latency transaction ordering and availability. -  Auditors should look out for missing L2 sequencer activity checks when they see price code callinglatestRoundData() in projects that are to be deployed on L2s.

slippage - the difference between the value of an asset at order placement and the value at order fulfilment. It can be found when buying or selling assets, and can result in either a loss or a gain (higher invariants lead to less slippage; Uniswap)

smart contract - programs stored on a blockchain that run when predetermined conditions are met; a transaction protocol intended to automatically execute, control or document events and actions according to the terms of a contract or an agreement; Ethereum contracts are essentially single threaded machine

  • hybrid smart contracts - combine code running on the blockchain (on-chain) with data and computation from outside the blockchain (off-chain) provided by decentralized oracle networks. chainlink

Solc - the solidity compiler to byte code

source lines of code (SLOC) - software metric used to measure the size of a computer program by counting the number of lines

staking - the act of depositing 32 ETH to activate validator software. As a validator you’ll be responsible for storing data, processing transactions, and adding new blocks to the blockchain.

state variables - variables stored permanently on the blockchain

stateless fuzzing - where the state of the previous run is discarded for every new run
stateful fuzzing - fuzzing where final state of previous run is the starting state of the next run

storageroot - a hash of the root node of a Merkle Patricia tree which encodes the hash of the storage contents of this account, and is empty by default

struct - useful for grouping related data, can be declared outside of a contract and imported in another contract

sybil attack a type of attack on a computer network service in which an attacker subverts the service's reputation system by creating a large number of pseudonymous identities and uses them to gain a disproportionately large influence. It is named after the subject of the book Sybil, a case study of a woman diagnosed with dissociative identity disorder; also sybil resistance

timelock - locks functionality on an application until a certain amount of time has passed; video

topics - indexed parameters for ‘logged’ events allow you to search for these events using the indexed parameters as filters; at most 3 parameters can receive the property indexed

TPS - transactions per second chart

transfer vs. transferFrom (aka delegatedTransfer) - transfer - simply transfer the tokens from one address to another; transferFrom -you give permission for someone else to transfer from your account; someone else can be either an externally-owned account or a smart-contract account
- transferFrom vs. safeTransferFrom in ERC721:

  • transferFrom: Transfers ownership of a token.
  • safeTransferFrom: Same as transferFrom but checks if the receiver is a smart contract and if so, checks to ensure it can handle ERC721 tokens.

tumbler - a service that mixes potentially identifiable or "tainted" cryptocurrency funds with others, so as to obscure the trail back to the fund's original source: Tornado cash; Zcash and Zk-SNARK's?

TVL - total value locked: includes all coins deposited in all functions that protocol offers: Staking, Lending, Liquidity pools

TWAPs or time-weighted average prices - often used by traders to execute larger orders without causing a significant impact on the market price

tx - "transaction": tx.origin, txn.gasprice; don't use tx.origin

unchecked - instead of SafeMath can be more gas efficient if you know your math won’t reach top or bottom limits

Uniswap - decentralized cryptocurrency exchange that uses a set of smart contracts (liquidity pools) to execute trades on its exchange; whitepaper and billion dollar algorithm ticklower and tickupper via Tick Uniswap

UTXO -  an unspent transaction output (UTXO) represents some amount of digital currency which has been authorized by one account to be spent by another. UTXOs use public key cryptography to identify and transfer ownership between holders of public/private key pairs

URI - unique sequence of characters that identifies a logical or physical resource used by web technologies.

UUPS (Universal Upgradeable Proxy Standard) - an upgradeable contract design pattern that separates a contract's logic from its data storage, allowing the logic to be replaced without affecting the stored data, thereby facilitating efficient and flexible smart contract upgrades; is more gas-efficient and flexible than the Transparent Upgradeable Proxy, but requires more care to ensure safety.

verbatim - introduced in Solidity 0.8.4, it allows injecting precompiled bytecode into the contract, useful for specific cryptographic operations.

whitelisting - allows only pre-approved entities to interact with a particular service, contract, or system within the blockchain environment; only authorized participants can access specific functionalities

witness - cryptography solution to puzzle; unspent transaction output, any solution to unlock UTXO; see also Segregated Witness

Yul - an intermediate language between Solidity and EVM bytecode.

Zcash - cryptocurrency using zk-SNARKs to provide enhanced privacy; either in a transparent pool or a shielded pool

zero address - contract creation; sometimes sent in an intentional ether burn

zero padding — (big-endian) for taking up entire memory; if your data type is uint8 or uint32 it is still managed as uint256 values (occupies 32bytes)

zkproof - method by which one party (the prover) can prove to another party (the verifier) that a given statement is true, while avoiding conveying to the verifier any information beyond the mere fact of the statement's truth ethereum Zk docs

  • zkRollup - bundling transactions off chain and submitting a single transaction onchain
  • zkSNARK - succinct non interactive argument of knowledge
  • optimistic rollup - assumes transactions are valid by default until proven otherwise. Incorrect transactions are challenged and rolled back.
  • zk-friendly vs. non-zk-friendly hash Functions: zk-friendly hash functions can be efficiently computed inside a zk-SNARK circuit, whereas non-zk-friendly ones can't.
  • Nullifier in Zero Knowledge: It's a unique value associated with a secret, used in zk-SNARKs protocols (like Zcash) to prevent double-spending without revealing the secret itself.

Solidity Contract Layout

// Layout of Contract:
// version
// imports
// errors
// interfaces, libraries, contracts
// Type declarations
// State variables
// Events
// Modifiers
// Functions

// Layout of Functions:
// constructor
// receive function (if exists)
// fallback function (if exists)
// external
// public
// internal
// private
// internal & private view & pure functions
// external & public view & pure functions

Releases

No releases published

Packages

No packages published