In this guide, we'll walk through creating token-gated custom actions for your Farcaster agent. Token-gating allows you to create exclusive features that are only accessible to users who hold specific tokens.
Before adding custom actions, you'll need to set up your Farcaster agent. Once you have the basic setup complete, head over to the Neynar developer dashboard to create your agent account.
First, install the required dependencies for interacting with the blockchain:
npm install [email protected]
In your project's actions folder, create a new file for your custom action. Here's a template for creating a token-gated action:
import { Action } from './base.js';
import { ethers } from 'ethers';
export class TokenGatedAction extends Action {
constructor() {
super('actionName', 'Description of your action');
this.TOKEN_ADDRESS = 'your_token_contract_address';
this.PROVIDER_URL = 'your_rpc_endpoint'; // e.g. https://mainnet.base.org
}
shouldExecute(text) {
// Define when your action should trigger
const lowerText = text.toLowerCase();
return lowerText.includes('/yourcommand');
}
async execute(message) {
// Get user's verified address
const userAddress = message?.author?.verifications?.[0];
if (!userAddress) {
return {
success: false,
text: "Please verify your Farcaster account first.",
shouldSendMessage: true
};
}
// Check token balance
const provider = new ethers.JsonRpcProvider(this.PROVIDER_URL);
const tokenContract = new ethers.Contract(
this.TOKEN_ADDRESS,
['function balanceOf(address) view returns (uint256)'],
provider
);
const balance = await tokenContract.balanceOf(userAddress);
if (balance <= 0n) {
return {
success: false,
text: "You need to hold our token to use this feature.",
shouldSendMessage: true
};
}
// Add your custom functionality here
// This is where you implement your specific features
// For example, the F150 action provides maintenance guidance
return {
success: true,
text: "Your response here",
shouldSendMessage: true
};
}
}
Add your new action to the actions/index.js
file:
import { TokenGatedAction } from './your-action.js';
export const actions = [
// ... other actions
new TokenGatedAction(),
];
You can customize your action to provide any functionality you want. For example:
For a real-world example, check out arjux' new F150 maintenance function that provides vehicle diagnostic guidance to token holders.
Token-gated actions allow you to create exclusive features for your Farcaster agent that are only accessible to token holders. This opens up possibilities for creating premium features, exclusive communities, and specialized tools.
For more examples and documentation, check out the Actions Documentation.