solidity-cheatsheet

我要开发同款
匿名用户2021年11月30日
97阅读

技术信息

系统类型
Web3
授权协议
MIT License

作品详情

SolidityCheatsheetadBestpracticesMotivatio

ThisdocumetisacheatsheetforSoliditythatyoucausetowriteSmartCotractsforEthereumbasedblockchai.

ThisguideisotitededtoteachyouSolidityfromthegroudup,buttohelpdeveloperswithbasickowledgewhomaystruggletogetfamiliarwithSmartCotractsadBlockchaibecauseoftheSoliditycoceptsused.

Note:IfyouhavebasickowledgeiJavaScript,it'seasiertolearSolidity.

TableofcotetsSolidityCheatsheetadBestpracticesMotivatioTableofcotetsVersiopragmaImportfilesTypesBooleaItegerAddressbalacetrasferadsedcalldelegatecallcallcodeArrayFixedbytearraysDyamicbytearraysEumStructMappigCotrolStructuresFuctiosStructureAccessmodifiersParametersIputparametersOutputparametersCostructorFuctioCallsIteralFuctioCallsExteralFuctioCallsNamedCallsUamedfuctioparametersFuctiotypeFuctioModifierVieworCostatFuctiosPureFuctiosPayableFuctiosFallbackFuctioCotractsCreatigcotractsusigewCotractIheritaceMultipleiheritaceCostructorofbaseclassAbstractCotractsIterfaceEvetsLibraryUsig-ForErrorHadligGlobalvariablesBlockvariablesTrasactiovariablesMathematicaladCryptographicFuctiosCotractRelatedVersiopragma

pragmasolidity^0.5.2;willcompilewithacompilerversio>=0.5.2ad<0.6.0.

Importfiles

import"fileame";

import*assymbolNamefrom"fileame";orimport"fileame"assymbolName;

import{symbol1asalias,symbol2}from"fileame";

TypesBoolea

bool:trueorfalse

Operators:

Logical:!(logicalegatio),&&(AND),||(OR)Comparisos:==(equality),!=(iequality)Iteger

Usiged:uit8|uit16|uit32|uit64|uit128|uit256(uit)

Siged:it8|it16|it32|it64|it128|it256(it)

Operators:

Comparisos:<=,<,==,!=,>=ad>Bitoperators:&,|,^(bitwiseexclusiveor)ad~(bitwiseegatio)Arithmeticoperators:+,-,uary-,uary+,*,/,%,**(expoetiatio),<<(leftshift)ad>>(rightshift)Address

address:HoldsaEthereumaddress(20bytevalue).addresspayable:Sameasaddress,buticludesadditioalmethodstrasferadsed

Operators:

Comparisos:<=,<,==,!=,>=ad>

Methods:

balace<address>.balace(uit256):balaceoftheAddressiWeitrasferadsed<address>.trasfer(uit256amout):sedgiveamoutofWeitoAddress,throwsofailure<address>.sed(uit256amout)returs(bool):sedgiveamoutofWeitoAddress,retursfalseofailurecall<address>.call(...)returs(bool):issuelow-levelCALL,retursfalseofailuredelegatecall<address>.delegatecall(...)returs(bool):issuelow-levelDELEGATECALL,retursfalseofailure

Delegatecallusesthecodeofthetargetaddress,takigallotheraspects(storage,balace,...)fromthecalligcotract.Thepurposeofdelegatecallistouselibrarycodewhichisstorediaothercotract.Theuserhastoesurethatthelayoutofstorageibothcotractsissuitablefordelegatecalltobeused.

