A Decentralized Application, as its name suggests, is decentralized, meaning there is no central authority and it supports a decentralized form. It runs on a P2P (decentralized) network. It offers secure, transparent, and user-centric solutions. It also provides Web 3.0 capabilities. This article focuses on discussing DApp Development in detail.
The Full Form of DApp is a Decentralized Application. DApps run on a peer-to-peer network, it does not support Centralized control and enhance security and transparency. All the applications where control is not centralized come under Decentralized applications.
What is DApp Development?DApp development involves blockchain technology with smart contracts. When we build a DApp, we have to work on the front-end part and the back-end part.
- In the back-end part, we use smart contracts to automate processes and enhance performance. Smart contracts enhance security and remove intermediaries.
- Blockchain networks distribute data across different nodes to prevent tampering and ensure integrity.
- Unlike centralized apps, DApps run on a P2P network and remove the need for central authorities.
- DApp development makes apps faster, more secure, and more transparent.
- DApps are open source, which means the codebase is accessible to the public, allowing them to make modifications and contributions. Open source promotes collaboration and innovation within the developer community. It helps in finding vulnerabilities and adding more features to the DApps.
- DApps are decentralized, which means there are no central authorities, ensuring that no single entity has control over the entire network. This enhances the security and integrity of the application because there is no centralization.
- Consensus mechanisms such as Proof of Work (PoW) and Proof of Stake (PoS) help in validating transactions and maintaining the integrity of the blockchain in DApps. These mechanisms ensure decentralized agreement, prevent fraud, and ensure secure and trustless transactions.
What Programming Language is Used for DApp?Different types of programming languages are used for DApps. The choice depends on various factors, such as the blockchain platform utilized and the developer’s expertise. Developers choose programming languages based on the specific requirements for the DApp.
1. SoliditySolidity is used for crafting smart contracts on the Ethereum blockchain. It supports intricate user-defined types, libraries, and inheritance for creating decentralized applications. Solidity helps in designing and deploying smart contracts and handling functions such as token creation (ERC-20), decentralized finance (DeFi) protocols, and voting systems.
- It Supports inheritance and libraries.
- Specifically It is designed for the Ethereum based ecosystem.
2. JavaScript/TypeScriptJavaScript and TypeScript play a major role in front-end development for DApps and scripting interactions with smart contracts. These languages help in crafting user interfaces. They use libraries such as Web3.js, Ethers.js, and Truffle to interface with blockchain networks.
- Mostly Used for front-end development.
- It interact with smart contracts.
3. RustWe use Rust for writing smart contracts on blockchains like Solana and Polkadot. It offers memory safety without a garbage collector and includes features like concurrency without data races, ensuring system reliability. Rust is also used in developing intricate and performance-oriented DApps.We use Rust for writing smart contracts on blockchains like Solana and Polkadot. It offers memory safety without a garbage collector and includes features like concurrency without data races, ensuring system reliability. Rust is also used in developing intricate and performance-oriented DApps.
- It Provides safety of memory without a garbage collector.
- It mainly Enhanced performance and safety.
4. VyperVyper is another language used to script smart contracts on the Ethereum blockchain. It is famous for its simplicity and emphasis on security. Vyper lacks features like infinite loops and recursive calling for security purposes.
- Security audits, particularly for financial applications, are suitable for Vyper implementation.
- It’s main focus on security and simplicity.
Example of DAppBlockchain Based Medical Record StorerIt is a Decentralized Blockchain based medical record storer where a patient can store and delete his medical records by using Ethereums. It is a safe and secure DApp for storing medical records. User has to connect his wallet with the application and after connection user can submit his patient form and do transactions.
Solidity Code:
Solidity
//SPDX-License-Identifier:MIT
pragma solidity ^0.8.0;
contract MedicalRecords {
uint public recordId;
mapping(uint => Record) records;
mapping(uint => bool) public isDeleted;
struct Record {
uint recordId;
uint timestamp;
string name;
uint age;
string gender;
string bloodType;
string allergies;
string diagnosis;
string treatment;
}
event MedicalRecords__AddRecord(
uint recordId,
uint timestamp,
string name,
uint age,
string gender,
string bloodType,
string allergies,
string diagnosis,
string treatment
);
event MedicalRecords__DeleteRecord(
uint recordId,
uint timestamp,
string name,
uint age,
string gender,
string bloodType,
string allergies,
string diagnosis,
string treatment
);
function addRecord(
string memory _name,
uint _age,
string memory _gender,
string memory _bloodType,
string memory _allergies,
string memory _diagnosis,
string memory _treatment
) public {
recordId++;
records[recordId] = Record(
recordId,
block.timestamp,
_name,
_age,
_gender,
_bloodType,
_allergies,
_diagnosis,
_treatment
);
emit MedicalRecords__AddRecord(
recordId,
block.timestamp,
_name,
_age,
_gender,
_bloodType,
_allergies,
_diagnosis,
_treatment
);
}
function deleteRecord(uint _recordId) public {
require(!isDeleted[_recordId], "The record is already deleted");
Record storage record = records[_recordId];
emit MedicalRecords__DeleteRecord(
record.recordId,
block.timestamp,
record.name,
record.age,
record.gender,
record.bloodType,
record.allergies,
record.diagnosis,
record.treatment
);
isDeleted[_recordId] = true;
}
function getRecord(
uint _recordId
)
public
view
returns (
uint,
string memory,
uint,
string memory,
string memory,
string memory,
string memory,
string memory
)
{
Record storage record = records[_recordId];
return (
record.timestamp,
record.name,
record.age,
record.gender,
record.bloodType,
record.allergies,
record.diagnosis,
record.treatment
);
}
function getRecordId() public view returns (uint) {
return recordId;
}
function getTimeStamp(uint _recordId) public view returns (uint) {
return records[_recordId].timestamp;
}
function getName(uint _recordId) public view returns (string memory) {
return records[_recordId].name;
}
function getAge(uint _recordId) public view returns (uint) {
return records[_recordId].age;
}
function getGender(uint _recordId) public view returns (string memory) {
return records[_recordId].gender;
}
function getBloodType(uint _recordId) public view returns (string memory) {
return records[_recordId].bloodType;
}
function getAllergies(uint _recordId) public view returns (string memory) {
return records[_recordId].allergies;
}
function getDiagnosis(uint _recordId) public view returns (string memory) {
return records[_recordId].diagnosis;
}
function getTreatment(uint _recordId) public view returns (string memory) {
return records[_recordId].treatment;
}
function getDeleted(uint256 _recordId) public view returns (bool) {
return isDeleted[_recordId];
}
}
Deploy Script:
JavaScript
const { ethers } = require("hardhat");
async function main() {
console.log("Deploying smart contract...");
const Medical = await ethers.getContractFactory("MedicalRecords");
const account = await ethers.getSigners();
const medical = await Medical.connect(account[1]).deploy();
await medical.deployed();
console.log(`Medical is deployed in address ${medical.address}`);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.log(error);
process.exit(1);
});
Seeding Script:
JavaScript
const { ethers } = require("hardhat");
const config = require("../src/config.json");
const wait = (seconds) => {
const milliseconds = seconds * 1000;
return new Promise((resolve) => setTimeout(resolve, milliseconds));
};
async function main() {
const { chainId } = await ethers.provider.getNetwork();
console.log(`Using chainId ${chainId}`);
const account = await ethers.getSigners();
const medical = await ethers.getContractAt(
"MedicalRecords",
config[chainId].medical.address
);
console.log(`MedicalRecord smart contract fetched at ${medical.address}`);
let transactionResponse;
const user1 = account[0];
transactionResponse = await medical
.connect(user1)
.addRecord(
"Aman Gupta",
44,
"Male",
"B positive",
"Allergic rhinitis",
"Hypertension ",
"Medications"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Michael Miller",
34,
"Male",
"A negative",
"Pollen allergy ",
"Type 2 diabetes ",
"Psychotherapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"David Wright",
45,
"Male",
"B positive",
"Insect sting allergy ",
"Asthma ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ethan Clark",
23,
"Male",
"O negative",
"Drug allergy",
"Bronchitis ",
"Radiation therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ryan GupMillerta",
34,
"Male",
"AB positive",
"Latex allergy",
"Pneumonia ",
"Physical therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Olivia Robinson",
77,
"Female",
"A negative",
"Animal dander allergy ",
"Acute appendicitis ",
"Occupational therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Emma Gupta",
23,
"Female",
"B positive",
"Dust mite allergy ",
"Osteoporosis ",
"Speech therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Mia Clark",
29,
"Female",
"B negative",
"Chemical allergy ",
"Rheumatoid arthritis ",
"Alternative therapies"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Sofia Wright",
83,
"Female",
"O positive",
"Sun allergy ",
"Coronary artery disease ",
"Behavioral interventions"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Victoria Robinson",
93,
"Female",
"O negative",
"Food allergy",
"Congestive heart failure ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Aman Gupta",
44,
"Male",
"B positive",
"Allergic rhinitis",
"Hypertension ",
"Medications"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Michael Miller",
34,
"Male",
"A negative",
"Pollen allergy ",
"Type 2 diabetes ",
"Psychotherapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"David Wright",
45,
"Male",
"B positive",
"Insect sting allergy ",
"Asthma ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ethan Clark",
23,
"Male",
"O negative",
"Drug allergy",
"Bronchitis ",
"Radiation therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ryan GupMillerta",
34,
"Male",
"AB positive",
"Latex allergy",
"Pneumonia ",
"Physical therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Olivia Robinson",
77,
"Female",
"A negative",
"Animal dander allergy ",
"Acute appendicitis ",
"Occupational therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Emma Gupta",
23,
"Female",
"B positive",
"Dust mite allergy ",
"Osteoporosis ",
"Speech therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Mia Khalifa",
25,
"Female",
"B negative",
"Chemical allergy ",
"Rheumatoid arthritis ",
"Alternative therapies"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Sofia Wright",
83,
"Female",
"O positive",
"Sun allergy ",
"Coronary artery disease ",
"Behavioral interventions"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Victoria Robinson",
93,
"Female",
"O negative",
"Food allergy",
"Congestive heart failure ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Aman Gupta",
44,
"Male",
"B positive",
"Allergic rhinitis",
"Hypertension ",
"Medications"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Michael Miller",
34,
"Male",
"A negative",
"Pollen allergy ",
"Type 2 diabetes ",
"Psychotherapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"David Wright",
45,
"Male",
"B positive",
"Insect sting allergy ",
"Asthma ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ethan Clark",
23,
"Male",
"O negative",
"Drug allergy",
"Bronchitis ",
"Radiation therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ryan GupMillerta",
34,
"Male",
"AB positive",
"Latex allergy",
"Pneumonia ",
"Physical therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Olivia Robinson",
77,
"Female",
"A negative",
"Animal dander allergy ",
"Acute appendicitis ",
"Occupational therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Emma Gupta",
23,
"Female",
"B positive",
"Dust mite allergy ",
"Osteoporosis ",
"Speech therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Mia Clark",
29,
"Female",
"B negative",
"Chemical allergy ",
"Rheumatoid arthritis ",
"Alternative therapies"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Sofia Wright",
83,
"Female",
"O positive",
"Sun allergy ",
"Coronary artery disease ",
"Behavioral interventions"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Victoria Robinson",
93,
"Female",
"O negative",
"Food allergy",
"Congestive heart failure ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Aman Gupta",
44,
"Male",
"B positive",
"Allergic rhinitis",
"Hypertension ",
"Medications"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Michael Miller",
34,
"Male",
"A negative",
"Pollen allergy ",
"Type 2 diabetes ",
"Psychotherapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"David Wright",
45,
"Male",
"B positive",
"Insect sting allergy ",
"Asthma ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ethan Clark",
23,
"Male",
"O negative",
"Drug allergy",
"Bronchitis ",
"Radiation therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ryan GupMillerta",
34,
"Male",
"AB positive",
"Latex allergy",
"Pneumonia ",
"Physical therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Olivia Robinson",
77,
"Female",
"A negative",
"Animal dander allergy ",
"Acute appendicitis ",
"Occupational therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Emma Gupta",
23,
"Female",
"B positive",
"Dust mite allergy ",
"Osteoporosis ",
"Speech therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Mia Khalifa",
25,
"Female",
"B negative",
"Chemical allergy ",
"Rheumatoid arthritis ",
"Alternative therapies"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Sofia Wright",
83,
"Female",
"O positive",
"Sun allergy ",
"Coronary artery disease ",
"Behavioral interventions"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Victoria Robinson",
93,
"Female",
"O negative",
"Food allergy",
"Congestive heart failure ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Aman Gupta",
44,
"Male",
"B positive",
"Allergic rhinitis",
"Hypertension ",
"Medications"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Michael Miller",
34,
"Male",
"A negative",
"Pollen allergy ",
"Type 2 diabetes ",
"Psychotherapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"David Wright",
45,
"Male",
"B positive",
"Insect sting allergy ",
"Asthma ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ethan Clark",
23,
"Male",
"O negative",
"Drug allergy",
"Bronchitis ",
"Radiation therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ryan GupMillerta",
34,
"Male",
"AB positive",
"Latex allergy",
"Pneumonia ",
"Physical therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Olivia Robinson",
77,
"Female",
"A negative",
"Animal dander allergy ",
"Acute appendicitis ",
"Occupational therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Emma Gupta",
23,
"Female",
"B positive",
"Dust mite allergy ",
"Osteoporosis ",
"Speech therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Mia Clark",
29,
"Female",
"B negative",
"Chemical allergy ",
"Rheumatoid arthritis ",
"Alternative therapies"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Sofia Wright",
83,
"Female",
"O positive",
"Sun allergy ",
"Coronary artery disease ",
"Behavioral interventions"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Victoria Robinson",
93,
"Female",
"O negative",
"Food allergy",
"Congestive heart failure ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Aman Gupta",
44,
"Male",
"B positive",
"Allergic rhinitis",
"Hypertension ",
"Medications"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Michael Miller",
34,
"Male",
"A negative",
"Pollen allergy ",
"Type 2 diabetes ",
"Psychotherapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"David Wright",
45,
"Male",
"B positive",
"Insect sting allergy ",
"Asthma ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ethan Clark",
23,
"Male",
"O negative",
"Drug allergy",
"Bronchitis ",
"Radiation therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ryan GupMillerta",
34,
"Male",
"AB positive",
"Latex allergy",
"Pneumonia ",
"Physical therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Olivia Robinson",
77,
"Female",
"A negative",
"Animal dander allergy ",
"Acute appendicitis ",
"Occupational therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Emma Gupta",
23,
"Female",
"B positive",
"Dust mite allergy ",
"Osteoporosis ",
"Speech therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Mia Khalifa",
25,
"Female",
"B negative",
"Chemical allergy ",
"Rheumatoid arthritis ",
"Alternative therapies"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Sofia Wright",
83,
"Female",
"O positive",
"Sun allergy ",
"Coronary artery disease ",
"Behavioral interventions"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Victoria Robinson",
93,
"Female",
"O negative",
"Food allergy",
"Congestive heart failure ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Aman Gupta",
44,
"Male",
"B positive",
"Allergic rhinitis",
"Hypertension ",
"Medications"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Michael Miller",
34,
"Male",
"A negative",
"Pollen allergy ",
"Type 2 diabetes ",
"Psychotherapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"David Wright",
45,
"Male",
"B positive",
"Insect sting allergy ",
"Asthma ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ethan Clark",
23,
"Male",
"O negative",
"Drug allergy",
"Bronchitis ",
"Radiation therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ryan GupMillerta",
34,
"Male",
"AB positive",
"Latex allergy",
"Pneumonia ",
"Physical therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Olivia Robinson",
77,
"Female",
"A negative",
"Animal dander allergy ",
"Acute appendicitis ",
"Occupational therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Emma Gupta",
23,
"Female",
"B positive",
"Dust mite allergy ",
"Osteoporosis ",
"Speech therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Mia Clark",
29,
"Female",
"B negative",
"Chemical allergy ",
"Rheumatoid arthritis ",
"Alternative therapies"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Sofia Wright",
83,
"Female",
"O positive",
"Sun allergy ",
"Coronary artery disease ",
"Behavioral interventions"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Victoria Robinson",
93,
"Female",
"O negative",
"Food allergy",
"Congestive heart failure ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Aman Gupta",
44,
"Male",
"B positive",
"Allergic rhinitis",
"Hypertension ",
"Medications"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Michael Miller",
34,
"Male",
"A negative",
"Pollen allergy ",
"Type 2 diabetes ",
"Psychotherapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"David Wright",
45,
"Male",
"B positive",
"Insect sting allergy ",
"Asthma ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ethan Clark",
23,
"Male",
"O negative",
"Drug allergy",
"Bronchitis ",
"Radiation therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Ryan GupMillerta",
34,
"Male",
"AB positive",
"Latex allergy",
"Pneumonia ",
"Physical therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Olivia Robinson",
77,
"Female",
"A negative",
"Animal dander allergy ",
"Acute appendicitis ",
"Occupational therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Emma Gupta",
23,
"Female",
"B positive",
"Dust mite allergy ",
"Osteoporosis ",
"Speech therapy"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Mia Khalifa",
25,
"Female",
"B negative",
"Chemical allergy ",
"Rheumatoid arthritis ",
"Alternative therapies"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Sofia Wright",
83,
"Female",
"O positive",
"Sun allergy ",
"Coronary artery disease ",
"Behavioral interventions"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical
.connect(user1)
.addRecord(
"Victoria Robinson",
93,
"Female",
"O negative",
"Food allergy",
"Congestive heart failure ",
"Surgery"
);
await transactionResponse.wait();
console.log(`Record added with id ${await medical.getRecordId()}`);
transactionResponse = await medical.connect(user1).deleteRecord(69);
await transactionResponse.wait();
console.log(`Record deleted`);
transactionResponse = await medical.connect(user1).deleteRecord(55);
await transactionResponse.wait();
console.log(`Record deleted`);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
Frontend Part Alert.js:
JavaScript
import React, { useEffect, useRef } from "react";
import "./alert.css";
import { useSelector } from "react-redux";
import { myEventsSelector } from "../../store/selectors";
import config from "../../config.json";
const Alert = () => {
const alertRef = useRef(null);
const event = useSelector(myEventsSelector);
const overlayRef = useRef(null);
const isPending = useSelector((state) => state.medical.transaction.isPending);
const isError = useSelector((state) => state.medical.transaction.isError);
const chainId = useSelector((state) => state.provider.chainId);
const removeHandler = async (e) => {
alertRef.current.className = "alertBox--remove";
overlayRef.current.className = "overlay--remove";
};
useEffect(() => {
if (isPending) {
alertRef.current.className = "alertBox";
overlayRef.current.className = "overlay";
}
}, [isPending]);
return (
<div>
{isPending ? (
<div className="alert" onClick={removeHandler}>
<div className="overlay--remove" ref={overlayRef}></div>
<div className=" alertBox--remove " ref={alertRef}>
<h2>Action Pending...</h2>
</div>
</div>
) : isError ? (
<div className="alert" onClick={removeHandler}>
<div className="overlay--remove" ref={overlayRef}></div>
<div className=" alertBox--remove " ref={alertRef}>
<h2>Action Will Fail</h2>
</div>
</div>
) : !isPending && event[0] ? (
<div className="alert" onClick={removeHandler}>
<div className="overlay--remove" ref={overlayRef}></div>
<div className=" alertBox--remove " ref={alertRef}>
<h2>Action Successful</h2>
<div className="transactionHashOut">
<a
className="transactionHash"
href={
config[chainId]
? `${config[chainId].explorerURL}tx/${event[0].transactionHash}`
: `#`
}
target="_blank"
rel="noreferrer"
>
{event[0].transactionHash.slice(0, 6) +
"..." +
event[0].transactionHash.slice(60, 66)}
</a>
</div>
</div>
</div>
) : (
<div></div>
)}
</div>
);
};
export default Alert;
Data.js:
JavaScript
import React from "react";
import "./data.css";
import { dataBookSelector } from "../../store/selectors";
import { useDispatch, useSelector } from "react-redux";
import { deleteData } from "../../store/interactions";
const Data = () => {
const orderData = useSelector(dataBookSelector);
const account = useSelector((state) => state.provider.account);
const provider = useSelector((state) => state.provider.connection);
const medical = useSelector((state) => state.medical.contract);
const dispatch = useDispatch();
const deleteHandler = (e, data) => {
if (window.confirm("Do you want to delete the record?")) {
deleteData(medical, data.recordId, dispatch, provider);
} else {
console.log("Data not delete");
}
};
return (
<div>
{account ? (
<div>
<table>
<thead>
<tr>
<th>Record ID</th>
<th>Data and Time</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Blood Type</th>
<th>Allergies</th>
<th>Diagnosis</th>
<th>Treatment</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{orderData &&
orderData.map((data, index) => {
return (
<tr key={index}>
<td>{index + 1}</td>
{/* <td>{data.recordIdNew}</td> */}
<td>{data.formattedTimestamp}</td>
<td>{data.name}</td>
<td>{data.ageNew} </td>
<td>{data.gender}</td>
<td>{data.bloodType}</td>
<td>{data.allergies}</td>
<td>{data.diagnosis}</td>
<td>{data.treatment}</td>
<td>
<button
className="delete-button"
onClick={(e) => deleteHandler(e, data)}
>
Delete
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
) : (
<h1>Connect the account</h1>
)}
</div>
);
};
export default Data;
JavaScript
import React, { useState } from "react";
import "./form.css";
import { submitRecord } from "../../store/interactions";
import { useDispatch, useSelector } from "react-redux";
const Form = () => {
const provider = useSelector((state) => state.provider.connection);
const medical = useSelector((state) => state.medical.contract);
const account=useSelector((state)=>state.provider.account);
const dispatch = useDispatch();
const submitHandler = (e) => {
e.preventDefault();
submitRecord(
name,
age,
gender,
bloodType,
allergies,
diagnosis,
treatment,
provider,
medical,
dispatch
);
setName(0);
setAge(0);
setGender(0);
setBloodType(0);
setAllergies(0);
setDiagnosis(0);
setTreatment(0);
};
const [name, setName] = useState(0);
const [age, setAge] = useState(0);
const [gender, setGender] = useState(0);
const [bloodType, setBloodType] = useState(0);
const [allergies, setAllergies] = useState(0);
const [diagnosis, setDiagnosis] = useState(0);
const [treatment, setTreatment] = useState(0);
return (
<div className="login-container">
<h1></h1>
{account?( <form onSubmit={submitHandler}>
<h1>Patient Details</h1>
<label htmlFor="name">Patient Name:</label>
<input
type="text"
id="name"
name="name"
value={name === 0 ? "" : name}
onChange={(e) => setName(e.target.value)}
required
placeholder="Aman Dhattarwal"
/>
<label htmlFor="age">Age:</label>
<input
type="number"
id="age"
name="age"
required
placeholder="29"
value={age === 0 ? "" : age}
onChange={(e) => setAge(e.target.value)}
/>
<label htmlFor="gender">Gender:</label>
<select
id="gender"
name="gender"
required
onChange={(e) => setGender(e.target.value)}
value={gender === 0 ? "" : gender}
>
<option value="">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<label htmlFor="address">Blood type:</label>
<input
type="text"
id="name"
name="name"
required
placeholder="B positive"
value={bloodType === 0 ? "" : bloodType}
onChange={(e) => setBloodType(e.target.value)}
/>
<label htmlFor="address">Allergies:</label>
<input
type="text"
id="name"
name="name"
required
placeholder="Pollen allergy"
value={allergies === 0 ? "" : allergies}
onChange={(e) => setAllergies(e.target.value)}
/>
<label htmlFor="address">Diagnosis:</label>
<input
type="text"
id="name"
name="name"
required
placeholder="Osteoporosis"
value={diagnosis === 0 ? "" : diagnosis}
onChange={(e) => setDiagnosis(e.target.value)}
/>
<label htmlFor="address">Treatment:</label>
<input
type="text"
id="name"
name="name"
required
placeholder="Surgery"
value={treatment === 0 ? "" : treatment}
onChange={(e) => setTreatment(e.target.value)}
/>
<input type="submit" value="Submit" />
</form>):(
<h1>Connect the account</h1>
)}
</div>
);
};
export default Form;
Navbar.js:
JavaScript
import React from "react";
import "./navbar.css";
import healthReport from "../../assets/health-report.png";
import { loadAccount } from "../../store/interactions";
import { useDispatch, useSelector } from "react-redux";
import Blockies from "react-blockies";
import config from "../../config.json";
const Navbar = () => {
const dispatch = useDispatch();
const provider = useSelector((state) => state.provider.connection);
const account = useSelector((state) => state.provider.account);
const balance = useSelector((state) => state.provider.balance);
const chainId = useSelector((state) => state.provider.chainId);
const connectHandler = async (e) => {
await loadAccount(provider, dispatch);
};
const networkHandler = async (e) => {
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [
{
chainId: e.target.value,
},
],
});
};
return (
<div className="Navbar">
<div className="nav__name">
<img src={healthReport} alt="" width="40" height="40" />
<h2> Secure Health </h2>
</div>
<div className="nav__networkSelector">
<select
name="network"
id="network"
onChange={networkHandler}
value={config[chainId] ? `0x${chainId.toString(16)}` : `0`}
>
<option value="0" disabled>
Select Network
</option>
<option value="31337">Localhost</option>
<option value="0x5">Goerli</option>
<option value="0x13881">Mumbai</option>
</select>
</div>
<div className="nav__balance">
{balance ? (
<p className="nav__myBalance">
<small>My Balance : </small>
{Number(balance).toFixed(4)}
</p>
) : (
<p className="nav__myBalance">
<small>My Balance : </small>
0ETH
</p>
)}
{account ? (
<a className="nav__myAccount" href="#">
{account.slice(0, 5) + "...." + account.slice(38, 42)}
<Blockies
seed={account}
size={10}
scale={3}
color="#2187D0"
bgColor="#F1F2F9"
spotColor="#767F92"
className="identicon"
/>
</a>
) : (
<button className="nav__balance-box" onClick={connectHandler}>
Connect
</button>
)}
</div>
</div>
);
};
export default Navbar;
Option.js:
JavaScript
import React, { useState } from "react";
import "./option.css";
import { Link } from "react-router-dom";
const Option = () => {
return (
<div className="Option">
<Link to="/" className="opt__form">
Form
</Link>
<Link to="/data" className="opt__data">
Data
</Link>
</div>
);
};
export default Option;
App.js:
JavaScript
import { Route, Routes } from "react-router-dom";
import "../App.css";
import Data from "./Data/Data";
import Form from "./Form/Form";
import Navbar from "./Navbar/Navbar";
import Option from "./Option/Option";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import {
loadAccount,
loadAllData,
loadMedical,
loadNetwork,
loadProvider,
subscribeToEvents,
} from "../store/interactions";
import config from "../config.json";
import Alert from "./Alert/Alert";
function App() {
const dispatch = useDispatch();
const loadBlockchainData = async () => {
const provider = loadProvider(dispatch);
const chainId = await loadNetwork(provider, dispatch);
// Check if config contains an entry for the chainId
if (!(chainId in config)) {
console.error(`No configuration found for chainId ${chainId}`);
return;
}
const medical_config = config[chainId].medical;
window.ethereum.on("accountsChanged", () => {
loadAccount(provider, dispatch);
});
window.ethereum.on("chainChanged", () => {
window.location.reload();
});
const medical = loadMedical(provider, medical_config.address, dispatch);
loadAllData(provider, medical, dispatch);
subscribeToEvents(medical, dispatch);
};
useEffect(() => {
loadBlockchainData();
}, []); // Empty dependency array to run once on component mount
return (
<div className="App">
<div className="navbar">
<Navbar />
<Option />
<Routes>
<Route path="/" exact element={<Form />} />
<Route path="/Data" element={<Data />} />
</Routes>
<Alert />
</div>
</div>
);
}
export default App;
Note:
Include css files for frontend files according to you.
Store interactions.js:
JavaScript
import { ethers } from "ethers";
import MEDICAL_ABI from "../abis/MedicalRecords.json";
export const loadProvider = (dispatch) => {
const connection = new ethers.providers.Web3Provider(window.ethereum);
dispatch({ type: "PROVIDER_LOADED", connection });
return connection;
};
export const loadNetwork = async (provider, dispatch) => {
const { chainId } = await provider.getNetwork();
dispatch({ type: "NETWORK_LOADED", chainId });
return chainId;
};
export const loadAccount = async (provider, dispatch) => {
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
});
const account = ethers.utils.getAddress(accounts[0]);
dispatch({ type: "ACCOUNT_LOADED", account });
let balance = await provider.getBalance(account);
balance = ethers.utils.formatEther(balance);
dispatch({ type: "ETHER_BALANCE_LOADED", balance });
return account;
};
export const loadMedical = (provider, address, dispatch) => {
const medical = new ethers.Contract(address, MEDICAL_ABI, provider);
dispatch({ type: "MEDICAL_LOADED", medical });
return medical;
};
export const loadAllData = async (provider, medical, dispatch) => {
const block = await provider.getBlockNumber();
const medicalStream = await medical.queryFilter(
"MedicalRecords__AddRecord",
0,
block
);
const medicalRecords = medicalStream.map((event) => event.args);
dispatch({ type: "ALL_MEDICAL_RECORDS", medicalRecords });
const deleteStream = await medical.queryFilter(
"MedicalRecords__DeleteRecord",
0,
block
);
const deleteRecords = deleteStream.map((event) => event.args);
dispatch({ type: "ALL_DELETED_RECORDS", deleteRecords });
};
export const submitRecord = async (
name,
age,
gender,
bloodType,
allergies,
diagnosis,
treatment,
provider,
medical,
dispatch
) => {
let transaction;
dispatch({ type: "NEW_RECORD_LOADED" });
try {
const signer = await provider.getSigner();
transaction = await medical
.connect(signer)
.addRecord(name, age, gender, bloodType, allergies, diagnosis, treatment);
await transaction.wait();
} catch (error) {
dispatch({ type: "NEW_RECORD_FAIL" });
}
};
export const deleteData = async (medical, recordId, dispatch, provider) => {
let transaction;
dispatch({ type: "DELETE_REQUEST_INNITIALIZED" });
try {
const signer = await provider.getSigner();
transaction = await medical.connect(signer).deleteRecord(recordId);
await transaction.wait();
} catch (error) {
dispatch({ type: "DELETE_REQUEST_FAILED" });
}
};
export const subscribeToEvents = async (medical, dispatch) => {
medical.on(
"MedicalRecords__AddRecord",
(
recordId,
timestamp,
name,
age,
gender,
bloodType,
allergies,
diagnosis,
treatment,
event
) => {
const medicalOrder = event.args;
dispatch({ type: "NEW_RECORD_SUCCESS", medicalOrder, event });
}
);
medical.on(
"MedicalRecords__DeleteRecord",
(
recordId,
timestamp,
name,
age,
gender,
bloodType,
allergies,
diagnosis,
treatment,
event
) => {
const deleteOrder = event.args;
dispatch({ type: "DELETE_REQUEST_SUCCESS", deleteOrder, event });
}
);
};
reducer.js:
JavaScript
export const provider = (state = {}, action) => {
switch (action.type) {
case "PROVIDER_LOADED":
return { ...state, connection: action.connection };
case "NETWORK_LOADED":
return { ...state, chainId: action.chainId };
case "ACCOUNT_LOADED":
return {
...state,
account: action.account,
};
case "ETHER_BALANCE_LOADED":
return {
...state,
balance: action.balance,
};
default:
return state;
}
};
const DEFAULT_MEDICAL_STATE = {
loaded: false,
contract: {},
transaction: {
isSuccessful: false,
},
allMedical: {
loaded: false,
data: [],
},
deleteMedical: {
loaded: false,
data: [],
},
events: [],
};
export const medical = (state = DEFAULT_MEDICAL_STATE, action) => {
let index, data;
switch (action.type) {
case "MEDICAL_LOADED":
return {
...state,
loaded: true,
contract: action.medical,
};
case "ALL_MEDICAL_RECORDS":
return {
...state,
allMedical: {
loaded: true,
data: action.medicalRecords,
},
};
case "ALL_DELETED_RECORDS":
return {
...state,
deleteMedical: {
loaded: true,
data: action.deleteRecords,
},
};
case "NEW_RECORD_LOADED":
return {
...state,
transaction: {
isPending: true,
isSuccessful: false,
},
};
case "NEW_RECORD_SUCCESS":
index = state.allMedical.data.findIndex(
(order) =>
order.recordId.toString() === action.medicalOrder.recordId.toString()
);
if (index === -1) {
data = [...state.allMedical.data, action.medicalOrder];
} else {
data = state.allMedical.data;
}
return {
...state,
allMedical: {
...state.allMedical,
data,
},
transaction: {
isPending: false,
isSuccessful: true,
},
events: [action.event, ...state.events],
};
case "NEW_RECORD_FAIL":
return {
...state,
transaction: {
isPending: false,
isError: true,
isSuccessful: false,
},
};
case "DELETE_REQUEST_INNITIALIZED":
return {
...state,
transaction: {
isPending: true,
isSuccessful: false,
},
};
case "DELETE_REQUEST_SUCCESS":
index = state.deleteMedical.data.findIndex(
(order) =>
order.recordId.toString() === action.deleteOrder.recordId.toString()
);
if (index === -1) {
data = [...state.deleteMedical.data, action.deleteOrder];
} else {
data = state.deleteMedical.data;
}
return {
...state,
deleteMedical: {
...state.deleteMedical,
data,
},
transaction: {
isPending: false,
isSuccessful: true,
},
events: [action.event, ...state.events],
};
case "DELETE_REQUEST_FAILED":
return {
...state,
transaction: {
isPending: false,
isError: true,
isSuccessful: false,
},
};
default:
return state;
}
};
selector.js:
JavaScript
import { get, reject } from "lodash";
import moment from "moment/moment";
import { createSelector } from "reselect";
const allData = (state) => get(state, "medical.allMedical.data", []);
const deleteData = (state) => get(state, "medical.deleteMedical.data", []);
const account = (state) => get(state, "provider.account");
const events = (state) => get(state, "medical.events");
const openData = (state) => {
const all = allData(state);
const delet = deleteData(state);
const openData = reject(all, (data) => {
const dataDeleted = delet.some(
(o) => o.recordId.toString() === data.recordId.toString()
);
return dataDeleted;
});
return openData;
};
export const dataBookSelector = createSelector(openData, (data) => {
data = decorateOpenData(data);
return data;
});
const decorateOpenData = (datas) => {
return datas.map((data) => {
data = decorateOrder(data);
return data;
});
};
export const decorateOrder = (data) => {
const precision = 100000;
let recordIdNew = Math.round(data.recordId * precision) / precision;
let ageNew = Math.round(data.age * precision) / precision;
return {
...data,
recordIdNew,
ageNew,
formattedTimestamp: moment
.unix(data.timestamp)
.format("h:mm:ssa d MMM yyyy"),
};
};
export const myEventsSelector = createSelector(
account,
events,
(account, events) => {
return events;
}
);
store.js:
JavaScript
import { createStore, combineReducers, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
/* Import Reducers */
import { provider, medical } from "./reducer";
const reducer = combineReducers({ provider, medical });
const initialState = {};
const middleware = [thunk];
const store = createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
App.test.js:
JavaScript
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
index.js:
JavaScript
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./components/App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import store from "./store/store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
<Provider store={store}>
<App />
</Provider>
</BrowserRouter>
);
reportWebVitals();
TestMedicalRecords.test.js:
JavaScript
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("MedicalRecords", () => {
let user1, medical, transactionResponse, transactionReceipt;
beforeEach(async () => {
const account = await ethers.getSigners();
user1 = account[1];
const Medical = await ethers.getContractFactory("MedicalRecords");
medical = await Medical.connect(user1).deploy();
});
describe("Deployment", () => {
it("The contract is deployed successfully", async () => {
expect(await medical.address).to.not.equal(0);
});
});
describe("Add Record", () => {
beforeEach(async () => {
transactionResponse = await medical.addRecord(
"Wastron",
22,
"Male",
"B positive",
"Dengue",
"Dengue",
"Dengue"
);
transactionReceipt = await transactionResponse.wait();
});
it("Emits a Add Record event", async () => {
const event = await transactionReceipt.events[0];
expect(event.event).to.equal("MedicalRecords__AddRecord");
const args = event.args;
expect(args.timestamp).to.not.equal(0);
expect(args.name).to.equal("Wastron");
expect(args.age).to.equal(22);
expect(args.gender).to.equal("Male");
expect(args.bloodType).to.equal("B positive");
expect(args.allergies).to.equal("Dengue");
expect(args.diagnosis).to.equal("Dengue");
expect(args.treatment).to.equal("Dengue");
});
it("The getRecords function is working", async () => {
const [
timestamp,
name,
age,
gender,
bloodType,
allergies,
diagnosis,
treatment,
] = await medical.getRecord(await medical.getRecordId());
expect(await medical.getRecordId()).to.equal(1);
expect(timestamp).to.not.equal(0);
expect(name).to.equal("Wastron");
expect(age).to.equal(22);
expect(gender).to.equal("Male");
expect(bloodType).to.equal("B positive");
expect(allergies).to.equal("Dengue");
expect(diagnosis).to.equal("Dengue");
expect(treatment).to.equal("Dengue");
});
});
describe("The delete function is working", () => {
beforeEach(async () => {
transactionResponse = await medical.addRecord(
"Wastron",
22,
"Male",
"B positive",
"Dengue",
"Dengue",
"Dengue"
);
transactionReceipt = await transactionResponse.wait();
transactionResponse = await medical.deleteRecord(1);
transactionReceipt = await transactionResponse.wait();
});
it("The record is deleted ", async () => {
expect(await medical.getDeleted(1)).to.be.equal(true);
});
it("Emits a delete event", async () => {
const event = await transactionReceipt.events[0];
const args = event.args;
expect(event.event).to.equal("MedicalRecords__DeleteRecord");
expect(args.timestamp).to.not.equal(0);
expect(args.name).to.equal("Wastron");
expect(args.age).to.equal(22);
expect(args.gender).to.equal("Male");
expect(args.bloodType).to.equal("B positive");
expect(args.allergies).to.equal("Dengue");
expect(args.diagnosis).to.equal("Dengue");
expect(args.treatment).to.equal("Dengue");
});
});
});
hardhat.config.js:
JavaScript
require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config();
const privateKeys = process.env.PRIVATE_KEYS || "";
// const goerliApiKey = process.env.GOERLI_URL;
// const mumbaiApiKey = process.env.MUMBAI_URL;
module.exports = {
solidity: "0.8.18",
networks: {
localhost: {},
// goerli: {
// url: goerliApiKey,
// accounts: privateKeys.split(","),
// },
// mumbai: {
// url: mumbaiApiKey,
// accounts: privateKeys.split(","),
// },
},
};
After writing these codes.
Step 1: Open the terminal and start local host by using npx hardhat node.
Step 2: Write the command in another shell to deploy smart contracts in blockchain and to seed it in blockchain.
npx hardhat run scripts/00-deploy.js –network localhost
npx hardhat run scripts/01-seeding.js –network localhost
 Deploying Smart Contracts  Seeding Smart Contracts Step 3: Deploy frontend by using npm run start.
 Deploying frontend After Deploying Frontend of DApp.
Step 4: Connect the wallet with DApp.
 Connecting Wallet with DApp Step 5: Add the details of patient and submit the form than do the transaction using wallet and record the patient details.
 Transaction through Wallet  Successful Transaction Step 6: Go to the Data section and see the new added record.
 Data Section Records  New Added Record Why Should You Learn About DApp Development?In this new technological era, most apps are being built in a decentralized form because it is safe, secure, and transparent. Nowadays, it is a required skill for removing the need for central authorities.
- Eliminate centralized Models: This approach enhance the security and trust by cryptographic verifications. Many big industries are using this approach to eliminate centralized models.
- Cutting-Edge Technology: Blockchain knowledge is necessary for building DApps. Understanding and working with blockchain can give you insight into one of the most transformative technologies of today’s time. It prevents tampering and ensures integrity.
- Decentralization: DApps operate on decentralized networks. This can lead to increased security and transparency.
- Community and Collaboration: DApp development frequently involves engagement in open-source communities where developers collaborate, exchange knowledge, and contribute to advancing decentralized technologies. These communities enhance learning and foster innovation through peer review, feedback, and ongoing enhancements. Developers work collectively to improve applications.
- Career Opportunities: There are many career opportunities in blockchain startups and tech companies. Many industries are exploring blockchain solutions and building decentralized applications.
- Innovation: Blockchain with smart contracts plays a crucial role in data security and transparency, enhancing the performance of applications. It is a demanding skill for DApp developers. Blockchain-specific languages like Solidity, Vyper, and Rust are in high demand for creating DApps.
- User Ownership: Users of DApps have greater control and ownership over their data and assets.
What Are the Important Components in DApp Development?1. Smart ContractsSmart contracts automate processes and enhance security. These contracts make apps faster and ensure transparency and reliability in decentralized applications. We use smart contracts in the back-end part of DApps, which removes intermediaries and ensures integrity.
2. Front-EndIt is the part of the DApp with which users interact and perform actions. The front end should be user-friendly so that users can easily interact with the DApp. For building the front end, we use standard web technologies and frameworks. The front end interacts with the blockchain via smart contracts, so when users perform any actions, it provides immediate results.
- HTML, CSS, JavaScript are used to built frontend.
- Popular frameworks like React, Angular, or Vue.js used in creation of frontend.
3. BlockchainThe blockchain is a fundamental component of DApp development. It stores data and smart contracts, ensuring data integrity, transparency, and security while executing smart contracts across a distributed network.
- It Provides a decentralized, immutable ledger.
- Popular Platforms like Ethereum, Binance Smart Chain, Polkadot, and Solana offer blockchain capabilities.
4. WalletWallets are used to store money in the form of cryptocurrency. They manage private keys and facilitate secure transactions on the blockchain. Users have to pay for performing actions on the blockchain. Wallets enable users to interact with DApps and smart contracts, ensuring the security of their digital assets.
- It Manage private keys and facilitate secure transactions.
- It is Available as both software-based and hardware-based.
- MetaMask is software-based wallet and Ledger is hardware-based wallet.
Steps for Creating a DApp1. Define Your Objective: The initial step is defining the purpose of the DApp. Identify the problem it solves and the target audience.
2. Outline Technical Requirements: Outline other technical requirements such as blockchain platform, smart contract language, and development tools.
3. Choose the Right Blockchain Platform: Choose a appropriate blockchain platform to build a DApp such as Ethereum, Polkadot, Solana, Binance Smart Chain, etc.
4. Design the Architecture: Design the logic and functionality that will be implemented as smart contracts. Plan the frontend and decide the backend components and how they will interact with the blockchain.
5. Development Environment Setup: Setup the development environment with necessary tools and libraries. Setup IDE, Blockchain Node for local blockchain testing, and Wallet for interacting with DApp.
6. Develop Smart Contracts: Write Smart Contracts by using supporting languages like Solidity, Rust and Vyper. Throughly test smart contract using frameworks like Truffle and conduct security audits to identify security weaknesses.
7. Develop the Frontend: Develop the frontend part by using HTML, CSS, JavaScript and frameworks like React and Angular.
8. Develop the Backend: If DApp requires backend, then setup servers or use decentralized storage solutions like IPFS. Develop and integrate APIs to facilitate data exchange between blockchain and backened.
9. Write config.json file to write address of different networks.
10. Testing: Write and run unit tests, conduct integration testing and user testing.
11. Deployment: Deploy your smart contract to testnet first and after thorough testing deploy smart contract to mainnet. Deploy frontend on web servers.
12. Monitoring and Maintenance: Implement tools to monitor usage, performance, and user behavior. Regularly update your DApp to fix bugs.
13. Community Building and Marketing: Use various channels to promote your DApp and Build and engage with your community through social media and forums.
14. Compliance and Legal Considerations: Ensure your DApp complies with relevant legal requirements and Implement measures to protect user data and maintain privacy.
DApp vs App
Feature
| DApp
| App
|
---|
Architecture
| Decentralized
| Centralized
|
---|
Control
| Distributed among network Participants
| Controlled by single entity
|
---|
Security
| High Transparency
| Variable
|
---|
Trust
| Trustless
| Relies on trust in the central authority
|
---|
Data Storage
| Blockchain and Decentralized
| Centralized Servers
|
---|
Maintenance
| Community-driven
| Developer/organization
|
---|
Transaction Fees
| Gas Fees
| No Fees
|
---|
Transactions
| Transactions recorded on blockchain, often with cryptocurrencies
| Transactions processed through centralized servers
|
---|
Performance
| Slower due to blockchain consensus mechanisms
| Generally faster due to centralized processing
|
---|
Example
| Ethereum dApps
| Facebook, Instagram
|
---|
Which Blockchain is Best for DApp?There are many popular Blockchain used for DApp Development. Each blockchain has it’s own advantages. We usually select blockchain according to the problems and need. Some popular blockchain are written below.
1. EthereumEthereum is a very popular blockchain platform recognized for its robust developer community, advanced smart contract capabilities, and well-established ecosystem. Ethereum helps developers to create DApps with smart contracts that provide transparency and security. Ethereum provides facilities such as rapid prototyping, testing, and deployment across diverse industries.
2. SolanaSolana has high capability, processing up to 65,000 transactions per second (TPS). It ensures fast transaction confirmation and low latency in DApps. The architecture of this platform ensures significantly lower transaction fees compared to Ethereum, providing a cost-effective solution for DApps managing large transaction volumes or microtransactions. Solana combines Proof of History (PoH) with Proof of Stake (PoS) to achieve scalability and efficiency.
3. PolkadotPolkadot is famous for its cross-chain interoperability. With the help of Polkadot different blockchains easily communicate and share data. Its parachain architecture promotes scalabililty and flexible governance. Polkadot also support wide range of use cases.
4. Binance Smart Chain (BSC)Binance Smart Chain (BSC) is famous for its low transaction fees and rapid confirmation times compared to Ethereum. It supports the Ethereum Virtual Machine (EVM) and utilizes existing tools, libraries, and developer expertise. Binance Smart Chain benefits from integration with Binance’s broader ecosystem. It includes liquidity pools, token swaps, and access to a vast user base.
ConclusionDApp development removes central authority and provides transparency with security. In today’s world, many big companies like Meta and Google are centralized, with all the data controlled by central authorities, which produces insecurity. To overcome these issues, DApp development plays a major role. By mastering the core components and steps, developers can create innovative solutions that empower users.
FAQs related to Dapp Development1. What is a DApp?Decentralized Application which removes central authority and runs on a decentralized network.
2. What are the Main programming languages for DApp? Main programming languages are Solidity, JavaScript, Rust, and Vyper.
3. What are the Best blockchains for DApp development?Ethereum, Solana, BSC, and Polkadot are the best blockchains.
4. How does a DApp different from a Centralized app?DApp different from a centralized app because It is Decentralized, Secure and transparent.
5. Why should learn DApp development?market demand, Opportunities, innovation, Open source and decentralization advantages.
|