0% found this document useful (0 votes)
44 views27 pages

Lab6A-Asset Tracking

Uploaded by

mohammed.ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views27 pages

Lab6A-Asset Tracking

Uploaded by

mohammed.ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Bhartiya Vidya Bhavan’s

Sardar Patel Institute of Technology, Mumbai-400058


Department of Computer Science and Engineering
OEIT1:Blockchain Technology and Applications

Lab-6A:Asset Tracking

Student Name: Shanouf Ansari (Batch - A)


UCID: 2021300004
Branch: Computer Engineering

Objective: Write a smart contract for the asset tracker application, and deploy it to Ethereum
Private blockchain

Outcomes: After successful completion of lab students should be able to


1. Write a smart contract for real-world use case asset management
2. Identify participants in the asset tracker application
3. Creating a participant contract and an asset contract
4. Building an asset tracker smart contract with Solidity
5. Learning Truffle and Web3.js framework
6. Deploy AssetTracker smart contract to Ethereum private network

System Requirements:
PC (C2D, 4GB RAM, 100GB HDD space and NIC),Ubuntu Linux 14.04/20.04
Internet connectivity,Python Cryptography and Pycrypto,REST API,Go Language
Go Ethereum, Truffle Suite, Metamask, IPFS, OpenSea Market Place
Local Blockchain network with Ganache,Truffle framework,Web3.js

1
Figure-1: Blockchain Implementation

About the Asset Management:

What is asset management?


Asset management refers to a systematic approach to the governance and realization of value
from the things that a group or entity is responsible for, over their entire life cycles. Asset
management is a systematic process of developing, operating, maintaining, upgrading, and
disposing of assets in the most cost-effective manner (including all costs, risks, and performance
attributes) -Wikipedia.

What are assets?


An asset is something that has potential or actual value to an organization. An asset can be
tangible or intangible. Tangible assets (assets that can be touchable) include buildings, materials,
vehicles, properties, and equipment among others. On the other hand, intangible assets (assets
that are not touchable) like copyrights, patents, software, and so on.

Asset management is not new, people have been managing assets for years. Over the years,
managing assets is getting better and easier through adopting technology solutions. However,
current asset management process is not efficient and optimized..

Challenges with asset tracking in the real world


Asset management is the biggest area in many supply chain industries. Current asset
management solutions are facing the following challenges:

KYC: Knowing participant’s history and behaviors helps to predict the business outcome
accurately. Participants/parties identity within the supply chain is still manual and involves
paperwork. Some participants have a digital identity, but lacks trust as it is built on a centralized
platform.

Provenance and authenticity: Unable to trace the asset to its origin and provenance. It is very
difficult/impossible/costly to trace an asset in the asset lifecycle.

2
Agreement and Paperwork: A lot of parties in the supply chain still follow paperwork to create a
contract, and record the transactions.

Ownership in case of asset damage: Asset gets exchange multiple hands in the supply chain
when something goes wrong with the asset. It's impossible to find out where it went wrong.

Cost: Companies spending millions to billions of dollars every year to manage assets better.
Multiple parties involved: Too many people involved and each of them operates in their own
way.

Apart from the above challenges, current asset management solutions are non-auditable and non
traceable with a very high fraud rate.

Advantages of building asset management in blockchain

Designing an asset management system with blockchain overcomes above challenges, and has
the following advantages:

Traceability and auditing: State of assets and all the transactions from manufacturer to the buyer
is recorded in the immutable ledger. For example metrics like temperature, condition of the
assets, and so on through IoT devices are stored in blockchain. Blockchain tracks information
like geolocation which makes it easy to trace assets. This makes blockchain a single source of
truth. Consensus: Each transaction will be validated by the participant in the network, which
makes the transactions trustable.

Smart contracts: Makes business rules and contracts programmable, automates the processes and
eliminates the waits in the life cycle.

Security: Private blockchains mitigate much of this operational risk,eliminate fraud, and data
tampering.

Decentralized: No one in the supply chain controls the data, which means that the data can be
trusted. Every participant in the network will have a copy of the ledger, which makes the system
consistent, highly available, and fault tolerance.

