# FunctionsClient API Reference Source: https://docs.chain.link/chainlink-functions/api-reference/functions-client Consumer contract developers inherit [FunctionsClient](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/FunctionsClient.sol) to create Chainlink Functions requests. ## Events ### RequestSent ```solidity event RequestSent(bytes32 id) ``` ### RequestFulfilled ```solidity event RequestFulfilled(bytes32 id) ``` ## Errors ### OnlyRouterCanFulfill ```solidity error OnlyRouterCanFulfill() ``` ## Methods ### constructor ```solidity constructor(address router) ``` ### _sendRequest ```solidity function _sendRequest(bytes data, uint64 subscriptionId, uint32 callbackGasLimit, bytes32 donId) internal returns (bytes32) ``` Sends a Chainlink Functions request to the stored router address #### Parameters | Name | Type | Description | | ---------------- | ------- | --------------------------------------------------------------------- | | data | bytes | The CBOR encoded bytes data for a Functions request | | subscriptionId | uint64 | The subscription ID that will be charged to service the request | | callbackGasLimit | uint32 | the amount of gas that will be available for the fulfillment callback | | donId | bytes32 | | #### Return Values | Name | Type | Description | | ---- | ------- | --------------------------------------------------- | | [0] | bytes32 | requestId The generated request ID for this request | ### fulfillRequest ```solidity function fulfillRequest(bytes32 requestId, bytes response, bytes err) internal virtual ``` User defined function to handle a response from the DON *Either response or error parameter will be set, but never both* #### Parameters | Name | Type | Description | | --------- | ------- | ----------------------------------------------------------------------------------- | | requestId | bytes32 | The request ID, returned by sendRequest() | | response | bytes | Aggregated response from the execution of the user's source code | | err | bytes | Aggregated error from the execution of the user code or from the execution pipeline | ### handleOracleFulfillment ```solidity function handleOracleFulfillment(bytes32 requestId, bytes response, bytes err) external ``` Chainlink Functions response handler called by the Functions Router during fulfillment from the designated transmitter node in an OCR round *Either response or error parameter will be set, but never both* #### Parameters | Name | Type | Description | | --------- | ------- | -------------------------------------------------------------------------------------- | | requestId | bytes32 | The requestId returned by FunctionsClient.sendRequest(). | | response | bytes | Aggregated response from the request's source code. | | err | bytes | Aggregated error either from the request's source code or from the execution pipeline. | --- # FunctionsRequest library API Reference Source: https://docs.chain.link/chainlink-functions/api-reference/functions-request Consumer contract developers use the [FunctionsRequest library](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol) to build their [requests](#request). ## Types and Constants ### REQUEST_DATA_VERSION ```solidity uint16 REQUEST_DATA_VERSION ``` ### DEFAULT_BUFFER_SIZE ```solidity uint256 DEFAULT_BUFFER_SIZE ``` ### Location ```solidity enum Location { Inline, Remote, DONHosted } ``` | Value | Description | | ----------- | ----------------------------------------------------------------------------- | | `Inline` | Provided within the Request. | | `Remote` | Hosted through a remote location that can be accessed through a provided URL. | | `DONHosted` | Hosted on the DON's storage. | ### CodeLanguage ```solidity enum CodeLanguage { JavaScript } ``` ### Request ```solidity struct Request { enum FunctionsRequest.Location codeLocation; enum FunctionsRequest.Location secretsLocation; enum FunctionsRequest.CodeLanguage language; string source; bytes encryptedSecretsReference; string[] args; bytes[] bytesArgs; } ``` | Field | Type | Description | | --------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `codeLocation` | `Location` | The location of the source code that will be executed on each node in the DON. | | `secretsLocation` | `Location` | The location of secrets that will be passed into the source code. \*Only Remote secrets are supported. | | `language` | `CodeLanguage` | The coding language that the source code is written in. | | `source` | `string` | Raw source code for `Request.codeLocation` of `Location.Inline`, URL for `Request.codeLocation` of `Location.Remote`, or slot decimal number for `Request.codeLocation` of `Location.DONHosted`. | | `encryptedSecretsReference` | `bytes` | Encrypted URLs for `Request.secretsLocation` of `Location.Remote`, or CBOR encoded `slotid+version` for `Request.secretsLocation` of `Location.DONHosted`. | | `args` | `string[]` | String arguments that will be passed into the source code. | | `bytesArgs` | `bytes[]` | Bytes arguments that will be passed into the source code. | ## Errors ### EmptySource ```solidity error EmptySource() ``` ### EmptySecrets ```solidity error EmptySecrets() ``` ### EmptyArgs ```solidity error EmptyArgs() ``` ### NoInlineSecrets ```solidity error NoInlineSecrets() ``` ## Functions ### encodeCBOR ```solidity function encodeCBOR(struct FunctionsRequest.Request self) internal pure returns (bytes) ``` Encodes a Request to CBOR encoded bytes #### Parameters | Name | Type | Description | | ---- | ------------------------------- | --------------------- | | self | struct FunctionsRequest.Request | The request to encode | #### Return values | Name | Type | Description | | ---- | ----- | ------------------ | | [0] | bytes | CBOR encoded bytes | ### initializeRequest ```solidity function initializeRequest(struct FunctionsRequest.Request self, enum FunctionsRequest.Location codeLocation, enum FunctionsRequest.CodeLanguage language, string source) internal pure ``` Initializes a Chainlink Functions Request *Sets the codeLocation and code on the request* #### Parameters | Name | Type | Description | | ------------ | ---------------------------------- | ----------------------------------------- | | self | struct FunctionsRequest.Request | The uninitialized request | | codeLocation | enum FunctionsRequest.Location | The user provided source code location | | language | enum FunctionsRequest.CodeLanguage | The programming language of the user code | | source | string | The user provided source code or a url | ### initializeRequestForInlineJavaScript ```solidity function initializeRequestForInlineJavaScript(struct FunctionsRequest.Request self, string javaScriptSource) internal pure ``` Initializes a Chainlink Functions Request *Simplified version of initializeRequest for PoC* #### Parameters | Name | Type | Description | | ---------------- | ------------------------------- | --------------------------------------------- | | self | struct FunctionsRequest.Request | The uninitialized request | | javaScriptSource | string | The user provided JS code (must not be empty) | ### addSecretsReference ```solidity function addSecretsReference(struct FunctionsRequest.Request self, bytes encryptedSecretsReference) internal pure ``` Adds Remote user encrypted secrets to a Request #### Parameters | Name | Type | Description | | ------------------------- | ------------------------------- | --------------------------------------------------------------------- | | self | struct FunctionsRequest.Request | The initialized request | | encryptedSecretsReference | bytes | Encrypted comma-separated string of URLs pointing to offchain secrets | ### addDONHostedSecrets ```solidity function addDONHostedSecrets(struct FunctionsRequest.Request self, uint8 slotID, uint64 version) internal pure ``` Adds DON-hosted secrets reference to a Request #### Parameters | Name | Type | Description | | ------- | ------------------------------- | ------------------------------------------- | | self | struct FunctionsRequest.Request | The initialized request | | slotID | uint8 | Slot ID of the user's secrets hosted on DON | | version | uint64 | User data version (for the slotID) | ### setArgs ```solidity function setArgs(struct FunctionsRequest.Request self, string[] args) internal pure ``` Sets args for the user run function #### Parameters | Name | Type | Description | | ---- | ------------------------------- | -------------------------------------------- | | self | struct FunctionsRequest.Request | The initialized request | | args | string[] | The array of string args (must not be empty) | ### setBytesArgs ```solidity function setBytesArgs(struct FunctionsRequest.Request self, bytes[] args) internal pure ``` Sets bytes args for the user run function #### Parameters | Name | Type | Description | | ---- | ------------------------------- | ------------------------------------------- | | self | struct FunctionsRequest.Request | The initialized request | | args | bytes[] | The array of bytes args (must not be empty) | --- # JavaScript code API Reference Source: https://docs.chain.link/chainlink-functions/api-reference/javascript-source JavaScript source code for a Functions request should comply with certain restrictions: - **Allowed Modules**: Vanilla [Deno](https://deno.land/) and module [imports](/chainlink-functions/tutorials/importing-packages). - **Return Type**: Must return a JavaScript `Buffer` object representing the response bytes sent back to the invoking contract. - **Time Limit**: Scripts must execute within a 10-second timeframe; otherwise, they will be terminated, and an error will be returned to the requesting contract. ## HTTP requests For making HTTP requests, use the `Functions.makeHttpRequest` function. ### Syntax ```javascript const response = await Functions.makeHttpRequest({ url: "http://example.com", method: "GET", // Optional // Other optional parameters }) ``` ### Parameters | Parameter | Optionality | Description | Default Value | | -------------- | ----------- | ----------------------------------------- | ------------- | | `url` | Required | The target URL. | N/A | | `method` | Optional | HTTP method to be used. | `'GET'` | | `headers` | Optional | HTTP headers for the request. | N/A | | `params` | Optional | URL query parameters. | N/A | | `data` | Optional | Body content for the request. | N/A | | `timeout` | Optional | Maximum request duration in milliseconds. | `3000 ms` | | `responseType` | Optional | Expected response type. | `'json'` | ### Return Object | Response Type | Fields | Description | | ------------- | ------------ | ------------------------------------------------ | | Success | `data` | Response data sent by the server. | | | `status` | Numeric HTTP status code. | | | `statusText` | Textual representation of HTTP status. | | | `headers` | HTTP headers sent by the server in the response. | | Error | `error` | Indicates an error occurred (`true`). | | | `message` | Optional error message. | | | `code` | Optional error code. | | | `response` | Optional server response. | ## Data encoding functions The Functions library includes several encoding functions, which are useful for preparing data for blockchain contracts. | Function | Input Type | Output Type | Description | | ------------------------- | ---------------- | ---------------- | ------------------------------------------------------------------------------ | | `Functions.encodeUint256` | Positive Integer | 32-byte `Buffer` | Converts a positive integer to a 32-byte `Buffer` for a `uint256` in Solidity. | | `Functions.encodeInt256` | Integer | 32-byte `Buffer` | Converts an integer to a 32-byte `Buffer` for an `int256` in Solidity. | | `Functions.encodeString` | String | `Buffer` | Converts a string to a `Buffer` for a `string` type in Solidity. | **Note**: Using these encoding functions is optional. The source code must return a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) which represents the `bytes` that are returned onchain. ```javascript const myArr = new Uint8Array(ARRAY_LENGTH) ``` --- # Getting Started Source: https://docs.chain.link/chainlink-functions/getting-started Learn how to make requests to the Chainlink Functions Decentralized Oracle Network (DON) and make any computation or API calls offchain. Chainlink Functions is available on several blockchains (see the [supported networks page](/chainlink-functions/supported-networks)), but this guide uses Sepolia to simplify access to testnet funds. Complete the following tasks to get started with Chainlink Functions: - Set up your web3 wallet and fund it with testnet tokens. - Simulate a Chainlink Functions on the [Chainlink Functions Playground](https://functions.chain.link/playground). - Send a Chainlink Functions request to the DON. The JavaScript source code makes an API call to the [Star Wars API](https://swapi.info) and fetches the name of a given character. - Receive the response from Chainlink Functions and parse the result. ## Simulation Before making a Chainlink Functions request from your smart contract, it is always a good practice to simulate the source code offchain to make any adjustments or corrections. 1. Open the [Functions playground](https://functions.chain.link/playground). 2. Copy and paste the following source code into the playground's code block. 3. Under *Argument*, set the first argument to 1. You are going to fetch the name of the first Star Wars character. 4. Click on *Run code*. Under *Output*, you should see *Luke Skywalker*. ## Configure your resources ### Configure your wallet You will test on Sepolia, so you must have an Ethereum web3 wallet with enough testnet ETH and LINK tokens. Testnet ETH is the native gas fee token on Sepolia. You will use testnet ETH tokens to pay for gas whenever you make a transaction on Sepolia. On the other hand, you will use LINK tokens to pay the Chainlink Functions Decentralized Oracles Network (DON) for processing your request. 1. [Install the MetaMask wallet](/quickstarts/deploy-your-first-contract#install-and-fund-your-metamask-wallet) or other Ethereum web3 wallet. 2. Set the network for your wallet to the Sepolia testnet. If you need to add Sepolia to your wallet, you can find the chain ID and the LINK token contract address on the [LINK Token Contracts](/resources/link-token-contracts#sepolia-testnet) page. - 3. Request testnet LINK and ETH from [faucets.chain.link/sepolia](https://faucets.chain.link/sepolia). ### Deploy a Functions consumer contract on Sepolia 1. Open the [GettingStartedFunctionsConsumer.sol](https://remix.ethereum.org/#url=https://docs.chain.link/samples/ChainlinkFunctions/GettingStartedFunctionsConsumer.sol) contract in Remix. 2. Compile the contract. 3. Open MetaMask and select the *Sepolia* network. 4. In Remix under the **Deploy & Run Transactions** tab, select *Injected Provider - MetaMask* in the **Environment** list. Remix will use the MetaMask wallet to communicate with *Sepolia*. 5. Click the **Deploy** button to deploy the contract. MetaMask prompts you to confirm the transaction. Check the transaction details to make sure you are deploying the contract to *Sepolia*. 6. After you confirm the transaction, the contract address appears in the **Deployed Contracts** list. Copy the contract address and save it for later. You will use this address with a Functions Subscription. ### Create a subscription You use a Chainlink Functions subscription to pay for, manage, and track Functions requests. 1. Go to [functions.chain.link](https://functions.chain.link/). 2. Click **Connect wallet**: 3. Read and accept the Chainlink Foundation Terms of Service. Then click **MetaMask**. 4. Make sure your wallet is connected to the *Sepolia* testnet. If not, click the network name in the top right corner of the page and select *Sepolia*. 5. Click **Create Subscription**: 6. Provide an email address and an optional subscription name: 7. The first time you interact with the Subscription Manager using your EOA, you must accept the Terms of Service (ToS). A MetaMask popup appears and you are asked to accept the ToS: 8. After you approve the ToS, another MetaMask popup appears, and you are asked to approve the subscription creation: 9. After the subscription is created, MetaMask prompts you to sign a message that links the subscription name and email address to your subscription: ### Fund your subscription 1. After the subscription is created, the Functions UI prompts you to fund your subscription. Click **Add funds**: 2. For this example, add 2 LINK and click **Add funds**: ### Add a consumer to your subscription 1. After you fund your subscription, add your consumer to it. Specify the address for the consumer contract that you deployed earlier and click **Add consumer**. MetaMask prompts you to confirm the transaction. 2. Subscription creation and configuration is complete. You can always see the details of your subscription again at [functions.chain.link](https://functions.chain.link): ## Run the example The example is hardcoded to communicate with Chainlink Functions on Sepolia. After this example is run, you can examine the code and see a detailed description of all components. 1. In Remix under the **Deploy & Run Transactions** tab, expand your contract in the **Deployed Contracts** section. 2. Expand the `sendRequest` function to display its parameters. 3. Fill in the `subscriptionId` with your subscription ID and `args` with `[1]`. You can find your subscription ID on the Chainlink Functions Subscription Manager at [functions.chain.link](https://functions.chain.link/). The `[1]` value for `args` specifies which argument in the response will be retrieved. 4. Click the **transact** button. 5. Wait for the request to be fulfilled. You can monitor the status of your request on the Chainlink Functions Subscription Manager. 6. Refresh the Functions UI to get the latest request status. 7. After the status is *Success*, check the character name. In Remix, under the **Deploy & Run Transactions** tab, click the `character` function. If the transaction and request ran correctly, you will see the name of your character in the response. Chainlink Functions is capable of much more than just retrieving data. Try one of the [Tutorials](/chainlink-functions/tutorials) to see examples that can GET and POST to public APIs, securely handle API secrets, handle custom responses, and query multiple APIs. ## Examine the code ### Solidity code - To write a Chainlink Functions consumer contract, your contract must import [FunctionsClient.sol](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/FunctionsClient.sol) and [FunctionsRequest.sol](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol). You can read the API references: [FunctionsClient](/chainlink-functions/api-reference/functions-client) and [FunctionsRequest](/chainlink-functions/api-reference/functions-request). These contracts are available in an NPM package so that you can import them from within your project. ``` 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"; ``` - Use the FunctionsRequest.sol library to get all the functions needed for building a Chainlink Functions request. ``` using FunctionsRequest for FunctionsRequest.Request; ``` - The latest request ID, latest received response, and latest received error (if any) are defined as state variables: ``` bytes32 public s_lastRequestId; bytes public s_lastResponse; bytes public s_lastError; ``` - We define the `Response` event that your smart contract will emit during the callback ``` event Response(bytes32 indexed requestId, string character, bytes response, bytes err); ``` - The Chainlink Functions router address and donID are hardcoded for Sepolia. Check the [supported networks page](/chainlink-functions/supported-networks) to try the code sample on another testnet. - The `gasLimit` is hardcoded to `300000`, the amount of gas that Chainlink Functions will use to fulfill your request. - The JavaScript source code is hardcoded in the `source` state variable. For more explanation, read the [JavaScript code section](#javascript-code). - Pass the router address for your network when you deploy the contract: ``` constructor() FunctionsClient(router) ``` - The two remaining functions are: - `sendRequest` for sending a request. It receives the subscription ID and list of arguments to pass to the source code. Then: - It uses the `FunctionsRequest` library to initialize the request and add the source code and arguments. You can read the API Reference for [Initializing a request](/chainlink-functions/api-reference/functions-request/#initializerequestforinlinejavascript) and [adding arguments](/chainlink-functions/api-reference/functions-request/#setargs). ``` FunctionsRequest.Request memory req; req.initializeRequestForInlineJavaScript(source); if (args.length > 0) req.setArgs(args); ``` - It sends the request to the router by calling the `FunctionsClient` `sendRequest` function. You can read the API reference for [sending a request](/chainlink-functions/api-reference/functions-client/#_sendrequest). Finally, it stores the request id in `s_lastRequestId` and returns it. ``` s_lastRequestId = _sendRequest( req.encodeCBOR(), subscriptionId, gasLimit, jobId ); return s_lastRequestId; ``` **Note**: `_sendRequest` accepts requests encoded in `bytes`. Therefore, you must encode it using [encodeCBOR](/chainlink-functions/api-reference/functions-request/#encodecbor). - `fulfillRequest` to be invoked during the callback. This function is defined in `FunctionsClient` as `virtual` (read `fulfillRequest` [API reference](/chainlink-functions/api-reference/functions-client/#fulfillrequest)). So, your smart contract must override the function to implement the callback. The implementation of the callback is straightforward: the contract stores the latest response and error in `s_lastResponse` and `s_lastError`, parses the `response` from `bytes` to `string` to fetch the character name before emitting the `Response` event. ``` s_lastResponse = response; character = string(response); s_lastError = err; emit Response(requestId, s_lastResponse, s_lastError); ``` ### JavaScript code This JavaScript source code uses [Functions.makeHttpRequest](/chainlink-functions/api-reference/javascript-source#http-requests) to make HTTP requests. The source code calls the `https://swapi.info/` API to request a Star Wars character name. If you read the [Functions.makeHttpRequest](/chainlink-functions/api-reference/javascript-source#http-requests) documentation and the [Star Wars API documentation](https://swapi.info/people), you notice that URL has the following format where `$characterId` is provided as parameter when making the HTTP request: ``` url: `https://swapi.info/api/people/${characterId}/` ``` To check the expected API response for the first character, you can directly paste the following URL in your browser `https://swapi.info/api/people/1/` or run the `curl` command in your terminal: ```bash curl -X 'GET' \ 'https://swapi.info/api/people/1/' \ -H 'accept: application/json' ``` The response should be similar to the following example: ```json { "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male", "homeworld": "https://swapi.info/api/planets/1/", "films": [ "https://swapi.info/api/films/1/", "https://swapi.info/api/films/2/", "https://swapi.info/api/films/3/", "https://swapi.info/api/films/6/" ], "species": [], "vehicles": ["https://swapi.info/api/vehicles/14/", "https://swapi.info/api/vehicles/30/"], "starships": ["https://swapi.info/api/starships/12/", "https://swapi.info/api/starships/22/"], "created": "2014-12-09T13:50:51.644000Z", "edited": "2014-12-20T21:17:56.891000Z", "url": "https://swapi.info/api/people/1/" } ``` Now that you understand the structure of the API. Let's delve into the JavaScript code. The main steps are: - Fetch `characterId` from `args`. Args is an array. The `characterId` is located in the first element. - Make the HTTP call using `Functions.makeHttpRequest` and store the response in `apiResponse`. - Throw an error if the call is not successful. - The API response is located at `data`. - Read the name from the API response `data.name` and return the result as a [buffer](https://nodejs.org/api/buffer.html#buffer) using the `Functions.encodeString` helper function. Because the `name` is a `string`, we use `encodeString`. For other data types, you can use different [data encoding functions](/chainlink-functions/api-reference/javascript-source#data-encoding-functions). **Note**: Read this [article](https://www.freecodecamp.org/news/do-you-want-a-better-understanding-of-buffer-in-node-js-check-this-out-2e29de2968e8/) if you are new to Javascript Buffers and want to understand why they are important. --- # Chainlink Functions Source: https://docs.chain.link/chainlink-functions Chainlink Functions provides your smart contracts access to trust-minimized compute infrastructure, allowing you to fetch data from APIs and perform custom computation. Your smart contract sends source code in a request to a [Decentralized Oracle Network (DON)](/chainlink-functions/resources/concepts), and each node in the DON executes the code in a serverless environment. The DON then aggregates all the independent return values from each execution and sends the final result back to your smart contract. Chainlink Functions eliminates the need for you to manage your own Chainlink node and provides decentralized offchain computation and consensus, ensuring that a minority of the network cannot manipulate the response sent back to your smart contract. Furthermore, Chainlink Functions allows you to include secret values in your request that are encrypted using threshold encryption. These values can only be decrypted via a multi-party decryption process, meaning that every node can only decrypt the secrets with participation from other DON nodes. This feature can provide API keys or other sensitive values to your source code, enabling access to APIs that require authentication. To pay for requests, you fund a subscription account with LINK. Your subscription is billed when the DON fulfills your requests. Check out the [subscriptions](/chainlink-functions/resources/subscriptions) page for more information. Read the [architecture](/chainlink-functions/resources/architecture) page to learn more about how Chainlink Functions works. See the [Tutorials](/chainlink-functions/tutorials) page for simple tutorials showing you different GET and POST requests that run on Chainlink Functions. You can also gain hands-on experience with Chainlink Functions with the [Chainlink Functions Playground](https://functions.chain.link/playground). ## When to use Chainlink Functions Chainlink Functions enables a variety of use cases. Use Chainlink Functions to: - Connect to any public data. For example, you can connect your smart contracts to weather statistics for parametric insurance or real-time sports results for Dynamic NFTs. - Connect to public data and transform it before consumption. You could calculate Twitter sentiment after reading data from the Twitter API, or derive asset prices after reading price data from [Chainlink Price Feeds](/data-feeds/price-feeds). - Connect to a password-protected data source; from IoT devices like smartwatches to enterprise resource planning systems. - Connect to an external decentralized database, such as IPFS, to facilitate offchain processes for a dApp or build a low-cost governance voting system. - Connect to your Web2 application and build complex hybrid smart contracts. - Fetch data from almost any Web2 system such as AWS S3, Firebase, or Google Cloud Storage. You can find several community examples at [useChainlinkFunctions.com](https://www.usechainlinkfunctions.com/) ## Supported networks See the [Supported Networks](/chainlink-functions/supported-networks) page to find a list of supported networks and contract addresses. --- # Chainlink Functions Architecture Source: https://docs.chain.link/chainlink-functions/resources/architecture ## Request and Receive Data This model is similar to the [Basic Request Model](/architecture-overview/architecture-request-model): The consumer contract initiates the cycle by sending a request to the [FunctionsRouter contract](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/FunctionsRouter.sol). Oracle nodes watch for events emitted by the [FunctionsCoordinator contract](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_1_0/FunctionsCoordinator.sol) and run the computation offchain. Finally, oracle nodes use the [Chainlink OCR](/architecture-overview/off-chain-reporting) protocol to aggregate all the returned before passing the single aggregated response back to the consumer contract via a callback function. The main actors and components are: - Initiator (or end-user): initiates the request to Chainlink Functions. It can be an [EOA (Externally Owned Account)](https://ethereum.org/en/developers/docs/accounts/#types-of-account) or Chainlink Automation. - Consumer contract: smart contract deployed by developers, which purpose is to interact with the FunctionsRouter to initiate a request. - FunctionsRouter contract: manages subscriptions and is the entry point for consumers. The interface of the router is stable. Consumers call the `sendRequest` method to initiate a request. - FunctionsCoordinator contracts: interface for the [Decentralized Oracle Network](https://chain.link/education/blockchain-oracles#decentralized-oracles). Oracle nodes listen to events emitted by the coordinator contract and interact with the coordinator to transmit the responses. - DON: Chainlink Functions are powered by a [Decentralized Oracle Network](https://chain.link/education/blockchain-oracles#decentralized-oracles). The oracle nodes are independent of each other and are responsible for executing the request's source code. The nodes use the [Chainlink OCR](/architecture-overview/off-chain-reporting) protocol to aggregate all the nodes' responses. Finally, a DON's oracle sends the aggregate response to the consumer contract in a callback. - Secrets endpoint: To transmit their secrets, users can encrypt them with the DON public key and then upload them to the secrets endpoint, a highly available service for securely sharing encrypted secrets with the nodes. **Note**: An alternative method involves self-hosting secrets. In this approach, users provide a publicly accessible HTTP(s) URL, allowing nodes to retrieve the encrypted secrets. Refer to the [secrets management](/chainlink-functions/resources/secrets) page for detailed information on both methods. - Serverless Environment: Every Oracle node accesses a distinct, sandboxed environment for computation. While the diagram illustrates an API request, the computation isn't restricted solely to this. You can perform any computation, from API calls to mathematical operations, using vanilla [Deno](https://deno.land/) code without module imports. Note: All nodes execute identical computations. If the target API has throttling limits, know that multiple simultaneous calls will occur since each DON node will independently run the request's source code. Let's walk through the sequence of interactions among these components, as illustrated in the diagram: 1. If there are secrets, a user encrypts secrets with the public key linked to the DON master secret key (MSK) and then uploads the encrypted secrets to the secrets endpoint. The secrets endpoint pushes the encrypted secrets to the nodes part of the DON (The secrets capability depicted in this diagram is called *threshold encryption* and is explained in [secrets management](/chainlink-functions/resources/secrets#threshold-encryption)). 2. An [EOA (Externally Owned Account)](https://ethereum.org/en/developers/docs/accounts/#types-of-account) or Chainlink Automation initiates the request by calling the consumer contract. 3. The consumer contract should inherit the [FunctionsClient](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/FunctionsClient.sol) contract. This ensures it will be able to receive responses from the [FunctionsRouter](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/FunctionsRouter.sol) contract via the `handleOracleFulfillment` callback. The router contract starts the billing to estimate the fulfillment costs and block the amount in the *reservation balance* (To learn more, read [Cost simulation](/chainlink-functions/resources/billing#cost-simulation-reservation)). Then it calls the [FunctionsCoordinator contract](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_1_0/FunctionsCoordinator.sol). 4. The coordinator contract emits an `OracleRequest` event containing information about the request. 5. On reception of the event by the DON, the DON's nodes decrypt the secrets using threshold decryption (The threshold encryption feature is explained in [secrets management](/chainlink-functions/resources/secrets#threshold-encryption)). Each DON's Oracle node executes the request's source code in a serverless environment. 6. The DON runs the Offchain Reporting protocol (OCR) to aggregate the values returned by each node's execution of the source code. 7. A DON's oracle node transmits the attested report (which includes the aggregated response) to the FunctionsCoordinator contract. 8. The FunctionsCoordinator contract calls the FunctionsRouter's `fulfill` method to calculate the fulfillment costs and finalize the billing (To learn more, read [Cost calculation](/chainlink-functions/resources/billing#cost-calculation-fulfillment)). 9. The FunctionsRouter contract calls the consumer contract's callback with the aggregated response. **Note**: Chainlink Functions requests are not limited to API requests. The diagram depicts an example of API requests, but you can request the DON to run any computation. ## Subscription management Chainlink Functions do not require your consumer contracts to hold LINK tokens and send them to oracles when making requests. Instead, you must create a subscription account and fund it to pay for your Chainlink Functions requests, so your consumer contracts don't need to hold LINK when calling Chainlink Functions. ### Concepts - Terms of service (ToS): Before interacting with Chainlink Functions, users must agree to the terms of service. Once signed, the accounts that can manage subscriptions are added to the `allowedSenders` in the [ToS allow list contract](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/accessControl/TermsOfServiceAllowList.sol). - Chainlink Functions Subscription Manager: A user interface that allows users to agree to the sign Terms of service and interact with the FunctionsRouter to manage subscriptions. - Subscription account: An account that holds LINK tokens and makes them available to fund requests to Chainlink DON. A *Subscription ID* uniquely identifies each account. - Subscription ID: 64-bit unsigned integer representing the unique identifier of the *Subscription account*. - Subscription owner: The wallet address that creates and manages a *Subscription account*. Any account can add LINK tokens to the subscription balance. Still, only the owner can add consumer contracts to the subscription, remove consumer contracts from the subscription, withdraw funds, or transfer a subscription. Only the subscription owner can generate encrypted secrets for requests that use their *Subscription ID*. - Subscription balance: The amount of LINK maintained on your *Subscription account*. Requests from consumer contracts are funded as long as sufficient funds are in the balance, so be sure to maintain sufficient funds in your *Subscription balance* to pay for the requests and keep your applications running. - Subscription reservation: The amount of LINK blocked on the *Subscription balance*. It corresponds to the total LINK amount to be paid by in-flight requests. - Effective balance: The amount of LINK available on your *Subscription account*. `Effective balance = Subscription balance - Subscription reservation`. - Subscription consumers: Consumer contracts are approved to use funding from your *Subscription account* while making Chainlink Functions requests. The consumers receive response data in a callback. ### Accept ToS To ensure compliance and governance, Chainlink Functions mandates that any account that manages a subscription must first accept the platform's Terms of Service (ToS). The acceptance is verified by cross-referencing the account with the `allowedSenders` registry contained within the [TermsOfServiceAllowList contract](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/accessControl/TermsOfServiceAllowList.sol). The acceptance process is initiated via the Chainlink Functions Subscription Manager. After a user accepts the ToS by generating the required signature with their externally owned account (EOA), they transmit proof of acceptance to the [TermsOfServiceAllowList contract](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/accessControl/TermsOfServiceAllowList.sol). Upon successful validation of the proof, the EOA is added to the `allowedSenders` registry, permitting it to manage subscriptions. ### Create subscription After the ToS is accepted, EOAs can create subscriptions. Upon creation, the [FunctionsRouter](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/FunctionsRouter.sol) assigns a unique identifier, *Subscription ID*. **Note**: EOAs can directly interact with the FunctionsRouter contract using their preferred web3 library, such as web3.js or ethers.js. ### Fund subscription You must fund your subscription accounts with enough LINK tokens: 1. Connect your EOA to the Chainlink Functions Subscription Manager. 2. Fund your subscription account. The Chainlink Functions Subscription Manager abstracts the following: 1. Call `transferAndCall` on the LINK token contract, transferring LINK tokens along with the *Subscription ID* in the payload. 2. The FunctionsRouter contract implements `onTokenTransfer`: It parses the *Subscription ID* from the payload and funds the subscription account with the transferred LINK amount. **Note**: EOAs can directly interact with the LinkToken contract using their preferred web3 library, such as web3.js or ethers.js. ### Add consumer You must allowlist your consumers' contracts on your subscription account before they can make Chainlink Functions requests: 1. Connect your EOA to the Chainlink Functions Subscription Manager. 2. Add the address of the consumer contract to the subscription account. 3. The Chainlink Functions Subscription Manager interacts with the FunctionsRouter contract to register the consumer contract address to the subscription account. **Note**: EOAs can directly interact with the FunctionsRouter contract using a web3 library, such as web3.js or ethers.js. ### Remove consumer To prevent further Chainlink Functions requests from a given consumer contract, you must remove it from your subscription account: 1. Connect your EOA to the Chainlink Functions Subscription Manager. 2. Remove the address of the consumer contract from the subscription account. 3. The Chainlink Functions Subscription Manager communicates with the FunctionsRouter contract to remove the consumer contract address from the subscription account. **Note**: You can still remove consumers from your subscription even if in-flight requests exist. The consumer contract will still receive a callback, and your *Subscription Account* will be charged. **Note**: EOAs can directly interact with the FunctionsRouter contract using a web3 library, such as web3.js or ethers.js. ### Cancel subscription To cancel a subscription: 1. Connect your EOA to the Chainlink Functions Subscription Manager. 2. Cancel your subscription, providing the *Subscription Balance* receiver account address. The Chainlink Functions Subscription Manager handles the following processes: 1. Invokes the `cancelSubscription` function on the FunctionsRouter contract, deleting the *Subscription ID* and removing all associated consumers. 2. Transfers the remaining *Subscription Balance* to the specified receiver account. **Note**: EOAs can directly interact with the FunctionsRouter contract using their preferred web3 library, such as web3.js or ethers.js. **Note**: Subscriptions cannot be canceled while there are in-flight requests. Furthermore, any expired requests (requests that have yet to receive a response within 5 minutes) must be timed out before cancellation. ### Transferring ownership of a Subscription Transferring ownership is currently only supported using the [Functions Hardhat Starter kit](https://github.com/smartcontractkit/functions-hardhat-starter-kit) or the [Functions Toolkit NPM package](https://github.com/smartcontractkit/functions-toolkit): 1. Use the `functions-sub-transfer` command to initiate the transfer of ownership by specifying the new owner's address. 2. As a prerequisite, the prospective owner must be part of the `allowedSenders` registry within the [TermsOfServiceAllowList contract](https://github.com/smartcontractkit/chainlink/blob/contracts-v1.3.0/contracts/src/v0.8/functions/v1_0_0/accessControl/TermsOfServiceAllowList.sol). This verifies their acceptance of the Chainlink Functions' Terms of Service (ToS). 3. The prospective owner should use the [Functions Hardhat Starter kit](https://github.com/smartcontractkit/functions-hardhat-starter-kit) and run the `functions-sub-accept` command to confirm the ownership transfer. **Note**: This guide will be updated as soon as the Chainlink Functions Subscription Manager supports ownership transfers. --- # Chainlink Functions Billing Source: https://docs.chain.link/chainlink-functions/resources/billing ## Request costs To send Chainlink Functions requests, you must maintain a sufficient amount of LINK in your subscription balance. Because Chainlink Functions follows the [Request and Receive Data](/chainlink-functions/resources/architecture) model, billing is done in two steps: 1. During the **request** step, the cost to fulfill a Chainlink Functions request is **estimated** and blocked on the subscription balance by adding it to the subscription reservation. 2. During the **receive** step, the exact fulfillment cost is **calculated**, then billed to the subscription account, and the subscription reservation is removed. You can break down total costs into the following components: - Gas cost: This cost is paid back to the transmitter oracle in LINK for fulfilling the request. - Premium fees: These fees are paid in LINK to compensate nodes for their work and for the maintenance of the FunctionsRouter contract. Gas cost calculation includes the following variables: - Gas price: The current gas price fluctuates depending on network conditions. - Overestimated gas price: refers to a deliberately higher gas price estimation to account for potential price fluctuations between the time a request is made and the time Chainlink Functions fulfills it. By setting the gas price higher than the current one, Chainlink Functions increases the likelihood that the request will be fulfilled, even if gas prices rise unexpectedly in the short term. The overestimation is calculated as a percentage increase over the current gas price. - Callback gas: The amount of gas used for the callback request. See the [Cost Calculation](#cost-calculation-fulfillment) section. - Callback gas limit: The maximum amount of gas that can be used to call the `handleOracleFulfillment` callback function of the consumer contract in order to provide the response. See the [Cost Simulation](#cost-simulation-reservation) section. - Gas overhead: The amount of gas used by the FunctionsRouter and FunctionsCoordinator contracts. It is an estimate of the total gas cost of fulfilling a request. - Native to LINK translation: Your subscription balance can be billed only in LINK tokens. - Translate the network's native gas tokens to LINK: The total gas cost in *native* units is translated using the correct [Price Feed](/data-feeds/price-feeds/addresses). For example, on Sepolia, the translation uses the ETH/LINK Price Feed, and on Polygon, the translation uses POL/LINK Price Feed. - Fallback Wei to LINK ratio: In the unlikely event that the *Native to LINK* price data feed is unavailable, the fallback translation is used. You can find this ratio by running the `getConfig` function in the FunctionsCoordinator contract. See the [Supported Networks](/chainlink-functions/supported-networks) page to find the contract addresses for each network. ### Cost simulation (reservation) During the **request** step: 1. The total cost in LINK is **estimated** using the following formula: ``` total estimated gas cost in LINK = (Overestimated gas price * (Gas overhead + Callback gas limit)) / Native to LINK translation total estimated cost in LINK = total estimated gas cost + premium fees ``` All networks have USD-denominated premium fees. This means that the fixed premium fee is denominated in USD, but no USD is ever used. The LINK equivalent of this fee is calculated at request time. 2. The total estimated cost is then added to the subscription reservation. ### Cost calculation (fulfillment) When a DON's oracle reports the response, subscription accounts are charged based on the gas amount used in the callback: 1. The total cost in LINK is **calculated** using the following formula: ``` total gas cost in LINK = (Gas price * (Gas overhead + Callback gas)) / Native to LINK translation total cost in LINK = total gas cost + premium fees ``` All networks have USD-denominated premium fees. This means that the fixed premium fee is denominated in USD, but no USD is ever used. The LINK equivalent of this fee is calculated at request time. 2. The FunctionsRouter contract performs several accounting movements. ### Cost calculation example This is an example of cost estimation for a request and then cost calculation at fulfillment. For networks with USD-denominated premium fees, the premium fees are set in USD, but no USD is ever used. The LINK equivalent of the fee is calculated at request time, and then deducted from your subscription in LINK at response time. #### Cost Simulation (Reservation) | Parameter | Value | | ----------------------- | ------------- | | Overestimated gas price | 9 gwei | | Callback gas limit | 300000 | | Gas overhead | 185000 | | Premium fee | 320 cents USD | 1. Calculate the total estimated gas cost in LINK, using an overestimated gas price, the gas overhead, and the full callback gas limit: | Gas cost calculation | Total estimated gas cost | | ------------------------------------------------------------- | --------------------------- | | Overestimated gas price x (Gas overhead + Callback gas limit) | | | 9 gwei x (300000 + 185000) | 4365000 gwei (0.004365 ETH) | 2. Convert the gas cost to LINK using the [LINK/ETH feed](https://data.chain.link/ethereum/mainnet/crypto-eth/link-eth). For this example, assume the feed returns a conversion value of Ξ0.007 ETH per 1 LINK. | ETH to LINK cost conversion | Total gas cost (LINK) | | ----------------------------- | --------------------- | | 0.004365 ETH / 0.007 ETH/LINK | 0.62 LINK | 3. Convert the USD-denominated premium fee to LINK using the [LINK/USD feed](https://data.chain.link/feeds/ethereum/mainnet/link-usd). For this example, assume the feed returns a conversion value of $20.00 USD per 1 LINK: | USD to LINK cost conversion | Premium fee (LINK) | | --------------------------- | ------------------ | | $3.20 USD / 20.00 USD/LINK | 0.16 LINK | 4. Add the converted premium fee to get the estimated cost for a subscription reservation: | Adding converted LINK premium | Maximum request cost (LINK) | | ----------------------------------- | --------------------------- | | Total gas cost (LINK) + Premium fee | | | 0.62 LINK + 0.16 LINK | 0.78 LINK | For this example request, 0.78 LINK is reserved from your subscription balance, but not yet deducted. When the request is fulfilled, the exact request cost is deducted. The estimated cost of a request is overestimated to allow for 99% of gas price fluctuation increases in between request and response time. #### Cost calculation (fulfillment) | Parameter | Value | | ----------------------------- | --------- | | Gas price | 1.5 gwei | | Callback gas | 200000 | | Gas overhead | 185000 | | Premium fee converted to LINK | 0.16 LINK | 1. Calculate the total gas cost: | Gas cost calculation | Total gas cost | | ----------------------------------------- | --------------------------- | | Gas price x (Gas overhead + Callback gas) | | | 1.5 gwei x (200000 + 185000) | 577500 gwei (0.0005775 ETH) | 2. Convert the gas cost to LINK using the [LINK/ETH feed](https://data.chain.link/ethereum/mainnet/crypto-eth/link-eth). For this example, assume the feed returns a conversion value of Ξ0.007 ETH per 1 LINK. | ETH to LINK cost conversion | Total gas cost (LINK) | | ------------------------------ | --------------------- | | 0.0005775 ETH / 0.007 ETH/LINK | 0.0825 LINK | 3. The premium fee was converted from USD to LINK at the time of the request. Add this converted premium fee to get the total cost of a request: | Adding premium fee | Total request cost (LINK) | | ----------------------------------- | ------------------------- | | Total gas cost (LINK) + premium fee | | | 0.0825 LINK + 0.16 LINK | 0.2425 LINK | This example request would cost 0.2425 LINK when it is fulfilled. The subscription reservation for the 0.78 LINK is released, and the actual cost of 0.2425 LINK is deducted from your subscription balance. ## Minimum balance for uploading encrypted secrets If you choose to store the encrypted secrets with the DON (learn more on the [Secrets Management page](/chainlink-functions/resources/secrets)), then one of your subscriptions must maintain a balance greater than the minimum required for uploading encrypted secrets. This balance is blockchain-specific. You can find the specific values for each blockchain on the [Supported Networks](/chainlink-functions/supported-networks) page. **Note**: Uploading encrypted secrets is free of charge. However, to prevent misuse of Chainlink Functions, you are required to maintain a minimum balance in one of the subscriptions owned by your externally-owned account (EOA) before you can upload encrypted secrets to a DON. ## Withdrawing funds To withdraw your LINK balance, you must first cancel your subscription. To prevent misuse of Chainlink Functions, any subscription with fulfilled requests below the *request threshold* will incur a cancellation fee. Both the request threshold and the cancellation fee are blockchain-specific. You can find their values for each blockchain on the [Supported Networks](/chainlink-functions/supported-networks) page. **Example 1**: - **Request Threshold**: Two requests - **Cancellation Fee**: 0.5 LINK - **Your Balance**: 0.4 LINK - **Number of Fulfilled Requests**: One - **Outcome**: Canceling your subscription results in a non-refundable balance **Example 2**: - **Request Threshold**: Two requests - **Cancellation Fee**: 0.5 LINK - **Your Balance**: 1 LINK - **Number of Fulfilled Requests**: One - **Outcome**: You will receive 0.5 LINK if you cancel your subscription **Example 3**: - **Request Threshold**: Two requests - **Cancellation Fee**: 0.5 LINK - **Your Balance**: 1 LINK - **Number of Fulfilled Requests**: Two or more - **Outcome**: You will receive 1 LINK if you cancel your subscription. Your subscription will not incur the cancellation fee --- # Chainlink Functions Resources Source: https://docs.chain.link/chainlink-functions/resources ## Topics - [Architecture](/chainlink-functions/resources/architecture) - [Managing Subscriptions](/chainlink-functions/resources/subscriptions) - [Billing](/chainlink-functions/resources/billing) - [Supported Networks](/chainlink-functions/supported-networks) - [Service Limits](/chainlink-functions/resources/service-limits) --- # Secrets Management Source: https://docs.chain.link/chainlink-functions/resources/secrets Chainlink Functions enables users to fetch data from HTTP(s) APIs and perform custom computation. To enable access to APIs that require authentication credentials, Chainlink Functions allows users to provide encrypted secret values, which can be used when the DON executes a Functions request. These values can only be decrypted via a multi-party decryption process called threshold decryption. This means that every node can only decrypt the secrets with participation from other DON nodes. These encrypted secret values can either be uploaded to the DON or hosted at a remote URL. Then, a reference to the encrypted secrets can be used when making a Functions request. ## Threshold encryption Using a single private key to decrypt user secrets poses a considerable security risk. If any node with this key becomes malicious or compromised, it can decrypt all accessible user secrets. To address this vulnerability, we have integrated a feature known as *threshold encryption*. The characteristics of this enhanced security measure include: 1. Decentralized Nodes Deployment: The system operates on a Decentralized Oracle Network (DON) with N nodes. 2. Master Secret Key Distribution: Instead of centralizing the private key, the master secret key (MSK) is partitioned into shares. Each node within the DON possesses a distinct share of this MSK. 3. The system enforces two thresholds: - Liveness: This feature ensures the system's availability and fault tolerance. It can tolerate up to F Byzantine nodes (nodes that can act arbitrarily or maliciously) while remaining operational. The system adheres to the mathematical relationship `3F+1≤N`. This means the total number of nodes N must be at least three times the number of faulty or malicious nodes F, plus one more. - Decryption security: Considering that the MSK is distributed across multiple nodes, safeguarding it is essential. To recover the master secret key (MSK), an attacker must corrupt a number of K nodes, adhering to the relationship: `F Contact us to increase the limits for your Chainlink Function. | Item | Description | Limits | | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | | Supported languages | Supported language of the Source code that is submitted in the Chainlink Functions request | JavaScript compatible with [Deno](https://deno.land/) runtime and module imports | | Maximum requests in flight | The maximum number of simultaneous Chainlink Functions requests that are not fulfilled yet by the DON | Limited by the [effective balance](/chainlink-functions/resources/architecture#subscription-management) | | Maximum callback gas limit | The maximum amount of gas that you can set for Chainlink Functions to fulfill your callback function | 300,000 | | Maximum subscriptions | Maximum subscriptions that you can create | unbounded | | Maximum consumer contracts per subscription | The maximum number of consumer contracts that you can add to a subscription | 100 | | Maximum duration of a request
(Request fulfillment timeout) | The maximum duration of a request is the time allowed for processing a Chainlink Functions request from start to finish, covering all steps such as reading from the chain, executing code, and posting back on chain. If processing takes longer, the request times out, and no charges are applied to your subscription for that request. In such cases, the initially locked estimated request costs must be manually requested to be returned to your subscription balance | 5 minutes | | Maximum request size | The maximum size of a Chainlink Request. This includes the source code, arguments, and secrets | 30 kilobytes | | Maximum returned value size | The maximum size of the value that your Function can return | 256 bytes | | Maximum source code execution time | The maximum amount of time that a source code can run | 10 seconds | | Maximum memory allocated to the source code | The maximum amount of memory allocated to your source code during execution | 128 megabytes | | HTTP - Maximum queries | The maximum number of HTTP requests that your source code can make | 5 | | HTTP - query timeout | The maximum duration of an HTTP request before it times out | 9 seconds | | HTTP - Maximum URL length | Length of the HTTP URL | 2048 characters | | HTTP - Maximum request length | The maximum size of an HTTP request, including the request body and HTTP headers | 30 kilobytes | | HTTP - Maximum response length | The maximum size of an HTTP response | 2 megabytes | | Max size of request payload CBOR | The maximum size of an encoded request | 30 kilobytes | | Don-hosted secrets - Maximum Time to live (TTL) | The maximum duration for which a secret hosted on a DON remains valid before it gets deleted |
  • Mainnets: 3 months (2160 hours)
  • Testnets: 3 days (72 hours)
