Initial experience of blockchain engineer's portable toolbox of "solidity smart contract library" of Weizhong bank

Xiang Biao 2021-04-21 13:32:26 阅读数:576

initial experience blockchain engineer portable

One 、 Brief introduction of smart contract Library

As a complete intelligent contract programming language, Turing ,Solidity Programming language development 、 Design 、 iteration 、 The logic of evolution is entirely based on blockchain , And has extensive influence and detailed documents in the field of blockchain , Supported by many blockchain underlying platforms , Among them is FISCO BCOS.

however ,Solidity Programming languages also have a number of challenges . First , Limited by the expensive resources of blockchain ,Solidity Many features that are common in other languages are discarded , For example, advanced grammar and so on . secondly , The popular Solidity Smart contract libraries are mostly developed by public chains , And FISCO BCOS There are compatibility issues . Last , The security requirement of smart contract programming is high , And it's hard to upgrade the contract , Once there's a security hole , The consequences are unimaginable .

In order to solve the above problems ,WeBankBlockchain-SmartDev-Contract Smart contract library came into being , Contains basic types 、 data structure 、 Common functions 、 Smart contract library for upper business and so on . Users can refer to the actual needs 、 Reuse . The original intention of smart contract library design is to provide scenario 、 Generalization 、 Pluggable smart contract code , So as to save the time of developing smart contract to the greatest extent , Change the shortage of smart contract tool library .

SmartDev-Contract The smart contract library is a “ Though sparrows are small , Five zang organs ” The tool class library of smart contract , adopt Solidity Of library encapsulation , To help Solidity Developers enhance the development experience , Avoid making wheels repeatedly , Let's write Solidity Language can be written as well Python The language is like that “ It's smooth ”.

SmartDev-Contract Each contract file in the smart contract library is carefully polished by the blockchain engineers of Weizhong bank , From the actual use of the scene “ Many littles make a mickle ”, It covers various aspects of business scenario development “ A nook and cranny ”, It's about developing smart contracts “10 Double Engineer ” The only way .

In terms of function ,SmartDev-Contract The smart contract Library covers the common code from the basic type to the upper business , Users can make reference according to actual needs 、 Reuse . As follows :


Two 、 Pain points and solutions

In the Solidity Language will address Type to string For example .

In the past : Turn on the search engine or github-> Search for keywords “Solidity address convert to string”-> Find relevant search results -> Copy the relevant code -> Paste it into your own smart contract code . If you can't find the relevant code , Developers have to reinvent the wheel , Time consuming and laborious at the same time , New risks may also be introduced .

Now? : Download the smart contract code base directly -> decompression -> Find the relevant library contract -> Introduce code -> Call related functions . Smart contract codebase address :

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

 Insert picture description here Test code :

pragma solidity ^0.4.24;import "./LibAddress.sol";contract Test { function get() public view returns (bytes memory) { address addr = 0xE0f5206BBD039e7b0592d8918820024e2a7437b9; bytes memory bs = LibAddress.addressToBytes(addr); return bs; }}

 Insert picture description here

It is possible for developers to introduce or copy code from unknown sources on the Internet bug. alike , Rewriting your own code may be due to lack of testing or practical verification , More prone to risk . Smart contract library provides convenience 、 mature 、 Security 、 Low cost solutions .

It hurts a little : Computation may overflow

In the development of smart contracts , Numerical problems are inevitable . however ,Solidity The built-in computing mechanism is not secure enough , Smart contract security incidents caused by computing problems are common .

SmartDev-Contract The smart contract library provides a code class library for secure computing . With uint256 For example, data type ,LibSafeMathForUint256Utils Provides Uint256 Type of related calculation operations , And ensure the correctness and security of data , Including addition 、 Subtraction 、 Multiplication 、 division 、 modulus 、 chengfang 、 Maximum 、 Minimum and average operations . Other numerical types can be implemented by reference .

LibSafeMathForUint256Utils Download address : After downloading, import what you need to use sol In file , Then it can be called LibSafeMathForUint256Utils Related methods , The details are as follows :

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、 Modulus operation 、 Multiplication

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 value 、 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 two : The conversion is not convenient enough

Numerical conversion tools

Basic data type conversion is the basic requirement of programming language .LibConverter Provide a variety of Solidity Conversion of basic data types , Developers can extend this tool to other numeric conversion types and functions .