Auto payments: Based on asset arrival and condition through crypto or off-chain payment
system.

Eliminates middlemen: Eliminate transfer agents, broker-dealers, and so on. Reduces operational
cost.

Apart from the above advantages, blockchain provides efficient processing and real-time access
to information.

3
Asset tracker use cases
Asset tracker project-Blockchain is the right fit for asset management, which brings trust and
traceability alongside eliminating fraud, reducing cost, and offering a decentralized
infrastructure.

The following are the asset tracking use cases, where blockchain is a right fit:

Tracking of high-value goods like Rolex watches, diamonds, jewelry, and so on

Tracking machinery from manufacturer till the disposal

Tracking computer equipment in an office

Tracking intellectual properties

Tracking vehicles start from manufacturing to recycling/disposal and so on

In this lab, we will be building an asset tracking application that tracks vehicle assets from
manufacturing to the buyer.

Figure-1:Asset tracker project workflow diagram

Procedure: IDE - You can use any of your preferred IDE e.g. Visual Studio code

Solidity Compiler - Solidity extension to Visual Studio code

Chrome browser

MetaMask wallet extension in the Chrome browser

node.js and npm

4
Solidity compiler for node.js: npm install -g solc

Make sure all the pre-requisites are in place before you start the lab

$cd ~

$mkdir lab6a

$cd lab6a

Step-1: Ganache - setup local blockchain network.

Ganache makes the development of smart contracts faster and easier. Instead of using a live/test
blockchain network for Ethereum development, you can use Ganache to create a local
blockchain network to deploy contracts, develop applications, and run tests.

Step-2: Truffle framework - setup asset tracker project

Truffle is the development framework to build Ethereum blockchain applications. It aims to


make the life of a developer easy.

The following are some of the advantages of using Truffle:

Truffle helps in building, compiling, and deploying solidity smart contracts to any Ethereum
network (local, Test net, private network, and main network).

Creates a pipeline for blockchain using EVM.

Automated contract testing for rapid development.

Scriptable, extensible deployment and migrations framework.

Package management with the EthPM and NPM, using theERC190 standard.

Interactive console for direct contract communication.

Truffle makes it easy to start with basic project templates.

Installing Truffle

Before installing truffle makes sure NodeJS v8.9.4 or later is installed. Once that is done, follow
the steps to install Truffle:

Truffle can be installed through npm by entering the following command:

5
$ npm install -g truffle

After the installation, verify the installation with the following command:

$ truffle version

$truffle

6
We will use Truffle compile, develop, console, and migrate commands in this lab

Creating AssetTracker project

In this section, we will create an AssetTacker project through Truffle.

The following are step by step instructions for creating an AssetTracker project: Create a new
folder called the

$ mkdir AssetTracker

Change directory to the AssetTracker

$ cd AssetTracker

Enter the following command to create an empty project with

$ truffle init

Check the directory structure:

$tree

Truffle created a contracts folder; this is where we will keep smart contracts for our application.

migrations folder store scripts to deploy smart contracts.

7
test folder consists of unit tests.

truffle-config.js to application configuration.

We will use this as a base template and start building an AssetTracker application on top of this.

Web3.js - Ethereum JavaScript API

web3.js is a collection of libraries that allows you to interact with a local or remote Ethereum
node, using an HTTP, WebSocket or IPC connection.

Installing web3.js

Web3.js can be installed through npm package manager. Enter the following command inside the
AssetTracker directory to install web3.

$ npm install web3

Creating participants contracts

There are multiple parties involved in vehicle transfer start from supplier to disposal. For this
sample, we have identified four players/participants namely:

Manufacturer - Producer of the vehicle asset

Shipper - Ships vehicle asset to the dealers

Dealer – Sells the vehicle to a consumer

Buyer - Buys from seller

We need to track a few details of these participants and transactions into the blockchain. We will
write a smart contract to track assets.

Creating a manufacturer contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

