What is ICP Blockchain? A Brief Introduction

ICP, short for Internet Computer Protocol, represents the third generation of blockchain technology, poised to revolutionize the Internet and accelerate the adoption of Web 3. Developed by the DFINITY Foundation , the Internet Computer blockchain aims to extend the public internet’s capabilities, allowing it to natively host software and services. In addition, it seeks to enable decentralized versions of popular applications—such as social media, enterprise software, and financial services—while fostering a new, decentralized internet that operates independently of traditional IT infrastructure.

The DFINITY Foundation, a non-profit organization founded by Dominic Williams in 2016 and headquartered in Zurich, Switzerland, achieved a major milestone with the launch of the Internet Computer in 2021. Dominic Williams, a serial entrepreneur, cryptographer, and DFINITY’s chief scientist, leads the foundation. With a team of over 250 scientists, researchers, and professionals, DFINITY is dedicated to building a public network that offers a secure, scalable, and efficient alternative to the current internet.

Dominic Williams

ICP boasts a unique architecture featuring independent subnet networks that run smart contracts known as canisters. Canisters are more powerful than traditional smart contracts, enabling more complex computations. Unlike conventional blockchains, ICP combines the security of blockchain technology with the scalability of cloud computing. Its core components include the Network Nervous System (NNS), which governs the entire network, and canisters—autonomous code units that operate on the Internet Computer.

In the Internet Computer, nodes are connected to form subnets, which are the fundamental building blocks of the IC. Each subnet operates its own consensus algorithm and runs canister smart contracts. Subnets replicate computation and storage while running concurrently with one another. The Internet Computer consists of numerous subnets and scales linearly by adding more, allowing for continuous expansion.

Subnets

Canisters are the building blocks of decentralized applications (DApps) on ICP, they contain both the code and state, making them more versatile than traditional smart contracts. Canisters run directly on the Internet Computer, without intermediaries. and enable developers to build complex DApps with ease. Benefits of using canisters are higher performance and scalability, and ability to handle complex logic and data storage.

ICP’s consensus protocol, known as Threshold Relay, introduces a novel mechanism that randomly selects nodes to produce blocks, ensuring both fairness and security. This protocol leverages chain key technology, enabling the Internet Computer to finalize transactions within milliseconds, a speed unmatched by most traditional blockchains. Additionally, the consensus algorithm ensures decentralization and security by eliminating the need for a centralized authority, promoting a more equitable and transparent internet. Compared to other consensus mechanisms like Proof of Work (PoW) and Proof of Stake (PoS), Threshold Relay offers significantly faster consensus, greater scalability, and lower energy consumption, making it a more sustainable and efficient solution for blockchain technology.

Canisters communicate via asynchronous messaging, allowing them to exchange data and execute functions without waiting for immediate responses. This enables canisters to continue other tasks while awaiting a reply, improving efficiency and scalability. Asynchronous messaging supports parallel processing, allowing distributed applications to run smoothly across the network. It also enhances fault tolerance, as messages can be retried without disrupting operations. This model ensures high responsiveness and performance, making the Internet Computer more scalable and reliable than traditional synchronous systems.

Canisters are precharged with “cycles,” which serve as the fuel for computation and storage, allowing them to run smoothly. These cycles are analogous to gas fees in other blockchains but are designed to be more efficient and cost-effective. Developers must ensure that their canisters are sufficiently stocked with cycles, which are consumed as the canister processes computations, stores data, or handles messages. One key advantage of this system is that users interacting with decentralized applications (dApps) on the Internet Computer are not burdened with transaction fees, unlike on traditional blockchains. Instead, the cost of running the canister is handled by the developers or organizations maintaining it. This user-friendly approach removes the friction of micro-transactions, offering a seamless and more accessible experience for users, thereby encouraging greater adoption of decentralized applications. Additionally, cycles are pegged to the cost of real-world computing resources, ensuring stability in pricing over time. This helps developers predict and manage operational costs more effectively while providing users with a fee-free experience.

