In Sway, constants are values that remain unchanged throughout the lifecycle of the smart contract.
In the provided code, we define a smart contract named MyContract
with a function called test_func
that returns an instance of the Point
struct.
ZERO_B256
with the value 0x0000000000000000000000000000000000000000000000000000000000000000, which is a 256-bit value.ZERO_ADDRESS
, which is an address-type constant.Point
struct and, within its implementation, define an associated constant ZERO
, which is an instance of the Point
struct with x
and y
fields both set to 0.test_func
function of the smart contract demonstrates how to use these constants. It first defines a basic constant named MY_NUM
with the value 123. Then, it returns the associated constant ZERO
.The test_func
function of this smart contract ultimately returns an instance of the Point
struct. This simple example is intended to show you how to use basic and associated constants in Sway. We hope this tutorial helps you better understand constants in Sway.
contract; // Configurable constants configurable { MY_NUM: u64 = 123, OWNER: Address = Address::from(0x3333333333333333333333333333333333333333333333333333333333333333), POINT: Point = Point { x: 1, y: 2 }, } struct Point { x: u64, y: u64, } abi MyContract { fn test_func() -> (u64, Address, Point); } impl MyContract for Contract { fn test_func() -> (u64, Address, Point) { (MY_NUM, OWNER, POINT) } }