⌘K

Icon SunFilledIcon MoonStars

Icon LinkEnums

Sway Enums are a little distinct from TypeScript Enums. In this document, we will explore how you can represent Sway Enums in the SDK and how to use them with Sway contract functions.

Icon LinkBasic Sway Enum Example

Consider the following basic Sway Enum called StateError:

pub enum StateError {
Void: (),
Pending: (),
Completed: (),
}

The type () indicates that there is no additional data associated with each Enum variant. Sway allows you to create Enums of Enums or associate types with Enum variants.

Icon LinkUsing Sway Enums As Function Parameters

Let's define a Sway contract function that takes a StateError Enum variant as an argument and returns it:

fn echo_state_error_enum(state_error: StateError) -> StateError {
	state_error
}

To execute the contract function and validate the response, we can use the following code:

const enumVariant = 'Completed';
 
const { value } = await contract.functions
	.echo_state_error_enum(enumVariant)
	.txParams({ gasLimit: 10_000 })
	.simulate();
 
expect(value).toEqual(enumVariant);

In this example, we simply pass the Enum variant as a value to execute the contract function call.

Icon LinkEnum of Enums Example

In this example, the Error Enum is an Enum of two other Enums: StateError and UserError.

pub enum StateError {
Void: (),
Pending: (),
Completed: (),
}
 
pub enum UserError {
Unauthorized: (),
InsufficientPermissions: (),
}
 
pub enum Error {
StateError: StateError,
UserError: UserError,
}

Icon LinkUsing Enums of Enums with Contract Functions

Now, let's create a Sway contract function that accepts any variant of the Error Enum as a parameter and returns it immediately. This variant could be from either the StateError or UserError Enums.

fn echo_error_enum(error: Error) -> Error {
	error
}

Since the Error Enum is an Enum of Enums, we need to pass the function parameter differently. The parameter will be a TypeScript object:

const userErroVar = 'InsufficientPermissions';
 
const enumParam = { UserError: userErroVar };
 
const { value } = await contract.functions
	.echo_error_enum(enumParam)
	.txParams({ gasLimit: 10_000 })
	.simulate();
 
expect(value).toEqual(enumParam);

In this case, since the variant InsufficientPermissions belongs to the UserError Enum, we create a TypeScript object using the Enum name as the object key and the variant as the object value.

We would follow the same approach if we intended to use a variant from the StateError Enum:

const stateErrorVar = 'Completed';
 
const enumParam = { StateError: stateErrorVar };
 
const { value } = await contract.functions
	.echo_error_enum(enumParam)
	.txParams({ gasLimit: 10_000 })
	.simulate();
 
expect(value).toEqual(enumParam);