Canister smart contracts have the unique capability to interact with Web2 systems, bridging the gap between traditional web services and decentralized blockchain applications. This means that canisters can communicate with existing Web2 APIs, databases, and services, enabling seamless integration with conventional web technologies. For example, a canister could fetch data from an external Web2 source, such as a financial API, or interact with cloud services like AWS, allowing decentralized applications (dApps) to utilize real-world data and functionality without needing to rely solely on blockchain-native data. This interoperability makes the Internet Computer highly versatile, as it allows developers to build dApps that can easily interact with both decentralized and centralized infrastructures. By enabling communication with Web2, canisters help ensure that blockchain-based applications can be integrated into the broader digital ecosystem, promoting smoother transitions from centralized systems to decentralized ones and broadening the use cases for blockchain technology in real-world applications.

Canister smart contracts have the capability to own and transact any cryptocurrency, allowing them to operate across multiple blockchain ecosystems. Unlike traditional smart contracts that are limited to a single token, canisters can manage and transfer various cryptocurrencies like Bitcoin, Ethereum, and more. This flexibility enables the creation of decentralized applications (dApps) that support multi-currency transactions, such as decentralized exchanges (DEXs) and cross-chain DeFi protocols. By facilitating seamless interaction between different cryptocurrencies, canisters enhance interoperability, security, and functionality, making the Internet Computer a versatile platform for innovative blockchain solutions.

Chain fusion in the Internet Computer (ICP) is a process where independent subnet blockchains can merge to increase scalability and efficiency. Subnets, which run smart contracts called canisters, operate autonomously but can be seamlessly combined when more computational resources are needed. This allows the Internet Computer to dynamically scale as demand grows, ensuring that decentralized applications (dApps) can handle increased traffic without performance bottlenecks. Chain fusion ensures interoperability, enhances resource allocation, and maintains the network’s security and decentralization, making ICP a flexible and scalable blockchain platform.

ICP tokens serve multiple essential functions within the Internet Computer (ICP) ecosystem. One of the primary roles is governance, where ICP token holders participate in decision-making through the Network Nervous System (NNS). By locking up ICP tokens to create neurons, users can vote on proposals related to network upgrades, policies, and development directions. The more tokens a user locks and the longer they are staked, the greater their voting power and potential rewards. This decentralized governance model ensures that the community actively shapes the future of the network.

In addition to governance, ICP tokens are used to fuel computation on the network by being converted into cycles, which act as the computational currency for running applications (canisters). Developers use these cycles to pay for processing power and storage, ensuring predictable and stable costs. ICP tokens also incentivize participation in the network by rewarding node operators and developers who contribute to the network’s security and functionality. While users are not directly charged transaction fees, ICP tokens are essential for the network’s operations, ensuring smooth and efficient interactions within decentralized applications.

The Network Nervous System (NNS) in the Internet Computer (ICP) is a decentralized, autonomous system responsible for governing the entire network. It acts as the control center, managing everything from the configuration of nodes to protocol upgrades, economic policies, and security measures. The NNS is crucial for maintaining the decentralized nature of the Internet Computer, as it allows decisions to be made transparently and collectively by the community of ICP token holders.

Here are the key functions of the NNS:

  1. Governance: The NNS enables ICP token holders to participate in governance by creating “neurons.” Token holders can lock up their ICP tokens to form these neurons, which gives them the ability to vote on proposals related to network upgrades, protocol changes, and other decisions that affect the Internet Computer. Neurons can also submit proposals for consideration, and the NNS automatically executes approved proposals. The more tokens a neuron locks up and the longer the staking duration, the greater the neuron’s voting power.
  2. Network Management: The NNS manages the configuration of the network by onboarding new node operators, setting up new subnets, and merging or upgrading existing subnets. It ensures that the network remains secure, scalable, and efficient by automating many aspects of its maintenance and operation. This includes distributing rewards to node operators and ensuring that resources are allocated efficiently.
  3. Security and Economic Control: The NNS controls the economic system of the Internet Computer by regulating the creation and burning of ICP tokens, especially when they are converted into cycles (the fuel for computation). It also plays a role in ensuring network security by monitoring and addressing potential threats, such as malicious nodes, and coordinating responses to safeguard the integrity of the blockchain.