8
contract Manufacturer {
struct Vehicle {
string vin;
string model;
address manufacturerAddress;
}

mapping(string => Vehicle) public vehicles;

event VehicleRegistered(string vin, string model, address


manufacturerAddress);

function registerVehicle(string memory _vin, string memory _model)


public {
require(bytes(vehicles[_vin].vin).length == 0, "Vehicle already
registered");
vehicles[_vin] = Vehicle(_vin, _model, msg.sender);
emit VehicleRegistered(_vin, _model, msg.sender);
}

function getVehicle(string memory _vin) public view returns (string


memory, string memory, address) {
Vehicle memory vehicle = vehicles[_vin];
return (vehicle.vin, vehicle.model, vehicle.manufacturerAddress);
}
}

Our first contract will be for the manufacturer, which will store the manufacturer name, account
address, and location onto the blockchain. If you want to track more attributes (QRCode, and so
on.) you can add them, but for now, let us stick to three properties for simplicity. Now, will
create a new file called Manufacturer.sol under contracts folder by adding the following code:

pragma solidity >=0.4.25 <0.6.0;

contract Manufacturer

string public name;

address public manufacturer_address;

string public location;

9
constructor (string memory manufacturerName, address

manufacturerAddress,

string memory manufacturerLocation) public {

name = manufacturerName;

manufacturer_address = manufacturerAddress;

location = manufacturerLocation;

Here we are creating a contract called There are three public properties namely, the location, and
a constructor that will be executed while initiating this contract.

Creating a shipper contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Shipper {
struct Shipment {
string vin;
address shipperAddress;
string status;
}

mapping(string => Shipment) public shipments;

event ShipmentCreated(string vin, address shipperAddress, string


status);

function createShipment(string memory _vin, string memory _status)


public {
shipments[_vin] = Shipment(_vin, msg.sender, _status);
emit ShipmentCreated(_vin, msg.sender, _status);
}

function getShipment(string memory _vin) public view returns (string


memory, address, string memory) {
Shipment memory shipment = shipments[_vin];
return (shipment.vin, shipment.shipperAddress, shipment.status);
}

10
}

Our second contract will be for Shipper - which stores shipper name, shipper account address,
and shipper location onto the blockchain. This can be done by creating a new file called
Shipper.sol under the contracts folder, and adding the following code:

pragma solidity >=0.4.25 <0.6.0;

contract Shipper

string public name;

address public shipper_address;

string public location;

constructor (string memory shipperName, address shipperAddress,

string memory shipperLocation) public {

name = shipperName;

shipper_address = shipperAddress;

location = shipperLocation;

Here we are creating a contract called. There are three public properties name, the location, and a
constructor, which will be executed while initiating this contract.

Create a dealer contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Dealer {
struct Sale {
string vin;
address buyerAddress;
address dealerAddress;
bool completed;
}

11
mapping(string => Sale) public sales;

event VehicleSold(string vin, address buyerAddress, address


dealerAddress);

function sellVehicle(string memory _vin, address _buyerAddress)


public {
require(sales[_vin].dealerAddress == address(0), "Vehicle already
sold");
sales[_vin] = Sale(_vin, _buyerAddress, msg.sender, false);
emit VehicleSold(_vin, _buyerAddress, msg.sender);
}

function completeSale(string memory _vin) public {


require(msg.sender == sales[_vin].dealerAddress, "Only dealer can
complete sale");
sales[_vin].completed = true;
}

function getSale(string memory _vin) public view returns (string


memory, address, address, bool) {
Sale memory sale = sales[_vin];
return (sale.vin, sale.buyerAddress, sale.dealerAddress,
sale.completed);
}
}

Our third contract will be for Dealer that stores the dealer name, dealer account address, and the
dealer location onto the blockchain. To get started, create a new file called Dealer.sol under

the contracts folder and add the following code:

pragma solidity >=0.4.25 <0.6.0;

contract Dealer

string public name;

address public dealer_address;

string public location;

12
constructor (string memory dealerName, address dealerAddress,

string memory dealerLocation) public

name = dealerName;

dealer_address = dealerAddress;

location = dealerLocation;

Here we are creating a contract called. There are three public properties name, location, and a
constructor, which will be executed while initiating this contract.

Create a buyer contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Buyer {
struct Purchase {
string vin;
address buyerAddress;
address dealerAddress;
bool confirmed;
}

mapping(string => Purchase) public purchases;

event PurchaseConfirmed(string vin, address buyerAddress, address


dealerAddress);

function confirmPurchase(string memory _vin, address _dealerAddress)


public {
purchases[_vin] = Purchase(_vin, msg.sender, _dealerAddress,
true);
emit PurchaseConfirmed(_vin, msg.sender, _dealerAddress);
}

13
function getPurchase(string memory _vin) public view returns (string
memory, address, address, bool) {
Purchase memory purchase = purchases[_vin];
return (purchase.vin, purchase.buyerAddress,
purchase.dealerAddress, purchase.confirmed);
}
}

Our fourth contract will be for which stores buyer name, buyer account address, and buyer
location onto the blockchain. This can be done by creating a new file called Buyer.sol under the
contracts folder adding the following code:

pragma solidity >=0.4.25 <0.6.0;

contract Buyer

string public name;

address public buyer_address;

string public location;

constructor(string memory buyerName, address buyerAddress,

string memory buyerLocation) public

name = buyerName;

buyer_address = buyerAddress;

location = buyerLocation;

Here we are creating a contract called three public properties name, location, and a constructor,
which will be executed while initiating this contract.

Compiling the contracts

14
Migration file

const Manufacturer = artifacts.require("Manufacturer");


const Shipper = artifacts.require("Shipper");
const Dealer = artifacts.require("Dealer");
const Buyer = artifacts.require("Buyer");

module.exports = function (deployer) {


deployer.deploy(Manufacturer);
deployer.deploy(Shipper);
deployer.deploy(Dealer);
deployer.deploy(Buyer);
};

Migrating the contracts (after properly configuring the truffle-config.js file)

15
16
Various contract address as obtained on the terminal running Ganache

Writing the web3 script with basic HTML interface to interact with the contracts

<!DOCTYPE html>
<html>
<head>
<title>Vehicle Asset Management</title>

17
<script
src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.6.1/web3.min.js"></
script>
<script>
let web3;
let manufacturerContract, shipperContract, dealerContract,
buyerContract;

const manufacturerAddress =
'0x1ebedd8c33153c36929e7e3d62c497613acc1377';
const shipperAddress =
'0xc440166cf786b74265a6dda493b8b57b3b93b232';
const dealerAddress =
'0x2bf340563985c2d413e55613c312681f7a77f79c';
const buyerAddress =
'0x73310b8a86d3fb24f5bb8d42f10b8d7a80fc3aa6';

const manufacturerAbi = [
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "string",
"name": "vin",
"type": "string"
},
{
"indexed": false,
"internalType": "string",
"name": "model",
"type": "string"
},
{
"indexed": false,
"internalType": "address",
"name": "manufacturerAddress",
"type": "address"
}
],
"name": "VehicleRegistered",
"type": "event"
}
];
const shipperAbi = [ {

18
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "string",
"name": "vin",
"type": "string"
},
{
"indexed": false,
"internalType": "address",
"name": "shipperAddress",
"type": "address"
},
{
"indexed": false,
"internalType": "string",
"name": "status",
"type": "string"
}
],
"name": "ShipmentCreated",
"type": "event"
} ];
const dealerAbi = [ {
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "string",
"name": "vin",
"type": "string"
},
{
"indexed": false,
"internalType": "address",
"name": "buyerAddress",
"type": "address"
},
{
"indexed": false,
"internalType": "address",
"name": "dealerAddress",
"type": "address"
}

19
],
"name": "VehicleSold",
"type": "event"
} ];
const buyerAbi = [ {
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "string",
"name": "vin",
"type": "string"
},
{
"indexed": false,
"internalType": "address",
"name": "buyerAddress",
"type": "address"
},
{
"indexed": false,
"internalType": "address",
"name": "dealerAddress",
"type": "address"
}
],
"name": "PurchaseConfirmed",
"type": "event"
} ];

