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


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 offchain 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 by the user as [gists](https://docs.github.com/en/get-started/writing-on-github/editing-and-sharing-content-with-gists/creating-gists). Read the [Secrets Management page](/chainlink-functions/resources/secrets) to learn more.

Read the [Using Secrets in Requests](/chainlink-functions/tutorials/api-use-secrets) tutorial before you follow the steps in this example. This tutorial uses the same example but with a slightly different process:

1. Instead of uploading the encrypted secrets to the DON, you will host your encrypted secrets as gist.
2. Encrypt the gist URL.
3. Include the encrypted gist URL in your Chainlink Functions request.

> **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/6-use-secrets-gist* directory](https://github.com/smartcontractkit/smart-contract-examples/tree/main/functions-examples/examples/6-use-secrets-gist).

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

2. The [request.js](https://github.com/smartcontractkit/smart-contract-examples/blob/main/functions-examples/examples/6-use-secrets-gist/request.js) example stores encrypted secrets as [gists](https://docs.github.com/en/get-started/writing-on-github/editing-and-sharing-content-with-gists/creating-gists) to share them offchain with the Decentralized Oracle Network. To allow the `request.js` script to write gists on your behalf, create a [github fine-grained personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token#creating-a-fine-grained-personal-access-token).
   1. Visit [Github tokens settings page](https://github.com/settings/tokens?type=beta).
   2. Click on *Generate new token*.
   3. Provide a name to your token and define the expiration date.
   4. Under `Account permissions`, enable *Read and write* for Gists. **Note**: Do not enable additional settings.
   5. Click on *Generate token* and copy your fine-grained personal access token.

3. Run `npx env-enc set` to add an encrypted `GITHUB_API_TOKEN` and `COINMARKETCAP_API_KEY` to your `.env.enc` file.

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

To run the example:

1. Open the file `request.js`, which is located in the `6-use-secrets-gist` 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/6-use-secrets-gist/request.js
   ```

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

   ```text
   $ node examples/6-use-secrets-gist/request.js
   secp256k1 unavailable, reverting to browser version
   Start simulation...
   Simulation result {
   capturedTerminalOutput: 'Price: 66918.25 USD\n',
   responseBytesHexstring: '0x0000000000000000000000000000000000000000000000000000000000661bf1'
   }
   ✅ Decoded response to uint256:  6691825n

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

   Make request...
   Creating gist...

   ✅Gist created https://gist.github.com/thedriftofwords/f00db83b79df7e064253a3f396aee1f7/raw . Encrypt the URLs..

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

   ✅ Request 0x37f860fba46af84b84f5ce48efbb7c6ebbfb2ecde5063621f695bbd1c2547975 successfully fulfilled. Cost is 0.237283011969506455 LINK.Complete response:  {
   requestId: '0x37f860fba46af84b84f5ce48efbb7c6ebbfb2ecde5063621f695bbd1c2547975',
   subscriptionId: 2303,
   totalCostInJuels: 237283011969506455n,
   responseBytesHexstring: '0x0000000000000000000000000000000000000000000000000000000000661bf1',
   errorString: '',
   returnDataBytesHexstring: '0x',
   fulfillmentCode: 0
   }

   ✅ Decoded response to uint256:  6691825n
   Delete gistUrl https://gist.github.com/thedriftofwords/f00db83b79df7e064253a3f396aee1f7/raw

   ✅ Gist https://gist.github.com/thedriftofwords/f00db83b79df7e064253a3f396aee1f7/raw deleted
   ```

   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.

   - A gist `https://gist.github.com/thedriftofwords/f00db83b79df7e064253a3f396aee1f7/raw` containing the encrypted secrets was created .

   - The gist URL is encrypted before sending it in the request.

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

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

   - The consumer contract received a response in `bytes` with a value of `0x0000000000000000000000000000000000000000000000000000000000661bf1`. Decoding it offchain to `uint256` gives you a result: `6691825`.

   - After the request is fulfilled, the gist `https://gist.github.com/thedriftofwords/f00db83b79df7e064253a3f396aee1f7/raw` is deleted.

## Examine the code

### FunctionsConsumerExample.sol

### JavaScript example

#### source.js

The JavaScript code is similar to the [Using Secrets in Requests](/chainlink-functions/tutorials/api-use-secrets) tutorial.

#### request.js

This explanation focuses on the [request.js](https://github.com/smartcontractkit/smart-contract-examples/blob/main/functions-examples/examples/6-use-secrets-gist/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/6-use-secrets-gist/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 the Sepolia testnet.
   - `donId`: Identifier of the DON that will fulfill your requests on the Sepolia testnet.
   - `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.
   - `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 create a gist containing the encrypted secrets object. This is done in two steps:
   - Initialize a `SecretsManager` instance from the Functions NPM package, then call the `encryptSecrets` function.
   - Call the `createGist` utility function from the Functions NPM package to create a gist.
   - Call the `encryptedSecretsUrls` function of the `SecretsManager` instance. This function encrypts the gist URL. **Note**: The encrypted URL will be sent to the DON when making a request.

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).
   - Call the `deleteGist` utility function from the Functions NPM package to delete the gist.