Scratch Space
Scratch space is a temporary place to store values for later use in your program. It is temporary because any changes to scratch space do not persist beyond the current transaction. Scratch space can be used in both Application and Signature mode.
Scratch space consists of 256 scratch slots, each capable of storing one integer or byte slice. When
using the ScratchVar class to work with scratch space, a slot is automatically assigned to
each variable.
ScratchVar: Writing and Reading to/from Scratch Space
To write to scratch space, first create a ScratchVar object and pass in the TealType
of the values that you will store there. It is possible to create a ScratchVar that can store
both integers and byte slices by passing no arguments to the ScratchVar constructor, but note
that no type checking takes places in this situation. It is also possible to manually specify which
slot ID the compiler should assign the scratch slot to in the TEAL code. If no slot ID is specified,
the compiler will assign it to any available slot.
To write or read values, use the corresponding ScratchVar.store or ScratchVar.load methods. ScratchVar.store must be invoked before invoking ScratchVar.load.
For example:
myvar = ScratchVar(TealType.uint64) # assign a scratch slot in any available slot
program = Seq([
myvar.store(Int(5)),
Assert(myvar.load() == Int(5))
])
anotherVar = ScratchVar(TealType.bytes, 4) # assign this scratch slot to slot #4
DynamicScratchVar: Referencing a ScratchVar
DynamicScratchVar functions as a pointer to a ScratchVar instance.
Reference a ScratchVar instance by invoking DynamicScratchVar.set_index. DynamicScratchVar.set_index must be invoked before using DynamicScratchVar.load and DynamicScratchVar.store.
Here’s an example to motivate usage. The example shows how a DynamicScratchVar updates the value of a referenced ScratchVar from 7 to 10.
s = ScratchVar(TealType.uint64)
d = DynamicScratchVar(TealType.uint64)
return Seq(
d.set_index(s),
s.store(Int(7)),
d.store(d.load() + Int(3)),
Assert(s.load() == Int(10)),
Int(1),
)