Solid smart contract Library: a portable toolbox for blockchain engineers

Time:2021-9-21

Editor’s recommendation:
Does solidity not work as smoothly as other languages? Safety accidents are inevitable? The community welcomes the solid smart contract library for FISCO bcos, which can easily solve various small problems of the contract, making the contract development more rapid, efficient, time-saving and labor-saving. At present, the contract library has been fully open-source and fed back to the community. You are welcome to participate in the co construction.

The following article comes from Weizhong bank blockchain, author: Weizhong blockchain

After more than ten years of development, blockchain technology has gradually taken on a “prairie fire” and has been taking root in various industries. However, from a technical point of view, blockchain application development still has a high threshold and many pain points. In order to improve the user experience in all aspects of application development, Weizhong bank will fully open source the blockchain application development component webankblockchain smartdev independently developed to speed up the efficiency of blockchain application development in multiple dimensions. See blockchain application development components: helping low code development for details of the open source announcement.

The smart contract library components contained in webankblockchain smartdev cover common solid library codes from basic types to upper business. Users can refer to and reuse them according to their actual needs. The smart contract library has been integrated into the blockchain service network BSN designed by the top level of the national information center and the blockchain middleware platform webase independently developed by Weizhong bank, and has been widely used in many business scenarios such as supply chain finance, deposit certificate, agriculture and animal husbandry traceability, etc. We expect blockchain technology enthusiasts and partners in the open source community to participate in the joint construction and work together to promote the development of the solid smart contract library to a more mature technology and a more perfect ecology.

Introduction to smart contract Library

As a Turing complete smart contract programming language, the logic of development, design, iteration and evolution of solid programming language is completely based on blockchain. It has extensive influence and detailed documents in the blockchain field and is supported by many blockchain underlying platforms, including FISCO bcos.

However, there are several challenges with the solid programming language. First, limited by the expensive resources of the blockchain, solidity has omitted many common features in other languages, such as high-level syntax. Secondly, the popular solid smart contract libraries are mostly developed by the public chain, which has compatibility problems with FISCO bcos. Finally, the security requirements of smart contract programming are high, and it is difficult to upgrade the contract. Once there are security vulnerabilities, the consequences are unimaginable.

In order to solve the above problems, the webankblockchain smartdev contract smart contract library came into being, including smart contract libraries such as basic types, data structures, general functions and upper services. Users can reference and reuse according to actual needs. The original design intention of smart contract library is to provide scenario, universal and pluggable smart contract code, so as to save the time of developing smart contract to the greatest extent and change the lack of smart contract tool library.

Smartdev contract smart contract library is a tool class library of smart contract with “although sparrows are small, they have all kinds of internal organs”. Encapsulated by solid library, it aims to help solid developers improve their development experience, avoid making wheels repeatedly, and make the writing of solid language as “smooth” as writing Python language.

Each contract file of smartdev contract smart contract library is carefully polished by the blockchain engineer of Weizhong bank, and comes from the “gathering sand into a tower” in the actual use scenario, covering all kinds of “corners” in the development of business scenarios. It is the only way for the “10 times engineer” to develop smart contracts.

From a functional point of view, the smartdev contract smart contract Library covers common codes from basic types to upper business, which can be referenced and reused by users according to actual needs. The details are as follows:
Solid smart contract Library: a portable toolbox for blockchain engineers

Pain points and Solutions

Take the example of converting the address type to string in the solid language.

past times:
Open the search engine or GitHub – > search keyword “solid address convert to string” – > find relevant search results – > copy relevant code – > paste into your own smart contract code.

If the relevant code cannot be searched, the developer must rebuild the wheel, which is time-consuming and labor-consuming, and may introduce new risks.

Now?
Directly download the smart contract code library – > decompress – > find the relevant library contract – > Import code – > call relevant functions. Smart contract code base address:
https://github.com/WeBankBloc…


pragma solidity ^0.4.25;
import "./LibAddress.sol" 
contract Demo {
    ...
    address addr = 0xE0f5206BBD039e7b0592d8918820024e2a7437b9;
    bytes memory bs = LibAddress.addressToBytes(addr);
}

There may be major bugs when developers introduce or copy code from unknown sources on the network. Similarly, self rewritten code may be more prone to risk due to lack of testing or practical verification. Smart contract library provides convenient, mature, safe and low-cost solutions.

Pain point 1: calculation may overflow

In the development of smart contract, the problem of numerical calculation is inevitable. However, the built-in computing mechanism of solidity is not safe enough, and smart contract security accidents caused by computing problems are common.

The smartdev contract smart contract library provides a code class library for secure computing. Taking uint256 data type as an example, libsafemathforuint256utils provides relevant calculation operations of uint256 type, and ensures the correctness and security of data, including addition, subtraction, multiplication, division, modulus, power, maximum, minimum and average. Other numerical types can be implemented by reference.

