Addresses and Address Functions
Addresses
The type Address
represents an address. Addresses are unsigned integers with a size of 64 bits (8 bytes). Hexadecimal integer literals can be used to create address values:
_13// Declare a constant that has type `Address`._13//_13let someAddress: Address = 0x436164656E636521_13_13// Invalid: Initial value is not compatible with type `Address`,_13// it is not a number._13//_13let notAnAddress: Address = ""_13_13// Invalid: Initial value is not compatible with type `Address`._13// The integer literal is valid, however, it is larger than 64 bits._13//_13let alsoNotAnAddress: Address = 0x436164656E63652146757265766572
Integer literals are not inferred to be an address:
_10// Declare a number. Even though it happens to be a valid address,_10// it is not inferred as it._10//_10let aNumber = 0x436164656E636521_10_10// `aNumber` has type `Int`
An Address
can also be created using a byte array or string.
_17// Declare an address with hex representation as 0x436164656E636521._17let someAddress: Address = Address.fromBytes([67, 97, 100, 101, 110, 99, 101, 33])_17_17// Invalid: Provided value is not compatible with type `Address`. The function panics._17let invalidAddress: Address = Address.fromBytes([12, 34, 56, 11, 22, 33, 44, 55, 66, 77, 88, 99, 111])_17_17// Declare an address with the string representation as "0x436164656E636521"._17let addressFromString: Address? = Address.fromString("0x436164656E636521")_17_17// Invalid: Provided value does not have the "0x" prefix. Returns Nil_17let addressFromStringWithoutPrefix: Address? = Address.fromString("436164656E636521")_17_17// Invalid: Provided value is an invalid hex string. Return Nil._17let invalidAddressForInvalidHex: Address? = Address.fromString("0xZZZ")_17_17// Invalid: Provided value is larger than 64 bits. Return Nil._17let invalidAddressForOverflow: Address? = Address.fromString("0x436164656E63652146757265766572")
Address functions
Addresses have multiple built-in functions you can use.
-
_10view fun toString(): String
Returns the string representation of the address. The result has a
0x
prefix and is zero-padded._10let someAddress: Address = 0x436164656E636521_10someAddress.toString() // is "0x436164656E636521"_10_10let shortAddress: Address = 0x1_10shortAddress.toString() // is "0x0000000000000001" -
_10view fun toBytes(): [UInt8]
Returns the byte array representation (
[UInt8]
) of the address._10let someAddress: Address = 0x436164656E636521_10_10someAddress.toBytes() // is `[67, 97, 100, 101, 110, 99, 101, 33]`