Motoko is a programming language designed specifically for building smart contracts and decentralized applications (dApps) on the Internet Computer (ICP) blockchain. Developed by the DFINITY Foundation, it is compiled to WebAssembly (Wasm) to ensure compatibility and efficient execution on the Internet Computer’s infrastructure. Motoko is a statically typed language, providing strong type safety and minimizing runtime errors, which is crucial for secure blockchain development. It follows an actor-based model, aligning with the Internet Computer’s asynchronous messaging system, enabling efficient, concurrent operations within decentralized applications.

Motoko also includes features tailored for blockchain development, such as automatic memory management (garbage collection), cryptographic functions, and built-in tools for managing cycles (the computation resource on ICP). Its syntax is accessible to developers familiar with languages like JavaScript or TypeScript, making it easier to adopt. With these features, Motoko simplifies the process of building secure, scalable, and efficient dApps on the Internet Computer, making it an ideal choice for developers in the blockchain space.

ICP (Internet Computer Protocol) plays a significant role in accelerating the adoption of Web3 by providing a scalable, efficient, and decentralized platform that extends the capabilities of the public internet. Unlike traditional blockchains, which often struggle with scalability and high transaction fees, ICP enables decentralized applications (dApps) to run at web speed, with low costs, and without relying on centralized infrastructure. This makes it easier for developers to build and deploy dApps that offer the same level of performance and user experience as traditional web applications, removing a major barrier to Web3 adoption.

Moreover, ICP’s architecture allows it to host not only smart contracts but also entire web services, making it possible to run decentralized versions of popular applications like social media, enterprise software, and financial services directly on the blockchain. Its governance system, powered by the Network Nervous System (NNS), ensures that the platform evolves through decentralized decision-making, creating a more equitable and transparent internet. By addressing key issues like scalability, decentralization, and user experience, ICP provides the infrastructure necessary to drive the widespread adoption of Web3, making decentralized applications more accessible to both developers and users.


Building Blockchain for Business

Blockchain is the underlying technology for Bitcoin, Ethereum, and other cryptocurrencies. However, cryptocurrency is far from the only application of blockchain for businesses. One of the most popular business applications of blockchain is fundraising, especially for startups. Apart from conventional ways of funding, blockchain enables alternative methods of fundraising such as ICO or STO.

In the past few years, many companies have raised an incredible amount of money via ICO. Some of the biggest and most successful ICO projects include NEO, Ethereum, Spectrecoin, and Lisk. More info about ICO can be found on the Investopedia website.

That said, I am not going to discuss ICO in this article. Instead, we shall explore blockchain applications in businesses. Though we can use blockchain for all kinds of business applications, whether or not blockchain is suitable for a particular business depends on the nature of the business, the business model, the requirements, and many other factors.

Before implementing blockchain, the C-level management team of a business organization should conduct a feasibility study to determine whether it is necessary and plausible to adopt blockchain technology. You should ask the following questions:

  • Can blockchain add value to the current business?
  • Can blockchain increase the organization’s competitiveness?
  • Do you need to deal with many trustless parties?
  • Do you need a decentralized and distributed database system?
  • Can blockchain improve workflow efficiency?
  • Can blockchain increase revenue and profit?
  • Do you have enough financial resources to implement blockchain?
  • Can blockchain technology integrate with existing systems?
  • Do you have enough talents to manage the blockchain system?

Once you’ve decided that implementing blockchain would benefit your company, you need to carry out the following steps:

  1. Identify a suitable use case.
  2. Assemble your team.
  3. Design the blockchain architecture.

Identify a suitable use case

To embark on a blockchain project, you need to identify the most suitable use case for your business. The best way is to examine use cases in an industry that is similar to your business. Generally, there are three areas in which blockchains can perform very well.

Data Authentication & Verification

This includes immutable storage, digital signatures, and encryption. Data in almost any format can be stored in the blockchain. Blockchains can create public-private key pairs and also be used for generating and verifying digital signatures. Therefore, it can be used for data authentication & verification.

One of the best usages is counterfeiting prevention. For example, Luxtag, a Malaysia-based blockchain company, has patented an anti-counterfeit technology. This technology enables businesses and their customers to protect the authenticity and ownership of their valuable assets by providing digitized certificates using blockchain technology. They have rolled out their first product, known as e-Scroll, for a consortium of Malaysian public universities to verify and validate certificates using a blockchain-powered web application.

