0x2::address
to_u256
from_u256
from_bytes
to_bytes
to_ascii_string
to_string
from_ascii_bytes
hex_char_value
length
max
use 0x1::ascii;
use 0x1::bcs;
use 0x1::string;
use 0x2::hex;
Error from from_bytes
when it is supplied too many or too few bytes.
const EAddressParseError: u64 = 0;
The length of an address, in bytes
const LENGTH: u64 = 32;
const MAX: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
to_u256
Convert a
into a u256 by interpreting a
as the bytes of a big-endian integer
(e.g., to_u256(0x1) == 1
)
public fun to_u256(a: address): u256
public native fun to_u256(a: address): u256;
from_u256
Convert n
into an address by encoding it as a big-endian integer (e.g., from_u256(1) = @0x1
)
Aborts if n
> MAX_ADDRESS
public fun from_u256(n: u256): address
public native fun from_u256(n: u256): address;
from_bytes
Convert bytes
into an address.
Aborts with EAddressParseError
if the length of bytes
is not 32
public fun from_bytes(bytes: vector<u8>): address
public native fun from_bytes(bytes: vector<u8>): address;
to_bytes
Convert a
into BCS-encoded bytes.
public fun to_bytes(a: address): vector<u8>
public fun to_bytes(a: address): vector<u8> {
bcs::to_bytes(&a)
}
to_ascii_string
Convert a
to a hex-encoded ASCII string
public fun to_ascii_string(a: address): ascii::String
public fun to_ascii_string(a: address): ascii::String {
hex::encode(to_bytes(a)).to_ascii_string()
}
to_string
Convert a
to a hex-encoded string
public fun to_string(a: address): string::String
public fun to_string(a: address): string::String {
to_ascii_string(a).to_string()
}
from_ascii_bytes
Converts an ASCII string to an address, taking the numerical value for each character. The
string must be Base16 encoded, and thus exactly 64 characters long.
For example, the string â00000000000000000000000000000000000000000000000000000000DEADB33Fâ
will be converted to the address @0xDEADB33F.
Aborts with EAddressParseError
if the length of s
is not 64,
or if an invalid character is encountered.
public fun from_ascii_bytes(bytes: &vector<u8>): address
public fun from_ascii_bytes(bytes: &vector<u8>): address {
assert!(bytes.length() == 64, EAddressParseError);
let mut hex_bytes = vector[];
let mut i = 0;
while (i < 64) {
let hi = hex_char_value(bytes[i]);
let lo = hex_char_value(bytes[i+1]);
hex_bytes.push_back((hi << 4) | lo);
i = i + 2;
};
from_bytes(hex_bytes)
}
hex_char_value
fun hex_char_value(c: u8): u8
fun hex_char_value(c: u8): u8 {
if (c >= 48 && c <= 57) c - 48 // 0-9
else if (c >= 65 && c <= 70) c - 55 // A-F
else if (c >= 97 && c <= 102) c - 87 // a-f
else abort EAddressParseError
}
length
Length of a Sui address in bytes
public fun length(): u64
max
Largest possible address
public fun max(): u256