-1

I am getting "sp.if: cannot unify branches" error from a onchain view method. Below is the code snippet. Full error msg: [error] Type Error sp.TRecord( locked_balance = sp.TNat, refundable_balance = sp.TNat, usable_balance = sp.TNat, user_balance = sp.TNat) is not sp.TUnit sp.if: cannot unify branches

@sp.onchain_view()
def balance_of(self, params):
    sp.set_type(params, sp.TRecord(owner=sp.TAddress, coin_name=sp.TString))

    sp.if params.coin_name == self.data.native_coin_name:
        sp.result(sp.record(usable_balance = sp.nat(0),
                                locked_balance = self.data.balances[sp.record(address=params.owner, coin_name=params.coin_name)].locked_balance,
                                refundable_balance = self.data.balances[sp.record(address=params.owner, coin_name=params.coin_name)].refundable_balance,
                                user_balance = sp.nat(2)))

    fa2_address = self.data.coins[params.coin_name]
    usable_balance=sp.nat(1)
    sp.if fa2_address != sp.address("tz10000"):
        pass   
    sp.if fa2_address == sp.address("tz10000"):
        pass
    sp.result(sp.record(usable_balance=usable_balance,
                            locked_balance=self.data.balances[sp.record(address=params.owner, coin_name=params.coin_name)].locked_balance,
                            refundable_balance=self.data.balances[sp.record(address=params.owner, coin_name=params.coin_name)].refundable_balance,
                            user_balance=user_balance))

2 Answers 2

1

You need to return something of the same type (or fail the execution) in the case where the if statement evaluates to false. An untested example:

    sp.else:
        // return a default value
        sp.result(sp.record(usable_balance = sp.nat(0),
                                locked_balance = sp.nat(0),
                                refundable_balance = sp.nat(0),
                                user_balance = sp.nat(0)))
        // or just use failwith
        // sp.failwith("error message")
2
  • Yeah there is something below if the case fails. I have edited the question above.
    – theBatMan
    Commented Apr 4, 2023 at 10:26
  • Looks like putting everything below if into else would make sense. And this solve the issue. Thank you!
    – theBatMan
    Commented Apr 4, 2023 at 10:32
1

You are missing the else branch:

sp.else:
  sp.failwith("INVALID_COIN_NAME")

Michelson is a functional and strongly typed language, every branch must result in the same type or explicitly fail.

Your Answer

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

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