DEV Community

Cover image for Top 5 smart contract programming languages for blockchain
Matt Angelosanto for LogRocket

Posted on • Originally published at blog.logrocket.com

Top 5 smart contract programming languages for blockchain

Written by Eze Sunday ✏️

Everyone is talking about smart contracts, blockchain, decentralized finance, and cryptocurrencies. However, without developers, none of these would exist, so the demand for blockchain developers continues to surge.

Many programming languages allow you to write smart contracts. In this article, we’ll explore the top smart contract programming languages to use.

What are smart contracts?

A smart contract is a computer program that automatically executes actions according to the terms of the contract without intermediaries. For example, if you want to purchase a piece of land using a smart contract mechanism, your land ownership documents will be sent to you immediately after your payment is completed. You don’t need to trust a third-party site to transfer the ownership after making payments.

Also, you can see smart contracts in action in decentralized exchanges (DEX), like PancakeSwap, which allows you to exchange your tokens for another token. If you have BNB, you can easily exchange it for Ethereum without having to talk to customer support.

Smart contract programming languages allow you to write programs that implement smart contracts on the blockchain.

So, what are the top smart contract languages, you asked? Let’s get into it.

1. Solidity

Solidity is an object-oriented and statically-typed programming language that was designed to allow developers to create smart contracts.

Solidity is designed based on existing programming languages like C++, Python, and JavaScript, so it uses similar language structures found in these languages, most likely to make it easy for developer adoption.

Here is an example of a smart contract with Solidity:

pragma solidity ^0.8.7;

contract MyContract {

    constructor() public{

        value = "My value";
    }

    string public value;

    function get() public view returns (string memory){
        return value;
    }

    function set(string memory _value) public{
        value = _value;
    }
} 
Enter fullscreen mode Exit fullscreen mode

If you are a JavaScript or C++ developer, this will look familiar to you.

Solidity, being the first smart contract programming language, has wide market adoption and is being used to build many decentralized applications. It was developed to write smart contracts on Ethereum, and, just like Java and Java Virtual Machine (JVM), Solidity runs on the Ethereum Virtual Machine (EVM).

Advantages of programming smart contracts with Solidity

  • Solidity has a large, accessible community. Because Solidity was the first smart contract programming language and was developed solely for smart contract programming on the Ethereum network, it has gained wide community support, making it easy for new developers to get help when there are stuck
  • Solidity is Turing-complete, so it’s not limited to running just a handful of algorithms — it can be used to compute all computable functions
  • Solidity offers concepts that are available in most modern programming languages. It has functions, string manipulation, classes, variables, arithmetic operations, etc. In addition, Solidity supports mapping data structures, which act as hash tables and consist of key types and key value pairs
  • Solidity doesn’t have a steep learning curve if you already know how to program with popular programming languages like Python, C++, and JavaScript, as most of its syntax was borrowed from these languages

Disadvantages of programming smart contracts with solidity

  • Solidity is a newer language, and even though the community has been helping with library development and its tools, there’s still so much to be done in the language that you’ll have to completely implement yourself

Examples of blockchains using Solidity include Tendermint, Binance Smart Chain, Ethereum Classic, Tron, Avalanche, CounterParty, and Hedera.

2. Rust

According to Stack Overflow surveys, Rust is one of the most beloved programming languages for five years in a row.

Stack Overflow Developer Survey

Rust is a low-level statically-typed programming language that is fast and memory-efficient — in an industry where scalability is not negotiable, Rust, as a language, finds a home. Rust is a relatively new programming language with enormous power while retaining simplicity, memory efficiency, reliability, and complexity combined.

By default, Rust assumes best design and development practices and also gives you a chance to alter them if you choose to. Rust has no garbage collector, which means there would be no surprise incident (caused by the language) during the runtime.

All of these factors make Rust a great choice for programming blockchain. It’s not surprising that one of the fastest blockchains, Solana, is built with Rust at its core.

