Enum in Solidity smart contracts

Phemex Trading

Short for enumeration, enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums and are constant. They are used to provide names for integral constants which makes the contract easier to maintain and read. When you need a predefined list of values which represent numeric or textual data you should use an enum.

In our shipping contract below lets create a simple enum that helps track the status of an order. This enum will be call ‘status’ and it will contain only the following values:

  • Pending
  • Shipped
  • Accepted
  • Rejected
  • Canceled

This enum restricts the variables to one of a few predefined values. By having a readable list it makes our code easier to maintain. Since return values are 0, 1, 2, 3, 4 there can not be a 5 (remember the first position is position 0). Having a defined list of 0-4 will reduce the chances of a bug in your code by eliminating the possibility of a 5, 10, 15 being passed in.

Read the sample contract below to see a working example. This contract contains an enum called status which defines several shipping status’. It also contains a function that reads a variable. If the variable is pending change the status to shipped.

Contract Order {
Enum status {
      Pending, 
      Shipped, 
      Accepted, 
      Rejected, 
      Canceled
      }
//take the enum status, make its visibility public and call it status.  The first item in the enum is the default (pending would be the default - 0).
      Status public status; 

//function on how to update the status to shipped if the current status is pending
Function ship() public {

//the status has to equal pending.  If it does change it to shipped
         Require(status ==Status.Pending);
         Status = Status.Shipped;
         }

Try it in Remix

What you can not do with an enum in Solidity

  • Implicit conversion is not allowed
  • Numbers or booleans can not be uses as member of an enum
  • Enums can not be used as a key type in a mapping
  • Enums types are not part of the ABI so you can not return an enum within a function.
  • You can not define enums in an interface if your Solidity compiler version is less than 0.5.0.

For more information read the docs.

This code is for learning and entertainment purposes only. The code has not been audited and use at your own risk. Remember smart contracts are experimental and could contain bugs.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – Struct in Solidity smart contracts

1 thought on “Enum in Solidity smart contracts

Leave a Reply