Counter Webapp
Now we have the Counter smart contract and deployed it to the CLV local node. It's time to make changes to the web app so that it can interact with the Counter smart contract instance.

Preparation

Setup the browser wallet

As it's a web application, make sure you've setup a browser wallet that connects to the local node. Follow the tutorials in the Quick Start section if you have set it up yet. In this guide, we assume you connect to the local node using the MetaMask wallet.
MetaMask is the most commonly used browser wallet for Ethereum like blockchain networks. We can use MetaMask to connect to CLV network since CLV is fully compatible with Ethereum.
After you have the wallet installed, import the dev account , you can import the dev account using the seed phase:
bottom drive obey lake curtain smoke basket hold race lonely fit walk
Or using just the private key:
0x03183f27e9d78698a05c24eb6732630eb17725fcf2b53ee3a6a635d6ff139680
Do not use this key or seed phase in any real chain to store your assets! It's for test only, you will lose your money if you used them in any real chain!

Install Packges

Install necessary packages before we start:
1
$ yarn add @web3-react/core @web3-react/injected-connector @ethersproject/providers
Copied!
The @web3-react packages provide pretty good web3 utilities for react application to talk with web3 compatible blockchain. @ethersproject/providers give use the web3 providers.

Connecting to the wallet

The first step is connect our Counter DApp to the browser wallet. Firstly we need to create several files.
connector.js
1
import { InjectedConnector } from '@web3-react/injected-connector'
2
​
3
export const injected = new InjectedConnector({ supportedChainIds: [1337] })
Copied!
We make a InjectedConnector and specified the supported chain id to include the CLV chain id 1337.
hooks.js
1
import { useState, useEffect } from 'react'
2
import { useWeb3React } from '@web3-react/core'
3
import { injected } from './connectors'
4
​
5
export function useEagerConnect() {
6
const { activate, active } = useWeb3React()
7
​
8
const [tried, setTried] = useState(false)
9
​
10
useEffect(() => {
11
injected.isAuthorized().then((isAuthorized) => {
12
if (isAuthorized) {
13
activate(injected, undefined, true).catch(() => {
14
setTried(true)
15
})
16
} else {
17
setTried(true)
18
}
19
})
20
}, []) // intentionally only running on mount (make sure it's only mounted once :))
21
​
22
// if the connection worked, wait until we get confirmation of that to flip the flag
23
useEffect(() => {
24
if (!tried && active) {
25
setTried(true)
26
}
27
}, [tried, active])
28
​
29
return tried
30
}
31
​
32
export function useInactiveListener(suppress = false) {
33
const { active, error, activate } = useWeb3React()
34
​
35
useEffect(() => {
36
const { ethereum } = window
37
if (ethereum && ethereum.on && !active && !error && !suppress) {
38
const handleConnect = () => {
39
console.log("Handling 'connect' event")
40
activate(injected)
41
}
42
const handleChainChanged = (chainId) => {
43
console.log("Handling 'chainChanged' event with payload", chainId)
44
activate(injected)
45
}
46
const handleAccountsChanged = (accounts) => {
47
console.log("Handling 'accountsChanged' event with payload", accounts)
48
if (accounts.length > 0) {
49
activate(injected)
50
}
51
}
52
const handleNetworkChanged = (networkId) => {
53
console.log("Handling 'networkChanged' event with payload", networkId)
54
activate(injected)
55
}
56
​
57
ethereum.on('connect', handleConnect)
58
ethereum.on('chainChanged', handleChainChanged)
59
ethereum.on('accountsChanged', handleAccountsChanged)
60
ethereum.on('networkChanged', handleNetworkChanged)
61
​
62
return () => {
63
if (ethereum.removeListener) {
64
ethereum.removeListener('connect', handleConnect)
65
ethereum.removeListener('chainChanged', handleChainChanged)
66
ethereum.removeListener('accountsChanged', handleAccountsChanged)
67
ethereum.removeListener('networkChanged', handleNetworkChanged)
68
}
69
}
70
}
71
}, [active, error, suppress, activate])
72
}
73
​
Copied!
hooks.js provides several hooks to help connect with the wallet.
Spinner.js
1
import React from 'react'
2
​
3
// <!-- By Sam Herbert (@sherb), for everyone. More @ http://goo.gl/7AJzbL -->
4
export function Spinner(props) {
5
const { color, ...rest } = props
6
return (
7
<svg width="38" height="38" viewBox="0 0 38 38" xmlns="http://www.w3.org/2000/svg" stroke={color} {...rest}>
8
<g fill="none" fillRule="evenodd">
9
<g transform="translate(1 1)" strokeWidth="2">
10
<circle strokeOpacity=".5" cx="18" cy="18" r="18" />
11
<path d="M36 18c0-9.94-8.06-18-18-18">
12
<animateTransform
13
attributeName="transform"
14
type="rotate"
15
from="0 18 18"
16
to="360 18 18"
17
dur="1s"
18
repeatCount="indefinite"
19
/>
20
</path>
21
</g>
22
</g>
23
</svg>
24
)
25
}
Copied!
Spinner.js implements a simple spinner component which could be used as the loading status.
Update the App.js to set its content to:
App.js
1
import { Web3ReactProvider, useWeb3React, } from '@web3-react/core'
2
import { Web3Provider } from '@ethersproject/providers'
3
import { useEagerConnect, useInactiveListener } from './hooks'
4
​
5
import './App.css';
6
​
7
function getLibrary(provider) {
8
const library = new Web3Provider(provider)
9
library.pollingInterval = 5000
10
return library
11
}
12
​
13
function ChainId() {
14
const { chainId, library } = useWeb3React()
15
​
16
return (
17
<div className="ChainIdWrapper">
18
<span>Chain Id</span>
19
<span role="img" aria-label="chain">
20
β›“
21
</span>
22
<span className="ChainIdText">{chainId ?? 'Not Connected'}</span>
23
</div>
24
)
25
}
26
​
27
function App() {
28
const triedEager = useEagerConnect()
29
​
30
return (
31
<div className="App">
32
<header className="App-header">
33
<h1>Counter Example </h1>
34
<ChainId/>
35
<p>
36
Current value: n/a
37
</p>
38
<button className="CounterButton">Inc Counter</button>
39
<button className="CounterButton">Dec Counter</button>
40
</header>
41
</div>
42
);
43
}
44
​
45
​
46
export default function() {
47
return (
48
<Web3ReactProvider getLibrary={getLibrary}>
49
<App />
50
</Web3ReactProvider>
51
)
52
}
Copied!
We added the Web3ReactProvider to the root of the application and include the useEagerConnect hooks in the App component. We also includes the ChainId component which will show the connected chain id and show not connected if no connection detected.
Start the application you will see the not connected in the ChainId component. It's find since we haven't implement the connection logic. But you can test it by manually connect to the web app from MetaMask, try to figure out how to do it by yourself.

