Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article explains how to document Solidity smart contracts using OpenAPI and Swagger.

When developing Solidity smart contracts, the ABI (Application Binary Interface) alone may not adequately communicate the purpose of functions, error conditions, or the meaning of events. More detailed, structured documentation is particularly useful for team development, communicating with clients, and collaborating with frontend developers.

This article proposes documenting Solidity smart contracts in OpenAPI 3.0 (YAML) and Swagger 2.0 (JSON) formats. It also introduces a Claude Code subagent that automates specification generation.

The workflow can produce a documentation site such as the following.

Benefits of using OpenAPI and Swagger

Documenting contracts in these formats has several benefits.

  • Standardized format OpenAPI and Swagger are familiar industry-standard formats for sharing API documentation among developers.
  • Interactive documentation Swagger UI and Redocusaurus support visual, interactive documentation sites.
  • Explicit type information Represent Solidity types such as address, uint256, and bytes32 with patterns and explicit validation rules.
  • Visible error handling Describe custom errors and revert conditions in a structured format.
  • Documentation of events and structs Document the various elements of a contract comprehensively.

Design principles

Purpose and constraints

This specification describes Solidity contract interfaces in OpenAPI and Swagger formats; it is not an HTTP API design. The primary objective is to represent Solidity behavior accurately and compactly rather than follow HTTP API best practices.

Actual HTTP invocation is not assumed. Paths and HTTP methods are assigned as a documentation convention to accommodate the OpenAPI and Swagger formats.

Basic rules

