Smart Contract in Solidity
Smart Contract in Solidity
In Solidity, a contract is the fundamental building block of Ethereum smart contracts. It is written in a
language similar to JavaScript and is compiled into bytecode that can be executed on the Ethereum
Virtual Machine (EVM). Here's a basic structure of a contract in Solidity:
Pragma Directive: This is the first line of a Solidity contract and specifies the version of the Solidity
compiler to be used. It's important to specify the compiler version to ensure that the contract behaves
as expected with the specific compiler version.
Example:
pragma solidity ^0.8.0;
Contract Declaration: The contract keyword is used to define a new contract. It is followed by the
name of the contract and a pair of curly braces that enclose the contract's code.
Example:
contract MyContract {
// Contract code goes here
}
State Variables: State variables represent the state of the contract and can be accessed and modified by
its functions. They are declared within the contract body.
Example:
contract MyContract {
uint256 public myVariable;
}
Constructor: The constructor is a special function that is executed only once when the contract is
deployed. It is used to initialize contract state variables and can take arguments.
Example:
contract MyContract {
uint256 public myVariable;
constructor(uint256 initialValue) {
myVariable = initialValue;
}
}
Functions: Functions define the behavior of the contract. They can be public, private, internal, or
external. Public functions can be called externally, while private functions are only accessible within
the contract. Internal functions are like private functions but can also be called by contracts that
inherit from this one. External functions are similar to public functions but cannot be called internally.
Example:
contract MyContract {
uint256 public myVariable;
constructor(uint256 initialValue) {
myVariable = initialValue;
}
Example:
contract MyContract {
address public owner;
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can call this function");
_; // Continue executing the function if the condition is met
}
Example:
contract MyContract {
event ValueChanged(uint256 newValue);
constructor(uint256 initialValue) {
myVariable = initialValue;
}