Add the Connect Button

Now let's add a button to trigger the wallet connect dialog.
Edit App.js to add some imports:
1
import React from 'react'
2
import { Spinner } from './Spiner'
3
import { injected } from './connectors'
Copied!
And create the ConnectChain component:
1
function ConnectChain(props) {
2
const context = useWeb3React()
3
const { connector, library, chainId, account, activate, deactivate, active, error } = context
4
​
5
const [activatingConnector, setActivatingConnector] = React.useState()
6
React.useEffect(() => {
7
if (activatingConnector && activatingConnector === connector) {
8
setActivatingConnector(undefined)
9
}
10
}, [activatingConnector, connector])
11
​
12
const activating = injected === activatingConnector
13
const connected = injected === connector
14
const disabled = !props.triedEager || !!activatingConnector || !!error
15
​
16
useInactiveListener(!props.triedEager || !!activatingConnector)
17
​
18
let isDisconnect = !error && chainId
19
const buttonText = isDisconnect ? 'Disconnect' : (activating ? 'Connectting' : 'Connect' )
20
​
21
return (
22
<button
23
style={{
24
borderColor: activating ? 'orange' : connected ? 'green' : 'unset',
25
cursor: disabled ? 'unset' : 'pointer',
26
position: 'relative',
27
}}
28
className="ConnectButton"
29
disabled={disabled}
30
onClick={() => {
31
if (!isDisconnect) {
32
setActivatingConnector(injected)
33
activate(injected)
34
} else {
35
deactivate()
36
}
37
}}
38
>
39
<div
40
style={{
41
position: 'absolute',
42
top: '0',
43
left: '0',
44
height: '100%',
45
display: 'flex',
46
alignItems: 'center',
47
color: 'black',
48
margin: '0 0 0 1rem'
49
}}
50
>
51
{activating && <Spinner color={'red'} style={{ height: '50%', marginLeft: '-1rem' }} />}
52
</div>
53
{ buttonText }
54
</button>
55
)
56
}
Copied!
and the css class for the button
App.css
1
.ConnectButton {
2
background-color: #4CAF50;
3
border: none;
4
color: white;
5
margin-top: 15px;
6
margin-bottom: 15px;
7
padding: 15px 32px;
8
text-align: center;
9
text-decoration: none;
10
display: inline-block;
11
font-size: 16px;
12
width: 200px;
13
}
14
​
15
.ConnectButton:disabled {
16
background-color: grey;
17
color: black;
18
}
Copied!
The ConnectChain component simple renders a button if it's not connected, click it will trigger the web3 connection dialog.
Let's add the ConnectChain component to the App component, you could place it under the <h1> title or somewhere else as you like.
1
<ConnectChain triedEager={triedEager} />
Copied!
Reload the page, the Connect button will show up and you can click it to open the connect dialog. After connected to the wallet, click the button will disconnect it.

