Read different resources from multiple addresses

86 views Asked by At

I have a set of addresses and resources

[
  {address1, resource1},
  {address2, resource2},
  {address3, resrouce3},
  ...
]

I want to read from every address the assigned resource.

Right now I am calling the API .../accounts/" + address + "/resource/" + resource for every address, which is slow (because of the multiple requests).

I want, if it's possible, to create a contract with a view function which is receiving the set of addresses and resources and then return a list with pulled data.

The only code which I managed is

module firstapp_addr::firstapp {

    #[view]
    public fun getResources(){
      
    }

}

I have no idea how I can write this function. This is my first interaction with move.

If someone can give me at least some examples.

I am also open to other solutions if the result is 1 request for all data.

Thank you.

1

There are 1 answers

2
TristanMas On

You can use this function structure as starting point :

module firstapp_addr::firstapp {
    struct ResourceData {
        // Define structure of resource data 
    }

    #[view]
    public fun getResources(addresses: vector<address>, resources: vector<vector<u8>>): vector<ResourceData> {
        let result: vector<ResourceData> = Vector::empty();

        let n = Vector::length(&addresses);
        assert(Vector::length(&resources) == n, 0); // Ensure addresses and resources have same length

        let i = 0;
        while (i < n) {
            let addr = *Vector::borrow(&addresses, i);
            let res_type = Vector::borrow(&resources, i);
            
            // implement the logic to pull data from each address and resource type
            // could call other functions or accessing data directly

            let data: ResourceData = ...; // Retrieve construct resource data
            Vector::push_back(&mut result, data);

            i = i + 1;
        }

        result
    }
}

Hoping it will be useful