Icon HelpCircleForumIcon Link

⌘K

Icon HelpCircleForumIcon Link
Script With Configurable Constants

Icon LinkScript 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:

script;
 
configurable {
AMOUNT: u8 = 10,
}
 
fn main(inpputed_amount: u8) -> u8 {
inpputed_amount + AMOUNT
}

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:

const script = new Script(binHexlified, abiContents, wallet);
 
const configurableConstants = {
	AMOUNT: 81,
};
 
script.setConfigurableConstants(configurableConstants);
 
const inpputedValue = 10;
 
const { value } = await script.functions
	.main(inpputedValue)
	.txParams({ gasPrice, gasLimit: 10_000 })
	.call();
 
const expectedTotal = inpputedValue + configurableConstants.AMOUNT;
 
expect(new BN(value as number).toNumber()).toEqual(expectedTotal);

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.