Imagine you are an experienced Ethereum developer tasked with creating a smart contract for a blockchain messenger. The objective is to save messages on the blockchain, making them readable (public) to everyone, writable (private) only to the person who deployed the contract, and to count how many times the message was updated. Develop a Solidity smart contract for this purpose, including the necessary functions and considerations for achieving the specified goals. Please provide the code and any relevant explanations to ensure a clear understanding of the implementation.
c1f778a verified | ```solidity | |
| // SPDX-License-Identifier: MIT | |
| pragma solidity ^0.8.0; | |
| contract MessageStorage { | |
| string private currentMessage; | |
| address public owner; | |
| uint256 public updateCount; | |
| // Events | |
| event MessageUpdated(string newMessage, address updater, uint256 timestamp); | |
| // Modifier to restrict access to owner only | |
| modifier onlyOwner() { | |
| require(msg.sender == owner, "Only contract owner can perform this action"); | |
| _; | |
| } | |
| constructor(string memory initialMessage) { | |
| owner = msg.sender; | |
| currentMessage = initialMessage; | |
| updateCount = 1; // Initial message is considered first update | |
| } | |
| // Function to update the message (only owner) | |
| function updateMessage(string memory newMessage) public onlyOwner { | |
| currentMessage = newMessage; | |
| updateCount++; | |
| emit MessageUpdated(newMessage, msg.sender, block.timestamp); | |
| } | |
| // Function to read the current message (public) | |
| function getMessage() public view returns (string memory) { | |
| return currentMessage; | |
| } | |
| // Function to get the number of updates (public) | |
| function getUpdateCount() public view returns (uint256) { | |
| return updateCount; | |
| } | |
| } | |
| ``` |