How to Develop Smart Contracts: A Comprehensive Guide by SumatoSoft Experts

Contents
how to develop a smart contracthow to develop a smart contract

Hi! The other day, the marketing team approached me and asked to share my expertise. I’m not really into writing articles or any marketing activities, but the marketing team was really persuasive. I work as a blockchain developer at SumatoSoft, and here I’m going to tell you a story about the way I’m developing smart contracts.

This article, focusing on using the Solidity language for the Ethereum network, is structured into two main sections—’ Basics’ and ‘Practical Applications.’ Feel free to jump to the section that interests you most.

The Basics of Smart Contracts

the basics of smart contract development

In this section, I’ll cover the very basics of smart contracts. If you are familiar with the Basics, go to the Practical part (use the navigation bar on the right side). This part is about the following staff:

  • Definition – what smart contracts are and how they work.
  • Strengths and weaknesses – why smart contracts are considered effective Understand the pros and cons that come with implementing smart contracts.
  • Consensus algorithms – explore the mechanisms that enable decentralization and uphold contract integrity.

For those want to get familiar with the blockchain technology in general, I wrote another great article: 

Basics: Definition of a Smart Contract 

A smart contract is a self-executing contract, meaning it:

  1. carries out actions automatically without human involvement when predefined conditions are met;
  2. the terms of the agreement between parties are directly written into lines of code. 

Smart contracts serve as a digital evolution of traditional legal and financial documents, offering the advantage of automation and eliminating the need for intermediaries like controllers or arbitrators.

Nick Szabo first conceptualized smart contracts in 1994. However, it wasn’t until 2008, with the advent of blockchain technology and the Bitcoin protocol, that smart contracts saw practical application. The real breakthrough came with the Ethereum network, which offered what is known as “Turing-complete” functionality. In simple terms, a Turing-complete system can perform any computational task, enabling complex conditions and calculations to be embedded within the contract itself.

As of now, the smart contracts market size was valued at USD 684.3 million in 2022. Smart contracts have widespread applications and have even gained legal recognition in various jurisdictions around the world:

  • Britain – Smart contracts have legal validity.
  • U.S. States – Arizona, Nevada, Tennessee, and Wyoming have enacted laws recognizing smart contracts.
  • Malta – Known as the “Blockchain Island,” Malta has laws that recognize the legality of smart contracts.
  • Singapore – Passed legislation to enable the use of digital contracts, including smart contracts.
  • United Arab Emirates – Specifically, Dubai aims to run all its governmental transactions on blockchain technology by 2021, including the use of smart contracts.
  • Switzerland – Has a favorable legal environment for blockchain and smart contract development.
  • Estonia – Pioneering digital identification and blockchain, Estonia also recognizes the legality of smart contracts.
  • Australia – The government is exploring the use of blockchain for smart contracts in various sectors.

The list sounds impressive, right? Well, let’s go a little deeper.  

Basics: Strengths and Weaknesses of Smart Contracts

strength and weakness

Strengths

  1. Autonomy and absence of intermediaries – smart contracts use mathematical algorithms to automatically execute conditions when verified data is received. This negates the need for human approvals or third-party validations.
  2. Cost-efficiency – the automation and absence of intermediaries in smart contracts often lead to lower transaction costs.
  3. Accuracy – automation reduces the risk of errors that are common in manually filled-out forms, provided that the smart contract code is written correctly.
  4. Security – transactions within a blockchain are encrypted and require verification by network nodes, making them secure against fraud to a large extent.
  5. Transparency – the code for smart contracts is generally publicly available. This allows anyone to review the underlying code. That means that developers need to put a lot of effort into the security aspect.
  6. Immutability – this characteristic of smart contracts is both a blessing and a curse. The positive effect is that once added to a shared network, a smart contract cannot be altered. This feature reduces opportunities for fraudulent manipulation.
  7. Accessibility – companies across different sectors, including household names like Nike, engage with smart contracts for a variety of applications, such as cryptocurrency payments, issuance of Non-Fungible Tokens (NFTs), and secure data storage.

