Smart Contracts Explained

by Nov 18, 2022#DigitalTransformation, #HomePage

Printer Icon

What Are Smart Contracts?

A smart contract is a digital contract or agreement that executes transactions (data) automatically on the blockchain network when predetermined terms and conditions are met. It is a computer program (code) stored on a blockchain, and it allows participants to be certain of an outcome without intermediaries.

Smart contracts are suitable for many transactions that can be processed and validated by executing business logic by a network of computers in a blockchain infrastructure. Furthermore, smart contracts are immutable (cannot be changed after being deployed) and have a deterministic outcome.

Smart Contract Platform

Smart contract developers have many options when building blockchains; i.e., depending on the use case, developer may choose different platforms and approaches to deploy smart contracts.

Blockchain platforms provide a secure environment for building and running decentralized applications, abstracting details of blockchains, peer-to-peer networks, consensus mechanisms, etc.

There are open public blockchains that are permissionless as well as private blockchains (permissioned) that require information about their participants.

Ethereum is the most popular platform, a level 1 (L1) hub for deploying smart contracts in the public blockchain. It is a general-purpose, Turing-complete blockchain that runs a virtual machine (EVM) that can execute various applications and complex transactions.

Ethereum attracts the most developers in blockchain and has an unmatched demand for block space. Ethereum has its cryptocurrency, Ether, to pay for running smart contracts on the EVM. Every transaction requires payment of an execution fee called Gas, which is charged in virtual currency (Ether).

In general, implementing smart contracts depends on your requirements. For example, if working with enterprise-class distributed ledgers, you can choose a Hyperledger framework that offers a modular architecture and supports permissioned smart contracts that run in Dockers and execute in Ethereum.

Other platforms that work on top of Ethereum (aggregators)—also called Layer 2 (L2)—for building dApps include Polygon, Arbitrum, and Optimism.


Smart Contracts in
Blockchain—Architecture Components

Creating blockchain-based applications and smart contracts requires knowledge and understanding of combining components according to the properties and specifications of the blockchain. Consider that frameworks reference architecture principles uniquely. Most blockchains have the following components.

  •  Communication of peer-to-peer (P2P) networks based on a standard protocol
  • Transactions and network messages between senders and recipients
  • Clear consensus rules for validating transactions in the block
  • A state machine that executes and processes smart contracts
  • A journal or chain of blocks of verified transactions stored on each node (database)
  • Established consensus algorithms to enforce rules and produce a common state
  • Alignment of a rewards and incentives system (a metering mechanism) to pay for the computation of smart contracts
  • APIs that enable interfaces with blockchains
  • Interoperation between different blockchains

Smart Contracts and dApps

A dApp is a web application composed of a smart contract and a front-end web interface that contains storage and messaging protocol (peer-to-peer) and a platform. The smart contract is a component of a dApp or the backend that runs and manages the app in the blockchain platform. It stores the code that contains the logic and the app state.

A smart contract is the same as a dApp with a web front-end—a decentralized application. The front-end interacts with the blockchain through a wallet extension configured in the web browser via JSON RPC (web3.js.JavaScript library).

Once the code is deployed, it cannot be changed and will be open for anyone to see.

Decentralized Off-chain Storage Solutions

Some apps may have computations and data storage outside of the blockchain platform due to the high cost of Gas. Data storage can be centralized in the cloud or decentralized on a P2P storage—Inter Planetary File System (IPFS).

IPFS is a decentralized file system that works by splitting data into smaller chunks and assigning a unique fingerprint (content identifier) that works by retrieving data from multiple cryptographically hashed nodes. Many Web3 projects are being built on IPFS—decentralized web (Dweb).

Another system to access websites from a P2P system is called Swarm—it is a peer-to-peer (P2P) network node implemented in Go that creates a decentralized storage and communication service that works through an incentive system enforced through smart contracts. We can run our app from a Swarm node and build a fully decentralized application, storing the code on IPFS or Swarm.

dApp Interaction with Ethereum

The front-end app must connect to an Ethereum node to read blockchain data and send transactions. It is implemented using a JSON-RPC interface (API) transport protocol with a specification of methods and rules around the processing. As a result, it is reliable and can be used in many message environments.

dApps can connect with the blockchain using client APIs already built that provide functionality and reduce complexity. You can access Ethereum and connect instantly with IPFS with a cloud-based blockchain development tool like Infura (which is compatible with IPFS tools, frameworks, and libraries).

The application must interact with a node to broadcast transactions. Any node can broadcast requests for executing transactions and propagate the resulting change in state to the rest of the network. You can set up your node or connect using nodes provided by third parties that take care of managing the node infrastructure.

