Blockchain_Practicals_Reference Journal.docx
Blockchain_Practicals_Reference Journal.docx
Blockchain_Practicals_Reference Journal.docx
VIVEKANANDEDUCATION SOCIETY’S
INSTITUTE OF TECHNOLOGY
HashuAdvani Memorial Complex, Collector’s Colony, R. C. Marg,
Chembur, Mumbai – 400074. Contact No. 02261532532
Since 1962
CERTIFICATE
Implementation of Decentralized
9 10/12/2021 96
Applications
Theory:
What is Cryptography?
Plain-text: abcdefghijklmnopqrstuvwxyz
Cipher-text: bcdefghijklmnopqrstuvwxyza
Code:
Output:
Conclusion:
Hence, we have successfully implemented Caesar Cipher (Symmetric
Encryption) and we have shown the encryption as well as the decryption
process.
Practical 2
Aim:
Implement RSA Algorithm (Asymmetric Encryption), Encrypt and decrypt a
string.
Theory:
What is Asymmetric Encryption?
The public key is open to everyone. Anyone can access it and encrypt
data with it. However, once encrypted, the data can only be unlocked by
using the corresponding private key. As you can imagine, the private key
must be kept secret to keep it from becoming compromised. So, only the
authorized person, server, machine, or instrument has access to the
private key.
Algorithm
difficult to solve.
There are two sets of keys in this algorithm: private key and public key.
You will have to go through the following steps to work on RSA
algorithm –
The initial procedure begins with selection of two prime numbers namely p
and q, and then calculating their product N, as shown
− N=p*q
Here, let N be the specified large number.
The specified pair of numbers n and e forms the RSA public key and it is
made public.
The above formula is the basic formula for Extended Euclidean Algorithm,
which takes p and q as the input parameters.
Encryption Formula
Consider a sender who sends the plain text message to someone whose
public key is (n,e). To encrypt the plain text message in the given
scenario, use the following syntax:
C = Pe mod n
Decryption Formula
Plaintext = Cd mod n
Code:
Output:
Conclusion:
Hence, we have successfully implemented RSA Algorithm (Asymmetric
Encryption) and we have encrypted and decrypted a string.
Practical 3
Aim:
To implement SHA 256 Algorithm
Theory:
Hashing
As seen from the above image, the hash function is responsible for
converting the plaintext to its respective hash digest. They are designed
to be irreversible, which means your digest should not provide you with
the original plaintext by any means necessary.
Hash functions also provide the same output value if the input remains
unchanged, irrespective of the number of iterations.
SHA256:
SHA 256 is a part of the SHA 2 family of algorithms, where SHA stands for Secure
Hash Algorithm. Published in 2001, it was a joint effort between the NSA and NIST
to introduce a successor to the SHA 1 family, which was slowly losing strength
against brute force attacks. The significance of the 256 in the name stands for the
final hash digest value, i.e., irrespective of the size of plaintext/cleartext, the hash
value will always be 256 bits.
The other algorithms in the SHA family are more or less similar to SHA 256. Now,
look into knowing a little more about their guidelines. The Secure Hash Algorithm
is one of a number of cryptographic hash functions. A cryptographic hash is like a
signature for a data set. If you would like to compare two sets of raw data it is
always better to hash it and compare SHA256 values. It is like the fingerprints of
the data. Even if only one symbol is changed the algorithm will produce a different
hash value.
SHA256 algorithm generates an almost-unique, fixed size 256-bit
(32-byte) hash. Hash is so called a one-way function. This makes it
suitable for checking integrity of your data, challenge hash
authentication, anti-tamper, digital signatures, blockchain. With the
newest hardware improvements, it has become
For example, if you download something you can easily check if data has
not changed due to network errors or malware injection. You can
compare hashes of your file and original one which is usually provided
in the website you are getting data or the file from. SHA-256 is one of
the successor hash functions to SHA-1, and is one of the strongest hash
functions available.
Code:
Output:
Conclusion:
Hence, we have successfully implemented RSA algorithm (asymmetric
encryption), encrypt and decrypt a string.
Practical 4
Aim:
To Implementation of Binary Tree and to show all operations (Insert,
Delete, Traversals, Display)
Theory:
Tree
In the Tree data structure, the topmost node is known as a root node.
Each node contains some data, and data can be of any type. In the
above tree structure, the node contains the name of the employee, so
the type of data would be a string. Each node contains some data and
the link or reference of other nodes that can be called children.
Tree Terminologies
Root
In a tree data structure, the root is the first node of the tree. The root
node is the initial node of the tree in data structures. In the tree data
structure, there must be only one root node.
Edge
Parent
In the tree in data structures, the node that is the predecessor of any
node is known as a parent node, or a node with a branch from itself to
any other successive node is called the parent node.
Child
Siblings
In trees in the data structure, nodes that belong to the same parent are
called siblings.
Leaf
Trees in the data structure, the node with no child, is known as a leaf
node. In trees, leaf nodes are also called external nodes or terminal
nodes.
Internal nodes
Trees in the data structure have at least one child node known as
internal nodes. In trees, nodes other than leaf nodes are internal nodes.
Sometimes root nodes are also called internal nodes if the tree has more
than one node.
Degree
Level
In tree data structures, the root node is said to be at level 0, and the root
node's children are at level 1, and the children of that node at level 1 will
be level 2, and so on.
Height
In a tree data structure, the number of edges from the leaf node to the
particular node in the longest path is known as the height of that node.
In the tree, the height of the root node is called "Height of Tree". The
tree height of all leaf nodes is 0.
Depth
In a tree, many edges from the root node to the particular node are
called the depth of the tree. In the tree, the total number of edges from
the root node to the leaf node in the longest path is known as "Depth of
Tree". In the tree data structures, the depth of the root node is 0.
Path
In the tree in data structures, the sequence of nodes and edges from one
node to another node is called the path between those two nodes. The
length of a path is the total number of nodes in a path.zx
Subtree
Binary Tree:
A binary tree is a tree data structure in which each parent node can have
at most two children. Each node has a key and an associated value. The
value of the key of the left sub-tree is less than the value of its parent
(root) node's key. The value of the key of the right sub-tree is greater
than or equal to the value of its parent (root) node's key.
A parent node has two child nodes: the left child and right child.
Hashing, routing data for network traffic, data compression, preparing
binary heaps, and binary search trees are some of the applications that
use a binary tree.
• data item
• address of left child
• address of right child
Basic Operations
Create Root − We just create a Node class and assign a value to the
node. This becomes a tree with only a root node.
Insert – (Inserts an element in a tree.) To insert into a tree, we use the same
node class created above and add an insert class to it. The insert class
compares the value of the node to the parent node and decides to add it as a
left node or a right node. Finally, the PrintTree class is used to print the tree.
Traversing a Tree – The tree can be traversed by deciding on a
sure that tree shrinks from the bottom. This is different from
BST deletion. Here we do not have any order among elements, so
we replace it with the last element.
Algorithm
1. Starting at the root, find the deepest and rightmost node in the binary
tree and node which we want to delete.
2. Replace the deepest rightmost node’s data with the node to be deleted.
Merkle Tree
Merkle tree / Hash Tree is a tree in which every leaf node is labelled
with the cryptographic hash of a data block, and every non-leaf node is
labelled with the cryptographic hash of the labels of its child nodes.
Hash trees allow efficient and secure verification of the contents of large
data structures. Hash trees are a generalization of hash lists and hash
chains. used for data verification and synchronization. It is a tree data
structure where each non-leaf node is a hash of its child nodes. All the
leaf nodes are at the same depth and are as far left as possible. It
maintains data integrity and uses hash functions for this purpose.
Every leaf node is a hash of transactional data, and the non-leaf node
is a hash of its previous hashes. Merkle trees are in a binary tree, so it
requires an even number of leaf nodes. If there is an odd number of
transactions, the last hash will be duplicated once to create an even
number of leaf nodes.
Applications:
Benefits:
# Insert Node
def insert(self,
data): if
self.data:
if data < self.data:
if self.left is None:
self.left =
Node(data)
else:
self.left.insert(dat
a) elif data > self.data:
if self.right is None:
self.right =
Node(data)
else:
self.right.insert(dat
a) else:
self.data = data
# Preorder
traversal # Root ->
Left ->Right
def PreorderTraversal(self,
root): res = []
if root:
res.append(root.data)
res = res +
self.PreorderTraversal(root.left) res =
res + self.PreorderTraversal(root.right)
return res
# Postorder
traversal # Left
->Right -> Root
def PostorderTraversal(self,
root): res = []
if root:
res = self.PostorderTraversal(root.left)
res = res +
self.PostorderTraversal(root.right)
res.append(root.data)
return res
Output:
Conclusion:
Hence, we have successfully implemented Binary Tree and showed all
operations (Insert, Delete, Traversals, Display).
Practical 5
Aim:
Install Geth Ethereum Node (Show installation steps also). Create a
Genesis block and a private chain. Use geth commands to create user
accounts, mine, transact etc.
Theory:
What is a node?
Geth:
Genesis Block:
chaindata.
account.
Open up notepad, copy & paste the code below into a new file
{
"config": {
"chainId": 4777,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0, "eip158Block": 0
},
"alloc" : {}, "difficulty"
: "0x400", "extraData"
: "",
"gasLimit" : "0x7A1200",
"parentHash" :
"0x000000000000000000000000000000000000000000000
0000000000 000000000", "timestamp" : "0x00"
}
genesis.json.
run geth: geth --datadir=./chaindata/
1. Start mining:
2. Stop mining:
3. Check blockNumber:
Transaction:
Conclusion:
Hence, we have successfully learned how to install Geth, create a genesis
block, private chain and commands to create user accounts, mine and
transact ethers among accounts.
Practical 6
Aim:
To implement the installation of Ganache, Metamask and Remix IDE and
deploy smart contract using injected web 3 environment.
Theory:
Ganache is used for setting up a personal Ethereum Blockchain for
testing your Solidity contracts. It provides more features when
compared to Remix. Ganache is a personal blockchain for rapid
Ethereum and Corda distributed application development. You can use
Ganache across the entire development cycle; enabling you to develop,
deploy, and test your dApps in a safe and deterministic environment.
Ganache:
2) Install Ganache
The console in the above screenshot shows user accounts with balance
of 100 ETH (Ether - a currency for transaction on Ethereum platform).
It shows a transaction count of zero for each account. As the user has
not performed any transactions so far, this count is obviously zero.
Metamask: Installation:
Step 8: Click on the dark area which says Click here to reveal secret
words to get your secret phrase.
Step 9: This is the most important step. Back up your secret phrase
properly. Do not store your secret phrase on your computer. Please read
everything on this screen until you understand it completely before
proceeding. The secret phrase is the only way to access your wallet if you
forget your password.
Once done click the Next button.
Step 10: Click the buttons respective to the order of the words in your
seed phrase. In other words, type the seed phrase using the button on
the screen. If done correctly the Confirm button should turn blue.
Step 11: Click the All Done button. Please follow the tips
mentioned.
Step 12: One can see the balance and copy the address of the account
by clicking on the Account 1 area.
Step 13: One can access MetaMask in the browser by clicking the
MetaMask extension icon on the top right.
● Fill the network details such as Network Name, RPC Url and Chain
Id and Save it.
Note: RPC url is mentioned on your ganache console as RPC Server.
Step 15: Importing Accounts.
Step 1: Go to https://remix.ethereum.org/
Let’s now create a new contract. For that, right-click on the workspace
and select New File. Name our file.
Step 2: Select your newly created file and type the following code.
Code:
pragma solidity ^0.4.2;
contract Election {
// Model a Candidate
struct Candidate {
uint id; string
name;
uint voteCount;
}
// Store Candidates
// Fetch Candidate
mapping(uint => Candidate) public candidates;
Step 3:
Click on Deploy Button and you will see a pop up for confirmation.
Once confirm your contract is deployed.
After your contract is successfully deployed, you will able to see your
contract under the deployed contracts.
If you give the input as 1 in Candiates column , you will be to see the
details of our first candidate. In our case, the first candidate is Modi.
If you give the input as 1 in Candiates column , you will be to see the
details of our first candidate. In our case, the first candidate is Modi.
If you click on votes button with any account address as input you can
see whether the person has voted or not.
It gives the Boolean result meaning false as not voted and true as voted.
Conclusion:
Hence, we have successfully completed the installation of Ganache,
Metamask and Remix IDE and the deployed the smart contract and
shown its output.
Practical 7
Aim:
To study solidity and implement some examples with it.
Theory:
Solidity:
When deploying contracts, you should use the latest released version of
Solidity. Apart from exceptional cases, only the latest version receives
security fixes. Furthermore, breaking changes as well as new features
are introduced regularly. We currently use a
0.y.z version number to indicate this fast pace of change.
Smart Contract:
A smart contract is a stand-alone script usually written in Solidity and compiled into
binary or JSON and deployed to a specific address on the blockchain. In the same
way that we can call a specific URL endpoint of a RESTful API to execute some logic
through an HttpRequest, we can similarly execute the deployed smart contract at a
specific address by submitting the correct data along with the necessary Ethereum to
call the deployed and compiled Solidity function.
Q1. Write a program in solidity to create a structured
student with Roll no, Name,Class, Department,Course
enrolled as variables.
Students.sol
pragma solidity ^ 0.5 .0;
contract students
struct Student
uint rn;
string name;
string class;
string department;
string course;
Student[] student;
uint count;
constructor() public
count = 0;
}
uint i = 0;
if (student[i].rn == rollNumber)
return student;
}}
Output:
- Deploy the code:
Code:
pragma solidity ^ 0.8 .0;
pragma experimental ABIEncoderV2;
contract pract7b
{
struct Consumer {
uint units;
string name;
string addr;
uint consumerID;
uint amount;
}
Consumer[] consumer;
Conclusion:
Hence, we have successfully studied solidity and implemented some
examples with it.
Practical 8
Aim:
Smart Contract using Truffle Framework.
Theory:
Truffle framework:
− Deposit
− Withdraw ( keep a condition that only the owner of the
contract can withdraw)
− Receive Ether
− Transfer Ether
− Check Balance
Code:
- FC1.sol
pragma solidity ^ 0.5 .0;
contract FC1
{
address owner;
constructor() public
{
owner = msg.sender;
}
modifier ifOwner()
{
if (owner != msg.sender)
{
revert();
}
else
{
_;
}
}
Steps:
1. Go to cmd prompt:
$ mkdir blockchain-toolkit
$ cd blockchain-toolkit
$ truffle init
$ touch package.json
4. $ npm install
= function(deployer)
deployer.deploy(overloading);
};
Outputs:
1. $ truffle compile
2. $ truffle migrate
3. $ truffle console
4. > overloading.deployed().then((instance) => {app = instance} )
5. > app.getSum(5,6)
6. > app.callSumWithTwoArguments()
7. > app.callSumWithThreeArguments()
Conclusion:
Hence, we have successfully executed the smart contract using truffle
framework.
Practical 9
Aim:
Create Daps using Solidity smart contract and web3.
Theory:
Solidity Smart Contracts:
You can install Truffle with NPM in your command line like this:
Web3:
Web3 enhances the internet as we know it today with a few other added
characteristics. web3 is:
● Verifiable
● Trustless
● Self-governing
● Permissionless
● Distributed and robust
● Stateful
● Native built-in payments
In web3, developers don't usually build and deploy applications that run
on a single server or that store their data in a single database (usually
hosted on and manage by a single cloud provider). Instead, web3
applications either run on blockchains, decentralized networks of many
peer to peer nodes (servers), or a combination of the two that forms a
cryptoeconomic protocol.
These apps are often referred to as dapps (decentralized apps), and you
will see that term used often in the web3 space. To achieve a stable and
secure decentralized network, network participants (developers) are
incentivized and compete to provide the highest quality services to
anyone using the service.
Ethereum:
Code:
- Election.sol
pragma solidity 0.4.25;
contract Election {
// Model a Candidate
struct Candidate {
uint id;
string name;
uint voteCount;
}
// Store accounts that have voted
mapping(address => bool) public voters;
// Store Candidates // Fetch Candidate
mapping(uint => Candidate) public candidates;
// Store Candidates Count
uint public candidatesCount;
// voted event
event votedEvent (uint indexed _candidateId);
constructor () public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
function addCandidate (string _name) private {
candidatesCount ++;
candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
}
function vote (uint _candidateId) public {
// require that they haven't voted before
require(!voters[msg.sender]);
// require a valid candidate
require(_candidateId > 0 && _candidateId <= candidatesCount);
// record that voter has voted
voters[msg.sender] = true;
// update candidate vote Count
candidates[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}}
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Election Results</title>
- app.js
App = {
web3Provider: null,
contracts: {},
account: '0x0',
hasVoted: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// TODO: refactor conditional if
(typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask. App.web3Provider =
web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided App.web3Provider =
new
Web3.providers.HttpProvider('http://localhost:7545'); web3
= new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function() {
$.getJSON("Election.json", function(election) {
// Instantiate a new truffle contract from the artifact App.contracts.Election =
TruffleContract(election);
// Connect provider to interact with contract
App.contracts.Election.setProvider(App.web3Provider); App.listenForEvents();
return App.render();
});
},
// Listen for events emitted from the contract
listenForEvents: function() {
App.contracts.Election.deployed().then(function(instance) {
// Restart Chrome if you are unable to receive this event
// This is a known issue with Metamask
// https://github.com/MetaMask/metamask-extension/issues/2393
instance.votedEvent({}, {
fromBlock: 0,
toBlock: 'latest'
}).watch(function(error, event) {
console.log("event triggered", event)
// Reload when a new vote is recorded App.render();
});
});
},
render: function() {
var electionInstance;
var loader = $("#loader");
var content = $("#content");
loader.show();
content.hide();
// Load account data web3.eth.getCoinbase(function(err,
account) {
if (err === null) {
App.account = account;
$("#accountAddress").html("Your Account: " + account);
}
});
// Load contract data App.contracts.Election.deployed().then(function(instance)
{
electionInstance = instance;
return electionInstance.candidatesCount();
}).then(function(candidatesCount) {
var candidatesResults = $("#candidatesResults"); candidatesResults.empty();
var candidatesSelect = $('#candidatesSelect');
candidatesSelect.empty();
for (var i = 1; i <= candidatesCount; i++) {
electionInstance.candidates(i).then(function(candidate) {
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate = "<tr><th>" + id + "</th><td>" + name +
"</td><td>" + voteCount + "</td></tr>"
candidatesResults.append(candidateTemplate);
// Render candidate ballot option
var candidateOption = "<option value='" + id + "' >" + name + "</
option>"
candidatesSelect.append(candidateOption);
});
}
return electionInstance.voters(App.account);
}).then(function(hasVoted) {
// Do not allow a user to vote if(hasVoted)
{
$('form').hide();
}
loader.hide();
content.show();
}).catch(function(error) {
console.warn(error);
});
},
castVote: function() {
var candidateId = $('#candidatesSelect').val();
App.contracts.Election.deployed().then(function(instance) {
return instance.vote(candidateId, { from: App.account });
}).then(function(result) {
// Wait for votes to update
$("#content").hide();
$("#loader").show();
}).catch(function(err) {
console.error(err);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
- truffle-config.js
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// for more about customizing your Truffle configuration! networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
}
},
compilers: {
solc: {
version: '0.4.25',
optimizer: {
enabled: true,
runs: 200
}
}
}
};
- bs-config.js
{
"server": {
"baseDir": ["./src", "./build/contracts"]
}
}
- package.json
{
"name": "election",
"version": "1.0.0",
"description": "",
"main": "truffle.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"lite-server": "^2.3.0",
"truffle": "5.0.0-beta.0"
}
}
- 2_deploy_contracts.js
module.exports = function(deployer) {
deployer.deploy(Election);
};
Output:
Q.2. Supply Chain Management:
Code:
- AssetTracker.sol
pragma solidity ^0.5.0;
contract AssetTracker {
struct Asset {
string name;
string description;
address manufacturer;
bool initialized;
}
struct tracking {
address location;
string uuid;
}
mapping(string => tracking) locations;
mapping(string => Asset) private assetStore;
event AssetCreate(address manufacturer, string uuid, address location); event
AssetTransfer(address from, address to, string uuid);
function createAsset(string memory name, string memory description, string
memory uuid) public {
require(!assetStore[uuid].initialized, "Asset With This UUID Already
Exists");
assetStore[uuid] = Asset(name, description, msg.sender,true); locations[uuid] =
tracking(msg.sender, uuid);
emit AssetCreate(msg.sender, uuid, msg.sender);
}
function transferAsset(address to, string memory uuid) public {
require(locations[uuid].location==msg.sender, "You are Not
Authorized to Transfer This Asset");
locations[uuid]= tracking(to, uuid);
emit AssetTransfer(msg.sender, to, uuid);
}
function getAssetLocation2()public view returns (bool) {
return false;
}
function getAssetDetails(string memory uuid)public view returns (string memory,string
memory,address) {
return (assetStore[uuid].name, assetStore[uuid].description,
assetStore[uuid].manufacturer);
}
function getAssetLocation(string memory uuid)public view returns (address) {
return (locations[uuid].location); }}
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Supplychain Tracking Dapp</title>
</head>
<body>
<div id="band"></div>
<h2>Supplychain Tracking System</h2>
</br>
<div style="text-align: center;">
<label><b>Create Asset:</b></label>
<form id='createAsset' onSubmit="App.createAsset(); return false;" >
<input type="text" id="assetName" placeholder=" Asset Name" required
/>
<input type="text" id="assetDescription" placeholder="Description"
required />
<input type="number" id="assetUuid" placeholder="UUID" required />
<button id='createAsset' type="submit" class="registerbtn">Create Asset</button>
</form>
</div>
// Render Account
// $('#account').html(App.account)
// Render Tasks
await
App.AssetTracker.transferAsset(document.getElementById("address").value,
document.getElementById("Uuid").value,{from:App.account}).then(function
(err, result4) {
if (err) {
return error(err);
}
// The return value is a BigNumber object
console.log(result4);
});
console.log("shruti nft1");
},
createAsset:async()=>{
console.log(document.getElementById("assetName").value,document.get
ElementById("assetDescription").value,document.getElementById("assetUuid
").value);
await
App.AssetTracker.createAsset(document.getElementById("assetName").value
,document.getElementById("assetDescription").value,document.getElementB
yId("assetUuid").value,{from:App.account}).then(function (x) {
console.log(x);
// document.getElementById("location").innerHTML = result4;
});
console.log("shruti nft1");
},
getAssetDetails:async()=>{ console.log(document.getElementById("trackUuid").value);
const rs3= await App.AssetTracker.getAssetLocation2({from:App.account});
console.log(rs3);
const res = await
App.AssetTracker.getAssetDetails(document.getElementById("trackUuid").val
ue,{from:App.account});
console.log(res);
await
App.AssetTracker.getAssetDetails(document.getElementById("trackUuid").val
ue,{from:App.account}).then(function(x) {
console.log(x);
// The return value is a BigNumber object
// document.getElementById("location").innerHTML = result4;
document.getElementById("name").innerHTML = x[0];
document.getElementById("description").innerHTML = x[1];
document.getElementById("manufacturer").innerHTML = x[2];
// document.getElementById("location").innerHTML = result4;
});
await
App.AssetTracker.getAssetLocation(document.getElementById("trackUuid").v
alue,{from:App.account}).then(function(x) {
console.log(x);
document.getElementById("location").innerHTML = x;
});
console.log("shruti nft1");
},
setLoading: (boolean) => {
App.loading = boolean
const loader = $('#loader')
const content = $('#content')
if (boolean) {
loader.show()
content.hide()
} else {
loader.hide()
content.show()
}
}
}
$(() => {
$(window).load(() => {
App.load()
})
})
- truffle-config.js
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
}
},
compilers: {
solc: {
version: '0.4.25',
optimizer: {
enabled: true,
runs: 200
}
}
}
};
- bs-config.js
{
"server": {
"baseDir": [
"./src",
"./build/contracts"
],
"routes": {
"/vendor": "./node_modules"
}
}
}
- package.json
{
"name": "election",
"version": "1.0.0",
"description": "",
"main": "truffle.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"lite-server": "^2.3.0",
"truffle": "5.0.0-beta.0"
}
}
- 2_deploy_contracts.js
const AssetTracker = artifacts.require("AssetTracker");
module.exports = function (deployer) {
deployer.deploy(AssetTracker);
};
Output:
Creating an asset
Click confirm
Conclusion:
We successfully created Daps for voting and Supply chain management.
Mini – Project
Team Members:
1. Name: Prathamesh Indulkar
Roll No.: 22
2. Name: Shruti Naik
Roll No.: 40
Introduction:
A decentralized online marketplace is an eCommerce platform operated
on a blockchain.
Existing System:
E-commerce provides tremendous benefits to traditional brick and
mortar stores by allowing businesses to exponentially expand their
reach and reach a much larger market. However, with such
convenience comes a cost; this cost is paid to the third party, which
essentially acts as insurance in mediating the
payment. eBay, Amazon, Ali Baba, and other well-known centralized
e-commerce platforms are examples. The issue with these e-commerce
websites is that they charge exorbitant fees. Furthermore, because the
dispute process is painfully slow, it could take weeks or even months to
get your money back when a dispute arises.
Proposed System:
Marketplace is not a fee-based intermediary platform for buyers and
sellers; it simply provides them with a client. Sellers create a listing on
the Marketplace, and other Marketplace buyer can view and buy it.
Payments are only made in Ether. Once a product is sold it cannot be
sold again.
Technologies/Software Used:
▪ Node.js:
This is used to install all the packages required for the project and
also to handle the client-side of the project
▪ Truffle Suite:
▪ Ganache:
It is blockchain used for this project where you and use it without
paying any thing for it.
▪ MetaMask:
▪ React:
// contract that handles the entire business logic (buying and selling)
contract Marketplace {
// state variable
string public name;
struct Product {
uint256 id;
string name;
uint256 price;
address payable owner;
// owner - person who owns the product when the product is
// sold the owner gets changed to new buyer
bool purchased; //to check if the product is already purchased or not
}
event ProductCreated(
uint256 id,
string name,
uint256 price,
address payable owner,
bool purchased
);
event ProductPurchased(
uint256 id,
string name,
uint256 price,
address payable owner,
bool purchased
);
// payable is a modifier
function purchaseProduct(uint256 _id) public payable {
// fetch product
Product memory _product = products[_id];
// fetch owner
address payable _seller = _product.owner;
require(!_product.purchased);
// 4. required that
buyer is not seller
require(_seller !=
msg.sender);
// trigger an event
emit ProductPurchased( productCount,
_product.name,
_product.price,
msg.sender, true
);
}
}
2_deploy_contracts.js:
const Marketplace = artifacts.require("Marketplace");
module.exports = function(deployer) {
deployer.deploy(Marketplace);
};
Marketplace.test.js:
// selling product
it('sells product', async()=>{
// console.log(newSellerBalance)
// console.log(oldSellerBalance)
// console.log(price);
// failed
// 1. trying to buy product that does not exist (product should have a
valid id)
await marketplace.purchaseProduct(99, { from: buyer, value:
web3.utils.toWei('1', 'Ether') }).should.be.rejected;
// 2. buyer tries to buy without enough ethers
await marketplace.purchaseProduct(productCount, { from: buyer, value:
web3.utils.toWei('0.5', 'Ether') }).should.be.rejected;
// 3. deployer tries to buy the product, i.e product cant be purchased twice
(fake product)
await marketplace.purchaseProduct(productCount, { from: deployer, value:
web3.utils.toWei('1', 'Ether') }).should.be.rejected;
// 4. buyer tries to buy again, i.e buyer cant be the seller
await marketplace.purchaseProduct(productCount, { from: buyer, value:
web3.utils.toWei('1', 'Ether') }).should.be.rejected;
})
})
})
Client Side:
App.js:
import React, { Component } from 'react';
import Web3 from 'web3';
import logo from '../logo.png'; import
'./App.css';
import Navbar from './Navbar';
import Main from './Main'
import Marketplace from '../abis/Marketplace.json'
// lifecycle component - anytime the component gets called this function will be
executed first
async componentWillMount(){ await
this.loadWeb3()
// console.log(window.web3); await
this.loadBlockchainData()
}
async loadWeb3(){
if (window.ethereum) {
window.web3 = new Web3(window.ethereum); await
window.ethereum.enable();
}
else if (window.web3) {
window.web3 = new Web3(window.web3.currentProvider);
}
else {
window.alert('Non-Ethereum browser detected. You should consider trying
MetaMask!');
}
}
async loadBlockchainData(){
const web3 = window.web3
// load acct
const accounts = await web3.eth.getAccounts()
// console.log(accounts);
this.setState({account: accounts[0]})
// console.log(Marketplace.abi, Marketplace.networks[5777].address);
const networkId = await web3.eth.net.getId()
// console.log(networkId);
const networkData = Marketplace.networks[networkId]
if(networkData){
// const abi = Marketplace.abi
// const address = Marketplace.networks[networkId].address
// const marketplace = new web3.eth.Contract(abi, address)
// console.log(marketplace);
const marketplace = new web3.eth.Contract(Marketplace.abi,
networkData.address)
// console.log(marketplace);
this.setState({ marketplace })
const productCount = await marketplace.methods.productCount().call()
// console.log(productCount);
this.setState({productCount})
// fetching products
for(var i = 1; i<= productCount; i++)
{
const product = await marketplace.methods.products(i).call() this.setState({
products: [...this.state.products, product]
})
}
this.setState({ loading: false })
// console.log(this.state.products);
}
else{
window.alert("Marketplace Contract not deployed to detected network")
}
}
constructor(props){
super(props)
this.state = {
account: '',
productCount: 0,
products: [], loading:
true
}
this.createProduct = this.createProduct.bind(this)
this.purchaseProduct = this.purchaseProduct.bind(this)
}
createProduct(name, price){
this.setState({ loading : true })
this.state.marketplace.methods.createProduct(name, price).send({ from:
this.state.account })
.once('receipt', (receipt) => {
this.setState({loading: false})
})
}
purchaseProduct(id, price){
this.setState({loading: true})
this.state.marketplace.methods.purchaseProduct(id).send({from:
this.state.account, value: price})
.once('receipt', (receipt)=>{
this.setState({loading: false})
})
}
render() {
return (
<div>
<Navbar account={this.state.account}/>
<div className="container-fluid mt-5">
<div className="row">
<main role="main" className="col-lg-12 d-flex justify-content- center
text-center">
{ this.state.loading
? <div id="loader" className="text-center"><p className="text-
center">Loading ..</p></div>
: <Main
products = {this.state.products}
createProduct = {this.createProduct }
purchaseProduct = {this.purchaseProduct }
/>
}
</main>
</div>
</div>
</div>
);
}}
export default App;
Navbar.js:
import React, { Component } from 'react';
</tbody>
</table>
</div>
);
}
}
export default Main;
Output:
1. truffle compile:
3. truffle test:
4. truffle migrate:
Run the server to open frontend:
npm run start:
Add Product:
Click Confirm
Product added:
Add 2 more products
Conclusion:
We have successfully created Marketplace using Blockchain.