Weaknesses

  1. Risk of fund loss – Given the high financial stakes, even minor user mistakes like the wrong amount or recipient address entered lead to irreversible transfer. Moreover, developer oversights, such as a bug in the contract code, could similarly result in a substantial loss of funds stored within the contract.
  2. Complexity – smart contract programming includes the use of familiar programming languages like Python, Java, and Rust and contract-based programming languages like Solidity which is quite similar to JS and C++. Nevertheless, smart contracts represent a relatively new technology that requires additional studying.
  3. Weak legal regulation – Some countries like Egypt, Morocco, Algeria, and China have outright banned smart contracts and blockchain technology, while others restrict their use within certain sectors like banking.
  4. Low scalability – Unlike traditional applications, scaling smart contracts is more challenging. Any significant changes often require migrating to a new smart contract altogether.
  5. Immutability – while it offers security against unauthorized changes, it also means that errors or bugs in the code cannot be easily corrected. This immutability can lead to complications, especially if the contract needs to adapt to new laws or unforeseen situations.
  6. Low scalability – as another consequence of the immutability, any alterations, updates, or feature additions generally require the creation of a new smart contract. This makes iterative development and scalability more challenging and resource-intensive.

Basics: Consensus Algorithms

consensus algorythms

The term “consensus” in “consensus algorithms” denotes the process of reaching an agreement among a group of participants in a network. In the context of blockchain technology, this refers to the synchronization of all the nodes in the network to agree upon the validity and order of transactions. Any transaction or record (including smart contract) must be verified by nodes or validators by following a specific process dictated by the network’s chosen consensus algorithm.

I want to briefly describe here 6 consensus algorithms I work with. I’ll cover the most noticeable positive and negative characteristics from my perspective. If you need more details on any specific algorithm, please Google it. 

#1. Proof of Work (PoW)

Nodes (you know them as miners) solve complex mathematical problems to validate transactions and create new blocks.

Pros

  • Security – highly secure due to the computational work required.
  • Decentralization – anybody can participate, ensuring a decentralized network.

Cons

  • Energy-intensive – In 2015, it was estimated that a single Bitcoin transaction required an amount of electricity comparable to the energy needed to power 1.57 American homes a day. Things got better but ecologists still aren’t happy, continuing to publish articles like “Crypto is killing the planet”.
  • Scaling issues – not highly scalable in terms of transaction throughput. Ethereum network moved from PoW to PoS in 2022 because of that. 

#2. Proof of Stake (PoS)

Nodes (these are not miners, they are validators) are chosen to validate transactions based on the number of coins they hold and are willing to “stake” as collateral.

Pros

  • Energy-efficient – much less energy-intensive than PoW.
  • Scalability – generally more scalable and faster than PoW.

Cons

  • Wealth concentration – those with more coins have more decision-making power.
  • New coins – fewer opportunities for smaller participants to earn new coins.

#3. Delegated Proof of Stake (DPoS)

A variation of PoS where coin holders vote for a few nodes to do the validating.

Pros 

  • Efficiency – more efficient and faster than basic PoS and PoW.
  • Democratic – the voting system can be considered more democratic compared to PoS. 

Cons

  • Centralization risk – fewer nodes involved in validation may lead to some level of centralization.
  • Voting complexity – the voting process could be complicated for ordinary users.

#4. Practical Byzantine Fault Tolerance (PBFT)

In a network of communicating nodes, the algorithm tolerates the failure of some nodes.

Pros

  • High throughput – very fast, capable of handling thousands of transactions per second.
  • Low latency – transactions are confirmed in a few seconds.

Cons

  • Centralization risks – often used in private blockchains, which are more centralized.
  • Complexity – more complex to implement compared to PoW and PoS.

#5. Proof of Authority (PoA)

In PoA-based networks, transactions and blocks are validated by a pre-approved set of nodes referred to as validators. These validators are identifiable and their authority is established by the network.

Pros

  • Efficiency – PoA is typically fast and requires less computational power, making it highly efficient.
  • Simplified validation – with trusted, pre-approved validators, the process is less complex and quicker.

