Examples

These examples showcase the power of post-conditions through multiple scenarios you might encounter as a Stacks developer.

No transfers

A simple contract function with no asset transfers specified.

On the frontend, this should be set to a postConditionMode of "deny", without needing a specific post-condition statement.

(define-public (no-transfers)
  (ok "no transfer events executed.")
)

User Expectation: No assets will be transferred out of their wallet.

Result: No transfers made during transaction execution. Transaction is confirmed.


Single STX transfer

A function that contains a single asset transfer of 10 STX from the tx-sender to the contract.

(define-public (single-stx-transfer)
  (stx-transfer? u10000000 tx-sender (as-contract tx-sender))
) 

User Expectation: Allow only 10 STX to be transferred.

Result: 10 STX are transferred from the sender's wallet as the user expected. Transaction is confirmed.


Multiple STX transfers

When multiple transfer events happen for the same asset on the same address, your post-condition statement should aggregate the net total amount of that asset being transferred during the execution of the entire function.

The contract first transfers 20 STX then transfers another 10 STX from the sender.

User Expectation: Allow less than 30 STX to be transferred.

Result: 30 STX was transferred out of the sender's wallet as expected. Transaction is confirmed.


Mint and Burn Events

A post-condition statement is needed for burn events, but not needed for mint events.

User Expectation: Allow exactly 10 STX to be transferred for burning.

Result: 10 STX transferred out of the sender's wallet to be burned. Some good-token were minted to the user. No other asset transfers happened. Transaction is confirmed.


Uncertain asset transfer amount

The function below demonstrates a scenario where the amount of STX to send is dynamic and uncertain. Having two post-condition statements that capture a range would be appropriate.

User Expectation: Allow between 0 STX and 1 STX to be transferred from the user.

Result: If the actual amount of STX is within the specified expectated range, the transaction will confirm. If not, the transaction will abort and fail.


Hidden asset transfers

The function below contains a bunch of asset transfer events that are obfiscated in a way where it may not be noticeable at first glance. It's setup for the tx-sender to pay for a cool-nft for 2 STX, but unbeknownst to the user, the function will attempt to transfer out a few of the user's good tokens AND send the users some evil tokens.

User Expectation: Allow the transfer of 2 STX for a cool-nft asset.

Result: The contract attempted to perform other asset transfers that were not covered by the declared post-conditions. Transaction will abort and fail.

Last updated

Was this helpful?