How to work with payable function in smart contract using Thirdweb?

174 views Asked by At

As per Thirdweb's latest documentation for React, I have to use the useContractWrite function to call functions that basically make changes to the storage variables/data.

My question is, let say there is already a fixed amount (say 0.1ether) that you have to pay to let say buy some nft or donate etc. How do I make thirdweb call the function and set the paying amount automatically? Where do I specify that value?

This is a sample code that I got in the code snippets but no mention of how to deal with the payable amount.

import { useContract, useContractWrite } from "@thirdweb-dev/react";

export default function Component() {
  const { contract } = useContract("0x6e2c9f94e38B2c18FC9f957D20381d3C63661e2a");
  const { mutateAsync: donateToNFT, isLoading } = useContractWrite(contract, "donateToNFT")

  const call = async () => {
    try {
      const data = await donateToNFT({ args: [_id] });
      console.info("contract call successs", data);
    } catch (err) {
      console.error("contract call failure", err);
    }
  }
}
1

There are 1 answers

0
Akeel Ahmed Qureshi On BEST ANSWER

One thing which i found in thirdweb documentation for useContrctWrite hook is that we can modify the default transaction options by providing overrides object while interacting with the smart contract function.

You can set the desired amount of native token(eg. ETH) you want to send to the payable function on mutateAsync function. This way you should be able to interact with payable function on smart contract.

import { useContractWrite, useContract, Web3Button } from "@thirdweb-dev/react";
import { utils } from "ethers";

// Your smart contract address
const contractAddress = "{{contract_address}}";

function App() {
  const { contract } = useContract(contractAddress);
  const { mutateAsync, isLoading, error } = useContractWrite(
    contract,
    "setName",
  );

  return (
    <Web3Button
      contractAddress={contractAddress}
      action={() =>
        mutateAsync({
          args: ["My Name"],
          overrides: {
            gasLimit: 1000000, // override default gas limit
            value: utils.parseEther("0.1"), // send 0.1 native token with the contract call
          },
        })
      }
    >
      Send Transaction
    </Web3Button>
  );
}

export default App;

You can refer to the official docs for more details. https://portal.thirdweb.com/react/react.usecontractwrite#call-overrides-optional