Cons

  • Centralization – the network relies on a few trusted nodes, which implies network centralization.
  • Trust requirement – the system hinges on the trustworthiness of the validators, which can be a point of vulnerability if that trust is misplaced.

#6. Proof of History (PoH)

Proof of History (PoH) is an algorithm unique to the Solana blockchain. While most blockchains rely on a sequence of blocks to establish the order of transactions, PoH creates a cryptographic “timestamp,” so to speak, for each transaction or operation. PoH stamps each event or transaction to create an unalterable historical record. It can be likened to a meticulously maintained diary or accountant’s ledger where each entry is precisely timestamped.

Pros

  • Speed – extremely fast and scalable.
  • Energy efficiency – more energy-efficient compared to PoW.

Cons

  • It’s a dark horse among algorithms – being relatively new, its long-term viability is not yet proven.
  • Specialized use-case – primarily used in the Solana blockchain, limiting its widespread adoption.

Practice or How to Develop Your Own Smart Contract

From there, I’ll deep down into the technical aspect. The section will have little value to you if you aren’t planning to implement the information. I’ll cover: 

  • The tech stack of popular blockchain platforms.
  • Useful development tools including wallets, IDE, testing tools, libraries, and more. 
  • The development process itself. 

Practice: The Tech Stack of Popular Blockchain Platforms 

Below are popular blockchain platforms, the consensus algorithms they employ, and the programming languages supported for developing DApps and smart contracts.

  1. Ethereum (PoS) – Solidity, Vyper. In 2020, Ethereum transitioned from PoW to PoS with its Ethereum 2.0 upgrade.
  2. Solana (PoH) – Rust, C/C++
  3. Cardano (PoS) – Plutus, Haskell.
  4. Avalanche (PoS) – Solidity.
  5. Tron (DPoS) – Solidity, Java.
  6. EOS (DPoS) – C/С++
  7. Tezos (PoS) – LIGO (Pascal), SmartPy (Python).
  8. BNB (PoS + PoA) – Solidity. Binance Chain uses Tendermint BFT (which can be considered PoA), while Binance Smart Chain uses a PoS variant. Both support Solidity for smart contracts.

Practice: Smart Contract Development Tools

practice of developing a smart contract

Given the broad scope of this topic and my personal preferences, I’ll initially focus on tools for developing smart contracts on Ethereum using Solidity, as it’s one of the most popular platforms. However, it’s worth noting that some of these tools also support other networks and programming languages.

Tool #1: Wallet

A crypto wallet is indispensable for smart contract development. While you can technically write a smart contract without a wallet, deploying the contract, conducting initial tests, and integrating it with a frontend are virtually impossible without one.

  1. MetaMask – MetaMask is a highly popular wallet primarily designed for Ethereum and Ethereum-compatible blockchains like Binance Smart Chain and Polygon. Easy to use, it’s widely supported across various services, including marketplaces like OpenSea, Mintable, and Rarible, as well as cryptocurrency exchanges. Available as a browser extension for Chrome and Firefox, it also offers a mobile application. It accommodates a wide range of transactions, including asset exchanges, purchases, contract deployments, and NFT transactions.
  2. Phantom – Phantom is a multi-network wallet with support for Solana and Ethereum blockchains. While it may also support Polygon, it’s advisable to check the latest updates for the most current information. The wallet is accessible both as a browser extension and a mobile application. It is particularly prevalent on Solana-based platforms like SolScan and SolSea.
  3. WalletConnect – WalletConnect is not a wallet per se but functions as a connectivity tool. It enables the linking of mobile wallet applications to decentralized applications (DApps) through QR code scanning. This is particularly useful as not all wallets are directly supported by every DApp platform, offering a flexible approach to secure connectivity.

Tool #2: Integrated Development Environment (IDE) 

An Integrated Development Environment (IDE) is a comprehensive toolset that facilitates the process of developing, testing, and deploying programs. In the context of smart contract development, various types of IDEs can be utilized:

