Refund by Location Smart Contract—Web3.0

Abel Mitiku
10 min readJul 12, 2022

--

Introduction

A program or application stored and run on the blockchain network is referred to as a decentralized application (dApp).

Decentralized Location Tracking Application (dApp GPS Tracker) is a class of software that tracks the user’s location. This application’s primary goal is to set up a safe location tracking mechanism between an employee and an employer.

The refund by location smart contract is aimed to be used when one party, for example, an employer, agrees to pay another party, for example, an employee, for being present in a certain geographic area for a certain duration. The employee’s phone sends its GPS location to a smart contract at a certain interval. Based on the pre-agreed contract codified in an Ethereum smart contract, a cryptocurrency payment is executed when all the agreed conditions are met.

If at any point, the GPS sensor indicates that an employee is outside the range of the agreed GPS area, the contract state will be updated to indicate that it is out of compliance.

Although numerous similar programs have these functions, they are all under the jurisdiction of one central organization, which has complete control over all data. Users’ data is no longer secure if the central authority is compromised or fails, and there is a possibility that data will be deleted. This dApp leverages blockchain in the backend to overcome this problem. Blockchain is a distributed ledger, and using it has several benefits over using a centralized organization. Blockchain guarantees that data is easily accessible across numerous nodes, that data is impervious to tampering, and that users retain control over the program.

Because the user trusts this central authority, if it is compromised, all of the data on its servers and the data that passes through them will also be compromised (lost, leaked, or otherwise altered), jeopardizing the user’s security. To solve these problems, this application uses blockchain as its backend. A distributed ledger that cannot be changed is the blockchain. Each node in the peer-to-peer network that makes up the blockchain duplicates the data that is stored there. Thus, it is impossible to alter or erase the data. Furthermore, the data kept in the blockchain can be saved as ciphertext and can only be decoded with the use of a secret key when used in conjunction with various encryption techniques.

Blockchain

A blockchain is a distributed, peer-to-peer database that hosts a continuously growing number of transactions. Each transaction, referred to as a “block,” is secured through cryptography, timestamped, and validated by every authorized member of the database using consensus algorithms (i.e., a set of rules). A transaction that is not validated by all members of the database is not added to the database. Every transaction is attached to the previous transaction in sequential order, creating a chain of transactions (or blocks). A transaction cannot be deleted or edited, thereby creating an immutable audit trial. A transaction can only be changed by adding another transaction to the chain.

To cause a transition from one state to the next, a transaction must be valid. For a transaction to be considered valid, it must go through a validation process known as mining. Mining is when a group of nodes (i.e. computers) expend their compute resources to create a block of valid transactions.

Transactions Process

The actions used to guarantee a successful transaction are as follows:

  1. In order to send a specific cryptocurrency or token from themselves to another person, a user must first approve a transaction from their wallet application.
  2. The wallet application has broadcasted the transaction, which is currently waiting for a miner to pick it up on the relevant blockchain. It floats in a “pool of unconfirmed transactions” until it is picked up.
  3. In order to create a “block,” network miners choose transactions from these pools. A block is essentially a collection of transactions, some additional metadata, and unconfirmed transactions at this time. Each miner creates a unique block of transactions. The same transactions can be chosen by multiple miners to be included in their block.
  4. Miners assemble a block of transactions by choosing certain transactions and including them in it. The block must first have a signature, also known as a “proof of work,” in order to be added to the blockchain. Each block of transactions has its own unique mathematical problem that must be solved in order to produce this signature.
  5. The miner that finds an eligible signature for its block first, broadcasts this block and its signature to all the other miners.
  6. Other miners now verify the signature’s legitimacy by taking the string of data of the broadcasted block.
  7. If it is valid, the other miners will confirm its validity and agree that the block can be added to the blockchain. This is also where the definition ‘proof of work’ comes from. The signature is the ‘proof’ of the work performed (the computational power that was spent). The block can now be added to the blockchain and is distributed to all other nodes on the network.
  8. After a block has been added to the chain, every other block that is added on top of it counts as a ‘confirmation’ for that block. After a new block is added to the blockchain, all miners need to start over again at step three by forming a new block of transactions.

Accounts