Another area related to authentication and verification is data provenance. One of the most successful companies in this area is Everledger. This company has built the Diamond Time-Lapse Protocol, a traceability initiative built on a blockchain-based platform for the diamond and jewelry industry. The system is to ensure that there is transparency along the entire diamond’s lifetime journey, instilling consumer confidence and driving industry growth.

Another application is supply chain management. The most notable is the initiative by Walmart using blockchain technology to ensure food safety. Walmart has been working with IBM on a food safety blockchain solution requiring all suppliers of leafy green vegetables for Sam’s and Walmart to upload their data to the blockchain by September 2019. By placing a supply chain on the blockchain, it makes the process more traceable, transparent and fully digital.

Watch the following video about food safety:

Other business applications could be medical records management, insurance, KYC management for banks, and more.

Digital Asset Management

Any asset that can be digitized is considered a digital asset. Digital assets include ebooks, digital art, images, video, music, journals, newspapers, audio books, online training courses, recipes, and more. With the invention of blockchain technology, digital assets also include crypto assets. Crypto assets can be cryptocurrencies like Bitcoin, Ethereum, and other altcoins, or the tokenized version of a real-world asset such as gold, silver, oil, land titles, property, paintings, etc.

Currently, most digital assets are traded over the Internet via the centralized e-commerce marketplace. However, digital assets can be traded more efficiently over the decentralized peer-to-peer blockchain platforms.

Some real world use cases for digital assets management in blockchain include:

  • AlphaPoint. Provides enterprise-grade software that enables institutions to convert assets to securities tokens and trade those assets on an exchange.
  • Polymath. Enables trillions of dollars of securities to migrate to the blockchain.
  • Harbor. Offers a digital securities platform for compliant fundraising, investor management, and liquidity.
  • Powerledger. Provides a platform for peer-to-peer energy trading.

Smart Contracts

A smart contract is a programmable contract that enables auto execution of a contract the moment it fulfills certain terms and conditions. It is akin to a vending machine – you get your product by inserting some coins or banknotes.

According to Investopedia, smart contracts are:

“self-executing contracts with the terms of the agreement between buyer and seller being directly written into lines of code. The code and the agreements contained therein exist across a distributed, decentralized blockchain network. Smart contracts permit trusted transactions and agreements to be carried out among disparate, anonymous parties without the need for a central authority, legal system, or external enforcement mechanism. They render transactions traceable, transparent, and irreversible.”

Almost any blockchain business application involves the use of a smart contract. A famous use case is Cryptokitties. A smart contract is executed when a user acquires a unique virtual kitty from the Cryptokitties collectible marketplace via a bidding process. The highest bidder gets to own the digital asset. Other dapp transactions also make use of smart contracts.

Blockchain-powered supply chain management makes use of smart contracts to handle transactions between manufacturer, suppliers, wholesalers, and retailers.

In the insurance industry, the client who wishes to buy insurance can provide personal information including sensitive data like medical records via a smart contract to the insurance company. In the health care industry, a patient can get faster and more accurate diagnoses and treatment via a smart contract that allows them to share medical records.

Assemble your Team

After conceptualizing a business use case that is suitable for your business, you need to assemble your team to kick-start the blockchain project. Getting the right people in your team is crucial to success. Your team should comprise people with business skills and also people with technical skills. People with business skills should be able to see the overall picture of your business model and know how to execute it. They must also have good interpersonal skills, strategic thinking, good networks, and financial knowledge. The people with business skills should be assigned the posts of CEO, CFO, marketing manager, business development manager, and so on.

People with good IT skill in general and blockchain in particular are equally important. The CTO must have many years of experience in the IT and software industry and have a good grasp of blockchain. He or she must be assisted by a technical lead who has good practical experience in setting up the blockchain platform, know how to program the smart contract, sound knowledge of programming languages including Solidity, JavaScript, Goland, C++, Java, Python, and so on.

In addition, if you plan to raise funds via ICO, you need to employ a compliance officer, preferably a lawyer who understands the guidelines provided by the security commission and the central bank.