Online IDEs:

  • Remix – Remix is an online IDE explicitly designed for creating, testing, and deploying smart contracts written in Solidity. The platform is continuously updated with new features to improve its usability and capabilities.
  • Etherlime Playground – this IDE is designed specifically for Etherlime, a development and deployment framework based on ethers.js. It allows for quick prototyping of smart contracts. Etherlime is commonly used locally and integrates with popular IDEs like VSCode.
  • Superblocks Lab – it provides a user-friendly interface for building smart contracts and decentralized applications. The IDE supports both Solidity and Vyper.
  • EthFiddle – aimed at beginners, it’s a simpler IDE that allows for quick prototyping and sharing of Solidity code snippets.

Local IDEs:

For more intricate development tasks, developers typically opt for local IDEs that support the programming language in which the smart contract is written. Popular local IDEs include:

  • VSCode – highly versatile and commonly used for various programming languages.
  • IntelliJ IDEA – known for its robust set of features tailored for Java but also supports other languages.
  • Atom – an open-source editor that’s highly customizable.
  • PyCharm – ideal for Python development but also offers some support for other languages.

Each IDE has its unique strengths, but personally, I find VSCode to be the most well-rounded option. After selecting an IDE, additional frameworks for testing and deployment are usually installed, as described in subsequent sections. However, it’s worth noting that developers are free to mix and match tools and frameworks according to their specific needs and preferences.

Tool #3: Testing Tools

Testing smart contracts can be done in various ways: you can use JavaScript scripts, other smart contracts, or dedicated IDEs like Remix. 

For unit testing with JavaScript, popular frameworks include: 

  • Truffle
  • Hardhat
  • Waffle
  • Foundry

These frameworks offer command-line interfaces (CLI) that facilitate the building, testing, debugging, and deployment of smart contracts. In addition to these frameworks, helper libraries like:

  • ethers js
  • web3 js

These are often used in tandem with testing libraries like:

  • Chai
  • Mocha

Many developers currently favor a Hardhat and ethers.js stack, often accompanied by testing libraries like Chai or Mocha. Personally, I prefer using Hardhat, ethers.js, Chai, and the solidity-coverage library. I’ve found this combination to offer greater stability and fewer unexpected bugs compared to using web3.js and Truffle.

Tool #4: Support Tools

Now, let’s talk about a range of tools that provide flexibility, precision, and convenience in different aspects of blockchain development. A detailed explanation of how developers apply these tools is described in the Development Process section. 

Libraries with Reusable Code

These libraries offer a repertoire of tried-and-tested code segments that can be directly implemented into your projects, saving development time.

  • OpenZeppelin – an open-source library that provides thoroughly tested code, covering ERC standards and test helpers.

Local Blockchains

Local blockchains emulate a blockchain environment on your local machine, facilitating more controlled testing.

  • Ganache – simulates a local blockchain for efficient testing, command execution, and process inspection.

Smart Contract Auditing Tools

These tools conduct security assessments of your smart contracts to identify vulnerabilities and recommend fixes.

  • Slither – a static analysis tool for scrutinizing smart contracts.
  • Ethlint – analyzes your Solidity code for stylistic and security concerns.

Node Providers/Managers

Smart contracts usually interact with blockchain network nodes. While you can develop a decentralized application without directly linking it to blockchain nodes, you’ll need to establish such a connection for features that demand up-to-the-minute blockchain data, higher security measures, or more reliable smart contract functionality. These services provide reliable access to reputable nodes. 

  • Infura – provides scalable and reliable access to Ethereum and IPFS.
  • Alchemy – operates similarly to Infura but uses its own ‘supernode’ architecture for additional functionalities.

Read more info about Infura and Alchemy on theur official websites: Infura, Alchemy

Smart Contract Generators (No-code/Low-code)

