Created
October 2, 2022 16:21
-
-
Save sandoche/1f0c5146a919db67b047ee184c952441 to your computer and use it in GitHub Desktop.
Example of a Counter with Owner access control in Solidity (for a blog post)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.17; | |
contract Counter { | |
uint public count; | |
address owner; | |
// Modifier that makes sure the caller is the owner | |
modifier onlyOwner() { | |
require(msg.sender == owner); | |
_; | |
} | |
// Constructor that sets the owner as the initial creator of the smart contract | |
constructor() { | |
owner = msg.sender; | |
} | |
// Function to get the current count | |
function get() public view returns (uint) { | |
return count; | |
} | |
// Function to increment count by 1 | |
function inc() public { | |
count += 1; | |
} | |
// Function to decrement count by 1, method only accessible by the owner | |
function dec() public onlyOwner { | |
// This function will fail if count = 0 | |
count -= 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment