# Using DON-hosted Secrets in Requests
Source: https://docs.chain.link/chainlink-functions/tutorials/api-use-secrets

> For the complete documentation index, see [llms.txt](/llms.txt).

This tutorial shows you how to send a request to a Decentralized Oracle Network to call the [Coinmarketcap API](https://coinmarketcap.com/api/documentation/v1/). After [OCR](/chainlink-functions/resources/architecture) completes offchain computation and aggregation, it returns the `BTC/USD` asset price to your smart contract. Because the API requires you to provide an API key, this guide will also show you how to encrypt, sign your API key, and share the encrypted secret with a Decentralized Oracle Network (DON).

The encrypted secrets are never stored onchain. This tutorial uses the threshold encryption feature. The encrypted secrets are stored with the DON. Read the [Secrets Management page](/chainlink-functions/resources/secrets) to learn more.

> **CAUTION**
>
> Chainlink Functions is still in BETA. The use of secrets in your requests is an experimental feature that may not
> operate as expected and is subject to change. Use of this feature is at your own risk and may result in unexpected
> errors, possible revealing of the secret as new versions are released, or other issues.

> **NOTE**
>
> Chainlink Functions is a self-service solution. You must ensure that the data sources or APIs specified in requests
> are of sufficient quality and have the proper availability for your use case. You are responsible for complying with
> the licensing agreements for all data providers that you connect with through Chainlink Functions. Violations of data
> provider licensing agreements or the [terms](https://chain.link/terms) can result in suspension or termination of your
> Chainlink Functions account.

## Tutorial

This tutorial is configured to get the `BTC/USD` price with a request that requires API keys. For a detailed explanation of the code example, read the [Examine the code](#examine-the-code) section.

You can locate the scripts used in this tutorial in the [*examples/5-use-secrets-threshold* directory](https://github.com/smartcontractkit/smart-contract-examples/tree/main/functions-examples/examples/5-use-secrets-threshold).

1. Get a free API key from [CoinMarketCap](https://coinmarketcap.com/api/) and note your API key.

2. Run `npx env-enc set` to add an encrypted `COINMARKETCAP_API_KEY` to your `.env.enc` file.

   ```shell
   npx env-enc set
   ```

3. Make sure your subscription has enough LINK to pay for your requests. Also, you must maintain a minimum balance to upload encrypted secrets to the DON (Read the [minimum balance for uploading encrypted secrets section](/chainlink-functions/resources/billing#minimum-balance-for-uploading-encrypted-secrets) to learn more). You can check your subscription details (including the balance in LINK) in the [Chainlink Functions Subscription Manager](/chainlink-functions/resources/subscriptions). If your subscription runs out of LINK, follow the [Fund a Subscription](/chainlink-functions/resources/subscriptions#fund-a-subscription) guide. This guide recommends maintaining at least 2 LINK within your subscription.

To run the example:

1. Open the file `request.js`, which is located in the `5-use-secrets-threshold` folder.

2. Replace the consumer contract address and the subscription ID with your own values.

   ```javascript
   const consumerAddress = "0x8dFf78B7EE3128D00E90611FBeD20A71397064D9" // REPLACE this with your Functions consumer address
   const subscriptionId = 3 // REPLACE this with your subscription ID
   ```

3. Make a request:

   ```shell
   node examples/5-use-secrets-threshold/request.js
   ```

   The script runs your function in a sandbox environment before making an onchain transaction:

   ```text
   $ node examples/5-use-secrets-threshold/request.js
   secp256k1 unavailable, reverting to browser version
   Start simulation...
   Simulation result {
     capturedTerminalOutput: 'Price: 66757.65 USD\n',
     responseBytesHexstring: '0x000000000000000000000000000000000000000000000000000000000065dd35'
   }
   ✅ Decoded response to uint256:  6675765n

   Estimate request costs...
   Fulfillment cost estimated to 1.104471544715335 LINK

   Make request...
   Upload encrypted secret to gateways https://01.functions-gateway.testnet.chain.link/,https://02.functions-gateway.testnet.chain.link/. slotId 0. Expiration in minutes: 15

   ✅ Secrets uploaded properly to gateways https://01.functions-gateway.testnet.chain.link/,https://02.functions-gateway.testnet.chain.link/! Gateways response:  { version: 1712949090, success: true }

   ✅ Functions request sent! Transaction hash 0xcac39aeea98651f307da185aed387314c453272d185e58b26b3bb399b82a90b6. Waiting for a response...
   See your request in the explorer https://sepolia.etherscan.io/tx/0xcac39aeea98651f307da185aed387314c453272d185e58b26b3bb399b82a90b6

   ✅ Request 0xbc09de04f4dd39fa78d4b00b7ab4d2f4a37d8b9a8edf97df5c86061175b9d9c3 successfully fulfilled. Cost is 0.23730142355580769 LINK.Complete response:  {
     requestId: '0xbc09de04f4dd39fa78d4b00b7ab4d2f4a37d8b9a8edf97df5c86061175b9d9c3',
     subscriptionId: 2303,
     totalCostInJuels: 237301423555807690n,
     responseBytesHexstring: '0x000000000000000000000000000000000000000000000000000000000065dc31',
     errorString: '',
     returnDataBytesHexstring: '0x',
     fulfillmentCode: 0
   }

   ✅ Decoded response to uint256:  6675505n
   ```

   The output of the example gives you the following information:

   - Your request is first run on a sandbox environment to ensure it is correctly configured.

   - The fulfillment costs are estimated before making the request.

   - The encrypted secrets were uploaded to the secrets endpoint `https://01.functions-gateway.testnet.chain.link/user`.

   - Your request was successfully sent to Chainlink Functions. The transaction in this example is [0xcac39aeea98651f307da185aed387314c453272d185e58b26b3bb399b82a90b6](https://sepolia.etherscan.io/tx/0xcac39aeea98651f307da185aed387314c453272d185e58b26b3bb399b82a90b6) and the request ID is `0xbc09de04f4dd39fa78d4b00b7ab4d2f4a37d8b9a8edf97df5c86061175b9d9c3`.

   - The DON successfully fulfilled your request. The total cost was: `0.23730142355580769 LINK`.

   - The consumer contract received a response in `bytes` with a value of `0x000000000000000000000000000000000000000000000000000000000065dc31`. Decoding it offchain to `uint256` gives you a result: `6675505`. The median BTC price is 66755.05 USD.

## Examine the code

### FunctionsConsumerExample.sol

### JavaScript example

#### source.js

The Decentralized Oracle Network will run the [JavaScript code](https://github.com/smartcontractkit/smart-contract-examples/blob/main/functions-examples/examples/5-use-secrets-threshold/source.js). The code is self-explanatory and has comments to help you understand all the steps.

This JavaScript source code uses [Functions.makeHttpRequest](/chainlink-functions/api-reference/javascript-source#http-requests) to make HTTP requests. To request the `BTC` asset price, the source code calls the `https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest/` URL. If you read the [Functions.makeHttpRequest](/chainlink-functions/api-reference/javascript-source#http-requests) documentation, you see that you must provide the following parameters:

- `url`: `https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest`
- `headers`: This is an HTTP headers object set to `"X-CMC_PRO_API_KEY": secrets.apiKey`. The `apiKey` is passed in the secrets, see [request](#requestjs).
- `params`: The query parameters object:

  ```
  {
    convert: currencyCode,
    id: coinMarketCapCoinId
  }
  ```

To check the expected API response, run the `curl` command in your terminal:

```bash
curl -X 'GET' \
  'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?id=1&convert=USD' \
  -H 'accept: application/json' \
  -H 'X-CMC_PRO_API_KEY: REPLACE_WITH_YOUR_API_KEY'
```

The response should be similar to the following example:

```json
{
  ...,
  "data": {
    "1": {
      "id": 1,
      "name": "Bitcoin",
      "symbol": "BTC",
      "slug": "bitcoin",
      ...,
      "quote": {
        "USD": {
          "price": 23036.068560170934,
          "volume_24h": 33185308895.694683,
          "volume_change_24h": 24.8581,
          "percent_change_1h": 0.07027098,
          "percent_change_24h": 1.79073805,
          "percent_change_7d": 10.29859656,
          "percent_change_30d": 38.10735851,
          "percent_change_60d": 39.26624921,
          "percent_change_90d": 11.59835416,
          "market_cap": 443982488416.99316,
          "market_cap_dominance": 42.385,
          "fully_diluted_market_cap": 483757439763.59,
          "tvl": null,
          "last_updated": "2023-01-26T18:27:00.000Z"
        }
      }
    }
  }
}
```

The price is located at `data,1,quote,USD,price`.

The main steps of the scripts are:

- Fetch the `currencyCode` and `coinMarketCapCoinId` from `args`.
- Construct the HTTP object `coinMarketCapRequest` using `Functions.makeHttpRequest`.
- Make the HTTP call.
- Read the asset price from the response.
- Return the result as a [buffer](https://nodejs.org/api/buffer.html#buffer) using the helper function: `Functions.encodeUint256`. Note: Because solidity doesn't support decimals, we multiply the result by `100` and round the result to the nearest integer. **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.

#### request.js

This explanation focuses on the [request.js](https://github.com/smartcontractkit/smart-contract-examples/blob/main/functions-examples/examples/5-use-secrets-threshold/request.js) script and shows how to use the [Chainlink Functions NPM package](https://github.com/smartcontractkit/functions-toolkit) in your own JavaScript/TypeScript project to send requests to a DON. The code is self-explanatory and has comments to help you understand all the steps.

The script imports:

- [path](https://nodejs.org/docs/latest/api/path.html) and [fs](https://nodejs.org/api/fs.html) : Used to read the [source file](https://github.com/smartcontractkit/smart-contract-examples/blob/main/functions-examples/examples/5-use-secrets-threshold/source.js).
- [ethers](https://docs.ethers.org/v5/): Ethers.js library, enables the script to interact with the blockchain.
- `@chainlink/functions-toolkit`: Chainlink Functions NPM package. All its utilities are documented in the [NPM README](https://github.com/smartcontractkit/functions-toolkit/blob/main/README.md).
- `@chainlink/env-enc`: A tool for loading and storing encrypted environment variables. Read the [official documentation](https://www.npmjs.com/package/@chainlink/env-enc) to learn more.
- `../abi/functionsClient.json`: The abi of the contract your script will interact with. **Note**: The script was tested with this [FunctionsConsumerExample contract](https://remix.ethereum.org/#url=https://docs.chain.link/samples/ChainlinkFunctions/FunctionsConsumerExample.sol).

The script has two hardcoded values that you have to change using your own Functions consumer contract and subscription ID:

```javascript
const consumerAddress = "0x8dFf78B7EE3128D00E90611FBeD20A71397064D9" // REPLACE this with your Functions consumer address
const subscriptionId = 3 // REPLACE this with your subscription ID
```

The primary function that the script executes is `makeRequestSepolia`. This function can be broken into six main parts:

1. Definition of necessary identifiers:
   - `routerAddress`: Chainlink Functions router address on Sepolia.
   - `donId`: Identifier of the DON that will fulfill your requests on Sepolia.
   - `gatewayUrls`: The secrets endpoint URL to which you will upload the encrypted secrets.
   - `explorerUrl`: Block explorer URL of the Sepolia testnet.
   - `source`: The source code must be a string object. That's why we use `fs.readFileSync` to read `source.js` and then call `toString()` to get the content as a `string` object.
   - `args`: During the execution of your function, These arguments are passed to the source code. The `args` value is `["1", "USD"]`, which fetches the BTC/USD price.
   - `secrets`: The secrets object that will be encrypted.
   - `slotIdNumber`: Slot ID at the DON where to upload the encrypted secrets.
   - `expirationTimeMinutes`: Expiration time in minutes of the encrypted secrets.
   - `gasLimit`: Maximum gas that Chainlink Functions can use when transmitting the response to your contract.
   - Initialization of ethers `signer` and `provider` objects. The signer is used to make transactions on the blockchain, and the provider reads data from the blockchain.

2. Simulating your request in a local sandbox environment:
   - Use `simulateScript` from the Chainlink Functions NPM package.
   - Read the `response` of the simulation. If successful, use the Functions NPM package `decodeResult` function and `ReturnType` enum to decode the response to the expected returned type (`ReturnType.uint256` in this example).

3. Estimating the costs:
   - Initialize a `SubscriptionManager` from the Functions NPM package, then call the `estimateFunctionsRequestCost` function.
   - The response is returned in Juels (1 LINK = 10\*\*18 Juels). Use the `ethers.utils.formatEther` utility function to convert the output to LINK.

4. Encrypt the secrets, then upload the encrypted secrets to the DON. This is done in two steps:
   - Initialize a `SecretsManager` instance from the Functions NPM package, then call the `encryptSecrets` function.
   - Call the `uploadEncryptedSecretsToDON` function of the `SecretsManager` instance. This function returns an object containing a `success` boolean as long as `version`, the secret version on the DON storage. **Note**: When making the request, you must pass the slot ID and version to tell the DON where to fetch the encrypted secrets.

5. Making a Chainlink Functions request:
   - Initialize your functions consumer contract using the contract address, abi, and ethers signer.
   - Call the `sendRequest` function of your consumer contract.

6. Waiting for the response:
   - Initialize a `ResponseListener` from the Functions NPM package and then call the `listenForResponseFromTransaction` function to wait for a response. By default, this function waits for five minutes.
   - Upon reception of the response, use the Functions NPM package `decodeResult` function and `ReturnType` enum to decode the response to the expected returned type (`ReturnType.uint256` in this example).