1

I'm trying to ensure my contract is upgradable and I learn best by looking at existing examples. Does anyone have any good examples to look at?

Here are some links to previous stackoverflow Q&A's discussuing smart contract updates:

  1. How to upgrade a smart contract
  2. Upgradeable Contracts: Proxy Delegate vs Stored Lambdas

1 Answer 1

2

Stored lambdas approach:

It allows any packable value as a parameter and the method that computes the new value can be updated.

import smartpy as sp

class Upgradable(sp.Contract):
  def __init__(self, **kargs):
    self.init(**kargs)

  @sp.entry_point
  def calc(self, data):
    self.data.value = self.data.logic(data)

  @sp.entry_point
  def updateLogic(self, logic):
    self.data.logic = logic

@sp.add_test(name = "Upgradable")
def test():
  scenario = sp.test_scenario()
  scenario.h1("Upgradable")

  def logic1(data):
    t = sp.TRecord(x = sp.TNat, y = sp.TNat)
    unpacked = sp.unpack(data, t).open_some(message = "Cannot UNPACK")
    
    sp.result(unpacked.x + unpacked.y)
    
  def logic2(data):
    t = sp.TRecord(x = sp.TNat, y = sp.TNat, z = sp.TNat)
    unpacked = sp.unpack(data, t).open_some(message = "Cannot UNPACK")
    
    sp.result(unpacked.x + unpacked.y + unpacked.z)

  c1 = Upgradable(value = 0, logic = sp.build_lambda(logic1))
  scenario += c1

  # Use logic version 1
  scenario += c1.calc(sp.pack(sp.record(x = 1, y = 2)))

  # Update logic to version 2
  scenario += c1.updateLogic(sp.build_lambda(logic2))

  # Use logic version 2
  scenario += c1.calc(sp.pack(sp.record(x = 1, y = 2, z = 3)))

The proxy approach is also simple, it just points to the latest contract whenever a new one gets deployed.

3
  • awesome. thanks. if I were to want to support an arbitrary number of operations, I suppose I would need to use a proxy delegate with a multipurpose entrypoint that can check the storage to see if a param.function is supported and call that function on the address associated with that function?
    – JJJ
    Apr 9, 2021 at 19:12
  • 1
    I'm not sure I understood the question, but yes, it is possible. Apr 9, 2021 at 19:26
  • 1
    We are also working on an extension of the lazy entry point compilation for upgradable contracts. We expect to have something sometime in May.
    – FFF
    Apr 9, 2021 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.