Over a million developers have joined DZone.

How the Existing Architecture of Your App Can Be Transferred to Blockchain

DZone 's Guide to

How the Existing Architecture of Your App Can Be Transferred to Blockchain

In this post, a developer explains a project he is working on that is based on Ethereum's blockchain and smart contracts and provides some Solidity code to get started.

· Security Zone ·
Free Resource

I would like to note that this article is not about how to write code in Solidity, but how the existing classical architecture of your application can be transferred to the blockchain and how you can think in the key of decentralization.

A couple of years ago, I was working on an interesting web application that offered a p2p delivery service for parcels. For some reason, the development had to be frozen at the prototype stage, so I just put the source code on GitHub and forgot about it.

Recently, I have been working on several projects related to cryptocurrency and blockchain technology. Having become acquainted with Ethereum and its concept of decentralized applications (DApps), I became infatuated with this idea: no censorship, no one can confiscate your funds, you can not just take and shut down the server your application is running on. At some point, I came to the conclusion that it is in such an environment that my project could have a chance to live.

So, let's look at the work.

The original idea of the project was that people who travel often could deliver packages once they arrived at their destination, thus acting as courier service. A sort of Uber for delivery. Users were divided into travelers (Donkeys) and customers. If you are going to go, say, from Moscow to Minsk this weekend, you can add the service to a new trip (trip) with a description of what you can transport and when. Customers subscribed to this area received a notification of a new trip and could add shipping requests, such as some medications or an iPad for their mother. The parties agreed to the payment amount (self-signed escrow on PayPal) and terms of delivery. After executing the order, the parties could leave ratings and comments about each other. Each user profile had a small statistic.

Over time, I started rethinking some of the points in the algorithm of the service. It became clear that it would be correct if, initially, customers added their orders for transportation, and the Donkeys would already choose which package they wanted to deliver (much like how Uber drivers can pick their fares). Next, you will see how this concept provides flexibility and scalability.

The application will be absolutely open, immutable, decentralized, and, therefore, free of regulation, even by the developer himself. Thus, we will get a decentralized platform on the basis of which any person can implement their front-end, mobile, or server-side application.

The protocol for the operation of such a service in a short form will be as follows:

  • The customer adds an order for transportation from point A to point B.

  • A Donkey may add a Service Offer.

  • The customer can add a Reply to the Offer.

  • The Donkey will issue an invoice for payment of the order indicating the amount of the prepayment and deposit.

  • The customer pays the account and can install the key to withdrawing the deposit.

  • The Donkey fulfills the order and receives the key to withdrawing the deposit (QR code for example).

  • A Donkey, at any time, can refund the money to the Client.

  • Donkeys and Clients exchange ratings.

    This protocol will be implemented by a smart contract written in Solidity, which we will call Osliki. To start, we'll set up variables for storing orders, offers, invoices, and statistics:

Order [] public orders; // orders
Offer [] public offers; // suggestions (immediately there will be stored and answers from clients)
Invoice [] public invoices; // Accounts
mapping (address => Stat) internal stats; // mapping the user's address to his statistics

Description of All Structures:

struct Order {
    address customer; // client ethereum-address
    string from; // geo coordinates in the format "lat, lon" or ethereum-address "0x ..." (for example, the address belonging to the store, restaurant, farm or private person) or just empty value (for example, if it is important that they bring, not from where)
    string to; // same as previous
    string params; // parcel parameters in the format "weight (kg), length (m), width (m), height (m)"
    uint expires; // expiration date, Unix-time in seconds
    string message; // just plain text in free form

    uint [] offerIds; // array of id suggestions

    address carrier; // ethereum-address of the selected donkey for execution of the order
    uint invoiceId; // paid paid account

