Skip to content

Vectors

In Sway, a Vector is a dynamic-sized collection of elements of the same type. Vectors can hold arbitrary types, including non-primitive types.

Working with Vectors in the SDK

A basic Vector in Sway is similar to a TypeScript Array:

ts
// Sway Vec<u8>
// #context const basicU8Vector = [1, 2, 3];

Consider the following example of a EmployeeData struct in Sway:

rust
pub struct EmployeeData {
    name: str[8],
    age: u8,
    salary: u64,
    idHash: b256,
    ratings: [u8; 3],
    isActive: bool,
}

Now, let's look at the following contract method. It receives a Vector of the Transaction struct type as a parameter and returns the last Transaction entry from the Vector:

ts
fn echo_last_employee_data(employee_data_vector: Vec<EmployeeData>) -> EmployeeData {
    employee_data_vector.get(employee_data_vector.len() - 1).unwrap()
}

The code snippet below demonstrates how to call this Sway contract method, which accepts a Vec<Transaction>:

ts
// #import { getRandomB256 };

const employees = [
  {
    name: 'John Doe',
    age: 30,
    salary: 8000,
    idHash: getRandomB256(),
    ratings: [1, 2, 3],
    isActive: true,
  },
  {
    name: 'Everyman',
    age: 31,
    salary: 9000,
    idHash: getRandomB256(),
    ratings: [5, 6, 7],
    isActive: true,
  },
];
const { value } = await contract.functions.echo_last_employee_data(employees).simulate();

Working with Bytecode in the SDK

Some Sway functions require you to pass in bytecode to the function. The type of the bytecode parameter is usually Vec<u8>.

Take the compute_bytecode_root function from the bytecode Sway library, for example.

rust
contract;

use bytecode::*;

abi MyContract {
    fn compute_bytecode_root(bytecode_input: Vec<u8>) -> b256;
}

impl MyContract for Contract {
    fn compute_bytecode_root(bytecode_input: Vec<u8>) -> bool {
        let root = compute_bytecode_root(bytecode_input);
        return root;
    }
}

To pass bytecode to this function, you can make use of the arrayify function to convert the bytecode file contents into a UInt8Array, the TS compatible type for Sway's Vec<u8> type and pass it the function like so:

ts
// #import { arrayify, readFile };

const bytecode = await readFile(bytecodePath);

const { value: bytecodeRoot } = await bytecodeContract.functions
  .compute_bytecode_root(arrayify(bytecode))
  .call();

Returning vectors

Currently, returning vectors is not supported by Sway. If you try returning a type that is or contains a Vector, you will get a compile-time error.