The document summarizes new features and design decisions of Uniswap v2 core contracts, including supporting arbitrary ERC20 token pairs, a price oracle that estimates time-weighted average prices, "flash swaps" that allow receiving assets before paying, and a optional 0.05% protocol fee. It also describes reducing the contracts' attack surface and making them more upgradeable by minimizing logic in the core contract storing liquidity providers' funds.
Smart contract honeypots for profit (and fun) - bhaPolySwarm
This document discusses various "smart contract honeypots" that appear vulnerable but are actually designed to exploit would-be attackers. It provides examples like a wallet with a reentrancy bug that doesn't actually allow funds to be stolen, and a gambling contract that displays a fake winning number. The document aims to educate about unintuitive behaviors in Ethereum and Solidity that honeypot designers exploit. It also notes the need for block explorer tools to carefully validate contract code and data.
The document provides an analysis of building a complete dataframe of historical data from the Uniswap V2 ETH-DAI liquidity pool. It describes collecting data on over 59,000 minting and burning events through over 200,000 API calls to retrieve smart contract data. The resulting dataframe contains 27 columns with information on reserves, prices, liquidity levels, fees earned, and more. It explores analyzing profitability, impermanent loss, and volume without accessing individual swap data.
This document introduces LayerZero, a protocol that enables trustless transactions directly between any blockchains. It aims to solve the problem of fragmentation across blockchains by allowing users to freely move assets and liquidity. LayerZero uses two independent entities, an Oracle and Relayer, to validate transactions across chains without relying on intermediaries. It establishes lightweight on-chain clients called LayerZero Endpoints to enable any blockchain to directly transact with any other, creating an interconnected omnichain network. This protocol opens opportunities for new cross-chain applications like decentralized exchanges and yield aggregators.
This document proposes a bidding strategy to optimize the use of Amazon spot instances. It includes:
1. A price prediction model to determine the lowest bid price needed for a given availability level by analyzing historical price data.
2. A bidding engine that aims to either finish jobs as quickly as possible or minimize monetary cost, while meeting deadline and budget constraints.
3. Experimental results showing the bidding engine can provide useful suggestions by predicting prices accurately and finding good bid prices and time ranges to meet user requirements.
Basics you need to know about Solidity and how it works. Learn the simple way of building a smart contract in Solidity. Tools that can be used with Solidity.
This document discusses the architecture of decentralized exchanges. It explains that decentralized exchanges have four main components: the blockchain platform, counterparty discovery mechanism, order matching algorithm, and transaction settlement protocol. It describes how these components are implemented in different decentralized exchanges, including using on-chain or off-chain order books and liquidity reserves. On-chain order books provide less censorship but lower performance, while off-chain order books require more trust but have better performance. The document analyzes the tradeoffs of different architectural designs.
Ripple - XRP we know how XRP blockchain throughout WhitepaperTrung Vu
Ripple (XRP) is an independent digital asset that is native to the Ripple Consensus Ledger. With proven governance and the fastest transaction confirmation of its kind, XRP is said to be the most efficient settlement option for financial institutions and liquidity providers seeking global reach, accessibility and fast settlement finality for interbank flows.
Source: Ripple - XRP
This document compares three distributed ledger platforms: Ethereum, Hyperledger Fabric, and R3 Corda. Ethereum is an open blockchain that allows any application to be built on top of it, while Hyperledger Fabric and Corda are permissioned ledgers often used for enterprise applications. Fabric utilizes channels to restrict information sharing, while Corda uses a model where each node maintains a unique ledger and shares facts only with counterparties to transactions. Overall, the platforms differ in their governance models, data sharing capabilities, and focus on public versus private deployments.
Smart contract honeypots for profit (and fun) - bhaPolySwarm
This document discusses various "smart contract honeypots" that appear vulnerable but are actually designed to exploit would-be attackers. It provides examples like a wallet with a reentrancy bug that doesn't actually allow funds to be stolen, and a gambling contract that displays a fake winning number. The document aims to educate about unintuitive behaviors in Ethereum and Solidity that honeypot designers exploit. It also notes the need for block explorer tools to carefully validate contract code and data.
The document provides an analysis of building a complete dataframe of historical data from the Uniswap V2 ETH-DAI liquidity pool. It describes collecting data on over 59,000 minting and burning events through over 200,000 API calls to retrieve smart contract data. The resulting dataframe contains 27 columns with information on reserves, prices, liquidity levels, fees earned, and more. It explores analyzing profitability, impermanent loss, and volume without accessing individual swap data.
This document introduces LayerZero, a protocol that enables trustless transactions directly between any blockchains. It aims to solve the problem of fragmentation across blockchains by allowing users to freely move assets and liquidity. LayerZero uses two independent entities, an Oracle and Relayer, to validate transactions across chains without relying on intermediaries. It establishes lightweight on-chain clients called LayerZero Endpoints to enable any blockchain to directly transact with any other, creating an interconnected omnichain network. This protocol opens opportunities for new cross-chain applications like decentralized exchanges and yield aggregators.
This document proposes a bidding strategy to optimize the use of Amazon spot instances. It includes:
1. A price prediction model to determine the lowest bid price needed for a given availability level by analyzing historical price data.
2. A bidding engine that aims to either finish jobs as quickly as possible or minimize monetary cost, while meeting deadline and budget constraints.
3. Experimental results showing the bidding engine can provide useful suggestions by predicting prices accurately and finding good bid prices and time ranges to meet user requirements.
Basics you need to know about Solidity and how it works. Learn the simple way of building a smart contract in Solidity. Tools that can be used with Solidity.
This document discusses the architecture of decentralized exchanges. It explains that decentralized exchanges have four main components: the blockchain platform, counterparty discovery mechanism, order matching algorithm, and transaction settlement protocol. It describes how these components are implemented in different decentralized exchanges, including using on-chain or off-chain order books and liquidity reserves. On-chain order books provide less censorship but lower performance, while off-chain order books require more trust but have better performance. The document analyzes the tradeoffs of different architectural designs.
Ripple - XRP we know how XRP blockchain throughout WhitepaperTrung Vu
Ripple (XRP) is an independent digital asset that is native to the Ripple Consensus Ledger. With proven governance and the fastest transaction confirmation of its kind, XRP is said to be the most efficient settlement option for financial institutions and liquidity providers seeking global reach, accessibility and fast settlement finality for interbank flows.
Source: Ripple - XRP
This document compares three distributed ledger platforms: Ethereum, Hyperledger Fabric, and R3 Corda. Ethereum is an open blockchain that allows any application to be built on top of it, while Hyperledger Fabric and Corda are permissioned ledgers often used for enterprise applications. Fabric utilizes channels to restrict information sharing, while Corda uses a model where each node maintains a unique ledger and shares facts only with counterparties to transactions. Overall, the platforms differ in their governance models, data sharing capabilities, and focus on public versus private deployments.
Horizon: A Gas-Efficient Trustless Bridge for Cross-Chain TransactionsGanesha Upadhyaya
The document describes a proposed trustless bridge protocol called Horizon for transferring assets between blockchains using gas-efficient cross-chain transactions. Key aspects include:
1) A super-light client that can prove a transaction was recorded on a Byzantine fault tolerance (BFT) chain using a constant-size cryptographic proof.
2) A bridge smart contract that can verify these proofs and mint/unlock equal amounts of tokens on the destination blockchain once verification succeeds.
3) A relay node that periodically transmits checkpoint information to the contract to allow verification of light client proofs for transactions on the BFT chain.
The protocol aims to enable trustless cross-chain transfers using small, self-sufficient transactions
The Ethereum network is a decentralized public blockchain that allows users to create and run decentralized applications (dApps). Ether (ETH) is the cryptocurrency that powers the Ethereum network and is used to pay transaction fees. Smart contracts enable the creation of dApps that execute automatically based on predefined rules without intermediaries.
In this white paper we introduce a new decentralized, non-custodial and open-source protocol that will provide an autonomous interest rate market to lenders and borrowers while setting interest rates based on credit supply and demand, enabling users to frictionlessly exchange the time value of their crypto assets at both variable and fixed interest rates for the first time in DeFi.
Aside from taking loans and making deposits at variable interest rates from a Variable Rate Pool, this protocol enables users to do so at fixed rates as well through the interaction with several Fixed Rate Pools, each one representing a specific maturity date. Interest rates are determined based on the credit utilization rate of each Fixed Rate Pool.
The document introduces the Compound protocol, which establishes decentralized money markets for cryptocurrency assets. It allows users to supply assets to earn interest and borrow assets using supplied assets as collateral. Interest rates are algorithmically determined based on supply and demand. The protocol improves on centralized exchanges and peer-to-peer lending by offering liquidity, allowing assets to be borrowed and used instantly without negotiation, and mitigating default risk through liquidation of collateral assets when borrowing limits are exceeded.
The document introduces the Compound protocol, which establishes decentralized money markets for cryptocurrencies. It allows users to supply assets to earn interest and borrow assets using supplied assets as collateral. Interest rates are algorithmically determined based on supply and demand in each market. The protocol uses ERC-20 tokens (cTokens) to represent supplied assets and tracks borrowing balances. It aims to create efficient markets for trading the time value of digital assets without counterparty risk.
[Cryptica 22] Introduction to Decentralized Finance - Nikola MarkovicDataScienceConferenc1
The aim of the talk is to introduce decentralized finance and its core concepts: Decentralized exchanges AKA Automated Market Makers (AMMs), lending protocols, and stablecoins. The talk will cover the similarities between traditional finance and DeFi with the accent on the innovative mechanisms DeFi & blockchain as underlying technology bring.
A SECURE ELECTRONIC PAYMENT PROTOCOL FOR WIRELESS MESH NETWORKSIJNSA Journal
This document proposes a secure electronic payment protocol for wireless mesh networks. It discusses:
- Micropayment schemes are well-suited for wireless mesh networks due to their efficient operations for small payments and support of mobile devices.
- The proposed protocol uses a one-way hash chain structure to support both prepaid and credit-based payment schemes efficiently and securely. Tickets containing payment hash chains are used to facilitate authentication and billing.
- The protocol aims to minimize public-key operations by relying on hash functions whenever possible to reduce computational burden on wireless devices. It also supports roaming between mesh routers in the same domain.
D1Conf 2018 | xDai Chain:Decentralized Insurance & the Benefits of the Stable...D1Conf
xDai is a new network created by POA Network in which Dai, a stablecoin, is the native currency of that chain. POA and Etherisc have joined forces to showcase how decentralized insurance DApps can be used on xDai, with the additional benefits of much faster transactions without the price volatility. Igor Barinov and Dmitry Savitsky presented the results of this joint effort at D1Conf.
These slides are courtesy of Igor Barinov, POA Network and Dmitry Savitsky, Etherisc
This document discusses building a blockchain-based platform for a government revenue department to store land records. A blockchain would allow records to be stored securely in blocks and verified by all nodes, reducing the risk of missing or duplicate records. The platform would allow online applications for NOCs and property transfers. Users could search for land details and location by identifiers. It would also reduce time spent by enabling online services. The platform would be built using JavaScript, HTML, CSS for the front end, a Python web server as middleware, and Python, Solidity and EVM for the backend.
How to Start Building in Web3 – Smart Contract Design & Development Part 1Zeeve
Sankalp Sharma, Co-Founder & VP of Engineering of Zeeve, starts the webinar by briefly introducing the topic of smart contract design and development, emphasizing the importance of understanding smart contracts and their potential to address challenges faced by traditional contracts.
Sankalp Sharma explains that the session is designed to be beginner-friendly, so no previous knowledge of smart contracts is required. He also briefly overviews what will be covered in the session and expresses his hope that participants will find the session productive.
An introduction to Ethereum, the peer to peer computing framework based on the blockchain design. It describes how Ethereum relates to earlier blockchain technologies and how it represents an evolution of these technologies
The document describes Kyber, an on-chain liquidity protocol that allows for instant token swaps in a decentralized manner across blockchains. It discusses the key actors in the protocol including takers, reserves, and maintainers. It outlines the core functions including getting conversion rates from reserves and executing trades. It also describes how basic token trades and token-to-token trades are executed. The document discusses connecting liquidity across blockchains through practical relay approaches and envisioning a unified liquidity network.
Rolling with Rollups Exploring Optimistic & Zero Knowledge Solutions use case...Zeeve
Titled “Rolling with Rollups: Exploring Optimistic & Zero Knowledge Solutions, Use Cases, and Impact,” this webinar will focus on the innovative concept of rollups and their potential to address scalability challenges in the blockchain ecosystem. Rollups have gained significant attention in recent times as a promising layer 2 scaling solution. During this webinar, Dr Ravi Chamria will provide a comprehensive exploration of both optimistic and zero-knowledge rollup solutions.
Boot Finance aims to be the primary AMM/DEX for defi projects by allowing projects to control their own liquidity pools. It proposes a 3-pronged approach for L2 chains: 1) stableswap AMMs, 2) project-controlled AMMs where projects design their own token swap curves, and 3) a unified cross-chain AMM that pools liquidity across chains. Project-controlled AMMs allow customization of features like swap curves and fees to benefit projects. The cross-chain AMM aims to make liquidity fragmented across chains feel unified to users by abstracting away bridge complexities.
Horizon: A Gas-Efficient Trustless Bridge for Cross-Chain TransactionsGanesha Upadhyaya
This document proposes Horizon, a gas-efficient and trustless bridge for cross-chain transactions. Horizon allows assets to be transferred from a proof-of-stake blockchain to another blockchain like Ethereum that supports smart contracts. It constructs a "super-light client" that can prove a transaction was recorded on the proof-of-stake chain with a cryptographic proof of logarithmic size. It also proposes a stateless bridge contract that requires only this small proof from the client, without needing pre-relayed checkpoint data from a relay node. This allows for efficient and trustless cross-chain transfers of assets between blockchains.
The document provides information on key components and concepts related to the public Ethereum blockchain, including miners and mining nodes, the Ethereum Virtual Machine (EVM), Ether, gas, transactions, accounts, Swarm and Whisper protocols, the Ethash mining algorithm, and frameworks like Truffle and Embark. It also compares Ethereum to Bitcoin and describes tools like Etherscan.io.
This document discusses numerical methods for pricing financial derivatives. It covers discrete and continuous time frameworks, American and path-dependent options, and Monte Carlo simulation. The key points are:
1) Discrete models compute expected value through backward recursion on a lattice, allowing early exercise of American options. Continuous models generalize Black-Scholes.
2) Path-dependent options like lookbacks require Markovianization by introducing an auxiliary state variable. Lattice methods can be refined non-uniformly using adaptive meshing.
3) Monte Carlo simulation prices derivatives through discretization and sampling, with techniques to reduce variance like control variates.
The Libra blockchain uses an account-based model where the ledger state is a key-value store mapping account addresses to account values. Account values contain Move resources (data) and modules (code). When a transaction attempts to send Libra to a non-existent account, the transaction will create that account by generating a verification key pair and deriving the account address from the verification key. Executing a Libra transaction involves applying the transaction against the previous ledger state to produce a new state and outputs like events and status codes. Validators execute transactions deterministically and independently to reach consensus on the new ledger state.
- Phase I of bridging Aave from Ethereum to Starknet involves bridging aTokens, which represent deposited liquidity on Ethereum, to static aTokens on Starknet. This allows holders to passively accumulate yield from the deposited Ethereum aTokens without active communication between the chains.
- When depositing aTokens to the Ethereum bridge contract, a message is sent and recorded on Starknet. Starknet proves the message was executed, removing it from the record. A cancellation mechanism allows unprocessed messages to be cancelled within 5 days to retrieve deposited funds if needed.
This document discusses arbitrage and synthetic instruments. It begins by defining arbitrage as profiting from price discrepancies between markets through simultaneous transactions. It then discusses the history of arbitrage from ancient times to modern day. Key risks in arbitrage in India include execution lags, interest rate uncertainty, transaction risk, and default risk. The document also covers other types of arbitrage like pure arbitrage and futures arbitrage. It concludes by listing some impediments to arbitrage in India such as lack of liquidity, regulatory anomalies, inadequate infrastructure, and lack of knowledge.
Storytelling is an incredibly valuable tool to share data and information. To get the most impact from stories there are a number of key ingredients. These are based on science and human nature. Using these elements in a story you can deliver information impactfully, ensure action and drive change.
Horizon: A Gas-Efficient Trustless Bridge for Cross-Chain TransactionsGanesha Upadhyaya
The document describes a proposed trustless bridge protocol called Horizon for transferring assets between blockchains using gas-efficient cross-chain transactions. Key aspects include:
1) A super-light client that can prove a transaction was recorded on a Byzantine fault tolerance (BFT) chain using a constant-size cryptographic proof.
2) A bridge smart contract that can verify these proofs and mint/unlock equal amounts of tokens on the destination blockchain once verification succeeds.
3) A relay node that periodically transmits checkpoint information to the contract to allow verification of light client proofs for transactions on the BFT chain.
The protocol aims to enable trustless cross-chain transfers using small, self-sufficient transactions
The Ethereum network is a decentralized public blockchain that allows users to create and run decentralized applications (dApps). Ether (ETH) is the cryptocurrency that powers the Ethereum network and is used to pay transaction fees. Smart contracts enable the creation of dApps that execute automatically based on predefined rules without intermediaries.
In this white paper we introduce a new decentralized, non-custodial and open-source protocol that will provide an autonomous interest rate market to lenders and borrowers while setting interest rates based on credit supply and demand, enabling users to frictionlessly exchange the time value of their crypto assets at both variable and fixed interest rates for the first time in DeFi.
Aside from taking loans and making deposits at variable interest rates from a Variable Rate Pool, this protocol enables users to do so at fixed rates as well through the interaction with several Fixed Rate Pools, each one representing a specific maturity date. Interest rates are determined based on the credit utilization rate of each Fixed Rate Pool.
The document introduces the Compound protocol, which establishes decentralized money markets for cryptocurrency assets. It allows users to supply assets to earn interest and borrow assets using supplied assets as collateral. Interest rates are algorithmically determined based on supply and demand. The protocol improves on centralized exchanges and peer-to-peer lending by offering liquidity, allowing assets to be borrowed and used instantly without negotiation, and mitigating default risk through liquidation of collateral assets when borrowing limits are exceeded.
The document introduces the Compound protocol, which establishes decentralized money markets for cryptocurrencies. It allows users to supply assets to earn interest and borrow assets using supplied assets as collateral. Interest rates are algorithmically determined based on supply and demand in each market. The protocol uses ERC-20 tokens (cTokens) to represent supplied assets and tracks borrowing balances. It aims to create efficient markets for trading the time value of digital assets without counterparty risk.
[Cryptica 22] Introduction to Decentralized Finance - Nikola MarkovicDataScienceConferenc1
The aim of the talk is to introduce decentralized finance and its core concepts: Decentralized exchanges AKA Automated Market Makers (AMMs), lending protocols, and stablecoins. The talk will cover the similarities between traditional finance and DeFi with the accent on the innovative mechanisms DeFi & blockchain as underlying technology bring.
A SECURE ELECTRONIC PAYMENT PROTOCOL FOR WIRELESS MESH NETWORKSIJNSA Journal
This document proposes a secure electronic payment protocol for wireless mesh networks. It discusses:
- Micropayment schemes are well-suited for wireless mesh networks due to their efficient operations for small payments and support of mobile devices.
- The proposed protocol uses a one-way hash chain structure to support both prepaid and credit-based payment schemes efficiently and securely. Tickets containing payment hash chains are used to facilitate authentication and billing.
- The protocol aims to minimize public-key operations by relying on hash functions whenever possible to reduce computational burden on wireless devices. It also supports roaming between mesh routers in the same domain.
D1Conf 2018 | xDai Chain:Decentralized Insurance & the Benefits of the Stable...D1Conf
xDai is a new network created by POA Network in which Dai, a stablecoin, is the native currency of that chain. POA and Etherisc have joined forces to showcase how decentralized insurance DApps can be used on xDai, with the additional benefits of much faster transactions without the price volatility. Igor Barinov and Dmitry Savitsky presented the results of this joint effort at D1Conf.
These slides are courtesy of Igor Barinov, POA Network and Dmitry Savitsky, Etherisc
This document discusses building a blockchain-based platform for a government revenue department to store land records. A blockchain would allow records to be stored securely in blocks and verified by all nodes, reducing the risk of missing or duplicate records. The platform would allow online applications for NOCs and property transfers. Users could search for land details and location by identifiers. It would also reduce time spent by enabling online services. The platform would be built using JavaScript, HTML, CSS for the front end, a Python web server as middleware, and Python, Solidity and EVM for the backend.
How to Start Building in Web3 – Smart Contract Design & Development Part 1Zeeve
Sankalp Sharma, Co-Founder & VP of Engineering of Zeeve, starts the webinar by briefly introducing the topic of smart contract design and development, emphasizing the importance of understanding smart contracts and their potential to address challenges faced by traditional contracts.
Sankalp Sharma explains that the session is designed to be beginner-friendly, so no previous knowledge of smart contracts is required. He also briefly overviews what will be covered in the session and expresses his hope that participants will find the session productive.
An introduction to Ethereum, the peer to peer computing framework based on the blockchain design. It describes how Ethereum relates to earlier blockchain technologies and how it represents an evolution of these technologies
The document describes Kyber, an on-chain liquidity protocol that allows for instant token swaps in a decentralized manner across blockchains. It discusses the key actors in the protocol including takers, reserves, and maintainers. It outlines the core functions including getting conversion rates from reserves and executing trades. It also describes how basic token trades and token-to-token trades are executed. The document discusses connecting liquidity across blockchains through practical relay approaches and envisioning a unified liquidity network.
Rolling with Rollups Exploring Optimistic & Zero Knowledge Solutions use case...Zeeve
Titled “Rolling with Rollups: Exploring Optimistic & Zero Knowledge Solutions, Use Cases, and Impact,” this webinar will focus on the innovative concept of rollups and their potential to address scalability challenges in the blockchain ecosystem. Rollups have gained significant attention in recent times as a promising layer 2 scaling solution. During this webinar, Dr Ravi Chamria will provide a comprehensive exploration of both optimistic and zero-knowledge rollup solutions.
Boot Finance aims to be the primary AMM/DEX for defi projects by allowing projects to control their own liquidity pools. It proposes a 3-pronged approach for L2 chains: 1) stableswap AMMs, 2) project-controlled AMMs where projects design their own token swap curves, and 3) a unified cross-chain AMM that pools liquidity across chains. Project-controlled AMMs allow customization of features like swap curves and fees to benefit projects. The cross-chain AMM aims to make liquidity fragmented across chains feel unified to users by abstracting away bridge complexities.
Horizon: A Gas-Efficient Trustless Bridge for Cross-Chain TransactionsGanesha Upadhyaya
This document proposes Horizon, a gas-efficient and trustless bridge for cross-chain transactions. Horizon allows assets to be transferred from a proof-of-stake blockchain to another blockchain like Ethereum that supports smart contracts. It constructs a "super-light client" that can prove a transaction was recorded on the proof-of-stake chain with a cryptographic proof of logarithmic size. It also proposes a stateless bridge contract that requires only this small proof from the client, without needing pre-relayed checkpoint data from a relay node. This allows for efficient and trustless cross-chain transfers of assets between blockchains.
The document provides information on key components and concepts related to the public Ethereum blockchain, including miners and mining nodes, the Ethereum Virtual Machine (EVM), Ether, gas, transactions, accounts, Swarm and Whisper protocols, the Ethash mining algorithm, and frameworks like Truffle and Embark. It also compares Ethereum to Bitcoin and describes tools like Etherscan.io.
This document discusses numerical methods for pricing financial derivatives. It covers discrete and continuous time frameworks, American and path-dependent options, and Monte Carlo simulation. The key points are:
1) Discrete models compute expected value through backward recursion on a lattice, allowing early exercise of American options. Continuous models generalize Black-Scholes.
2) Path-dependent options like lookbacks require Markovianization by introducing an auxiliary state variable. Lattice methods can be refined non-uniformly using adaptive meshing.
3) Monte Carlo simulation prices derivatives through discretization and sampling, with techniques to reduce variance like control variates.
The Libra blockchain uses an account-based model where the ledger state is a key-value store mapping account addresses to account values. Account values contain Move resources (data) and modules (code). When a transaction attempts to send Libra to a non-existent account, the transaction will create that account by generating a verification key pair and deriving the account address from the verification key. Executing a Libra transaction involves applying the transaction against the previous ledger state to produce a new state and outputs like events and status codes. Validators execute transactions deterministically and independently to reach consensus on the new ledger state.
- Phase I of bridging Aave from Ethereum to Starknet involves bridging aTokens, which represent deposited liquidity on Ethereum, to static aTokens on Starknet. This allows holders to passively accumulate yield from the deposited Ethereum aTokens without active communication between the chains.
- When depositing aTokens to the Ethereum bridge contract, a message is sent and recorded on Starknet. Starknet proves the message was executed, removing it from the record. A cancellation mechanism allows unprocessed messages to be cancelled within 5 days to retrieve deposited funds if needed.
This document discusses arbitrage and synthetic instruments. It begins by defining arbitrage as profiting from price discrepancies between markets through simultaneous transactions. It then discusses the history of arbitrage from ancient times to modern day. Key risks in arbitrage in India include execution lags, interest rate uncertainty, transaction risk, and default risk. The document also covers other types of arbitrage like pure arbitrage and futures arbitrage. It concludes by listing some impediments to arbitrage in India such as lack of liquidity, regulatory anomalies, inadequate infrastructure, and lack of knowledge.
Storytelling is an incredibly valuable tool to share data and information. To get the most impact from stories there are a number of key ingredients. These are based on science and human nature. Using these elements in a story you can deliver information impactfully, ensure action and drive change.
Navigating the world of forex trading can be challenging, especially for beginners. To help you make an informed decision, we have comprehensively compared the best forex brokers in India for 2024. This article, reviewed by Top Forex Brokers Review, will cover featured award winners, the best forex brokers, featured offers, the best copy trading platforms, the best forex brokers for beginners, the best MetaTrader brokers, and recently updated reviews. We will focus on FP Markets, Black Bull, EightCap, IC Markets, and Octa.
Building Your Employer Brand with Social MediaLuanWise
Presented at The Global HR Summit, 6th June 2024
In this keynote, Luan Wise will provide invaluable insights to elevate your employer brand on social media platforms including LinkedIn, Facebook, Instagram, X (formerly Twitter) and TikTok. You'll learn how compelling content can authentically showcase your company culture, values, and employee experiences to support your talent acquisition and retention objectives. Additionally, you'll understand the power of employee advocacy to amplify reach and engagement – helping to position your organization as an employer of choice in today's competitive talent landscape.
Taurus Zodiac Sign: Unveiling the Traits, Dates, and Horoscope Insights of th...my Pandit
Dive into the steadfast world of the Taurus Zodiac Sign. Discover the grounded, stable, and logical nature of Taurus individuals, and explore their key personality traits, important dates, and horoscope insights. Learn how the determination and patience of the Taurus sign make them the rock-steady achievers and anchors of the zodiac.
[To download this presentation, visit:
https://www.oeconsulting.com.sg/training-presentations]
This presentation is a curated compilation of PowerPoint diagrams and templates designed to illustrate 20 different digital transformation frameworks and models. These frameworks are based on recent industry trends and best practices, ensuring that the content remains relevant and up-to-date.
Key highlights include Microsoft's Digital Transformation Framework, which focuses on driving innovation and efficiency, and McKinsey's Ten Guiding Principles, which provide strategic insights for successful digital transformation. Additionally, Forrester's framework emphasizes enhancing customer experiences and modernizing IT infrastructure, while IDC's MaturityScape helps assess and develop organizational digital maturity. MIT's framework explores cutting-edge strategies for achieving digital success.
These materials are perfect for enhancing your business or classroom presentations, offering visual aids to supplement your insights. Please note that while comprehensive, these slides are intended as supplementary resources and may not be complete for standalone instructional purposes.
Frameworks/Models included:
Microsoft’s Digital Transformation Framework
McKinsey’s Ten Guiding Principles of Digital Transformation
Forrester’s Digital Transformation Framework
IDC’s Digital Transformation MaturityScape
MIT’s Digital Transformation Framework
Gartner’s Digital Transformation Framework
Accenture’s Digital Strategy & Enterprise Frameworks
Deloitte’s Digital Industrial Transformation Framework
Capgemini’s Digital Transformation Framework
PwC’s Digital Transformation Framework
Cisco’s Digital Transformation Framework
Cognizant’s Digital Transformation Framework
DXC Technology’s Digital Transformation Framework
The BCG Strategy Palette
McKinsey’s Digital Transformation Framework
Digital Transformation Compass
Four Levels of Digital Maturity
Design Thinking Framework
Business Model Canvas
Customer Journey Map
[To download this presentation, visit:
https://www.oeconsulting.com.sg/training-presentations]
This PowerPoint compilation offers a comprehensive overview of 20 leading innovation management frameworks and methodologies, selected for their broad applicability across various industries and organizational contexts. These frameworks are valuable resources for a wide range of users, including business professionals, educators, and consultants.
Each framework is presented with visually engaging diagrams and templates, ensuring the content is both informative and appealing. While this compilation is thorough, please note that the slides are intended as supplementary resources and may not be sufficient for standalone instructional purposes.
This compilation is ideal for anyone looking to enhance their understanding of innovation management and drive meaningful change within their organization. Whether you aim to improve product development processes, enhance customer experiences, or drive digital transformation, these frameworks offer valuable insights and tools to help you achieve your goals.
INCLUDED FRAMEWORKS/MODELS:
1. Stanford’s Design Thinking
2. IDEO’s Human-Centered Design
3. Strategyzer’s Business Model Innovation
4. Lean Startup Methodology
5. Agile Innovation Framework
6. Doblin’s Ten Types of Innovation
7. McKinsey’s Three Horizons of Growth
8. Customer Journey Map
9. Christensen’s Disruptive Innovation Theory
10. Blue Ocean Strategy
11. Strategyn’s Jobs-To-Be-Done (JTBD) Framework with Job Map
12. Design Sprint Framework
13. The Double Diamond
14. Lean Six Sigma DMAIC
15. TRIZ Problem-Solving Framework
16. Edward de Bono’s Six Thinking Hats
17. Stage-Gate Model
18. Toyota’s Six Steps of Kaizen
19. Microsoft’s Digital Transformation Framework
20. Design for Six Sigma (DFSS)
To download this presentation, visit:
https://www.oeconsulting.com.sg/training-presentations
Industrial Tech SW: Category Renewal and CreationChristian Dahlen
Every industrial revolution has created a new set of categories and a new set of players.
Multiple new technologies have emerged, but Samsara and C3.ai are only two companies which have gone public so far.
Manufacturing startups constitute the largest pipeline share of unicorns and IPO candidates in the SF Bay Area, and software startups dominate in Germany.
HOW TO START UP A COMPANY A STEP-BY-STEP GUIDE.pdf46adnanshahzad
How to Start Up a Company: A Step-by-Step Guide Starting a company is an exciting adventure that combines creativity, strategy, and hard work. It can seem overwhelming at first, but with the right guidance, anyone can transform a great idea into a successful business. Let's dive into how to start up a company, from the initial spark of an idea to securing funding and launching your startup.
Introduction
Have you ever dreamed of turning your innovative idea into a thriving business? Starting a company involves numerous steps and decisions, but don't worry—we're here to help. Whether you're exploring how to start a startup company or wondering how to start up a small business, this guide will walk you through the process, step by step.
Understanding User Needs and Satisfying ThemAggregage
https://www.productmanagementtoday.com/frs/26903918/understanding-user-needs-and-satisfying-them
We know we want to create products which our customers find to be valuable. Whether we label it as customer-centric or product-led depends on how long we've been doing product management. There are three challenges we face when doing this. The obvious challenge is figuring out what our users need; the non-obvious challenges are in creating a shared understanding of those needs and in sensing if what we're doing is meeting those needs.
In this webinar, we won't focus on the research methods for discovering user-needs. We will focus on synthesis of the needs we discover, communication and alignment tools, and how we operationalize addressing those needs.
Industry expert Scott Sehlhorst will:
• Introduce a taxonomy for user goals with real world examples
• Present the Onion Diagram, a tool for contextualizing task-level goals
• Illustrate how customer journey maps capture activity-level and task-level goals
• Demonstrate the best approach to selection and prioritization of user-goals to address
• Highlight the crucial benchmarks, observable changes, in ensuring fulfillment of customer needs
The 10 Most Influential Leaders Guiding Corporate Evolution, 2024.pdfthesiliconleaders
In the recent edition, The 10 Most Influential Leaders Guiding Corporate Evolution, 2024, The Silicon Leaders magazine gladly features Dejan Štancer, President of the Global Chamber of Business Leaders (GCBL), along with other leaders.
❼❷⓿❺❻❷❽❷❼❽ Dpboss Matka Result Satta Matka Guessing Satta Fix jodi Kalyan Final ank Satta Matka Dpbos Final ank Satta Matta Matka 143 Kalyan Matka Guessing Final Matka Final ank Today Matka 420 Satta Batta Satta 143 Kalyan Chart Main Bazar Chart vip Matka Guessing Dpboss 143 Guessing Kalyan night
How to Implement a Strategy: Transform Your Strategy with BSC Designer's Comp...Aleksey Savkin
The Strategy Implementation System offers a structured approach to translating stakeholder needs into actionable strategies using high-level and low-level scorecards. It involves stakeholder analysis, strategy decomposition, adoption of strategic frameworks like Balanced Scorecard or OKR, and alignment of goals, initiatives, and KPIs.
Key Components:
- Stakeholder Analysis
- Strategy Decomposition
- Adoption of Business Frameworks
- Goal Setting
- Initiatives and Action Plans
- KPIs and Performance Metrics
- Learning and Adaptation
- Alignment and Cascading of Scorecards
Benefits:
- Systematic strategy formulation and execution.
- Framework flexibility and automation.
- Enhanced alignment and strategic focus across the organization.
B2B payments are rapidly changing. Find out the 5 key questions you need to be asking yourself to be sure you are mastering B2B payments today. Learn more at www.BlueSnap.com.
Discover timeless style with the 2022 Vintage Roman Numerals Men's Ring. Crafted from premium stainless steel, this 6mm wide ring embodies elegance and durability. Perfect as a gift, it seamlessly blends classic Roman numeral detailing with modern sophistication, making it an ideal accessory for any occasion.
https://rb.gy/usj1a2
1. Uniswap v2 Core
Hayden Adams
hayden@uniswap.org
Noah Zinsmeister
noah@uniswap.org
Dan Robinson
dan@paradigm.xyz
March 2020
Abstract
This technical whitepaper explains some of the design decisions behind the Uniswap
v2 core contracts. It covers the contracts’ new features—including arbitrary pairs
between ERC20s, a hardened price oracle that allows other contracts to estimate the
time-weighted average price over a given interval, “flash swaps” that allow traders to
receive assets and use them elsewhere before paying for them later in the transaction,
and a protocol fee that can be turned on in the future. It also re-architects the contracts
to reduce their attack surface. This whitepaper describes the mechanics of Uniswap v2’s
“core” contracts including the pair contract that stores liquidity providers’ funds—and
the factory contract used to instantiate pair contracts.
1 Introduction
Uniswap v1 is an on-chain system of smart contracts on the Ethereum blockchain, imple-
menting an automated liquidity protocol based on a “constant product formula” [1]. Each
Uniswap v1 pair stores pooled reserves of two assets, and provides liquidity for those two
assets, maintaining the invariant that the product of the reserves cannot decrease. Traders
pay a 30-basis-point fee on trades, which goes to liquidity providers. The contracts are
non-upgradeable.
Uniswap v2 is a new implementation based on the same formula, with several new highly-
desirable features. Most significantly, it enables the creation of arbitrary ERC20/ERC20
pairs, rather than supporting only pairs between ERC20 and ETH. It also provides a hard-
ened price oracle that accumulates the relative price of the two assets at the beginning of
each block. This allows other contracts on Ethereum to estimate the time-weighted average
price for the two assets over arbitrary intervals. Finally, it enables “flash swaps” where users
can receive assets freely and use them elsewhere on the chain, only paying for (or returning)
those assets at the end of the transaction.
While the contract is not generally upgradeable, there is a private key that has the
ability to update a variable on the factory contract to turn on an on-chain 5-basis-point fee
on trades. This fee will initially be turned off, but could be turned on in the future, after
which liquidity providers would earn 25 basis points on every trade, rather than 30 basis
points.
As discussed in section 3, Uniswap v2 also fixes some minor issues with Uniswap v1, as
well as rearchitecting the implementation, reducing Uniswap’s attack surface and making
the system more easily upgradeable by minimizing the logic in the “core” contract that
holds liquidity providers’ funds.
1
2. This paper describes the mechanics of that core contract, as well as the factory contract
used to instantiate those contracts. Actually using Uniswap v2 will require calling the
pair contract through a “router” contract that computes the trade or deposit amount and
transfers funds to the pair contract.
2 New features
2.1 ERC-20 pairs
Uniswap v1 used ETH as a bridge currency. Every pair included ETH as one of its
assets. This makes routing simpler—every trade between ABC and XYZ goes through the
ETH/ABC pair and the ETH/XYZ pair—and reduces fragmentation of liquidity.
However, this rule imposes significant costs on liquidity providers. All liquidity providers
have exposure to ETH, and suffer impermanent loss based on changes in the prices of other
assets relative to ETH. When two assets ABC and XYZ are correlated—for example, if
they are both USD stablecoins—liquidity providers on a Uniswap pair ABC/XYZ would
generally be subject to less impermanent loss than the ABC/ETH or XYZ/ETH pairs.
Using ETH as a mandatory bridge currency also imposes costs on traders. Traders have
to pay twice as much in fees as they would on a direct ABC/XYZ pair, and they suffer
slippage twice.
Uniswap v2 allows liquidity providers to create pair contracts for any two ERC-20s.
A proliferation of pairs between arbitrary ERC-20s could make it somewhat more difficult
to find the best path to trade a particular pair, but routing can be handled at a higher layer
(either off-chain or through an on-chain router or aggregator).
2.2 Price oracle
The marginal price offered by Uniswap (not including fees) at time t can be computed
by dividing the reserves of asset a by the reserves of asset b.
pt =
ra
t
rb
t
(1)
Since arbitrageurs will trade with Uniswap if this price is incorrect (by a sufficient amount
to make up for the fee), the price offered by Uniswap tends to track the relative market price
of the assets, as shown by Angeris et al [2]. This means it can be used as an approximate
price oracle.
However, Uniswap v1 is not safe to use as an on-chain price oracle, because it is very
easy to manipulate. Suppose some other contract uses the current ETH-DAI price to settle
a derivative. An attacker who wishes to manipulate the measured price can buy ETH from
the ETH-DAI pair, trigger settlement on the derivative contract (causing it to settle based
on the inflated price), and then sell ETH back to the pair to trade it back to the true price.1
This might even be done as an atomic transaction, or by a miner who controls the ordering
of transactions within a block.
Uniswap v2 improves this oracle functionality by measuring and recording the price
before the first trade of each block (or equivalently, after the last trade of the previous
1For a real-world example of how using Uniswap v1 as an oracle can make a contract vulnerable to such
an attack, see [3].
2
3. block). This price is more difficult to manipulate than prices during a block. If the attacker
submits a transaction that attempts to manipulate the price at the end of a block, some
other arbitrageur may be able to submit another transaction to trade back immediately
afterward in the same block. A miner (or an attacker who uses enough gas to fill an entire
block) could manipulate the price at the end of a block, but unless they mine the next block
as well, they may not have a particular advantage in arbitraging the trade back.
Specifically, Uniswap v2 accumulates this price, by keeping track of the cumulative sum
of prices at the beginning of each block in which someone interacts with the contract. Each
price is weighted by the amount of time that has passed since the last block in which it was
updated, according to the block timestamp.2
This means that the accumulator value at any
given time (after being updated) should be the sum of the spot price at each second in the
history of the contract.
at =
t
i=1
pi (2)
To estimate the time-weighted average price from time t1 to t2, an external caller can
checkpoint the accumulator’s value at t1 and then again at t2, subtract the first value from
the second, and divide by the number of seconds elapsed. (Note that the contract itself does
not store historical values for this accumulator—the caller has to call the contract at the
beginning of the period to read and store this value.)
pt1,t2
=
t2
i=t1
pi
t2 − t1
=
t2
i=1 pi −
t1
i=1 pi
t2 − t1
=
at2 − at1
t2 − t1
(3)
Users of the oracle can choose when to start and end this period. Choosing a longer
period makes it more expensive for an attacker to manipulate the TWAP, although it results
in a less up-to-date price.
One complication: should we measure the price of asset A in terms of asset B, or the
price of asset B in terms of asset A? While the spot price of A in terms of B is always the
reciprocal of the spot price of B in terms of A, the mean price of asset A in terms of asset B
over a particular period of time is not equal to the reciprocal of the mean price of asset B in
terms of asset A.3
For example, if the USD/ETH price is 100 in block 1 and 300 in block 2,
the average USD/ETH price will be 200 USD/ETH, but the average ETH/USD price will
be 1/150 ETH/USD. Since the contract cannot know which of the two assets users would
want to use as the unit of account, Uniswap v2 tracks both prices.
Another complication is that it is possible for someone to send assets to the pair con-
tract—and thus change its balances and marginal price—without interacting with it, and
thus without triggering an oracle update. If the contract simply checked its own balances
and updated the oracle based on the current price, an attacker could manipulate the oracle
by sending an asset to the contract immediately before calling it for the first time in a
block. If the last trade was in a block whose timestamp was X seconds ago, the contract
would incorrectly multiply the new price by X before accumulating it, even though nobody
2Since miners have some freedom to set the block timestamp, users of the oracle should be aware that
these values may not correspond precisely to real-world times.
3The arithmetic mean price of asset A in terms of asset B over a given period is equal to the reciprocal
of the harmonic mean price of asset B in terms of asset A over that period. If the contract measured the
geometric mean price, then the prices would be the reciprocals of each other. However, the geometric mean
TWAP is less commonly used, and is difficult to compute on Ethereum.
3
4. has had an opportunity to trade at that price. To prevent this, the core contract caches
its reserves after each interaction, and updates the oracle using the price derived from the
cached reserves rather than the current reserves. In addition to protecting the oracle from
manipulation, this change enables the contract re-architecture described below in section
3.2.
2.2.1 Precision
Because Solidity does not have first-class support for non-integer numeric data types,
the Uniswap v2 uses a simple binary fixed point format to encode and manipulate prices.
Specifically, prices at a given moment are stored as UQ112.112 numbers, meaning that 112
fractional bits of precision are specified on either side of the decimal point, with no sign.
These numbers have a range of [0, 2112
− 1]4
and a precision of 1
2112 .
The UQ112.112 format was chosen for a pragmatic reason — because these numbers can
be stored in a uint224, this leaves 32 bits of a 256 bit storage slot free. It also happens that
the reserves, each stored in a uint112, also leave 32 bits free in a (packed) 256 bit storage slot.
These free spaces are used for the accumulation process described above. Specifically, the
reserves are stored alongside the timestamp of the most recent block with at least one trade,
modded with 232
so that it fits into 32 bits. Additionally, although the price at any given
moment (stored as a UQ112.112 number) is guaranteed to fit in 224 bits, the accumulation
of this price over an interval is not. The extra 32 bits on the end of the storage slots for the
accumulated price of A/B and B/A are used to store overflow bits resulting from repeated
summations of prices. This design means that the price oracle only adds an additional three
SSTORE operations (a current cost of about 15,000 gas) to the first trade in each block.
The primary downside is that 32 bits isn’t quite enough to store timestamp values that
will reasonably never overflow. In fact, the date when the Unix timestamp overflows a uint32
is 02/07/2106. To ensure that this system continues to function properly after this date,
and every multiple of 232
− 1 seconds thereafter, oracles are simply required to check prices
at least once per interval (approximately 136 years). This is because the core method of
accumulation (and modding of timestamp), is actually overflow-safe, meaning that trades
across overflow intervals can be appropriately accounted for given that oracles are using the
proper (simple) overflow arithmetic to compute deltas.
2.3 Flash Swaps
In Uniswap v1, a user purchasing ABC with XYZ needs to send the XYZ to the contract
before they could receive the ABC. This is inconvenient if that user needs the ABC they
are buying in order to obtain the XYZ they are paying with. For example, the user might
be using that ABC to purchase XYZ in some other contract in order to arbitrage a price
difference from Uniswap, or they could be unwinding a position on Maker or Compound by
selling the collateral to repay Uniswap.
Uniswap v2 adds a new feature that allows a user to receive and use an asset before paying
for it, as long as they make the payment within the same atomic transaction. The swap
function makes a call to an optional user-specified callback contract in between transferring
out the tokens requested by the user and enforcing the invariant. Once the callback is
complete, the contract checks the new balances and confirms that the invariant is satisfied
4The theoretical upper bound of 2112 − ( 1
2112 ) does not apply in this setting, as UQ112.112 numbers in
Uniswap are always generated from the ratio of two uint112s. The largest such ratio is 2112
−1
1
= 2112 − 1.
4
5. (after adjusting for fees on the amounts paid in). If the contract does not have sufficient
funds, it reverts the entire transaction.
A user can also repay the Uniswap pool using the same token, rather than completing
the swap. This is effectively the same as letting anyone flash-borrow any of assets stored in
a Uniswap pool (for the same 0.30% fee as Uniswap charges for trading).5
2.4 Protocol fee
Uniswap v2 includes a 0.05% protocol fee that can be turned on and off. If turned on,
this fee would be sent to a feeTo address specified in the factory contract.
Initially, feeTo is not set, and no fee is collected. A pre-specified address—feeToSetter—can
call the setFeeTo function on the Uniswap v2 factory contract, setting feeTo to a different
value. feeToSetter can also call the setFeeToSetter to change the feeToSetter address
itself.
If the feeTo address is set, the protocol will begin charging a 5-basis-point fee, which is
taken as a 1
6 cut of the 30-basis-point fees earned by liquidity providers. That is, traders will
continue to pay a 0.30% fee on all trades; 83.3% of that fee (0.25% of the amount traded)
will go to liquidity providers, and 16.6% of that fee (0.05% of the amount traded) will go to
the feeTo address.
Collecting this 0.05% fee at the time of the trade would impose an additional gas cost on
every trade. To avoid this, accumulated fees are collected only when liquidity is deposited
or withdrawn. The contract computes the accumulated fees, and mints new liquidity tokens
to the fee beneficiary, immediately before any tokens are minted or burned.
The total collected fees can be computed by measuring the growth in
√
k (that is,
√
x · y)
since the last time fees were collected.6
This formula gives you the accumulated fees between
t1 and t2 as a percentage of the liquidity in the pool at t2:
f1,2 = 1 −
√
k1
√
k2
(4)
If the fee was activated before t1, the feeTo address should capture 1
6 of fees that were
accumulated between t1 and t2. Therefore, we want to mint new liquidity tokens to the
feeTo address that represent φ · f1,2 of the pool, where φ is 1
6 .
That is, we want to choose sm to satisfy the following relationship, where s1 is the total
quantity of outstanding shares at time t1:
sm
sm + s1
= φ · f1,2 (5)
After some manipulation, including substituting 1 −
√
k1√
k2
for f1,2 and solving for sm, we
can rewrite this as:
sm =
√
k2 −
√
k1
( 1
φ − 1) ·
√
k2 +
√
k1
· s1 (6)
Setting φ to 1
6 gives us the following formula:
5Because Uniswap charges fees on input amounts, the fee relative to the withdrawn amount is actually
slightly higher: 1
1−0.003
− 1 = 3
997
≈ 0.3009203%.
6We can use this invariant, which does not account for liquidity tokens that were minted or burned,
because we know that fees are collected every time liquidity is deposited or withdrawn.
5
6. sm =
√
k2 −
√
k1
5 ·
√
k2 +
√
k1
· s1 (7)
Suppose the initial depositor puts 100 DAI and 1 ETH into a pair, receiving 10 shares.
Some time later (without any other depositor having participated in that pair), they attempt
to withdraw it, at a time when the pair has 96 DAI and 1.5 ETH. Plugging those values
into the above formula gives us the following:
sm =
√
1.5 · 96 −
√
1 · 100
5 ·
√
1.5 · 96 +
√
1 · 100
· 10 ≈ 0.0286 (8)
2.5 Meta transactions for pool shares
Pool shares minted by Uniswap v2 pairs natively support meta transactions. This means
users can authorize a transfer of their pool shares with a signature7
, rather than an on-chain
transaction from their address. Anyone can submit this signature on the user’s behalf by
calling the permit function, paying gas fees and possibly performing other actions in the
same transaction.
3 Other changes
3.1 Solidity
Uniswap v1 is implemented in Vyper, a Python-like smart contract language. Uniswap v2
is implemented in the more widely-used Solidity, since it requires some capabilities that were
not yet available in Vyper (such as the ability to interpret the return values of non-standard
ERC-20 tokens, as well as access to new opcodes such as chainid via inline assembly) at
the time it was being developed.
3.2 Contract re-architecture
One design priority for Uniswap v2 is to minimize the surface area and complexity of
the core pair contract—the contract that stores liquidity providers’ assets. Any bugs in this
contract could be disastrous, since millions of dollars of liquidity might be stolen or frozen.
When evaluating the security of this core contract, the most important question is
whether it protects liquidity providers from having their assets stolen or locked. Any feature
that is meant to support or protect traders—other than the basic functionality of allowing
one asset in the pool to be swapped for another—can be handled in a “router” contract.
In fact, even part of the swap functionality can be pulled out into the router contract.
As mentioned above, Uniswap v2 stores the last recorded balance of each asset (in order to
prevent a particular manipulative exploit of the oracle mechanism). The new architecture
takes advantage of this to further simplify the Uniswap v1 contract.
In Uniswap v2, the seller sends the asset to the core contract before calling the swap
function. Then, the contract measures how much of the asset it has received, by comparing
the last recorded balance to its current balance. This means the core contract is agnostic
7The signed message conforms to the EIP-712 standard, the same one used by meta transactions for
tokens like CHAI and DAI.
6
7. to the way in which the trader transfers the asset. Instead of transferFrom, it could be a
meta transaction, or any other future mechanism for authorizing the transfer of ERC-20s.
3.2.1 Adjustment for fee
Uniswap v1’s trading fee is applied by reducing the amount paid into the contract by
0.3% before enforcing the constant-product invariant. The contract implicitly enforces the
following formula:
(x1 − 0.003 · xin)) · y1 >= x0 · y0 (9)
With flash swaps, Uniswap v2 introduces the possibility that xin and yin might both
be non-zero (when a user wants to pay the pair back using the same asset, rather than
swapping). To handle such cases while properly applying fees, the contract is written to
enforce the following invariant:8
(x1 − 0.003 · xin) · (y1 − 0.003 · yin) >= x0 · y0 (10)
To simplify this calculation on-chain, we can multiply each side of the inequality by
1,000,000:
(1000 · x1 − 3 · xin) · (1000 · y1 − 3 · yin) >= 1000000 · x0 · y0 (11)
3.2.2 sync() and skim()
To protect against bespoke token implementations that can update the pair contract’s
balance, and to more gracefully handle tokens whose total supply can be greater than 2112
,
Uniswap v2 has two bail-out functions: sync()and skim().
sync() functions as a recovery mechanism in the case that a token asynchronously
deflates the balance of a pair. In this case, trades will receive sub-optimal rates, and if no
liquidity provider is willing to rectify the situation, the pair is stuck. sync() exists to set
the reserves of the contract to the current balances, providing a somewhat graceful recovery
from this situation.
skim() functions as a recovery mechanism in case enough tokens are sent to an pair to
overflow the two uint112 storage slots for reserves, which could otherwise cause trades to
fail. skim() allows a user to withdraw the difference between the current balance of the
pair and 2112
− 1 to the caller, if that difference is greater than 0.
3.3 Handling non-standard and unusual tokens
The ERC-20 standard requires that transfer() and transferFrom() return a boolean in-
dicating the success or failure of the call [4]. The implementations of one or both of these
functions on some tokens—including popular ones like Tether (USDT) and Binance Coin
(BNB)—instead have no return value. Uniswap v1 interprets the missing return value of
these improperly defined functions as false—that is, as an indication that the transfer was
not successful—and reverts the transaction, causing the attempted transfer to fail.
8Note that using the new architecture, xin is not provided by the user; instead, it is calculated by
measuring the contract’s balance after the callback, x1, and subtracting (x0 - xout) from it. This logic does
not distinguish between assets sent into the contract before it is called and assets sent into the contract
during the callback. yin is computed in the same way, based on y0, y1, and yout.
7
8. Uniswap v2 handles non-standard implementations differently. Specifically, if a transfer()
call9
has no return value, Uniswap v2 interprets it as a success rather than as a failure. This
change should not affect any ERC-20 tokens that conform to the standard (because in those
tokens, transfer() always has a return value).
Uniswap v1 also makes the assumption that calls to transfer() and transferFrom() cannot
trigger a reentrant call to the Uniswap pair contract. This assumption is violated by certain
ERC-20 tokens, including ones that support ERC-777’s “hooks” [5]. To fully support such
tokens, Uniswap v2 includes a “lock” that directly prevents reentrancy to all public state-
changing functions. This also protects against reentrancy from the user-specified callback
in a flash swap, as described in section 2.3.
3.4 Initialization of liquidity token supply
When a new liquidity provider deposits tokens into an existing Uniswap pair, the number
of liquidity tokens minted is computed based on the existing quantity of tokens:
sminted =
xdeposited
xstarting
· sstarting (12)
But what if they are the first depositor? In that case, xstarting is 0, so this formula will
not work.
Uniswap v1 sets the initial share supply to be equal to the amount of ETH deposited (in
wei). This was a somewhat reasonable value, because if the initial liquidity was deposited
at the correct price, then 1 liquidity pool share (which, like ETH, is an 18-decimal token)
would be worth approximately 2 ETH.
However, this meant that the value of a liquidity pool share was dependent on the ratio
at which liquidity was initially deposited, which was fairly arbitrary, especially since there
was no guarantee that that ratio reflected the true price. Additionally, Uniswap v2 supports
arbitrary pairs, so many pairs will not include ETH at all.
Instead, Uniswap v2 initially mints shares equal to the geometric mean of the amounts
deposited:
sminted =
√
xdeposited · ydeposited (13)
This formula ensures that the value of a liquidity pool share at any time is essentially
independent of the ratio at which liquidity was initially deposited. For example, suppose
that the price of 1 ABC is currently 100 XYZ. If the initial deposit had been 2 ABC and
200 XYZ (a ratio of 1:100), the depositor would have received
√
2 · 200 = 20 shares. Those
shares should now still be worth 2 ABC and 200 XYZ, plus accumulated fees.
If the initial deposit had been 2 ABC and 800 XYZ (a ratio of 1:400), the depositor
would have received
√
2 · 800 = 40 pool shares.10
The above formula ensures that a liquidity pool share will never be worth less than
the geometric mean of the reserves in that pool. However, it is possible for the value of
9As described above in section 3.2, Uniswap v2 core does not use transferFrom().
10This also reduces the likelihood of rounding errors, since the number of bits in the quantity of shares
will be approximately the mean of the number of bits in the quantity of asset X in the reserves, and the
number of bits in the quantity of asset Y in the reserves:
log2
√
x · y =
log2 x + log2 y
2
(14)
8
9. a liquidity pool share to grow over time, either by accumulating trading fees or through
“donations” to the liquidity pool. In theory, this could result in a situation where the value
of the minimum quantity of liquidity pool shares (1e-18 pool shares) is worth so much that
it becomes infeasible for small liquidity providers to provide any liquidity.
To mitigate this, Uniswap v2 burns the first 1e-15 (0.000000000000001) pool shares that
are minted (1000 times the minimum quantity of pool shares), sending them to the zero
address instead of to the minter. This should be a negligible cost for almost any token
pair.11
But it dramatically increases the cost of the above attack. In order to raise the
value of a liquidity pool share to $100, the attacker would need to donate $100,000 to the
pool, which would be permanently locked up as liquidity.
3.5 Wrapping ETH
The interface for transacting with Ethereum’s native asset, ETH, is different from the
standard interface for interacting with ERC-20 tokens. As a result, many other protocols on
Ethereum do not support ETH, instead using a canonical ”wrapped ETH” token, WETH
[6].
Uniswap v1 is an exception. Since every Uniswap v1 pair included ETH as one asset, it
made sense to handle ETH directly, which was slightly more gas-efficient.
Since Uniswap v2 supports arbitrary ERC-20 pairs, it now no longer makes sense to
support unwrapped ETH. Adding such support would double the size of the core codebase,
and risks fragmentation of liquidity between ETH and WETH pairs12
. Native ETH needs
to be wrapped into WETH before it can be traded on Uniswap v2.
3.6 Deterministic pair addresses
As in Uniswap v1, all Uniswap v2 pair contracts are instantiated by a single factory
contract. In Uniswap v1, these pair contracts were created using the CREATE opcode,
which meant that the address of such a contract depended on the order in which that pair
was created. Uniswap v2 uses Ethereum’s new CREATE2 opcode [8] to generate a pair
contract with a deterministic address. This means that it is possible to calculate a pair’s
address (if it exists) off-chain, without having to look at the chain state.
3.7 Maximum token balance
In order to efficiently implement the oracle mechanism, Uniswap v2 only support reserve
balances of up to 2112
− 1. This number is high enough to support 18-decimal-place tokens
with a totalSupply over 1 quadrillion.
If either reserve balance does go above 2112
− 1, any call to the swap function will begin
to fail (due to a check in the _update() function). To recover from this situation, any user
can call the skim() function to remove excess assets from the liquidity pool.
11In theory, there are some cases where this burn could be non-negligible, such as pairs between high-value
zero-decimal tokens. However, these pairs are a poor fit for Uniswap anyway, since rounding errors would
make trading infeasible.
12As of this writing, one of the highest-liquidity pairs on Uniswap v1 is the pair between ETH and WETH
[7].
9
10. References
[1] Hayden Adams. 2018. url: https://hackmd.io/@477aQ9OrQTCbVR3fq1Qzxg/HJ9jLsfTz?
type=view.
[2] Guillermo Angeris et al. An analysis of Uniswap markets. 2019. arXiv: 1911.03380
[q-fin.TR].
[3] samczsun. Taking undercollateralized loans for fun and for profit. Sept. 2019. url:
https://samczsun.com/taking- undercollateralized- loans- for- fun- and-
for-profit/.
[4] Fabian Vogelsteller and Vitalik Buterin. Nov. 2015. url: https://eips.ethereum.
org/EIPS/eip-20.
[5] Jordi Baylina Jacques Dafflon and Thomas Shababi. EIP 777: ERC777 Token Standard.
Nov. 2017. url: https://eips.ethereum.org/EIPS/eip-777.
[6] Radar. WTF is WETH? url: https://weth.io/.
[7] Uniswap.info. Wrapped Ether (WETH). url: https://uniswap.info/token/0xc02aaa39b223fe8d0a0e5c4f27e
[8] Vitalik Buterin. EIP 1014: Skinny CREATE2. Apr. 2018. url: https://eips.ethereum.
org/EIPS/eip-1014.
4 Disclaimer
This paper is for general information purposes only. It does not constitute investment
advice or a recommendation or solicitation to buy or sell any investment and should not
be used in the evaluation of the merits of making any investment decision. It should not
be relied upon for accounting, legal or tax advice or investment recommendations. This
paper reflects current opinions of the authors and is not made on behalf of Paradigm or its
affiliates and does not necessarily reflect the opinions of Paradigm, its affiliates or individuals
associated with Paradigm. The opinions reflected herein are subject to change without being
updated.
10