Setup the Blockchain (Smart Contract)
We’ll use Solidity to create a smart contract that handles insurance claims. The contract will:
- Allow users to submit claims.
- Verify the claims.
- Allow an admin to approve or reject claims.
1.1 Install Dependencies
To get started with Solidity and deploy our smart contract on Ethereum, you need to install the following tools:
- Truffle (a development framework for Ethereum)
- Ganache (a personal blockchain for Ethereum development)
- MetaMask (for interacting with the Ethereum network via a browser)
To install Truffle:
bashCopy codenpm install -g truffle
1.2 Initialize the Truffle Project
In a new directory, initialize a Truffle project:
bashCopy codemkdir blockchain-insurance
cd blockchain-insurance
truffle init
1.3 Create the Insurance Smart Contract (Solidity)
Inside the contracts
folder, create a new file called Insurance.sol
and add the following code:
solidityCopy code// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Insurance {
struct Claim {
uint id;
string description;
uint claimAmount;
address claimant;
bool approved;
}
mapping(uint => Claim) public claims;
uint public claimCount;
address public owner;
constructor() {
owner = msg.sender;
}
// Modifier to restrict certain actions to the owner only
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can perform this action");
_;
}
// Submit a new claim
function submitClaim(string memory _description, uint _claimAmount) public {
claimCount++;
claims[claimCount] = Claim(claimCount, _description, _claimAmount, msg.sender, false);
}
// Approve a claim (only the contract owner can approve claims)
function approveClaim(uint _id) public onlyOwner {
Claim storage claim = claims[_id];
require(claim.id != 0, "Claim does not exist");
claim.approved = true;
}
// Reject a claim (only the contract owner can reject claims)
function rejectClaim(uint _id) public onlyOwner {
Claim storage claim = claims[_id];
require(claim.id != 0, "Claim does not exist");
claim.approved = false;
}
// Get details of a claim
function getClaim(uint _id) public view returns (uint, string memory, uint, address, bool) {
Claim memory claim = claims[_id];
return (claim.id, claim.description, claim.claimAmount, claim.claimant, claim.approved);
}
}
This contract has the following key features:
- Users can submit claims with a description and amount.
- Claims are stored with a unique ID.
- Only the contract owner (admin) can approve or reject claims.
- The claims can be viewed publicly, ensuring transparency.
1.4 Deploy the Smart Contract
In migrations/1_deploy_contracts.js
, add the following code to deploy the contract:
javascriptCopy codeconst Insurance = artifacts.require("Insurance");
module.exports = function (deployer) {
deployer.deploy(Insurance);
};
Now, start Ganache to simulate the Ethereum blockchain locally and deploy the contract. Run these commands:
bashCopy codeganache-cli
This will start a local Ethereum blockchain. In a new terminal window, migrate the contract to Ganache:
bashCopy codetruffle migrate --network development
Step 2: Create the Backend API (Node.js + Web3.js)
We’ll create a Node.js API that interacts with the smart contract to manage claims and interact with the frontend.
2.1 Initialize Node.js Project
Inside the blockchain-insurance
directory, create a backend
folder and initialize a Node.js project:
bashCopy codemkdir backend
cd backend
npm init -y
npm install express web3 dotenv
2.2 Setup the Web3 Connection
In the backend
folder, create a file called server.js
and add the following code:
javascriptCopy codeconst express = require("express");
const Web3 = require("web3");
require("dotenv").config();
const app = express();
const port = 3000;
// Connect to the local blockchain using Ganache
const web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545'));
// Contract ABI and address
const contractABI = [/* ABI from Truffle deployment */];
const contractAddress = 'your_contract_address_here'; // Copy from the output of Truffle deployment
// Set up the contract instance
const insuranceContract = new web3.eth.Contract(contractABI, contractAddress);
// Middlewares
app.use(express.json());
// Submit a claim
app.post("/submit-claim", async (req, res) => {
const { description, claimAmount } = req.body;
const accounts = await web3.eth.getAccounts();
try {
await insuranceContract.methods.submitClaim(description, claimAmount).send({ from: accounts[0] });
res.status(200).send({ message: "Claim submitted successfully!" });
} catch (error) {
res.status(500).send({ error: error.message });
}
});
// Get claim details
app.get("/get-claim/:id", async (req, res) => {
const { id } = req.params;
try {
const claim = await insuranceContract.methods.getClaim(id).call();
res.status(200).json(claim);
} catch (error) {
res.status(500).send({ error: error.message });
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
In the code above:
- We connect to the Ethereum blockchain using Web3.js.
- We define two routes:
POST /submit-claim
: To submit a new insurance claim.GET /get-claim/:id
: To fetch the details of a claim.
Make sure to replace contractABI
and contractAddress
with the correct values from the deployment of your smart contract.
Step 3: Develop the Frontend (HTML/CSS/JavaScript)
Now let’s build the frontend so that users can submit claims and view their status.
3.1 Create the Frontend Files
In the root directory (blockchain-insurance
), create a frontend
folder, and inside it, create the following files:
index.html
styles.css
app.js
3.2 index.html
(Form for Submitting Claims)
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blockchain Insurance</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Submit an Insurance Claim</h1>
<form id="claimForm">
<label for="description">Claim Description:</label>
<input type="text" id="description" required>
<label for="claimAmount">Claim Amount (in ETH):</label>
<input type="number" id="claimAmount" required>
<button type="submit">Submit Claim</button>
</form>
<h2>Check Claim Status</h2>
<label for="claimId">Claim ID:</label>
<input type="number" id="claimId">
<button onclick="getClaimDetails()">Check Status</button>
<div id="claimDetails"></div>
</div>
<script src="app.js"></script>
</body>
</html>
3.3 styles.css
(Basic Styling)
cssCopy codebody {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
width: 50%;
margin: 50px auto;
background-color: white;
padding: 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
h1, h2 {
text-align: center;
}
form input, form button, input {
width: 100%;
padding:
Leave a Reply