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 explores Chainlink Functions as described in September 2025. It is based on the following official documentation.

Overview

Chainlink Functions is a service designed to give on-chain smart contracts secure access to reliable off-chain computing infrastructure. It enables smart contracts to retrieve data from external APIs and perform complex computations.

Developers send a request from a smart contract containing the JavaScript code they want to execute to a distributed network called a Decentralized Oracle Network (DON). Each node in the DON independently executes the received code in a serverless environment. The nodes' execution results are aggregated and returned to the smart contract as a single result.

A major advantage of this approach is that developers do not need to operate or manage their own Chainlink nodes. Multiple distributed nodes perform computation and verification instead of relying on a single node. Under the network's fault assumptions, consensus helps prevent a malicious minority from manipulating the result.

Requests can also include confidential values, such as API keys. These values are encrypted using a technique called threshold encryption before transmission. Decryption requires cooperation among multiple DON nodes, so an individual node cannot decrypt the ciphertext independently.

Service fees are paid in LINK tokens. Developers deposit LINK into a subscription account in advance, and fees are deducted from that balance as the DON processes requests and returns results.

Usage Considerations

Chainlink Functions is a flexible tool, but developers must consider the following points.

Chainlink Functions is a self-service solution that developers use at their own risk. Developers must carefully review the reliability and security of the JavaScript code submitted in requests and any external APIs on which it depends. Community-provided sample code may not have been audited and should also be reviewed before use.

The service does not guarantee execution or results. The original documentation states that Chainlink Labs, Chainlink Foundation, and node operators do not assume responsibility for unintended results arising from issues such as bugs in developers' code or external API failures.

It is also important to ensure that data sources and APIs offer sufficient quality and availability for the intended use case. Developers must comply with the licensing agreements and terms of service of their data providers. Violations may result in suspension of their Chainlink Functions accounts.

Main Use Cases

The flexibility of Chainlink Functions supports a broad range of applications.

  • Connecting to public data: Retrieve statistical data from weather APIs to automate insurance products, or obtain sports results in real time to change NFT designs.
  • Retrieving and transforming data: Retrieve posts containing particular keywords from the Twitter API, calculate their sentiment (positive or negative), and use the resulting data in smart contracts.
  • Connecting to authenticated data sources: Access protected data from sources such as IoT devices (including smartwatches) and enterprise resource planning (ERP) systems.
  • Integrating with decentralized databases: Integrate with decentralized storage such as IPFS to streamline off-chain processes, including building lower-cost governance voting systems.
  • Integrating with existing Web2 applications: Combine conventional web services with smart contracts to create more sophisticated hybrid smart contracts.
  • Retrieving data from major cloud storage services: Retrieve data directly from widely used Web2 systems such as AWS S3, Firebase, and Google Cloud Storage.

Code Examples and Explanation

Code for using Chainlink Functions consists primarily of two parts.

  • Solidity code A smart contract running on the blockchain that sends requests to Chainlink Functions.
  • JavaScript code Source code executed off-chain by the DON's nodes to perform the requested operation, such as accessing an API.

The following simple example retrieves the current price of ether (ETH) in Japanese yen (JPY) from an external API.

JavaScript Code

This code sends a request to the CoinGecko API and returns the ETH price.

javascript
// CoinGecko APIからETHのJPY価格を取得する
const coinGeckoRequest = Functions.makeHttpRequest({
  url: "https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=jpy"
});

// HTTPリクエストを並行して実行
const [response] = await Promise.all([
  coinGeckoRequest
]);

// エラーチェック
if (!response.error) {
  // レスポンスのJSONから価格を取得
  const price = response.data.ethereum.jpy;
  // 結果を数値として返す (Solidity側で扱いやすいように)
  return Functions.encodeUint256(price);
} else {
  // エラーが発生した場合はエラーコードを返す
  return Functions.encodeUint256(0);
}
  • Functions.makeHttpRequest A function provided by Chainlink Functions for defining an HTTP request to an external API. The url parameter specifies the target API endpoint.
  • await Promise.all(...) Execute the defined request asynchronously and wait for the response.
  • response.data.ethereum.jpy The API returns a JSON response, so the code retrieves the price through the data object, the ethereum object, and the jpy property.
  • Functions.encodeUint256(price) Convert the retrieved numeric price to the uint256 format that a Solidity smart contract can interpret, and return it. Return 0 if an error occurs.