1. Addition, subtraction, multiplication and division

function f() public view {
    uint256 a = 25;
    uint256 b = 20;
    // a + b
    uint256 c = LibSafeMathForUint256Utils.add(a,b);
    // a - b
    uint256 d = LibSafeMathForUint256Utils.sub(a,b);
    // a * b
    uint256 e = LibSafeMathForUint256Utils.mul(a,b);
    // a/b
    uint256 f = LibSafeMathForUint256Utils.div(a,b);
}

2. Modular operation, power operation

function f() public view {
    uint256 a = 25;
    uint256 b = 20;
    // a % b
    uint256 c = LibSafeMathForUint256Utils.mod(a,b);
    // a ^ b
    uint256 d = LibSafeMathForUint256Utils.power(a,b);
}

3. Maximum, minimum and average operation


function f() public view {
    uint256 a = 25;
    uint256 b = 20;
    // max(a, b)
    uint256 c= LibSafeMathForUint256Utils.max(a,b);
    // min(a, b)
    uint256 d = LibSafeMathForUint256Utils.min(a,b);
    // average(a, b)
    uint256 e = LibSafeMathForUint256Utils.average(a,b);
}

Pain point 2: conversion is not convenient enough

Numerical conversion tool

Basic data type conversion is just needed by programming language. Libconverter provides conversion of various basic types of solid data. Developers can extend this tool to other numerical conversion types and functions.

1. Numeric type down conversion, such as uint256 to uint8.


function f() public view{
    uint256 a = 25;
    uint8 b = LibConverter.toUint8(a);
}

2. Value type to bytes


function f() public view{
    uint256 a = 25;
    bytes memory b = LibConverter.uintToBytes(a);
}

3. Bytes to numeric type

function f() public view{
    bytes memory a = "25";
    int b = LibConverter.bytesToInt(a);
}

Address conversion tool

The address type is one of the data types unique to solid. In the daily program running logic, the conversion between address and bytes and string types is often involved. Libaddress implements the above conversion functions.

Address to bytes

address addr = 0xE0f5206BBD039e7b0592d8918820024e2a7437b9;
bytes memory bs = LibAddress.addressToBytes(addr);

Bytes to address

bytes memory bs = newbytes(20);
address addr = LibAddress.bytesToAddress(bs);

Address to string

address addr = 0xE0f5206BBD039e7b0592d8918820024e2a7437b9;
string memory addrStr = LibAddress.addressToString(addr);

String to address

string memory str="0xE0f5206BBD039e7b0592d8918820024e2a7437b9";
address addr = LibAddress.stringToAddress(str);

Pain point 3: array operation is not rich enough

The array types supported in solidness do not support many common functions such as sorting, finding, comparing, removing, adding, flipping, merging and de duplication.

Based on the structure of dynamic array, smartdev contract smart contract library encapsulates the common tool function implementation of “libarrayforuint256utils”. Developers can also encapsulate relevant tool classes according to their own data structure.

1. Add non repeating elements


uint[] private array;
function f() public view {
    array=new uint[](0);
    // array add element 2
    LibArrayForUint256Utils.addValue(array,2);
    // array: {2}
}

2. Merge two arrays

uint[] private array1;
uint[] private array1;
function f() public view {
    array1=new uint[](2);
    array2=new uint[](2);
    LibArrayForUint256Utils.extend(array1,array2);
    // array1 length 4
}

3. De duplication of arrays


uint[] private array;
function f() public view {
    array=new uint[](2);
    array[0]=2;
    array[1]=2;
    LibArrayForUint256Utils.distinct(array);
    // array: {2}
}

4. Sort arrays in ascending order


uint[] private array;
function f() public view {
    array=new uint[](3);
    array[0]=3;
    array[1]=2;
    array[2]=1;
    LibArrayForUint256Utils.qsort(array);  
    // array: {1,2,3}
}

5. Binary search

Based on the sorted array, it supports binary search and improves the efficiency of search.


uint[] private array;
function f() public view {
    array=new uint[](3);
    array[0]=3;
    array[1]=2;
    array[2]=1;
    uint256 key=3;
    LibArrayForUint256Utils.binarySearch(array,key);  
    // array: {true, 1}
}

6. Delete element


uint[] private array;
function f() public view {
    array=new uint[](3);
    array[0]=3;
    array[1]=2;
    array[2]=1;
    LibArrayForUint256Utils.removeByValue(array,2);  
    // array: {3, 1}
}

Pain point 4: no string built-in operation is provided

String operation is a common operation in development, such as obtaining string length, case conversion, etc. In other development languages, some built-in string processing class libraries are usually provided. However, solidity itself does not provide built-in string operation, so this part of the requirements can be met by using smartdev contract smart contract library.

