Introducing Stateful Properties

How I Learned to Stop Worrying and Love Bitcoin State

sCrypt
Coinmonks
Published in
2 min readOct 6, 2021

--

One of the most challenging parts for sCrypt beginners is to keep internal state in a contract. We provide an elegant solution using state decorators.

State is carried across UTXOs in a contract

The Problem

Bitcoin smart contract uses UTXO model and is stateless by default. Previously, we have developed a general approach to maintain states in a contract, built upon the OP_PUSH_TX technique. Even the approach proves keeping state is feasible, it is awkward at best.

Counter contract

For instance, in the above contract, we maintain a state, counter, and increase it by one every time increment() is called. We only maintain a counter here and there is already tons of boilerplate code, mostly to serialize and deserialize the state (Line 5–9 and Line 15). The core logic is just one line at Line 12. Code grows more cumbersome and error-prone when the state becomes more complex.

The Solution: State Decorators

With the new state decorator approach, you can maintain state in a contract with three simple steps, as shown below:

  1. Declare any property that is part of the state with a decorator¹ @state.
  2. Use the stateful property as a normal property: read and update it.
  3. When you are ready to pass the new state into the output[s] of the current spending transaction, simply call a built-in function this.getStateScript() to get the locking script containing the latest stateful properties. It is automatically generated for every stateful contract, i.e., a contract that has at least one property decorated with @state.
Counter contract

As you can see, this is more concise and secure than manually serializing and deserializing state. The advantage is more significant when the state grows.

SDK Support

We have updated our JavaScript/TypeScript SDK to support stateful properties, greatly simplifying interactions with stateful contracts. Other SDKs (Python & Go)will be updated soon.

--

--

sCrypt
Coinmonks

sCrypt (https://scrypt.io) is a web3 development platform specialized in UTXO-blockchains like Bitcoin