Functions
Functions are the core building blocks of smart contracts. Most importantly, they make up our entry points to stuff our users aught to be able to do...
Think of a simple ATM machine. It basically has one function, "Withdraw Cash". This function would require one argument to be passed in: How much to withdraw. It would then perform all kinds of checks to make sure you can't withdraw more than what you're allowed, but as an external user, this "withdraw function" is all we really care about.
If we skim the code of the CryptoPunksMarket contract, we find a whole list of user facing functions that are relevant to us:
contract CryptoPunksMarket { // The initial distribution of punks function setInitialOwner() {} function setInitialOwners() {} function allInitialOwnersAssigned() {} function getPunk() {} // For Punk Owners function transferPunk() {} function punkNoLongerForSale() {} function offerPunkForSale() {} function offerPunkForSaleToAddress() {} // Execute Punk Purchases function buyPunk() {} function withdraw() {} // Bids on Punks function enterBidForPunk() {} function acceptBidForPunk() {} function withdrawBidForPunk() {}}
If we just have a closer look at the first one for now:
function setInitialOwner(address to, uint punkIndex) { // ...}
This, we can read that as follows:
The contract has a function to set the initial owner of a punk
setInitialOwner
. It expects to be passed the account addressto
we want to make the owner of the punk, as well as which punk to send them (punkIndex
, a number between 0 and 9,999).
These two data points are what we call "function arguments", and in Solidity they always come with a type (e.g. is this a number, a string, or something else).
One neat characteristic that helps programmers organize their code is that one function can call another. That way we can encapsulate a set of statements to do one specific, repeatable task.
For example, the punkNoLongerForSale
function removes an existing sell-offer on a given punk. If we hunt for the places the punkNoLongerForSale
function is used, we can see it's used in both the transferPunk
, and buyPunk
functions to ensure any existing sell-offer is cleared when the punk moves to another wallet.