Solidity CRUD Tutorial, Part 1 — Building a Smart Contract with CRUD Operations

Learn how to build a simple smart contract on Ethereum and how to test it using Truffle framework

Gaurav Agrawal
Oct 9, 2018 · 6 min read

Table of Contents

Quick Definitions

Building a smart contract with CRUD operations

Andy is Eng. manager at Google and works on Google chrome project
curdApp.sol

Think of a ‘contract’ as a ‘class’ in other programming languages.

Solidity Data Types

struct country{
string name;
string leader;
uint256 population;
}
uint256 public totalCountries;


function CurdApp() public{
totalCountries = 0;
}
event CountryEvent(string countryName , string leader, uint256 population);event LeaderUpdated(string countryName , string leader);event CountryDelete(string countryName);

Create Operation -

function insert( string countryName,
string leader,
uint256 population)
public
returns (uint256 totalCountries){
country memory newCountry = country(countryName , leader, population);
countries.push(newCountry);
totalCountries++;
emit CountryEvent (countryName, leader, population);
return totalCountries;
}

Read operation —

function getCountry(string countryName) 
public
view
returns(string name , string leader , uint256 population){
for(uint256 i =0; i< totalCountries; i++){
if(compareStrings(countries[i].name, countryName)){
return (countries[i].name , countries[i].leader , countries[i].population);
}
}
revert('country not found');
}
revert(‘Something bad happened’);

Update operation -

function updateLeader(string countryName, string newLeader) public returns (bool success){
//This has a problem we need loop
for(uint256 i =0; i< totalCountries; i++){
if(compareStrings(countries[i].name ,countryName)){
countries[i].leader = newLeader;
emit LeaderUpdated(countryName, newLeader);
return true;
}
}
return false;
}
function deleteCountry(string countryName) public returns(bool success){
require(totalCountries > 0);
for(uint256 i =0; i< totalCountries; i++){
if(compareStrings(countries[i].name , countryName)){
countries[i] = countries[totalCountries-1];
delete countries[totalCountries-1];
totalCountries--;
countries.length--;
//emit event
emit CountryDelete(countryName);
return true;
}
}
return false;
}

Other functions-

function compareStrings (string a, string b)  internal pure returns (bool){
return keccak256(a) == keccak256(b);
}


function getTotalCountries() public view returns (uint256 length){
return countries.length;
}

Notes & suggestions -


Building A Web Or Mobile App?

Crowdbotics

The fastest way to build your next app.

Thanks to William Wickey.

Gaurav Agrawal

Written by

CryptoFi (cryptofi.co), Coinmonks Jobs (coinmonks.com) and (coincodecap.com) Editor — Coinmonks, Crowdbotics and QuikNode

Crowdbotics

The fastest way to build your next app.