Factory Contract in SmartPy

Pawan Dhanwani
Tezos India
Published in
2 min readSep 25, 2020

This article will take you through how you can develop and deploy a factory contract using Smartpy.

SmartPy is an intuitive and powerful smart contract development platform for Tezos.

What is a Factory contract?

Contracts that are capable of deploying contracts with a user or caller defined storage are called Factory contracts.

General Architecture

Unlike normal smart contracts, Factory contracts need to have at least two classes, one is a deployer class and another is a to-be-deployed class.

What we gonna deploy

import smartpy as sp

class IncDec(sp.Contract):

def __init__(self):
self.init_type(sp.TRecord(counter = sp.TInt))

@sp.entry_point
def increment(self,params):
self.data.counter += params.by

@sp.entry_point
def decrement(self,params):
self.data.counter -= params.by


class Deployer(sp.Contract):

def __init__(self):
self.incDec = IncDec()
self.init(x = sp.none)

@sp.entry_point
def deployContract(self,params):
self.data.x = sp.some(sp.create_contract(storage = sp.record(counter = sp.int(0)), contract = self.incDec))
self.data.x = sp.none

@sp.add_test(name = "Test")

def test():

obj = Deployer()
scenario = sp.test_scenario()
scenario += obj
scenario += obj.deployContract()

This is a very simple scenario we are going to deploy a contract which will deploy an increment and decrement contract.

Let us see how it works.

Deploy the factory contract.

Deploy another contract (Increment Decrement in this case).

Played with the newly deployed contract.

Where can this be useful?

This type of contract can be very useful when a contract needs to be generated in a decentralized manner among a group of participants like lending and gambling contracts.

Thanks for reading.

Follow us on Twitter and Telegram to stay updated about all cool updates and events and activities happening at Tezos India.

--

--