More
    HomeCryptocurrenciesEthereumHow to program smart contracts with Ethereum

    How to program smart contracts with Ethereum

    Ethereum is behind one of the most popular cryptocurrencies – and yet it's so much more than that. This means that crypto-money can be managed completely autonomously thanks to algorithms. But how do so-called smart contracts work and where does the journey go?


    To understand the principle of smart contracts in Ethereum, it is necessary to first take a short excursion into the world of programming languages. Common programming languages are divided into two groups: interpreted and compiled languages. In the first group, programs are written in a high-level language, which are then executed by an interpreter. Two popular examples of this are Python and JavaScript. Interpreted languages are common in many application domains (such as the web) because you can get started right away. In addition, they are very versatile and can be used on different platforms without the need for additional instrumentation.

    On the other hand, there are compiled languages in which the compiler first converts the program text into another language – often binary machine code. This binary is platform dependent and executes directly on a processor. The compiler can (and should) output special code for a processor's instruction set, for example for ARM or Intel compatible processors. Well-known representatives of this type are C and Rust.

    However, reality, as always, is more complex than these simple categories suggest. There have long been mixed forms, such as Java. The Java compiler does not translate Java code directly into "real" machine code, but into a special intermediate format. This intermediate format is in turn implemented by an interpreter – the Java Virtual Machine – of the specific processor architecture.

    Ethereum smart contracts work in a similar way. All nodes that validate Ethereum transactions and mine new currencies contain an instance of the Ethereum Virtual Machine (EVM). The yellow book, Ethereum's technical specification, defines exactly which instructions the EVM supports - and how they should be executed.

    It is an in-house development that has numerous special features:

    • Interaction with the outside world is not possible: All algorithmic decisions must be the result of the blockchain and its transactions.
    • Arithmetic is based on 256-bit values to facilitate handling of addresses and large sums of money.
    • Special operations such as hash functions are built in directly to increase performance.
    • All instructions are assigned a cost function (fuel) that roughly corresponds to the required execution time and required amount of memory. The term measurement is common in the English language.
    • Programming of EVMs

    Similar to the Java ecosystem, there are several programming languages for which EVM compilers are available. The most common language is Solidity, which superficially (syntactically) resembles JavaScript. As of late 2020, the Ethereum documentation lists two more languages: Vyper, which is based on Python, and Yul Plus, a completely independent development.

    What all these languages have in common is that they are domain-specific because, unlike general-purpose languages, they occupy a niche with special features and, in particular, a special execution environment: EVM. Of course, such domain-specific languages (DSLs) are usually a good idea to reduce the complexity of applications.

    But in the case of EVMs it doesn't make much sense. After all, despite the blockchain's lack of interaction with the outside world, it can run any algorithm, so it is (in simple terms) Turing-complete.

    So why not use an existing language and runtime? If necessary, then you will have to remove features, but you can return to a longer experience, more robust tools and - much more importantly - a wider developer base. Since the popularity of a programming language is old hat these days, it depends not only on whether you can program in it particularly concisely, safely, or dynamically, but also how easily you can access how many existing libraries and packages there are. This changing of the times is exemplified especially by JavaScript, which is often criticized for its crude semantics, but has been the most popular programming language since the millionth NPM package.

    The people behind the Ethereum specification concluded that some problems could be solved by migrating from internal development to a universal language. How practical this development is currently running on the web to establish an alternative to the best JavaScript for dogs: web assembly (WASM). It is both a universal intermediate language and a binary format combined with a specification for translators. As the name suggests, the open standard was originally conceived for the web; Meanwhile, however, other areas of application (e.g. smartphone applications) are being discussed.

    The development of WASM is led by industry giants such as Microsoft, Google and Apple. What sets the language apart is that it was designed for portability from the ground up. This can be recognized by the fact that numerous existing programming languages such as Rust, C++ or Go can now be compiled for web assembly.

    And so also a perfect basis for smart contracts? In fact, Webassembly seems to be made for this purpose. Also in the browser – the original domain for WASM – the current code needs to be tightly regulated to prevent security breaches. Also, the fact that WASM has no garbage collection, ie. the programmer has to take care of the memory management himself, guarantees the deterministic execution of the algorithms. As a bonus, there are solid and effective interpreters for various platforms.

    All of these are also criteria that are extremely important for blockchain design. Therefore, the use of Ethereum Scented Web Assembly (EWASM) is the logical goal of the long-term planning of Ethereum 2. EWASM is fully compatible with WASM, but introduces an additional interface to the blockchain to be able to control typical Ethereum operations (e.g. token transfer). For Ethereum users, interaction with EWASM smart contracts is transparent and works just like EVM contracts.

    Smart contracts in web assembly

    But what to do if you want to program a smart contract in EWASM? For one, you need a proper Ethereum network. Because as beautiful as the vision of Ethereum 2.0 is, it is just a vision. Unfortunately, there is no official testnet, but you can switch to Oasis Ethereum, which is compatible with Ethereum and to some extent offers a preview of the future Ethereum 2.0.

    You also need a programming language so you don't have to manually write assembly code. Rust offers many advantages here. Thanks to WASM support in the Rust compiler, compatible smart contracts can be generated directly from a Rust program. However, Rust is not a reasonable choice for Ethereum at the moment, as the toolchain is still too fragile. Most examples that can be found on the Internet are already out of date shortly after publication.

    That's why it's worth looking at Solidity here instead. The classic example of a smart contract in Solidity is an ERC-20 token, a standardized interface for managing every token on the Ethereum chain. By default, Ethereum uses the currency Ether. With ERC-20 tokens, you can define other currencies, for example a token that can be exchanged one-for-one for euros. Such a contract has a fixed structure. Generally, there are storage fields in the contract for:

    • The number of tokens in circulation (therefore an upper limit can be set)
    • Current account balance

    In Solidity this can be defined as follows:

    uint256 private totalSupply;
    map(address => uint256) private balances;

    function add(uint256 a, uint256 b) internal pure returns (uint256) {
    uint256 c = a + b;
    require(c>=a, "SafeMath: overflow addition");
    return c;
    }
    function sub (uint256 a, uint256 b) internal pure return (uint256) {
    require (b <= a, "SafeMath: subtract overflow");
    uint256 c = a – b;
    return c;
    }

    These two methods are used to safely add or subtract two numbers. For example, if there are not enough tokens in the source account, the transaction is aborted with an error message ("Withdrawal Overflow"). Then the actual transfer function is executed quickly:

    function transfer (
    recipient address,
    uint256 amount
    ) {
    balances[msg.sender] = sub(balances[msg.sender], amount);
    balances [ recipient ] = add ( balances [ recipient ], amount );
    }

    First, the sender's account balance is reduced, then the recipient's account balance is increased. Calling this method is always transactional: If the receiver already has too many or the sender does not have enough tokens, neither operation is performed. The above solidity code can be translated into a web assembly using the SOLL compiler.

    Deployment and other options

    This completed WASM file can be deployed on the blockchain using web3.js, as is common for Ethereum. If you want to use Oasis for this, you can configure an appropriate provider. You can work in the browser or in Node.js.

    To deploy the contract, you must create a new transaction that has not given a recipient address. The HEX-encoded string of the web assembly code is passed as data:

    const receipt = await web3.eth.sendTransaction({ from: 0, data: "0061736d ...", gas: 10000000 });
    console.log(receive.contractAddress);

    If all is well, the last line displays the address of the newly created contract:

    "0xad1c3896b09F86906030654F6e92D61bf0D24293 "

    In addition to being used on the blockchain, the WASM code generated by the compiler can theoretically be executed unchanged in the browser, provided the necessary Ethereum features are provided. Web assembly tools also offer a number of other processing options, for example the binary code can be translated to C. Therefore, it would be quite possible to use the same code in both smart contracts and classic applications.

    Conclusion

    With EWASM, the Ethereum community has set the course for putting smart contracts on a solid footing in the future. In contrast to self-made EVM, web assembly offers tangible advantages – for example, broad applicability and greater security thanks to numerous analysis capabilities.

    Different Ethereum clients already implement this alternative virtual machine, but some of them are not yet compatible with each other. Too bad the Rust toolchain hasn't been properly integrated into Ethereum yet. However, as Ethereum 2.0 development continues to progress and there is a lot of interest in web assembly, hopefully more robust tools will be available soon.

    Click on a star to rate!
    [Total votes: 3 Average rating: 5]
    Sourcepublish0x

    YOUR COMMENT

    Please enter a comment!
    Please enter your name here

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Current

    Last ones

    You may also like…