Rust's compiler has a color-coded output and an even more detailed error output to help with debugging.

In many cases, Rust shows the cause of an error and where to find it by highlighting relevant code, accompanied by an explanation. Also, in some cases, it provides a fix for the error.

Here is an example smart contract using Rust:

use borsh::{BorshDeserialize, BorshSerialize};
use near_sdk::{env, near_bindgen};
use near_sdk::collections::UnorderedMap;

#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
pub struct StatusMessage {
    records: UnorderedMap<String, String>,
}
#[near_bindgen]
impl StatusMessage {
    pub fn set_status(&mut self, message: String) {
        let account_id = env::signer_account_id();
        self.records.insert(&account_id, &message);
    }
    pub fn get_status(&self, account_id: String) -> Option<String> {
        return self.records.get(&account_id);
    }
}
Enter fullscreen mode Exit fullscreen mode

Rust contains some object-oriented features; you can create structs and data. But unlike other object-oriented languages, it does not exhibit inheritance.

Smart contracts blockchain using Rust include Solana, Polkadot, and Near Blockchain. You can find many blockchain projects built with Rust in this GitHub repository.

Advantages of programming smart contracts with Rust

  • Because Rust is a low-level programming language and is designed for efficiency, you can build decentralized applications with high throughput
  • Rust immutability allows you to write predictable programs, which is what is needed for the type of applications built on the blockchain

Disadvantages of programming smart contracts with Rust

  • Rust is a new programming language with some new concepts. It might take some time to get used to working with it, especially if you are new to programming
  • There are limited libraries for almost everything compared to other languages like Python and JavaScript
  • It’s verbose. With Rust, you’ll have to state every program construct explicitly, meaning you’ll write more code than you would in languages like JavaScript and Python

3. JavaScript

JavaScript is a general-purpose programming language, and it’s found a place in the blockchain space. Because JavaScript is an entry-level language, most blockchains tend to create a JavaScript wrapper or library to allow developers to easily jump into the ecosystem and start building amazing products as soon as possible.

Hyperledger Fabric is a blockchain that allows you to build a smart contract with a few programming languages, including JavaScript (Node.js).

Here is an example of what a smart contract looks like in HyperLedger Fabric:

'use strict';

const { Contract } = require('fabric-contract-api');
const util = require('util');

/**
 * A program to support updating values in a smart contract
 */
class UpdateSmartContractValue extends Contract

    constructor(){
        super('UpdateSmartContractValue');
    }

    async transactionA(ctx, newValue) {
        let oldValue = await ctx.stub.getState(key);
        await ctx.stub.putState(key, Buffer.from(newValue));
        return Buffer.from(newValue.toString());
    }

    async transactionB(ctx) {
      //  .....
    }

};

module.exports = UpdateSmartContractValue
Enter fullscreen mode Exit fullscreen mode

The community built web3.js, a collection of libraries that allows you to interact with Ethereum smart contracts using HTTP, WebSocket, or IPC.

The Solana Foundation also built JavaScript wrappers around Solana Rust programs that allow JavaScript developers to start building Dapps on the blockchain as soon as possible.

Several tools have been built with JavaScript to help with blockchain development, but not for the core of the blockchain, due to its weak type checking.

Advantages of programming smart contracts with JavaScript

  • It’s a popular and mature programming language with plenty of community support
  • You’ll enjoy a faster development time compared to other languages, especially newer ones

Disadvantages of programming smart contracts with JavaScript

  • Dynamic typing: for mission-critical applications like smart contracts, type safety is an important feature. JavaScript implements dynamic type safety when most developers prefer to use a statically typed language for applications that are built on the blockchain

4. Vyper

Vyper is a contract-oriented Python-like programming language that targets the Ethereum Virtual Machine (EVM). It has contract-specific features, such as event notifiers for listeners, custom global variables, and global constants.

Vyper was built to address the security issues present in Solidity. It was developed to complement Solidity, not replace it.

