PatrickAlphaC (@patrickalphac) • Hey
🐸 #Blockend Engineer & Advocate 🥑
🏋️♂️Lover of all things smart contracts 🐍
🌲 linktr.ee/PatrickAlphaC 🌴
Views are my own.
Publications
- Ooo. Looks like if you transfer your lens NFT to a new address, it removes everyone you're following?
- ITS FINALLY HERE
🎊🎉🎊🎉🎊🎉🎊🎉🎊🎉🎊🎉
The Ultimate, Learn Blockchain Development, Solidity, AI-Powered Smart Contract Course | Foundry Edition sponsored by @CyfrinAudits!
🎊🎉🎊🎉🎊🎉🎊🎉🎊🎉🎊🎉
Here is everything you'll learn from this course, and more 👇
You can find parts 1 - 3 (A new YouTube cap of 12 hours means I had to split it up!)
🔗 Here's a link to part 1 of the course, with parts 2 and 3 on my YouTube.
After 2+ months of pouring every ounce of information into a video, this is where we have arrived - with 27+ hours of pure KNOWLEDGE.
https://www.youtube.com/watch?v=umepbfKp5rI
As many of you know, I've made a monster course every year for the past 3 years, dumping all my knowledge into a video so we can bring everyone in web3 up to speed quickly.
We chose Foundry this year because it is becoming the go-to tool for smart contracts and security researchers alike.
Here is a link to the entire course curriculum.
https://github.com/Cyfrin/foundry-full-course-f23
The best part of this year, is that since the course is in pure solidity, there are absolutely ZERO prerequisites, meaning anyone can take the course no matter where you are in your journey!
Additionally... We will teach you advanced AI prompting techniques so you can get up to speed FASTER THAN EVER BEFORE.
I can say with assurance that if you're looking to get started in Web3, Solidity, or become a blockchain developer, this is 100% the place to go.
I've poured my soul into this content, and we've been able to help thousands of developers in the past, with many developers surpassing me at their skill of smart contract development.
Here are some of the technologies, industries, and groups we will teach you:
- Solidity
- Foundry
- Chainlink
- MetaMask
- AlchemyPlatform
- EthereumRemix
- Openzeppelin
- trailofbits
- NFTs
- #Ganache
- etherscan
- AaveAave
- IPFS
- Governance
- Filecoin
- opensea
- ERC20s
- pinatacloud
- nft_storage
- arbitrum
- #Ethereum
- github
- Upgradable Smart Contracts
- code
- DefiLlama
- RektHQ
- Stablecoins
- DAOs
- compoundfinance
- OpenAI
- ChatGPT
- Fuzzing
- Symbolic Execution
- Smart Contract Auditing
And SO much more!
🔁 ❤️ Please smash this tweet a link and a retweet so we can bring web3 and blockchain to the masses by ushering the next generation of smart contract engineers.
And in case you missed it, here is the link to the video again.
Good luck, have fun, let's make the second half of this year for the builders & devs of the space.
Go Web3!!!!!
🦾🦾🦾🦾🦾🦾🦾
- 🚨 The secret to finding CRIT vulnerabilities easily is...
🐈 Fuzz Tests
(Sometimes known as invariant tests in Foundry)
Fuzz Testing or Fuzzing is when you supply random data to your system to break it.
There are two kinds of Fuzzing:
💨 Stateless Fuzzing: Fuzzing/Fuzz Testing where the state of a previous run is discarded for the next run.
🧱 Stateful Fuzzing: The state of our previous fuzz run is the starting state of our next fuzz run.
To see me do a breakdown of these concepts in video and all my balloon non-sense, be sure to watch my video or read my blog on the topic too!
https://www.youtube.com/watch?v=juyY-CTolac
Stateless fuzzing is often easier and faster to setup, while stateful fuzzing is really what you want to aim for.
But before you go write your fuzz tests, you need to understand your systems "invariants" or "properties"
Invariant: The property of the system that should always hold.
Only then, can you attempt to throw random stuff at your code to break it.
In DeFi an invariant might be:
- Can't withdraw more than staked
- Reserve balance must always be higher than debt, etc
Now it's impossible for a fuzzer to go through every scenario, so understanding how the random number selection is done is crucial.
@trailofbits echidna combined with their symbolic execution tool maat does a fantastic job at using math to find breaking points with fuzzing.
At @CyfrinAudits we use this method to find vulnerabilities quickly, and recommend all developers implement them, even before going to audit!!
1. Understand your invariants
2. Write stateful fuzz tests for them
3. Don’t go to an audit before you've done this.
4. If you do, ensure your auditors help you understand your invariants!
Let's stay safer out there Web3!
- 🌪️ What's happening with Tornado Cash and Coinbase is STILL one of the most important battles happening today in Web3.
Let me explain, or just watch my video.
https://www.youtube.com/shorts/6QI5WjaW8Zo
1. We need legal wins
Imagine a world where all governments bad using crypto.
Sure we can go prohibition style, but people already drank then, we haven't even brought Web3 to the masses!
We need to make it EASIER not HARDER to get into Web3.
2. The Tornado Cash ban was wrong
T-Cash is a privacy-preserving protocol, and as @coinbase backed motion says it violates freedom of speech and isn't even a sanctionable entity.
We would like them to undo this ban yes? Ok well then we need someone to fight it.
So is anyone showing up?
NO! Most of Web3 won't touch this with a 10-foot pole, and a TON of protocols and groups started banning T-Cash-related stuff because they were terrified the SEC would come after them.
I had blogs reject some of my posts due to their fear!
Coinbase is showing up.
Some are saying they have ulterior motives.
Frankly, I don't care. I'm happy we have someone fighting.
And if they have something nefarious planned we can hunger games them after they win.
I'm not sure how else to help other than vote and email my senators (to which @SenWarren and @EdMarkey have given me "hey sorry we too busy" answers)
So I decided to paint myself blue to call attention to it.
Let's go Coinbase.
- 🌪️ What's happening with Tornado Cash and Coinbase is STILL one of the most important battles happening today in Web3.
Let me explain, or just watch my video.
https://www.youtube.com/shorts/6QI5WjaW8Zo
1. We need legal wins
Imagine a world where all governments bad using crypto.
Sure we can go prohibition style, but people already drank then, we haven't even brought Web3 to the masses!
We need to make it EASIER not HARDER to get into Web3.
2. The Tornado Cash ban was wrong
T-Cash is a privacy-preserving protocol, and as @coinbase backed motion says it violates freedom of speech and isn't even a sanctionable entity.
We would like them to undo this ban yes? Ok well then we need someone to fight it.
So is anyone showing up?
NO! Most of Web3 won't touch this with a 10-foot pole, and a TON of protocols and groups started banning T-Cash-related stuff because they were terrified the SEC would come after them.
I had blogs reject some of my posts due to their fear!
Coinbase is showing up.
Some are saying they have ulterior motives.
Frankly, I don't care. I'm happy we have someone fighting.
And if they have something nefarious planned we can hunger games them after they win.
I'm not sure how else to help other than vote and email my senators (to which @SenWarren and @EdMarkey have given me "hey sorry we too busy" answers)
So I decided to paint myself blue to call attention to it.
Let's go Coinbase.
- Over the next decade, demand for knowledge workers will continue to diminish.
But not at the highest level.
Education is still critical, and AI will augment our learning journeys.
👇 Let me explain.
For the next decade (maybe shorter), you can think of AI as "statistics on steroids."
It is constantly predicting responses based on all the data it has been fed previously.
Knowing this, the flaw becomes apparent. At this time in history, AIs have a hard time with situations they have never seen before.
In 2016, AI was said to have surpassed human Go players by defeating the world Go champions.
However, just this year, some amateurs decided to try to beat these top bots by making "poor" moves the AI had never seen before, and they were able to consistently win 14/15 games.
https://arstechnica.com/information-technology/2023/02/man-beats-machine-at-go-in-human-victory-over-ai/
Standford Artificial Intelligence Research in Education (AIRE) director Dr. Li Jiang says:
"Humans are better at zero to one"
Knowing this, we need to continue to focus on education because we need to be the ones to push AI into the next phase, where it can be better than humans at creating things that have never been seen before.
- Want to learn the exact process Damn Vulnerable DeFi creator Tincho uses to audit a smart contract?
I bet you do.
You see exactly how a professional auditor works in this video!
https://www.youtube.com/watch?v=A-T9F0anN1E
- For the next few weeks we at the ⛨ Cyfrin team will be streaming a LIVE web3 solidity audit from a paid protocol.
As far as we know, this has never been done before.
For those of you looking to follow along to see an end-to-end audit as it happens LIVE here are the details you need to know 👇
🐸️ 1. You can follow along and watch me and our team at @CyfrinAudits work over the next few weeks here on twitch.
https://www.twitch.tv/patrickalphac
I will do my best to steam everything I can. This is undeployed code, so we shouldn't find any live exploitable issues. Sometimes, I will need to turn off the camera, but I'll try to stream as much as possible so you can see the inner workings.
⛲️ 2. We will be working on the @BeanstalkFarms's new Wells implementation.
As you already know, decentralized stablecoins are essentail to the success of web3 and DeFi, and especially as we've seen over this past week, the "decentralized" aspect of a stablecoin is more important than ever.
💰 If you're unfamiliar with stablecoins, be sure to watch this video I made a few months back.
https://www.youtube.com/watch?v=pciVQVocTYc
👯♂️ 3. We will not be working alone!
Teamwork makes the dreamwork.
1 auditor == 1 person of work
2 auditors == 4 people of work
Bouncing ideas off each other aggressively is important, and we will do this in the steam. We at Cyfrin have many ideas boards which I won't show on stream, but I'll say when I'm dropping an idea on the board.
🫘 4. We will not be working alone (part 2!)
A private audit with a company is more than just the report. We are looking at:
- How good the docs are
- How mature testing is
- Any best practices to be followed
Constant communication with the protocol devs is all part of the security journey, especially for a private audit.
- In a competitive audit, the product is the report.
- In a private audit, the product is the security journey, best practices & feedback, AND the report.
I will not be sharing the chat between us and Bean developers, however I will be mentioning when I ask them questions.
🟢 5. We will be starting in the next half hour
I will not be responding to twitch chat as I audit, however, I need to take breaks. So please add questions into the chat and I will get to them once I reach a break.
Please leave feedback and let us know if you find value in this!
https://www.twitch.tv/patrickalphac
And see you all in 30 minutes!
- Productivity tip: Never look at your email until the end of the day. Your email is a waste pit of urgent action items that are not important.
Do your essential action items first, and look at your email at the end of the day when your brain isn’t at its peak. Responding doesn’t usually take that much effort.
- 🧰 All your smart contract security tools are shit
...Or at least, according to a recent research study
After analyzing 516 bugs across 2021-2022, they discovered:- How good our tools are- How to categorize web3 bugs- How to use this knowledge to win $102k in audit contests
Let's unpack this paper.
🏋️♂️ 1. Humans still beat machines at finding web3 vulnerabilities
~80% of all vulnerabilities were undetectable by automated tools and required a human in some capacity.
~20% could be found by automated means.
What does this mean?
- Manual Review is 100% necessary in an audit- Tooling isn't a silver bullet- My header for this thread wasn't 100% accurate- Tools are used to aid auditors by guiding them to more information
If your auditor tells you:
"Yeah, we just did some formal verification and ran slither."
Run.
Run away from them as fast as you can.
Even protocols like Compound that had done formal verification ended up being exploited. Formal Verification isn't a silver bullet that says your code is bug-free.
https://docs.compound.finance/v2/security/#formal-verification
🙏 2. There aren't enough good auditors and tools in web3
Looking at ~50 real-world exploits and comparing bounties & payouts to ethical hackers vs. exploit damage - the ratio of damage to bug bounties is 20 to 1.($265M to $14M)
This means there is high demand for security, but also not enough strong people in security because people do be getting hacked.
Projects like @trailofbits and Foundry are some of the main groups leading the charge on building better web3 security tooling.
3. Bugs are hard to find (duh)
The team categorized machine unauditable bugs (MUBS) into 7 categories and then tried to calculate how difficult they were to find based on the number of auditors in a C4 competition who were able to find them.
Less people find them == more difficult bug
In order, the hardest to least difficult bugs to find were:
1. Price Oracle Manipulation
2. Erroneous Accounting
3. Atomicity Violations
4. Privilege escalation
5. Inconsistent State Updates
6. Contract Impl Specific Bugs
7. ID Uniqueness Violations
💣 4. Price oracle manipulations and privilege escalation seemed to be the most common bugs in the real world
Price oracle issues were often caused by:1. Implementing an oracle incorrectly2. Using some shady oracle
For 1, the remedy is to read the docs and not try to do something clever.
For 2... Haaaaaaaaave you met @chainlink?
Privilege Escalation is an example of a bug that would be helped by our tooling.
Using something like symbolic execution, fuzzing, etc, we could map out possible paths that a user could bypass access controls.
There is a lot more information in the paper itself, so I highly recommend everyone check it out. It's quite an enjoyable read.
Thanks to @bytes032 for calling this to my attention, and good luck out there.
The paper is in the GitHub here: https://github.com/ZhangZhuoSJTU/Web3Bugs
- Upgradeable smart contracts are both a potential security & decentrality threat.
When building & using protocols, keep this in mind. A proxy owner can swap out the logic of the contract at any moment, essentially changing the deal under your feet.
https://www.tiktok.com/@patrickalphac/video/7203887318015479086?lang=en
This video is in response to the Oasis recent developments.
TL;DR: Hacker stored funds in oasis controlled smart contract that was behind a proxy.
Contract was upgraded, funds pulled, showing the danger of proxies.
Learn more about proxies here:
https://www.youtube.com/watch?v=bdXJmWajZRY
- Filecoin, but for developers.
https://www.youtube.com/watch?v=Cj9r3pKI2L8
- 🎥 I interviewed @trust_90 who was the top earner on @code4rena for 4 contests in a row winning $67,000 and is the current top earner on code4rena for the past 90 days with over $100,000 in prize money.
Here are the insights from speaking with him 👇
And if you'd like to watch the summary video or read the blog, you can find both here.
https://www.youtube.com/watch?v=VRK2rLFPU0o
1. You need a good grasp of the EVM / environment
This means learning all the fundamentals of solidity, low-level EVM, common exploits, and if you're doing industry-specific audits, that industry.
For example, if you're doing audits on DeFi contracts, you should understand DeFi.
2. You need to understand the protocol before you review the code
Any nerd can find random bugs, but it takes a true bad-ass to find where the code doesn't match the mental model. Often, most of the novel and important bugs come from having a deep understanding of what the protocol is supposed to do, and finding where that doesn't align with the code.
3. Use your knowledge to go line by line
Then, go line by line experimenting with where the code should/shouldn't match up. Using tools like Foundry, @HardhatHQ, @EthereumRemix, @TenderlyApp, and your coding editor of choice. Ideally on a linux-like environment. Windows users, check out WSL.
And then maybe you can top the leaderboard too!
- 🌱 Want to build a decentralized next-generation social media or blogging app using Lens Protocol?
🏋️♂️ WE GOT YOU 🏋️♂️
👇 Get out your popcorn and bring your javascript framework cuz here is how you can create your decentralized social media.
We made one for you if you want to copy-paste!
🎥 Check out the video on the #ChainDev YouTube channel, where we walk you through the @LensProtocol blog step by step.
All the code for the blog is in the description.
https://www.youtube.com/watch?v=SBgh06dDSdo
🤳 To create your own dSocial media:
1. Do your regular javascript framework setup
Before going into Lens, you first do what you'd normally do to build a website.
@nextjs, @sveltejs, @angular, or whatever you want! In our video, we used NextJS so we got set up as such.
2. Interact with Lens
Once you have your framework and built a minimal page, you're going to need to start hooking up to either:
- Lens Protocol GraphQL API
- Lens Protocol contracts
Querying the blockchain can be difficult, so the Lens team set up an API to make it easier.
For users to log in via their Lens profile to your app, they need to authenticate via the GraphQL API.
We can get a challenge query from the API using their ETH address. Then use that challenge response to authenticate.
If you get lost making queries, no worries!
You can go to the apollo studio sandbox, enter the lens API endpoint, and it'll help you build queries for you!
3. Send Transactions
Finally, we need to be able to send transactions directly to the blockchain (if we don't want to use the Lens API)
In our video, I used the react @MoralisWeb3 UI tools for hooks.
And that's it in a REALLY quick nutshell.
Watch the vid, let me know what you think, and have fun!
- I don't love how Lenster captures my "ARTICLE" tagged posts.
Curious if there is a way not to have Lenster post my articles. The twitter-esk formatting is better for short-form content IMO.
- 🌱 Lens Protocol is a decentralized composable social graph enabling developers to make the next generation of social media, with their backend already done!
Here is what makes @LensProtocol such a game changer for web3 devs 👇
And if you want to watch a video that summaries Lens in 3 minutes with some hidden jokes, you can watch it here!
Stay tuned for a tutorial where we show you how to make your own decentralized blog!
https://www.youtube.com/watch?v=9UvieEJEhDk
🖼️ Every social media uses the same framework. You can:
- Make a Profile
- Post
- Subscribe
- React to others
And every time you go to a new social media, you have to do all this again, re-grow your following, re-post updates, and more.
But it all gets siloed to the social media you are working with, and that social media hordes the data for themselves.
🤯 Enter Lens Protocol - Lens sets up the boilerplate social media backend for you in a decentralized manner, to:
- Make it quicker to build a social media
- Allow social followings, profiles, and posts to come with you on every platform
- Make social medias composible
The composibility is really only possible on a decentralized platform.
👻 It's built on the @0xPolygon blockchain, because of Polygon's speed, and was created by the brains behind the @AaveAave protocol.
📈 It comes with a graphQL API you can use to query - because we all know querying the blockchain can be hard.
The graphQL API is not decentralized, but it can make reading from the blockchain easier, and it would be easy enough for a future @graphprotocol integration in the future.
With these powers, we can engage with the graphQL API to build new social media front ends, or integrate with the smart contracts.
If we want to post some content for example, we'd call the post function on the Lens contract with our:
- ProfileId
- ContentURI (URL pointing to our content)
- Collect Module (Contract address governing if people pay us when they support us)
- Collect Module Input data
- Reference Module (Contract address governing if people pay us when they retweet or "mirror" our content)
- Reference Module Input data
This is as a struct, so if we use #foundry's cast, it would look something like the image attached.
To then read this content, we could call directly from the LensHub contract, or the GraphQL API. Using the @apollographql studio we can build a graphQL query to get this result easy.
And mix that in with some @nextjs and you can make ANY social media you want!
- ## We are losing this battle
If the what’s happening with Tornado Cash is allowed to stand.
Got your attention didn’t I?
If the sanctioning of Tornado Cash stands, everything that we as engineers do in blockchain world could be worthless.
In this article we will go over:
1. What happened with Tornado Cash
2. Why it's a big deal
3. What we can do to fix it
# 1. What happened?
Tornado Cash is a privacy-preserving protocol deployed to Ethereum and other EVM blockchains. It uses encryption and zero-knowledge technology to take your money, put it into a pool of money, mix it up, and allow you to take it out the other side anonymously.
For example, let's say you wanted to donate to Ukraine but don't want to get put on Russia's shit list. All you'd have to do to protect yourself is funnel your money through Tornado Cash which would anonymize it, and then send your money to Ukraine.
Poof! You've now helped out Ukraine without Russia ever knowing it's you!
However, on August 7th, 2022 the US Treasury sanctioned Tornado Cash Ethereum addresses. Meaning, no US citizen is allowed to interact with the code at those specific addresses. If you own a wallet that sends or receives money from tornado cash, that's now illegal.
The rationale for this, was that Tornado Cash is used to launder over $7 billion dollars, although most analysts say it's closer to $2.5b, including hacks from the infamous Lazarus group, a hacking group associated with North Korea.
Right after the ban, GitHub removed the user accounts of those associated with building Tornado Cash, removed their organization. Alchemy, Infura and other node-as-a-service providers blocked transactions associated with Tornado Cash addresses.
One of the main original developers was put in jail without being charged of a crime in Amsterdam.
USDC and other centralized coins blacklisted addresses and tens of thousands of dollars.
And hordes of trolls decided to send thousands of Ethereum addresses money coming from tornado cash to show how ridiculous this rule is to enforce.
Up to speed? Good.
# 2. Why this is such a big deal
- Privacy and freedom of speech are prerequisites for a free nation, and this sanction destorys both
- The uncertain precedent it sets
- The “chilling effect” of surrounding entities
There is an argument of "You don't need privacy if you have nothing to hide.", which, as a kid, I used to think. But let's unpack that a little. I'd argue, that you always have something to hide, and sometimes hiding stuff is good.
Scenario: Let's say you are a Jewish person in, I don't know the 1930s. Let's say for a random example your government hates Jewish people and wants to round them up and kill them. Would privacy of religion be a good thing in this scenario?
Scenario: It's the 1960s You think that black lives are just as important as everyone else's, and you want to vote for and support removing Jim Crow laws. The town you live in loves Jim Crow laws and wants to kill anyone who disagrees, do you think privacy is important here?
Scenario: You live in a country surrounding Russia in 2022, and you're not a big fan of the war going on in Ukraine. You want to send Ukraine money for the war efforts, but you don't want to end up on Russia's shit list. Is privacy good here?
In order to be able to congregate and express dissenting opinions without the threat of being crucified for it, privacy is essential to a free nation. In order to come to the best conclusion on anything, you need to be able to freely talk about dissenting opinions.
The topic of why privacy and freedom of speech are so important has been done a hundred times, I've left some links in the description if you want to learn more.
So now, let's talk about how this sanction destroys both privacy and freedom of speech.
- Privacy
Tornado Cash, is a privacy-preserving lump of code. Yes, we want to stop all the bad guys, but this ban actually doesn't stop them. They can and will just keep using Tornado Cash. Instead, it just paints a target on average citizen's backs. Now, they can't anonymize where their money is.
Imagine if every bank was forced to publicly expose how much money was in everyone's bank account. In a way, that's what has happened here. The US is saying they want to make sure they can track everyone’s financial information. But guess what, if they can do that, so can the bad guys.
Identifying a target is the #1 step in any hackers plan. In fact, the United States government themselves[ tells us to limit information on the internet](https://www.ready.gov/cybersecurity) for this exact reason! They know that the more information out there about you, the easiest you are to attack.
So this sanction of tornado cash is dangerous, because now, we have to find other ways to protect our financial privacy.
- Freedom of Speech
- This sets a precedent against all of web3... and why this sanction is kind of silly
This sanction shows a great misunderstanding of how web3 technology works. Tornado Cash isn't an entity, it's a lump of code on the Ethereum blockchain. It's a math equation.
Tornado Cash "failed to curb laundering” which is the reason for the sanction, but the sanction itself doesn’t even cub laundering! It’s is really funny if you think about it. Tornado Cash code is immutable, which means, it "can't be changed". The way it's programmed is money comes in, anon money comes out. The US asking developers to change this is sort of the same as the United States asking math to make 2 + 2 = 5.
So what did OFAC want here? To have them change how the algorithm works? You can’t do that. You can outlaw using the algorithm in the same way you can outlaw using dangerous chemicals, but an open source algorithm doesn’t have the chance of killing other people like chemicals do! We are banning a massive defensive protection option for internet safety.
It's just ridiculous.
You could also think of this in the sense that the US Treasury is demanding people not use the Tornado algorithm in a weird way. Anyone could easily fork and deploy their own tornado cash or mixer, but the US has made it clear they are fighting all money anonymity out there.
The US is saying the pros of "stopping" malicious users is worth the privacy damage it causes to people who use these protocols. I think it doesn't do anything to stop malicous users and everything to stop average users from defending their privacy.
Web3 is the world of trust minimization. The USA coming in and saying they have the power to ban interacting with neutral technology is a radical stance. The purpose of web3 is to enable interaction without a centralized entity corrupting the interaction. Preventing promises from being broken. We know this means that contracts include protection from the United States government. But if they decide they need that backdoor, they need to be able to be the centralized middle body, then it threatens everything we are doing in web3.
If it becomes illegal to use trust-minimized software, all our code could be useless since we’d no longer be allowed to interact with it. Or at least, it would all need to be done in hiding or in a country that hasn’t outlawed it.
* Our future EVM code might be illegal
The future of web3 depends on these choices. Look, we all know that proper web3 and smart contracts are nearly uncensorable, but that’s just the technology itself. Someone has to write the technology in the first place.
But if countries decide that writing privacy preserving protocols are illegal, or writing blockchain based code is illegal, it becomes much harder for us developers to continue to work in this industry. I know this is a little bit of a slippery slope argument, but hear me out for a second. If you can arrest someone from writing code in web3, will people risk continuing to do so? That would definely deter the majority of users from continuing.
In web3, we are building a world where people can interact without having centralized intermediaries, allowing for trust-minimized agreements and unbreakable promises. But it’s hard to build that world if centralized intermediaries outlaw building such technologies.
# 3. What you can do
I want to stay in my lane and just "be a dev", but if rules like these are left in, there is potential for our industry to be completely eroded away. If we aren't allowed to interact with trust minimized agreements or unbreakable promises, this whole space is sort of for nothing.
The good thing is that the technology works regardless of what laws the US comes up with. And to me, that's the power of the space anywasy, and that's why we need to care.
For us normal devs, there are 4 things that you can do right now to help right this wrong.
- Donate
- Write an Email to Senators & OFAC
- Pay attention to industry leaders
- CoinCenter
- EFF
- Lobby3
- Something to do with this coinbase lawsuit
- Vote
I donated to the EFF. I've written a letter to my senators and OFAC. In the description of this video, I'll leave links to the EFF's donation address, links for CoinCenter, EFF, and Lobby3, and a link that you can click to get your senators contact information, and send them an email.
If you don't know what to put in the email, I made one for you!
There is also the OFAC's reconsideration email, where I've written a letter that you can send as well to OFAC.
It'll take a few minutes, but it can be the difference.
And then finally, vote. We can vote for politicians who want trust minimized blockchain technology. I will be paying close attention.
## Find your senator’s contact information:
[https://sengov.com/email/](https://sengov.com/email/)
## Short email to senators:
Dear Honorable <SENATOR_NAME_HERE>,
The recent sanctions against Tornado Cash were done with good intentions but have catastrophic consequences on privacy, freedom of speech, and overall freedom. I think that the sanction has come from an incredibly dangerous misunderstanding about how the technology works.
The action item of this letter is that I am asking for your help to revoke the sanction on Tornado Cash as soon as possible, by either signing a petition to remove Tornado Cash from the sanctions list or creating one.
I agree with the standpoints taken by Coin Center and the EFF on this matter.
Thank you
# Other links
[https://www.eff.org/fa/deeplinks/2022/08/code-speech-and-tornado-cash-mixer](https://www.eff.org/fa/deeplinks/2022/08/code-speech-and-tornado-cash-mixer)
[https://mtsu.edu/first-amendment/article/897/chilling-effect](https://mtsu.edu/first-amendment/article/897/chilling-effect)
[https://scholar.google.com/scholar_case?case=114991681069810012](https://scholar.google.com/scholar_case?case=114991681069810012)
[https://home.treasury.gov/policy-issues/financial-sanctions/specially-designated-nationals-list-sdn-list/filing-a-petition-for-removal-from-an-ofac-list](https://home.treasury.gov/policy-issues/financial-sanctions/specially-designated-nationals-list-sdn-list/filing-a-petition-for-removal-from-an-ofac-list)
Groups defending the Privacy and Tornado
[https://www.coincenter.org/](https://www.coincenter.org/)
[https://www.eff.org/fa/deeplinks/2022/08/code-speech-and-tornado-cash-mixer](https://www.eff.org/fa/deeplinks/2022/08/code-speech-and-tornado-cash-mixer)
[https://www.lobby3.io/](https://www.lobby3.io/)
OFAC Contact information
[OFAC.Reconsideration@treasury.gov](mailto:OFAC.Reconsideration@treasury.gov)
See Torando on the sanctions list
https://sanctionssearch.ofac.treas.gov/Details.aspx?id=38499
- My recent post on what in the Ethereum application ecosystem excited me:
https://vitalik.ca/general/2022/12/05/excited.html
- @lensprotocol dev idea:\n\nBuild a @chainlink.lens price feeds powered collect module so users can set the price of their publications in USD or any other currency but get paid in the native blockchain token. \n\nHave fun
- #### **Python developers love working with the smart contract framework Brownie. A successor to Brownie is in the making—creating a reimagination of the Python Web3 developer experience. **
In this piece, I’ll be talking about [ApeWorX](https://www.apeworx.io/), also known as “Ape”.
ApeWorX is a Python-based smart contract development and deployment framework known for its customizability and safe private key management.
Many of you know that I love Python, and upon entering the Web3 space I fell in love with the[ Brownie](https://github.com/eth-brownie/brownie) framework. Since I entered the space it seems as if all the original Web3 frameworks have either been succeeded or another competitor has swooped in:
* [DappTools officially recognized Foundry](https://github.com/dapphub/dapptools/pull/927/files) as its successor.
* [Hardhat](https://hardhat.org/) took the spot of the most-used framework in DeFi after a long tenure from[ Truffle](https://trufflesuite.com/)<span style="text-decoration:underline;">.</span>
* [ApeWorX](https://www.apeworx.io/) seems to be positioned to one day be the successor to the Brownie framework.
The Ethereum Python community is known for being one of the most collaborative and tight-knit groups out there. Many of the[ Vyper](https://vyper.readthedocs.io/en/stable/index.html) and[ Brownie contributors](https://github.com/eth-brownie/brownie/graphs/contributors) can be seen on the list of[ Ape contributors](https://github.com/ApeWorX/ape/graphs/contributors), including[ Doggie B](https://github.com/fubuloubu),[ Banteg](https://twitter.com/bantg), and[ Skellet0r](https://github.com/skellet0r) (and to a lesser extent, even myself!)
Additionally, both Python enthusiasts and DeFi protocols[ like Curve](https://curve.fi/) have started[ using Ape](https://github.com/curvefi/metaregistry) as a framework for their contracts.
Today we are going to take a high-level “lickity-split” look at coming at ApeWorX from a Brownie user’s perspective.
### **Lickity-Split**
_You can find a minimal ApeWorX & Vyper template in our[ ApeWorX-starter-kit](https://github.com/smartcontractkit/apeworx-starter-kit) with code examples to get you started. _
After[ installing ape](https://docs.apeworx.io/ape/stable/userguides/quickstart.html#installation) with something like pipx install eth-ape or pip, you’ll have access to the ape command-line interface.
The quickest way to start a new project is to use ape init, which will give you a blank setup that will look as such:
```
.
├── ape-config.yaml
├── contracts
├── scripts
└── tests
```
Here’s what each folder contains:
* **Contracts: **Where all your Vyper, Solidity, or other contracts will go.
* **Scripts: **Where all your Python code will go.
* **Tests: **Your Python tests.
* **ape-config.yaml: **The config file for your project. This is the ape equivalent of brownie-config.yaml or hardhat.config.js.
In your scripts folder, you can make a script like:
```python
def main():
print("Hello!")
```
To run any of your Python scripts in ape, run:
```python
ape run scripts/my_script.py
```
#### **Plugins**
Ape doesn’t have Vyper, Solidity, or really anything by default, and instead uses a[ system of plugins](https://docs.apeworx.io/ape/stable/userguides/installing_plugins.html) to make ApeWorX completely customizable to your specific smart contract needs. Two of the most popular plugins are those for[ Solidity](https://github.com/ApeWorX/ape-solidity) and[ Alchemy](https://github.com/ApeWorX/ape-alchemy), which allow you to compile Solidity contracts and easily deploy to Alchemy.
ape plugins install solidity alchemy
Once you have this set up, you can write your Solidity contract in the contracts folder and compile.
ape compile
#### **Networks**
Ape takes a specific approach to working with networks. Most frameworks, including Hardhat, Brownie, and Foundry, treat EVM chains in a similar fashion. ApeWorX is different.
ApeWorX separates networks into **ecosystems **and **chains**. For example, the Ethereum ecosystem is separated into **mainnet, ropsten, kovan, goerli, **etc. If you want to work with something like Fantom, you can install the fantom network plugin:
ape plugins install fantom
Then you’ll see your new list of networks on the ape networks list:
```
fantom
├── opera
│ └── geth (default)
├── testnet
│ └── geth (default)
└── local (default)
└── test (default)
```
In cases where you don’t want to have to install a plugin for your network, you can use the[ ad-hoc method](https://docs.apeworx.io/ape/stable/userguides/networks.html#ad-hoc-network-connection) and just drop the RPC URL to the network you like. ape will assume as much as it can for sending transactions.
ape run scripts/my_script.py --network https://my_rpc_url.com
#### **Accounts**
One of the biggest differences across frameworks is how they deal with accounts. Most frameworks have you setup a .env file to store your private keys in. However, putting your private keys in a .env has been[ tripping up developers forever](https://twitter.com/heyOnuoha/status/1522542744954191872). You _can _do this in ape, but the default is much safer.
Ape allows you to import private keys, then it will encrypt and store them on your computer. Whenever you want to work with that account or private key, you’ll need the password to decrypt it. This means no more accidentally pushing your keys up to GitHub!
ape accounts import my_key
It will then prompt you for your key and your password. In your Python scripts, you can then get your private key using the load function.
from ape import accounts
accounts.load("local-default")
When you run this script, you’ll be prompted for your password.
#### **The Rest…**
The rest of the framework works as you’d expect. You can write your tests using[ pytest](https://docs.pytest.org/en/7.1.x/), one of the most popular Python testing frameworks. You can enter the[ ape console](https://docs.apeworx.io/ape/stable/commands/console.html) to work with an interactive shell in a Python environment with your network of choice.
It’s everything you’d want and expect from a framework.
Ape is a new player in the framework space, and it’s a[ wonderful repo to contribute to.](https://github.com/ApeWorX/ape/issues) If you love Python and have an idea on how to improve ape, be sure to leave an issue, a pull request, or just drop them a star!
Happy Ape-ing!
- _Special thanks to [Adrian Hetman](https://twitter.com/adrianhetman), [Alejandro Munoz-McDonald](https://twitter.com/unsafe_call), [Ivan Benavides](https://twitter.com/Ivanbenavides_), and [Leon Spacewalker](https://twitter.com/leonspacewalker)._
[https://www.youtube.com/watch?v=sgHHbWvWj9A](https://www.youtube.com/watch?v=sgHHbWvWj9A)
# Top 7 Strategies for Finding Smart Contract Vulnerabilities
Hunting for smart contract bugs can be a ludicrously well-paying job, and it’s also an integral part of protecting the ecosystem from hacks. I recently had the pleasure of [interviewing a developer](https://twitter.com/leonspacewalker) who found a $7 billion dollar bug—and [was paid $2.2M](https://medium.com/immunefi/polygon-lack-of-balance-check-bugfix-postmortem-2-2m-bounty-64ec66c24c7d) for reporting it.
In this blog, we’re going to go through the bug that this developer found and how it had the potential to compromise $7b in value before offering some strategies and tools that will help you find bugs.
Let's dive in.
# What Happened
## Build Up
On May 31, 2020, the [Matic blockchain went live](https://crypto.news/matic-network-mainnet-live/) (Matic would later be rebranded as [Polygon](https://polygon.technology/)). Polygon is an EVM-compatible blockchain known for it's low gas fees and short block time. The chain has recently begun exploring [zk-rollup technology](https://www.alchemy.com/overviews/polygon-zk-rollups).
If you take a look at [block 0](https://polygonscan.com/block/0) of Polygon, the absolute first block of the blockchain, also known as its “genesis” block, you'll see 10 transactions. One of these transactions created a contract called MRC20.
What is this contract?
When we send a native blockchain token we have to spend gas to do so. So the Polygon team deployed a contract that allows you to sign a transaction to send someone ETH, with someone else able to pay the gas fee for this transaction. Known as a "meta transaction," this capability was popularized with the introduction of [EIP-712](https://eips.ethereum.org/EIPS/eip-712).
You can see that this contract was given almost 10 billion MATIC tokens in order to help facilitate these gasless transactions. However, this clever contract contained a vulnerability that could have potentially been exploited to drain the entire balance!
On December 3rd, 2021 the hero of the story, pseudo-anon developer [Leon Spacewalker](https://twitter.com/leonspacewalker), submitted a report to the [Immunefi bug bounty](https://immunefi.com/bounty/immunefi/) program laying out the details of this exact function. A second hero, who we will just call Whitehat2, also reported the vulnerability a day later.
Around 800,000 MATIC tokens were stolen before the chain was finally forked, rolled back, and fixed [December 5th, 2021.](https://github.com/maticnetwork/bor/releases/tag/v0.2.12)
This leaves us with some more questions: What was the vulnerability? How did it stay undiscovered for so long? How was it found?
## The Exploit
Below is the function that facilitates these gasless transactions.
```javascript
function transferWithSig(
bytes calldata sig,
uint256 amount,
bytes32 data,
uint256 expiration,
address to
) external returns (address from) {
require(amount > 0);
require(
expiration == 0 || block.number <= expiration,
"Signature is expired"
);
bytes32 dataHash = getTokenTransferOrderHash(
msg.sender,
amount,
data,
expiration
);
require(disabledHashes[dataHash] == false, "Sig deactivated");
disabledHashes[dataHash] = true;
from = ecrecovery(dataHash, sig);
_transferFrom(from, address(uint160(to)), amount);
}
```
At first glance, it seems harmless: It takes the signature of the user, how many tokens and who they want to send them to, and any further data, along with an expiration date for the transaction.
It runs some requires, gets the data hash in order to send the meta transaction, makes sure the data hash hasn't been used, and does this `ecrecovery` function.
This function is essentially a wrapper for the [Solidity ecrecover function](https://docs.soliditylang.org/en/latest/cheatsheet.html?highlight=ecrecover#global-variables).
This function is how we can verify where signed transactions are coming from. You’ll notice, even in the Solidity documentation, it says it will “return zero on error”. The `ecrecovery` function copied this, and if it had an issue, it would return 0. Which, as many developers know, can be scary. If it returns zero on error, that means that we should check to make sure that the returned address isn’t zero, right?
Well... We that's not what happened.
So we don’t perform a check on the address to make sure it didn’t result in an error. Not a problem. The last line of code in our `transferWithSig` function does the actual transfer, surely we will perform some sort of check there, right?
```javascript
function _transfer(address sender, address recipient, uint256 amount)
internal
{
require(recipient != address(this), "can't send to MRC20");
address(uint160(recipient)).transfer(amount); // It just sends the money!
emit Transfer(sender, recipient, amount);
}
```
The `_transferFrom` function just called our `_transfer` function, shown above. You'll notice it doesn't check to make sure the `from` address has enough money.
This means that someone could send an invalid signature, which would result in a zero address returned from ecrecovery, but the MRC20 contract would still send the `to` address an amount of money. This is how that 9,999,993,000 MATIC could be drained, since the MRC20 contract sends the money directly from itself!
A check to make sure that the `from` address has enough money for this signed transaction would have prevented this issue.
## How Did the Vulnerability Elude Discovery for So Long?
What's odd to me is that, after the vulnerability laying dormant for almost a year and a half, it was discovered by Leon, another white hat, and a hacker within the span of a few days.
Seems fishy. But the Immunefi team told me this can often happen. Some exploits can become popular based on an article, write-up, or [challenge](https://github.com/code-423n4/2021-09-swivel-findings/issues/61) and people then start looking for that vulnerability, resulting in several people finding it at the same time.
But more likely is that it turns out that polygon verified the contract on Polygonscan around this time - so that was when people _really _started to look at it.
Maybe there is more to the story, but maybe not.
In any case, let’s use this bug as a teachable moment and look at some of the skills Leon and other bug hunters use to find bugs, helping protect the Web3 ecosystem.
# Top 7 Strategies
Now, we are going to learn the skills Leon and other bug hunters use to find these vulnerabilities and claim bug bounties. This list of tips assumes you already know the basics of smart contracts, so yes, [learning Solidity is a prerequisite](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=23615s).
Use these superpowers for [ethical hacking](https://www.eccouncil.org/ethical-hacking/), and please remember to [responsibly disclose](https://www.hackerone.com/vulnerability-management/what-responsible-disclosure-policy-and-why-you-need-one) any vulnerabilities you find.
A lot of the work of finding vulnerabilities comes from looking at the code and running tools like [slither](https://github.com/crytic/slither). For this $2.2M payout, Leon said he was able to find the bug by looking line-by-line at the smart contract code, so remember, finding vulnerabilities is often a huge manual lift!
In addition to the practical tips below, Leon's biggest takeaway was for smart contract bug hunters to "find your edge," but what does he mean by that? Typically, this means finding that thing that sets you apart from other hackers. We as a community need to cover every corner of the smart contract space, so find a section that you are specifically good at and excel.
Here are the seven strategies and tips to help find your edge, to make you a successful smart contract bug hunter.
## 1. Find a Project and Search For Bugs
The first way you can find bugs is to know every inch of how a protocol works. This is one of the first skills every smart contract bug hunter needs to be learn: the ability to understand a protocol end to end.
Go through docs, try to reimplement a protocol yourself, and view transactions through that protocol on a block explorer.
Leon said this strategy works for other hunters but not him. He focuses on the next three, but it’s important for every bug hunter to be able to do this.
## 2. Find a Bug and Search For Projects
An easier approach to hunting for bugs is to find a bug that not a lot of people know about and try to see which protocols have implemented it.
This strategy takes a lot of research, as there are a lot of people working on [exposing bugs to the general public](https://swcregistry.io/).
You first need to understand the [top smart contract exploits](https://swcregistry.io/) and then their advanced versions. You need to be aware of best practices and see if there are protocols that have not been followed them.
Once you find a smart contract bug you think a lot of projects might not have protected against, start searching for that bug. Get really familiar with this new bug and how to find it. And be sure to write a blog or some kind of post to help other smart contract developers who run into this bug protect themselves.
## 3. Be Fast
Projects that want bug hunters to look at their smart contracts need to sign up for bug bounty programs like [Immunefi](https://immunefi.com/). And you'll want to be one of the first developers to find the new bounties. If you start looking at a contract before other hunters, you’ll have more time to find a bug than other hunters.
There are a few ways to be fast—one of the ways Leon was able to find the smart contract vulnerability before others was by having notifications on for the [Immunifi updates Discord channel](https://discord.gg/nVE8WqH3MH). He received a notification anytime a new project came in, or a project was updated. Tools like this can help you get to digging into code before anyone else does.
## 4. Be Creative
Another way Leon was able to get an edge, was traversing [community forums](https://forum.makerdao.com/), and finding out they were thinking about submitting a bug. He'd then start looking at the smart contracts even before the bounty was approved. This gave him way more time to look at a contract than other developers, since they would wait for a bug bounty to be submitted.
## 5. Know Your Tooling
Bug hunters use tools like the VSCode Solidity visual developer extension, Hardhat, Foundry, Brownie, Dune, Etherscan, plus a host of others.
A typical bug hunting strategy might be loading up VSCode, adding the code to VSCode with the Solidity visual extension, and going line by line looking for common bugs or bad best practices.
After finding a weakness, setting up a testing environment to run tests on the contract is a good next step. You can often reuse a lot of the tests the developers of the protocol originally used.
## 6. Don’t Be Afraid of Audited Projects
Not much else to say here. Audit firms make mistakes. Many of the projects Leon found vulnerabilities for had been audited by top firms.
Using the skills we talked about in this blog can be the difference for you to find these issues!
## 7. Industry-Specific Knowledge
One of the biggest advantages in finding your edge is specializing in a specific niche. If you understand one area incredibly well, you’ll have the advantage of knowing how all the functions interact with each other. If you’re a phenomenal smart contract vulnerability expert but don’t know anything about DeFi, it’ll be hard to find vulnerabilities in DeFi contracts. For example, a lot of developers understand code, but don't understand financial primitives.
You could get incredibly good at understanding decentralized exchanges, borrowing protocols, or maybe just NFTs!
If you can become a master of security and a master of a certain vertical within Web3, you'll be well-positioned to have a massive leg up on everyone else looking for bugs.
## Summary
I hope this piece is useful to you in your smart contract bug-hunting journey. If you want to learn more about security when writing your smart contracts, be sure to check out [Top Ten DeFi Security Best Practices](https://blog.chain.link/defi-security-best-practices/).
And, as always, I hope to see you out there building and keeping the ecosystem a little safer.
## Links
[MRC20 contract.](https://polygonscan.com/address/0x0000000000000000000000000000000000001010#code)
[Immunefi writeup.](https://medium.com/immunefi/polygon-lack-of-balance-check-bugfix-postmortem-2-2m-bounty-64ec66c24c7d)
[Change to Polygon contracts](https://github.com/maticnetwork/contracts/commit/55e8118ad406c9cb0e9b457ca4f275c5977809e4#diff-cc4ed03464edad9d87d48cff647eb6940dfe9a4c419f63e3994bdc91b01bfecb).
[Previous Polygon contracts.](https://github.com/maticnetwork/contracts/blob/56ec7eb257ce10a9f70621f56f6e3f37eb8e0c57/contracts/child/MRC20.sol)
[Ecrecovery challenge.](https://github.com/code-423n4/2021-09-swivel-findings/issues/61)
- _Special thanks to [Adrian Hetman](https://twitter.com/adrianhetman), [Alejandro Munoz-McDonald](https://twitter.com/unsafe_call), [Ivan Benavides](https://twitter.com/Ivanbenavides_), and [Leon Spacewalker](https://twitter.com/leonspacewalker)._
[https://www.youtube.com/watch?v=sgHHbWvWj9A](https://www.youtube.com/watch?v=sgHHbWvWj9A)
# Top 7 Strategies for Finding Smart Contract Vulnerabilities
Hunting for smart contract bugs can be a ludicrously well-paying job, and it’s also an integral part of protecting the ecosystem from hacks. I recently had the pleasure of [interviewing a developer](https://twitter.com/leonspacewalker) who found a $7 billion dollar bug—and [was paid $2.2M](https://medium.com/immunefi/polygon-lack-of-balance-check-bugfix-postmortem-2-2m-bounty-64ec66c24c7d) for reporting it.
In this blog, we’re going to go through the bug that this developer found and how it had the potential to compromise $7b in value before offering some strategies and tools that will help you find bugs.
Let's dive in.
# What Happened
## Build Up
On May 31, 2020, the [Matic blockchain went live](https://crypto.news/matic-network-mainnet-live/) (Matic would later be rebranded as [Polygon](https://polygon.technology/)). Polygon is an EVM-compatible blockchain known for it's low gas fees and short block time. The chain has recently begun exploring [zk-rollup technology](https://www.alchemy.com/overviews/polygon-zk-rollups).
If you take a look at [block 0](https://polygonscan.com/block/0) of Polygon, the absolute first block of the blockchain, also known as its “genesis” block, you'll see 10 transactions. One of these transactions created a contract called MRC20.
What is this contract?
When we send a native blockchain token we have to spend gas to do so. So the Polygon team deployed a contract that allows you to sign a transaction to send someone ETH, with someone else able to pay the gas fee for this transaction. Known as a "meta transaction," this capability was popularized with the introduction of [EIP-712](https://eips.ethereum.org/EIPS/eip-712).
You can see that this contract was given almost 10 billion MATIC tokens in order to help facilitate these gasless transactions. However, this clever contract contained a vulnerability that could have potentially been exploited to drain the entire balance!
On December 3rd, 2021 the hero of the story, pseudo-anon developer [Leon Spacewalker](https://twitter.com/leonspacewalker), submitted a report to the [Immunefi bug bounty](https://immunefi.com/bounty/immunefi/) program laying out the details of this exact function. A second hero, who we will just call Whitehat2, also reported the vulnerability a day later.
Around 800,000 MATIC tokens were stolen before the chain was finally forked, rolled back, and fixed [December 5th, 2021.](https://github.com/maticnetwork/bor/releases/tag/v0.2.12)
This leaves us with some more questions: What was the vulnerability? How did it stay undiscovered for so long? How was it found?
## The Exploit
Below is the function that facilitates these gasless transactions.
```javascript
function transferWithSig(
bytes calldata sig,
uint256 amount,
bytes32 data,
uint256 expiration,
address to
) external returns (address from) {
require(amount > 0);
require(
expiration == 0 || block.number <= expiration,
"Signature is expired"
);
bytes32 dataHash = getTokenTransferOrderHash(
msg.sender,
amount,
data,
expiration
);
require(disabledHashes[dataHash] == false, "Sig deactivated");
disabledHashes[dataHash] = true;
from = ecrecovery(dataHash, sig);
_transferFrom(from, address(uint160(to)), amount);
}
```
At first glance, it seems harmless: It takes the signature of the user, how many tokens and who they want to send them to, and any further data, along with an expiration date for the transaction.
It runs some requires, gets the data hash in order to send the meta transaction, makes sure the data hash hasn't been used, and does this `ecrecovery` function.
This function is essentially a wrapper for the [Solidity ecrecover function](https://docs.soliditylang.org/en/latest/cheatsheet.html?highlight=ecrecover#global-variables).
This function is how we can verify where signed transactions are coming from. You’ll notice, even in the Solidity documentation, it says it will “return zero on error”. The `ecrecovery` function copied this, and if it had an issue, it would return 0. Which, as many developers know, can be scary. If it returns zero on error, that means that we should check to make sure that the returned address isn’t zero, right?
Well... We that's not what happened.
So we don’t perform a check on the address to make sure it didn’t result in an error. Not a problem. The last line of code in our `transferWithSig` function does the actual transfer, surely we will perform some sort of check there, right?
```javascript
function _transfer(address sender, address recipient, uint256 amount)
internal
{
require(recipient != address(this), "can't send to MRC20");
address(uint160(recipient)).transfer(amount); // It just sends the money!
emit Transfer(sender, recipient, amount);
}
```
The `_transferFrom` function just called our `_transfer` function, shown above. You'll notice it doesn't check to make sure the `from` address has enough money.
This means that someone could send an invalid signature, which would result in a zero address returned from ecrecovery, but the MRC20 contract would still send the `to` address an amount of money. This is how that 9,999,993,000 MATIC could be drained, since the MRC20 contract sends the money directly from itself!
A check to make sure that the `from` address has enough money for this signed transaction would have prevented this issue.
## How Did the Vulnerability Elude Discovery for So Long?
What's odd to me is that, after the vulnerability laying dormant for almost a year and a half, it was discovered by Leon, another white hat, and a hacker within the span of a few days.
Seems fishy. But the Immunefi team told me this can often happen. Some exploits can become popular based on an article, write-up, or [challenge](https://github.com/code-423n4/2021-09-swivel-findings/issues/61) and people then start looking for that vulnerability, resulting in several people finding it at the same time.
But more likely is that it turns out that polygon verified the contract on Polygonscan around this time - so that was when people _really _started to look at it.
Maybe there is more to the story, but maybe not.
In any case, let’s use this bug as a teachable moment and look at some of the skills Leon and other bug hunters use to find bugs, helping protect the Web3 ecosystem.
# Top 7 Strategies
Now, we are going to learn the skills Leon and other bug hunters use to find these vulnerabilities and claim bug bounties. This list of tips assumes you already know the basics of smart contracts, so yes, [learning Solidity is a prerequisite](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=23615s).
Use these superpowers for [ethical hacking](https://www.eccouncil.org/ethical-hacking/), and please remember to [responsibly disclose](https://www.hackerone.com/vulnerability-management/what-responsible-disclosure-policy-and-why-you-need-one) any vulnerabilities you find.
A lot of the work of finding vulnerabilities comes from looking at the code and running tools like [slither](https://github.com/crytic/slither). For this $2.2M payout, Leon said he was able to find the bug by looking line-by-line at the smart contract code, so remember, finding vulnerabilities is often a huge manual lift!
In addition to the practical tips below, Leon's biggest takeaway was for smart contract bug hunters to "find your edge," but what does he mean by that? Typically, this means finding that thing that sets you apart from other hackers. We as a community need to cover every corner of the smart contract space, so find a section that you are specifically good at and excel.
Here are the seven strategies and tips to help find your edge, to make you a successful smart contract bug hunter.
## 1. Find a Project and Search For Bugs
The first way you can find bugs is to know every inch of how a protocol works. This is one of the first skills every smart contract bug hunter needs to be learn: the ability to understand a protocol end to end.
Go through docs, try to reimplement a protocol yourself, and view transactions through that protocol on a block explorer.
Leon said this strategy works for other hunters but not him. He focuses on the next three, but it’s important for every bug hunter to be able to do this.
## 2. Find a Bug and Search For Projects
An easier approach to hunting for bugs is to find a bug that not a lot of people know about and try to see which protocols have implemented it.
This strategy takes a lot of research, as there are a lot of people working on [exposing bugs to the general public](https://swcregistry.io/).
You first need to understand the [top smart contract exploits](https://swcregistry.io/) and then their advanced versions. You need to be aware of best practices and see if there are protocols that have not been followed them.
Once you find a smart contract bug you think a lot of projects might not have protected against, start searching for that bug. Get really familiar with this new bug and how to find it. And be sure to write a blog or some kind of post to help other smart contract developers who run into this bug protect themselves.
## 3. Be Fast
Projects that want bug hunters to look at their smart contracts need to sign up for bug bounty programs like [Immunefi](https://immunefi.com/). And you'll want to be one of the first developers to find the new bounties. If you start looking at a contract before other hunters, you’ll have more time to find a bug than other hunters.
There are a few ways to be fast—one of the ways Leon was able to find the smart contract vulnerability before others was by having notifications on for the [Immunifi updates Discord channel](https://discord.gg/nVE8WqH3MH). He received a notification anytime a new project came in, or a project was updated. Tools like this can help you get to digging into code before anyone else does.
## 4. Be Creative
Another way Leon was able to get an edge, was traversing [community forums](https://forum.makerdao.com/), and finding out they were thinking about submitting a bug. He'd then start looking at the smart contracts even before the bounty was approved. This gave him way more time to look at a contract than other developers, since they would wait for a bug bounty to be submitted.
## 5. Know Your Tooling
Bug hunters use tools like the VSCode Solidity visual developer extension, Hardhat, Foundry, Brownie, Dune, Etherscan, plus a host of others.
A typical bug hunting strategy might be loading up VSCode, adding the code to VSCode with the Solidity visual extension, and going line by line looking for common bugs or bad best practices.
After finding a weakness, setting up a testing environment to run tests on the contract is a good next step. You can often reuse a lot of the tests the developers of the protocol originally used.
## 6. Don’t Be Afraid of Audited Projects
Not much else to say here. Audit firms make mistakes. Many of the projects Leon found vulnerabilities for had been audited by top firms.
Using the skills we talked about in this blog can be the difference for you to find these issues!
## 7. Industry-Specific Knowledge
One of the biggest advantages in finding your edge is specializing in a specific niche. If you understand one area incredibly well, you’ll have the advantage of knowing how all the functions interact with each other. If you’re a phenomenal smart contract vulnerability expert but don’t know anything about DeFi, it’ll be hard to find vulnerabilities in DeFi contracts. For example, a lot of developers understand code, but don't understand financial primitives.
You could get incredibly good at understanding decentralized exchanges, borrowing protocols, or maybe just NFTs!
If you can become a master of security and a master of a certain vertical within Web3, you'll be well-positioned to have a massive leg up on everyone else looking for bugs.
## Summary
I hope this piece is useful to you in your smart contract bug-hunting journey. If you want to learn more about security when writing your smart contracts, be sure to check out [Top Ten DeFi Security Best Practices](https://blog.chain.link/defi-security-best-practices/).
And, as always, I hope to see you out there building and keeping the ecosystem a little safer.
## Links
[MRC20 contract.](https://polygonscan.com/address/0x0000000000000000000000000000000000001010#code)
[Immunefi writeup.](https://medium.com/immunefi/polygon-lack-of-balance-check-bugfix-postmortem-2-2m-bounty-64ec66c24c7d)
[Change to Polygon contracts](https://github.com/maticnetwork/contracts/commit/55e8118ad406c9cb0e9b457ca4f275c5977809e4#diff-cc4ed03464edad9d87d48cff647eb6940dfe9a4c419f63e3994bdc91b01bfecb).
[Previous Polygon contracts.](https://github.com/maticnetwork/contracts/blob/56ec7eb257ce10a9f70621f56f6e3f37eb8e0c57/contracts/child/MRC20.sol)
[Ecrecovery challenge.](https://github.com/code-423n4/2021-09-swivel-findings/issues/61)
- What Is a Stablecoin? (But Actually)
====================================
**What are stablecoins? What do they do in DeFi? Why do people mint stablecoins? Where are stablecoins right now?**
-------------------------------------------------------------------------------------------------------------------
You can watch the video on the topic on ChainDev
_Thanks to_ [_ChainlinkGod_](https://twitter.com/ChainLinkGod)_,_ [_Luca Prosperi_](https://substack.com/profile/33975085-luca-prosperi)_,_ [_Zubin Pratap_](https://twitter.com/ZubinPratap)_, and_ [_Gerrit Hall_](https://www.linkedin.com/in/gerrithall/) _for their help on this article._
_For those looking for some code, we have a_ [_stablecoins folder in the defi-minimal project._](https://github.com/smartcontractkit/defi-minimal/tree/main/contracts/stablecoins)
_This blog was originallly posted on_ [_blog.chain.link_](https://blog.chain.link/stablecoins-but-actually/)
Introduction
------------
When you look up “what is a stablecoin” you get a lot of *pushes glasses up* wrong or misleading information.
The wrong and misleading information is:
1. All stablecoins are pegged/anchored to that of another asset/currency
2. All stablecoins fall into the categories of fiat-collateralized, crypto-collateralized, and algorithmic
And I’m here to straighten the record and tell you EVERYTHING you need to know to really understand stablecoins. What are stablecoins, what they do in DeFi, why they are so important, and where they are right now.
And additionally, probably the most important and interesting part of the picture, how stablecoins are created and the economics behind them. This isn’t your average stablecoin article, but your end-to-end mega stablecoin article.
Buckle up, because we are in for a volatile ride about stability.
Table of Contents
=================
* What is a stablecoin?
* Why do we care?
* Categories and anatomy
* A look at various modern coins
* Who pays for stablecoins?
* What’s the deal with curve wars?
* Final thoughts
What Is a Stablecoin?
=====================
**A stablecoin is a non-volatile crypto asset.**
That’s it.
If you take away anything from this article, please, have it be this:
A stablecoin is any crypto asset whose buying power fluctuates very little relative to the rest of the market.
“Non-volatile” means that a crypto asset’s **buying power** will stay **similar** for a **long** duration of time. “Similar” and “long” are subjective terms, so we’ve already learned that a stablecoin is subjective from person to person! Stable to you might not be so stable to someone else.
“Buying Power” is how much a currency can buy. If one dollar can buy you a box of apples today and in ten years, we would say the buying power of that currency stayed stable over 10 years. If after ten years one dollar could only buy half a box of apples, we’d say the buying power of the dollar was cut in half. We give more buying examples later in this blog.
An asset whose price jumps up and down would not be considered a stablecoin. Most crypto assets are volatile in nature or have the capacity to be volatile.
The second most important takeaway is this:
Almost every question you have about the purpose of stablecoins can be answered by swapping out the word “stablecoin” for “dollar” in your question, and asking “well, how does a dollar, Euro, or Yen handle that?”
For example:
Question: Why are **stablecoins** important?
Has nearly the same answer as:
Question: Why are **dollars** important?
Why Do We Care?
===============
In our daily lives, a low-volatility currency is very important for three reasons:
1. **Storage of Value:** So that we can build wealth or bartering power. Having your dollars in a bank account is using them as a store of value.
2. **Unit of Account:** A way to measure how valuable things are. Like when you go to the store and see goods listed in terms of dollars. Dollars are acting like a unit of account.
3. **Medium of Exchange:** An agreed-upon method to transact between each other. When you use a currency to purchase items, you’re using it as a medium of exchange.
In order for our everyday lives to be efficient, it’s good to have a currency or coin that accomplishes these three goals. Most crypto assets like Ether or Bitcoin don’t accomplish all three goals very well. Now some would argue they are good at all three, but I’m quite certain that they do a terrible job of at least **unit of account**.
If I were to go to the Crypto Amazon online store and we had Ethereum or Bitcoin as the unit of account, based on the day of the week the prices could be twice what they were the week before. This high volatility makes for a poor unit of account.
Now, an average stablecoin article would stop there, or go deep into the history of money, but we have bigger plans… Let’s look at what a stablecoin looks like, then we will jump down to the top stablecoins.
If this next section is a little confusing, feel free to skip down to the top stablecoins section.
Categories and Anatomy
======================
Now in order to make or use a stablecoin, you have to understand the 3 main categories of a stablecoin.
1. **Relative Stability.** Pegged/anchored or floating.
2. **Stability Method.** Governed or algorithmic.
3. **Collateral Type.** Endogenous or exogenous.
These categories are each spectrums, meaning a coin can be more algorithmic or more governed by its stability method. It can be more exogenous or more endogenous for its collateral type. And more pegged or more floating depending on its implementation.
Let’s understand each of these categories and the tokens that fall into them.
Relative Stability
==================
As mentioned above, a stablecoin is only stable as a relative term, so we need to know what we are comparing our stablecoin to that makes them stable.
Pegging/Anchoring
-----------------
One of the easiest ways to make a stablecoin would be to back it by or peg it to another asset that most people consider “non-volatile.” So yes, _some_ stablecoins are pegged to another asset, but not all (more on that later). The most popular asset most people choose is the US dollar. Many stablecoins like [USDT](https://www.investopedia.com/terms/t/tether-usdt.asp), [DAI](https://makerdao.com/en/), and [USDC](https://www.investopedia.com/usd-coin-5210435) follow this strategy.
A stablecoin that is “pegged” or “anchored” to another asset is a stablecoin that follows the buying power of another asset that people consider to be stable, like the Dollar, Euro, or Yen.
They then follow the narrative of:
One Dollar-Pegged Coin (USDT, DAI, or USDC) = null
Which is easy for people to understand. The way pegged stablecoins work is they have a smart contract or service which says at any time (usually any time) you can swap your coin for its underlying collateral. With our dollar-pegged stablecoins, you can swap your DAI, USDC, or USDT for the dollar equivalent.
For example, with DAI, the protocol enables you to trade your DAI in for your ETH collateral at any time, at an exchange rate of exactly null of collateral per 1 DAI. So if you have 100 DAI, and you had ETH down as collateral, you can trade your DAI in for $100 in ETH via a smart contract. Boom! Now that we have a (roughly) permanent exchange for the currency where the price of one DAI is always null.
**Pegged Asset Examples**: DAI, USDC, USDT, FRAX, UST
Floating
--------
A token can go the “non-volatile” route and follow a “pseudo-index” like route and create a stablecoin whose buying power stays relatively the same over time — without it being pegged to another asset. Relatively speaking, the coin would still be stable by very slowly following current market conditions, but is resistant to the quick spikes and dumps of the market. You could think of a floating stablecoin as an oobleck-like substance, but in the financial market. It’s firm when markets are volatile, but liquid when change comes slowly.
Another analogy is a board “pegged” to a dock vs. a buoy “floating” by a dock compared to the water. The “pegged” board might seem more stable at first, but when the tide is in, the pegged board is underwater and the buoy is still floating in the same position.
Coins like [RAI](https://reflexer.finance/) follow this principle. They “float” around a price that very slowly follows the market, trying to keep the buying power of the coin the same at all times.
A non-pegged token might be difficult to wrap your mind around but just remember, in order to be a stablecoin its buying power just has to be relatively stable. So a coin that fluctuates around $2.10 always, could be considered a stablecoin even though it is worth a weird amount of dollars.
You could even have a floating stablecoin be _more_ stable than a dollar-pegged coin, for example:
If 1 Cheesecake in 2018 is worth $45 and 1 cheesecake is worth $55 in 2022, one could say the buying power of the dollar went down by ~20% in those four years. [Inflation](https://www.forbes.com/advisor/investing/what-is-inflation/) (CPI) is usually a good measurement of the instability of the dollar. If we had a coin (let’s say “Cheesecake Coin”) that could buy 1 cheesecake for 1 Cheesecake Coin in 2018 and 2022, the buying power of that coin stayed the same across the four years, making it a relatively more stable stablecoin than a dollar-pegged one.
Anyways…
I won’t get into the mechanics of a coin like RAI here, as it’s pretty difficult to explain how they work without getting into the other properties of the coin. We will explain RAI more later on.
And will we be talking more about those in this article? You bet we will.
**Floating Asset Examples:** RAI
An Example
----------
To further clarify the difference, let’s take a buoy and an anchor as examples.
If you asked “is the anchor or the buoy more stable” how would you answer? Well, it depends on what you need it stable for.
If you’re looking for stable in relation to the ocean floor, the anchor is more stable. But if you’re looking for stable related to sea level, the buoy is more stable.
This a solid pegged vs. floating analogy. One may go further with the analogy and ask “what happens when a temporary storm comes, wouldn’t the buoy start rocking all over the place and going up and down, making it not stable?” To that I’d say, yes. This is why a lot of protocols like RAI account for that with built-in mechanisms to slow down rapid temporary changes. Imagine a buoy that stays at sea level, unless there is a storm. A “magic buoy” in a weird sense
You might even ask “well, isn’t the buoy sort of anchored then, since it needs to be tied down somewhere to stay in the same place?” To that I’d also say yes. A stablecoin that keeps its buying power can be thought of almost as an asset that tracks a sort of consumer index, or the long-term market movements of its underlying collateral. But we might be going a little too far down the analogy rabbit hole.
Stability Method
================
The stability method is the way the coin stays stable. It is on a spectrum of algorithmic to governed, where either it’s 100% automated by an algorithm, or it has some form of human intervention.
Algorithmic
-----------
An algorithmic stablecoin is any coin that uses an automated algorithm that, usually, mints or burns tokens in a specific way to keep stability.
The stability method could also be called the “supply mechanism” or “mint and burn” mechanism since they are so closely tied. These algorithms can also vary a LOT in how they are implemented. Rebasing, supply and demand games, and other oracle-based ventures are all different algorithms that many stablecoins use today.
**Algorithmic Examples:** DAI, FRAX, RAI, UST
Governed
--------
A governed stablecoin is one where a central issuer chooses when to mint and burn tokens. Now, this could be put to the extreme, where one person is doing the minting and burning, but it could be more algorithmic if there is perhaps a DAO voting on when to mint and burn. The Maker protocol is a fantastic example of how an algorithmic stablecoin can have a lot of governed properties — since the DAO controls so much of how the protocol operates.
A lot of times, centralized stablecoins are easily in the governed category, since a single off-chain entity controls their minting and burning.
**Governed Examples:** USDC, USDT, TUSD
Summary
-------
A token can have both algorithmic and governed mechanisms, and be on the spectrum of being more decentralized and algorithmic to more centralized and governed. With this definition, the DAI token would fall into the algorithmic category. USDC would fall into the governed category, being a deeply centralized stablecoin. Traditionally-thought algorithmic coins like the original LUNA/UST would also be considered algorithmic.
[The Dirt Roads](https://dirtroads.substack.com/p/-40-pruning-memes-algo-stables-are) article gives a great visualization of popular stablecoins and where they are on this spectrum. He uses “dumb” as the opposite of Algorithmic, which I don’t think is a bad replacement for governed.
The part we haven’t discussed is his **anchored** vs. **reflexive** spectrum. However, that comes next in the collateral section.
If we look at classically categorized “fiat-collateralized” stablecoins, they almost all fall into the “governed” side of minting mechanisms, since some single entity is doing the minting. Crypto-collateralized tokens like DAI have a governance process but are _more_ algorithmic in the algorithmic-governed spectrum.
Collateral Type
===============
The final and most important categorization of stablecoins is their collateral type. There are two types of collateral that protocols use, ranging on a spectrum once again, **endogenous** and **exogenous**.
Now, these two collateral types can be a little tricky to define, but as a test, you can ask:
If the stablecoin fails, does the underlying collateral also fail?
If yes, it’s endogenous; if no, it’s exogenous. Endogenous roughly means the collateral is embedded within the protocol, and exogenous means the collateral is completely different from the protocol. Some other good tests that people use are:
* If the collateral was created for the sole purpose of being collateral
* If the protocol owns the issuance of the underlying collateral
**Exogenous Example:** ETH is collateral for the DAI token. If DAI fails, does ETH fail? No, ETH still has smart contract uses outside of DAI and will continue to thrive. Therefore, the ETH collateral is **exogenous**.
**Endogenous Example:** Very roughly, the underlying collateral of UST was LUNA. In order to mint UST, you needed to burn LUNA, and vice versa. They were designed together at the protocol level, so very “in-bed” together. If UST failed does LUNA fail? Well, this was already proven to be true, so UST had **endogenous** collateral of LUNA.
It’s this endogenous scheme that most people are afraid of when they traditionally refer to algorithmic stablecoins.
Most stablecoin protocols are 1:1 or overcollateralized, meaning they have more underlying value backing the stablecoin than the total sum of the assets minted, whereas endogenous collateralized protocols can often be undercollateralized. FRAX is interesting in that it has a sliding scale of collateral, and is partially undercollateralized. It can become more exogenous or endogenous depending on current market conditions. The image below illustrates FRAX, DAI (MakerDAO), and UST (Terra).
**Endogenous Examples:** FRAX (sort of), UST
**Exogenous Examples:** DAI, USDC, RAI
Some Top Stablecoins
====================
DAI
---
The DAI token is one of the most influential tokens in crypto and is often cited for being the protocol that really kicked off the DeFi craze. DAI was revolutionary as it allowed more sophisticated financial products to emerge on the DeFi scene.
The DAI stablecoin is a pegged, algorithmic, exogenous collateral stablecoin. Now remember, it’s technically algorithmic, but it does have a governance process based on the MKR token and the interest rates of minting DAI, so it’s on a scale of algorithmic to governed. It’s actually a lot closer than you’d think. And now that voting proposals have passed to even allow [off-chain collateral into the system](https://cryptobriefing.com/makerdao-votes-to-loan-dai-to-us-bank/), the system has moved farther from the algorithmic mark.
Normally, the way DAI is created is that a user deposits some collateral, like ETH, into a smart contract. Then using an [oracle](https://chain.link/education/blockchain-oracles), you are given DAI that in total is less than the amount of ETH you put up as collateral.
For example, I put down 1 ETH, and at the time, 1 ETH is null,000. I can then mint 500 DAI. I always have to mint less DAI than I have collateral down, hence DAI being an **over-collateralized** system. The collateral of DAI is exogenous because it’s things like ETH and other cryptos that don’t need DAI to exist. One could argue though, that if DAI goes down, the value of ETH would go down too, so on a sliding scale, they are at least a tiny bit endogenous.
When I mint my DAI, I get charged a continuous stability fee to do so — usually around 2% a year. With this in mind, anyone who holds DAI is really holding someone else’s debt. Every year whoever minted the DAI is charged 2% for you to hold the DAI you have. This is why a lot of people talk about DAI as “debt” or “a loan.”
Now if your collateral falls below a certain threshold (usually, something around 200% of the value of DAI you minted) you can get what’s called [liquidated](https://itovault.com/how-dai-liquidation-work-makerdaos-mcd-system/). This is DAI’s solvency policy, to make sure it never has less money as collateral than DAI in the world. Essentially, if your balance of collateral falls too low, someone else can pay back the DAI you minted and get some of your collateral at a discount. So others are heavily incentivized to pay back your DAI loan if you default!
Keep this in mind as we go through these stablecoins. Most currencies are a form of debt.
USDC
----
[USDC](https://www.centre.io/usdc) is the coin behind the joint venture of [Circle](https://www.circle.com/en/) and [Coinbase](https://www.coinbase.com/home) and is a 100% centralized coin. The team behind the coin can blacklist users and is governed 100% off-chain.
The token is pegged to the dollar and is supposed to be backed 1:1. For every one USDC coin, there is one US dollar in a bank somewhere. Sometimes, they invest these dollars in other assets, so it might not even be backed by dollars but anything, like real estate, stocks, bonds, etc.
There are many tokens that have nearly identical setups to USDC, a centralized entity minting and burning tokens, pegged to the dollar, saying their tokens are backed 1:1 with US dollars. Protocols like USDT, TUSD, and GUSD all follow this blueprint.
FRAX
----
Now that we know more, we can take a look at more stablecoins and start to understand them more quickly. [FRAX](https://frax.finance/) uses its FLX governance token as part of its collateral as well as other tokens, and is known for being undercollateralized. This makes the token slightly endogenous since one of the underlying collaterals (FLX) would collapse if the FRAX system collapsed. It’s pegged to the dollar, and is algorithmic in nature, with some governance from the FLX token.
FRAX is our first token on the list to implement a version of the [seigniorage shares](https://blog.bitmex.com/wp-content/uploads/2018/06/A-Note-on-Cryptocurrency-Stabilisation-Seigniorage-Shares.pdf), but is still collateralized and uses a lot of exogenous collateral as well to prevent what happened with UST. What’s especially interesting about FRAX, is that the amount of exogenous vs endogenous collateral it needs can shift, based on how risky the protocol is at the moment.
UST (With the Original LUNA)
----------------------------
Now we know UST collapsed, but it’s important to reflect on this stablecoin as a cautionary tale of what can happen with algorithmic endogenous coins. UST was a seigniorage shares type coin with LUNA absorbing the volatility so UST could stay stable.
It ended up imploding on itself, as once the UST token lost its peg, more LUNA shares were minted to try to find the peg again when people redeemed their UST for LUNA just as in Robert Sams’ paper. However, as a LUNA holder, you don’t love the idea of more LUNA being minted, since that reduces the price of your LUNA, so if you see the UST peg falling, you start dumping your LUNA. This makes the total collateral of UST fall, meaning the UST loses its peg, meaning more LUNA is minted. More LUNA minted means more LUNA holders panic selling, which means UST losing its peg, which means more LUNA minting, which means more…
Do you see the issue here?
With the circular logic of endogenous tokens, there is a massive risk of these algorithmic systems working correctly. We say that UST/LUNA was **reflexive** in this sense since the value of the protocol was based on itself.
RAI
---
[RAI](https://reflexer.finance/) is one of the few stablecoins that is not pegged to another asset. It was originally up for governance on the DAI project but the Maker group decided to move forward with the protocol as we know it today, so many took off wanting to see improvements like:
1. Less governance
2. No peg
3. More “pure” collateral
If we want DeFi to stand on its own two feet, it would make sense that we wouldn’t peg our currency to the world’s nation-states. Additionally, the more governance in a protocol, the less algorithmic and trust-minimized it is. The purpose of web3 is to make transparent trust-minimized systems, and every piece of governance introduced is another piece that needs to be trusted.
Without going too deep into the mechanics of RAI, RAI is a coin that focuses on two prices, the market price of the coin, and the redemption price. The market price of RAI is the price people are buying and selling the coin at, and the redemption price is how much the protocol will buy your coin for. If the market price of the coin is too high, essentially the redemption price drops, and if the market price is too low, essentially the redemption price rises. This is how the coin is able to keep relatively stable buying power.
You can [learn more about it here](https://medium.com/reflexer-labs/stability-without-pegs-8c6a1cbc7fbd) or, in [this video](https://www.youtube.com/watch?v=wyr297JjEGY) which breaks it down with visuals. Essentially, RAI works similarly to DAI with users depositing ETH to get RAI minted, but the difference is that RAI isn’t pegged to a dollar. It instead uses supply and demand forces (via a sort of interest rate) to create or suppress demand, and has the value of the token very slowly follow where the market goes. This means, your buying power with RAI stays relatively the same over the course of time.
USD (the US Dollar)
-------------------
“Hold the phone, Patrick. The US Dollar isn’t a stablecoin!”
Yes, you’re right, but using the categorizations we came up with above, they actually apply to _all_ stable-type assets, and the dollar is one of those. And it’s interesting to compare because we want to make a world in Web3 that is better than our current system in Web2.
The easiest category to get correct is its stability — which is 100% governed. Sure they might use some algorithms behind closed doors to decide how much to print, but the monetary policy of the dollar is up to the US government, full stop.
Now collateral is particularly interesting, as the dollar was once backed by gold, but [taken off the “gold standard” in the 1970s.](https://owninggold.com/gold-standard/) Now, one US dollar is worth… one US dollar, which means the dollar is reflexive, and arguably, endogenous in nature.
However, you could argue the answer is no, and that the US dollar is backed by other national assets (political, military, technological, and geographic resources), which would make it exogenous.
So sometimes, it can be hard to tell what an asset is backed by.
Which Stablecoin Is Best?
=========================
There isn’t one: each has its tradeoffs.
Each stablecoin makes design choices that make them widely different from each other but accomplish similar things. There isn’t a “best” system, and we are seeing the industry constantly change.
Who Is Paying for Stablecoins?
==============================
Now that we have all this background information, we can get to the good stuff.
These stablecoins aren’t just popping up out of nowhere. Someone is making money off their creation. I told you at the start of the article that stablecoins are important because we need a medium of exchange, store of value, and unit of accounts — however, this is for the average person. I also said that stablecoins like DAI are a form of debt: someone is taking on the debt to get these good currencies into circulation. This means that the incentive to mint these stablecoins better be really good.
Let’s talk about that.
Creation of Currency (Debt)
===========================
Now, the exact date that [currency was created](https://en.wikipedia.org/wiki/History_of_money) is debated, but we can imagine it went something like this.
Person A: Hey, I’ll trade you 10 carrots for 50 tomatoes
Person B: Sounds good, but hey my tomatoes are back at my house. Can I give you these 50 signed rocks as a promise to get you the tomatoes?
Person A: Sure
Boom. 50 signed rocks are now money. 1 signed rock = 1 tomato from Person B.
Person A can now run around and trade these 50 IOU rocks for other stuff around the village. These IOU rocks though represent debt; they are the debt of Person B. At some point, person B needs to fulfill their debt (i.e. give the holder of a signed rock 1 tomato).
In the DeFi and stablecoin world, creating stablecoins works the exact same way. When you mint DAI, RAI, or most other stablecoins, they represent debt that you need to pay back to the system at some point, otherwise risk constantly paying interest.
Oddly enough, you could make the same argument that US dollars are debt, but the [argument gets a lot more complicated.](https://www.quora.com/Is-the-US-dollar-debt?share=1) Some might even argue that [all money is debt.](https://mises.org/library/our-money-based-debt)
Creation of Stablecoins
-----------------------
So, if in order for me to create a stablecoin, I need to take on this debt, why would I want to do this? Not only that, but most of the minting of these stablecoins or swapping the stablecoins for their collateral has some sort of fee associated with it! If we look at one of the [most popular DAI minting vaults](https://oasis.app/vaults/open-multiply/ETH-B), we see a fee over 2%! If we look at RAI, [we see it’s over 0.1%](https://app.reflexer.finance/#/)! Even USDC and USDT need to pay fees to swap your dollars and their tokens.
This means that whoever creates DAI, RAI, etc is paying a little extra. If I want $100 in DAI, I need to put down over $100 in collateral and pay maybe $2 in fees! Why would anyone do this? The normal users can’t be doing this, since spending $2 to get some silly stablecoin doesn’t seem worth it. So who is minting these coins?
Well, this leads me to what I think is the most important part of this whole article.
Stablecoins are not minted because we need a good medium of exchange, unit of account, and storage of value. They cost money to mint. Stablecoins are instead created for sophisticated investors to take leveraged bets or earn subsidized yields.
It’s funny.
Why are stablecoins good? -> Because we need currency!
Why are stablecoins minted? -> Because investors want to make leveraged bets.
Final Thoughts
==============
A lot of people look at stablecoins and think there is a [trilemma](https://stablecoins.wtf/resources/the-stablecoin-trillema) at play.
A stablecoin can be two of the three. I’m not so sure I agree with this trilemma, but we are still working it out.
Stablecoins are an incredibly important piece of making sure Web3 works. We need a token that people can transact in without the spikes and volatility of native blockchain assets.
There is a lot of work to be done. I’ve started by creating a [DeFi-minimal repo](https://github.com/smartcontractkit/defi-minimal/tree/main/contracts/stablecoins) with some stablecoin architectures that you can take a look at and hopefully learn from. As of now, we have a pegged, governed, exogenous coin and a pegged, algorithmic, exogenous coin for minimal examples.
Hopefully, we can get some more examples in there, and devs can build something even better.
Thanks all, hope you learned a lot here.
- I'm giving my @PyChainConf talk on @vyperlang in 10 minutes!
Come join :)
https://pychain2022.loudswarm.com/session/keynote-vyper-smart-contract-programming-language
- gm all
- Are there developer docs for lenster? I'd love to build a bot that auto pushes your tweets -> lenster and your lenster posts -> twitter.
- 👨💻 It's that day of the week again where I shill a template smart contract repo.
🐎🐴🎠🏇🏾🐎🐴🎠🏇🏾🐎🐴🎠🏇🏾🐎
♘ But yo... This one is crazy. ♞
🐎🐴🎠🏇🏾🐎🐴🎠🏇🏾🐎🐴🎠🏇🏾🐎
♘ The @huff_language x #foundry starter-kit is now live!
Let me tell you why huff makes me full of beans 👇
1. Horse
🐴 neeiiigghhhhhhhhhhh *horse whinny*
...but wait there is more!
2. Big Brain Opcodes Education
🧠 So if you're like me, you probably look at bytecode and push it away from your face like a child who hates being served green peas.
You know you SHOULD be an EVM savant, but solidity & vyper just make knowing that stuff a bit "extra".
😎 Working with Huff makes learning low-level EVM assembly... Fun.
Dare I say assembly is fun, sacrilegious I know.
🫵 And those who want to become auditors, yeah you, you better learn opcodes.
3. Optimiiizzoooorrrrrs eat your heart out
👾 You could write everything 100% in bytecode and then slowly turn into a robot, or write huff and get all the advantages whilst remaining human.
Huff gets you VERY gas-optimized contracts since you build them opcode-by-opcode.
I've already started doing some gas comparisons 😉
Now, that being said, for a lot of projects, huff is likely overkill. But for that contract that you need PERFECT... Well, you know the solution.
1. Horse
2. Learn EVM
3. Optimized
🏇🏾 Now, be sure to check out the huff starter kit:
https://github.com/smartcontractkit/huff-starter-kit/
It shows some minimized examples on working with @chainlink'd smart contracts.
🏀 Like and retweet if you're going to try out Huff to bring your audit skillz to the next level.
- Why isn't everyone here yet
- Twitter down, let's party Lens Frens!!
- Whatup web3