solidity-cheatsheet

我要开发同款
匿名用户2021年11月30日
46阅读
所属分类、Web3、区块链
授权协议MIT License

作品详情

SolidityCheatsheetandBestpracticesMotivation

ThisdocumentisacheatsheetforSoliditythatyoucanusetowriteSmartContractsforEthereumbasedblockchain.

ThisguideisnotintendedtoteachyouSolidityfromthegroundup,buttohelpdeveloperswithbasicknowledgewhomaystruggletogetfamiliarwithSmartContractsandBlockchainbecauseoftheSolidityconceptsused.

Note:IfyouhavebasicknowledgeinJavaScript,it'seasiertolearnSolidity.

TableofcontentsSolidityCheatsheetandBestpracticesMotivationTableofcontentsVersionpragmaImportfilesTypesBooleanIntegerAddressbalancetransferandsendcalldelegatecallcallcodeArrayFixedbytearraysDynamicbytearraysEnumStructMappingControlStructuresFunctionsStructureAccessmodifiersParametersInputparametersOutputparametersConstructorFunctionCallsInternalFunctionCallsExternalFunctionCallsNamedCallsUnnamedfunctionparametersFunctiontypeFunctionModifierVieworConstantFunctionsPureFunctionsPayableFunctionsFallbackFunctionContractsCreatingcontractsusingnewContractInheritanceMultipleinheritanceConstructorofbaseclassAbstractContractsInterfaceEventsLibraryUsing-ForErrorHandlingGlobalvariablesBlockvariablesTransactionvariablesMathematicalandCryptographicFunctionsContractRelatedVersionpragma

pragmasolidity^0.5.2;willcompilewithacompilerversion>=0.5.2and<0.6.0.

Importfiles

import"filename";

import*assymbolNamefrom"filename";orimport"filename"assymbolName;

import{symbol1asalias,symbol2}from"filename";

TypesBoolean

bool:trueorfalse

Operators:

Logical:!(logicalnegation),&&(AND),||(OR)Comparisons:==(equality),!=(inequality)Integer

Unsigned: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)Address

address: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,returnsfalseonfailure

Delegatecallusesthecodeofthetargetaddress,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,returnsfalseonfailure

Priortohomestead,onlyalimitedvariantcalledcallcodewasavailablethatdidnotprovideaccesstotheoriginalmsg.senderandmsg.valuevalues.

Array

Arrayscanbedynamicorhaveafixedsize.

uint[]dynamicSizeArray;uint[7]fixedSizeArray;Fixedbytearrays

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

Operators:

Comparisons:<=,<,==,!=,>=,>(evaluatetobool)Bitoperators:&,|,^(bitwiseexclusiveor),~(bitwisenegation),<<(leftshift),>>(rightshift)Indexaccess:IfxisoftypebytesI,thenx[k]for0<=k<Ireturnsthekthbyte(read-only).

Members

.length:read-onlyDynamicbytearrays

bytes:Dynamically-sizedbytearray.Itissimilartobyte[],butitispackedtightlyincalldata.Notavalue-type!

string:Dynamically-sizedUTF-8-encodedstring.Itisequaltobytesbutdoesnotallowlengthorindexaccess.Notavalue-type!

Enum

Enumworksjustlikeineveryotherlanguage.

enumActionChoices{GoLeft,GoRight,GoStraight,SitStill}ActionChoiceschoice=ActionChoices.GoStraight;Struct

Newtypescanbedeclaredusingstruct.

structFunder{addressaddr;uintamount;}Funderfunders;Mapping

Declaredasmapping(_KeyType=>_ValueType)

Mappingscanbeseenashashtableswhicharevirtuallyinitializedsuchthateverypossiblekeyexistsandismappedtoavalue.

keycanbealmostanytypeexceptforamapping,adynamicallysizedarray,acontract,anenum,orastruct.valuecanactuallybeanytype,includingmappings.

ControlStructures

MostofthecontrolstructuresfromJavaScriptareavailableinSolidityexceptforswitchandgoto.

ifelsewhiledoforbreakcontinuereturn?:FunctionsStructure

function(<parametertypes>){internal|external|public|private}[pure|constant|view|payable][returns(<returntypes>)]

Accessmodifierspublic-Accessiblefromthiscontract,inheritedcontractsandexternallyprivate-Accessibleonlyfromthiscontractinternal-Accessibleonlyfromthiscontractandcontractsinheritingfromitexternal-Cannotbeaccessedinternally,onlyexternally.Recommendedtoreducegas.Accessinternallywiththis.f.ParametersInputparameters

