James Bachini

Ownable Contracts | Solidity Tips & Examples

Solidity onlyOwner Ownable Contracts

Ownable contracts in Solidity are used to implement access control for certain functions.

The idea is that only the contract owner, who is typically the deployer of the contract, can execute these protected functions.

To do this we will first import the OpenZeppelin library

import "@openzeppelin/contracts//contracts/access/Ownable.sol";

Inside our contract we can then add the onlyOwner modifier to the function that needs to be protected. The onlyOwner modifier checks that the address calling the function is the same as the contract owner’s address, and if not, it will revert the transaction.

function adminFunctionExample() public onlyOwner {
    // Avoid Decentralization Here
}

There is a full code example of ownable contracts using the OpenZeppelin library and a custom integration here: https://github.com/jamesbachini/Solidity-Snippets/blob/main/contracts/Ownable.sol

In many cases we need to protect certain functionalities within a smart contract. However I believe that this library is widely overused and detracts away from the ideals of decentralized development.

As blockchain developers we have the opportunity to write permissionless code and distribute it on a decentralized peer to peer network. By using onlyOwner functions we give away that power and negate the unique selling point of blockchain development.

Blockchains are slow and expensive and if we want a permissioned solution why not use a database and save yourself a whole bunch of headaches? There are certain examples where permissioned contracts make sense like trading bots or personal vaults but when creating applications for users we should strive for true decentralization.

It is much easier to create a permissioned ownable contract but wherever possible Solidity devs should strive to create immutable, permissionless code where all parties have equal access.

ownable contracts solidity

Get The Blockchain Sector Newsletter, binge the YouTube channel and connect with me on Twitter

The Blockchain Sector newsletter goes out a few times a month when there is breaking news or interesting developments to discuss. All the content I produce is free, if you’d like to help please share this content on social media.

Thank you.

James Bachini

Disclaimer: Not a financial advisor, not financial advice. The content I create is to document my journey and for educational and entertainment purposes only. It is not under any circumstances investment advice. I am not an investment or trading professional and am learning myself while still making plenty of mistakes along the way. Any code published is experimental and not production ready to be used for financial transactions. Do your own research and do not play with funds you do not want to lose.