0

I heard that constructor is usually used for initializing variables but It just has 'console.log' here. Is constructor essential for every contract?

// SPDX-License-Identifier: UNLICENSED

pragma solidity ^0.8.4;

import "hardhat/console.sol";

contract WavePortal {
   uint256 totalWaves;

   event NewWave(address indexed from, uint256 timestamp, string message);

   struct Wave {
       address waver;
       string message;
       uint256 timestamp;
   }

   Wave[] waves;

   constructor() payable {
       console.log("We have been constructed!");
   }

   function wave(string memory _message) public {
       totalWaves += 1;
       console.log("%s waved w/ message %s", msg.sender, _message);

       waves.push(Wave(msg.sender, _message, block.timestamp));

       emit NewWave(msg.sender, block.timestamp, _message);
    
       uint256 prizeAmount = 0.0001 ether;
       require(
           prizeAmount <= address(this).balance,
           "Trying to withdraw more money than the contract has."
       );
       (bool success, ) = (msg.sender).call{value: prizeAmount}("");
       require(success, "Failed to withdraw money from contract.");
   }

   function getAllWaves() public view returns (Wave[] memory) {
       return waves;
   }

   function getTotalWaves() public view returns (uint256) {
       console.log("We have %d total waves!", totalWaves);
       return totalWaves;
   }
}

1 Answer 1

1

Console.log is only there for debuging purpose.

constructor function is optional, you can omit, which is equivalent to constructor() {}.

In your code, the constructor is marked as payable though, so one can send ether while deploying this contract, which is not possible if use the default constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.