Item Rule
Success response Always use HTTP 200
Error response Always use HTTP 500, rather than other 4xx or 5xx codes
Descriptions Write descriptions in Japanese in the original generator. The displayed examples in this English edition are localized.
Identifier notation Enclose variable names, function names, error names, and similar identifiers in backticks (`)
Extension fields Do not introduce custom x- fields for contract semantics. The example uses x-tagGroups as a presentation extension for Redoc.

Identifier notation

Enclose the following elements in backticks when referring to them in a description.

Element Examples
Function names transfer, balanceOf
Variables and parameters _to, amount, owner
Error names InsufficientBalance, InvalidAddress
Event names Transfer, Approval
Types address, uint256
Modifiers onlyOwner, whenNotPaused
Constants DECIMALS, MAX_SUPPLY
yaml
# Correct example
description: |
  Transfers `amount` tokens to the address specified by `_to`.
  If the balance is insufficient, an `InsufficientBalance` error occurs.

# Incorrect example
description: |
  Transfers amount tokens to the address specified by _to.
  If the balance is insufficient, an InsufficientBalance error occurs.

Path design

Use function and event names directly in paths to maintain a clear structure.

Element Path format HTTP method
view/pure functions /{functionName} GET
nonpayable/payable functions /{functionName} POST
Variables, constants, and mappings /{variableName} GET
Events /events/{EventName} GET
Errors /errors/{ErrorName} GET
Structs /structs/{StructName} GET
Modifier /modifiers/{ModifierName} GET

Writing summaries

Use the function name directly in the summary field. Avoid redundant wording such as getter or descriptions beginning with get.

yaml
# Correct example
summary: "balanceOf"
summary: "transfer"
summary: "totalSupply"

# Incorrect examples (do not use)
summary: "balanceOf getter"
summary: "Retrieve the balance"
summary: "Get balance"

Parameter placement

Define parameters in query or path; do not use requestBody.

yaml
# Correct example
parameters:
  - name: owner
    in: query
    required: true

# Incorrect example (do not use requestBody)
requestBody:
  content:
    application/json:
      schema:
        properties:
          owner:
            type: string

Representing inheritance

Describe contract inheritance in info.description. List the names of inherited contracts.

yaml
info:
  title: "MyToken Solidity Interface"
  version: "1.0.0"
  description: |
    This specification represents the MyToken Solidity interface in OpenAPI format.

    This contract inherits the following contracts.

    ERC20.

    Ownable.

    Pausable.

Including inherited functions, events, and errors provides a complete view of the contract.

Structure of an OpenAPI and Swagger contract specification

The following describes the basic structure for representing smart contracts in these formats.

Overall structure

yaml
openapi: 3.0.3
info:
  title: "Contract Name Solidity Interface"
  version: "1.0.0"
  description: |
    Contract description.
    Include inheritance and network information here.

tags:
  - name: Read Functions
    description: Functions that retrieve information from the contract without modifying state.
  - name: Write Functions
    description: Functions that modify state.
  - name: Variables
  - name: Constants
  - name: Mapping
  - name: Events
  - name: Errors
  - name: Structs
  - name: Modifier

x-tagGroups:
  - name: Functions
    tags:
      - Read Functions
      - Write Functions
  - name: Storage
    tags:
      - Variables
      - Constants
      - Mapping
  - name: Others
    tags:
      - Events
      - Errors
      - Structs
      - Modifier

paths:
  # Paths for functions, events, errors, and structs

components:
  schemas:
    # ErrorResponse, event schemas, and struct schemas

Categorizing elements with tags

The specification classifies contract elements using the following nine tags.

Tag Description
Read Functions view and pure functions that retrieve information without modifying state
Write Functions nonpayable and payable functions that may modify state
Variables public state variables
Constants constant and immutable values
Mapping public mappings
Events Events declared by the contract
Errors Custom errors
Structs Struct definitions
Modifier Modifier definitions

Tag names are standardized in English. Only Read Functions and Write Functions have a description; the remaining tags have names only.

Representing contract elements

Functions

Read functions (view/pure)

Represent read functions with GET and define their arguments in parameters using query or path parameters.

yaml
/balanceOf:
  get:
    summary: "balanceOf"
    description: |
      Retrieves the token balance of the specified account.

      An ERC20 standard function.
    operationId: balanceOf
    tags:
      - Mapping
    parameters:
      - name: owner
        in: query
        required: true
        schema:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
        description: "Specifies the owner address."
        example: "0x1234567890123456789012345678901234567890"
    responses:
      "200":
        description: "Successful response."
        content:
          application/json:
            schema:
              type: object
              properties:
                result:
                  type: string
                  description: "Returns the account balance."
                  example: "1000000000000000000"

The fields have the following meanings.

Field Description
summary Function name displayed in the Swagger UI sidebar
description Detailed function description; the multiline scalar (|) supports multiple lines
operationId Unique identifier, usually the function name; overloaded functions need distinct identifiers
tags Function category used for grouping in Swagger UI
parameters Function arguments, represented as query parameters using in: query
responses Return values and errors: 200 for success and 500 for errors

For address, the pattern ^0x[0-9a-fA-F]{40}$ validates a 0x-prefixed string containing 40 hexadecimal digits. Represent uint256 as type: string because its values may exceed JavaScript's safe integer range. If a read function has no explicitly defined error conditions, the documentation defines only a 200 response.

Write functions (nonpayable/payable)

Represent write functions with POST.

yaml
/transfer:
  post:
    summary: "transfer"
    description: |
      Transfers tokens to the specified address.

      An ERC20 standard function.
    operationId: transfer
    tags:
      - Write Functions
    parameters:
      - name: to
        in: query
        required: true
        schema:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
        description: "Specifies the recipient address."
        example: "0x1234567890123456789012345678901234567890"
      - name: amount
        in: query
        required: true
        schema:
          type: string
        description: "Specifies the token amount in base units."
        example: "1000000000000000000"
    responses:
      "200":
        description: "Successful response."
        content:
          application/json:
            schema:
              type: object
              properties:
                result0:
                  type: string
                  description: "Returns true if the transfer succeeds."
                  example: "true"
      "500":
        description: "Possible errors for this function.\n\n- InsufficientBalance\n\n- InvalidAddress"
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ErrorResponse'
            examples:
              InsufficientBalance:
                summary: "Insufficient balance"
                value:
                  message: "InsufficientBalance"
                  data: {}
              InvalidAddress:
                summary: "Invalid address"
                value:
                  message: "InvalidAddress"
                  data: {}

The following fields are particularly relevant to write functions.

Field Description
responses["500"] Error response; list possible errors in description
examples Concrete examples of individual errors, keyed by error name, with a summary and value
$ref Reference to a shared schema; use #/components/schemas/ErrorResponse for a consistent format

Represent all errors with HTTP 500, using only 200 and 500 as response status codes. This convention provides a uniform representation of Solidity reverts and custom errors, not actual HTTP status semantics.

Error response details

ErrorResponse schema

All errors use the common ErrorResponse schema.

yaml
components:
  schemas:
    ErrorResponse:
      type: object
      description: "Shared schema representing errors during contract calls."
      properties:
        message:
          type: string
          description: "Custom error name or revert/require message."
        data:
          type: object
          description: "Additional information (optional)."

Writing a 500 response description

In the 500 response's description, list possible errors as separate bullet items. The original Japanese generator uses a middle-dot bullet; the English examples below use a hyphen.

yaml
"500":
  description: "Possible errors for this function.\n\n- InsufficientBalance\n\n- InvalidAddress\n\n- AmountZero"

Separate list items with a blank line (\n\n). This improves readability in Swagger UI.

Writing examples

Define a concrete example for each error in the examples field. Use the error name as the key and a concise Japanese description as summary in the original generator; the examples here are localized to English.

yaml
examples:
  InsufficientBalance:
    summary: "Insufficient balance"
    value:
      message: "InsufficientBalance"
      data: {}
  InvalidAddress:
    summary: "Invalid address"
    value:
      message: "InvalidAddress"
      data:
        address: "0x0000000000000000000000000000000000000000"

If the error has arguments, include their values in data.

Events

Represent events using the /events/{EventName} path.

yaml
/events/Transfer:
  get:
    summary: "Transfer"
    description: |
      Emitted when tokens are transferred.

      **Parameters:**
      - `from` (address) - indexed
      - `to` (address) - indexed
      - `value` (uint256)
    operationId: event_Transfer
    tags:
      - Events
    responses:
      "200":
        description: "Token transfer event"
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TransferEvent'

Define event schemas under components/schemas.

yaml
components:
  schemas:
    TransferEvent:
      type: object
      description: "Transfer event"
      properties:
        from:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Indexed. Source address."
          example: "0x1234567890123456789012345678901234567890"
        to:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Indexed. Recipient address."
          example: "0x1234567890123456789012345678901234567890"
        value:
          type: string
          description: "Transferred amount in base units."
          example: "1000000000000000000"

Event schema fields have the following meanings.

Field Description
type Schema type; use object for events
description Event description explaining when it is emitted
properties Event parameters; identify indexed parameters in their descriptions

Mark Solidity indexed parameters as indexed in their descriptions to indicate that they can be searched through log topics.

Errors

Represent custom errors using /errors/{ErrorName} paths.

yaml
/errors/InsufficientBalance:
  get:
    summary: "InsufficientBalance"
    description: |
      Returned when the available balance is insufficient.
      Ensure that the required balance is available.
    operationId: error_InsufficientBalance
    tags:
      - Errors
    responses:
      "200":
        description: "Insufficient balance error"
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                  example: "InsufficientBalance"

Variables and constants

Represent public variables and constants through their automatically generated getters. Include the variable declaration itself in a code block within the description, followed by an explanation.

yaml
/totalSupply:
  get:
    summary: "totalSupply"
    description: |
      ```solidity
      uint256 public totalSupply;
      ```

      Retrieves the total token supply.

      An ERC20 standard function.
    operationId: totalSupply
    tags:
      - Variables
    responses:
      "200":
        description: "Successful response."
        content:
          application/json:
            schema:
              type: object
              properties:
                result:
                  type: string
                  description: "Returns the total supply."
                  example: "1000000000000000000"

Including the declaration makes the type and visibility clear at a glance. Include declarations for constants (constant) and immutable variables (immutable) in the same way.

yaml
description: |
  ```solidity
  uint8 public constant DECIMALS = 18;
  ```

  Number of decimal places used to display the token.

Mappings

As with other variables, include the mapping type declaration in a code block in the description.

yaml
/allowance:
  get:
    summary: "allowance"
    description: |
      ```solidity
      mapping(address owner => mapping(address spender => uint256)) public allowance;
      ```

      Retrieves the token amount that `owner` has authorized `spender` to spend.

      An ERC20 standard function.
    operationId: allowance
    tags:
      - Mapping
    parameters:
      - name: owner
        in: query
        required: true
        schema:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
        description: "Specifies the owner address."
        example: "0x1234567890123456789012345678901234567890"
      - name: spender
        in: query
        required: true
        schema:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
        description: "Specifies the address authorized to spend tokens."
        example: "0x1234567890123456789012345678901234567890"
    responses:
      "200":
        description: "Successful response."
        content:
          application/json:
            schema:
              type: object
              properties:
                result:
                  type: string
                  description: "Returns the allowance."
                  example: "1000000000000000000"

Structs

yaml
/structs/ERC20Storage:
  get:
    summary: "ERC20Storage"
    description: |
      ERC20 storage struct.

      **Fields:**
      - _name (string)
      - _symbol (string)
    operationId: struct_ERC20Storage
    tags:
      - Structs
    responses:
      "200":
        description: "ERC20Storage struct"
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ERC20StorageStruct'

Define struct schemas under components/schemas.

yaml
components:
  schemas:
    ERC20StorageStruct:
      type: object
      description: "ERC20Storage struct"
      properties:
        _name:
          type: string
          description: "Token name"
          example: "Example Token"
        _symbol:
          type: string
          description: "Token symbol"
          example: "EXT"

Struct schema fields have the following meanings.

Field Description
type Schema type; use object for structs
description Purpose and role of the struct
properties Struct fields, using the Solidity variable names as keys

Modifiers

Define modifiers under /modifiers/{ModifierName}.

yaml
/modifiers/onlyOwner:
  get:
    summary: "onlyOwner"
    description: |
      ```solidity
      modifier onlyOwner() {
          require(msg.sender == owner, "Not owner");
          _;
      }
      ```

      This modifier verifies that the function caller is the contract owner.
      The call reverts if the caller is not the owner.
    operationId: modifier_onlyOwner
    tags:
      - Modifier
    responses:
      "200":
        description: "onlyOwner modifier"

Describing functions with modifiers

When a function has a modifier, describe its effect in the function's description.

yaml
/mint:
  post:
    summary: "mint"
    description: |
      Mints new tokens.

      :::note info
      **Modifier**: This function is protected by `onlyOwner`.
      Only the contract owner can execute it.
      :::
    operationId: mint
    tags:
      - Write Functions

When multiple modifiers apply, document the effects of all of them.

Solidity type mapping

Solidity type OpenAPI representation
address type: string, pattern: "^0x[0-9a-fA-F]{40}$"
uint256 / int256 type: string to accommodate large integers
bytes32 type: string, pattern: "^0x[0-9a-fA-F]{64}$"
bytes4 type: string, pattern: "^0x[0-9a-fA-F]{8}$"
bool type: boolean
string type: string
bytes type: string
Arrays type: array, items: {...}

Example specification (ERC20)

The following is a complete example of an OpenAPI specification for an ERC20 token contract, with human-readable text localized to English.

https://github.com/cardene777/smartcontract-specification/blob/main/docs/contract/ERC20/ERC20.openapi.yaml

yaml
# file: docs/contract/ERC20/ERC20.openapi.yaml
# Generated by: contract-spec-generator skill

openapi: 3.0.3
info:
  title: "ERC20 Solidity Interface"
  version: "1.0.0"
  description: |
    This specification represents the ERC20 Solidity interface in OpenAPI format.

    This contract inherits the following contracts.

    Context, IERC20, IERC20Metadata, IERC20Errors

    An implementation of the ERC20 token standard, providing fundamental fungible-token functionality such as transfers, approvals, and balance tracking.

tags:
  - name: Read Functions
    description: Functions that retrieve information without modifying contract state.
  - name: Write Functions
    description: Functions that modify contract state.
  - name: Events
  - name: Errors

x-tagGroups:
  - name: Functions
    tags:
      - Read Functions
      - Write Functions
  - name: Events and Errors
    tags:
      - Events
      - Errors

paths:
  /name:
    get:
      tags:
        - Read Functions
      summary: "name"
      description: |
        Returns the token name.

        A standard ERC20 metadata function.
      operationId: name
      responses:
        "200":
          description: "Successful response."
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: string
                    description: "Token name (Solidity: string)."
                    example: "MyToken"

  /symbol:
    get:
      tags:
        - Read Functions
      summary: "symbol"
      description: |
        Returns the token symbol, usually an abbreviated version of its name.

        A standard ERC20 metadata function.
      operationId: symbol
      responses:
        "200":
          description: "Successful response."
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: string
                    description: "Token symbol (Solidity: string)."
                    example: "MTK"

  /decimals:
    get:
      tags:
        - Read Functions
      summary: "decimals"
      description: |
        Returns the number of decimals used for user-facing display.

        For example, if `decimals` is `2`, a balance of `505` base units should be displayed as `5.05` (`505 / 10 ** 2`).

        Tokens commonly use 18 decimals, reflecting the relationship between Ether and wei. This implementation returns 18 by default.

        This information is used only for display and does not affect contract arithmetic.
      operationId: decimals
      responses:
        "200":
          description: "Successful response."
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: integer
                    minimum: 0
                    maximum: 255
                    description: "Number of decimals (Solidity: uint8)."
                    example: 18

  /totalSupply:
    get:
      tags:
        - Read Functions
      summary: "totalSupply"
      description: |
        Returns the total amount of tokens in existence.

        An ERC20 standard function.
      operationId: totalSupply
      responses:
        "200":
          description: "Successful response."
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: string
                    description: "Total token supply (Solidity: uint256)."
                    example: "1000000000000000000000000"

  /balanceOf:
    get:
      tags:
        - Read Functions
      summary: "balanceOf"
      description: |
        Returns the token balance of the specified account.

        An ERC20 standard function.
      operationId: balanceOf
      parameters:
        - name: account
          in: query
          required: true
          schema:
            type: string
            pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Address whose balance is queried (Solidity: address)."
          example: "0x1234567890123456789012345678901234567890"
      responses:
        "200":
          description: "Successful response."
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: string
                    description: "Token balance (Solidity: uint256)."
                    example: "1000000000000000000"

  /allowance:
    get:
      tags:
        - Read Functions
      summary: "allowance"
      description: |
        Returns the remaining token amount that `spender` may spend on behalf of `owner` through `transferFrom`.

        An ERC20 standard function.
      operationId: allowance
      parameters:
        - name: owner
          in: query
          required: true
          schema:
            type: string
            pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Token owner address (Solidity: address)."
          example: "0x1234567890123456789012345678901234567890"
        - name: spender
          in: query
          required: true
          schema:
            type: string
            pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Address authorized to spend tokens (Solidity: address)."
          example: "0x0987654321098765432109876543210987654321"
      responses:
        "200":
          description: "Successful response."
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: string
                    description: "Remaining allowance (Solidity: uint256)."
                    example: "500000000000000000000"

  /transfer:
    post:
      tags:
        - Write Functions
      summary: "transfer"
      description: |
        Transfers `value` tokens from the caller's account to `to`.

        Returns a Boolean indicating whether the operation succeeded.

        Emits a `Transfer` event on successful transfer.

        **Requirements:**
        - `to` must not be the zero address.
        - The caller must hold a balance of at least `value`.
      operationId: transfer
      parameters:
        - name: to
          in: query
          required: true
          schema:
            type: string
            pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Recipient address (Solidity: address)."
          example: "0x0987654321098765432109876543210987654321"
        - name: value
          in: query
          required: true
          schema:
            type: string
          description: "Amount of tokens to transfer (Solidity: uint256)."
          example: "1000000000000000000"
      responses:
        "200":
          description: "Successful response."
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: boolean
                    description: "Returns true if the transfer succeeds (Solidity: bool)."
                    example: true
        "500":
          description: |
            Possible errors for this function.

            - ERC20InvalidSender

            - ERC20InvalidReceiver

            - ERC20InsufficientBalance
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                ERC20InvalidSender:
                  summary: "ERC20InvalidSender"
                  description: "Returned when the sender is `address(0)`, indicating an invalid sender."
                  value:
                    message: "ERC20InvalidSender"
                    data:
                      sender: "0x0000000000000000000000000000000000000000"
                ERC20InvalidReceiver:
                  summary: "ERC20InvalidReceiver"
                  description: "Returned when `to` is `address(0)`, indicating an invalid recipient."
                  value:
                    message: "ERC20InvalidReceiver"
                    data:
                      receiver: "0x0000000000000000000000000000000000000000"
                ERC20InsufficientBalance:
                  summary: "ERC20InsufficientBalance"
                  description: "Returned when the caller has a balance below `value`, indicating insufficient funds for the transfer."
                  value:
                    message: "ERC20InsufficientBalance"
                    data:
                      sender: "0x1234567890123456789012345678901234567890"
                      balance: "100"
                      needed: "1000"

  /approve:
    post:
      tags:
        - Write Functions
      summary: "approve"
      description: |
        Sets the allowance of `spender` over the caller's tokens to `value`.

        Returns a Boolean indicating whether the operation succeeded.

        If `value` equals the maximum `uint256` value, this implementation does not update the allowance during `transferFrom`, treating it as unlimited approval.

        Emits an `Approval` event on successful approval.

        **Requirements:**
        - `spender` must not be the zero address.
      operationId: approve
      parameters:
        - name: spender
          in: query
          required: true
          schema:
            type: string
            pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Address to authorize to spend tokens (Solidity: address)."
          example: "0x0987654321098765432109876543210987654321"
        - name: value
          in: query
          required: true
          schema:
            type: string
          description: "Token amount to approve (Solidity: uint256)."
          example: "1000000000000000000"
      responses:
        "200":
          description: "Successful response."
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: boolean
                    description: "Returns true if approval succeeds (Solidity: bool)."
                    example: true
        "500":
          description: |
            Possible errors for this function.

            - ERC20InvalidApprover

            - ERC20InvalidSpender
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                ERC20InvalidApprover:
                  summary: "ERC20InvalidApprover"
                  description: "Returned when the approver (owner) is `address(0)`, indicating an invalid approver."
                  value:
                    message: "ERC20InvalidApprover"
                    data:
                      approver: "0x0000000000000000000000000000000000000000"
                ERC20InvalidSpender:
                  summary: "ERC20InvalidSpender"
                  description: "Returned when `spender` is `address(0)`, indicating an invalid spender."
                  value:
                    message: "ERC20InvalidSpender"
                    data:
                      spender: "0x0000000000000000000000000000000000000000"

  /transferFrom:
    post:
      tags:
        - Write Functions
      summary: "transferFrom"
      description: |
        Transfers `value` tokens from `from` to `to` using the allowance mechanism, deducting the amount from the caller's allowance where applicable.

        Returns a Boolean indicating whether the operation succeeded.

        If the current allowance is the maximum `uint256` value, this implementation does not update it.

        Emits a `Transfer` event on successful transfer.

        **Requirements:**
        - `from` and `to` must not be the zero address.
        - `from` must hold a balance of at least `value`.
        - The caller must have an allowance of at least `value` over the tokens held by `from`.
      operationId: transferFrom
      parameters:
        - name: from
          in: query
          required: true
          schema:
            type: string
            pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Source address for the token transfer (Solidity: address)."
          example: "0x1234567890123456789012345678901234567890"
        - name: to
          in: query
          required: true
          schema:
            type: string
            pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Recipient address (Solidity: address)."
          example: "0x0987654321098765432109876543210987654321"
        - name: value
          in: query
          required: true
          schema:
            type: string
          description: "Amount of tokens to transfer (Solidity: uint256)."
          example: "1000000000000000000"
      responses:
        "200":
          description: "Successful response."
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: boolean
                    description: "Returns true if the transfer succeeds (Solidity: bool)."
                    example: true
        "500":
          description: |
            Possible errors for this function.

            - ERC20InvalidSender

            - ERC20InvalidReceiver

            - ERC20InsufficientBalance

            - ERC20InsufficientAllowance

            - ERC20InvalidApprover

            - ERC20InvalidSpender
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                ERC20InvalidSender:
                  summary: "ERC20InvalidSender"
                  description: "Returned when `from` is `address(0)`, indicating an invalid sender."
                  value:
                    message: "ERC20InvalidSender"
                    data:
                      sender: "0x0000000000000000000000000000000000000000"
                ERC20InvalidReceiver:
                  summary: "ERC20InvalidReceiver"
                  description: "Returned when `to` is `address(0)`, indicating an invalid recipient."
                  value:
                    message: "ERC20InvalidReceiver"
                    data:
                      receiver: "0x0000000000000000000000000000000000000000"
                ERC20InsufficientBalance:
                  summary: "ERC20InsufficientBalance"
                  description: "Returned when the balance of `from` is below `value`, indicating insufficient funds for the transfer."
                  value:
                    message: "ERC20InsufficientBalance"
                    data:
                      sender: "0x1234567890123456789012345678901234567890"
                      balance: "100"
                      needed: "1000"
                ERC20InsufficientAllowance:
                  summary: "ERC20InsufficientAllowance"
                  description: "Returned when the caller’s allowance is below `value`, indicating insufficient allowance."
                  value:
                    message: "ERC20InsufficientAllowance"
                    data:
                      spender: "0xabcdef1234567890abcdef1234567890abcdef12"
                      allowance: "100"
                      needed: "1000"
                ERC20InvalidApprover:
                  summary: "ERC20InvalidApprover"
                  description: "Returned when the approver (owner) is `address(0)` during an internal approval update."
                  value:
                    message: "ERC20InvalidApprover"
                    data:
                      approver: "0x0000000000000000000000000000000000000000"
                ERC20InvalidSpender:
                  summary: "ERC20InvalidSpender"
                  description: "Returned when `spender` is `address(0)` during an internal approval update."
                  value:
                    message: "ERC20InvalidSpender"
                    data:
                      spender: "0x0000000000000000000000000000000000000000"

  /events/Transfer:
    get:
      tags:
        - Events
      summary: "Transfer"
      description: |
        Emitted when `value` tokens move from one account (`from`) to another (`to`).

        The value may be zero.

        A standard ERC20 event.
      operationId: event_Transfer
      responses:
        "200":
          description: "Event schema"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TransferEvent"

  /events/Approval:
    get:
      tags:
        - Events
      summary: "Approval"
      description: |
        Emitted when `approve` sets the allowance granted by `owner` to `spender`. The `value` field is the new allowance.

        A standard ERC20 event.
      operationId: event_Approval
      responses:
        "200":
          description: "Event schema"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ApprovalEvent"

  /errors/ERC20InsufficientBalance:
    get:
      tags:
        - Errors
      summary: "ERC20InsufficientBalance"
      description: |
        Indicates an error concerning the sender's available balance during a transfer.
      operationId: error_ERC20InsufficientBalance
      responses:
        "200":
          description: "Error schema"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ERC20InsufficientBalanceError"

  /errors/ERC20InvalidSender:
    get:
      tags:
        - Errors
      summary: "ERC20InvalidSender"
      description: |
        Indicates an invalid token sender during a transfer.
      operationId: error_ERC20InvalidSender
      responses:
        "200":
          description: "Error schema"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ERC20InvalidSenderError"

  /errors/ERC20InvalidReceiver:
    get:
      tags:
        - Errors
      summary: "ERC20InvalidReceiver"
      description: |
        Indicates an invalid token recipient during a transfer.
      operationId: error_ERC20InvalidReceiver
      responses:
        "200":
          description: "Error schema"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ERC20InvalidReceiverError"

  /errors/ERC20InsufficientAllowance:
    get:
      tags:
        - Errors
      summary: "ERC20InsufficientAllowance"
      description: |
        Indicates insufficient spender allowance during a transfer.
      operationId: error_ERC20InsufficientAllowance
      responses:
        "200":
          description: "Error schema"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ERC20InsufficientAllowanceError"

  /errors/ERC20InvalidApprover:
    get:
      tags:
        - Errors
      summary: "ERC20InvalidApprover"
      description: |
        Indicates an invalid approver during an approval operation.
      operationId: error_ERC20InvalidApprover
      responses:
        "200":
          description: "Error schema"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ERC20InvalidApproverError"

  /errors/ERC20InvalidSpender:
    get:
      tags:
        - Errors
      summary: "ERC20InvalidSpender"
      description: |
        Indicates an invalid spender during an approval operation.
      operationId: error_ERC20InvalidSpender
      responses:
        "200":
          description: "Error schema"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ERC20InvalidSpenderError"

components:
  schemas:
    ErrorResponse:
      type: object
      description: "Shared schema representing errors during contract calls."
      properties:
        message:
          type: string
          description: "Stores the custom error name or revert/require message verbatim."
        data:
          type: object
          description: "Additional information (optional)."

    TransferEvent:
      type: object
      description: "Emitted when tokens are transferred, including zero-value transfers."
      properties:
        from:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "indexed: true. Source address (Solidity: address)."
        to:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "indexed: true. Recipient address (Solidity: address)."
        value:
          type: string
          description: "indexed: false. Transferred amount (Solidity: uint256)."

    ApprovalEvent:
      type: object
      description: "Emitted when the owner sets a spender allowance."
      properties:
        owner:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "indexed: true. Token owner address (Solidity: address)."
        spender:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "indexed: true. Authorized spender address (Solidity: address)."
        value:
          type: string
          description: "indexed: false. New allowance (Solidity: uint256)."

    ERC20InsufficientBalanceError:
      type: object
      description: "Indicates insufficient sender balance."
      properties:
        sender:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Address with insufficient balance (Solidity: address)."
        balance:
          type: string
          description: "Current balance (Solidity: uint256)."
        needed:
          type: string
          description: "Required balance (Solidity: uint256)."

    ERC20InvalidSenderError:
      type: object
      description: "Indicates an invalid token sender."
      properties:
        sender:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Invalid sender address (Solidity: address)."

    ERC20InvalidReceiverError:
      type: object
      description: "Indicates an invalid token recipient."
      properties:
        receiver:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Invalid recipient address (Solidity: address)."

    ERC20InsufficientAllowanceError:
      type: object
      description: "Indicates insufficient spender allowance."
      properties:
        spender:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Spender address with insufficient allowance (Solidity: address)."
        allowance:
          type: string
          description: "Current allowance (Solidity: uint256)."
        needed:
          type: string
          description: "Required allowance (Solidity: uint256)."

    ERC20InvalidApproverError:
      type: object
      description: "Indicates an invalid token approver."
      properties:
        approver:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Invalid approver address (Solidity: address)."

    ERC20InvalidSpenderError:
      type: object
      description: "Indicates an invalid spender."
      properties:
        spender:
          type: string
          pattern: "^0x[0-9a-fA-F]{40}$"
          description: "Invalid spender address (Solidity: address)."

Contract Spec Generator Subagent

Creating the specifications described above manually can be time-consuming. I created a Claude Code subagent called Contract Spec Generator to automate this work.

Given a prompt, the subagent automates the workflow from generating specifications to constructing a documentation site. Users answer its questions rather than manually configuring each component or running every command.

Agent and skill structure

Contract Spec Generator consists of an agent definition and a skill with supporting files.

text
.claude/
├── agents/
│   └── contract-spec-generator.md    # Agent definition (workflow control)
└── skills/
    └── contract-spec-generator/
        ├── SKILL.md                   # Skill definition (generation rules and specification)
        └── references/
            ├── generate-openapi-specs.js   # Specification skeleton generator
            ├── generate-contract-docs.js   # Markdown documentation generator
            ├── spec-prompt.md              # Specification generation rules
            ├── docusaurus-setup.md         # Site setup guide
            ├── sidebars.template.js        # Sidebar template
            └── custom.css                  # CSS template

Agent Controls the interactive workflow. It handles user confirmations, phase transitions, and command execution.

Skill Defines the specification generation rules and procedures. It describes details such as tag classification, type mapping, and error handling.

Features

Contract Spec Generator automatically creates OpenAPI and Swagger specifications from Solidity ABIs and source code. Its interactive workflow consists of three phases.

Phase Work User confirmation
Phase 1 Generate specifications (skeleton generation and AI enrichment) No
Phase 2 Build a Docusaurus site and start it locally Yes
Phase 3 Deploy to Vercel Yes

After completing each phase, the subagent asks the user whether to continue and advances only with approval. If only specification files are required, stop after Phase 1. Continue if a documentation site or deployment is needed.

Three-phase workflow

Phase 1: Generate specifications

Specification generation consists of two stages.

Stage 1: Generate skeletons

A Node.js script generates basic specification structures for all contracts in a batch. It automatically supplies descriptions for familiar patterns such as ERC20 functions, Pausable, and AccessControl. It also maps types automatically, assigning a regular-expression pattern to address and appropriate examples to uint256. It adds common error candidates to write functions and generates paths and basic schemas for events, errors, and structs. These candidates must be checked against the actual contract behavior.

Stage 2: AI enrichment

After skeleton generation, the subagent analyzes the source code and performs the following enhancements.

  • Trace internal calls and add possible errors to the 500 response.
  • Describe the effects of modifiers in function descriptions.
  • Replace generic descriptions with detailed Japanese descriptions grounded in the business logic, in accordance with the original generator's language setting.
  • Add meaningful parameter descriptions alongside type information.

Phase 2: Build the site

After Phase 1, the subagent asks whether to build a documentation site. With approval, it automatically performs the following operations.

  • Create or update a Docusaurus project.
  • Install the Redocusaurus plugin.
  • Generate Markdown documentation with generate-contract-docs.js.
  • Start a local development server at http://localhost:3000.

Phase 3: Deploy to Vercel

After the local preview, the subagent asks whether to deploy the site to Vercel. The user can choose from three options.

  • CLI Automatically deploy using the Vercel CLI.
  • Manual Output instructions for deployment through the Vercel dashboard.
  • No Finish with the local environment only.

Usage

Invoking the subagent

Invoke the subagent in Claude Code as shown below. Specify the ABI file path and contract source path.

text
The ABI is at contract/out/MyToken.sol/MyToken.json and the contract is at contract/src/MyToken.sol. Use the contract-spec-generator agent to generate the specification.

Alternatively, provide directory paths as follows.

text
The ABIs are in contract/out and the contracts are in contract/src. Use the contract-spec-generator agent to generate the specifications.

Given the prompt, the subagent runs the following workflow while asking the user questions. Users respond to the questions rather than manually executing complex commands.

Required inputs

Provide the following information when invoking the subagent.

Input Description Example
ABI file path Compiled ABI in JSON format contract/out/MyToken.sol/MyToken.json
Contract source path Solidity source code contract/src/MyToken.sol

ABI output locations vary by build tool. Build the contracts and generate their ABIs beforehand.

Detailed automated workflow

Step 1: Build contracts and generate ABIs (prerequisites)

Before invoking the subagent, compile the contracts to generate their ABIs. The ABI contains function signatures, events, errors, and tuple information for ABI-visible structs, providing the basis for specification generation.

Generate the ABIs using the commands appropriate to your build tool.

Foundry (forge)

bash
cd contract
forge build

The generated artifact is located at out/{ContractName}.sol/{ContractName}.json.

Hardhat

bash
cd contract
npx hardhat compile

The generated artifact is located at artifacts/contracts/{ContractName}.sol/{ContractName}.json.

Step 2: Run the skeleton generation script

The generate-openapi-specs.js script analyzes the ABIs and source code and generates OpenAPI and Swagger specification skeletons in a batch.

bash
node generate-openapi-specs.js

The script performs the following operations.

Operation Description
ABI analysis Obtain ABIs using forge inspect and extract functions, events, and errors
Source analysis Use regular expressions to extract inheritance, structs, modifiers, state variables, and constants
Type mapping Convert types automatically, for example address to pattern: "^0x[0-9a-fA-F]{40}$" and uint256 to type: string
Description generation Automatically attach Japanese descriptions to familiar patterns such as standard ERC20 functions and AccessControl
Error generation Add common error candidates such as InvalidAddress and AmountZero to write functions for subsequent validation

The outputs are placed in docs/contract/{ContractName}/{ContractName}.openapi.yaml and the corresponding .swagger.json file.

Step 3: Add detailed information through AI enrichment

After skeleton generation, the subagent analyzes the source code and performs the following enhancements.

Trace errors from internal calls

Trace functions called internally by external functions and add possible errors to their 500 responses. For example, if transferFrom() calls _spendAllowance() internally and that function can produce an InsufficientAllowance error, include that error in the 500 response for transferFrom().

Add modifier information

Add descriptions of the effects of modifiers attached to a function. For a function protected by onlyRole(ADMIN_ROLE), add an explanation that only accounts with ADMIN_ROLE may execute the function.

Add contract-specific descriptions

Replace generic descriptions with detailed Japanese explanations based on the actual business logic. For example, replace a generic description of a token transfer with one explaining that the function transfers stablecoins to a specified address and raises InsufficientBalance when the source balance is insufficient.

Step 4: Build the Docusaurus site

Once specification generation is complete, the subagent displays a confirmation prompt such as the following.

text
Build a documentation site?

Answer Yes to begin building the site. Answer No to finish with only the generated specification files.

Once site construction is approved, the following tasks run automatically.

If a Docusaurus project does not exist, create it and install the Redocusaurus plugin. Configure a helper in docusaurus.config.js to detect and register all contracts under docs/contract/.

Run generate-contract-docs.js to generate Markdown documentation for each contract. This produces both interactive specifications rendered with Redoc and human-readable Markdown documentation.

Step 5: Start the local preview

After constructing the site, run npm run start to start the development server and preview the documentation at http://localhost:3000.

The site has the following structure.

Page Path Contents
Home / Contract cards grouped by category
Specification /api/{ContractName} Interactive specification rendered by Redoc
Documentation /docs/contracts/{ContractName} Detailed Markdown documentation

Step 6: Deploy to Vercel (optional)

After reviewing the preview, the subagent displays a confirmation prompt such as the following.

text
Deploy to Vercel?
- Yes (CLI): Deploy using the Vercel CLI.
- Yes (manual): Output deployment instructions if the CLI is not preferred.
- No: Finish with the local environment only.

Deploy using the CLI

Selecting Yes (CLI) triggers the following steps.

  1. Copy the specification files to docs-site/specs/.
  2. Update paths in docusaurus.config.js.
  3. Deploy using vercel --prod.

After deployment, the site is published at its Vercel URL, represented here by https://{project-name}.vercel.app/.

Deploy manually

Selecting Yes (manual) displays instructions for deployment through the Vercel dashboard. The original workflow describes importing a GitHub repository or deploying a local project; the available deployment method depends on the Vercel workflow.

Generated artifacts

The subagent produces the following artifacts.

Specification files

An OpenAPI 3.0 YAML file and a Swagger 2.0 JSON file are generated for each contract. They are stored under docs/contract/{ContractName}/.

Documentation site

A Docusaurus documentation site is built in docs-site/. Redocusaurus renders the generated specifications as interactive API documentation. Markdown documentation for each contract is also generated under docs-site/docs/contracts/, including an overview, inheritance, principal features, and function list.

Site structure

The generated documentation site looks like the following.

The documentation page describes important functions and other details for each contract.

https://smartcontract-specification.vercel.app/docs/intro

Each contract also has a specification page.

https://smartcontract-specification.vercel.app/api/ERC20

Page structure

Page Path Contents
Home / Contract cards grouped by category
Overview /overview System-wide description and list of contracts
Documentation /docs/contracts/* Detailed Markdown documentation for each contract
Specifications /api/* OpenAPI and Swagger specifications rendered with Redoc

Header structure

Position Element Destination
Leftmost Logo and project name /
Second Docs /overview (system overview)
Third onward Category dropdown /api/{ContractName} (specification)
Rightmost GitHub Repository URL

Home page

Contract cards are grouped by category, and the View specification button links to each contract's detailed specification.

The hero section contains only a title and subtitle, without buttons. Category names are centered.

API specification pages

Interactive specifications are rendered by Redocusaurus. The sidebar groups functions, events, errors, and structs.

Documentation pages

Documentation is written in Markdown. Each page includes an overview, inheritance, principal features, and a list of functions.

A link to the corresponding API specification appears at the beginning of each documentation page.

markdown
> **[📋 View API specification](/api/{ContractName})**

Overview page

Displays a system-wide explanation and a list of all contracts. Each contract has links to both its documentation and its specification.

Conclusion

This article examined a method for documenting Solidity smart contracts in OpenAPI and Swagger formats.