VOOZH about

URL: https://www.geeksforgeeks.org/solidity/solidity-basics-of-contracts/

⇱ Solidity - Basics of Contracts - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Solidity - Basics of Contracts

Last Updated : 2 Mar, 2023

Solidity Contracts are like a class in any other object-oriented programming language. They firmly contain data as state variables and functions which can modify these variables. When a function is called on a different instance (contract), the EVM function call happens and the context is switched in such a way that the state variables are inaccessible. A contract or its function needs to be called for anything to happen. Some basic properties of contracts are as follows :

  • Constructor: Special method created using the constructor keyword, which is invoked only once when the contract is created.
  • State Variables: These are the variables that are used to store the state of the contract.
  • Functions: Functions are used to manipulate the state of the contracts by modifying the state variables.

Creating a Contract

Creating contracts programmatically is generally done by using JavaScript API web3.js, which has a built-in function web3.eth.Contract to create the contracts. When a contract is created its constructor is executed, a constructor is an optional special method defined by using the constructor keyword which executes one per contract. Once the constructor is called the final code of the contract is added to the blockchain.

Syntax:

contract <contract_name>{

 constructor() <visibility>{
 .......
 }
 // rest code
}

Example: In the below example, the contract Test is created to demonstrate how to create a contract in Solidity.

Output : 

👁 Creating a Contract

Visibility Modifiers

Solidity provides four types of visibilities for functions and state variables. Functions have to specified by any of the four visibilities but for state variables external is not allowed. 

  1. External: External functions are can be called by other contracts via transactions. An external function cannot be called internally. For calling an external function within the contract this.function_name() method is used. Sometimes external functions are more efficient when they have large arrays of data.
  2. Public: Public functions or variables can be called both externally or internally via messages. For public static variables, a getter method is created automatically in solidity.
  3. Internal: These functions or variables can be accessed only internally i.e. within the contract or the derived contracts.
  4. Private: These functions or variables can only be visible for the contracts in which they are defined. They are not accessible to derived contracts also.

Example: In the below example, the contract contract_example is created to demonstrate different visibility modifiers discussed above.

Output : 
 

👁 Visibility Modifiers Example


 

Comment
Article Tags:

Explore