Skip to Content

Memory storage and scheduled block-end flush

Focus: one in-block batching contract that queues values in memory and flushes them once at block end.

Open in Playground 

memory_batch.slx
const QUEUE_KEY: string = "queued_values" const MAX_GAS: u64 = 200000 fn flush_queue(args: any[]) -> u64 { let memory: MemoryStorage = MemoryStorage::new(true) let values: u64[] = memory.load(QUEUE_KEY).unwrap_or([]) let total: u64 = values.iter().sum() // Debug print: by default, nodes do not show println output. println("flushing queued values") memory.delete(QUEUE_KEY) return total } entry queue(value: u64) { let memory: MemoryStorage = MemoryStorage::new(true) let values: u64[] = memory.load(QUEUE_KEY).unwrap_or([]) values.push(value) memory.store(QUEUE_KEY, values) let pending: optional<ScheduledExecution> = ScheduledExecution::get_pending(null) if pending == null { let scheduled: optional<ScheduledExecution> = ScheduledExecution::new_at_block_end( flush_queue, [], MAX_GAS, true ) require(scheduled != null, "schedule failed") } return 0 }

How it works

  • MemoryStorage::new(true) shares temporary state across executions of this contract in the same block.
  • queue(value) appends one value to the in-memory array under QUEUE_KEY.
  • ScheduledExecution::get_pending(null) prevents scheduling duplicate flush callbacks.
  • ScheduledExecution::new_at_block_end(...) registers flush_queue to run at block end with a gas limit.
  • flush_queue(args) sums the queued values, prints a local debug message, then deletes the temporary key.
Last updated on