Smart Contracts and Wallet Accounts

A wallet is an application that provides a user interface to control and manage a user’s private keys and addresses, create and sign transactions, or provide functionality as a dApp.

Metamask is a popular web-based wallet application that runs as a browser extension. It is the primary user interface for managing and accessing blockchain systems. Users can connect with multiple Ethereum networks, nodes, testnets (Ropsten test networks), or private blockchains through the wallet application.

An externally owned account (EOA) provides a private key to control access to funds and contracts by users. When creating a smart contract, it is necessary to create a contract account in the wallet that is identified with a contract address to link transactions. The contract account is controlled by the logic of its code and doesn’t have private keys.

Transactions are directed to a smart contract and cause the contract to run in the blockchain and use the data as input to call a fun

Smart Contract Programming Languages

The main programming languages used to write smart contracts are Goland, Java, JavaScript, Python, Solidity, Go, and C++. However, the dominant language choice for Ethereum is Solidity, a language similar to Java and JavaScript.

On the other hand, the web front-end of dApps can be programmed with HTML, JavaScript, CSS, etc., and can interact with the blockchain platform through the wallet extensions configured in the web browser.

Smart Contract Creation

An integrated development environment (IDE) such as Remix IDE must be used to load the contract, compile the code into EVM code (bytecode), and register it in the blockchain. Remix connects with the wallet, which creates the contract transaction to be approved by the developer and submits it to the blockchain.

A contract address is generated when creating the contract transaction. It works as a recipient, sending funds or calling a function. Transactions are initiated from EOA accounts and can trigger more actions in a chain of calls to other contracts.

Transactions are executed entirely and recorded in their state after being completed. They can also be rolled back without affecting their state. A smart contract may be programmed with instructions that allow it to be deleted by the owner (self-destruct function) to stop any future transactions. Regardless, the transaction history always remains in the network due to the principle of immutability.

Smart contract programming can be done in several languages with special features, methods to call contracts, and many other considerations that are out of the scope of this article. For example, developers have to code functions and data inside contracts that require an understanding of how keywords affect the code when calling functions, specifying function arguments, internal and external visibility, payable functions, modifiers, gas estimation, error handling, access control, preconditions, adding constructors and self-destruct function, extending additional functionality, logs, etc.

Smart Contract Development Tools

Smart contract developers install a known development framework for creating Ethereum contracts. Two popular frameworks are Hardhat and Truffle. Choose a framework with the needed features or plugin system, utilities to compile and test, add-ons to build the front-end using the project repository, configuration to connect to blockchain networks and deploy contracts, integration with storage options, etc.

Smart Contracts and NFTs

NFTs are non-fungible tokens. Tokens are blockchain abstractions that represent assets, currency, rights, collectibles, identity, or other digital items. NFTs can track ownership of unique digital items (intangible) and physical objects (tangible). Non-fungible tokens (NFTs) can serve multiple purposes, are governed by consensus rules, have unique identifiers, and are not interchangeable (non-fungible).

You can achieve your needs by integrating with existing smart contracts and adding custom functionality. For example, you can create an NFT handled by a smart contract using an existing token standard, such as the ERC721 (API contract interface), which defines the minimum specifications for implementation.

ERC721 is used to represent ownership of unique tokens. Of course, an existing standard must follow the specification and implementation of its functions and behaviors. Still, it is a proven way to bring interoperability with other contracts and components of existing infrastructures, wallets, APIs, platforms, etc.

Use one of the many reference implementations in the OpenZeppelin with reusable modules and libraries. OpenZeppelin Contracts has a library for smart contract development.

Smart Contract Security
and Web3 Development Checklist

Smart contract developers follow best practices when designing, developing, and maintaining a smart contract system.

1. Identify security threats during the design phase (thread modeling) and implement security controls.
2. Utilize reusable templates, libraries, and existing standards, and evaluate the security of protocol integrations.
3. Define trust boundaries with other smart contracts.
4. Implement identity management and access control, follow least privilege principles, and restrict administrative tasks.
5. Create comprehensive documentation and test all arguments (test suite) with assumptions of expected behaviors using known testing frameworks.
6. Perform internal reviews and external audits.
7. Create security monitoring (protocol monitoring detection bots) and incentivize bug bounty programs.
8. Monitor smart contracts and components implementing oracles.
9. Practice preventative techniques to avoid vulnerabilities (reentrancy, under/overflow, etc.) and use defensive programming techniques.
10. Be sure to specify visibility on contract functions correctly.

About Us: Krasamo is a mobile-first digital services and consulting company focused on the Internet-of-Things and Digital Transformation.

Click here to learn more about our digital transformation services.