Docs
Calling contracts

Calling contract functions

This is the most complex transaction type that we can work with -- this is for when you're interested in calling a specific public function for a given smart contract deployed to the blockchain.

💡

If you're interested in learning how to call read-only contract functions, check out this guide.

Usage

@micro-stacks/react exports a hook that you will use to call contract functions: useOpenContractCall.

import { useOpenContractCall } from '@micro-stacks/react';

Parameters

  • contractAddress: The principal that deployed the contract you want to interact with.
  • contractName: The name of the contract.
  • functionName: The specific function that you want to call.
  • functionArgs: An array of either hex-encoded ClarityValue or ClarityValue values.
  • validateWithAbi: A boolean value, if set to true, the function will attempt to fetch the ABI for the contract. Alternatively, you can pass the ABI directly to this parameter.

Example

export const MyContractCallTx = () => {
  const { openContractCall, isRequestPending } = useOpenContractCall();
  const { stxAddress } = useAccount();
  const [response, setResponse] = useState(null);

  const handleOpenContractCall = async () => {
    const functionArgs = [
      uintCV(1234),
      intCV(-234),
      bufferCV(utf8ToBytes('hello, world')),
      stringAsciiCV('hey-ascii'),
      stringUtf8CV('hey-utf8'),
      standardPrincipalCV('ST1X6M947Z7E58CNE0H8YJVJTVKS9VW0PHEG3NHN3'),
      trueCV(),
    ];

    const postConditions = [
      makeStandardSTXPostCondition(stxAddress!, FungibleConditionCode.LessEqual, '100'),
    ];

    await openContractCall({
      contractAddress: 'ST1X6M947Z7E58CNE0H8YJVJTVKS9VW0PHEG3NHN3',
      contractName: 'faker',
      functionName: 'rawr',
      functionArgs,
      postConditions,
      attachment: 'This is an attachment',
      onFinish: async (data) => {
        console.log('finished contract call!', data);
        setResponse(data);
      },
      onCancel: () => {
        console.log('popup closed!');
      },
    });
  };

  return (
    <div>
      <h4>Faker contract call</h4>
      {response && <pre><code>{JSON.stringify(response, null, 2)}</code></pre>}
      <button onClick={() => handleOpenContractCall()}>
        {isRequestPending ? 'request pending...' : 'Call Contract'}
      </button>
    </div>
  );
};