window.onload = async () => {


if (window.ethereum) {
web3 = new Web3(window.ethereum);
await window.ethereum.enable(); // Request account access

manufacturerContract = new
web3.eth.Contract(manufacturerAbi, manufacturerAddress);
shipperContract = new web3.eth.Contract(shipperAbi,
shipperAddress);
dealerContract = new web3.eth.Contract(dealerAbi,
dealerAddress);
buyerContract = new web3.eth.Contract(buyerAbi,
buyerAddress);
}
};

20
async function registerVehicle() {
const vin = document.getElementById('vin').value;
const model = document.getElementById('model').value;

const accounts = await web3.eth.getAccounts();


await manufacturerContract.methods.registerVehicle(vin,
model).send({ from: accounts[0] });
}

async function createShipment() {


const vin = document.getElementById('shipmentVin').value;
const status = document.getElementById('status').value;

const accounts = await web3.eth.getAccounts();


await shipperContract.methods.createShipment(vin,
status).send({ from: accounts[0] });
}

async function sellVehicle() {


const vin = document.getElementById('saleVin').value;
const buyerAddress =
document.getElementById('buyerAddress').value;

const accounts = await web3.eth.getAccounts();


await dealerContract.methods.sellVehicle(vin,
buyerAddress).send({ from: accounts[0] });
}