In the smartdev contract smart contract library, we provide rich functions for strings. Here are three common functions.

1. Get string length

In the following examples, the length of the string and the number of bytes of the string are obtained respectively:

pragma solidity ^0.4.25;
import "./LibString.sol";
contract Test {
    function f() public{
        String memory STR = "hello";
        uint256 lenOfChars = LibString.lenOfChars(str);
        uint256 lenOfBytes = LibString.lenOfBytes(str);
        require(lenOfChars == 2);
        require(lenOfBytes == 6);
    }
}

2. Case conversion

In the following example, convert uppercase to lowercase:


pragma solidity ^0.4.25;
import "./LibString.sol";
contract Test {
    function f() public view returns(string memory)  {
        string memory c = LibString.toUppercase("abcd");// Expected to be ABCD
        return c;
    }
}

3. Equal comparison

pragma solidity ^0.4.25;
import "./LibString.sol";
contract Test {
    function f() public view {
        bool r = LibString.equal("abcd","abcd");//Expected to be true
        require(r);
    }
}

Pain point 5: incomplete advanced data structure

As a blockchain oriented language, in order to save resources, solidty has cut off many features at the data structure level, which makes its use quite different from that of conventional languages. On the one hand, solidty only provides data structures such as array and mapping. If there are other requirements, they need to be implemented by self-service; On the other hand, for mapping, the internal key only saves the hash value, and the original value of the key cannot be obtained.

To sum up, we provide enhanced support for data structure in smartdev contract smart contract library for reference and use.

Mapping mapping

In the following example, a map is defined and three key value pairs are stored in it. Then, take out the key in an iterative way and store it in the event.

pragma solidity ^0.4.25;
import "./LibBytesMap.sol";

contract Test {
    using LibBytesMap for LibBytesMap.Map;
    LibBytesMap.Map private map;
    event Log(bytes key, uint256 index);
    function f() public {
        string memory k1 = "k1";
        string memory k2 = "k2";
        string memory k3 = "k3";
        string memory v1 = "v1";
        string memory v2 = "v2";
        string memory v3 = "v3";
        map.put(bytes(k1),bytes(v1));
        map.put(bytes(k2),bytes(v2));
        map.put(bytes(k3),bytes(v3));
        //Start iteration
        uint256 i = map.iterate_start();
        while(map.can_iterate(i)){
            emit Log(map.getKeyByIndex(i), i);
            i = map.iterate_next(i);
        }
    }
}

Address set collection

As the standard data structure of most high-level programming languages, set is a set data structure, in which the element of each unique attribute is unique.

Smartdev contract smart contract library implements a basic set set based on dynamic array and mapping. In addition, because solidity does not support generic mechanism, developers can refer to this tool to implement the set collection of other elements.

pragma solidity ^0.4.25;

import "./LibAddressSet.sol";

contract Test {
    using LibAddressSet for LibAddressSet.AddressSet;
    LibAddressSet.AddressSet private addressSet;
    event Log(uint256 size);
    function testAddress() public {
        //Add elements;
        addressSet.add(address(1));
        // {1}
        //Query set container quantity
        uint256 size = addressSet.getSize();
        require(size == 1);
        //Gets the element of the specified index
        address addr = addressSet.get(0);
        require(addr == address(1));
        //Returns all elements in a set
        addressSet.getAll();
        // {0x1}
        //Determine whether the element exists
        bool contains = addressSet.contains(address(1));
        require(contains== true);
        //Delete element
        addressSet.remove(address(1));
    }
}

In addition to libbytesmap and libaddressset, smartdev contract smart contract library also includes heap, stack, one-way queue, two-way queue, two-way linked list and other practical data structures.

Contract template for business scenario

For the upper level business scenarios, we select the most common and typical deposit certificate and integral business scenarios in the alliance chain landing, and provide examples of smart contract codes. Developers can modify the smart contract code based on their actual business scenario, or refer to some codes in the scenario for expansion and tailoring.

Scenario 1: deposit scenario

Electronic data certificate is a way to record the whole process of “user authentication – data creation – storage – Transmission”. It applies a series of security technologies to ensure the authenticity, integrity and security of electronic data in an all-round way, and has complete legal effect in judicature.

Using blockchain smart contracts for data presence has the following advantages:

  • Perfect tamper proof mechanism of blockchain Technology: the use of blockchain technology to preserve evidence further strengthens the non tamperability of evidence.
  • Evidence effectiveness is recognized by institutions: as a node in the chain, judicial institutions participate in the recognition and signature of the chain data, and can confirm the authenticity and effectiveness of the data from the chain afterwards.
  • The service is continuously effective: after the data is linked by multi-party consensus, even if some consensus parties withdraw, it will not cause data loss or failure.

