Build your Ethereum dApp using Golang and React

0mkar
7Finney
Published in
5 min readAug 21, 2020

In this tutorial, we will use Golang API backend with ReactJS front-end for our Ethereum dApp and Docker to run our dApp as a containerized service. Users will be given an unsigned transaction to sign and deploy in the blockchain.

Part 1: Deploying contracts to Görli Testnet

Step 1: Write an ERC-20 token using openzepplin library

Clone openzepplin contracts library.

https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts

We need contents of the above directory copied under your project directory.

i.e: YourdAppContracts/contracts

Create your ERC-20 token contracttoken.sol

Create ERC-20 token manager contracttokenManager.sol

Step 2: Compile & Deploy to Goerli Test Network using Ethcode

Deploy your token contract first. Our example token contract is deployed at:

0x1ae1aed6eba7ebee6039b383f1be3c5c141d3bc5

This will mint 100 tokens to the creator.

Then deploy your token manager contract. Our example token manager is deployed at:

0x292889dabe412cbbd0e66c7b2e65b6dc5e29943d

*Ethcode is a vscode plugin that you can use to compile and deploy your smart contracts to Ethereum test networks. A more detailed guide about our Ethereum plugin can be found on our previous post — ERC-20 development with Ethcode.

Step 3: Execute solidity function calls directly to EVM using Ethcode

Once deployed to the network we can execute functions on the deployed contracts. Our ERC-20 manager contract needs to have a config call before we can use it with our ERC-20 token.

function config(address _tokenContract) public onlyOwner
{
tokenContract = ET(_tokenContract);
}

The config function parameters can be supplied like the following:

[
{
"internalType": "address",
"name": "_tokenContract",
"type": "address",
"value": "0x1ae1aed6eba7ebee6039b383f1be3c5c141d3bc5" // pass our token contract address as value
}
]

Using ethcode we execute the function like the following:

Once configured the admin needs to deposit some Ether to manager contract and distribute the wrapped ether tokens. Execute the following functions in order to wrap some ether and transfer them to another account.

  1. Select token.sol from file selector. Then execute `approve function to approve manager contract to transfer some token from the creator’s address.
  2. Select tokenManager.sol and execute transferTo function. This call should transfer some token to another address and also wrap the supplied ether.
// transferTo someone else and wrap ether    function transferTo(uint256 amount, address toAddr) external payable isConfigured gtPrice
{
require(msg.sender == seller);
require(tokenContract.balanceOf(msg.sender) > amount);
require(msg.value > price * amount);
tokenContract.transferFrom(msg.sender, toAddr, amount);
}

To transfer 10 tokens to another address pass following parameters

[
{
"internalType": "uint256",
"name": "amount",
"type": "uint256",
"value": "10"
},
{
"internalType": "address",
"name": "toAddr",
"type": "address",
"value": "0x8a296947Df2f1536585CBf9B89d0d5868c9a1BE1"
}
]

Part 2: Building the webapp

Step 4: Write a golang program to interact with smart contracts

// CreateSwapTokenTx -> Creates and unsigned transaction to swap tokens for ether
func CreateSwapTokenTx(authToken string, txParams types.TxParams, netID uint32) (string, error) {
conn, err := grpc.Dial(GRPC_URL, grpc.WithInsecure())
if err != nil {
return "", err
}
defer conn.Close()
client := proto.NewProtoEthServiceClient(conn)
...
...
// swap() call to manager contract
c := &proto.CallRequest{
Networkid: netID,
Fn: "swap",
Params: string(p),
Abi: ABI,
Address: CONTRACT_ADDR,
FromAddress: txParams.From,
Value: txParams.Value,
}
unsignedTx, err := client.ContractCall(ctxHeader, c)
if err != nil {
return "", err
}
return unsignedTx.Result, nil
}

We have used a gRPC wrapper around regular go-ethereum API endpoints. You can run your own gRPC endpoint by using our ethereum-gRPC docker image available on docker hub.

Our example API looks like the following:

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /api/v0/genToken/:clientID --> ethential/dsvc/controllers.GenTokenController (5 handlers)
[GIN-debug] POST /api/v0/transferToken --> ethential/dsvc/controllers.TransferTokenController (5 handlers)
[GIN-debug] POST /api/v0/getTokenBalance --> ethential/dsvc/controllers.TokenBalanceController (5 handlers)
[GIN-debug] POST /api/v0/swap --> ethential/dsvc/controllers.SwapTokenController (5 handlers)
[GIN-debug] POST /api/v0/approve --> ethential/dsvc/controllers.ApproveController (5 handlers)
[GIN-debug] Listening and serving HTTP on :4551

Step 5: React frontend for user interactions

In our react frontend we have two main parts.

scan QR code to load the transaction on your wallet.
  1. Create an unsigned transaction with supplied parameters by calling our golang API /api/v0/swap .
  2. Let users share the unsigned transaction using a QR code or a JSON file.

Step 6: Load unsigned transactions into a disposable wallet

We then use a disposable style wallet to load the transaction.

We are using Ethential Wallet as now this is the only wallet that can load an unsigned transaction from raw data.

Github — https://github.com/ethential/wallet

Download apk from IPFS — https://gateway.ipfs.io/ipfs/QmSziuA9wfxfA1thfdswgb3KfjE3sF7QRmeaXBax4zuDGb

Download apk from google drive — https://drive.google.com/file/d/1WnLUHSCTsaLCx_ZVsClb1BpWjP4vVzID/view?usp=sharing

Step 7: Sign and deploy the transaction to network

Ethential wallet is a disposable style wallet. It uses go-ethereum to sign transactions. You can create ethereum accounts with or without passwords. This wallet is undergoing heavy development and we request *NOT to use it for mainnet transactions.

Our example dApp is deployed at https://service.ethcode.dev/

dApp source code: https://github.com/ethential/dApp-example

Wallet source code: https://github.com/ethential/wallet

Wallet download link: https://gateway.ipfs.io/ipfs/QmSziuA9wfxfA1thfdswgb3KfjE3sF7QRmeaXBax4zuDGb

Ethereum-gRPC source code: https://github.com/ethential/ethereum-grpc

The wallet uses https://github.com/0mkara/react-native-geth to sign transactions. For any questions regarding our dApp development stack please join our discord — https://discord.gg/k7yrMhY

About our team

We are a small team building devtools for Ethereum community for over a year. Our team has built Ethcode, Etheratom. Now we want to build a microservice friendly tech stack for building ethereum dApps. We seek help and support from ethereum community. Please try out our tools and let us know your feedback.

--

--