Solidity Code

This smart contract asks the DON to execute the JavaScript code above and receives the result.

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import { FunctionsClient } from "@chainlink/contracts/src/v0.8/functions/v1_0_0/FunctionsClient.sol";
import { FunctionsRequest } from "@chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol";

contract MyFunctionsConsumer is FunctionsClient {
    using FunctionsRequest for FunctionsRequest.Request;

    bytes32 public latestRequestId;
    bytes public latestResponse;
    bytes public latestError;

    // 実行するJavaScriptコード
    string private source = "/* ここに上記のJavaScriptコードを文字列として記述 */";
    // サブスクリプションID
    uint64 private subscriptionId = 123;
    // ガスリミット
    uint32 private gasLimit = 300000;

    constructor() FunctionsClient(msg.sender) {}

    // Chainlink Functionsにリクエストを送信する関数
    function sendRequest() external returns (bytes32 requestId) {
        FunctionsRequest.Request memory req;
        req.initializeRequestForInlineJavaScript(source); // JavaScriptコードを初期化
        
        // リクエストを送信
        latestRequestId = _sendRequest(req.encodeCBOR(), subscriptionId, gasLimit, 0xac7a68e6488d5f309b43c5f2b801457884d34a4a49c8112e525164627a8103e3);
        return latestRequestId;
    }

    // DONから結果を受け取るためのコールバック関数
    function fulfillRequest(bytes32 requestId, bytes memory response, bytes memory err) internal override {
        latestResponse = response;
        latestError = err;
    }
}
  • import Import the contracts and libraries provided by Chainlink to use Functions.
  • source Store the JavaScript code that the DON should execute as a string.
  • subscriptionId The ID of the subscription created and funded in advance to pay fees.
  • gasLimit Specifies the maximum gas available for fulfilling the Functions request.
  • sendRequest() An externally callable function that prepares and submits a request.
    • req.initializeRequestForInlineJavaScript(source) Initialize the request using the JavaScript code stored in source.
    • _sendRequest(...) An internal function inherited from FunctionsClient that sends the request to the DON.
  • fulfillRequest(...) A callback function invoked to deliver the result after the DON completes request processing. The response parameter contains the result returned by the JavaScript code (the ETH price in this example), and err contains error information. Store these values in variables such as latestResponse to inspect the result later.

Architecture

Data Request and Response Mechanism

The Chainlink Functions request-response model resembles Chainlink's basic request model. The process begins when a consumer contract created by a developer initiates a request. The request is sent to the FunctionsRouter contract. Oracle nodes in the DON monitor events emitted on the blockchain and execute the requested computations off-chain. The nodes' results are then aggregated using Chainlink's OCR protocol and delivered as a single response to the consumer contract's callback function.

The principal components of this mechanism are as follows.

  • Initiator The entity that initiates a Functions request. This may be an ordinary wallet account operated by a person (EOA) or Chainlink Automation, which automates scheduled tasks.
  • Consumer contract The smart contract deployed by the developer, which interacts with FunctionsRouter to initiate requests.
  • FunctionsRouter contract The contract that manages subscriptions and serves as the entry point for consumer requests. Developers initiate requests through its sendRequest method.
  • FunctionsCoordinator contract The contract that serves as the interface to the DON. Oracle nodes monitor events emitted by this contract and interact with it when submitting responses.
  • DON (Decentralized Oracle Network) The core of Chainlink Functions, comprising independent oracle nodes. Each node executes the source code specified in the request, and the results are aggregated using the OCR protocol. Ultimately, an oracle node selected from the DON delivers the aggregated response to the consumer contract through the on-chain fulfillment path.
  • Secrets endpoint A service for securely supplying confidential information such as API keys to the DON. Users encrypt their secrets with the DON's public key and upload the encrypted information to this endpoint. The encrypted information can then be shared with the nodes. Alternatively, users can self-host the encrypted secrets on their own server and provide a URL from which the information can be retrieved.
  • Serverless environment Each oracle node accesses an isolated sandbox environment to perform computations. In addition to API requests, the environment can execute pure Deno code (JavaScript or TypeScript), such as mathematical computations that do not require module imports, subject to runtime constraints. Because the DON's nodes execute the same computation independently, developers should account for request rate limits imposed by external APIs.