Designing the Blockchain Architecture

You need to decide whether to build the blockchain network from scratch, or use a third party blockchain solution like Azure blockchain, Oracle, or AWS blockchain. The former is time-consuming, whereas the latter could be up in as little as 30 minutes.

Each of the the aforementioned enterprise blockchains offer their own functionalities and features as well as cost advantages. Both AWS and Azure offers solutions for Ethereum, Hyperledger Fabric, Corda, and Quorum, while Oracle only caters for Hyperledger Fabric. We can compare their features in the following table:

Courtesy of 101 Blockchains


The cost of setting up Azure Blockchain Workbench is roughly $400-$500 depending on your region and usage. The main costs are three VMs and one app service. Two VMs are for the default blockchain network, and one VM is for the microservices on Workbench. For AWS Blockchain pricing, refer to: https://aws.amazon.com/managed-blockchain/pricing/

References

ETHKL #5 : Security Audits & Scaling

The meetup was at HelloGold office , KL on Friday 23, Nov.

Speakers:

  1. Petar Tsankov-Chief Scientist/co-founder of ChainSecurity AG & Senior Researcher at the ICE center. ETH Zurich. 
  2. Andras Kristof- Founder and Advisor of Akomba Labs
  3. Lai Ying Tong- Researcher at Ethereum Foundation
  4. Ken Chan

The session began with Ken Chan introducing the audience about Zero-Knowledge Proofs. I was sure many developers among the audience understand what it is but the concept sounds strange to me. Fortunately, Ken was good in demonstrating the concept by using the scenario of the American presidential election involving Trump and Clinton as well as a “live demo” with Harith of HelloGold as the co-actor.

