SolidityCheatsheetadBestpracticesMotivatio
ThisdocumetisacheatsheetforSoliditythatyoucausetowriteSmartCotractsforEthereumbasedblockchai.
ThisguideisotitededtoteachyouSolidityfromthegroudup,buttohelpdeveloperswithbasickowledgewhomaystruggletogetfamiliarwithSmartCotractsadBlockchaibecauseoftheSoliditycoceptsused.
Note:IfyouhavebasickowledgeiJavaScript,it'seasiertolearSolidity.
TableofcotetsSolidityCheatsheetadBestpracticesMotivatioTableofcotetsVersiopragmaImportfilesTypesBooleaItegerAddressbalacetrasferadsedcalldelegatecallcallcodeArrayFixedbytearraysDyamicbytearraysEumStructMappigCotrolStructuresFuctiosStructureAccessmodifiersParametersIputparametersOutputparametersCostructorFuctioCallsIteralFuctioCallsExteralFuctioCallsNamedCallsUamedfuctioparametersFuctiotypeFuctioModifierVieworCostatFuctiosPureFuctiosPayableFuctiosFallbackFuctioCotractsCreatigcotractsusigewCotractIheritaceMultipleiheritaceCostructorofbaseclassAbstractCotractsIterfaceEvetsLibraryUsig-ForErrorHadligGlobalvariablesBlockvariablesTrasactiovariablesMathematicaladCryptographicFuctiosCotractRelatedVersiopragmapragmasolidity^0.5.2;willcompilewithacompilerversio>=0.5.2ad<0.6.0.
Importfilesimport"fileame";
import*assymbolNamefrom"fileame";orimport"fileame"assymbolName;
import{symbol1asalias,symbol2}from"fileame";
TypesBooleabool:trueorfalse
Operators:
Logical:!(logicalegatio),&&(AND),||(OR)Comparisos:==(equality),!=(iequality)ItegerUsiged: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)Addressaddress: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,retursfalseofailureDelegatecallusesthecodeofthetargetaddress,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,retursfalseofailurePriortohomestead,olyalimitedvariatcalledcallcodewasavailablethatdidotprovideaccesstotheorigialmsg.sederadmsg.valuevalues.
ArrayArrayscabedyamicorhaveafixedsize.
uit[]dyamicSizeArray;uit[7]fixedSizeArray;Fixedbytearraysbytes1(byte),bytes2,bytes3,...,bytes32.
Operators:
Comparisos:<=,<,==,!=,>=,>(evaluatetobool)Bitoperators:&,|,^(bitwiseexclusiveor),~(bitwiseegatio),<<(leftshift),>>(rightshift)Idexaccess:IfxisoftypebytesI,thex[k]for0<=k<Iretursthekthbyte(read-oly).
Members
.legth:read-olyDyamicbytearraysbytes:Dyamically-sizedbytearray.Itissimilartobyte[],butitispackedtightlyicalldata.Notavalue-type!
strig:Dyamically-sizedUTF-8-ecodedstrig.Itisequaltobytesbutdoesotallowlegthoridexaccess.Notavalue-type!
EumEumworksjustlikeieveryotherlaguage.
eumActioChoices{GoLeft,GoRight,GoStraight,SitStill}ActioChoiceschoice=ActioChoices.GoStraight;StructNewtypescabedeclaredusigstruct.
structFuder{addressaddr;uitamout;}Fuderfuders;MappigDeclaredasmappig(_KeyType=>_ValueType)
Mappigscabeseeashashtableswhicharevirtuallyiitializedsuchthateverypossiblekeyexistsadismappedtoavalue.
keycabealmostaytypeexceptforamappig,adyamicallysizedarray,acotract,aeum,orastruct.valuecaactuallybeaytype,icludigmappigs.
CotrolStructuresMostofthecotrolstructuresfromJavaScriptareavailableiSolidityexceptforswitchadgoto.
ifelsewhiledoforbreakcotiueretur?:FuctiosStructurefuctio(<parametertypes>){iteral|exteral|public|private}[pure|costat|view|payable][returs(<returtypes>)]
Accessmodifierspublic-Accessiblefromthiscotract,iheritedcotractsadexterallyprivate-Accessibleolyfromthiscotractiteral-Accessibleolyfromthiscotractadcotractsiheritigfromitexteral-Caotbeaccessediterally,olyexterally.Recommededtoreducegas.Accessiterallywiththis.f.ParametersIputparametersParametersaredeclaredjustlikevariablesadarememoryvariables.
fuctiof(uit_a,uit_b){}OutputparametersOutputparametersaredeclaredafterthereturskeyword
fuctiof(uit_a,uit_b)returs(uit_sum){_sum=_a+_b;}Outputcaalsobespecifiedusigreturstatemet.Ithatcase,wecaomitparameteramereturs(uit).
Multiplereturtypesarepossiblewithretur(v0,v1,...,v).
CostructorFuctiothatisexecuteddurigcotractdeploymet.Defiedusigthecostructorkeyword.
cotractC{addressower;uitstatus;costructor(uit_status){ower=msg.seder;status=_status;}}FuctioCallsIteralFuctioCallsFuctiosofthecurretcotractcabecalleddirectly(iterally-viajumps)adalsorecursively
cotractC{fuctiofuA()returs(uit){retur5;}fuctioFuB(uit_a)returs(uitret){returfuA()+_a;}}ExteralFuctioCallsthis.g(8);adc.g(2);(wherecisacotractistace)arealsovalidfuctiocalls,but,thefuctiowillbecalled“exterally”,viaamessagecall.
.gas()ad.value()caalsobeusedwithexteralfuctiocalls.
NamedCallsFuctiocallargumetscaalsobegivebyameiayorderasbelow.
fuctiof(uita,uitb){}fuctiog(){f({b:1,a:2});}UamedfuctioparametersParameterswillbepresetothestack,butareotaccessible.
fuctiof(uita,uit)returs(uit){retura;}FuctiotypePassfuctioasaparametertoaotherfuctio.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));}}FuctioModifierModifierscaautomaticallycheckacoditiopriortoexecutigthefuctio.
modifierolyOwer{require(msg.seder==ower);_;}fuctioclose()olyOwer{selfdestruct(ower);}VieworCostatFuctiosFuctioscabedeclaredvieworcostatiwhichcasetheypromiseottomodifythestate,butcareadfromthem.
fuctiof(uita)viewreturs(uit){retura*b;//wherebisastoragevariable}Thecompilerdoesoteforceyetthataviewmethodisotmodifyigstate.
PureFuctiosFuctioscabedeclaredpureiwhichcasetheypromiseottoreadfromormodifythestate.
fuctiof(uita)purereturs(uit){retura*42;}PayableFuctiosFuctiosthatreceiveEtheraremarkedaspayablefuctio.
FallbackFuctioAcotractcahaveexactlyoeuamedfuctio.Thisfuctiocaothaveargumetsadcaotreturaythig.Itisexecutedoacalltothecotractifoeoftheotherfuctiosmatchthegivefuctioidetifier(orifodatawassuppliedatall).
fuctio(){//Dosomethig}CotractsCreatigcotractsusigewCotractscabecreatedfromaothercotractusigewkeyword.Thesourceofthecotracthastobekowiadvace.
cotractA{fuctioadd(uit_a,uit_b)returs(uit){retur_a+_b;}}cotractC{addressa;fuctiof(uit_a){a=ewA();}}CotractIheritaceSoliditysupportsmultipleiheritaceadpolymorphism.
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){}}AbstractCotractsCotractsthatcotaiimplemetedado-implemetedfuctios.Suchcotractscaotbecompiled,buttheycabeusedasbasecotracts.
pragmasolidity^0.4.0;cotractA{fuctioC()returs(bytes32);}cotractBisA{fuctioC()returs(bytes32){retur"c";}}IterfaceIterfacesaresimilartoabstractcotracts,buttheyhaverestrictios:
Caothaveayfuctiosimplemeted.Caotiheritothercotractsoriterfaces.Caotdefiecostructor.Caotdefievariables.Caotdefiestructs.Caotdefieeums.pragmasolidity^0.4.11;iterfaceToke{fuctiotrasfer(addressrecipiet,uitamout);}EvetsEvetsallowthecoveietusageoftheEVMloggigfacilities,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);}}LibraryLibrariesaresimilartocotracts,buttheyaredeployedolyoceataspecificaddress,adtheircodeisusedwithdelegatecall(callcode).
libraryarithmatic{fuctioadd(uit_a,uit_b)returs(uit){retur_a+_b;}}cotractC{uitsum;fuctiof(){sum=arithmatic.add(2,3);}}Usig-ForusigAforB;cabeusedtoattachlibraryfuctiostoaytype.
libraryarithmatic{fuctioadd(uit_a,uit_b)returs(uit){retur_a+_b;}}cotractC{usigarithmaticforuit;uitsum;fuctiof(uit_a){sum=_a.add(3);}}
评论