| | External module imports - Maximum size | The maximum size in MB that each imported module can be | 10 MB | | External module imports - Number of imports | The maximum number of external module imports allowed in each request | 100 imports | --- # Simulate your Functions Source: https://docs.chain.link/chainlink-functions/resources/simulation Before making a Chainlink Functions request from your smart contract, it is always a good practice to simulate the source code off-chain to make any adjustments or corrections. Currently, there are several options for simulating a request: - [Chainlink Functions playground](https://functions.chain.link/playground). - [Chainlink Functions Hardhat Starter Kit](https://github.com/smartcontractkit/functions-hardhat-starter-kit): Use the `npx hardhat functions-simulate-script` command to simulate your Functions JavaScript source code. - [Chainlink Functions Toolkit NPM package](https://github.com/smartcontractkit/functions-toolkit): Import this NPM package into your JavaScript/TypeScript project, then use the `simulateScript` function to simulate your Functions JavaScript source code. ## Chainlink Functions playground To use the [Chainlink Functions Playground](https://functions.chain.link/playground), enter any source code, arguments, and secrets you would like to use. Click the **Run code** button to view the output. ## Chainlink Functions Hardhat Starter Kit This repository comes preconfigured with [Hardhat](https://hardhat.org/) and the [Chainlink Functions Toolkit NPM package](https://github.com/smartcontractkit/functions-toolkit), allowing you to quickly get started with Functions. To simulate: 1. In a terminal, clone the [functions-hardhat-starter-kit repository](https://github.com/smartcontractkit/functions-hardhat-starter-kit) and change to the `functions-hardhat-starter-kit` directory. ```shell git clone https://github.com/smartcontractkit/functions-hardhat-starter-kit && \ cd functions-hardhat-starter-kit ``` 2. Run `npm install` to install the dependencies. ```shell npm install ``` 3. For simulation, you don't need to set up the environment variables. Run `npx hardhat functions-simulate-script` to simulate the [calculation-example.js](https://github.com/smartcontractkit/functions-hardhat-starter-kit/blob/main/calculation-example.js) JavaScript source code. **Note:** This example calculates the continuously compounding interest for a given principal amount over one month. It takes the principal amount and annual percentage yield (APY) as input arguments and uses [Euler's number](https://www.investopedia.com/terms/e/eulers-constant.asp) to compute the total amount after interest. ```shell npx hardhat functions-simulate-script ``` Result: ```text secp256k1 unavailable, reverting to browser version Response returned by script during local simulation: 1003757 ``` ## Chainlink Functions Toolkit NPM package Follow the [Simple Computation](/chainlink-functions/tutorials/simple-computation) guide to learn how to import the [Chainlink Functions Toolkit NPM package](https://github.com/smartcontractkit/functions-toolkit) into your JavaScript project to simulate and execute a Functions request. You can read the [Examine the code section](/chainlink-functions/tutorials/simple-computation#javascript-example) for a detailed description of the code example. **Note**: You can also import and use the Chainlink Functions Toolkit NPM package as a scripting dependency inside [Remix IDE scripts](https://remix-ide.readthedocs.io/en/latest/running_js_scripts.html) in your browser. --- # Managing CL Functions Subscriptions Source: https://docs.chain.link/chainlink-functions/resources/subscriptions The Chainlink Functions Subscription Manager is available [here](https://functions.chain.link/). The Functions Subscription Manager lets you create a subscription, add consumers to it, remove consumers from it, fund it with LINK, and delete it. When you connect to the Subscription Manager, choose the correct network, then click *connect wallet*. ## Subscriptions You use a Chainlink Functions subscription to pay for, manage, and track Functions requests. ### Create a subscription 1. Open [functions.chain.link](https://functions.chain.link/) and click *Create Subscription*: 2. Provide an email address and an optional subscription name: 3. The first time that you interact with the Subscription Manager using your EOA, you have to approve the Terms of Service (ToS): 4. When you approve the ToS, a MetaMask popup appears that asks you to approve the subscription creation: 5. After the subscription is created, you are asked to sign a message in MetaMask to link the subscription name and email address to your subscription: {" "} 1. After the subscription is created, fund it with LINK: 2. After funding, you can add a consumer to it: 3. After creation, you can fetch the details of your subscription: ### Fund a subscription 1. Open your subscription details and click *Actions* then click *Fund subscription*: 2. Fund your subscription. For instance, *0.1 LINK*: 3. A MetaMask popup appears, and you are asked to confirm the transaction. After you confirm the transaction, a confirmation screen appears: ### Add a consumer contract to a subscription 1. Open your subscription details and click *Add Consumer*: 2. Fill in the consumer address: 3. A MetaMask popup appears, and you are asked to confirm the transaction. After you confirm the transaction, a confirmation screen appears: ### Remove a consumer contract from a subscription 1. Open your subscription details and click the consumer you want to remove, then *Remove Consumer*: 2. A MetaMask popup appears, and you are asked to confirm the transaction. 3. After you confirm the transaction, a confirmation screen appears: ### Cancel a subscription **Note**: You cannot cancel a subscription if there are in-flight requests. In-flight requests are requests that still need to be fulfilled. 1. Open your subscription details, click *Actions*, then *Cancel subscription*: 2. Fill in the receiver address of the remaining funds: 3. A MetaMask popup appears, and you are asked to confirm the transaction. 4. After you confirm the transaction, a confirmation screen appears: ## Time out pending requests manually The Subscription Manager provides the option to time out requests manually. You can time out requests that have been pending for longer than five minutes to unlock your subscription funds. 1. Open your subscription details and scroll to the **Pending** section. If a request has been pending longer than five minutes, its status displays as *Time out required*. Click the link within the red banner that says **Time out request**: If you have multiple requests that are eligible for timeout, the **Time out request** link in the red banner times out all the requests at once. Alternatively, you can time out an individual request. Open the **Actions** menu for that request, and click **Time out request**: {" "} 2. A MetaMask popup appears, and you are asked to confirm the transaction: 3. After you confirm the transaction, a confirmation screen appears: 4. The subscription details page displays another confirmation in the upper right corner showing that the request has been timed out successfully: 5. The timed out request appears in the **Failed fulfillments** tab of the **History** section: --- # Chainlink Functions Service Responsibility Source: https://docs.chain.link/chainlink-functions/service-responsibility Chainlink Functions provides access to trust-minimized compute infrastructure that allows you to retrieve data and run computation. Because the service is highly-flexible and runs offchain, both developers and Chainlink service providers share responsibility in ensuring that operation and performance match expectations. ## Developer responsibilities Developers who implement Chainlink Functions in their code and applications are responsible for several components. ### Data - **Data quality:** When using Chainlink Functions, developers are responsible for ensuring that any external data they retrieve meet the data quality requirements for their applications. This responsibility applies to data retrieved via APIs or other data retrieval mechanisms. You must ensure that the data sources you consume through Chainlink Functions are accurate, reliable, secure, and not at risk of manipulation by malicious actors. When possible, use multiple data sources to reduce single points of failure and manipulation risks. - **Data availability:** Developers must ensure that the data sources and APIs that they use with Chainlink Functions meet the fault-tolerance and availability requirements for their applications. Node operators are geographically distributed, so developers must ensure that APIs do not have geographic or other restrictions that would prohibit node operators from retrieving data. When possible, use redundant data sources to reduce the risk that your applications cannot execute due to unavailable data. In situations where data isn't available, ensure proper error handling. - **Data privacy and ethics:** Developers are responsible for determining what data they have a right to use with Chainlink Functions and ensuring that they use that data ethically. Developers must ensure that their Chainlink Functions code does not expose their private information or the private information of users without proper consent. Do not use data that you are not authorized to access. Your Chainlink Functions code and your application must ensure that private or sensitive information remains secure. ### Code - **Code quality and reliability:** Developers must execute code on Chainlink Functions only if the code meets the quality and reliability requirements for their use case and application. - **Code and application audits:** Developers are responsible for auditing their code and applications before deploying to production. You must determine the quality of any audits and ensure that they meet the requirements for your application and any code that runs on Chainlink Functions. - **Code dependencies and imports:** Developers are responsible for ensuring the quality, reliability, and security of any dependencies or imported packages that they use with Chainlink Functions. Review and audit these dependencies and packages. ### Secrets - **Self-hosted secrets**: Developers are responsible for securing self-hosted secrets, monitoring unauthorized access, auditing permissions, and ensuring that secrets are available for retrieval by Chainlink Functions when executing code. - **Secrets best practices**: For all types of secrets used with Chainlink Functions, developers must follow common best practices for managing secrets for applications. Developers are responsible for selecting, setting expiration time, monitoring, and rotating secrets to ensure the security of their applications and Chainlink Functions code. ### Subscriptions - **Subscription owner wallet management:** Developers must ensure the security of any wallets that own Chainlink Functions subscriptions or wallets that secure funds for subscriptions. - **Subscription balances:** Subscription owners are responsible for maintaining the Chainlink Function balance that is necessary to fund Chainlink Functions requests and computation. Monitor your subscription balance and implement the necessary processes to fund your subscription balance at a level that meets your application's requirements. ## Node Operator responsibilities High-quality node operators participate in the Functions DONs using a configuration specified in the Chainlink software. As participants in these deployments, Node Operators are responsible for the following components of Chainlink Functions: - Ensuring the proper configuration, maintenance, and monitoring of nodes participating in the Chainlink Functions DON. - Storing encrypted secrets that developers provide using threshold encryption. - Ensuring that transactions execute onchain in a timely manner and apply gas bumping when necessary. - Selecting and properly employing blockchain clients to connect to supported blockchain networks. - Maintaining continuous uptime and active participation in OCR consensus. - Employ defensive measures to prevent unauthorized access to their Chainlink node deployments. - Ensure that Chainlink node deployments are running the latest software versions. - Responding to important communication from Chainlink Labs or from other node operators in a timely manner. --- # Supported Networks Source: https://docs.chain.link/chainlink-functions/supported-networks {/* Static anchor points for link checker */}