Professional Documents
Culture Documents
FunctionSignature:
functionname(parameters){internal/external}{scope}{view/pure}{returns(returntype)}
● TherearefourtypesofSolidityfunctions:e xternal,internal,public,andprivate.
● Furtherfunctionscanbesetasviewandpuretorestrictreadingandmodifyingofthe
state.
● Internal:thesefunctionsareinvokedinsidethecurrentcontractandcannotbe
completedindifferentcontexts.
● External:thesefunctionsareinvokedfromtheoutsideandthroughtransactionsas
well.Itisnotpossibletocallexternalfunctionsinternally.Whendealingwithbig
arraysofinformation,thesefunctionscanbehighlyeffective.
View:F
unctionswithviewdonotchangethestate,theycanonlyreadthevalueofstate
variable.
Pure:F unctionssettopurecanneithermodifynorreadfromthestate.
pecialVariablesandFunctions:
S
Thesearespecialvariablesthatexistinglobalnamespaceandaremainlyusedtoprovide
informationabouttheblockchainoraregeneral-useutilityfunctions.
BlockandTransactionProperties:
● blockhash(uintblockNumber)returns(byte32)-returnsthehashofgivenblock,works
onlyfor256mostrecentblock,excludingcurrentblock.
● block.coinbase(addresspayable):currentblockminer’saddress.
● block.difficulty(uint):currentblockdifficulty.
● block.gaslimit(uint):currentblockgaslimit.
● block.number(uint):currentblocknumber.
● block.timestamp(uint):currentblocktimestampassecondssinceunixepoch.
● gasleft()returns(uint256):remaininggas.
● msg.data(bytescalldata):completecalldata.
● msg.sender(addresspayable):senderofthemessage(currentcall).
● msg.sig(bytes4):firstfourbytesofthecalldata(i.e.functionidentifier).
● msg.value(uint):numberofweisentwiththemessage.
● now(uint):currentblocktimestamp.
● tx.gasprice(uint):gaspriceofthetransaction.
● tx.origin(addresspayable):senderofthetransaction(fullcallchain)/fromwherethe
transactionstarted.
FunctionsinSolidity
ABIEncodingandDecodingFunctions:
ABIstandsforA
pplicationBinaryInterface.ABIw orksasaninterfacebetweentwoprogram
modules,oneofwhichisatmachinelevelcode.It isthedefactomethodfor
encoding/decodingdatain/outofthemachinecode.
● abi.decode(bytesmemoryencodedData,(...datatypes))returns(...):ABIdecodesthe
givendata,whilethetypesaregiveninparenthesesasasecondargument.
● abi.encode(...)returns(bytesmemory):ABIencodesthegivenarguments.
● abi.encodePacked(...)returns(bytesmemory):Performspackedencodingofthe
givenarguments.
● abi.encodeWithSelector(bytes4selector,...)returns(bytesmemory):ABIencodes
thegivenargumentsstartingfromthesecondandprependsthegivenfour-byte
selector.
● abi.encodeWithSignature(stringmemorysignature,...)returns(bytesmemory):
Equivalenttoabi.encodeWithSelector(bytes4(keccak256(bytes(signature))),...)
ErrorHandling:
Solidityprovidesvariousfunctionsforerrorhandling.Whenanerroroccurs,thestateis
revertedbacktoitsoriginalstateandtheremaininggasisreturnedtothecaller.
Someimportanterrorhandlingmethodsare:
● assert(boolcondition):usedforinternalerrors,iftheconditionisnotmetthemethod
callcausesaninvalidopcodeandthusstatechangereversion.
● require(boolcondition):useforcheckingerrorsininputsorexternal
components,revertsiftheconditionisnotmet.
● require(boolcondition,stringmemorymessage):sameasrequire(boolcondition),will
alsoprovideanerrormessage.
● revert():abortexecutionandrevertstatechanges.
● revert(stringmemoryreason):sameasrevert(),alsoprovideanexplanatorystring.
MathematicalFunction:
● addmod(uintx,uinty,uintk)returns(uint):computes(x+y)%kwheretheaddition
isperformedwitharbitraryprecisionanddoesnotwraparoundat2**256.
● mulmod(uintx,uinty,uintk)returns(uint)−computes(x*y)%kwheretheaddition
isperformedwitharbitraryprecisionanddoesnotwraparoundat2**256
CryptographicFunctions:
● keccak256(bytesmemory)returns(bytes32):computesK
ECCAK256hashofthe
input.
● sha256(bytesmemory)returns(bytes32):computesS
HA256hashoftheinput.
FunctionsinSolidity
● ripemd160(bytesmemory)returns(bytes20):computesR IPEMD60hashoftheinput.
● ecrecover(bytes32hash,uint8v,bytes32r,bytes32s)returns(address):recoverthe
addressassociatedwithapublickeyfromellipticcurvesignatureorreturnzeroon
error.
Note:ecrecoverreturnsanaddressnotaddresspayable.
MemberofAddressTypes:
● <address>.balance(uint256): balanceofaddressinW ei( 1Wei=10e-18Ether)
● <addresspayable>.transfer(uint256amount):sendsgivenamountofWeito
Address.
● <addresspayable>.send(uint256amount):sendgivenamountofWeitoaddress,
returnsfalseonfailure
● <address>.call(bytesmemory)returns(bool,bytesmemory) :issuelow-levelCALL
withthegivenpayload,returnssuccessconditionandreturndata,forwardsall
availablegas.
● <address>.delegatecall(bytesmemory)returns(bool,bytesmemory): issuelow-level
DELEGATECALLwiththegivenpayload,returnssuccessconditionandreturndata,
forwardsallavailablegas.
● <address>.staticcall(bytesmemory)returns(bool,bytesmemory):issuelow-level
STATICCALLwiththegivenpayload,returnssuccessconditionandreturndata,
forwardsallavailablegas.
→ ACALLisalowlevelfunctiontointeractwithothercontracts.
ContractRelatedFunctions:
● this:referstothecurrentcontract,explicitlyconvertibletoaddress.
● selfdestruct(addresspayablerecipient):destroysthecurrentcontractand
sendsallitsfundstothegivenaddress.
Try/catchStatement(solidity^0.6.0):
try/catchletushandlefailureinexternalfunctioncallswithoutrollingbacktheentire
transaction.try/catchworksexactlylikeasinanyotherlanguage.Wecannotuse
try/catchforinternalfunctioncall.Towrapapublicfunctioncallwithinthesame
contractwithtry/catch,itcanbemadeexternalbycallingthefunctionwiththis.
● Areversionwithinatryblockwillnotbecaught.
FunctionsinSolidity
Currently,Soliditysupportstwotypesofcatchblocks:
● CatchError(stringmemoryreason):Iftheerrorwascausedbyrevert("reasonString")
orrequire(false,"reasonString")oraninternalerrorthatcausessuchanexception,
thenthecatchclauseofthetypecatchError(stringmemoryreason)willbeexecuted
● Catch(bytesmemorylowleveldata):thiscatchblockhandlesallothercases.This
blockexecuteiftheerrorsignaturedoesn'tmatchanyotherclause
DestructuringAssignmentsandReturningMultiplevalues:
Internally,Soliditypermitstupletypes.Theyareappliedtoretrieveseveralvalues
simultaneously.Afterthat,thesevaluescanbesettonewvariablesoralready
existingones.
Destructuringhelpsustounpackthereceiveddata.
● Itisnotpossibletomixvariabledeclarationsandnon-declarationassignments,i.e.
thefollowingisnotvalid:(x,uinty)=(1,2);