Building on Ethereum: Part 6 – Bootstrapping the Client
Check out the latest installment on building Ethereum smart contracts.
Join the DZone community and get the full member experience.Join For Free
in this series, i’m discussing the phases of a project encompassing a non-trivial set of ethereum smart contracts and the react/redux application that communicates with them.
the project, called in-app pro shop , aims to help ethereum developers easily support in-app purchases, and it was written over the last half of 2018 as a way of learning about the ethereum development ecosystem.
this project revealed many aspects of the power and constraints of ethereum and its programming language, solidity. i hope to pass as much of that on to you as possible in this series.
what i’ll be doing here is showing you the unique aspects of a client that talks to the blockchain on behalf of a user that has authenticated with a blockchain-aware browser or metamask . for the purposes of the article, i’ll assume you’re running metamask and have configured it as described in part 3 .
first things first
given that we have ganache running, with our contracts deployed and mock data created, there are two things that need to do before anything useful can happen in this client:
- authenticate the user in some fashion so that we can make blockchain transactions on their behalf
- connect to the blockchain so that we can send transactions or invoke methods that request data
how do we achieve those tasks?
web3 – the low-level ethereum api
from your application’s perspective, both of these things will be handled by a library called web3.js .
your app’s awareness of the user will be strictly reduced to list of the accounts that are made available to you by web3. all interactions with the blockchain will happen via web3. you can instantiate web3 yourself, or you can snag metamask’s instance. if metamask isn’t running in your browser, then your instance can still connect to ganache and get the accounts it created at startup.
now, if you followed the web3 link above and had a look at the api, it might seem a little daunting. it’s definitely a low-level api that requires you to know a lot about the nitty gritty details of ethereum. when i began the in-app pro shop client, i started with web3 and nothing else. i was able to make progress, but i quickly realized there were a lot of places i could drop the ball.
fortunately, our friends over at consensys realized this and provided us with a much friendlier tool called drizzle . if you’re using react as we are, drizzle, is just about the quickest way to get to the joy.
drizzle – the high-level abstraction you need
drizzle is based on a redux store, which you’re free to use for managing the entire state of your app. i preferred to keep state in my own store while allowing drizzle to maintain its own state. you can treat drizzle as a black box that provides you with:
- the accounts you are authorized to use
- a local cache of relevant blockchain data for speed
- events from the blockchain (although the implementation is less than complete at the moment)
- representations of your contracts via truffle’s contract abstraction, which we’ve talked about previously and used in our contract unit tests
at startup, we need to create drizzle’s store, configured with everything it needs to know, including references to our compiled contracts. drizzle uses react’s context api to provide us with a handle to everything we need to interact with it. in my honest opinion, this wasn’t the best choice, but it works. it just led to an unavoidably obtuse bit of bootstrapping code, which we’ll see and unravel in a moment.
we also want to create our own redux store in the usual way. finally, we need to create our main app component. i haven’t added routing to this application, primarily because to support bookmarking of a route would be overly complicated given the possibility of multiple shop owner accounts with multiple shops.
bootstrapping with index.js
bearing all this in mind, let’s have a quick look at the index.js file for our react app.
in the imports section, the one notable thing to touch on is the
stockroom imports that come from the “/abi” folder. you may recall from part 1 that we’re using the create-react-app scripts and one of the prohibitions we’re laboring under is that all imported files need to come from the “/src” folder. from react’s standpoint, “/abi” is actually “/src/abi”. also, we had to configure truffle to output its compiled contracts to this folder so that we could import them. that was done in truffle.js .
that leads us to the
first, we pass the
stockroom imports to drizzle in the "contracts" section. simple enough. drizzle will use these compiled contracts to give us our contract abstraction that we can call methods on later.
the “events” section enumerates each contract and its events, which we presumably want to listen for and be notified about. as i mentioned above, this part of drizzle is not fully implemented at the moment, so they’re just here for form. later, we’ll get into how we handle the events using the underlying web3 library when needed.
finally, there is a “web3” section where a fallback is defined as a websocket to a port on our localhost. this is used if drizzle doesn’t find a web3 instance initialized by metamask. that allows us to talk to our local ganache instance directly if metamask isn’t installed.
instantiating drizzle and its store
drizzle has its own store, which we first create with
generatestore , passing it the
drizzleoptions we defined above. then, we instantiate drizzle itself, passing in the
drizzleoptions and the
drizzlestore we just created. i think that could have been done with a single call to a static factory method on drizzle, but i’m sure the architects at consensys had their reasons for doing it this way.
the render function
i said that the context api was maybe not the greatest choice for how to build this thing. that’s mainly because only the app component uses it and react’s context api is really meant as a way of letting descendent components magically access a context created above it somewhere without having to explicitly pass that context through intermediate components that don’t need it as props.
but here, only the app component needs access to the drizzlecontext, and its needed in
componentdidupdate , so we actually have to create the context. then, we need to get the context from the consumer and pass it into the app component as a prop anyway.
creating the context is done with the outer
drizzlecontext.provider wrapper, which we pass the
drizzle instance to. then, we instantiate the
provider for our own redux store in the usual way. inside that wrapper, we have a
drizzlecontext.consumer , which takes the
drizzlecontext , it gets from the
drizzlecontext.provider above it and returns an instance of our “app” component with
drizzlecontext as a prop.
could this be simpler? absolutely, i believe it could. but at least it’s contained to this one bootstrap file, and now, our app component can access the
drizzlecontext and all its goodness inside
componentdidupdate , which it will need to do in order to further orchestrate the startup process.
regardless of startup elegance or lack thereof, let’s move on and see how app.js takes this handoff and runs with it.
state management handled by the app component
in app.js , the component will orchestrate the rest of the startup process by watching drizzle’s state and our own store’s state in its
componentdidupdate method and taking appropriate actions on certain changes.
in the partial extract below, you can see that method and the state and action dispatchers we’ve mapped to props for the component using
drizzlecontext object, we get
drizzlestate , and
initialized . the initialized variable tells us when drizzle has managed to connect to web3 and has our contracts and accounts ready to work with.
we’re going to take our actions in
componentdidupdate only when something changes, and we know that by comparing the current values to the previous props. this is important so that we don’t get into a loop of continuously performing an action.
this method handles not only the startup of the app, but also a few state changes that are necessary when the user changes the selected account or shop.
things that happen automatically at startup
- store the accounts when drizzle initializes
- select the first account when the accounts are fetched
- get shops when an account is selected
if you are connecting to ganache, you might get ten accounts when drizzle initializes. if you’re connecting to metamask, you’ll only get its selected account. the former case is most likely true only during development and testing. if almost all of the time we’re only going to get a single account to work with, then we don’t want the user to have to manually open the accounts menu and select their sole account. so, we’ll automatically select it.
further, when whenever an account is selected (automatically at startup or later by the user), we’ll want to fetch all the shops for that account and populate the shops menu. if you need a refresher on what the interface looks like, pop back to part 2 .
when drizzle first initializes, if there are any accounts in
drizzlestate.accounts , we pass them to the action dispatcher
accountsfetched , which will in turn trigger a reducer to persist them in our store. that will in turn cause our mapped
accounts prop to change by way of
auto-selecting the first account
accounts prop changes, and has a non-zero length, we pass its first element to the
selectaccount action dispatcher. this will lead to our
selectedaccount prop changing via
fetching the selected account’s shops
selectedaccount prop changes and is non-null, we call the
getshops action dispatcher, passing the
stockroom contract (plucked by name using a constant from “drizzle.contracts”) and the
things that can happen on user interaction
- get shops when an account is selected
- get skus and skutypes when shop is selected
an account is selected
the user will only be able to select a different account if they have connected to their local ganache node via the drizzle fallback configuration when metamask and web3 are not present. still, it can happen and falls into this category as well as the startup conditions.
a shop is selected
we don’t automatically select a shop if there is one, because that we don’t want to fetch too much data in case the user has multiple shops or intends to create a new one in this session. we wait for them to make a selection or create one. when the
selectedshop changes and is non-null, we do the following:
- get the shop’s balance by passing the
- get the skutypes (categories) by passing the
stockroomcontract and the
selectedshopidto the getskutypes action dispatcher
- get the skus (item descriptions) by passing the
stockroomcontract and the
selectedshopidto the “getskus” action dispatcher
rendering the ui in the app component
we’ve seen how the app component gets its relevant state and action dispatchers, how it automatically fetches accounts when drizzle is initialized, automatically selects the first account, fetches the shops when the selected account changes, and checks the shop balance and fetches skus and skutypes when the selected shop changes. now, let’s see how we render the ui in the following excerpt.
the render method
render method is sleek and only needs to return the
navigationbar component and whatever is appropriate for the content section below it. it wraps these two items with the styled components
themeprovider and our custom kitwrapper , which is basically a styled html section element. it gets both the elements it needs to wrap from two helper functions.
the rendernavigation function
basically, all this function does is return our custom navigationbar component, passing
drizzlestate , and
initialized from the
drizzlecontext as props.
the renderappcontent function
this function returns either a shopview component or a splashview component, based on whether there is a
selectedshopid . the returned component also has
drizzlestate , and
initialized as props passed from the
splashview component renders the page that welcomes the user and offers a “create shop” form. the
shopview component displays and allows editing of an existing or newly created shop.
(not the) conclusion
in this part, we’ve seen how we use drizzle to mediate between our react client and the ethereum api (web3).
if metamask is available, we get the selected account from the authenticated user; otherwise, we can fallback to a websocket connection to our local ganache instance, where we would receive multiple accounts. accordingly, we auto-select the first account we receive and then fetch any shops that account may have associated with it so the user can choose one to edit or create a new one if they want.
we saw how the app manages all this and renders an appropriate screen to the user depending upon whether there is a selected shop.
coming up, in part 7, we’ll go deeper into the ui and how we interact with the contracts as the user engages with the application. stay tuned!
Published at DZone with permission of Cliff Hall, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.