Structure of a Smart Contract (2024)

Structure of a Smart Contract (1)

There's a number of key concepts defining Ethereum smart contracts that differ from a web2 development paradigm.

Types

In Solidity, the contract type is a struct that organizes a set of related functions around a single purpose.

Address types are Ethereum addresses that equate to 20 bytes, and are represented in hexadecimal form beginning with the prefix 0x.

Most other types will be familiar to you as a developer - including booleans, integers, fixed-point numbers, byte arrays, and literals.

Data Storage

In Solidity, reference data values can be stored as storage, memory or calldata depending on the role of the data stored. In particular:

  • storage keeps the data permanently on the blockchain, and is extremely expensive.
  • memory values are stored only for the lifetime of the smart contract's execution, and are inexpensive to use (costing only small amounts of gas).
  • calldata is a special data location that contains the function arguments, and is only available for external function call parameters.

Function Modifiers

Functions exist to get / set information based on calls initiated by external transactions. In particular, a smart contract can never run unless initiated by an external transaction - they don't execute silently in the background.

Access modifiers include:

  • public: Can be accessed by all functions or callers
  • external: Can be accessed only by external callers, not internal functions
  • internal: Can be accessed only by this contract, or contracts deriving from it
  • private: Can be accessed only from this contract itself

Other modifiers include:

  • view: This guarantees that the function will not modify the state of the contract's data (or data in storage).
  • pure: This guarantees that the function with neither read nor modify the state of the contract's data.
  • payable: Functions and addresses declared payable can receive ether into their contracts.

Special Functions and Variables

There are a number of global variables and functions that will be helpful to remember you have access to! Some special variables are:

  • block.number (uint256): The number of the most recent block.
  • block.timestamp (uint256): The UNIX timestamp of the most recent block.
  • block.gaslimit (uint256): The gas limit of the current block.
  • msg.sender (address payable): The sender of the transaction triggering the contract.
  • msg.value (uint256): The number of wei transferred with the message.

Special functions include:

  • receive(): Contracts may only have one of these functions declared. It serves as the default destination when a contract is sent Ether. It cannot have arguments, return anything, and must be external and payable.
  • fallback(): Contracts may only have one of these functions declared. It serves as the fallback if a call to the contract does not match any function, or if no data was supplied and the receive() function was not declared. It cannot have arguments, return anything, and must be external.

Events

Solidity events are roughly equivalent to logging in other programming paradigms. They're emitted when a contract is executed, stored permanently on the blockchain, but aren't accessible to be modified / read by smart contracts.

You can declare and emit an event like this:

-- CODE language-js line-numbers -- event TestEvent (uint256 date, string value); emit TestEvent(block.timestamp,’My first event!”);

Events can be accessed in a variety of different ways:

  1. Events are stored in the receipts of transactions, and can be accessed there.
  2. You can subscribe to an event with myContract.events.TestEvent([options][, callback])
  3. You can request past events using a request like myContract.getPastEvents(event[, options][, callback]).

This should give you a broad overview of the key components of a smart contract! You can find more detail in the Solidity Documentation linked here.

Structure of a Smart Contract (2024)

FAQs

What is the basic structure of a smart contract? ›

What Are the Four Major Parts of a Smart Contract? It depends on the blockchain and how it is programmed. Generally speaking, smart contracts have state variables (data), functions (what can be done), events (messages in and out), and modifiers (special rules for specific users).

What is struct in smart contract? ›

Structs are custom defined types that can group several variables (see Structs in types section). open in Remix. // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.4.0 <0.9.0; contract Ballot { struct Voter { // Struct uint weight; bool voted; address delegate; uint vote; } }

What is the anatomy of a smart contract? ›

Smart contracts are programs that are immutably stored in the chain. Through VM abstraction, the ISC virtual machine is agnostic about the interpreter used to execute each smart contract. It can support different VM types (i.e., interpreters) simultaneously on the same chain.

What is the architecture of smart contracts? ›

A blockchain platform works like a distributed database that stores all smart contracts. Each contract has a unique address used for state queries and updates. Methods in the contract code handle permission checks and logic.

What is the legal framework of a smart contract? ›

Code as Law: Smart contracts embody the principle of “code as law,” where the code itself serves as the legal framework for the agreement. This code is transparent, tamper-resistant, and executes without the need for human intervention.

What is a smart contract in layman's terms? ›

A smart contract is an agreement between two people or entities in the form of computer code programmed to execute automatically. The idea was proposed in the 1990s by Nick Szabo, a pioneer of modern computer science, who defined them as a set of virtual promises with associated protocols to enforce them.

