Contract Calls
Contract calls allow you to execute state-changing functions in smart contracts. Unlike read-only calls, these create transactions that must be signed and broadcast to the network.
Basic contract call
Execute a simple contract function by creating a transaction with the required parameters.
import {
makeContractCall,
broadcastTransaction,
AnchorMode
} from '@stacks/transactions';
async function callContract() {
const txOptions = {
contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
contractName: 'my-contract',
functionName: 'transfer',
functionArgs: [],
senderKey: 'your-private-key',
network: 'testnet',
anchorMode: AnchorMode.Any,
};
const transaction = await makeContractCall(txOptions);
const broadcastResponse = await broadcastTransaction({ transaction });
console.log('Transaction ID:', broadcastResponse.txid);
}The makeContractCall function creates a transaction that will execute the specified function when confirmed on-chain.
Passing function arguments
Most contract functions require arguments. Use Clarity value constructors to match the expected parameter types.
Each Clarity type has a corresponding constructor function that ensures proper encoding for the blockchain.
Complex argument types
Optional and response values have dedicated constructors for proper type safety.
Contract call with STX transfer
Some contracts require STX to be sent along with the function call, such as when minting NFTs or paying for services.
Handling contract responses
Process transaction results and contract responses:
Multi-step contract interactions
Approve spending
First, create and broadcast an approval transaction.
This step ensures the spender is authorized before subsequent actions.
Execute swap after approval
After the approval is confirmed, execute the swap transaction.
This step performs the token swap that depends on the prior approval.
Last updated
Was this helpful?