Accounts that makeup Ethereum’s global “shared-state” are connected to one another using a message-passing system. Each account has a 20-byte address and a state that go with it. A 160-bit identifier known as an address is used to identify any account in the Ethereum network.

There are two types of accounts:

  • Externally owned accounts, which are controlled by private keys and have no code associated with them.
  • Contract accounts, which are controlled by their contract code and have code associated with them.

Ethereum Blockchain

Ethereum is a technology for building apps and organizations, holding assets, transacting, and communicating without being controlled by a central authority. There is no need to hand over all your personal details to use Ethereum — you keep control of your own data and what is being shared. Ethereum has its own cryptocurrency, Ether, which is used to pay for certain activities on the Ethereum network.

Ethereum (ETH) is the second most popular cryptocurrency after Bitcoin. Founded by Vitalik Buterin and Gavin Wood in 2015, today Ethereum’s market capitalization represents more than 17% of the $1.2 trillion global crypto market.

There are some distinct differences between Ethereum and the original crypto. Unlike Bitcoin (BTC), Ethereum is intended to be much more than just a medium of exchange or a store of value. Instead, Ethereum is a decentralized computing network built on blockchain technology.

Wallets

Ethereum wallets are applications that let you interact with your Ethereum account. Think of it like an internet banking app — without the bank. Your wallet lets you read your balance, send transactions and connect to applications.

Your wallet is only a tool for managing your Ethereum account. That means you can swap wallet providers at any time. Many wallets also let you manage several Ethereum accounts from one application.

That’s because wallets don’t have custody of your funds, you do. They’re just a tool for managing what’s really yours.

Ethereum has two types of accounts:

  • Externally Owned Accounts (EOA): These accounts are used by nodes to send or receive Ether. These accounts are associated with a private key. 9
  • Contract Accounts: These accounts hold and execute smart contract code. Unlike EOAs, contract accounts do not have a private key.

Smart Contract

A “smart contract” is simply a program that runs on the Ethereum blockchain. It’s a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain.

Smart contracts are a type of Ethereum account. This means they have a balance and they can send transactions over the network. However they’re not controlled by a user, instead, they are deployed to the network and run as programmed. User accounts can then interact with a smart contract by submitting transactions that execute a function defined on the smart contract. Smart contracts can define rules, like a regular contract, and automatically enforce them via the code. Smart contracts cannot be deleted by default, and interactions with them are irreversible.

MetaMask

MetaMask is a popular Ethereum wallet. Ether (ETH) or any ERC-20 token can be stored in this wallet. Using it, a user can send or receive Ether. A user can also link this wallet to their smart 10 contracts to pay fees associated while deploying smart contract and pay fees when adding new data into the blockchain.

Setting up MetaMask Wallet

To use MetaMask wallet:

  • Install MetaMask extension on the desired web browser.
  • Setup Account and Test network (in this project, Rinkeby test network is used)
  • Load funds into Rinkeby account address by using crypto faucets.

After the above process, the wallet is loaded

Deploying Smart Contract via Remix

Remix IDE is generally used to compile and run Solidity smart contracts. Below are the steps for the compilation, execution, and debugging of the smart contract.

Step 1: Open Remix IDE on any of your browsers, select on the New File and click on Solidity to choose the environment.

Step 2: Write the Smart contract in the code section, and click the Compile button under the Compiler window to compile the contract.

Step 3: To execute the code, click on the Deploy button under Deploy and Run Transactions window.

Step 4: After deploying the code click on the method calls under the drop-down of deployed contracts to run the program, and for output, check to click on the drop-down on the console.

Step 5: For debugging click on the Debug button corresponding to the method call in the console. Here you can check each function call and variable assignments.

pragma solidity ^0.5.16;