The following describes how these components work together to process requests.

Data request and response mechanism https://docs.chain.link/chainlink-functions/resources/architecture

  1. Prepare secrets If a request needs confidential information such as an API key, the user encrypts it with the DON's master public key and uploads it to the secrets endpoint. The encrypted secrets are then distributed to the DON nodes.
  2. Initiate the request An EOA or Chainlink Automation calls a specific function in the consumer contract to initiate the request process.
  3. Send the request from the consumer to the router The consumer contract must inherit FunctionsClient to receive the response. Upon receiving the request, FunctionsRouter estimates the execution cost and temporarily reserves the corresponding amount of LINK from the subscription balance. It then calls the FunctionsCoordinator contract.
  4. Emit an event FunctionsCoordinator emits an OracleRequest event containing request details.
  5. Execute the request through the DON The DON's nodes detect the event. When secrets are specified, the nodes cooperate to decrypt them using threshold decryption. Each node then executes the specified source code in its own serverless environment.
  6. Aggregate results The DON executes the OCR protocol to aggregate the individual results produced by the nodes into a single value.
  7. Submit the aggregated result An oracle node in the DON submits an authenticated report containing the aggregated response to FunctionsCoordinator.
  8. Calculate the final cost FunctionsCoordinator invokes the fulfill method of FunctionsRouter, which determines the actual execution cost and finalizes the charge.
  9. Return the response Finally, FunctionsRouter calls the consumer contract's callback function, such as handleOracleFulfillment, to deliver the aggregated response.

Subscription Management

Chainlink Functions uses a subscription model rather than requiring LINK payments to be submitted separately with each request. Developers create and fund a subscription account with LINK in advance, allowing consumer contracts to issue requests without directly holding LINK.

Key Concepts

  • Terms of service (ToS) Users must agree to the terms of service before using Chainlink Functions. Accounts that agree are added to an allowlist and can manage subscriptions.
  • Chainlink Functions Subscription Manager A web interface for accepting the terms of service and creating and managing subscriptions.
  • Subscription account An account that holds LINK tokens used to pay for requests. Each account is identified by a unique Subscription ID.
  • Subscription ID A 64-bit integer uniquely identifying the subscription account.
  • Subscription owner The wallet address authorized to create and manage the subscription account. Anyone can fund it with LINK, but only the owner can add or remove consumers or withdraw funds.
  • Subscription balance The total amount of LINK deposited in the subscription account.
  • Subscription reservation The amount of LINK temporarily reserved from the balance for in-flight requests.
  • Effective balance The amount of LINK actually available for new requests. This equals the Subscription balance minus the Subscription reservation.
  • Subscription consumers The list of consumer contracts authorized to submit requests using the subscription's funds.

Subscription Operations

Accepting the Terms of Service

Accepting the terms of service https://docs.chain.link/chainlink-functions/resources/architecture

An account managing a subscription must first agree to the terms of service. By signing through the Subscription Manager, the account is registered in the allowlist contract.

Creating a Subscription

Creating a subscription https://docs.chain.link/chainlink-functions/resources/architecture

An account that has accepted the terms of service can create a subscription. A unique Subscription ID is assigned upon creation.

Funding a Subscription

Funding a subscription https://docs.chain.link/chainlink-functions/resources/architecture

Use the Subscription Manager to transfer LINK tokens to the subscription account. Internally, the LINK token contract's transferAndCall function is called, specifying the subscription to fund as part of the transfer.

Adding a Consumer

Adding a consumer https://docs.chain.link/chainlink-functions/resources/architecture

Add the deployed consumer contract's address to the subscription allowlist so that it can use the subscription.

Removing a Consumer

Removing a consumer https://docs.chain.link/chainlink-functions/resources/architecture