Read contract state

First install the @ethersproject/contracts package, i
1
$ yarn add @ethersproject/contracts
Copied!
@ethersproject/contracts is a sub module of the ethers project.It is creating (at run-time) an object which interacts with an on-chain contract as a native JavaScript object.
We need add extra hooks to interact with the contract:
hooks.js
1
import { Contract } from '@ethersproject/contracts'
2
​
3
export function useBlockNumber() {
4
const { library }= useWeb3React()
5
const [blockNumber, setBlockNumber] = useState(-1)
6
​
7
useEffect(() => {
8
if (!library) {
9
return
10
}
11
const t = setInterval(async () => {
12
try {
13
setBlockNumber(await library.getBlockNumber())
14
} catch(ex) {
15
console.error('failed to get block number', ex)
16
}
17
return () => {
18
clearInterval(t)
19
}
20
}, 1000)
21
​
22
}, [library])
23
return blockNumber
24
}
25
​
26
export function useContract(contractJson) {
27
const { chainId, library, account}= useWeb3React()
28
​
29
if (!chainId || !contractJson.networks || !contractJson.networks[chainId]) {
30
return null
31
}
32
​
33
const signer = library.getSigner(account).connectUnchecked()
34
return new Contract(contractJson.networks[chainId].address, contractJson.abi, signer)
35
}
36
​
37
export function useContractCallData(contract, methodName, args) {
38
const blockNumber = useBlockNumber()
39
const [ result, setResult ] = useState(null)
40
useEffect(() => {
41
if (!contract || !methodName) {
42
return null
43
}
44
async function loadData() {
45
try {
46
const result = await contract[methodName](...args)
47
setResult(result)
48
} catch (ex) {
49
console.log(`failed call contract method ${methodName}: `, ex)
50
}
51
}
52
loadData()
53
}, [blockNumber])
54
return result
55
}
Copied!
  1. 1.
    We add 3 hooks, the useBlockNumberhook returns the latest block number from the chain (we emulate the data with 1 second refresh interval).
  2. 2.
    The useContract hook creates a smart contract instance from the json definition which was created by truffle. It will automatically detect the smart contract address on the chain.
  3. 3.
    The useContractCallData hook calls the contract method and will keep up to date with the latest block.
