Building a Guestbook dApp with Vue.js and Truffle – James Kehoe
Open up truffle-config.js and modify module.exports to tell Truffle to place its JSON build output inside the src folder where the front end can access it.
Inside the contracts folder (in the project root, not src/contracts), create a new file called Guestbook.sol and create the contract.
The first line declares which version of the Solidity compiler this contract should use. For our purposes, we’ll use the same range of versions as the contract created by running truffle init.
The next block is the contract. First we make an event to fire whenever a signature is added. Then we make an array to hold the names. Next, a method to push a name to the array and emit the event to anyone that’s listening. Finally, we create a method that returns the list of names.
The contract is ready to deploy! But first we need to create a migration to tell Truffle about our new contract. Inside the migrations folder, create a new migration file called 2_deploy_guestbook.js. Add the following contents:
Back inside your console in the project root directory, initialize the Truffle dev console.
You’ll be rewarded with your own personal blockchain! There’s a list of addresses and private keys, as well as the mnemonic you’ll need to connect to this wallet elsewhere. You’ll notice your console has changed to truffle(develop)>. To both compile and migrate your contracts with one fell swoop, simply run:
to start with a fresh slate every time you migrate and ensure changes to your contracts propagate.
If all goes well, you should see a bunch of data related to the successful deployment of the contact to the dev blockchain.
Open up a new console (keep the Truffle REPL running — as your app needs a blockchain to connect to), head into your project root and install Drizzle Vue Plugin.
npm install @drizzle/vue-plugin
Next, go into thesrc folder and make a file called drizzleOptions.js. This file will contain the configuration for Drizzle. Add the following code:
import Guestbook from "@/contracts/Guestbook.json";const options =
},// The contracts to monitor
contracts: [Guestbook],
events: ,
polls:
};export default options;
Here, we tell Drizzle where the contract build artifacts are located, register the Guestbook contract, and tell Drizzle which events it should listen for that might be emitted by the contract.
Open up main.js and make it look like this:
import Vue from "vue"
import App from "./App.vue"
import store from "./store"import drizzleVuePlugin from "@drizzle/vue-plugin"
import drizzleOptions from "./drizzleOptions"Vue.config.productionTip = falseVue.use(drizzleVuePlugin, )new Vue().$mount("#app")
Here, we’re importing the Vuex store, the Drizzle plugin, and the options file we just created. Then we’re telling our app to use the plugin, and passing in the store and options file as parameters to the plugin.
Open App.vue and edit the template section. Be sure to remove any boilerplate code generated by the Vue CLI, such as HelloWorld components or unwanted styles:
<template>
<div v-if="isDrizzleInitialized" id="app">
<h1>Sign the Guestbook</h1>
<drizzle-contract-form
contractName="Guestbook"
method="signBook"
:placeholders="['Name']"
/>
<h2>Guests:</h2>
<ul v-if="getNames">
<li v-for="(name, i) in getNames" :key="i">}</li>
</ul>
</div>
<div v-else>
Loading application...
</div>
</template>
First, the template contains a v-if/else at the root. If Drizzle is not yet initialized, your smart contract data won’t be available and you’ll want to display something else in the meantime.
There’s a custom component called drizzle-contract-form, which is registered when you install the Drizzle plugin. Given the name of a contract and method, it will generate inputs corresponding to the input parameters expected by the contract. You can also set an array of placeholders which display in the order of parameter values.
The next section gets the list of names and iterates over them in an unordered list. We’ll build the getNames method shortly, but notice the transformation being applied to the list values. We need to convert the bytes returned by the smart contract into utf-8 strings, unless you prefer displaying hex code. For this, we’ll bring in some utilities.
Here’s the<script> section of the file:
<script>
import from "vuex"export default );
if (data === "loading") return false;
return data
}, utils()
}, created() )
}
}
</script>
Here’s the breakdown:
- Import
mapGettersfrom Vuex to allow access to Vuex store modules created by the plugin as computed properties in our component. See their documentation for more information about how mapGetters works. - Use
mapGettersto import several Drizzle functions from the store. We need adrizzleInstancefor its utilities to transform text.isDrizzleInitializedreturns a boolean that we can use to conditionally render the app, and show some type of ‘loading’ indicator when it’s not quite ready. Finally,getContractDataallows us to pass in the name and method of a contract and receive its state data in reactive fashion. Neat! - Get the list of guestbook names using
getContractData. Check the return value to avoid breaking anything in the layout. - Import utilities from
drizzleInstanceto transform hex to readable text. The Drizzle instance extends web3.utils — check out the docs for a better understanding of the types of operations available. - When the component is created, register the contract, method, and arguments using the
REGISTER_CONTRACTaction from the plugin. This sets up the contract in Drizzle, and makes its data and functions available to your app, including thegetContractDatamethod.
We’re ready to run the app!
In your terminal:
npm run serve
You can also use yarn serve if that’s your preferred flavor. On building successfully, a development server should start up.
Head to one of the URLs. We’re going to use Metamask in this example, but you can use any other web3 browser as long as you can import an account and customize the RPC URL.
If you’re on Metamask and don’t want to lose your current wallet, make sure you’ve exported your seed phrase (Settings -> Security & Privacy).
Log out of Metamask, then on the login screen click Import using account seed phrase. Use the seed phrase provided by truffle develop and your wallet should populate with the accounts shown in the Truffle console. In your app, you should now see an input field where you can add and submit a name to the list. Try it! Within a few seconds, you should see a name appear in the list below.
You did it! In the next part of this series, we’ll deploy the smart contracts to the Ropsten Ethereum Testnet. Stay tuned!
Published at Sun, 29 Sep 2019 16:15:12 +0000
{flickr|100|campaign}