To stop requests from a particular contract, remove that contract from the subscription. Any requests already in flight at removal continue to be processed and billed.

Canceling a Subscription

Canceling a subscription https://docs.chain.link/chainlink-functions/resources/architecture

Subscriptions that are no longer needed can be canceled. Specify the address to which the remaining LINK tokens should be transferred. However, cancellation is unavailable while there are in-flight requests or expired requests that have remained unanswered for more than five minutes.

Transferring Ownership

Subscription ownership can also be transferred to another account. At the time of the original article, this operation was performed through command-line tools such as the Hardhat Starter Kit. The new owner must also have accepted the terms of service in advance.

Processing Flow

sequenceDiagram
    participant Initiator as 開始者<br>(EOA/Automation)
    participant Consumer as コンシューマー<br>コントラクト
    participant Router as Functions<br>Router
    participant Coordinator as Functions<br>Coordinator
    participant DON as 分散オラクル<br>ネットワーク(DON)
    participant Secrets as シークレット<br>エンドポイント

    opt 準備フェーズ (秘密情報利用時)
        Initiator->>+Secrets: 1. 暗号化した秘密情報をアップロード
        Secrets-->>-DON: 2. 暗号化された秘密情報を配布
    end

    note over Initiator,Secrets: リクエストフェーズ
    Initiator->>+Consumer: 3. リクエスト関数を呼び出し
    Consumer->>+Router: 4. sendRequest() を実行
    Router->>Router: 5. コストを見積もり、<br>サブスクリプション残高を予約
    Router->>+Coordinator: 6. リクエストを転送
    Coordinator-->>DON: 7. OracleRequestイベントを発行
    deactivate Coordinator
    deactivate Router
    deactivate Consumer

    note over Initiator,Secrets: オフチェーン実行フェーズ
    DON->>DON: 8. (必要なら)閾値復号で秘密情報を復号
    DON->>DON: 9. 各ノードがソースコードを実行
    DON->>DON: 10. OCRプロトコルで結果を集約

    note over Initiator,Secrets: コールバックフェーズ
    DON->>+Coordinator: 11. 集約したレポートを送信
    Coordinator->>+Router: 12. fulfill() を呼び出し、最終コストを計算
    deactivate Coordinator
    Router->>Router: 13. 課金を確定
    Router->>+Consumer: 14. コールバック関数を呼び出し、<br>最終的な応答を渡す
    Consumer->>Consumer: 15. 受け取った応答を処理・保存
    deactivate Consumer
    deactivate Router

Preparation Phase

This optional phase is needed only when a request includes confidential information such as API keys.

  • 1. Upload encrypted secrets The initiator (a user wallet or an automation service) encrypts the secrets with the DON's public key and uploads the ciphertext to the secrets endpoint.

  • 2. Distribute encrypted secrets The secrets endpoint distributes the received ciphertext to each oracle node in the DON.

Request Phase

This is the initial stage in which a smart contract requests external computation or data retrieval.

  • 3. Call the request function The initiator calls the function that the developer created in the consumer contract to submit a Functions request. This begins the overall process.

  • 4. Execute sendRequest() The consumer contract calls the Functions Router contract's sendRequest function in response to the received instruction. It passes arguments such as the JavaScript code to execute and the references to any secrets to use.

  • 5. Estimate the cost and reserve the subscription balance The Router estimates the approximate request execution cost, including gas, and temporarily reserves the corresponding amount from the user's subscription balance.

  • 6. Forward the request The Router forwards the request information to the Functions Coordinator contract. The Coordinator handles direct interactions with the DON.

  • 7. Emit the OracleRequest event The Coordinator emits an OracleRequest event on the blockchain containing the request details, such as the code and parameters. The event triggers the DON's off-chain task execution.

Off-chain Execution Phase

This is the core phase in which the actual computations take place outside the blockchain.

  • 8. Decrypt secrets using threshold decryption if needed The DON nodes monitor OracleRequest events and begin processing when they detect one. If the request references secrets, the nodes cooperate through threshold decryption to decrypt them.

  • 9. Execute the source code on each node Each node executes the JavaScript code specified in the request in its own isolated environment. API access and data processing occur here.

  • 10. Aggregate results using the OCR protocol The individual execution results are aggregated through OCR (Off-Chain Reporting). This helps tolerate errors or malicious behavior by individual nodes under the network's fault assumptions and produces a single aggregated result.

