LogoLogo
  • Overview
  • Prompts
    • Quickstart
    • DeFi Swaps
    • MEME Launcher
    • Image Gen Mint
    • Drop Links
    • NFT Collection
    • Buys, Lists, Transfers
    • Create Contract
  • Agents
    • Introduction
    • Quick Start
    • Manifest
    • Embeddable Chat Component
    • Widget Component
    • Deploy Your Open Agent
    • MCP
    • make-agent
    • Contract To Agent
    • Sui Agent Building
  • Wallet
    • Quickstart
    • NFT Drops
    • Paymaster
    • Integrations
    • Sign Messages
    • Cross Chain Signatures
    • Telegram Integration
Powered by GitBook
LogoLogo

Socials

  • X (Twitter)
On this page
Export as PDF
  1. Agents

Contract To Agent

Previousmake-agentNextSui Agent Building

Last updated 7 months ago

How to Use Contract to Agent

The contract-to-agent tool enables you to scaffold an agent based on a NEAR contract that has an ABI. This process makes integration with the NEAR protocol seamless by providing a structured template for agent development. Here's a step-by-step guide to get started:

  1. Scaffold the Agent: Run the following command to start creating your agent. You will be prompted for necessary inputs:

    npx make-agent contract

    • Contract ID: Provide the contract ID. Ensure the contract has a well-defined ABI.

    • Description: Offer a detailed description of the contract's functionalities, which will guide the behavior of the agent.

    • Optional Directory: Specify a directory where you want to generate the agent files, or leave it blank to use the default.

    If you just want to run your agent and don't want to know how it works then skip to 2. The rest of the flow will continue as described below, but before following that we can take a look at what was generated, if you open your index.ts you should see a simple express server

    app.get('/api/ping', (req: Request, res: Response) => {
      return res.json({ message: "Pong" });
    });
    
    app.listen(PORT, () => {
      console.log(`Server is running on http://localhost:${PORT}`);
    });

    This should contain endpoints for each of your smart contract methods regardless of if they are read of write calls, notice the writes return a valid transaction object that will be executed by the runtime using the "generate-transaction" tool

    
    
    app.post('/api/set_greeting', (req: Request, res: Response) => {
      const { greeting } = req.body as SetGreeting;
    
      if (typeof greeting !== 'string' || greeting.trim() === '') {
        return res.status(400).json({ error: 'Invalid greeting provided.' });
      }
    
      const functionCall: FunctionCallAction = {
        type: "FunctionCall",
        params: {
          methodName: "set_greeting",
          args: { greeting },
          gas: "30000000000000",
          deposit: "1"
        }
      };
    
      return res.json(functionCall);
    });
    
    app.get('/api/get_greeting', async (req: Request, res: Response) => {
      const methodName = "get_greeting";
    
      const requestBody = {
        jsonrpc: "2.0",
        id: "dontcare",
        method: "query",
        params: {
          request_type: "call_function",
          finality: "final",
          account_id: CONTRACT_ID,
          method_name: methodName,
          args_base64: Buffer.from(JSON.stringify({})).toString('base64')
        }
      };
    
      try {
        const response = await fetch('https://rpc.mainnet.near.org', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestBody)
        });
    
        const data = await response.json();
        let deserializedResult;
    
        if (Array.isArray(data.result.result)) {
          deserializedResult = String.fromCharCode(...data.result.result);
        } else {
          deserializedResult = data.result.result;
        }
    
        return res.json({ greeting: deserializedResult });
      } catch (error) {
        return res.status(500).json({ error: 'Failed to fetch data from NEAR RPC.' });
      }
    });

    The most important part is this endpoint:

    app.get('/.well-known/ai-plugin.json', (req: Request, res: Response) => {

    Here your Open API Spec will be handled. This is how your agent knows how to interact with your API. If your agent isn't able to use your api correctly even though its functional this is probably the issue. Make sure your instruction field is explicit, some prompt engineering will be necessary

     "assistant": {
            "name": "Surgedev Assistant",
            "description": "An assistant designed to interact with the surgedev.near contract on the Near Protocol.",
            "instructions": "You are an assistant designed to interact with the surgedev.near contract on the Near Protocol. Your main functions are:\n\n1. [Set Greeting]: Use the /api/set_greeting endpoint to set a greeting. This endpoint will return a valid function call which you should be able to send. Ensure all required parameters are provided by the user as described in the paths section below.\n\n2. [Get Greeting]: Use the /api/get_greeting endpoint to retrieve the current greeting from the contract.\n\nWhen performing write operations:\n- Ensure all required parameters are non-empty and of the correct type.\n- Avoid using any special characters or formatting that might cause issues with the contract.\n- If the user provides invalid input, kindly ask them to provide valid data according to the parameter specifications.\n\nWhen performing view operations:\n- Simply use the appropriate /api/[function_name] endpoint and return the result to the user.\n\nImportant: For all write operations, the endpoints will return a function call object. You should clearly indicate to the user that this is a function call that needs to be sent to the blockchain, and not the final result of the operation.",
            "tools": [{
              "type": "generate-transaction"
            }]
          }

    You can learn more about it here Manifest If your contract is too complex for the scaffolding to work completely this will still work as very easy good starting point for your agent.

  2. Generate an API Key: If everything went well you will see this window open. If you don't already have a wallet you will first be prompted to create one first. Once you have signed the message you will have an API Key automatically generated for you and put into your environment variables.

  1. Develop and Test Agent: After creating an API Key you will be booted into the agent playground where you can start testing your agent. Based on the instructions and the contract methods we can see the agent was able to understand what the available methods are and should be able to make view and write contract calls out of the box

  2. If you ever close the execution you can run everything again by running your server and make-agent again

    npx tsx ./index.ts & npx make-agent dev -p 8080