 Hello all, welcome to the Flash Loans talk. My name is Andhra Joseph. I am a blockchain security engineer at Coinbase. I have been a speaker and a trainer in the past Black Hat, DefCon, Hack in the Box, and Alcon conferences. I'm interested in distributed systems, obviously, blockchains, and machine learning and memes. Let's go over the agenda for today's talk. We'll initially go over what are crypto loans, like regular loans, but in DeFi. We'll take a loan using Aave, which is one of the Flash Loans providers. We'll talk about what Flash Loans are. We'll use a tool called Brownie to interact with smart contracts. It is a Python-based tool, and it's really easy to use. We'll have a Flash Loan demo, and we'll also do an arbitrage towards the end of the talk. I'll share some resources where you can learn more. What is over collateralization? It sounds like a really complex word, right? But let's think of it as from the perspective of a regular loan. When you go to the bank to get a loan, you would put up your house as collateral. If you're taking a house loan, that is. And that assures the bank that you will make a repayment, because if you don't, they can take your house. And the loan value will always be lower than the market value of your house. But you would wonder, right, how can the bank hedge against changes in the market price, right? Things can go up and down. So they would have a certain amount of safety, that is the margin, when they approve a loan. And how do they make money? You obviously pay an interest on your loan. And crypto loans are mostly over-collateralized, but Flash Loans are an exception. So let's look at how we can take a loan from Aave using your browser and a wallet. To do that, you need some collateral. And we can use TestEther that you can get from a faucet, as noted here in the slides. And then we can use the TestNet Aave, which is the loan provider, to test our understanding, right? So let's get into it, all right? So here we are in the Aave TestNet, and I'm connecting my browser metamask, which is a wallet. And that is what we see here. That is the collateral that I have, test collateral that I have. And this is the dashboard where I can see what have I borrowed, what is my collateral. And to take a loan, you have to, first of all, provide some collateral, because it's an over-collateralized loan, right? And you can see that I have some deposits. And now we can add more collateral if we wish to. If we add collateral, we'll earn an APY on your collateral, which is interest. And here I'm adding some collateral, some more collateral, to my position in Aave. And when I click on the deposit, the app asks me to sign a transaction. And I will do that with my wallet. In this case, it is metamask, which has my private keys. If you click on that particular transaction, you can see either scan where you can explore the details of the transaction. And as you can see, the transaction is successful. And now we see that our current balance has increased. Now let's borrow some USDC. And as you can see, when I drag the slider across, I can borrow more, but it's a lot more risk. So what do I mean by a lot more risk, right? If you have a very high risk loan, you are very likely to get your position liquidated. Because for the protocol to stay solvent, they have to make sure that your loan never goes under. And to do that, the protocol will sell under collateralized loans at a discount to the market. And the participants that would liquidate your loans get to buy these collateral at a lower price. So that is how they are incentivized. Now once we have set up a safe health factor, we would want to select if you want a stable APY or a variable APY. For demo purposes, we will just go with a variable APY. And this would give us all the details of our loan. We would click Borrow, and then we can sign the transaction. We can explore the details of the transaction in either scan. And now when you look at your dashboard, you have USDC. So you effectively took a USDC loan against your collateral, which is ETH. And that's how you would take a loan against your collateral. Now let's look at Brownie. Because we just used a web browser and the browser extension, which is our wallet, to interact with a smart contract. And the web browser displays the front end to the smart contract, which are called DAPS. What if we want to directly interact with smart contracts? So Brownie is a Python-based development and testing framework for smart contracts targeting the Ethereum virtual machine. Now we will take a loan from our way using Brownie. We will get familiar with the Brownie API. And we'll also configure our Infura, Alchemy, and other scan keys. These are just node providers that Brownie can use to interact with the main net. So as you can see here, I have my secrets exported and I have started a main net fork. What is a main net fork? So Brownie creates a local version of the current Ethereum blockchain state that we can interact with without spending real funds. As you can see, this is a fork. And then we work on that particular fork. And we will fork at a particular block. Now we get a contract, a reference to a contract. And this is how you can get a reference to a contract. And that particular contract is the Wrapped ETH contract on the main net. And then we make a deposit. And we can check that we have some Wrapped ETH. So DeFi, most DABs prefer Wrapped ETH because it confirms to ERC-20 standards, which makes it easier to work with. And we can use the Web 3 provider to make it readable. And as you can see, the contract for the RA lending pool is also in here, which is required. So we can take a loan from Aave. Next, we approve. And then we can take a loan, right? So it is important that we approve Aave lending pool so to spend the funds so that this can work. It's just how ERC-20s work. And now we can see that we can make a deposit. And that is available in the transaction info, which you can get by calling dot info to the reference of the transaction. And once you deposit, you would have tokens that represents your position in RA, which is the contract that we are grabbing here. And as you can see, we have some balance. Again, this can be transformed to easily readable numbers using Web 3. And now we will be checking what's the amount of ETH that's available to borrow from. And we deposited a certain amount that you can see here. Now, because we are taking an over-collateralized loan, we cannot take a loan against all the collateral that we have. So there needs to be a health factor. And we also need the price of the asset, which you can get from a price Oracle. So you would get the current price, which is inside that array. And you would calculate the amount of ERC-20 that you can borrow with a particular health factor that you agree to. And we can look at what that is. And now we can send a transaction to the RA lending pool. And that should give us that particular loan. So in this case, we are taking a die loan. So we would grab the die contract from Mainnet. And then we can do a balance on the account. And you will see that we actually got a die loan against our draft ETH. And we can again use Web 3 to make it readable if you want. Yeah. So that's how easy it is to take a loan using Brownie, completely scripted. And you can see that we have that much amount of die in our account right now. Now, what's the deal about flash loans, right? So it was easy to take a regular loan from our way. But what are flash loans? Flash loans are the first unsecured loan option in DeFi, which means you don't need to put down any collateral. I mean, that sounds wild, right? Why would someone give you a loan like that? They have been used for arbitrage, flash liquidations, collateral swaths, and flash loans. It looks very attractive. So let's get into it. So how can someone provide no collateral loans? Some of the primitives that is required to provide such a loan is that a transaction on the network can be undone as long as it is reverted before it finishes. And so with a flash loan, the lender has the power to revert everything that happened in that transaction if their requirements are not met, which is basically they should get their money back within the same transaction plus some interest. So that is basically what no collateral loans are. And to actually make a flash loan, we would have to write some code. And Brownie has some templates, which has made it very easier to do a flash loan. And we will be exploring that. So this is the smart contract or the course part of the smart contract that we will be deploying to our mainnet fork so that we can make a flash loan. As you can see, there are three modes. One is zero, the no debt, which is basically a flash loan. The one and two represents a stable loan and a variable APR loan, which we observed earlier on. So we will be setting the mode to zero and we will be calling the rw lending pool dot flash loan. And these are self-explanatory. So this is the main function that enables this flash loan. And this is part of the smart contract that you would get when you use that particular Brownie mix. So in this demo, we will be taking a flash loan from our way using this Brownie mix template. We'll also get familiar with the flash loan API. And later on, we will try an arbitrage. So let's start a mainnet fork. And this is how you would do that. You grab the wrapped EAP contract from the mainnet, get a reference to it. Then you deposit some ether so you can have some wrapped ether to do all your DeFi magic with. So that is essentially what happened here. As you can see, we have some balance, which is expected. Now you can make it readable using the Web3 helpers. As you can see, we have NAND wrapped ether. You again, get a reference to the rw lending pool. And you can use this lending pool to do your flash loan as well. We earlier used this to get a regular overcollateralized loan. But now we are going to deploy the flash loan contract to the mainnet fork. And we will grab a reference to that flash loan contract so we can interact with it later on. As you can see, we have a reference to the flash loan now. Flash loan contract deployed on the mainnet fork. In this case, we need to pay back the loan provider before the end of the flash loan as the transaction would reward. But so for testing purposes, we will fund the flash loan contract with some test either so that the transaction doesn't fail. And you can see that we called the trans flash loan function. And we successfully did a flash loan. And this transaction info basically gives us information about our flash loan. So we wrapped some ether, we deposited. We have some interest bearing wrapped eth in a way. And we repaid the flash loan. So it's basically we got some collateral, we wrapped it, we took a flash loan, and then we repaid it. So we didn't do anything fancy with this collateral, but we'll be doing that in the upcoming demos. So one of the cool things that we are interested in to learn more are flash loan attacks. And we have a lot of these attacks, but we'll go over some of these in this presentation. The one attack that you guys might be interested in is a pump and an arbitrage, which basically means the pump of the price of a token pair on an automated market maker with leveraged funds. It could be in a margin trade. And as a result, the hacker would purchase these assets at a cheaper price because they basically distorted the price on this particular tax. The other one, other kind of attack is an oracle price manipulation attack. And that basically means a DAB, which uses some AMMs price feed as an oracle, can be manipulated using flash loans because of the way AMMs work. And not every oracle provided by the AMMs are resistant to flash loans. We can also exploit logical bugs. And that's a big topic. And that basically means that economic flaws or business logic flaws, which are economic exploits, can be exploited with a great amount of capital because of flash loans. Without flash loans, it would require you to have a lot of capital. But flash loans allow everyone to leverage capital and deal with inefficiencies in the space. So let's look at in detail about oracle price manipulation. So here we have a flow chart which shows an oracle price manipulation attack. It starts with the attacker borrowing a certain amount of ETH from a flash loan provider exchanging that ETH for synthetic USD and later depositing some ETH for more SUSD. And then using those acquired SUSD to manipulate the price on a DAX, which allows the attacker to cause a huge slippage and profit from it. So let's just explore how this is done. So initially, there's a flash loan of 7,500 ETH ETH on BCX. And then the attacker would convert their ETH to SUSD on Uniswap and Kiber. And they would deposit a certain amount of ETH to synthetics to get more SUSD. So at this point, the attacker has a lot of SUSD. So in total, about 4,417 ETH is converted to this much amount of SUSD at an average price of 249 SUSD per ETH. The price of Uniswap and Kiber are collectively used as a price oracle on BCX. So that's the trick here. Because of that reason, the adversarial trader takes a loan by collateralizing all the SUSD that he has acquired to borrow a certain amount of ETH. And that is at a price of 162 SUSD per ETH on BCX. And given that, we also have some unspent ETH from the flash loan, which is around 3,000 ETH. So adding all that up, because we have about 1,882 ETH right now, we can repay the flash loan we took plus the premium and still keep 2,382 ETH as a profit from this flash loan. That is essentially what the exploit is. And if you would like to learn more, I would totally recommend reading this research paper that I have the link for in the resources page later on in the presentation. So as you can see, there's a lot of arbitrage going on here. What is arbitrage? Arbitrage is the practice of taking advantage of a price difference between two or more markets, a striking combination of matching these that capitalize upon the imbalance. The profit being the difference between the market prices at which the unit is traded. In our case, we will be doing an arbitrage between two dexes, which is uniswap and sushi swap. So let's go over our arbitrage strategy. So we would take a flash loan from Aave, and we will borrow ETH. We will then call the uniswap V2 to wrap ETH into wrapped ETH, and then exchange it for die tokens on uniswap. Then we'll check the exchange rate of die back into ETH on sushi swap, which is a completely different dex. Then we will call the sushi swap router to swap the die back into wrapped ETH and then to ETH. If there is a price difference between uniswap and sushi swap, then we can arbitrage the difference. We can go either from uniswap to sushi swap, or we can go from sushi swap to uniswap. We then pay back the flash loan, which is the amount that we borrowed initially, plus the premium for the flash loan, and keep any difference. So then testing, we can fund the contract with some test either so your execution won't revert because this price difference doesn't exist all the time. Intuitively, you can think that in times of high volatility, you could see the price difference between multiple dexes varying at a greater percentage rate. So you could fork at a particular block when this particular dex is diverged from the market price, and then execute the strategy, and that is one way to test it without funding the contract. But for a piece of testing, we'll pre-fund the contract. You can also take a look at this contract and learn more the sources linked here. And this is one of the important functions in the arbitrage smart contract. So here you can see that we are integrating with the uniswap router, and then we are approving dye to be spent, and then we are also trying to swap funds using the socioswap router. So essentially, that is the logic of the smart contract. Now let's look at the demo. So as usual, we would start our brownie console mainnet fork, and right here, you can see that we are importing the smart contract that we just looked at, and we are also deploying this particular smart contract right after that. So to deploy the smart contract, we need some parameters. So let's look at what are the parameters required for the smart contract deployment. So you would need the RWA landing pool, the uniswap router, and the socioswap router. You can see that being highlighted here. So the first one is the RWA landing pool. The second one is the uniswap router, and the third address is the socioswap router. And the last item is just the account in which the funds will be spent. Once we have that deployed, we can actually do the flash loan, and flash loans also take some parameters. But before that, as explained before, for the ease of testing, we can transfer some funds to our flash loan contract. So the execution won't reward if there isn't an arbitrage available right now between these token pairs and these nexus. And if you look at this transaction, we can see that we have provided a bunch of parameters to the flash loan contract. So the first parameter is the asset that we want to borrow using the flash loan. And that is ether. And this is how you would represent ether. And then we have the amount that you want to flash borrow, right? And this basically represents one ether. And the next address is the die token address on the mainnet. And the next parameter is the amount that we need to trade, which is the amount that we borrowed. And the next item for the next parameter is the amount of tokens that we need to swap back to complete the arbitrage. So we are basically doing die, right? So that is the amount of die that we need to swap back. And let's look at the transaction. You can see that we've wrapped ether, because as explained earlier, wrapped ether is much easier to deal with within DeFi applications. So that is why you would wrap ether first. And then we have it converted to die, like die stablecoin on Uniswap. And then later on, we will convert die back to, like, wrapped ether, as you can see here, on SushiSwap. And then we will again convert wrapped ether to, like, ether. And if there was a price difference, we would make a profit after paying back the smart contract. Now that we have looked at arbitrage and some of the hacks, some of the hacking techniques using flash loans. How can we defend against these attacks? So some of my observations are it's important to write test cases. And security audits can certainly help uncover bugs. But it's also very important to simulate various market conditions. And fusing can help a lot here. For example, when your contract integrates with multiple other contracts, it is very important that we understand the behavior of the participants and how certain behavior will affect your logic. So that is what I mean by simulating various marketing market conditions. We should also verify your Oracle implementations. So if you were to just grab your price feed from some on-chain DEXS, without any verification of that price feed, it is very likely that that price feed can be manipulated by techniques that was explained earlier. I would certainly recommend reading the blog posts that I have linked down below, which goes into much detail about how something like that can be done. Uniswap has this time-weighted price average Oracle. I hope I said that right, which aims to mitigate some of this. There is also the audit for that Oracle that I have linked down below. I again would recommend double-checking any custom logic that you have, and triple-checking when you integrate with other contracts. These are some of the resources that have been used in this presentation, which was very helpful. And I would recommend you look at these as well. All of these has code that you can try it out. And there is code for doing an arbitrage that we had a demo for earlier in this presentation. If you want to try out your own flash loan strategies, we have a brownie mix for that. If you would like to do other strategies in DeFi, there is links to that as well. So I hope this was useful. And thank you. Thank you for listening.