Icon HelpCircleForumIcon Link

⌘K

Icon HelpCircleForumIcon Link
Configurable Constants

Icon LinkConfigurable constants

In Sway, you can define configurable constants which can be changed during the contract deployment in the SDK. Here is an example how the constants are defined.

contract;
 
#[allow(dead_code)]
enum EnumWithGeneric<D> {
    VariantOne: D,
    VariantTwo: (),
}
 
struct StructWithGeneric<D> {
    field_1: D,
    field_2: u64,
}
 
configurable {
    U8: u8 = 8u8,
    BOOL: bool = true,
    ARRAY: [u32; 3] = [253u32, 254u32, 255u32],
    STR_4: str[4] = __to_str_array("fuel"),
    STRUCT: StructWithGeneric<u8> = StructWithGeneric {
field_1: 8u8,
field_2: 16,
    },
    ENUM: EnumWithGeneric<bool> = EnumWithGeneric::VariantOne(true),
}
 
abi TestContract {
    fn return_configurables() -> (u8, bool, [u32; 3], str[4], StructWithGeneric<u8>, EnumWithGeneric<bool>);
}
 
impl TestContract for Contract {
    fn return_configurables() -> (u8, bool, [u32; 3], str[4], StructWithGeneric<u8>, EnumWithGeneric<bool>) {
(U8, BOOL, ARRAY, STR_4, STRUCT, ENUM)
    }
}
 

Each of the configurable constants will get a dedicated with method in the SDK. For example, the constant STR_4 will get the with_STR_4 method which accepts the same type as defined in the contract code. Below is an example where we chain several with methods and deploy the contract with the new constants.

    abigen!(Contract(
name = "MyContract",
abi = "packages/fuels/tests/contracts/configurables/out/debug/configurables-abi.json"
    ));
 
    let wallet = launch_provider_and_get_wallet().await?;
 
    let new_str: SizedAsciiString<4> = "FUEL".try_into()?;
    let new_struct = StructWithGeneric {
field_1: 16u8,
field_2: 32,
    };
    let new_enum = EnumWithGeneric::VariantTwo;
 
    let configurables = MyContractConfigurables::new()
.with_STR_4(new_str.clone())
.with_STRUCT(new_struct.clone())
.with_ENUM(new_enum.clone());
 
    let contract_id = Contract::load_from(
"tests/contracts/configurables/out/debug/configurables.bin",
LoadConfiguration::default().with_configurables(configurables),
    )?
    .deploy(&wallet, TxPolicies::default())
    .await?;
 
    let contract_instance = MyContract::new(contract_id, wallet.clone());