Icon SunFilledIcon MoonStars

Icon LinkConfigurable Constants

Sway introduces a powerful feature: configurable constants. When creating a contract, you can define constants, each assigned with a default value.

Before deploying the contract, you can then redefine the value for these constants, it can be all of them or as many as you need.

This feature provides flexibility for dynamic contract environments. It allows a high level of customization, leading to more efficient and adaptable smart contracts.

Icon LinkDefining Configurable Constants

Below is an example of a contract in which we declare four configurable constants:

contract;
 
enum MyEnum {
Checked: (),
Pending: (),
}
 
struct MyStruct {
x: u8,
y: u8,
state: MyEnum,
}
 
configurable {
age: u8 = 25,
tag: str[4] = "fuel",
grades: [u8; 4] = [3, 4, 3, 2],
my_struct: MyStruct = MyStruct {
	x: 1,
	y: 2,
	state: MyEnum::Pending,
},
}
 
abi EchoConfigurables {
fn echo_configurables() -> (u8, str[4], [u8; 4], MyStruct);
}
 
impl EchoConfigurables for Contract {
fn echo_configurables() -> (u8, str[4], [u8; 4], MyStruct) {
	(age, tag, grades, my_struct)
}
}

In this contract, we have a function echo_configurables that returns the values of the configurable constants.

If each of these constants has new values that have been assigned to them, the function will return the updated values. Otherwise, the function will return the default values.

Icon LinkSetting New Values For Configurable Constants

During contract deployment, you can define new values for the configurable constants. This is achieved as follows:

const configurableConstants: typeof defaultValues = {
	age: 30,
	tag: 'leuf',
	grades: [10, 9, 8, 9],
	my_struct: {
	x: 11,
	y: 22,
	state: 'Checked',
	},
};
 
const factory = new ContractFactory(bin, abi, wallet);
 
const contract = await factory.deployContract({
	configurableConstants,
});

You can assign new values to any of these configurable constants.

If you wish to assign a new value to just one constant, you can do the following:

const configurableConstants = {
	age: 10,
};
 
const factory = new ContractFactory(bin, abi, wallet);
 
const contract = await factory.deployContract({
	configurableConstants,
});

Please note that when assigning new values for a Struct, all properties of the Struct must be defined. Failing to do so will result in an error:

const configurableConstants = {
	my_struct: {
	x: 2,
	},
};
 
const factory = new ContractFactory(bin, abi, wallet);
 
await expect(factory.deployContract({ configurableConstants })).rejects.toThrowError();

Was this page helpful?