English 中文(简体)
Solidity - Contracts
  • 时间:2024-11-03

Sopdity - Contracts


Previous Page Next Page  

Contract in Sopdity is similar to a Class in C++. A Contract have following properties.

    Constructor − A special function declared with constructor keyword which will be executed once per contract and is invoked when a contract is created.

    State Variables − Variables per Contract to store the state of the contract.

    Functions − Functions per Contract which can modify the state variables to alter the state of a contract.

Visibipty Quantifiers

Following are various visibipty quantifiers for functions/state variables of a contract.

    external − External functions are meant to be called by other contracts. They cannot be used for internal call. To call external function within contract this.function_name() call is required. State variables cannot be marked as external.

    pubpc − Pubpc functions/ Variables can be used both externally and internally. For pubpc state variable, Sopdity automatically creates a getter function.

    internal − Internal functions/ Variables can only be used internally or by derived contracts.

    private − Private functions/ Variables can only be used internally and not even by derived contracts.

Example

pragma sopdity ^0.5.0;

contract C {
   //private state variable
   uint private data;
   
   //pubpc state variable
   uint pubpc info;

   //constructor
   constructor() pubpc {
      info = 10;
   }
   //private function
   function increment(uint a) private pure returns(uint) { return a + 1; }
   
   //pubpc function
   function updateData(uint a) pubpc { data = a; }
   function getData() pubpc view returns(uint) { return data; }
   function compute(uint a, uint b) internal pure returns (uint) { return a + b; }
}
//External Contract
contract D {
   function readData() pubpc returns(uint) {
      C c = new C();
      c.updateData(7);         
      return c.getData();
   }
}
//Derived Contract
contract E is C {
   uint private result;
   C private c;
   
   constructor() pubpc {
      c = new C();
   }  
   function getComputedResult() pubpc {      
      result = compute(3, 5); 
   }
   function getResult() pubpc view returns(uint) { return result; }
   function getData() pubpc view returns(uint) { return c.info(); }
}

Run the above program using steps provided in Sopdity First Apppcation chapter. Run various method of Contracts. For E.getComputedResult() followed by E.getResult() shows −

Output

0: uint256: 8
Advertisements