Introducing Stateful Properties
How I Learned to Stop Worrying and Love Bitcoin State
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.
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.
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:
- Declare any property that is part of the state with a decorator¹
@state
. - Use the stateful property as a normal property: read and update it.
- 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
.
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.
[1] The decorator syntax is inspired by Python, Java, and TypeScript.
Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing
Also, Read
- Grid Trading Bots | Cryptohopper Review | Bexplus Review
- 7 Best Zero Fee Crypto Exchange Platforms
- Decentralized Exchanges | Bitbns FIP | Pionex Review
- 10 Best Places to Buy Crypto with Credit Card
- Huobi Review | OKEx Margin Trading | Futures Trading
- Sparrow Exchange Review | Nash Exchange Review
- Best Crypto Trading Bots in the US | Changelly Review
- Earn Passive Income Using Crypto Arbitrage In India