blockchaincadenceonflow-cadence

How do you make a resource self-destruct on flow / cadence?


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.


Solution

  • 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.