contract Project {
string[2] coordinates = ["0.00", "0.00"];

function sendCoordinates(string memory _latitude, string memory _longitude) public
{
coordinates[0] = _latitude;
coordinates[1] = _longitude;
}

function sendMny(address receiver, uint amount) public {
if (amount > balances[msg.sender])
revert InsufficientBalance({
requested: amount,
available: balances[msg.sender]
});

function readCoordinates() public view
returns (string memory, string memory)
{
return (coordinates[0], coordinates[1]);
}
}

After compiling and deploying the Smart Contract by approving transactions in MetaMask wallet, it will show up on our wallet activity status that the contract is deployed successfully.

##############################################################
# Connects the app to the smart contract functions
##############################################################

[
{
"constant": false,
"inputs": [
{
"internalType": "string",
"name": "_latitude",
"type": "string"
},
{
"internalType": "string",
"name": "_longitude",
"type": "string"
}
],
"name": "sendCoordinates",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "readCoordinates",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
},
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]

Infura

The mobile application (or dApp) is linked to the smart contract using the Infura API. It serves as a Gateway and manages all requests made to the smart contract. An account must be created in order to access the Infura API. To view the statistics of requests made to a smart contract, a project must first be built for this application.

##########################################################
#################### Employee Model ######################
##########################################################

employee() {
initiateSetup();
}
Future<void> initiateSetup() async {
_httpClient = Client();
_client = Web3Client(
"https://rinkeby.infura.io/v3/84ee596119e643cdb6e534c7c3674cfa",
_httpClient);
await getAbi();
await getCredentials();
await getDeployedContract();
}

Future<void> getAbi() async {
_abi = await rootBundle.loadString("../assets/abi.json");
_contractAddress = "0x4943030bce7e49dd13b4dd120c0fef7dde3c18a0";
}

Future<void> getCredentials() async {
_credentials = EthPrivateKey.fromHex(
"d585835f87981557df21fbaf99df4c9d06fd374b6efd121c027e0655cee5b627");
}

Future<void> getDeployedContract() async {
_contract = DeployedContract(ContractAbi.fromJson(_abi, "Project"),
EthereumAddress.fromHex(_contractAddress));
_readCoordinates = _contract.function("readCoordinates");
_sendCoordinates = _contract.function("sendCoordinates");
}

getCoordinates() async {
List readCoordinates = await _client
.call(contract: _contract, function: _readCoordinates, params: []);
x = readCoordinates[0];
y = readCoordinates[1];
}

addCoordinates(String lat, String lon) async {
latitude = EncryptionDecryption.encryptAES(lat);
longitude = EncryptionDecryption.encryptAES(lon);
await _client.sendTransaction(
_credentials,
Transaction.callContract(
contract: _contract,
function: _sendCoordinates,
parameters: [latitude, longitude],
maxGas: 100000,
),
chainId: 4,
);
getCoordinates();
isLoading = false;
notifyListeners();
}
}
##########################################################
#################### Employer Model ######################
##########################################################

Future<void> initiateSetup() async {
_httpClient = Client();
_client = Web3Client(
"https://rinkeby.infura.io/v3/84ee596119e643cdb6e534c7c3674cfa",
_httpClient);
await getAbi();
await getCredentials();
await getDeployedContract();
}

Future<void> getAbi() async {
_abi = await rootBundle.loadString("../assets/abi.json");
_contractAddress = "0x4943030bce7e49dd13b4dd120c0fef7dde3c18a0";
}

Future<void> getCredentials() async {
_credentials = EthPrivateKey.fromHex(
"d585835f87981557df21fbaf99df4c9d06fd374b6efd121c027e0655cee5b627");
}

Future<void> getDeployedContract() async {
_contract = DeployedContract(ContractAbi.fromJson(_abi, "Project"),
EthereumAddress.fromHex(_contractAddress));
_readCoordinates = _contract.function("readCoordinates");
}

getCoordinates() async {
initiateSetup();
List readCoordinates = await _client
.call(contract: _contract, function: _readCoordinates, params: []);
x = readCoordinates[0];
y = readCoordinates[1];
latitude = EncryptionDecryption.decryptAES(x);
longitude = EncryptionDecryption.decryptAES(y);
isLoading = false;
notifyListeners();
}
}

Flutter Mobile Application

After installing the application on the mobile device of the employee, the user interface will look as shown below.

Etherscan

Etherscan is a blockchain explorer for the Ethereum network. It allows the user to check, track, and view transactions, blocks, smart contracts, and other on-chain data.

The above image displays the transactions going through the MetaMask wallet’s account address. It shows the latest wallet balance, latest transactions, etc.

Etherscan transactions when “Track Location” is turned on:

The program is tested in real-time numerous times. It shows the location updates sent to the blockchain when the employee moved 100 meters inside the defined area.

--

--