Build an NFT post-condition
Create post-conditions for NFT transfers to ensure specific tokens are or aren't transferred
import { Pc, Cl } from '@stacks/transactions';// Ensure a specific NFT will be sentconst sendPC = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM").willSendAsset().nft('ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.cool-nfts::nft-token', Cl.uint(42));// Ensure a specific NFT will NOT be sentconst keepPC = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM").willNotSendAsset().nft('ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.cool-nfts::nft-token', Cl.uint(1));
Use cases
- Protecting valuable NFTs from accidental transfers
- Ensuring specific NFTs are transferred in marketplace transactions
- Safeguarding NFT collections during contract interactions
Key concepts
NFT post-conditions use the .nft()
method which requires:
- Asset identifier: Contract address + asset name with
::
separator - Token ID: The specific NFT ID as a Clarity value (using
Cl.uint()
)
NFT post-condition types
// Will send a specific NFTconst willSend = Pc.principal(address).willSendAsset().nft(assetIdentifier, tokenId);// Will NOT send a specific NFTconst willNotSend = Pc.principal(address).willNotSendAsset().nft(assetIdentifier, tokenId);
Complete example
import {AnchorMode,Cl,makeContractNonFungiblePostCondition,NonFungibleConditionCode,Pc,PostConditionMode,createAssetInfo,} from '@stacks/transactions';// Define the NFT detailsconst nftContract = 'ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.art-gallery';const nftAsset = 'artwork';const tokenId = Cl.uint(123);// Using the Pc builderconst nftPostCondition = Pc.principal(senderAddress).willSendAsset().nft(`${nftContract}::${nftAsset}`, tokenId);// Alternative: Using the standard functionconst altPostCondition = makeContractNonFungiblePostCondition(senderAddress,nftContract,NonFungibleConditionCode.Sends,createAssetInfo(nftContract.split('.')[0], nftContract.split('.')[1], nftAsset),tokenId);// Use in transactionconst txOptions = {// ... other optionspostConditions: [nftPostCondition],postConditionMode: PostConditionMode.Deny,};
Package installation
Terminal
$npm install @stacks/transactions