Why are Smart Contracts so important

“A smart contract is a set of promises, specified in digital form, including protocols within which the parties perform on these promises.”
- Nick Szabo

Along with the blockchain technology, smart contracts are of intense interest to business. Despite of its early development they have been mostly existed in theory. Smart contract helps to solve the issue of mistrust between parties and business partners. Smart contracts have a number of benefits for a wide range of industries, reducing unnecessary costs and time expenditure while enhancing transparency.

What are smart contracts

The smart contracts are stored on blockchain. It is extremely difficult for the system to be corrupted as it would require enormous computing power to override the whole network which is not possible for everyone to achieve! Smart contract is a protocol intended to digitally facilitate, verify or enforce the negotiation of a contract. It also facilitates the credible transaction without the involvement of third party. After being first proposed by Nick Szabo who coined the term in 1994, smart contracts have recently caught the attention with various ERC standards coming forth, and numerous platforms facilitating a decentralised approach to run a code.
Some of the key properties of a smart contract are:
1. Autonomy
2. Decentralisation
3. Auto sufficiency

Autonomy means that after a smart contract launches the person who was the initiator of the transaction he does not have to participate any more in the process. It is a decentralised system so due to this property it does not require the presence of intermediates at the time of signing deals.

An example of a smart contract code. This is a Simple Escrow contract, written in solidity to be deployed on Ethereum blockchain, which does the same work as an escrow, dealing between a buyer and seller by introducing an arbiter.

pragma solidity ^0.4.19;

contract Escrow {

address public buyer;
address public seller;
address public arbiter;
address owner;

function Escrow(address _seller, address _arbiter) {
buyer = msg.sender;
seller = _seller;
arbiter = _arbiter;
}

modifier onlyOwner {
require(msg.sender == owner);
_;
}

function payoutToSeller() {
if(msg.sender == buyer || msg.sender == arbiter) {
seller.transfer(this.balance);
}
}

function refundToBuyer() {
if(msg.sender == seller || msg.sender == arbiter) {
buyer.transfer(this.balance);
}
}

function getBalance() constant returns (uint) {
return this.balance;
}

function setSeller(address _seller) public {
seller = _seller;
}

function setArbiter(address _arbiter) public {
arbiter = _arbiter;
}

function getSeller() public constant returns (address) {
return seller;
}

function getArbiter() public constant returns (address) {
return arbiter;
}

}

Uses of smart contracts

Even though, with such autonomous power, the possibilities are limitless, it’s mainly on how we choose to utilise them that defines the major use-cases of Smart Contracts. Some of such use-cases of smart contracts are listed below:

Insurance

Due to a lack of automated administration, it can take months for an insurance claim to be processed and paid. This is as problematic for insurance companies as it is for their customers, leading to admin costs, gluts, and inefficiency. Smart contracts can simplify the process by automatically triggering a claim when certain events occur. For example, if you are travelling and your car mets with an accident, the smart contract would recognise this and begin the claim . Specific details such as extent of damage, car number, location where the incident occurred could be recorded on the blockchain in order to determine exact amount of compensation.

Supply chain management

Supply chain management involves the flow of goods from raw material to finished product. Smart contracts can record ownership rights as items move through the supply chain, confirming who is responsible for the product at any given time

Protecting copyrighted content

Smart contracts can ensure that royalties go to the intended recipients by recording ownership rights in a decentralised blockchain system. A blockchain would keep track of all ownership rights.

Digital Identity

Smart contracts can allow individuals to own and control their digital identity containing data, reputation and digital assets.

Financial Data Recording

Financial organisations can utilise smart contracts for accurate, transparent financial data recording.

Mortgages

Smart contracts can automate mortgage contracts by automatically connecting the parties, providing for a frictionless and less error-prone process. The smart contract can automatically process payment and release liens from land records when the loan is paid.

Ethereum

Ethereum is a gold standard in the world of smart contracts and has the biggest capitalisation among other platforms. The majority of token sales happen on the Ethereum platform, using the ERC-20 token standard. There are various ERC standards and more are coming up as we speak.

The main language Ethereum smart contracts are written in is called Solidity. The first of it’s kind to provide Turing complete code running capability on a decentralised network, Ethereum changed the distributed network industry forever.

