Solid smart contract Library: a portable toolbox for blockchain engineers

FISCO_ BCOS 2022-04-06 13:23:32 阅读数:283

solid smart contract library portable

Editor's recommendation :
Solidity It doesn't work as smoothly as other languages ? Safety accidents are unavoidable ? Community welcome applies to FISCO BCOS Of Solidity Smart contract Library , Easily solve all kinds of small problems of the contract , Make contract development faster and more efficient 、 Time saving and labor saving . at present , The contract library has been fully open source and fed back to the community , Welcome to co build .

The following article comes from the blockchain of Weizhong bank , Author Weizhong blockchain

After more than ten years of development, blockchain Technology , Gradually “ A prairie fire ”, Continuously take root in various industries . But at the same time , From the perspective of Technology , Blockchain application development still has a high threshold , There are many pain points . In order to improve the user experience of all links of application development , Weizhong bank will independently develop blockchain application development components WeBankBlockchain-SmartDev Full open source , Multi dimensional acceleration of blockchain application development efficiency . See the open source announcement for details 《 Blockchain application development component : Help low code development 》.

WeBankBlockchain-SmartDev It contains Intelligent contract Library components , It covers common problems from basic types to upper level business Solidity Library code , Users can make reference according to actual needs 、 Reuse . The smart contract library has been integrated into the blockchain service network designed by the top level of the National Information Center BSN、 Blockchain middleware platform independently developed by Weizhong bank WeBASE in , And in Supply Chain Finance 、 existing evidence 、 It is widely used in many business scenarios such as agriculture and animal husbandry traceability . We look forward to blockchain technology enthusiasts and partners in the open source community , Participate in the construction of , Work together to promote Solidity Smart contract library to more mature technology 、 Better ecological development .

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 :
 Insert picture description here

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 :
https://github.com/WeBankBlockchain/SmartDev-Contract/archive/refs/tags/V1.0.0.zip

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

Entering or copying code from unknown sources on the network may cause significant 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 .

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 .

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

bytesfunction 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 .

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 .

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 .

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

except LibBytesMap and LibAddressSet outside ,SmartDev-Contract The smart contract library also contains a heap 、 Stack 、 One way queue 、 The bidirectional queue 、 Two way linked list and other practical data structures .

Contract template of business scenario

For the business scenario of the upper layer , We choose the most common alliance chain landing 、 Typical deposit certificate and integral business scenarios , Provide smart contract code examples . Developers can modify the smart contract code based on their actual business scenarios , You can also refer to some codes in the scene , Expand and crop .

Scene one : Deposit scenario

Electronic data storage certificate is a record “ User authentication - Data creation - Storage - transmission ” The way of the whole process , Apply a series of security technologies to ensure the authenticity of electronic data in an all-round way 、 integrity 、 Security , It has complete legal effect in judicature .

Use blockchain smart contracts for data storage , It has the following advantages : Blockchain technology and perfect tamper proof mechanism : Use blockchain technology to preserve evidence , It further strengthens the irreversibility of the evidence . The effectiveness of evidence is recognized by the institution : The judiciary as a node in the chain , Participate in the recognition and signature of chain data , The validity of the data chain can be confirmed afterwards . The service continues to be effective : After the data is linked by consensus of many parties , Even if some consenting 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 、 Reviewer and forensics . The depositor submits an application for the deposit of certificates . Reviewer based on content , Review and sign the certificate data . In the actual business scenario , The reviewer may be involved in the multi signature process of voting and multi-party audit . When the deposit certificate is chained , The forensics party can inquire the address of the depositor at any time 、 Relevant information such as time stamp and audit details shall be verified .
 Insert picture description here

Contract outline design

First , The code is designed to separate the logic and data layers . because Solidity Smart contract language has no independent data layer , To facilitate subsequent contract expansion 、 upgrade , You need to separate the logical and data layers , Reflected in the figure below is to distinguish the data layer from the control layer .

secondly , According to the principle of single responsibility in the contract , The permission layer is introduced into the code . In an alliance chain, all nodes can freely access the data on the chain , Smart contracts provide a decorator mechanism , The contract can be controlled to designate authorized users to access .
 Insert picture description here