Parametersaredeclaredjustlikevariablesandarememoryvariables.

functionf(uint_a,uint_b){}Outputparameters

Outputparametersaredeclaredafterthereturnskeyword

functionf(uint_a,uint_b)returns(uint_sum){_sum=_a+_b;}

Outputcanalsobespecifiedusingreturnstatement.Inthatcase,wecanomitparameternamereturns(uint).

Multiplereturntypesarepossiblewithreturn(v0,v1,...,vn).

Constructor

Functionthatisexecutedduringcontractdeployment.Definedusingtheconstructorkeyword.

contractC{addressowner;uintstatus;constructor(uint_status){owner=msg.sender;status=_status;}}FunctionCallsInternalFunctionCalls

Functionsofthecurrentcontractcanbecalleddirectly(internally-viajumps)andalsorecursively

contractC{functionfunA()returns(uint){return5;}functionFunB(uint_a)returns(uintret){returnfunA()+_a;}}ExternalFunctionCalls

this.g(8);andc.g(2);(wherecisacontractinstance)arealsovalidfunctioncalls,but,thefunctionwillbecalled“externally”,viaamessagecall.

.gas()and.value()canalsobeusedwithexternalfunctioncalls.

NamedCalls

Functioncallargumentscanalsobegivenbynameinanyorderasbelow.

functionf(uinta,uintb){}functiong(){f({b:1,a:2});}Unnamedfunctionparameters

Parameterswillbepresentonthestack,butarenotaccessible.

functionf(uinta,uint)returns(uint){returna;}Functiontype

Passfunctionasaparametertoanotherfunction.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));}}FunctionModifier

Modifierscanautomaticallycheckaconditionpriortoexecutingthefunction.

modifieronlyOwner{require(msg.sender==owner);_;}functionclose()onlyOwner{selfdestruct(owner);}VieworConstantFunctions

Functionscanbedeclaredvieworconstantinwhichcasetheypromisenottomodifythestate,butcanreadfromthem.

functionf(uinta)viewreturns(uint){returna*b;//wherebisastoragevariable}

Thecompilerdoesnotenforceyetthataviewmethodisnotmodifyingstate.

PureFunctions

Functionscanbedeclaredpureinwhichcasetheypromisenottoreadfromormodifythestate.

functionf(uinta)purereturns(uint){returna*42;}PayableFunctions

FunctionsthatreceiveEtheraremarkedaspayablefunction.

FallbackFunction

Acontractcanhaveexactlyoneunnamedfunction.Thisfunctioncannothaveargumentsandcannotreturnanything.Itisexecutedonacalltothecontractifnoneoftheotherfunctionsmatchthegivenfunctionidentifier(orifnodatawassuppliedatall).

function(){//Dosomething}ContractsCreatingcontractsusingnew

Contractscanbecreatedfromanothercontractusingnewkeyword.Thesourceofthecontracthastobeknowninadvance.

contractA{functionadd(uint_a,uint_b)returns(uint){return_a+_b;}}contractC{addressa;functionf(uint_a){a=newA();}}ContractInheritance

Soliditysupportsmultipleinheritanceandpolymorphism.

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){}}AbstractContracts

Contractsthatcontainimplementedandnon-implementedfunctions.Suchcontractscannotbecompiled,buttheycanbeusedasbasecontracts.

pragmasolidity^0.4.0;contractA{functionC()returns(bytes32);}contractBisA{functionC()returns(bytes32){return"c";}}Interface

Interfacesaresimilartoabstractcontracts,buttheyhaverestrictions:

Cannothaveanyfunctionsimplemented.Cannotinheritothercontractsorinterfaces.Cannotdefineconstructor.Cannotdefinevariables.Cannotdefinestructs.Cannotdefineenums.pragmasolidity^0.4.11;interfaceToken{functiontransfer(addressrecipient,uintamount);}Events

EventsallowtheconvenientusageoftheEVMloggingfacilities,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);}}Library

Librariesaresimilartocontracts,buttheyaredeployedonlyonceataspecificaddress,andtheircodeisusedwithdelegatecall(callcode).

libraryarithmatic{functionadd(uint_a,uint_b)returns(uint){return_a+_b;}}contractC{uintsum;functionf(){sum=arithmatic.add(2,3);}}Using-For

usingAforB;canbeusedtoattachlibraryfunctionstoanytype.

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

评论