If you prefer not to write a contract from scratch, you have alternatives. You can use a generator or a Software Development Kit (SDK) to facilitate the creation process. These tools offer predefined functions and templates, significantly speeding up your development timeline.

  • Bueno – specializes in generating smart contracts for selling NFTs.
  • Bunz – allows function-specific smart contract generation, deployment, and node connectivity.
  • Thirdweb – a comprehensive low-code platform supporting a full cycle of smart contract creation, IPFS, and Web3 UI.
  • OpenZeppelin – also serves as a smart contract generator, offering function-based contract templates.

Practice: Staff You Need to Know

When developing smart contracts for specific sectors like NFTs, gaming, and finance, it’s crucial to go beyond the basics. Along with understanding the programming language and blockchain principles, other elements such as specific ERC standards and data storage methods come into play. If you are a newbie in smart contracts, here are two useful links you should probably save: 

You’ll have to study different staff depending on the application you are planning to develop: 

For NFT: 

  • ERC standards – familiarize yourself with the relevant ERC standards like ERC-721 or ERC-1155.
  • Minting – understand both lazy minting and general minting procedures.
  • Marketing techniques – get to know methods like airdrops for promotion.
  • Data storage – options like IPFS for storing associated images or metadata.

For Gaming: 

  • ERC standards
  • Randomization techniques – important for gameplay elements.
  • User access management – control who can do what within your smart contract.
  • Ownership transfer – handling tokens or in-game items.
  • Interfaces – For reusing functions in multiple smart contracts.
  • Upgradability – to allow for future changes to the contract.

For Finance & Legal Contracts: 

  • Legal validity – study the legal standing of smart contracts in your jurisdiction.
  • Vesting schedules – for distributing tokens or assets over time.
  • On-chain governance – allows for voting on changes to the contract.
  • Security measures – such as ZK-proofs, which may require a strong grasp of cryptography and higher mathematics. So, good luck =)

Practice: The Development Process for Smart Contracts and DApps

smart contract development process

Let’s put everything into practice. In this section, I’ll go through the smart contract development using the Solidity language for the Ethereum network:

Step #1: Installing and Configuring the Necessary Tools

The foundational step is to have a cryptocurrency wallet that supports smart contracts. MetaMask is widely used and supports Ethereum-based smart contracts.

Then, you have three options: 

  1. quick and simple via Remix (recommended);
  2. more complex and flexible using local IDE and a bunch of other staff;
  3. the easiest and the least flexible using contract generators (highly not recommended for beginners). 

Quick and Simple via Remix

  • What: Remix is an online IDE tailored for Ethereum smart contracts.
  • Best for: Beginners or those who need to prototype quickly.

Advanced Local Setup

  • What: This involves setting up a local development environment.
  • Tools: IDEs like VSCode, testing frameworks like Truffle or Hardhat, and other auxiliary frameworks according to your project’s needs.
  • Best for: More experienced developers seeking a robust environment.

Utilizing Smart Contract Generators

  • What: These are platforms or libraries that offer pre-written contract logic.
  • Example: OpenZeppelin’s Contracts Wizard.
  • Best for: Those who prefer the simplest route, albeit with limited flexibility.

Here we will look at development using Solidity for the Ethereum network.

Step #2: Writing the Contract Logic

