Loading...
Loading...

returns keyword and data type.pure modifier.view modifier.payable modifier. Received funds are added to the contract's balance.
multiply(5, 3), he knows he will get 15, but he doesn't necessarily need to know how exactly the multiplication happens inside the function.function. Then the function name and parameters in parentheses. Then visibility modifiers, followed by the return type.function setTokenPrice(uint256 newPrice) public returns (bool) { // ↑ ↑ ↑ ↑ // name parameters modifiers what it returns
// function body - what it does. // Here – assigns a new value to a state variable tokenPrice = newPrice;
// return value return true;}function function_name(parameter_type parameter_name) modifiers returns (return_type) { // function body
// return value return value;}calculateArea is better than just calc."function transferTokens(address to, uint256 amount, string memory reason) public { // ↑ ↑ ↑ // address amount transfer reason}function getBalance(address user) public view returns (uint256) { // ↑ // returns a number return balances[user];}contract TokenContract { // Instead of one huge function — many small and understandable ones function validateTransfer(address from, address to, uint256 amount) internal pure returns (bool) { // Transfer validation }
function updateBalances(address from, address to, uint256 amount) internal { // Balance updating }
function transfer(address to, uint256 amount) public { require(validateTransfer(msg.sender, to, amount), "Invalid transfer"); updateBalances(msg.sender, to, amount); }}contract GameContract { function calculateDamage(uint256 baseDamage, uint256 multiplier) public pure returns (uint256) { return baseDamage * multiplier / 100; }
function swordAttack(uint256 strength) public pure returns (uint256) { return calculateDamage(strength, 120); // Reusing the function }
function magicAttack(uint256 intelligence) public pure returns (uint256) { return calculateDamage(intelligence, 150); // And reusing again }}view/pure) → create a transaction, cost gas, changes are written to blockchain forevercontract Example { uint256 public counter;
// Creates a transaction! Costs gas, written to blockchain function increment() public { counter += 1; }
// Does NOT create a transaction! Free, executed locally function getCounter() public view returns (uint256) { return counter; }}string always have string memory written, but uint256 doesn't? What is this memory?"storage — permanent storage (like a database field) — data is saved in the blockchain forevermemory — temporary storage (like RAM in a computer) — data exists only during function execution, you can read and write temporary informationcalldata — read-only (like a computer disk without write capability) — data is passed to the function, cannot be changed and is not saved after function executionmemory?memory keyword needs to be specified only for complex data types:memory:string — stringsbytes — byte arraysuint256[], address[], etc.)struct)memory:uint256, int256 — numbersbool — boolean valuesaddress — addresses// ✅ Correct - string requires memory specificationfunction setMessage(string memory newMessage) public { message = newMessage;}
// ✅ Correct - string requires memory when returningfunction getMessage() public view returns (string memory) { return message;}
// ✅ Correct - simple types do NOT require memoryfunction incrementCounter() public { counter = counter + 1; // uint256 doesn't require memory}
// ❌ Error - without memory the compiler won't understand where to store the stringfunction setMessage(string newMessage) public { // ERROR! message = newMessage;}public, private, internal, external) — define where the function can be called fromview, pure, payable) — define how the function works with contract statepublic - everyone can call// Basic balance operations, they may be needed both inside and outside the smart contractfunction getBalance() public view returns (uint256) { return balance;}
// Fund transferfunction transfer(address to, uint256 amount) public { // transfer logic}
// Account depositfunction deposit() public payable { balance += msg.value;}
// Getting contract informationfunction getContractInfo() public view returns (string memory) { return "My Smart Contract";}private - only functions in the same contract can call// Internal calculationsfunction _calculateFee(uint256 amount) private pure returns (uint256) { return amount * 3 / 100; // 3% fee}
// Checking internal conditionsfunction _isValidUser(address user) private view returns (bool) { return userBalances[user] > 0;}
// Resetting internal datafunction _resetCounters() private { dailyTransactions = 0; weeklyLimit = 1000;}internal - functions in the same contract and inheriting contracts can call// Basic transfer logic that can be extended by inheritorsfunction _transfer(address from, address to, uint256 amount) internal { balances[from] -= amount; balances[to] += amount;}
// Common checks, can be reused by child contractsfunction _validateAmount(uint256 amount) internal pure returns (bool) { return amount > 0 && amount < 1000000;}
// Initialization for inherited contractsfunction _initialize(address owner) internal { contractOwner = owner; isInitialized = true;}external - can only be called from functions in other contractspublic for large data.// Administrative functionsfunction emergencyStop() external { require(msg.sender == admin, "Only admin"); paused = true;}
// Callback functionsfunction onTokenReceived(address from, uint256 amount, bytes calldata data) external { // Called by other contracts}
// API for external calls with large datafunction processLargeData(uint256[] calldata numbers) external { // more economical for large arrays}public modifier for functions doesn't work the same as for variables!"public = automatic getter, allowing reading the variable from outside the contractcontract Example { uint256 public counter = 10; // Automatically creates:
// function counter() public view returns (uint256) { // return counter; // }}public = ability to call the function from outside the contract, by users or other contractscontract Example { function incrementCounter() public { // Can be called from outside AND inside // function logic }
function internalHelper() internal { // Only from inside the contract incrementCounter(); // This works }}public, attackers will be able to call it. While wrong variable visibility most often leads only to unwanted data disclosure, but not to loss of contract control.view - read-only data// Getting user balancefunction getBalance(address user) public view returns (uint256) { return balances[user];}
// Checking permissionsfunction isOwner(address user) public view returns (bool) { return user == owner;}
// Getting blockchain informationfunction getCurrentTime() public view returns (uint256) { return block.timestamp;}
// Calculations based on current datafunction calculateInterest(address user) public view returns (uint256) { return balances[user] * interestRate / 100;}pure - no state access// Mathematical calculationsfunction add(uint256 a, uint256 b) public pure returns (uint256) { return a + b;}
// Interest calculationfunction calculateInterest(uint256 amount, uint256 rate) public pure returns (uint256) { return amount * rate / 100;}
// String operationsfunction concatenate(string memory a, string memory b) public pure returns (string memory) { return string(abi.encodePacked(a, " ", b));}
// Data validationfunction isValidEmail(string memory email) public pure returns (bool) { bytes memory emailBytes = bytes(email); return emailBytes.length > 5; // Simplified check}payable - can receive paymentspayable, sending ETH will result in an error.// Account depositfunction deposit() public payable { balances[msg.sender] += msg.value; // msg.value - sent ETH amount}
// Item purchasefunction buyItem(uint256 itemId) public payable { require(msg.value >= itemPrices[itemId], "Insufficient payment"); // Purchase logic}
// Donations with messagefunction donate(string memory message) public payable { require(msg.value > 0, "Donation must be greater than 0"); totalDonations += msg.value;}
// Constructor can be payableconstructor() public payable { owner = msg.sender; // Can send ETH during deployment}Modifier | Read State | Change State | Receive ETH | Gas Cost | Creates Transaction |
|---|---|---|---|---|---|
view | ✅ Yes | ❌ No | ❌ No | 0 (free) | ❌ No |
pure | ❌ No | ❌ No | ❌ No | 0 (free) | ❌ No |
payable | ✅ Yes | ✅ Yes | ✅ Yes | Has cost | ✅ Yes |
Regular | ✅ Yes | ✅ Yes | ❌ No | Has cost | ✅ Yes |
pure for calculations, view for checking balances, payable for receiving payments!"contract TokenSaleVault { uint256 public tokenPrice = 0.001 ether; uint256 public userTokenBalance;
// Pure: we don't read state variables function calculateTokens(uint256 ethAmount) public pure returns (uint256) { return ethAmount / 0.001 ether; }
// View: only reading state variable – balances[user] function getBalance(address user) public view returns (uint256) { return userTokenBalance; }
// Payable: receiving payment and changing state function buyTokens() public payable { require(msg.value > 0, "Send ETH to buy tokens"); uint256 tokens = calculateTokens(msg.value); userTokenBalance += tokens; }
// ...}contract Example { uint256 private data = 42;
// Combination: external + view. Doesn't change state and can only be called from outside function getData() external view returns (uint256) { return data; }
// Combination: public + payable. Can be called inside and outside, and function can accept ETH function deposit() public payable { // Function is accessible to everyone AND can receive payments }
// Combination: internal + pure. Call only from inside, doesn't read or change state function helper(uint256 x) internal pure returns (uint256) { return x * 2; }}function cube(uint256 input) public pure returns (uint256) { // Only calculate value based on arguments. Don't read or change contract state variables. uint256 output = input * input * input; return output;}contract Calculator { uint256 public lastResult;
function getLastResult() public view returns (uint256) { return lastResult; // Only read, don't change }}contract Counter { uint256 public count;
function increment() public { count = count + 1; // Change contract state }}contract Donation { uint256 public totalDonations;
function donate() public payable { totalDonations += msg.value; // Receive and account for payment }}// SPDX-License-Identifier: MITpragma solidity ^0.8.0;
contract HelloWorld { string public message = "Hello, World!";
// Function to change the message function setMessage(string memory newMessage) public { message = newMessage; }
// Function to get the message function getMessage() public view returns (string memory) { return message; }}setMessage function and change the message in the contract. The contract can not only store the message, but also change it, and also return the current value.// SPDX-License-Identifier: MITpragma solidity ^0.8.0;
contract Counter { uint256 public counter = 0; // Variable stored in the blockchain
function incrementCounter() public { counter = counter + 1; // Users can increment the counter }}
incrementCounter function and a button to call it.
incrementCounter function and the counter variable value will increase by 1.Загрузка...