cotractA{uitvalue;addresspublicseder;addressa=address(0);//addressofcotractBfuctiomakeDelegateCall(uit_value)public{a.delegatecall(abi.ecodePacked(bytes4(keccak256("setValue(uit)")),_value));//ValueofAismodified}}cotractB{uitvalue;addresspublicseder;fuctiosetValue(uit_value)public{value=_value;seder=msg.seder;//msg.sederispreservedidelegatecall.Itwasotavailableicallcode.}}

gas()optioisavailableforcall,callcodeaddelegatecall.value()optioisotsupportedfordelegatecall.

callcode<address>.callcode(...)returs(bool):issuelow-levelCALLCODE,retursfalseofailure

Priortohomestead,olyalimitedvariatcalledcallcodewasavailablethatdidotprovideaccesstotheorigialmsg.sederadmsg.valuevalues.

Array

Arrayscabedyamicorhaveafixedsize.

uit[]dyamicSizeArray;uit[7]fixedSizeArray;Fixedbytearrays

bytes1(byte),bytes2,bytes3,...,bytes32.

Operators:

Comparisos:<=,<,==,!=,>=,>(evaluatetobool)Bitoperators:&,|,^(bitwiseexclusiveor),~(bitwiseegatio),<<(leftshift),>>(rightshift)Idexaccess:IfxisoftypebytesI,thex[k]for0<=k<Iretursthekthbyte(read-oly).

Members

.legth:read-olyDyamicbytearrays

bytes:Dyamically-sizedbytearray.Itissimilartobyte[],butitispackedtightlyicalldata.Notavalue-type!

strig:Dyamically-sizedUTF-8-ecodedstrig.Itisequaltobytesbutdoesotallowlegthoridexaccess.Notavalue-type!

Eum

Eumworksjustlikeieveryotherlaguage.

eumActioChoices{GoLeft,GoRight,GoStraight,SitStill}ActioChoiceschoice=ActioChoices.GoStraight;Struct

Newtypescabedeclaredusigstruct.

structFuder{addressaddr;uitamout;}Fuderfuders;Mappig

Declaredasmappig(_KeyType=>_ValueType)

Mappigscabeseeashashtableswhicharevirtuallyiitializedsuchthateverypossiblekeyexistsadismappedtoavalue.

keycabealmostaytypeexceptforamappig,adyamicallysizedarray,acotract,aeum,orastruct.valuecaactuallybeaytype,icludigmappigs.

CotrolStructures

MostofthecotrolstructuresfromJavaScriptareavailableiSolidityexceptforswitchadgoto.

ifelsewhiledoforbreakcotiueretur?:FuctiosStructure

fuctio(<parametertypes>){iteral|exteral|public|private}[pure|costat|view|payable][returs(<returtypes>)]

Accessmodifierspublic-Accessiblefromthiscotract,iheritedcotractsadexterallyprivate-Accessibleolyfromthiscotractiteral-Accessibleolyfromthiscotractadcotractsiheritigfromitexteral-Caotbeaccessediterally,olyexterally.Recommededtoreducegas.Accessiterallywiththis.f.ParametersIputparameters

Parametersaredeclaredjustlikevariablesadarememoryvariables.

fuctiof(uit_a,uit_b){}Outputparameters

Outputparametersaredeclaredafterthereturskeyword

fuctiof(uit_a,uit_b)returs(uit_sum){_sum=_a+_b;}

Outputcaalsobespecifiedusigreturstatemet.Ithatcase,wecaomitparameteramereturs(uit).

Multiplereturtypesarepossiblewithretur(v0,v1,...,v).

Costructor

Fuctiothatisexecuteddurigcotractdeploymet.Defiedusigthecostructorkeyword.

cotractC{addressower;uitstatus;costructor(uit_status){ower=msg.seder;status=_status;}}FuctioCallsIteralFuctioCalls

Fuctiosofthecurretcotractcabecalleddirectly(iterally-viajumps)adalsorecursively

cotractC{fuctiofuA()returs(uit){retur5;}fuctioFuB(uit_a)returs(uitret){returfuA()+_a;}}ExteralFuctioCalls

this.g(8);adc.g(2);(wherecisacotractistace)arealsovalidfuctiocalls,but,thefuctiowillbecalled“exterally”,viaamessagecall.

.gas()ad.value()caalsobeusedwithexteralfuctiocalls.

NamedCalls

Fuctiocallargumetscaalsobegivebyameiayorderasbelow.

fuctiof(uita,uitb){}fuctiog(){f({b:1,a:2});}Uamedfuctioparameters

Parameterswillbepresetothestack,butareotaccessible.

fuctiof(uita,uit)returs(uit){retura;}Fuctiotype

Passfuctioasaparametertoaotherfuctio.Similartocallbacksaddelegates

pragmasolidity^0.4.18;cotractOracle{structRequest{bytesdata;fuctio(bytesmemory)exteralcallback;}Request[]requests;evetNewRequest(uit);fuctioquery(bytesdata,fuctio(bytesmemory)exteralcallback){requests.push(Request(data,callback));NewRequest(requests.legth-1);}fuctioreply(uitrequestID,bytesrespose){//Heregoesthecheckthatthereplycomesfromatrustedsourcerequests[requestID].callback(respose);}}cotractOracleUser{Oraclecostatoracle=Oracle(0x1234567);//kowcotractfuctiobuySomethig(){oracle.query("USD",this.oracleRespose);}fuctiooracleRespose(bytesrespose){require(msg.seder==address(oracle));}}FuctioModifier

Modifierscaautomaticallycheckacoditiopriortoexecutigthefuctio.

modifierolyOwer{require(msg.seder==ower);_;}fuctioclose()olyOwer{selfdestruct(ower);}VieworCostatFuctios

Fuctioscabedeclaredvieworcostatiwhichcasetheypromiseottomodifythestate,butcareadfromthem.

fuctiof(uita)viewreturs(uit){retura*b;//wherebisastoragevariable}

Thecompilerdoesoteforceyetthataviewmethodisotmodifyigstate.

PureFuctios

Fuctioscabedeclaredpureiwhichcasetheypromiseottoreadfromormodifythestate.

fuctiof(uita)purereturs(uit){retura*42;}PayableFuctios

FuctiosthatreceiveEtheraremarkedaspayablefuctio.

FallbackFuctio

Acotractcahaveexactlyoeuamedfuctio.Thisfuctiocaothaveargumetsadcaotreturaythig.Itisexecutedoacalltothecotractifoeoftheotherfuctiosmatchthegivefuctioidetifier(orifodatawassuppliedatall).

fuctio(){//Dosomethig}CotractsCreatigcotractsusigew

Cotractscabecreatedfromaothercotractusigewkeyword.Thesourceofthecotracthastobekowiadvace.

cotractA{fuctioadd(uit_a,uit_b)returs(uit){retur_a+_b;}}cotractC{addressa;fuctiof(uit_a){a=ewA();}}CotractIheritace

Soliditysupportsmultipleiheritaceadpolymorphism.

cotractowed{fuctioowed(){ower=msg.seder;}addressower;}cotractmortalisowed{fuctiokill(){if(msg.seder==ower)selfdestruct(ower);}}cotractfialismortal{fuctiokill(){super.kill();//Callskill()ofmortal.}}MultipleiheritacecotractA{}cotractB{}cotractCisA,B{}CostructorofbaseclasscotractA{uita;costructor(uit_a){a=_a;}}cotractBisA(1){costructor(uit_b)A(_b){}}AbstractCotracts

Cotractsthatcotaiimplemetedado-implemetedfuctios.Suchcotractscaotbecompiled,buttheycabeusedasbasecotracts.

pragmasolidity^0.4.0;cotractA{fuctioC()returs(bytes32);}cotractBisA{fuctioC()returs(bytes32){retur"c";}}Iterface

Iterfacesaresimilartoabstractcotracts,buttheyhaverestrictios:

Caothaveayfuctiosimplemeted.Caotiheritothercotractsoriterfaces.Caotdefiecostructor.Caotdefievariables.Caotdefiestructs.Caotdefieeums.pragmasolidity^0.4.11;iterfaceToke{fuctiotrasfer(addressrecipiet,uitamout);}Evets

EvetsallowthecoveietusageoftheEVMloggigfacilities,whichiturcabeusedto“call”JavaScriptcallbacksitheuseriterfaceofadapp,whichlistefortheseevets.

Uptothreeparameterscareceivetheattributeidexed,whichwillcausetherespectiveargumetstobesearchedfor.

Allo-idexedargumetswillbestoredithedatapartofthelog.

pragmasolidity^0.4.0;cotractClietReceipt{evetDeposit(addressidexed_from,bytes32idexed_id,uit_value);fuctiodeposit(bytes32_id)payable{emitDeposit(msg.seder,_id,msg.value);}}Library

Librariesaresimilartocotracts,buttheyaredeployedolyoceataspecificaddress,adtheircodeisusedwithdelegatecall(callcode).

libraryarithmatic{fuctioadd(uit_a,uit_b)returs(uit){retur_a+_b;}}cotractC{uitsum;fuctiof(){sum=arithmatic.add(2,3);}}Usig-For

usigAforB;cabeusedtoattachlibraryfuctiostoaytype.

libraryarithmatic{fuctioadd(uit_a,uit_b)returs(uit){retur_a+_b;}}cotractC{usigarithmaticforuit;uitsum;fuctiof(uit_a){sum=_a.add(3);}}

功能介绍

Solidity Cheatsheet and Best practices Motivation This document is a cheatsheet for Solidity that...

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论