Flash swaps are an integral feature of Uniswap V2. In fact, under the hood, all swaps are actually flash swaps! This simply means that pair contracts send output tokens to the recipient before enforcing that enough input tokens have been received. This is slightly atypical, as one might expect a pair to ensure it's received payment before delivery. However, because Ethereum transactions are atomic, we can roll back the entire swap if it turns out that the contract hasn't received enough tokens to make itself whole by the end of the transaction.
For the sake of example, let's assume that we're dealing with a DAI/WETH pair, where DAI is token0 and WETH is token1. amount0Out and amount1Out specify the amount of DAI and WETH that the msg.sender wants the pair to send to the to address (one of these amounts may be 0). At this point you may be wondering how the contract receives tokens. For a typical (non-flash) swap, it's actually the responsibility of msg.sender to ensure that enough WETH or DAI has already been sent to the pair before swap is called (in the context of trading, this is all handled neatly by a router contract). But when executing a flash swap, tokens do not need to be sent to the contract before calling swap. Instead, they must be sent from within a callback function that the pair triggers on the to address.
To differentiate between the "typical" trading case and the flash swap case, pairs use the data parameter. Specifically, if data.length equals 0, the contract assumes that payment has already been received, and simply transfers the tokens to the to address. But, if data.length is greater than 0, the contract transfers the tokens and then calls the following function on the to address:
The logic behind this identification strategy is simple: the vast majority of valid flash swap use cases involve interactions with external protocols. The best way to pass information dictating how these interactions happen (function arguments, safety parameters, addresses, etc.) is via the data parameter. It's expected that data will be abi.decoded from within uniswapV2Call. In the rare case where no data is required, callers should ensure that data.length equals 1 (i.e. encode a single junk byte as bytes), and then ignore this argument in uniswapV2Call.
At the end of uniswapV2Call, contracts must return enough tokens to the pair to make it whole. Specifically, this means that the product of the pair reserves after the swap, discounting all token amounts sent by 0.3% LP fee, must be greater than before.
In the case where the token withdrawn is not the token returned (i.e. DAI was requested in the flash swap, and WETH was returned, or vice versa), the fee simplifies to the simple swap case. This means that the standard getAmountIn pricing function should be used to calculate e.g., the amount of WETH that must be returned in exchange for the amount of DAI that was requested out.
In the case where the token withdrawn is the same as the token returned (i.e. DAI was requested in the flash swap, used, then returned, or vice versa with WETH), the following condition must be satisfied:
It may be more intuitive to rewrite this formula in terms of a "fee" levied on the withdrawn amount (despite the fact that Uniswap always levies fees on input amounts, in this case the returned amount, here we can simplify to an effective fee on the withdrawn amount). If we rearrange, the formula looks like:
Both Uniswap V2 and V3 implement flash loans: unlimited and uncollateralized loans that must be repaid in the same transaction. Pools give users arbitrary amounts of tokens that they request, but, by the end of the call, the amounts must be repaid, with a small fee on top.
The fact that flash loans must be repaid in the same transaction means that flash loans cannot be taken by regular users: as a user, you cannot program custom logic in transactions. Flash loans can only be taken and repaid by smart contracts.
I am quite new to flash loan and I don't fully understand it. I've been reading on flash loan attacks lately and notice often times it involves a huge dump on Uniswap to skew the price of a coin. I am wondering if I can take out a flash loan, say 10000 ETH from AAVE, and dump all that in Uniwap to exchange BTC. Is this going to increase the price of BTC for a short time (a few seconds)? If yes, then what I can do is I immediately sell some of my own BTC on Uniswap after I skewed the price of BTC with the flash loan and buy it back when the price corrects itself. I don't even need to pay back the flash loan since all I need is to skew the price for a short moment (a few seconds) and do arbitrage with my own holdings. Pretty sure I'm missing something here but I don't know which part is wrong.
My second part of the question is say during a flash loan attack I manipulated a price of some coin. If a user queries the price of that coin in the middle of my flash loan attack, is that user seeing the manipulated price or the normal price?
No. Flash loans are opened and terminated within the same transaction. The "time" per see is infinitely small. This guarantees the borrower does not run away with the loan. The transaction fails unless the loaned money is returned by the end of the transaction.
You can now use npx hardhat to generate a Hardhat project. Following the instructions create a TypeScript project and answer yes to the rest of the questions. This will generate the necessary files and install the required dependencies.
You wouldn't want to share your API key with the whole world. To avoid this you will create a .env file, this SHOULD NOT be committed to version control. Double-check that you have .gitignore a file at the root of your project with the following content.
Before diving into creating the contract a little bit of theory might help you better understand what we doing here. For each token pair, Uniswap has what is called a liquidity pool. For example, let's say you have ETH/USDC token pair, you could think of the liquidity pool as one big vault that is split into two sections. One section would hold X amount of ETH while the other section would hold the equivalent amount in USDC.
When you create a flash loan on Uniswap essentially what you doing is taking liquidity out of the pool and putting it back in a single transaction. Using the vault example above, you borrow some ETH or USDC from the vault and immediately put it back before anyone notices.
Inside the contracts directory create a new file called Flashloan.sol and copy the above contents into it. While you are at it go ahead and create two new directories called interfaces and libraries you will make use of this shortly.
When deploying the contract the constructor takes three parameters. _token0 and _token1 are the addresses of the tokens that will form a pair, as mentioned at the beginning of this section. The _fee refers to the swapping fee of the token pair pool. As of Uniswap v3, there are four fee levels 0.01%, 0.05%, 0.30%, and 1%.
Similar to the IERC20 interface, the IUniswapV3Pool interface is used to interact with theUniswapV3Pool contract. You can find a reference to this on Uniswaps' GitHub repository here. However, the only action you should be interested in is the flash function, which is what you will use to perform the flash loan. A more simplified version of this interface would look like this.
To do this you need to make use of the PoolAddress library provided by Uniswap. Inside the libraries directory, create a new file called PoolAddress.sol. Copy the content below into the file you just creates.
At this point, you are free to do what you want with the borrowed amount. Maybe leverage your position while yield farming or taking advantage of an arbitrage opportunity. As long as you cover the gas fees and pay back the amount borrowed in a single transaction.
Version 2.0 of Uniswap is now live and it is, among other things, an amulet-minting machine, though probably everyone's still going to call them "tokens." Tokens are little more than keys that allow you to access something, such as a game or a laundry machine. Amulets have surprises inside; they can generate something new from within, for anyone with the skill to unlock them.
"Version 1 was almost this like proof-of-concept," Hayden Adams, Uniswap's founder, told CoinDesk. "It was the first implementation of this protocol. It got a lot of things very right. And that's proved by usage and traction."
Uniswap is a system on Ethereum for trading any ERC-20 token for any other, using Ethereum's core cryptocurrency, ETH, as the medium of trade. It currently has $43 million of liquidity (assets locked into the protocol) with $13 million in activity on the platform in the last 24 hours, according to Uniswap.info. It's one of the key so-called "financial primitives" powering decentralized finance (DeFi).
This is likely to lead to unexpected use cases, but the most obvious use out of the box is a new way to use stablecoins. Popular ERC-20s like MKR, ZRX, WBTC, OMG and others are very likely to be quickly paired up with stablecoins, such as USDT, USDC and dai.
Coinbase has already added liquidity to the ETH/USDC pair on Uniswap v1, after all. "Having stablecoin pairs on Uniswap is a pretty huge improvement. It's probably the most requested thing since Uniswap launched," Adams said.
The top-line advantage of having a direct pair of any two tokens is it should lower transaction fees for trades (v1 always requires two trades between any two ERC-20s). Another advantage: It allows liquidity providers to lower their volatility on one side of a pool. A MKR/ETH pool is volatile on both ends, but a MKR/USDT pool should only be volatile on the MKR side. "A lot of people don't want the ETH exposure," Adams said.
As mentioned above, these token pairs are created by users. If someone thinks WCK (wrapped CryptoKitties) and SOCKS (actual socks) should have a token pair, then they can set it up. Users pay a tiny fee to the liquidity pool for each trade (0.3%) and that ultimately goes back to liquidity providers (each gets it proportional to how much of the pool they have posted).
c80f0f1006