async function confirmPurchase() {


const vin = document.getElementById('purchaseVin').value;
const dealerAddress =
document.getElementById('dealerAddress').value;

const accounts = await web3.eth.getAccounts();


await buyerContract.methods.confirmPurchase(vin,
dealerAddress).send({ from: accounts[0] });
}
</script>
</head>
<body>
<h1>Vehicle Asset Management</h1>

<h2>Register Vehicle</h2>
<input type="text" id="vin" placeholder="VIN" />

21
<input type="text" id="model" placeholder="Model" />
<button onclick="registerVehicle()">Register Vehicle</button>

<h2>Create Shipment</h2>
<input type="text" id="shipmentVin" placeholder="VIN" />
<input type="text" id="status" placeholder="Status" />
<button onclick="createShipment()">Create Shipment</button>

<h2>Sell Vehicle</h2>
<input type="text" id="saleVin" placeholder="VIN" />
<input type="text" id="buyerAddress" placeholder="Buyer Address" />
<button onclick="sellVehicle()">Sell Vehicle</button>

<h2> </h2>
</body>
</html>

Connecting with MetaMask to simulate transactions

22
Interacting with the contracts through the interface-

Registering a new vehicle on the system (Would be initiated by a Manufacturer)

Confirming the transaction request on MetaMask

23
Transaction as seen on Ganache terminal

Acknowledgement as received

24
Initiating a shipment process (Maintained by Shipper entity)

25
Acknowledgement as received (along with the address of the Shipper entity)

Selling a vehicle (Initiated by the Dealer, co-ordinated with the Buyer entity)

Acknowledgement as received

26
Conclusion:

By performing this experiment, I was able to improve my understanding of smart contracts and
their respective compilation and deployment on a blockchain network. I was able to develop a
better intuition on how various contracts may be deployed together on a blockchain and how one
may interact with all the contracts in the required fashion. I was able to successfully implement
the task of Asset tracking through a decentralized process, integrating with MetaMask to
simulate transactions. I was able to interact with the created system through a simple HTML
interface and confirm its proper functioning.

References:

[1] Chapter 5 ERC-721 Non Fungible Tokens

https://www.oreilly.com/library/view/getting-started-with/9781484280454/html/
521550_1_En_5_Chapter.xhtml

[2] Mastering Blockchain Technology by Imran Bashir 4th Edition Chapter 11,12 and 13,Packt
Publications

[3] Web3.js and Blockchain Resources

https://web3.career/learn-web3

[4] Building Enterprise Blockchain Solutions on AWS by Murughan Palaniachari

https://rebrand.ly/b222d7

27

You might also like