pragma solidity ^0.4.0;

contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public constant returns (uint) {
return storedData;
}
}

The link to documentation site can be found here

NEM

Scalability is the most critical thing about NEM’s decentralized application. While ETH does a maximum of 15 transactions per second, NEM reportedly manages hundreds of transactions per second. The NEM foundation has given security and availability a priority so entrepreneurs deal with other problems and not technical difficulties.While NEM is reportedly the faster, safer and easier technology, Ethereum provides a broader base for the creation of custom DApps.

Where Ethereum is targeting companies intend to rebuild internal networks in the next 5 to 10 years, NEM is targeting companies looking for a fast, secure, and ready to use and handle solution that’s current.

An example of NEM code is given below:

//Include the library
var nem require(".. ./build/index.js")

/ Create an NIS endpoint object
var endpoint - nem.model.objects.create( endpoint
// Create a common object holding key
var common - nem.model.objects.create("common
I/Create an un-prepared transfer transaction object
var transferTransaction nem.model.objects

// Prepare the transfer transaction object
var transactionEntity nem.model.transactions
// Serialize transfer transaction and announce
nem.model.transactions.send(common,
transactionEntity, endpoint);

The link to the documentation site can be found here

Hyperledger Fabric

Hyperledger Fabric (HLF) call its smart contracts chaincode. HLF is an enterprise private blockchain, built with great flexibility, which makes it very useful for businesses as their business rules change after approximately 7 years. Most other blockchains are not built considering flexibility.

The three most important functions are:

  • PutState: Create new asset or update existing one.
  • GetState: Retrieve asset.
  • GetHistoryForKey : Retrieve history of changes.
  • DelState: Delete asset.

A Sample Smart contract code:

package main

import (
"fmt"

"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)

// SimpleAsset implements a simple chaincode to manage an asset
type SimpleAsset struct {
}

// Init is called during chaincode instantiation to initialize any
// data. Note that chaincode upgrade also calls this function to reset
// or to migrate data.
func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response {
// Get the args from the transaction proposal
args := stub.GetStringArgs()
if len(args) != 2 {
return shim.Error("Incorrect arguments. Expecting a key and a value")
}

// Set up any variables or assets here by calling stub.PutState()

// We store the key and the value on the ledger
err := stub.PutState(args[0], []byte(args[1]))
if err != nil {
return shim.Error(fmt.Sprintf("Failed to create asset: %s", args[0]))
}
return shim.Success(nil)
}

// Invoke is called per transaction on the chaincode. Each transaction is
// either a 'get' or a 'set' on the asset created by Init function. The Set
// method may create a new asset by specifying a new key-value pair.
func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
// Extract the function and args from the transaction proposal
fn, args := stub.GetFunctionAndParameters()

var result string
var err error
if fn == "set" {
result, err = set(stub, args)
} else { // assume 'get' even if fn is nil
result, err = get(stub, args)
}
if err != nil {
return shim.Error(err.Error())
}

// Return the result as success payload
return shim.Success([]byte(result))
}

// Set stores the asset (both key and value) on the ledger. If the key exists,
// it will override the value with the new one
func set(stub shim.ChaincodeStubInterface, args []string) (string, error) {
if len(args) != 2 {
return "", fmt.Errorf("Incorrect arguments. Expecting a key and a value")
}

err := stub.PutState(args[0], []byte(args[1]))
if err != nil {
return "", fmt.Errorf("Failed to set asset: %s", args[0])
}
return args[1], nil
}

// Get returns the value of the specified asset key
func get(stub shim.ChaincodeStubInterface, args []string) (string, error) {
if len(args) != 1 {
return "", fmt.Errorf("Incorrect arguments. Expecting a key")
}

value, err := stub.GetState(args[0])
if err != nil {
return "", fmt.Errorf("Failed to get asset: %s with error: %s", args[0], err)
}
if value == nil {
return "", fmt.Errorf("Asset not found: %s", args[0])
}
return string(value), nil
}

// main function starts up the chaincode in the container during instantiate
func main() {
if err := shim.Start(new(SimpleAsset)); err != nil {
fmt.Printf("Error starting SimpleAsset chaincode: %s", err)
}
}

The link to documentation site can be found here.

iOlite

iOlite is a product which focuses on the mass adoption of smart contract technology by providing an easy to use engine which is capable of understanding natural language to be compiled to smart contract code

It is based on FAE ( Fast adaption engine ) FAE is capable of converting natural language into smart contract code.

//it will insert a column in the specified location (AfterThisColumn) to store result
Function ErrorCorrelation(Output_DataTable, WaveOneName, WaveTwaName, After
wave/T Output_DataTable //wave reference to the Output_DataTable text wa
string WaveOneName
string Wavel woName
string Afterl hisColumn
String TistalumnName
Check if the Output_DataTable wave provided exists
if(waveexists(Output_DataTable)O)
PrintAbort(The error correlation function was called using an output data
endif
/need to check here that both of the required columns exist. if they don't the
if (FindDimLabel(Output_DataTable, 1, WaveOneName)2FindDimLabel(Out
return O
endif
wariable StartTime
variable Endlime
Variable StartPoint
Variable EndPoint
first insert a column into the output table to hold the error correlations
variable ColumnBeforelnsert 1 + FindDimLabel(Output DataTable, 1, AfterTh
InsertPoints M-1 ColumnBeforelnsert, 1, Output_DataTable //insert a colum
SetDimLabel 1, ColumnBeforelnsert, $ThisColumnName, Output_DataTable //a
wave index-Time = $ olíteDEpath("CurrentDRS","Index-Time")
variable ErrorCorrelation_Thislnteg
variable index=
variable NoOfOutputTableRows DimSize(Output DataTable, O)
if(cmpstr(llll, Output. DataTable(index [%S"DateTime"D-0&& str2num(O
StartTime-DateStr2Date1 904(Output-DataTable[index][%S"DateTime
Endtime = StartTime+ str2num(Output. DataTable[index][%S"Duratior
StartPoint ForBinarySearch(Index_Time, StartTime)
Endpoint = ForBinarySearch(index-Time, Endtime)
duplicate/0/R[StartPoint, EndPoint] $ioliteDFpath("CurrentDRS",Wa
duplicate/0/R [StartPoint, EndPoint] SioliteDFpath("CurrentDRS",Wav
wave WaveOne-Snippet= $ioliteDFpath("Temp",WaveOneName + "-Snil
wave WaveTwo-Snippet = $ialiteDFpath("Temp",WaveTwoName + "-Sni
//need to remove NaNs from both waves, as these will mess up the er
TrimNaNsTwoWaves(WaveOne_Snippet, WaveTwo_Snippet)
ErrorCorrelation_Thislnteg- StatsCorrelation(WaveOne_Snippet, Wav
Output-DataTable(index!%SThisColumnName] = num2str(ErrorCorrela
endif
index+= 1
while(index NoOfOutputTableRows)
KillWaves /Z WaveOne Snippet, WaveTwo Snippet
end

The link for documentation site can be found here.

Stellar Smart Contracts

Stellar smart contracts (SSC) are much different from Ethereum smart contracts. They are not Turing complete and are implemented as an agreement between multiple parties and enforced by transactions. You can read more about stellar smart contracts in the official documentation here.

An SSC is expressed as compositions of transactions that are connected and executed using various constraints.

Some of the constraints are given below

  • Multi-signature — What keys are needed to authorise a certain operation? What parties need to agree on a circumstance in order to execute the steps?
  • Batching/ Atomicity — What operations must all occur together or fail? What must happen in order to force this to fail or pass?
  • Sequence — In what order should a series of transactions be processed? What are the limitations and dependencies?
  • Time Bounds — When can a transaction be processed?

A sample code is given below:

const newKey = Stellar.Keypair.random();
const transaction = new Stellar.TransactionBuilder(ownerAccount)
.addOperation(Stellar.Operation.createAccount({
destination: escrowPubKey,
startingBalance: '2.5000000'
}))
.build();
transaction.sign(ownerKeypair);
return StellarConfig.server.submitTransaction(transaction);

Neblio — Blockchain for Business

Neblio is targeting the integration of blockchain into pre-existing enterprises via easy to use APIs in eight of the most commonly used programming languages. The key goal of Neblio is to provide an easy to use blockchain for existing businesses. Developers should be able to use Neblio blockchain technology without being a blockchain expert.

Neblio provides a Raspberry Pi wallet to stake your coins. The wallet itself can be set up with just one command after downloading the source code. The contact language for this platform is Python, Java and Objective C.

The link for documentation site is can be found here

Cardano

Similar to Ethereum, Cardano is a smart contract platform however, Cardano offers scalability and security through layered architecture.

Cardano’s approach is unique in the space itself since it is built on scientific philosophy and peer-reviewed academic research. The contact language used is Plutus.

add : Nat -> Nat -> Nat {
add = \m n ->
case m of {
Zero -> n ;
Suc m' -> Suc (add m' n)
}
}

The link to documentation site can be found here

Corda

Similar to Fabric, consensus in Corda is also reached at transaction level by involving parties only. Subject to consensus is transaction validity and transaction uniqueness. Validity is ensured by running the smart contract code (smart contracts are described in detail below) associated with a transaction, by checking for all required signatures and by assuring that any transactions that are referred to are also valid. Uniqueness concerns the input states of a transaction.

// Add these imports:
import net.corda.core.contracts.Command
import net.corda.core.identity.Party
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.utilities.ProgressTracker

// Replace TemplateFlow's definition with:
@InitiatingFlow
@StartableByRPC
class IOUFlow(val iouValue: Int,
val otherParty: Party) : FlowLogic<Unit>() {

/** The progress tracker provides checkpoints indicating the progress of the flow to observers. */
override val progressTracker = ProgressTracker()

/** The flow logic is encapsulated within the call() method. */
@Suspendable
override fun call() {
// We retrieve the notary identity from the network map.
val notary = serviceHub.networkMapCache.notaryIdentities[0]

// We create the transaction components.
val outputState = IOUState(iouValue, ourIdentity, otherParty)
val cmd = Command(TemplateContract.Commands.Action(), ourIdentity.owningKey)

// We create a transaction builder and add the components.
val txBuilder = TransactionBuilder(notary = notary)
.addOutputState(outputState, TEMPLATE_CONTRACT_ID)
.addCommand(cmd)

// We sign the transaction.
val signedTx = serviceHub.signInitialTransaction(txBuilder)

// We finalise the transaction.
subFlow(FinalityFlow(signedTx))
}
}

The link for thr documentation site can be found here

Ripple

Ripple is a real-time gross payment system first-conceived in 2004 by Ryan Fugger and officially launched in 2012. Its goal is to eliminate the high transaction fees and processing delays of online payments by providing a frictionless experience when sending money globally with the power of blockchain technology.

{
"source": {
"address": "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59",
"maxAmount": {
"value": "0.01",
"currency": "USD",
"counterparty": "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"
}
},
"destination": {
"address": "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo",
"amount": {
"value": "0.01",
"currency": "USD",
"counterparty": "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"
}
}
}

The link for documentation site can be found here.

Importance of smart contracts

One of the major advantage of smart contract implementation is the you won’t need to use intermediary services such as brokers, agents etc to facilitate a transaction. It also enables agent neutrality and automation in signing deals and is time saving. It excludes human participation in transactions, everything is done by the prescribed program code. It ensures safety as the data in the decentralised registry cannot be lost and cyber attacked . It automatically generates a record of all transactions that is highly resistant to forgery and also has the ability to create entire trading environments and schemes to exchange customised items of value (e.g. could be used to implement a private carbon credit scheme).

In fact, the scope of applications of this technology is a lot. For example, they can completely eradicate falsification of elections, when the votes will be placed in a special register, the decryption of which will require a computer with incredible power. Also, its users will be able to find a smart contract in the field of logistics, helping to solve the problems of bureaucracy, so characteristic of this area. Smart contracts can also determine who was guilty of an accident, and insurance companies can find it easier to determine their contributions.

The aim of the smart contract is to provide security while transaction and reduce surplus transaction costs. It saves time and conflict and is also cheaper, faster and more secure way of payment as compared to the traditional system.

Looking to work on or use Smart Contracts? Reach out to us at hello@acycliclabs.com.