Callback Phase

The final phase returns the off-chain result to the on-chain smart contract.

  • 11. Submit the aggregated report The DON produces a report containing the aggregated result and cryptographic signatures authenticating the report, then submits it to Functions Coordinator.

  • 12. Call fulfill() and calculate the final cost Upon receiving the report, the Coordinator verifies its contents and invokes the Functions Router contract's fulfill function. The actual cost incurred in executing the request is calculated at this stage.

  • 13. Finalize billing The Router deducts the calculated final cost from the previously reserved subscription funds. If the actual cost is lower than the reserved amount, the difference is released back into the available balance.

  • 14. Call the callback function and deliver the final response The Router calls the callback defined in the requesting consumer contract, for example handleOracleFulfillment, and passes the final response obtained from the DON.

  • 15. Process and store the received response The consumer contract uses the callback data as required, such as by storing it in contract variables or using it to trigger another operation. This completes the process.

Secrets Management

The original documentation described Chainlink Functions as a beta service. The use of secrets in requests was described as experimental and could behave unexpectedly or change in future versions. Developers use the feature at their own risk, including unexpected errors, potential exposure of secrets during version changes, and other problems.

Managing Secrets

Chainlink Functions provides functionality for retrieving data from HTTP(S) APIs and executing custom computations. Some APIs require credentials such as API keys or passwords. To support these APIs, Chainlink Functions allows requests to reference encrypted secrets.

These secrets are used when the DON executes the request. The ciphertext can be decrypted only through a process involving multiple participants, called threshold decryption. Individual DON nodes cannot decrypt the ciphertext independently; cooperation among multiple nodes is required.

Encrypted secrets can be uploaded to the DON directly or placed at a remote URL controlled by the user, with a reference to that location included in the request.

Threshold Encryption

If a single private key were used to decrypt users' secrets, a malicious or compromised node holding that key could decrypt every secret accessible to it, introducing significant security risk.

Chainlink Functions integrates threshold encryption to address this vulnerability. This mechanism has the following characteristics.

  • Distributed nodes The system operates on a DON consisting of N nodes.
  • Master secret key shares Instead of storing the master secret key (MSK) used for decryption in one location, it is divided into multiple shares. Each DON node holds a distinct share.

The system defines two important thresholds.

  • Availability The mechanism provides fault tolerance to support continued operation. The system can continue operating even in the presence of up to F Byzantine nodes (nodes that behave maliciously or unpredictably). This is expressed as 3F+1 ≤ N, meaning the total number of nodes N must be at least three times the number of faulty nodes F plus one.
  • Decryption security An attacker must compromise K nodes to reconstruct the master secret key (MSK). K satisfies the relation F < K ≤ 2F+1. The attacker must therefore control more nodes than the assumed number of faulty nodes F to reconstruct the key itself.

Encryption and Decryption Process

Users encrypt their secrets with the public key corresponding to the master secret key to produce ciphertext. The encrypted secrets themselves are not stored on the blockchain. Decrypting the ciphertext requires cooperation among at least K nodes, satisfying F < K ≤ 2F+1. Decryption requires the threshold number of nodes to participate in processing the same ciphertext.

Hosting Options

There are two ways to share encrypted secrets with the DON.

  • DON-hosted Users submit their encrypted secrets (ciphertext) directly to a dedicated secrets endpoint provided by the DON. This is the simplest option, but it requires at least one subscription owned by the user's account to maintain the required minimum balance.
  • User-hosted Some users want strict control over data storage and lifecycle, such as deleting secrets immediately after a request completes. In this model, users place encrypted secrets (ciphertext) on a publicly accessible HTTP(S) server they control. They encrypt the server URL using the DON's public key and provide the encrypted URL when submitting the request. Users are responsible for deleting the ciphertext from their server after request processing finishes.

Conclusion

This article covered Chainlink Functions.

I also publish articles elsewhere if you would like to explore them.

https://chaldene.net/