I am transferring some tez to an account and i want to assert balance of account before and after the transfer. How do i get the balance of test account in SmartPy.
3 Answers
There is no way to get the balance of test accounts.
You can replace the test account by a contract with an entrypoint named default
. You can set the contract's initial value and compare its balance as it is a contract.
import smartpy as sp
class MyContract(sp.Contract):
@sp.entry_point
def send_tez(self, destination, amount):
sp.send(destination, amount)
class Receiver(sp.Contract):
@sp.entry_point
def default(self):
pass
@sp.add_test(name = "Test")
def test():
sc = sp.test_scenario()
c1 = MyContract()
c1.set_initial_balance(sp.tez(42))
sc += c1
c2 = Receiver()
c2.set_initial_balance(sp.tez(0))
sc += c2
c1.send_tez(destination=c2.address, amount=sp.tez(10))
sc.show(c2.balance)
You can do so using sp.verify
and .balance
import smartpy as sp
class MyContract(sp.Contract):
def __init__(self, **kargs):
self.init(**kargs)
@sp.add_test(name = "First test")
def test():
sc = sp.test_scenario()
c1 = MyContract()
sc += c1
# and its balance
sc.verify(c1.balance == sp.tez(0))
-
This is for the balance of the contract. I am looking for how to get balance of a test address. Any way to do that? Thanks! Commented Feb 1, 2023 at 11:10
It is not possible to get the balance of an implicit account from the execution context of a smart contract in general, so I don't think SmartPy would include such a feature.
It doesn't really make sense to compare balances because, when you transfer tez at the end of the execution of the contract, the balance of the implicit account will only be updated AFTER the contract finished executing (because of the order of execution of the operations). The contract has to finish executing first before any side effects are saved in the blockchain, including tez transfers or even updates of its own storage!
-
I think the question was in the test scenario, not in the contract's code. Commented Feb 1, 2023 at 16:52