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.

Part 2 of this article is about “Creating a Private Network in Ethereum

Overview and Objective

Ethereum is a decentralized, open-source blockchain with smart contract
functionality. Ether is the native cryptocurrency of the platform. Among
cryptocurrencies, ether is second only to bitcoin in market capitalization.

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.

Produce an Ethereum based dApp that has both the smart contract tested
and deployed in a testnet and a front end that will allow monitoring of the
status.

Understanding of the Ethereum Blockchain

The Ethereum blockchain is essentially a transaction-based state machine. In computer science, a state machine refers to something that will read a series of inputs and, based on those inputs, will transition to a new state.

With Ethereum’s state machine, we begin with a “genesis state.” This is
analogous to a blank slate before any transactions have happened on the
network. When transactions are executed, this genesis state transitions into some final state. At any point in time, this final state represents the current state of Ethereum.

Gas and payment

  • One very important concept in Ethereum is the concept of fees.
    Every computation that occurs as a result of a transaction on the
    Ethereum network incurs a fee — there’s no free lunch! This fee is
    paid in a denomination called “gas.”
  • Gas is the unit used to measure the fees required for a particular
    computation. Gas price is the amount of Ether you are willing to
    spend on every unit of gas, and is measured in “gwei.” “Wei” is the
    smallest unit of Ether, where 1018 Wei represents 1 Ether. One gwei
    is 1,000,000,000 Wei.
  • With every transaction, a sender sets a gas limit and gas price.
    The product of gas price and gas limit represents the maximum
    amount of Wei that the sender is willing to pay for executing a
    transaction.

Transaction and messages

  • We noted earlier that Ethereum is a transaction-based state
    machine. In other words, transactions occurring between different
    accounts are what move the global state of Ethereum from one
    state to the next.
  • In the most basic sense, a transaction is a cryptographically
    signed piece of instruction that is generated by an externally
    owned account, serialized, and then submitted to the blockchain.
  • There are two types of transactions: message calls and contract
    creations (i.e. transactions that create new Ethereum contracts).

Blocks

  • All transactions are grouped together into “blocks.” A blockchain
    contains a series of such blocks that are chained together.

In Ethereum, a block consists of:

  • The block header
  • Information about the set of transactions included in that
    block
  • A set of other block headers for the current block’s ommers(Ommer blocks are created in the Ethereum blockchain when two blocks are created and submitted to the ledger at roughly the same time).

Ethereum networks

Networks are different Ethereum environments you can access for development, testing, or production use cases. Since Ethereum is a protocol, there can be multiple independent “networks” that conform to the protocol without interacting with each other.

Ethereum Mainnet

  • Mainnet is the primary public Ethereum production blockchain, where
    actual-value transactions occur on the distributed ledger.
  • When people and exchanges discuss ETH prices, they’re talking about
    Mainnet ETH.

Ethereum Testnets

  • In addition to Mainnet, there are public testnets. These are networks
    used by protocol developers or smart contract developers to test both
    protocol upgrades as well as potential smart contracts in a
    production-like environment before deployment to Mainnet. Think of
    this is an analog to production versus staging servers.
  • Goerli: Goerli is a proof-of-stake testnet. It is expected to be maintained
    long-term as a stable testnet for application developers. Before its
    testnet merge, Goerli was a proof-of-authority testnet.
  • Sepolia: Sepolia is a proof-of-stake testnet. Although Sepolia is still
    running, it is not currently planned to be maintained long-term.
    Before undergoing The Merge in June 2022, Sepolia was a
    proof-of-work testnet.

Consortium networks

  • The consensus process is controlled by a pre-defined set of nodes that
    are trusted. For example, a private network of known academic
    institutions that each govern a single node, and blocks are validated by
    a threshold of signatories within the network.
  • If a public Ethereum network is like the public internet, a consortium
    network is like a private intranet.

How smart contracts are designed

Smart contracts are self-executing digital contracts that define the terms of a blockchain transaction using code. This code makes it possible to, among
other things, exchange massive amounts of money within set input
parameters. Smart contracts are written with a variety of coding languages,
and the most popular one is Solidity.

Smart contract design patterns

Smart contract design patterns are reusable, repeatable solutions in writing code. They can serve a wide range of purposes but can be seen as offering four main functions:

  • Security patterns — To protect your contract against breaches.
  • Efficiency patterns — To reduce the cost of executing your contract.
  • Access control patterns — To manage who can execute the functions of
    your contract.
  • Contract management patterns — To organize your contracts and how
    they interact.

While these categories capture the main functions of all smart contract
patterns, it’s important to note that patterns are used across all blockchains, on and off-chain, in domain-based chains, and in data management.

For example, say you want to build a smart contract that will have a few
evolutions during its life cycle. You might use something called a state machine pattern, which falls under the multi-domain feature pattern. A state machine pattern allows you to manage smart contract transitions through different “state” transitions over time. This pattern is used in many scenarios, including your basic smart contract implementation, so we highlight it here.

Just keep in mind that we’re focusing here on the functions of various smart contract design patterns in the wider blockchain ecosystem.

Ethereum Virtual Machine(EVM)

The part of the protocol that actually handles processing the transactions is
Ethereum’s own virtual machine, known as the Ethereum Virtual Machine
(EVM).

The EVM is a Turing complete virtual machine, as defined earlier. The only
limitation the EVM has that a typical Turing complete machine does not is that the EVM is intrinsically bound by gas. Thus, the total amount of computation that can be done is intrinsically limited by the amount of gas provided.

Moreover, the EVM has a stack-based architecture. A stack machine is a
computer that uses a last-in, first-out stack to hold temporary values.

The size of each stack item in the EVM is 256-bit, and the stack has a
maximum size of 1024.

