1

I would like for a resource to have a function where at the end of the function it self destructs by calling destroy self

pub resource SelfDestructingConsumable {
  pub fun consume() {
    // do some stuff
    destroy self
  }
}

The type checker complains that this is illegal

Cannot destroy self

I'm wondering if anyone has any creative ways around this? I have a feeling that maybe it should be wrapped in some sort of ConsumableCollection or ConsumableManager like so

pub resource ConsumableCollection {
  pub let consumables: @{UInt64: SelfDestructingConsumable}
  pub fun consume(id: UInt64) {
    let consumable <- consumables.remove(id)
    // do some stuff
    destroy consumable
  }
}

But i feel that it makes more sense to be able to just use a consumable and have it independently self destruct.

I'd like to get some thoughts or ideas on a better way to do this.

Aylii
  • 525
  • 4
  • 10
  • could you elaborate more on the use case? – rrrkren Sep 01 '22 at 18:25
  • @rrrkren let's say a health potion in a game, i wanted to do healthPotion.use() which would increase player health then destroy itself. But now it's clearer that the player that contains the health potion would probably have the useHealthPotion which then destroys said potion after increasing self.health – Aylii Sep 01 '22 at 23:29

1 Answers1

4

You do need to create a wrapper around it in order to destroy like you have suggested. Some use cases also do this in a transaction itself. It depend upon your usecase, would also strongly suggest emitting an Burned event or something when you do so as it is a good practise to always emit events on state changes.

bjartek
  • 929
  • 1
  • 5
  • 11