The specific structure is as follows :

  • Authentication: Rights contract , Used to provide basic permission control functions .
  • videnceRepository: Certificate storage data warehouse , It inherits the rights contract , All deposit data are saved in the data contract . This can play a unified storage 、 The effect of unified management .
  • RequestRepository: Request data warehouse , It stores the certificate storage data and voting request information . When the depositor starts to submit the deposit data, it will not be directly written into the deposit warehouse , But only after the signature of the reviewer is completed can it really be submitted , It can be audited by multiple parties .
  • EvidenceController: controller , Two data warehouse contracts are introduced , It can complete the interaction of all user interfaces . Contains the creation of a deposit request , The function of the reviewer to vote on request .

Scene two : Points scenario

Blockchain integration scenario refers to the alliance of multiple independent and peer-to-peer retailers , Use the public alliance chain to provide consumers with real omni-channel comprehensive consumption experience .

Introduce blockchain into the integration scenario , It has the following advantages : Blockchain technology can increase brand exposure : Multiple institutions form an integral Alliance , Points can be effectively redeemed , Realize customer resource drainage , Improve the marketing effect . Ensure the safety of points : All integral generation and circulation processes are saved to the chain , Prevent merchants from tampering and denying . Enhance user experience : Realize the circulation of points between different merchants and users 、 Interworking , More convenient .

Brief business process

Based on blockchain Technology , Multiple merchants form a points Alliance , Realize integral universal deposit and withdrawal 、 Mutual drainage of customer resources, etc . Managers deploy and manage contracts . Merchants have distribution points 、 Pull in other businesses 、 The authority to revoke the identity of the publisher . The consumer has opened an account 、 Sales Account 、 Authority to consume points and transfer points .

 Insert picture description here

Contract outline design

In the deposit contract , We introduce the idea of separating data and logic ; In the point contract , We introduce management 、 The idea of separating data and logic .

With the introduction of management contracts , The effect similar to control reversal is realized , Both control contracts and data contracts are created by management contracts ; meanwhile , The management contract can also set the address of the control contract in the data contract at any time . such , The control contract can realize smooth business logic upgrading at any time ; Separate the management contract , It is also conducive to the authority management on the chain .
 Insert picture description here

Admin: Manage and generate contracts , Control access to Data The address of the contract Controller: The contract layer exposes the controller of the service Data: Store data related to business contracts BasicAuth、IssuerRole: jurisdiction 、 Role tool contract LibRoles、LibSafeMath: jurisdiction mapping, Library of numerical calculation

Experience it now

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 ask technical questions , welcome Pay attention to this public number , Dialog reply :

【 Little helper 】

Enter the technology exchange group .

Document address
https://smartdev-doc.readthedocs.io/zh_CN/latest/docs/WeBankBlockchain-SmartDev-Contract/index.htmlGitHub

Codebase address
https://github.com/WeBankBlockchain/SmartDev-Contractgitee

Codebase address
https://gitee.com/WeBankBlockchain/SmartDev-Contract

Welcome to participate WeBankBlockchain Community building in China : If the project helps you , Welcome to light our little star ( Click on the top left of the item Star Button ). Welcome to submit the code (Pull requests). Ask questions and submit BUG. If a security vulnerability is found in the code , You can report... At the following address :https://security.webank.com/

 Insert picture description here
FISCO BCOS The code is completely open source and free download address ↓↓↓
https://github.com/FISCO-BCOS/FISCO-BCOS
 Insert picture description here

 Insert picture description here
Learn more about dry goods , Please pay attention to FISCO BCOS Official account of open source community , visit FISCO BCOS The code warehouse can download all the source code of the project :https://github.com/FISCO-BCOS/FISCO-BCOS, Welcome to the top right corner of the page star Collection , Get the latest version .

版权声明:本文为[FISCO_ BCOS]所创,转载请带上原文链接,感谢。 https://netfreeman.com/2022/04/202204061320412019.html