使用ASSERT和RAISE检查输入并验证状态。 当发生错误时,它将暂停整个函数调用,撤消所有更改。 您仍需为失败的交易支付gas费。
# @version ^0.3.7
x: public(uint256)
owner: public(address)
@external
def __init__():
self.owner = msg.sender
@external
def testAssert(x: uint256):
assert x >= 1, "x < 1"
# self.x will not be updated if there is an error from line above
self.x = x
@external
def testRaise(x: uint256):
# same check as above using "raise"
if x <= 1:
raise "x < 1"
self.x = x
@internal
def _testErrorBubblesUp(x: uint256):
assert x >= 1, "x < 1"
self.x = x
@external
def testErrorBubblesUp(x: uint256):
self._testErrorBubblesUp(x)
# self.x = 123 will not be executed if there is an error
# from function above
self.x = 123
@external
def setOwner(owner: address):
assert msg.sender == self.owner, "!owner"
assert owner != ZERO_ADDRESS, "owner = zero"
self.owner = owner
Yanbo的Twitter|Web3Club的Twitter
加入Web3Club 官方讨论群:YanboTravelAllWorld(微信号)