LibConverter Download address : After downloading, import what you need to use sol In file , Then it can be called LibConverter Related methods , The details are as follows :

1、 Numeric type down conversion , for example uint256 Convert to uint8.

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

2、 The value type turns to bytes

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

3、bytes Turn to numeric type

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

address Transformation tool

address The type is Solidity One of the unique data types . In the daily logic of program operation , It often involves address And bytes and string The mutual transformation of types .LibAddress The above conversion function is realized .LibAddress Download address : After downloading, import what you need to use sol In file , Then it can be called LibAddress Related methods , The details are as follows :

address turn bytes

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

bytes turn address

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

address turn string

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

string turn address

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

Pain point three : Array operations are not rich enough

stay Solidity Array types supported by native , Sort is not supported 、 lookup 、 Compare 、 remove 、 add to 、 Flip 、 Merge 、 Many commonly used functions such as weight removal .

SmartDev-Contract The smart contract library is based on the dynamic array structure “LibArrayForUint256Utils” Common tool function implementation of . Developers can also choose their own data structure according to their own needs , Self encapsulating related tool classes .LibArrayForUint256Utils Download address : After downloading, import what you need to use sol In file , Then it can be called LibArrayForUint256Utils Related methods , The details are as follows :

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、 Deweight the array

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、 Two points search

Based on sorted arrays , Binary search is supported , Improve 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、 Remove elements

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}}

It hurts four : No string built-in operations are provided

String operation is a common operation in development , For example, get the string length 、 Case conversion, etc . In other development languages , There are usually some built-in string processing libraries . but Solidity There is no string built-in operation provided by itself , therefore , This part of the requirements can be achieved by using SmartDev-Contract Smart contract library to satisfy .

stay SmartDev-Contract Smart contract Library , For strings , We offer a wealth of features , Here are three common functions .LibString Download address : After downloading, import what you need to use sol In file , Then it can be called LibString Related methods , The details are as follows :

1、 Get string length

In the following example , It shows how to get the length of string respectively 、 Number of bytes of string :

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、 toggle case

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); }}

4、 String prefix comparison

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

Pain point five : The advanced data structure is incomplete

As a blockchain oriented language ,Solidity In order to save resources , A lot of features are cut off at the data structure level , This makes it easier to compare with regular languages , There are great differences in their use . One side ,Solidity Internally, only arrays are provided 、mapping And so on , If there are other needs , Self help is needed ; On the other hand , about mapping, The key inside only holds the hash value , Unable to get the original value of the key .

in summary , We are SmartDev-Contract Smart contract library provides enhanced support for data structure , For reference 、 Use .

Mapping mapping

In the following example , Defined a Map, Then I put three key value pairs in it . And then through the way of iteration, the key Take out , Stored 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 the iteration uint256 i = map.iterate_start(); while(map.can_iterate(i)){ emit Log(map.getKeyByIndex(i), i); i = map.iterate_next(i); } }}

address set aggregate

As a standard data structure for most advanced programming languages ,set It's a set of data structures , Each element with a unique attribute is unique .

SmartDev-Contract Smart contract library relies on dynamic array and mapping, To achieve a basic set aggregate . Besides , because Solidity Generic mechanism is not supported , Developers can refer to this tool , Implement other elements of set aggregate .

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 { // Additive elements ; addressSet.add(address(1)); // {1} // Inquire about set Number of containers uint256 size = addressSet.getSize(); require(size == 1); // Get specified index The elements of address addr = addressSet.get(0); require(addr == address(1)); // return set All the elements in addressSet.getAll(); // {0x1} // Determine whether an element exists bool contains = addressSet.contains(address(1)); require(contains== true); // Remove elements addressSet.remove(address(1)); }}

In addition to the above tools , There are many tools worth learning and applying in the open source library , Interested partners can do their own research , As shown in the figure below : Insert picture description here


Personal experience : Tools are generally collected first , And then remember what functions , And then in the application, if you can use the non repetitive wheel , Just use it ! It's fast and doesn't have to worry too much about safety issues .

Content reference :

GitHub Codebase address :

gitee Codebase address :

版权声明:本文为[Xiang Biao]所创,转载请带上原文链接,感谢。