Here’s an example of a simple Solidity smart contract implementing a counter. This example is sourced from solidity-by-example.org.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract Counter {
uint public count;

// Function to get the current count
function get() public view returns (uint) {
    return count;
}
// Function to increment count by 1
function inc() public {
    count += 1;
}
// Function to decrement count by 1
function dec() public {
    // This function will fail if count = 0
    count -= 1;
}

Some comments: 

  • License comment (// SPDX-License-Identifier: MIT) – this comment indicates the software license. It’s required for deployment and lends the contract legal standing.
  • Compiler version (pragma solidity ^0.8.17) – specifies the version of the Solidity compiler to use.
  • Contract declaration (contract Counter) – declares a new smart contract named Counter.
  • State variable (uint public count) – declares a state variable that holds the count value.
  • Functions (get, inc, dec) – three basic functions: get retrieves the current count, inc increments the count, and dec decrements the count.

Solidity syntax may resemble that of JavaScript or C++. If you have experience with these languages, you’ll find certain aspects of Solidity easier to grasp. However, it’s important to note that despite appearances, Solidity has unique features and complexities.

Step #3: Testing and Validation

Let’s start by discussing a sample test code. Here’s how a unit test for this function might look in a Hardhat project using ethers.js and Chai:

describe("Counter Contract", () => {
 it("Increment works", async () => {
   const counterContract = await ethers.deployContract("Counter");
   const countBefore = await counterContract.get();
   await counterContract.inc();
   const counterAfter = await counterContract.get();
   expect(countBefore.toString()).to.equal((counterAfter + 1).toString());
 });
});

That’s how the tests will look like using Hardhat, ethers.js, and Chai. A typical test for the increment method would set up the test environment using ‘describe’ and ‘it’ methods. After deploying the contract, it would capture the initial counter value, perform the increment operation, and then validate the new counter value to ensure it has been correctly incremented. Note that this example simplifies the scenario by not considering factors like handling Big Numbers or importing additional libraries.

Aiming for a test coverage of at least 95% is generally advisable. However, in high-stakes or commercial projects, striving for 100% coverage and performing additional audits can mitigate significant risks. You can order the audit from the appropriate companies or, in the case of a small internal project, you can use the libraries from the list above.

Step #4: Deploy 

You have a couple of options here. 

If your needs are straightforward and you don’t require a connection to a specific blockchain node, Remix is a convenient choice as it offers built-in functionalities for contract deployment. 

On the other hand, if your project demands more advanced features, both Truffle and Hardhat offer detailed code examples for contract deployment in addition to their unit testing capabilities.

SumatoSoft’s Expertise in Blockchain Development

We’re a team of seasoned professionals with over 5+ years of experience in blockchain development and blockchain consulting services—guided by senior experts boasting 7-10 years in the field. The text from the article must speak for itself about our expertise in blockchain development. Still, here is additional information about SumatoSoft:

  • 12 years on the market of software development. 
  • 250 successful projects in our portfolio built in 27 countries for 11 business domains.  
  • We work honestly and transparently. We communicate weekly, run demos of the work done, provide several contact points, send timesheet reports every month even if you don’t request them, explain potential risks and help to handle them, advise on the decisions, and help to avoid unnecessary costs. 
  • No language barrier. There is no language barrier, as our employees speak English  – at least B1 level for engineers and C1 level for managers.
  • We specialize in digitizing businesses For 12 years now we help our Clients to digitalize their businesses by providing relevant software solutions and implementing modern technologies like IoT, blockchain, Big Data, Machine Learning. 

If you have a blockchain project, feel free to contact us

Final Thoughts: Navigating the Legal Landscape of Blockchain and Its Future

To be frank, legal aspects aren’t my forte, but as of 2024, there are numerous unresolved questions surrounding the legality of blockchain and smart contracts. These range from dispute resolution and intellectual property rights to issues in international trade. Globally, countries seem to fall into one of three categories:

  • Those that have outright rejected blockchain technology.
  • Those actively seeking solutions to these legal quandaries, with partial implementations in place.
  • Those that have already enacted laws to legitimize smart contracts, as highlighted in the opening chapter. However, this doesn’t imply that smart contracts are in widespread use in these nations.

For a more in-depth analysis, you can refer to this article.

That’s it for now. I hope you found the article helpful.

Contents

Let’s start

You are here
1 Share your idea
2 Discuss it with our expert
3 Get an estimation of a project
4 Start the project

If you have any questions, email us info@sumatosoft.com

    Please be informed that when you click the Send button Sumatosoft will process your personal data in accordance with our Privacy notice for the purpose of providing you with appropriate information. This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

    Vlad Fedortsov
    Sales Department Lead
    Book consultation
    Thank you!
    Your form was successfully submitted!
    If you have any questions, email us info@sumatosoft.com

      Please be informed that when you click the Send button Sumatosoft will process your personal data in accordance with our Privacy notice for the purpose of providing you with appropriate information. This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

      Vlad Fedortsov
      Sales Department Lead
      Book consultation
      Thank you!
      Your form was successfully submitted!