0

here's the contract that has the resource in the resource

pub resource interface InventoryPublic{
        pub var items: @{UInt64: Grocery}
    }

    pub resource Inventory: InventoryPublic{
        pub var items: @{UInt64: Grocery}

        pub fun addItem(item: @Grocery) {
            var olditem <- self.items[item.uuid] <- item
            //self.items[item.uuid] <-! item
            destroy olditem
        }
        init(){
                self.items <- {}
        }

        destroy(){
            destroy self.items
        }
    }

    pub fun createInventory(): @Inventory{
            return <- create Inventory()
    }

    pub fun addItems(name: String, nos: Int, price: UFix64): @Grocery{

            return <- create Grocery(_grocery: name,_units : nos, _price: price)
    }

here's the script that displays the keys which end up returning the uuids, how can i retrieve the values?

import AgroLink from 0xf8d6e0586b0a20c7


pub fun main(acct: Address){
    let myitems = getAccount(acct).getCapability(/public/InventoryPublic)
                        .borrow<&AgroLink.Inventory>()
                        ?? panic("Can't get public link!")
    log(myitems.items.keys)
}

if i can retrieve the values, is it possible to update values in it? if so could you please tell me how?

1 Answers1

0

In order to get the Grocery values, you have two options:

  1. (Bad) You can add a function to remove the Grocery, read its content, and then put it back.
  2. (Good) You can add a function that returns a reference to the Grocery.
pub resource Inventory: InventoryPublic{
        pub var items: @{UInt64: Grocery}

        pub fun addItem(item: @Grocery) {
            var olditem <- self.items[item.uuid] <- item
            //self.items[item.uuid] <-! item
            destroy olditem
        }

        // returns a reference to a Grocery 
        pub fun getGrocery(itemId: UInt64): &Grocery? {
            return &self.items[itemId] as &Grocery?
        }

        init(){
                self.items <- {}
        }

        destroy(){
            destroy self.items
        }
}

Then in your script, you can simply call this function:

import AgroLink from 0xf8d6e0586b0a20c7


pub fun main(acct: Address){
    let myitems = getAccount(acct).getCapability(/public/InventoryPublic)
                        .borrow<&AgroLink.Inventory>()
                        ?? panic("Can't get public link!")
    let groceryList: [&AgroLink.Grocery?] = []
    for itemId in myitems.items.keys {
       groceryList.append(myitems.getGrocery(itemId: itemId))
    }

    // you now have a list of all your grocerys
}
Jacob Tucker
  • 132
  • 7