ThisdocumentisacheatsheetforSoliditythatyoucanusetowriteSmartContractsforEthereumbasedblockchain.
ThisguideisnotintendedtoteachyouSolidityfromthegroundup,buttohelpdeveloperswithbasicknowledgewhomaystruggletogetfamiliarwithSmartContractsandBlockchainbecauseoftheSolidityconceptsused.
Note:IfyouhavebasicknowledgeinJavaScript,it'seasiertolearnSolidity.
TableofcontentsSolidityCheatsheetandBestpracticesMotivationTableofcontentsVersionpragmaImportfilesTypesBooleanIntegerAddressbalancetransferandsendcalldelegatecallcallcodeArrayFixedbytearraysDynamicbytearraysEnumStructMappingControlStructuresFunctionsStructureAccessmodifiersParametersInputparametersOutputparametersConstructorFunctionCallsInternalFunctionCallsExternalFunctionCallsNamedCallsUnnamedfunctionparametersFunctiontypeFunctionModifierVieworConstantFunctionsPureFunctionsPayableFunctionsFallbackFunctionContractsCreatingcontractsusingnewContractInheritanceMultipleinheritanceConstructorofbaseclassAbstractContractsInterfaceEventsLibraryUsing-ForErrorHandlingGlobalvariablesBlockvariablesTransactionvariablesMathematicalandCryptographicFunctionsContractRelatedVersionpragmapragmasolidity^0.5.2;willcompilewithacompilerversion>=0.5.2and<0.6.0.
Importfilesimport"filename";
import*assymbolNamefrom"filename";orimport"filename"assymbolName;
import{symbol1asalias,symbol2}from"filename";
TypesBooleanbool:trueorfalse
Operators:
Logical:!(logicalnegation),&&(AND),||(OR)Comparisons:==(equality),!=(inequality)IntegerUnsigned:uint8|uint16|uint32|uint64|uint128|uint256(uint)
Signed:int8|int16|int32|int64|int128|int256(int)
Operators:
Comparisons:<=,<,==,!=,>=and>Bitoperators:&,|,^(bitwiseexclusiveor)and~(bitwisenegation)Arithmeticoperators:+,-,unary-,unary+,*,/,%,**(exponentiation),<<(leftshift)and>>(rightshift)Addressaddress:HoldsanEthereumaddress(20bytevalue).addresspayable:Sameasaddress,butincludesadditionalmethodstransferandsend
Operators:
Comparisons:<=,<,==,!=,>=and>Methods:
balance<address>.balance(uint256):balanceoftheAddressinWeitransferandsend<address>.transfer(uint256amount):sendgivenamountofWeitoAddress,throwsonfailure<address>.send(uint256amount)returns(bool):sendgivenamountofWeitoAddress,returnsfalseonfailurecall<address>.call(...)returns(bool):issuelow-levelCALL,returnsfalseonfailuredelegatecall<address>.delegatecall(...)returns(bool):issuelow-levelDELEGATECALL,returnsfalseonfailureDelegatecallusesthecodeofthetargetaddress,takingallotheraspects(storage,balance,...)fromthecallingcontract.Thepurposeofdelegatecallistouselibrarycodewhichisstoredinanothercontract.Theuserhastoensurethatthelayoutofstorageinbothcontractsissuitablefordelegatecalltobeused.
contractA{uintvalue;addresspublicsender;addressa=address(0);//addressofcontractBfunctionmakeDelegateCall(uint_value)public{a.delegatecall(abi.encodePacked(bytes4(keccak256("setValue(uint)")),_value));//ValueofAismodified}}contractB{uintvalue;addresspublicsender;functionsetValue(uint_value)public{value=_value;sender=msg.sender;//msg.senderispreservedindelegatecall.Itwasnotavailableincallcode.}}gas()optionisavailableforcall,callcodeanddelegatecall.value()optionisnotsupportedfordelegatecall.
callcode<address>.callcode(...)returns(bool):issuelow-levelCALLCODE,returnsfalseonfailurePriortohomestead,onlyalimitedvariantcalledcallcodewasavailablethatdidnotprovideaccesstotheoriginalmsg.senderandmsg.valuevalues.
ArrayArrayscanbedynamicorhaveafixedsize.
uint[]dynamicSizeArray;uint[7]fixedSizeArray;Fixedbytearraysbytes1(byte),bytes2,bytes3,...,bytes32.
Operators:
Comparisons:<=,<,==,!=,>=,>(evaluatetobool)Bitoperators:&,|,^(bitwiseexclusiveor),~(bitwisenegation),<<(leftshift),>>(rightshift)Indexaccess:IfxisoftypebytesI,thenx[k]for0<=k<Ireturnsthekthbyte(read-only).
Members
.length:read-onlyDynamicbytearraysbytes:Dynamically-sizedbytearray.Itissimilartobyte[],butitispackedtightlyincalldata.Notavalue-type!
string:Dynamically-sizedUTF-8-encodedstring.Itisequaltobytesbutdoesnotallowlengthorindexaccess.Notavalue-type!
EnumEnumworksjustlikeineveryotherlanguage.
enumActionChoices{GoLeft,GoRight,GoStraight,SitStill}ActionChoiceschoice=ActionChoices.GoStraight;StructNewtypescanbedeclaredusingstruct.
structFunder{addressaddr;uintamount;}Funderfunders;MappingDeclaredasmapping(_KeyType=>_ValueType)
Mappingscanbeseenashashtableswhicharevirtuallyinitializedsuchthateverypossiblekeyexistsandismappedtoavalue.
keycanbealmostanytypeexceptforamapping,adynamicallysizedarray,acontract,anenum,orastruct.valuecanactuallybeanytype,includingmappings.
ControlStructuresMostofthecontrolstructuresfromJavaScriptareavailableinSolidityexceptforswitchandgoto.
ifelsewhiledoforbreakcontinuereturn?:FunctionsStructurefunction(<parametertypes>){internal|external|public|private}[pure|constant|view|payable][returns(<returntypes>)]
Accessmodifierspublic-Accessiblefromthiscontract,inheritedcontractsandexternallyprivate-Accessibleonlyfromthiscontractinternal-Accessibleonlyfromthiscontractandcontractsinheritingfromitexternal-Cannotbeaccessedinternally,onlyexternally.Recommendedtoreducegas.Accessinternallywiththis.f.ParametersInputparametersParametersaredeclaredjustlikevariablesandarememoryvariables.
functionf(uint_a,uint_b){}OutputparametersOutputparametersaredeclaredafterthereturnskeyword
functionf(uint_a,uint_b)returns(uint_sum){_sum=_a+_b;}Outputcanalsobespecifiedusingreturnstatement.Inthatcase,wecanomitparameternamereturns(uint).
Multiplereturntypesarepossiblewithreturn(v0,v1,...,vn).
ConstructorFunctionthatisexecutedduringcontractdeployment.Definedusingtheconstructorkeyword.
contractC{addressowner;uintstatus;constructor(uint_status){owner=msg.sender;status=_status;}}FunctionCallsInternalFunctionCallsFunctionsofthecurrentcontractcanbecalleddirectly(internally-viajumps)andalsorecursively
contractC{functionfunA()returns(uint){return5;}functionFunB(uint_a)returns(uintret){returnfunA()+_a;}}ExternalFunctionCallsthis.g(8);andc.g(2);(wherecisacontractinstance)arealsovalidfunctioncalls,but,thefunctionwillbecalled“externally”,viaamessagecall.
.gas()and.value()canalsobeusedwithexternalfunctioncalls.
NamedCallsFunctioncallargumentscanalsobegivenbynameinanyorderasbelow.
functionf(uinta,uintb){}functiong(){f({b:1,a:2});}UnnamedfunctionparametersParameterswillbepresentonthestack,butarenotaccessible.
functionf(uinta,uint)returns(uint){returna;}FunctiontypePassfunctionasaparametertoanotherfunction.Similartocallbacksanddelegates
pragmasolidity^0.4.18;contractOracle{structRequest{bytesdata;function(bytesmemory)externalcallback;}Request[]requests;eventNewRequest(uint);functionquery(bytesdata,function(bytesmemory)externalcallback){requests.push(Request(data,callback));NewRequest(requests.length-1);}functionreply(uintrequestID,bytesresponse){//Heregoesthecheckthatthereplycomesfromatrustedsourcerequests[requestID].callback(response);}}contractOracleUser{Oracleconstantoracle=Oracle(0x1234567);//knowncontractfunctionbuySomething(){oracle.query("USD",this.oracleResponse);}functionoracleResponse(bytesresponse){require(msg.sender==address(oracle));}}FunctionModifierModifierscanautomaticallycheckaconditionpriortoexecutingthefunction.
modifieronlyOwner{require(msg.sender==owner);_;}functionclose()onlyOwner{selfdestruct(owner);}VieworConstantFunctionsFunctionscanbedeclaredvieworconstantinwhichcasetheypromisenottomodifythestate,butcanreadfromthem.
functionf(uinta)viewreturns(uint){returna*b;//wherebisastoragevariable}Thecompilerdoesnotenforceyetthataviewmethodisnotmodifyingstate.
PureFunctionsFunctionscanbedeclaredpureinwhichcasetheypromisenottoreadfromormodifythestate.
functionf(uinta)purereturns(uint){returna*42;}PayableFunctionsFunctionsthatreceiveEtheraremarkedaspayablefunction.
FallbackFunctionAcontractcanhaveexactlyoneunnamedfunction.Thisfunctioncannothaveargumentsandcannotreturnanything.Itisexecutedonacalltothecontractifnoneoftheotherfunctionsmatchthegivenfunctionidentifier(orifnodatawassuppliedatall).
function(){//Dosomething}ContractsCreatingcontractsusingnewContractscanbecreatedfromanothercontractusingnewkeyword.Thesourceofthecontracthastobeknowninadvance.
contractA{functionadd(uint_a,uint_b)returns(uint){return_a+_b;}}contractC{addressa;functionf(uint_a){a=newA();}}ContractInheritanceSoliditysupportsmultipleinheritanceandpolymorphism.
contractowned{functionowned(){owner=msg.sender;}addressowner;}contractmortalisowned{functionkill(){if(msg.sender==owner)selfdestruct(owner);}}contractfinalismortal{functionkill(){super.kill();//Callskill()ofmortal.}}MultipleinheritancecontractA{}contractB{}contractCisA,B{}ConstructorofbaseclasscontractA{uinta;constructor(uint_a){a=_a;}}contractBisA(1){constructor(uint_b)A(_b){}}AbstractContractsContractsthatcontainimplementedandnon-implementedfunctions.Suchcontractscannotbecompiled,buttheycanbeusedasbasecontracts.
pragmasolidity^0.4.0;contractA{functionC()returns(bytes32);}contractBisA{functionC()returns(bytes32){return"c";}}InterfaceInterfacesaresimilartoabstractcontracts,buttheyhaverestrictions:
Cannothaveanyfunctionsimplemented.Cannotinheritothercontractsorinterfaces.Cannotdefineconstructor.Cannotdefinevariables.Cannotdefinestructs.Cannotdefineenums.pragmasolidity^0.4.11;interfaceToken{functiontransfer(addressrecipient,uintamount);}EventsEventsallowtheconvenientusageoftheEVMloggingfacilities,whichinturncanbeusedto“call”JavaScriptcallbacksintheuserinterfaceofadapp,whichlistenfortheseevents.
Uptothreeparameterscanreceivetheattributeindexed,whichwillcausetherespectiveargumentstobesearchedfor.
Allnon-indexedargumentswillbestoredinthedatapartofthelog.
pragmasolidity^0.4.0;contractClientReceipt{eventDeposit(addressindexed_from,bytes32indexed_id,uint_value);functiondeposit(bytes32_id)payable{emitDeposit(msg.sender,_id,msg.value);}}LibraryLibrariesaresimilartocontracts,buttheyaredeployedonlyonceataspecificaddress,andtheircodeisusedwithdelegatecall(callcode).
libraryarithmatic{functionadd(uint_a,uint_b)returns(uint){return_a+_b;}}contractC{uintsum;functionf(){sum=arithmatic.add(2,3);}}Using-ForusingAforB;canbeusedtoattachlibraryfunctionstoanytype.
libraryarithmatic{functionadd(uint_a,uint_b)returns(uint){return_a+_b;}}contractC{usingarithmaticforuint;uintsum;functionf(uint_a){sum=_a.add(3);}}
评论