Vyper deliberately has fewer features than Solidity to make contracts more secure and easier to audit, and, as a result, it does not support modifiers, inheritance, inline assembly, function and operator overloading, recursive calling, infinite-length loops, and binary fixed points.

Advantages

  • Building secure smart contracts is possible and natural with Vyper, as they are less prone to attacks
  • Vyper code is human-readable. For Vyper, simplicity for the reader is more important than simplicity for the writer
  • A striking feature of Vyper is the ability to compute a precise upper limit for gas consumption related to a specific Vyper function call

Disadvantages

  • Vyper has limited support for pure functions, hence anything marked constant is not allowed to change state

If you have seen or worked with Python code, then you’ll almost be able to write Vyper code.

Here is an example from the docs, just to give you a feel of it:

class VyperContract:
    """
    An alternative Contract Factory which invokes all methods as `call()`,
    unless you add a keyword argument. The keyword argument assigns the prep method.
    This call
    > contract.withdraw(amount, transact={'from': eth.accounts[1], 'gas': 100000, ...})
    is equivalent to this call in the classic contract:
    > contract.functions.withdraw(amount).transact({'from': eth.accounts[1], 'gas': 100000, ...})
    """

    def __init__(self, classic_contract, method_class=VyperMethod):
        classic_contract._return_data_normalizers += CONCISE_NORMALIZERS
        self._classic_contract = classic_contract
        self.address = self._classic_contract.address
        protected_fn_names = [fn for fn in dir(self) if not fn.endswith('__')]
        for fn_name in self._classic_contract.functions:
            # Override namespace collisions
            if fn_name in protected_fn_names:
                _concise_method = mk_collision_prop(fn_name)
            else:
                _classic_method = getattr(
                    self._classic_contract.functions,
                    fn_name)
                _concise_method = method_class(
                    _classic_method,
                    self._classic_contract._return_data_normalizers
                )
            setattr(self, fn_name, _concise_method)

    @classmethod
    def factory(cls, *args, **kwargs):
        return compose(cls, Contract.factory(*args, **kwargs))
Enter fullscreen mode Exit fullscreen mode

5. Yul

Yul is an intermediate programming language that is compiled to bytecode for addressing the needs of different backends. The Solidity compiler has an experimental implementation that uses Yul as an intermediate language. Yul is used in stand-alone mode and for inline assembly inside Solidity.

Yul bears planned support for EVM and ewasm (Ethereum flavored WebAssembly). It is designed to be a usable common denominator of both platforms.

Yul is a great target for high-level optimization stages that can benefit both EVM and ewasm platforms equally.

Advantages to using Yul

  • Readability: programs written in Yul are readable even if the code is generated by a compiler from Solidity. Yul offers high-level constructs such as loops, function calls, and if and switch statements
  • Yul is simple to use, thanks to the translation of code from Yul code to bytecode
  • Yul uses a simple and flexible language to create contracts and is beginner-friendly
  • Yul is statically typed to avoid confusion on concepts like values and references. It has a default type that can always be omitted

Here is an example of what Yul code looks like:

object "SmartContract" {
  code {
    // Smart contract constructor
    datacopy(0, dataoffset("Runtime"), datasize("Runtime"))
    return(0, datasize("Runtime"))
  }
  object "Runtime" {
    code {
       // Runtime code
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Most Ethereum-based projects most likely already use Yul.

Disadvantages of using Yul

  • Because Yul needs to be compiled to bytecode, it requires additional time to complete the entire compilation process, thus making it time-consuming during development

Conclusion

Which programming language from the above list you should use is dependent on the blockchain you want to work on. For Ethereum blockchain, for example, Solidity is the top choice for most developers.

Of course, we expect more conventional language support and more blockchain languages to come up, as it’s still an emerging space.


LogRocket: Full visibility into your web apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx /store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

Try it for free.

Discussion (0)