Practical Design Patterns for dApp Developers by Josh Fraser (Devcon5)
Devcon·Fri, Oct 9, 2020, 12:00 AM
Visit the https://archive.devcon.org/ to gain access to the entire library of Devcon talks with the ease of filtering, playlists, personalized suggestions, decentralized access on IPFS and more. https://archive.devcon.org/archive/watch/5/practical-design-patterns-for-dapp-developers Used to building apps in Python or Ruby on Rails, but new to blockchain? This talk is aimed at experienced developers who are new to Ethereum. My goal is to give developers practical frameworks for architecting their decentralized applications, that will minimize gas costs, reduce the attack surface and simplify upgrades. Decentralized applications require a new way of thinking. I want to share some templates for developers who are making the jump to decentralized applications and aren't familiar with the quirks and limitation of the Ethereum EVM. We will look at the following Solidity design patterns: Approve and call Factory contracts Proxy contracts Name registry Upgradability As well as ways to reduce gas costs without compromising on security, including: Event sourcing Using IPFS effectively Building decentralized applications is hard. The stakes are high and there are a lot of ways to get things wrong. Mistakes can be expensive, either from security losses or high gas costs. I’m looking forward to sharing some of the lessons Origin’s engineering team has learned over the past two years building peer-to-peer marketplaces on top of Ethereum. Speaker(s): Josh Fraser Skill level: Intermediate Track: Developer Infrastructure Keywords: technical Follow us: https://twitter.com/efdevcon, https://twitter.com/ethereum Learn more about devcon: https://www.devcon.org/ Learn more about ethereum: https://ethereum.org/ Devcon is the Ethereum conference for developers, researchers, thinkers, and makers. Devcon 5 was held in Osaka, Japan on Oct 8 - 11, 2019. Devcon is organized and presented by the Ethereum Foundation, with the support of our sponsors. To find out more, please visit https://ethereum.foundation/
Transcript
[Applause] how many of you have built an app been used by thousands of users okay amazing guy could develop a problem keep your hands up and you built a decentralized app where free app has been used by thousands of users great we still have a few minutes this talk is designed for developers who may be due to read free space and I want to share some of the lessons we've learned from building origin so for both of you who are not familiar origin is a decentralized market place on the blockchain for enabling peer-to-peer commerce and without any middleman or intermediaries we've been working on it for about two years now our team includes people like one of the founders of PayPal the first special YouTube bunch of engineering managers from Google and Dropbox and we've got as of today we have of 69 thousand unique wallets that are using the marketplace and so I'm going to share some of the tips and tricks that we've learned from from building that and are relying heavily on my experience fair for some of the examples on how you can apply these design patterns to your own applications so what's unique about Bennett building on inferior well some of these are quite obvious gasps it's not something you have application you don't have to worry about the mutability as developers one thing we know for sure is you're not going to get everything right first try but how do you deal with that in wrong way you can't change anything in fact it's written to the blockchain for all eternity and how do we deal with some of our unfamiliar usability challenges of the blockchain because like why do we need gas right well it's fairly to allocate scarce resources against miners an incentive to secure a network and this is deterrent for abuse it's actually this really important concept but also it really sucks users aren't used to paint the gas you've got things like tammer and crypto kitties or fairway and clogging up the network and making your app really expensive or broken to use and then most people on this planet don't have a fake so how do you deal with that and when we look at what we've spent most of our time working on at origin over the last two years it's all related to that or one of them a lot of these problems are related to this concept of gas how do we minimize the gas cost or how to get rid of it altogether so the first thing you can do is just fill ins the word as much data contain what you can do here is I said strong on a Content Hatcher this is a very basic technique which we use for storing all of the data that our application needs we store on ipfs the content-addressable peer-to-peer file system and this is still secure because if you change one bite of that content it will get a completely different hash mr allows us to save a lot of money on gas goes by storing just content Harrison instead now you do have to worry about the deed of surviving might have a risk of data loss if you're not replicating that data there's no risk of that gonna be tampered with it's still secure so take a quick look at what our tap looks like so this is the origin marketplace this is live on main app on Ethernet has been ported twice of time you can see you can buy or rent all sorts of different items on this market based on all these assets are being fetched from a fearin blockchain and from EMS so here's my apartment and Sam Cisco you're all welcome to come state any time you can Lucas on watching this go okay what's that any discord with it well it's quite it just kind of phrase actually if you've ever written a confidence section 14 you can pay with Imperium or die and ending seniors you know a real nice party to Sean Penn State in such Bailey the scenes missus the data of it represents that listing it's just a big blob of JSON has all the details about this apartment it's got some links to you know the pictures here on ipfs but what we actually store on chain it's just this little part of URL right here for entry characters of a 19-minute slash and if you change one character it is JSON blog all that goes away so this saves us a lot of money by sorting in instead of doing it sort of always walk it off so actually put some numbers to this you actually look at how much gas it costs to store data across twenty thousand gas to store Freddy two bytes for a thirty two small pipe afraid to quite slow on the very I'm even modifying data caused by thousand gas if you delete data it cost five thousand gas but then you get a 15 thousand gas refund from when you first stored it but one thing you'll notice here on the right we have log and so it's way cheaper for us to write to logs and is to store data on a chain so whatever tricks that we've leaned on very handily at our gym is just emitting events instead of actually storing a tentative variables so pearls are pretty obvious seen save a lot of gas that's far more gas efficient to use events the only problem is that smart contracts can't read the locks so you have a nice database of all the different events but you have to have someone willing to be able to index those events from the locks and you know things like if you are you have to pay extra for it if you have the full mobility running to have some way of indexing ballistic sensitive but is worth doing if you can another trick if you are storing data on the blockchain it's helpful to understand how big EVM is storing data under cover so those ready to fight slots actually matter so you knew things like variable packet where you take before during which you analyze these variables and actual matters so if you've got you know be a B and C these three variables to around 128 back one is 256 pence now you can either pack it into two slots or free slots depending on the order those variables as a difference of my thousand yes just by swapping the order of high a might include how many of you know what you meant sourcing is the introduced time so some of you okay so I guarantee even if you don't know the term all of you know this concept it's essentially what the blockchain does if you were to fire off a film node and started a Genesis block and work your way to today to get the current state of how much money we all have lots events or some where you're actually building up a state based on a list of events instead of doing it as the current state distorting a snapshot of the current state doesn't need to the concept to blockchains it's also something that's really helpful when you're actually designing an app so here's how we do it and ordinance so here's an idiot so this is a tool we built that lets you sort of wonderful covers of our marketplace and actually look at all of the IP advantages and natural actions and all the data that we point to generally hide away from the users and so you can see here this list of all the events have been happening on my apartment so you can see when I first created it and the blob of JSON it was created and then I updated it a few times and then some of made an offer on it and then I accepted that offer and then they left to review it after it was the offer was completely after the cooking was completed we've got some some more offers coming in and I said to those as well and so instead of storing a calendar on the blockchain about which days my apartment is available can you think about doing that in salinity the amount of complexity of writing that code like word if you want to come in and block off the month of July well do you put that in for lit up and do it like how expensive is that going to be to update that all of your storing all I didn't love Gina is crazy so instead what we do is we don't don't even try we just omit these events with each of the offers of command when I accept them and then you can use JavaScript you can is very easy to walk through this list of events with JavaScript and rebuild the state of the world so if you want to know if my apartment is available or not the only way to do is go back to the star walk through all of them see which offers I accept I turn down and now you've got the sense of the state of the world and as way way cheaper as Whaley easier than trying to do everything my chain [Music] so named registries is another concept you should be aware of ENS is probably the best known example like take some when you want to map two things together so you take Josh phaser gives a nice friendly name and you can map it to an address Burton has one we have an identity contract where we publish identity access stations for all of the users on marketplace but as you might guess by now we don't actually store that data we just emit events and what might be was simply smart contracts you can have basically two functions they met identity updated it's you know the first message sender of your wallet and an idea pass hash with the artist stations on your profile and then we have identity deleted which if you ask nicely we will delete your rule unpin your data if you ask us to from ipfs factory contracts so these are super useful and another way to save on gas costs they allow you to basically clone an existing smart contract to use that as a template for the code that you want to have run a great example of a server enosis multi-sig watts so you can deploy your own multi sync with your own funds and patrol it but it uses all of their code and you can deploy that in a very cost-efficient way and we do this for deploying our proxy contracts which we'll get into a little bit the court is really simple you just use this master coffee you pass in the master operative contract you want to call and then use the magical like over here and you have a copy of that smart contract yes what are the tricks with you think Museum it's predictable smart contract addresses and so you can actually know the address of a smart contract reliably before it's even enlightened on the blockchain and so you can know it before where it exists and this is really useful for eliminating the need for a name registry so we can do is pass the order of proxy contract and a nonce and optional bonds to create two and then that will give you the address of where that proxy contractor is going to live so for origin we create a proxy contract for each of our users and then we deterministic we figure out where that contract is going to live and that way we don't have to use a name registry at all for doing that look up and figuring out who we are we are a proxy contract will actually live to see that code right here on how you do that so many transactions mentioned it in the last talk manage transactions the high levels is the way for you to sponsor the gas on behalf of your users and this is something that we rolled out at origin because one our first-time users to be able to get up and create a listing without having to have a few pennies of gas in their wallet the challenges the theorem says the person who signs a transaction is a person who has to pay the gas you can't have two different signatures on a transaction and so you have to jump through all these crazy hoops in order to do something as simple as paying the gas for someone else and so that's what we use our proxy contracts for a sign of transaction you send into our relay our relayer then deploys that proxy contract if it doesn't already exist and then since that you're saying to contract or your signed transaction - of a proxy contract any relays along to the destination contract we want that code to actually be executed and so the end result is pop-up it looks like this it says your signatures being requested but nope there's no gas associated with it so now you can actually write the other to the wall chaining thanks acute code and in yes you need to sign it to prove it you control of wallet you don't have to pay any gas so let's talk a little bit about different options for upgrading your code all right we don't have this problem in centralized application is very easy to operate your code but in this world that everything is immutable so one option some goes by different names we call master slave you have one smart contract it's just Italian proxy contract to tell everyone hey here's our proxy here's our code just update available with the smart contract but actually being called behind the scenes from of us of course is you have to interview users have to trust your operators be delicious it's well been malicious smart contract in place today yosef is probably wreck data gets fragmented because every time you update your smart contract the data starts living on both of our smart contracts instead okay not a great model that we do it is store your data your logic separately so you take approximation so cable over heaven will keep all the data on this contract but will just bring in new smart contracts for the logic and that helps quite a bit but you still have a problem what if we change the data structure so how do you do that well you can use a few value type structure where you just say okay we just add on new deals and anytime that works pretty well the only downside is that costs a lot more gas to all that sort of computation and remapping stuff the other day you can just pause the contracting to start over thank poor everything over and just do it again it's depending on your scenario sometimes that makes sense so what we do at our origin is we say like a lot of things we'll just do it in JavaScript instead keep our smart contracts is DOM and as simple as possible and instead will write adapters and know how to transform between each of a different versions of our smart contract and you can apply these adapters recursively so every version knows how to get back to the previous version and you can very simply adapt your gap across these different versions you're smart contract so let's talk a little bit about UX how many of you have seen this type of pop-up common manifested for what what makes no sense to me let alone the average user what is this why is this popping out the minute I tried and there's any sort of decentralized exchange and so reason you're seeing this is because of the fact that you have to move in your c28 token or for a smart contract to move near c22 okay it first has to have approval from user that makes sense these they have an allowance on how much how many tokens is allowed to do so the problem is is that you have two different meta max pop-ups that's how you have to do to do anything related to tokens one you have this crazy thing and then you have a second one which actually pokes a smart contract to actually move the tokens to where they need to be the reason you're seeing this that's pretty easy pop out is very they don't want to show us to you once and so we just go ahead and ask for like and basically in phenomena of tokens that they should want to be able to move but it was very confusing user experience and now we're going to be more lenient but an Orangeman like how do we get rid of that right huh me we how do we live our tokens from our marketplace contract without having to show that mana mass pop up every time and so looks like there's prior to working on this first GRC 8:27 which proposed combining these into a single step approved and called let's just do them both at the same time I would say great this is this is awesome this is what we're looking for and then we started reading the comments on it it's acceptable to every inch the attacks but we realized that the only problem but you can't use that with any untrusted smart contract but if you have your own trusted smart contract you can actually lock this down you can actually have a protocol Westerner and so what we did our tame this is live on our you know c20 contract has been audited by kilobits you can actually safely buying those two into one step and so your users only prompted one time to both approve and call whenever we use order tool kits on or is this marketplace and here is the code of how you do that's very simple the only thing we really added to say this was just put the whitelist and so I think I'm pretty much out of time here but last time I'll say towards is 100% open source and and all over do all our work in public so you know come join us in our escort we have over 160 contributors to our code base and we'd love to have more so thanks for your time and hope to see you guys [Applause]
Automatic transcript — names and jargon may be misspelled.