How is a smart contract coded? ›

Smart contracts work by following simple “if/when…then…” statements that are written into code on a blockchain. A network of computers executes the actions when predetermined conditions are met and verified.

What is the structure of a contract? ›

Certain essential elements must be present before a written contract is binding, including: identification (names) of the parties, the purpose of the agreement, a detailed statement of the rights and obligations of each party, what each party is giving (e.g., money, products, or services) in exchange for what they're ...

Is a smart contract a DAO? ›

DAOs are powered by smart contracts, which are self-executing code that run on a blockchain and enforce the rules and logic of the organization. In this article, we will explore what DAO smart contracts can do for your blockchain business, and how they can help you achieve your goals and vision.

What are the parameters of a smart contract? ›

Parameters are the variables that control the behavior and logic of your smart contract, such as fees, rates, limits, or thresholds. You should document your parameters in a separate file or repository, using a standard format, such as JSON or YAML.

How hard is it to write a smart contract? ›

If you have no experience, it may take you a few months to get comfortable with coding a simple smart contract. Developers with more experience might need just days or weeks. Once created, your smart contract can take anywhere from a handful of seconds to minutes to complete.

What are the smart contract phases? ›

These four phases are the formation of a smart contract, freezing of the smart contract, execution of the smart contract, and finalization of the smart contract.

What does the basic structure of a smart contract contain? ›

Structure of a Smart Contract

State Variables: These are the variables that store the contract's state. For example, in a smart contract for a sale, there might be state variables for the buyer, seller, price, and item status. Functions: This section contains the functions that the contract can perform.

What is a good example of a smart contract? ›

Before you learn about the best smart contracts examples, you must understand the significance of smart contracts in the web3 landscape. In simple words, smart contracts are self-executing programs that rely on an 'if-then' logic. One of the best examples of smart contracts in the real world is a vending machine.

How do smart contracts run? ›

A smart contract works by monitoring the blockchain or other credible information source for certain conditions or triggers. These triggers can include almost anything that can be verified digitally—a date reached, a payment completed, a monthly bill received, or any other verifiable event.

What are the basics of smart contracts? ›

Smart contracts are typically used to automate the execution of an agreement so that all participants can be immediately certain of the outcome, without any intermediary's involvement or time loss. They can also automate a workflow, triggering the next action when predetermined conditions are met.

What is the structure of smart? ›

Smart structures represent a new engineering approach or design philosophy that integrates the actions of sensors, actuators and control circuit elements into a single system that can respond adaptively to environmental changes in a useful manner.

Top Articles
Gambling
How do I withdraw money from my PayPal account?
Places 5 Hours Away From Me
Lighthouse Diner Taylorsville Menu
Craigslist Benton Harbor Michigan
Seething Storm 5E
Alpha Kenny Buddy - Songs, Events and Music Stats | Viberate.com
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Is Csl Plasma Open On 4Th Of July
Khatrimaza Movies
Aries Auhsd
Gina's Pizza Port Charlotte Fl
All Buttons In Blox Fruits
Nebraska Furniture Tables
Sony E 18-200mm F3.5-6.3 OSS LE Review
Byte Delta Dental
Welcome to GradeBook
How To Level Up Roc Rlcraft
Aaa Saugus Ma Appointment
Chaos Space Marines Codex 9Th Edition Pdf
Hood County Buy Sell And Trade
Usa Massage Reviews
Stickley Furniture
Gesichtspflege & Gesichtscreme
Craigslist Boerne Tx
Past Weather by Zip Code - Data Table
Salemhex ticket show3
Blush Bootcamp Olathe
Used 2 Seater Go Karts
The Latest: Trump addresses apparent assassination attempt on X
Craigslist Central Il
Flaky Fish Meat Rdr2
Sitting Human Silhouette Demonologist
Joe's Truck Accessories Summerville South Carolina
Toonily The Carry
Frank 26 Forum
Frcp 47
Main Street Station Coshocton Menu
Flags Half Staff Today Wisconsin
San Bernardino Pick A Part Inventory
303-615-0055
Walmart Car Service Near Me
Unlock The Secrets Of "Skip The Game" Greensboro North Carolina
Arcanis Secret Santa
Squalicum Family Medicine
The Machine 2023 Showtimes Near Roxy Lebanon
40X100 Barndominium Floor Plans With Shop
Walmart Front Door Wreaths
Definition of WMT
Southern Blotting: Principle, Steps, Applications | Microbe Online
Primary Care in Nashville & Southern KY | Tristar Medical Group
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 5992

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.