The EVM has memory, where items are stored as word-addressed byte arrays. Memory is volatile, meaning it is not permanent.

The EVM also has storage. Unlike memory, storage is non-volatile and is
maintained as part of the system state. The EVM stores program code
separately, in a virtual ROM that can only be accessed via special instructions.

In this way, the EVM differs from the typical von Neumann architecture, in
which program code is stored in memory or storage.

Smart contract security

Security is one of the most important considerations when writing smart
contracts. In the field of smart contract programming, mistakes are costly and easily exploited.

As with other programs, a smart contract will execute exactly what is written, which is not always what the programmer intended. Furthermore, all smart contracts are public, and any user can interact with them simply by creating a transaction. Any vulnerability can be exploited, and losses are almost always impossible to recover. It is therefore critical to follow best practices and use well-tested design patterns.

Security patterns are designed to maximize the level of security of a smart
contract against any risk. They are used to ward off reentrancy attacks,
overflow attacks, or the flawed behavior of the actual smart contracts.

These patterns might have a built-in panic button, such as the emergency
stop pattern, which gives the option to disable contract functionality if
necessary. Or a pattern might use rate limiters to control how often a task can be executed within a specified period. The check effect interaction pattern minimizes potential attack surfaces to reduce the risk of malicious contracts taking over.

Other examples of security design patterns are:

  1. Balance limit pattern
  2. Pull-over push payments
  3. Secure ether transfer
  4. Balance limit pattern
  5. Pull-over push payments
  6. Secure ether transfer
  7. Fork check
  8. Termination
  9. Math pattern
  10. Time constraint
  11. Mutex pattern
  12. Auto deprecation design pattern
  13. Withdrawal pattern

Tools used in the project

React JS for the web dApp

React is a library for building composable user interfaces. It encourages the creation of reusable UI components, which present data that changes over time. Lots of people use React as the V in MVC.
React abstracts away the DOM from you, offering a simpler programming model and better performance

Flutter for the mobile dApp

Flutter is an open-source UI software development kit created by Google. It is used to develop cross-platform applications for Android, iOS, Linux, macOS, Windows, Google Fuchsia, and the web from a single codebase. First described in 2015, Flutter was released in May 2017.

Solidity for Contract’s programing language

Solidity is an object-oriented programming language for implementing smart contracts on various blockchain platforms, most notably, Ethereum.

Web3.js for interacting with the contracts from UI

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

Truffle to deploy, test, and compile our contracts

The Truffle Suite is an ecosystem for Web3 development that consists of three different tools: Truffle, Ganache, and Drizzle. Truffle is a development environment, asset pipeline, and testing framework for developing smart contracts.

Metamask for linking accounts to perform transactions

MetaMask is a software cryptocurrency wallet used to interact with the Ethereum blockchain. It allows users to access their Ethereum wallet through a browser extension or mobile app, which can then be used to interact with decentralized applications.

Ganache for creating Ethereum blockchain on the local machine

Ganache is a pioneer in the Ethereum development space, aiding DApp developers and enthusiasts to build, test, and explore blockchain since 2016.

Setup and Installation

Project Implementation

Writing the Smart Contract

refund.sol
  • We will start by creating the Employee init_employee and the Employer init_employer.
function init_employee(string memory _name, address a)function init_employer(string memory _name, address a)
  • We will then create the contract create_contract.
function create_contract(address _employer_address, address _employee_address, uint[2] memory lat, uint[2] memory lng, uint radius)
  • We will then store records of the employee’s location create_employee_location_info
function create_employee_location_info(uint contract_id, address _employee_address, uint[2] memory _lat, uint[2] memory _lng, string memory _timestamp, bool _status, uint _distance)
  • truffle-config.js
//truffle-config.js
require('dotenv').config();
const HDWalletProvider = require('@truffle/hdwallet-provider');
const { INFURA_API_KEY, MNEMONIC } = process.env;
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*"
},
goerli: {
provider: () => new HDWalletProvider(MNEMONIC, INFURA_API_KEY),
network_id: '5',
gas: 4465030
}
}
};
  • Deploy the contract to ganache
$ truffle deploy --network development

Creating the Employer’s page

  • Create a Provider React component that allows consuming components to subscribe to context changes.
  • Create employee using
//AddEmployee.jsconst { state: { contract, accounts } } = useEth();contract.methods.init_employee(employeeName, employeeAddress).send({ from: accounts[0] });
  • Create contract using

const { state: { contract, accounts } } = useEth();
contract.methods.create_contract(accounts[0], employeeAddress, [l,latindex], [lg, lngindex], radius).send({ from: accounts[0] })

More functionalities are found in the below link

Creating the Employee page using flutter

  • Connect to the contract and fetch all needed functions.
Future<void> getDeployedContract() async {
// Telling Web3dart where our contract is declared.
_contract = DeployedContract(
ContractAbi.fromJson(_abi!, "RefundByLocation"), _contractAddress!);
// Extracting the functions, declared in contract.
_writeName = _contract!.function("employercount");
_getEmployeeCount = _contract!.function("employercount");
_getContractCount = _contract!.function("contract_info_count");
_getContract = _contract!.function("contract_infos");
_getEmployeeLocationCount =
_contract!.function("employee_location_infos_count");
_getEmployeeLocation = _contract!.function("employee_location_infos");
_sendEmployeeLocation =
_contract!.function("create_employee_location_info");
// getValue();
print("############GETTING CONTRACT###########");
print(_contractAddress);
print("############GETTING CONTRACT###########");
}
  • Full source code for connecting to contract and calling smart contract functions.
  • Link to full flutter app.

--

--

Natnael Melese

A Computer Programmer and an aspiring Machine Learning Engineer. My interests include programming, mathematics, AI research, and theoretical computer science.