Brief business process

  • In the deposit scenario, three types of typical users can be abstracted: depositor, auditor and forensics. The depositor shall submit the application for deposit.
  • The auditor shall review and sign the certificate data based on the content. In the actual business scenario, the approver may involve the multi signature process of voting and multi-party approval.
  • After the deposit certificate is linked, the forensics party can query the address, time stamp, audit details and other relevant information of the depositor for verification at any time.
    Solid smart contract Library: a portable toolbox for blockchain engineers

Contract outline design

Firstly, the code is designed to separate the logic and data layers. Because the solid smart contract language does not have an independent data layer, in order to facilitate the subsequent expansion and upgrading of the contract, it is necessary to separate the logic layer from the data layer, which is reflected in the figure below.

Secondly, according to the principle of single contract responsibility, the permission layer is introduced into the code. In an alliance chain, all nodes can freely access the data on the chain. The smart contract provides a modifier mechanism to control the access of the contract to the designated authorized users.
Solid smart contract Library: a portable toolbox for blockchain engineers

The specific structure is as follows:

  • Authentication: permission contract, which is used to provide basic permission control functions.
  • EvidenceRepository: certificate storage data warehouse, which inherits the permission contract, and all certificate storage data are saved in the data contract. This can achieve the effect of unified storage and unified management.
  • RequestRepository: request data warehouse, which stores certificate storage data and voting request information. The deposit data submitted by the depositor will not be directly written into the deposit warehouse, but will not be submitted until it is signed by the reviewer. The reviewer can be multi-party.
  • EvidenceController: the controller introduces two data warehouse contracts, which can complete the interaction of all user interfaces. It includes the function of creating a certificate deposit request and the approver voting according to the request.

Scenario 2: integration scenario

Blockchain integration scenario means that multiple independent and equal retailers form an alliance and use the public alliance chain to provide consumers with a real omni-channel comprehensive consumption experience.

The introduction of blockchain in the integration scenario has the following advantages:

  • Blockchain technology can increase brand exposure: multiple institutions form a points alliance, which can effectively redeem points, realize customer resource drainage and improve marketing effect.
  • Ensure the security of points: the generation and circulation of all points are saved to the chain to prevent merchants from tampering and repudiation.
  • Improve the user experience: it is more convenient for different merchants and users to realize the circulation and exchange of points.

Brief business process

Based on blockchain technology, multiple merchants form a points alliance to realize universal deposit and withdrawal of points, mutual drainage of customer resources, etc. Managers deploy and manage contracts. Businesses have the authority to issue points, pull in other businesses and revoke the identity of issuers. Consumers have the authority to open accounts, close accounts, consume points and transfer points.
Based on blockchain technology, multiple merchants form a points alliance to realize universal deposit and withdrawal of points, mutual drainage of customer resources, etc. Managers deploy and manage contracts. Businesses have the authority to issue points, pull in other businesses and revoke the identity of issuers. Consumers have the authority to open accounts, close accounts, consume points and transfer points.
Solid smart contract Library: a portable toolbox for blockchain engineers
Contract outline design

In the deposit contract, we introduce the idea of separating data and logic; In the integral contract, we introduce the idea of separating management, data and logic.

After the introduction of management contract, the effect similar to control reversal is realized. Both control contract and data contract are created by management contract; At the same time, the management contract can also set the address of the control contract in the data contract at any time. In this way, the control contract can realize smooth business logic upgrading at any time; Separating the management contract is also conducive to the Authority Governance on the chain.
Solid smart contract Library: a portable toolbox for blockchain engineers

  • Admin: manage and generate contracts, and control the address to access data contracts
  • Controller: controller of contract layer exposed service
  • Data: store data related to business contracts
  • BasicAuth、IssuerRoleTool contract permission and role:
  • LibRoles、LibSafeMath: permission mapping, library for numerical calculation

Immediate experience

The latest codes and technical documents related to the above optimization and functions have been updated synchronously. Welcome to experience and star support. If you need to consult technical questions, please welcome the official account.[assistant]Enter the technical exchange group.

Document address:
https://smartdev-doc.readthed…

GitHub codebase address:
https://github.com/WeBankBloc…

Gitee codebase address:
https://gitee.com/WeBankBlock…

Welcome to the community building of webankblockchain:

  • If the project is helpful to you, welcome to light up our little star (click the star button at the top left of the project).
  • Welcome to submit pull requests.
  • Ask questions and submit bugs.

If a security vulnerability is found in the code, it can be reported through the following address:
https://security.webank.com/

The code of FISCO bcos is completely open source and free of charge
Download address ↓↓

https://github.com/FISCO-BCOS…

Solid smart contract Library: a portable toolbox for blockchain engineers

Recommended Today

Supervisor

Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]