Apparently, the Zero-knowledge proof method, or more exactly zk_SNARKS, is a consensus protocol used by Zcash to validate its shielded transactions that are fully encrypted on its blockchain. According to Zcash(https://z.cash/technology/zksnarks/), the acronym zk-SNARK stands for “Zero-Knowledge Succinct Non-Interactive Argument of Knowledge,” and refers to a proof construction where one can prove possession of certain information, e.g. a secret key, without revealing that information, and without any interaction between the prover and the verifier.

Zcash further pointed out that “Zero-knowledge” proofs allow one party (the prover) to prove to another (the verifier) that a statement is true, without revealing any information beyond the validity of the statement itself. For example, given the hash of a random number, the prover could convince the verifier that there indeed exists a number with this hash value, without revealing what it is.

Ken illustrated the process of Succinct and Non-interactive using a diagram, where the prover begins by generating a proof string and then the verifier needs to verify the proof string, as shown below:

The above process is actually more complex than illustrated in the diagram. According to Zcash,  zk-SNARKs work by first turning what you want to prove into an equivalent form about knowing a solution to an algebraic equation, as follows:

Computation → Arithmetic Circuit → R1CS → QAP → zk-SNARK

Here is an example of what an arithmetic circuit looks like for computing the expression (a+b)*(b*c) :

Diagram Adapted from Zcash

The output is then verified by the verifier. However, Ken pointed out that the process might be compromised by some malicious codes which he called toxic waste that produce false proofs. Ken concluded with the following points:

Why ZK SNARKs?

  • Strong cryptography research by Zcash team
  • Math-based- not coin joining
  • Short proofs

Why not ZK SNARKS?

  • Trusted setup for every contract
  • No transparency for counterfeiting
  • Computationally expensive

Next, Dr.Petar from ChainSecurity discussed the importance of security audit. His topic was “How Not to get Hacked”. ChainSecurity is a smart contract auditing platform. They can identify security vulnerabilities and certify the functional correctness of smart contracts and blockchain projects. 

ChainSecuity has developed an Audit platform that can perform Automated Security Check on smart contracts. This platform can test and audit both Ethereum smart contracts (Security Scanner)and the Hyperledger Fabric chaincode(Chaincode Scanner).

According to Dr.Petar,  more USD$1 billion have been stolen this year due to crypto hacks. He stressed that writing secure smart contracts is difficult.  Developers might fail to see bugs and security flaws, therefore we need to audit the smart contracts.  However, currently, most audits are done manually and tend to miss many issues. Furthermore, in the post-development stage, most anomalies are invisible. 

To work around the aforementioned issues, ChainSecurity has developed some AI-based automated tools to help in every stage of smart contract lifeline. At the developmental stage, the automated tools will assist in certifying the correctness of the code. At code audit stage, the machine-checked audit will generate the audit report by committing the smart contract onto the Audit platform which runs security auditing using the security scanner, the symbolic verifier and the AI-based Tester. Finally, in the post development stage, there are monitoring tools to help track the smart contract health.

More information on security audit can be found on ChainSecurity website.

The final topic was scaling presented by Andras Kristof and Lai Ying Tong.  This is a topic where all Ethereum enthusiasts are concerned about. According to the speakers, the solution is to develop a two-layer architecture. Layer 1 is called serenity which comprises sharding, casper, random beacon, and p2p networking. Layer 2 comprises payment channels, state channels, sidechains, and plasma. The solution also comprises succinct proofs using snarks and starks. Furthermore, there are more integrations that include swarm, light clients and client optimizations.

In more details, the layer 1(serenity) structure includes the Main Chain(provides staking and PoW), the Beacon Chain((provides random number and PoS), the Shard Chain(provides data) and VM(provides state execution result).

For the payment channels, there are two channels, the Open Channel and the Close Channel. The transactions include blockchain transactions and Off-chain payments. Besides that, Lai also spoke on payment channels on the lightning network. The layer2 solutions are to move state-modifying operations off-chain, which include payment channels and state channels.

Besides that, Lai also covered topics on sidechains, plasma mvp, morevp, swarm, light clients and more. These are heavy topics and I shall discuss them in future articles.

Solidity Data Types

Solidity is a statically typed programming language, which means that the type of each variable needs to be specified at compile-time. Solidity provides several categories of data types, as listed below:

  • Value types
  • Reference types
  • Mappings

Value Types

These types of data are called value types because variables of these types will always be passed by value. There are several value types in solidity, as listed below:

  • Boolean
  • Integer
  • Fixed Point Number
  • String
  • Address
  • Array
  • Literal
  • Enum

We shall focus on boolean, integer and string data types first and discuss other data types in future articles.

Boolean

Boolean is a data type that only produces two possible values, true or false. They can be used together with some common operators, as follows:

OperatorMeaning
!Logical negation
&&Logical conjunction  “and”
||Logical disjunction “or’
==Equality
!=Inequality

We declare a Boolean variable using the keyword bool

Integer

There are two types of integer, the signed integers, and the unsigned integers. The keyword to declare signed integers is int and the keyword to declare unsigned integers is uint. In addition, we can assign the number of bits a signed integer can hold using int8, int16 until int256. Similarly, we can use uint8 until uint256 for unsigned integers.

We declare an integer variable using the keyword int or uint

We can use various operators to deal with operations that involve integers. The operators are listed as follows:

Comparison Operators<=  < ==  != >=  >
Bit Operators&  |  ^ and   ~
Arithmetic Operators –  * /   % **  << >>

String

The string is a data type that cannot be operated arithmetically. String literals are written with either double or single-quotes, for example, “Abraham”, “007”, “abc%&$” and more.

We declare a string variable using the keyword string .

Example: This example The string two types of variables, unsigned integer and boolean. We also use the keyword if and the operator > to check whether the outcome is true or false.

The code

pragma solidity ^0.4.24;

contract myContract2 {
      uint private a;
      uint private b;
      bool ans;
   
 function getValue1(uint num1) public{
    a = num1;
 }

  function getValue2(uint num2) public{
    b = num2;
 }
 
  function checkAns() public view returns (bool){ 
      if (a>b)
          ans=true;
      else
      ans=false;
      
      return ans;
  }

 
}

After we compiled and deployed the contract, we get the following output. We can test the results by entering different values in getValue1 and getValue2. The results will be either true or false.

The output on Remix iDE

Introduction to Solidity

What is Solidity?

Solidity is a high-level programming language that is used to create and implement smart contracts in Ethereum. The smart contracts created using Solidity can be used for financial transactions, crowdfunding, voting, intelligent supply chain management, improvement of  IoT workflow, ride sharing automation, smart city administration and more.

It has Python, C++ and JavaScript influences and is used for Ethereum Virtual Machine ( EVM ). As a result, it is fairly convenient and easy to grasp for those that are already familiar with the Python, C++ or JavaScript.

The IDE for Developing Smart Contracts

The best tool to write, compile, test and deploy smart contracts is  Remix.  Remix is a browser-based IDE that provides an inbuilt compiler as a well as runtime environment without server-side components.

We can also use other code editors for Solidity. I suggest we use Visual Studio Code or Solidity Plugin for Visual Studio. For the Solidity plugin, you need to download it from https://marketplace.visualstudio.com/items?itemName=ConsenSys.Solidity
Besides that, you need to install Visual Studio 2015.

Writing Your First Smart Contract in Solidity

A smart contract is a data, that can be referred to as its state, and code, which can be referred to as its functions, collection, that resides on a specific address in the Ethereum blockchain.

The first line of the smart contract is always 

pragma solidity ^0.4.24;

pragma is a keyword which is used to instruct the compiler how the source code should be treated. In this example, the pragma specified that the source code is written for the Solidity Library version 0.4.24

To define a contract, we use the statement

contract contractName {

}


You can use any name for the contract, but any meaningful name will be better. For example

Contract  NewCoin{

}

indicates that you intend to create a contract for a new cryptocurrency.

Assigning variables

Next, we would like to introduce some variables into the contract. First of all, let’s assign some string variables and some integer variables.

To assign a string variable, the syntax is

string myName;

In Solidity, there are two types of integers, the signed integer and the unsigned integer.

A signed integer means it can store positive or negative values while an unsigned integer can only store positive values.

To specify that it will be an unsigned integer, we use the keyword uint before the name of the new variable.

To assign an unsigned integer, the syntax is as follows;

uint MyAge;

Access Modifier

You may want to add the access modifier(or visibility modifier) private or public to the variable. Most programming languages put access modifier in front of the datatype  specifier like private string name but in Solidity, we put access modifier between datatype specifier and the variable name, as follows:

string private myName; 
String public myName
uint private MyAge;
uint public  MyAge;

Writing the Smart Contract Code

Now launch Remix IDE. Create your first smart contract by clicking on the little + button on the far left corner of the Remix IDE.  A new dialog will appear and you can create a new Solidity file.

After creating the new file, a new window will appear on a new tab displaying your new file. The file will also be show on the left pane of the IDE under the browser.

Now, let’s create a new contract by entering the following code into the Remix IDE.

pragma solidity ^0.4.24;

contract myContract {
    string private name;
    uint private age;
}

The first line inside the contract itself declares a string name and an unsigned integer variable called age.

We have already created a simple smart contract though it does not do anything yet. You can compile and deploy it if you want to.

Now let’s add some functions to the smart contract

pragma solidity ^0.4.24;

contract myContract {
    string private name;
    uint private age;
   
 function setName(string newName) public{
    name = newName;
 }

  function getName() public view returns (string){ 
    return name; 
  } 
  
  function setAge(uint newAge) public{
      age=newAge;
  }
  function getAge() public view returns (uint){ 
      return age;
  }
}

We create the function setName to allow the user inputs a string value. Set the modifier to public as we want to permit everyone to see it. Otherwise, when you deploy the contract you will not be able to view the function on the Remix IDE.

To return the value of name entered by a user, we create the function getName

The view keyword in public view returns is  the replacement for constant. It indicates that the function will not alter the storage state in any way.

Next, we create the function setAge by declaring  a parameter newAge as an unsigned integer. The setAge function will allow the user input an integer value when you deploy the contract.

To return the value of age entered by the user,  we create the function getAge

Now compile and deploy the Remix IDE, the output is shown in the following figure:

Deployed Contract

When you deploy the contract, a transaction is executed from your wallet address to the contract. A gas fee is charged in the process. You can view the transaction on Etherscan, as shown below:

When you click on the setName function, a transaction will also occur. You need to wait for the transaction to complete before you click on the getName function. You can see that whatever you entered in the setName box will appear on the getName box. You can do the same for the setAge and getAge functions.