Writing Smart contracts on Tezos
Smart contracts on Tezos have their own storage. In other words, they have their own memory space on the blockchain for storing the data they need.
Smart contract languages on Tezos
Smart contracts on Tezos can be written in a number of languages:
- Python - using the SmartPy library
- OCaml - using the CamlLigo library
- JavaScript/TypeScript - using the jsLigo library.
Entrypoints in Smart Contracts
Entrypoints are invocable functions within a smart contract. Entrypoints have access to
- The parameters passed to the function
- The storage of the smart contract
Entrypoints can only have two effects. They can;
- Modify the storage of the contract itself
- Generate new transactions
Within those restrictions, smart contracts can do all kinds of logic that you may be used to from other programming languages, like loops, variables, and conditional statements. However, smart contracts can't:
- Access programs outside the blockchain, including calling external APIs
- Access other contracts' storage
- Change their code or any other contract's code
Here's a more complex example of a smart contract with an entrypoint and an automated test. Testing smart contracts is extremely important because you can't change them after they are deployed.
import smartpy as sp
@sp.module
def main():
class StoreValue(sp.Contract):
def __init__(self, value):
self.data.storedValue = value
@sp.entrypoint
def add(self):
self.data.storedValue += 2
if "templates" not in __name__:
@sp.add_test(name="StoreValue")
def test():
c1 = main.StoreValue(12)
scenario = sp.test_scenario(main)
scenario.h1("Store Value")
scenario += c1
c1.add()
scenario.verify(c1.data.storedValue == 14)
In the example above, we start off by initializing the storage in the __init__
function. When we deploy the smart contract, we'll pass the initial value of the storage, which the contract stores as storedValue
. Values to be stored on the blockchain are denoted using the object self.data
.
The decorator @sp.entrypoint
is used to denote an entrypoint within the smart contract. The add
entrypoint increases the storedValue
in the storage by 2.
Then the contract has an automated test. It starts by initializing the storage as 12. It calls the add
entrypoint once and verifies that the storage is now 14.