Skip to main content

useGrantRole

Hook for granting roles on contracts that implement the ERC-1724 standard.

import { useGrantRole } from "@thirdweb-dev/react";

Usage

Provide your contract as the argument.

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

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

function App() {
const { contract } = useContract(contractAddress);
const { mutateAsync: grantRole, isLoading, error } = useGrantRole(contract);

if (error) {
console.error("failed to grant role", error);
}

return (
<Web3Button
contractAddress={contractAddress}
action={() =>
grantRole({
role: "admin",
address: "{{wallet_address}}",
})
}
>
Grant Role
</Web3Button>
);
}

Configuration

role

The role parameter is required and should be one of the following, depending on the smart contract.

  • A string, matching an existing role, if your contract implements the ERC-1724 standard
  • An enum value, if your contract implements the ERC-1724 standard
  • A string, matching an existing role, if your contract implements a custom role system
import { useGrantRole, useContract, Web3Button } from "@thirdweb-dev/react";

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

function App() {
const { contract } = useContract(contractAddress);
const { mutateAsync: grantRole, isLoading, error } = useGrantRole(contract);

if (error) {
console.error("failed to grant role", error);
}

return (
<Web3Button
contractAddress={contractAddress}
action={() =>
grantRole({
role: "admin", // Accepts a string, enum, or custom role
address: "{{wallet_address}}",
})
}
>
Grant Role
</Web3Button>
);
}

address

Likely, you will want to grant the role to the currently connected wallet address.

You can use the useAddress hook to get this value.

import {
useGrantRole,
useContract,
Web3Button,
useAddress,
} from "@thirdweb-dev/react";

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

function App() {
const address = useAddress();
const { contract } = useContract(contractAddress);
const { mutateAsync: grantRole, isLoading, error } = useGrantRole(contract);

if (error) {
console.error("failed to grant role", error);
}

return (
<Web3Button
contractAddress={contractAddress}
action={() =>
grantRole({
role: "admin",
address: address, // Use useAddress hook to get current wallet address
})
}
>
Grant Role
</Web3Button>
);
}