Now edit App.js and update it's content:
1
import { useEagerConnect, useInactiveListener, useContract, useContractCallData } from './hooks'
2
​
3
​
4
function App() {
5
const triedEager = useEagerConnect()
6
const counter = useContract(CounterContract)
7
const currentValue = useContractCallData(counter, 'current_value', [])
8
const currentValueText = (currentValue === undefined || currentValue === null) ? 'N/A' : currentValue
9
​
10
return (
11
<div className="App">
12
<header className="App-header">
13
<h1>Counter Example </h1>
14
<ConnectChain triedEager={triedEager} />
15
<ChainId/>
16
<p>
17
Current value: {currentValueText}
18
</p>
19
​
20
<button className="CounterButton">Inc Counter</button>
21
<button className="CounterButton">Dec Counter</button>
22
</header>
23
</div>
24
);
25
}
Copied!
Here we create the counter contract using the useContract hook. And then we use the useContractCallData hook to fetch the current_value state from the smart contract.
In the renderer function, we set the current value text to the value on the chain.
Save App.js and reload the webpage, you should see the current counter value on the page.

Write contract state

Now we can work on the inc/dec buttons, we'll add the onClick handler to them and call the inc/dec method correspondingly.
1
function App() {
2
const triedEager = useEagerConnect()
3
const counter = useContract(CounterContract)
4
const [loading, setLoading] = useState(false)
5
const currentValue = useContractCallData(counter, 'current_value', [])
6
​
7
const currentValueText = (currentValue === undefined || currentValue === null) ? 'N/A' : currentValue
8
const callMethod = async (name) => {
9
if (loading) {
10
return
11
}
12
setLoading(true)
13
try {
14
await counter[name]()
15
} catch(ex) {
16
console.error('transaction error: ', ex)
17
} finally {
18
setLoading(false)
19
}
20
}
21
​
22
return (
23
<div className="App">
24
<header className="App-header">
25
<h1>Counter Example </h1>
26
<ConnectChain triedEager={triedEager} />
27
<ChainId/>
28
<p>
29
Current value: {currentValueText}
30
</p>
31
​
32
{loading && <Spinner color={'red'} style={{ height: '40px', marginLeft: '-1rem' }} />}
33
<button className="CounterButton" onClick={() => callMethod('inc')}>Inc Counter</button>
34
<button className="CounterButton" onClick={() => callMethod('dec')}>Dec Counter</button>
35
</header>
36
</div>
37
);
38
}
Copied!
Besides calling the inc/decmethod, we also added a loading state to indicate we're waiting for some operation.
Save App.js and reload the webpage.
Click the Inc or Dec button, the sign transaction dialog will show up, click confirm to sign and send the transaction. The current value will be updated after a short while (~around 10 seconds).
That's it! We've implemented read/write the smart contracts in the DApp.
The source code of this chapter could be found at the revision fc93d686aabin the counter-dapp source repo.

Conclusion

In this tutorial we completed an e2e DApp development process which includes smart contract development, deployment and setup a frontend application to interact with the smart contract.
There're several things to improve which you can do:
  1. 1.
    The smart contract should send the update when the current value changes.
  2. 2.
    Implement a real time useBlockNumber hook
  3. 3.
    The current value was not updated in real time, improve it
  4. 4.
    The loading spinner shows when the confirm transaction dialog open, improve it so that it will wait for the transaction completes.
As we only demo a smallest DApp development, some code/functions are not written in a performant style, you should adjust them if you want to use them in a real project.