    EnumOrderStatus status; // order status
    uint createdAt; // date of creation
    uint updatedAt; // Date of change

struct Offer {
    address carrier; // ethereum-address of the donkey
    uint orderId; // order id
    string message; // the text of the sentence in free form
    string respond; // the text of the response from the client in free form.
    uint createdAt;
    uint updatedAt;

struct Invoice {
    address sender; // ethereum-address of the donkey
    uint orderId; // order id
    uint prepayment; // amount for prepayment (can be 0)
    uint deposit; // amount for the deposit (can be 0)
    uint expires; // expiration date of the invoice
    EnumCurrency currency; // the currency in which the account is billed
    bytes32 depositHash; // hash Ethereum-SHA-3 (Keccak-256) of the deposit key (set by the client at the moment of payment of the account)
    EnumInvoiceStatus status; // account status
    uint createdAt;
    uint updatedAt;

struct Stat {
    uint [] orders; // array of id orders in which the user participated as a client or a donkey
    uint rateSum; // sum of estimates
    uint rateCount; // the number of evaluations, the average score averageRate = rateSum / rateCount
    mapping (uint => Review) reviews; // Map the order id to the review and evaluation of this order

struct Review {
    uint8 rate; // score between 1 and 5
    string text; // the text of the response
    uint createdAt;


enum EnumOrderStatus {New, Process, Fulfilled}
enum EnumInvoiceStatus {New, Settled, Closed, Refund}
enum EnumCurrency {ETH, OSLIK} // pay bills on air (1% commission) or in your own internal OSLIK tokens (no commission)

Next, I will not discuss the functions in detail, as this would take too much time. At the bottom of the article, you can find a link to the source code on GitHub.

The customer adds the order:

function addOrder (
     string from, // "" || "lat, lon" || ethereum-address "0x ..."
     string to, // "" || "lat, lon" || ethereum-address "0x ..."
     string params, // "weight (kg), length (m), width (m), height (m)"
     uint expires,
     string message
) public;

Now, adding a proposal:

function addOffer (
     uint orderId,
     string message
) public;

The client sends a reply:

function respond (
     uint offerId,
     string message
) public; // only one response to a sentence

The Donkey sends a blockchain-based account to which their payment can be sent:

function addInvoice (
     uint orderId,
     uint prepayment,
     uint deposit,
     EnumCurrency currency, // ETH || OSLIKI
     uint expires
) public;

The customer pays the bill:

function pay (
     uint invoiceId,
     bytes32 depositHash // the client sends the hash of the keccak256 key for access to the deposit, it can be empty if there is no deposit and all funds are paid in advance
) public payable; // after payment, the account is attached to the order and the sender of the account is considered to be selected as the contractor

The Donkey fulfills the order. For example, during delivery, the Donkey scans the QR code from the Customer, in which the Deposit Key is sewn:

function fulfill (
     uint orderId,
     string depositKey // the key is hashed and compared with depositHash, it can be empty if there was no deposit, in this case simply the status of the order will be changed to 'Completed'
) public;

After that, the Donkey can return the funds to the Customer if the latter is not happy or something has gone wrong in the process:

function refund (
     uint invoiceId
) public payable;

Parties can add feedback about each other with an estimate of the impression of the order:

function addReview (
     uint orderId,
     uint8 rate,
     string text
) public; // immediately update the statistics

Plus, there is also a bunch of functions for accessing data. As a result, we have 2 contracts:

  1. The Osliki contract, which implements our protocol and is the core of the platform for building any business-related or dependent on delivery.

  2. The home currency token OSLIK, which can be used for payment without commission. Tokens can be sold within crowdfunding and raise funds for the development and promotion of the platform and services built on this platform.

In fact, the Osliki contract is an open database of delivery orders, which any individual, organization or some drone can use, such as Amazon Prime Air.

Imagine an entrepreneur with a fleet of cargo drones, based on the roof of a building in your city. Drones monitor the database in the block room and if the order corresponds to some specific parameters (for example, an acceptable range and cargo dimensions), they automatically send out offers and bills and then fly to execute orders.

  • Imagine Mr. X with Craigslist. He throws you a link where you can add an order to Osliki with the ethereal addresses of Mr. X directly so that other Donkeys do not spam the offers. Further, the bill, payment, and, here, the parcel, are already in your hands. And even if the account of Mr. X is blocked in Craiglist, fans of his will always remember where to send orders.

You can imagine a marketplace where farmers sell their biological, "just from the bed" vegetables without GMOs, fresh milk, and meat. Delivery can be carried out, for example, by drivers traveling from suburb to city. Farmers will thus have unrestricted access to retail customers bypassing supermarkets.

Well, the original idea with travelers carrying parcels between cities and countries also remains relevant.

As part of the platform, the same decentralized marketplace (Osliki Marketplace) or message board (Osliki Classifieds) would fit in here. Or, perhaps, use ready-made solutions.

Using the methods of Big Data and AI, you can more deeply analyze the behavior and statistics of each user and give out the results of their trustworthiness. For example, you can identify users who have earned a rating.

At the moment, the task is to implement the front-end application, osliki-js (as one of the implementation versions) on some GitHub pages so that you can work with contracts in the usual way in the browser. Plus a set of widgets for embedding it on sites. If the topic seemed interesting to you, join the development.

Links to the source code on GitHub:

The contracts are currently closed in the Ethereum Ropsten test network. To test it out, you can get here.

Addresses of Contracts:

Osliki 0xa5AF61cE7deEb042e7Ad6A2118b183D3733E1D99

ERC20-compatible token OSLIK 0x7ee36e1ddac343649edaa622f9bb067ed74545b2

cryptocurrencies ,blockchain ,security ,blockchain app development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}