Skip to content

Script With Configurable

In the same way as contracts and predicates, Scripts also support configurable constants. This feature enables dynamic adjustment of certain values within your scripts.

Configurable constants are fairly straightforward to add and set in your scripts.

Let's consider the following script:

rust
script;

configurable {
    AMOUNT: u8 = 10,
}

fn main(inpputed_amount: u8) -> u8 {
    inpputed_amount + AMOUNT
}
See code in context

In this script, AMOUNT is a configurable constant with a default value of 10. The main function returns the sum of the inputted_amount and the configurable constant AMOUNT.

To change the value of the AMOUNT constant, we can use the setConfigurableConstants method as shown in the following example:

ts
const script = new Script(binHexlified, abiContents, wallet);

const configurableConstants = {
  AMOUNT: 81,
};

script.setConfigurableConstants(configurableConstants);

const inpputedValue = 10;

const { value } = await script.functions.main(inpputedValue).call();

const expectedTotal = inpputedValue + configurableConstants.AMOUNT;

expect(new BN(value as number).toNumber()).toEqual(expectedTotal);
See code in context

In this example, we're setting a new value 81 for the AMOUNT constant. We then call the main function with an inputted value of 10.

The expectation is that the script will return the sum of the inputted value and the new value of AMOUNT.

This way, configurable constants in scripts allow for more flexibility and dynamic behavior during execution.