To build out our frontend application, we'll do the following:
fuels
SDK dependencies. Our front end application will need to interact with the Fuel Network, so we'll need to have a browser wallet installed for us to do so.
Before going to the next steps, install the Fuel Wallet.
Once you've installed the wallet, take the address of your wallet and use it to get some coins from the testnet faucet .
To split our project's contract from frontend code, let's create a new folder frontend
where we'll initialize our frontend project.
In the terminal, go back up one directory and initialize a react project using Create React App
.
$ cd ..
$ npx create-react-app frontend --template typescript
Success! Created frontend at Fuel/fuel-project/frontend
You should now have your outer folder, fuel-project
, with two folders inside: counter-contract
and frontend
fuels
SDK dependency The fuels
umbrella package includes all the main tools you need for your frontend; Wallet
, Contracts
, Providers
, and more.
Also, it contains the routines for ABI TypeScript generation.
ABI stands for Application Binary Interface. ABI's inform the application the interface to interact with the VM, in other words, they provide info to the APP such as what methods a contract has, what params, types it expects, etc...
Move into the frontend
folder, then run:
$ cd frontend
$ npm install fuels@0.38.0 @fuel-wallet/sdk --save
added 114 packages, and audited 115 packages in 9s
Next, update the TypeScript configuration at tsconfig.json
to add the Fuel Wallet types:
{
"compilerOptions": {
"types": ["@fuel-wallet/sdk"]
}
}
To make it easier to interact with our contract we use fuels typegen
command to interpret the output ABI JSON from our contract, and generate Typescript definitions based on it. This JSON was created when we executed the forc build
command to compile our Sway Contract into binary.
If you see the folder fuel-project/counter-contract/out
you will be able to see the ABI JSON there. If you want to learn more, read the ABI spec.
Inside the fuel-project/frontend
directory run:
$ npx fuels typegen -i ../counter-contract/out/debug/*-abi.json -o ./src/contracts
Generating files..
- src/contracts/CounterContractAbi.d.ts
- src/contracts/factories/CounterContractAbi__factory.ts
- src/contracts/index.ts
Done.⚡
Now you should be able to find a new folder fuel-project/frontend/src/contracts
. This folder was auto-generated by our fuels typegen
command, and these files abstract the work we would need to do to create a contract instance, and generate a complete TypeScript interface to the Contract, making easy to develop.
Inside the frontend/src
folder let's add code that interacts with our contract.
Read the comments to help you understand the App parts.
Change the file fuel-project/frontend/src/App.tsx
to:
File: ./frontend/src/App.tsx
import React, { useEffect, useState } from 'react';
import '@fuel-wallet/sdk';
import './App.css';
// Import the contract factory -- you can find the name in index.ts.
// You can also do command + space and the compiler will suggest the correct name.
import { CounterContractAbi__factory } from './contracts';
// The address of the contract deployed the Fuel testnet
const CONTRACT_ID =
'0x9751545a0f45aa4b88904b6b4a896bfb02f231676de5438d346d4beab5cb9820';
function App() {
const [connected, setConnected] = useState<boolean>(false);
const [account, setAccount] = useState<string>('');
const [counter, setCounter] = useState<number>(0);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
setTimeout(() => {
checkConnection();
setLoaded(true);
}, 200);
if (connected) getCount();
}, [connected]);
async function connect() {
if (window.fuel) {
try {
await window.fuel.connect();
const [account] = await window.fuel.accounts();
setAccount(account);
setConnected(true);
} catch (err) {
console.log('error connecting: ', err);
}
}
}
async function checkConnection() {
if (window.fuel) {
const isConnected = await window.fuel.isConnected();
if (isConnected) {
const [account] = await window.fuel.accounts();
setAccount(account);
setConnected(true);
}
}
}
async function getCount() {
if (window.fuel) {
const wallet = await window.fuel.getWallet(account);
const contract = CounterContractAbi__factory.connect(CONTRACT_ID, wallet);
const { value } = await contract.functions.count().get();
setCounter(value.toNumber());
}
}
async function increment() {
if (window.fuel) {
const wallet = await window.fuel.getWallet(account);
const contract = CounterContractAbi__factory.connect(CONTRACT_ID, wallet);
// Creates a transactions to call the increment function
// because it creates a TX and updates the contract state this requires the wallet to have enough coins to cover the costs and also to sign the Transaction
try {
await contract.functions.increment().txParams({ gasPrice: 1 }).call();
getCount();
} catch (err) {
console.log('error sending transaction...', err);
}
}
}
if (!loaded) return null;
return (
<>
<div className="App">
{connected ? (
<>
<h3>Counter: {counter?.toFixed(0)}</h3>
<button style={buttonStyle} onClick={increment}>
Increment
</button>
</>
) : (
<button style={buttonStyle} onClick={connect}>
Connect
</button>
)}
</div>
</>
);
}
export default App;
const buttonStyle = {
borderRadius: '48px',
marginTop: '10px',
backgroundColor: '#03ffc8',
fontSize: '20px',
fontWeight: '600',
color: 'rgba(0, 0, 0, .88)',
border: 'none',
outline: 'none',
height: '60px',
width: '400px',
cursor: 'pointer',
};
Now it's time to have fun, run the project in your browser.
Inside the fuel-project/frontend
directory run:
$ npm start
Compiled successfully!
You can now view frontend in the browser.
Local: http://localhost:3001
On Your Network: http://192.168.4.48:3001
Note that the development build is not optimized.
To create a production build, use npm run build.
Here is the repo for this project . If you run into any problems, a good first step is to compare your code to this repo and resolve any differences.
Tweet us @fuel_network letting us know you just built a dapp on Fuel, you might get invited to a private group of builders, be invited to the next Fuel dinner, get alpha on the project, or something 👀.
If you make changes to your contract, here are the steps you should take to get your frontend and contract back in sync:
forc build
forc deploy --node-url beta-3.fuel.network/graphql --gas-price 1 --random-salt
npx fuels typegen -i ../counter-contract/out/debug/*-abi.json -o ./src/contracts
fuel-project/frontend
directory, update the contract ID in your App.tsx
file Get help from the team by posting your question in the Fuel Forum .
Was this page helpful?