♈
Bootcamp-2024
  • Intro
  • 1. Blockchain & Wallet Fundamentals
    • Blockchain Introduction
    • State Machines
    • Cryptography
    • Distributed Networks
    • Game Theory
    • What is Web3
    • MetaMask Wallet Installation
    • Transferring Tokens with MetaMask
  • 2. Smart Contract & Solidity Fundamentals
    • Using Remix
    • Create, compile and publish your first smart contract
    • Interact with already published smart contracts
    • Blockchain Explorer
    • Verify source code on Etherscan
  • 3. Oracles, ERC20 & Chainlink Data Feeds
    • Oracles
    • Create & Deploy ERC20
    • Data Feeds
  • 4. Cross-Chain Tokens With Chainlink CCIP
    • Setting up MetaMask
    • Getting USDC Testnet Tokens
    • Create Smart Contract In Remix
    • Compile and Deploy
    • Approve USDC
    • Send LINK to your Contract
    • Send USDC from Fuji to Sepolia
    • USDC on Sepolia
  • 5. Mentoring Session
  • 6. NFTs & Chainlink Automation
    • NFT Basics
    • Dynamic NFTs
    • Creating an NFT Smart Contract
    • Deploying Your Dynamic NFTs
  • 7. Chainlink CCIP & Cross-Chain NFT dApps
    • Create and deploy CCIP NFT Contracts
    • Mint on Source Chain
    • Fund Contract
    • Mint On Sepolia From Fuji
    • Mint from Destination 2 - Base Sepolia
  • 8. Random Numbers with Chainlink VRF
    • Introduction to Chainlink VRF
    • Hands On Game Using VRF
  • 9. Off-Chain Data with Chainlink Functions
    • Chainlink Functions Playground
    • Setting up MetaMask
    • Remix
    • Functions Subscription
    • Creating The Functions Consumer Contract
    • Sending a Request from Remix
    • City Weather and Examples
    • City Weather on Chainlink Functions
  • 10. Connecting the 🌏 with Chainlink
  • Glossary
Powered by GitBook
On this page
  • Connect MetaMask to Remix
  • Creating your Smart Contract
  • Adding Code
  • Compile your Contract
  • Deploy your Smart Contract
  1. 9. Off-Chain Data with Chainlink Functions

Remix

Ethereum's Online IDE

PreviousSetting up MetaMaskNextFunctions Subscription

Last updated 1 year ago

Connect MetaMask to Remix

In Remix, Go to the "DEPLOY & RUN TRANSACTIONS" icon on left side:

In the “ENVIRONMENT” drop-down menu, select “Injected Provider - MetaMask”:

Make sure you are on Custom (43113) network, which is Avalanche Fuji Testnet:


Creating your Smart Contract

Create a smart contract called GettingStartedFunctionsConsumer.sol. First, go to the 1. “FILE EXPLORER” icon and then click the 2. “Create new file” icon:

Name the new Solidity file GettingStartedFunctionsConsumer.sol and a new tab will open in Remix:


Adding Code

Since contract we copied over was written for deployment on Sepolia, you will need to change configuration parameters like the address router and donID to the relevant addresses for Avalanche Fuji Testnet. Specifically:

Update the address router and donID by copying and pasting the following addresses into GettingStartedFunctionsConsumer.sol:

address router
0xA9d587a00A31A52Ed70D6026794a8FC5E2F5dCb0
donID
0x66756e2d6176616c616e6368652d66756a692d31000000000000000000000000
  1. Copy the full code below and paste into GettingStartedFunctionsConsumer.sol:

GettingStartedFunctionsConsumer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

// Deploy on Fuji

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

/**
 * Request testnet LINK and ETH here: https://faucets.chain.link/
 * Find information on LINK Token Contracts and get the latest ETH and LINK faucets here: https://docs.chain.link/resources/link-token-contracts/
 */

/**
 * @title GettingStartedFunctionsConsumer
 * @notice This is an example contract to show how to make HTTP requests using Chainlink
 * @dev This contract uses hardcoded values and should not be used in production.
 */
contract GettingStartedFunctionsConsumer is FunctionsClient, ConfirmedOwner {
    using FunctionsRequest for FunctionsRequest.Request;

    // State variables to store the last request ID, response, and error
    bytes32 public s_lastRequestId;
    bytes public s_lastResponse;
    bytes public s_lastError;

    // Custom error type
    error UnexpectedRequestID(bytes32 requestId);

    // Event to log responses
    event Response(
        bytes32 indexed requestId,
        string character,
        bytes response,
        bytes err
    );

    // Router address - Hardcoded for Fuji
    // Check to get the router address for your supported network https://docs.chain.link/chainlink-functions/supported-networks
    address router = 0xA9d587a00A31A52Ed70D6026794a8FC5E2F5dCb0;

    // JavaScript source code
    // Fetch character name from the Star Wars API.
    // Documentation: https://swapi.info/people
    string source =
        "const characterId = args[0];"
        "const apiResponse = await Functions.makeHttpRequest({"
        "url: `https://swapi.info/api/people/${characterId}/`"
        "});"
        "if (apiResponse.error) {"
        "throw Error('Request failed');"
        "}"
        "const { data } = apiResponse;"
        "return Functions.encodeString(data.name);";

    //Callback gas limit
    uint32 gasLimit = 300000;

    // donID - Hardcoded for Fuji
    // Check to get the donID for your supported network https://docs.chain.link/chainlink-functions/supported-networks
    bytes32 donID =
        0x66756e2d6176616c616e6368652d66756a692d31000000000000000000000000;

    // State variable to store the returned character information
    string public character;

    /**
     * @notice Initializes the contract with the Chainlink router address and sets the contract owner
     */
    constructor() FunctionsClient(router) ConfirmedOwner(msg.sender) {}

    /**
     * @notice Sends an HTTP request for character information
     * @param subscriptionId The ID for the Chainlink subscription
     * @param args The arguments to pass to the HTTP request
     * @return requestId The ID of the request
     */
    function sendRequest(
        uint64 subscriptionId,
        string[] calldata args
    ) external onlyOwner returns (bytes32 requestId) {
        FunctionsRequest.Request memory req;
        req.initializeRequestForInlineJavaScript(source); // Initialize the request with JS code
        if (args.length > 0) req.setArgs(args); // Set the arguments for the request

        // Send the request and store the request ID
        s_lastRequestId = _sendRequest(
            req.encodeCBOR(),
            subscriptionId,
            gasLimit,
            donID
        );

        return s_lastRequestId;
    }

    /**
     * @notice Callback function for fulfilling a request
     * @param requestId The ID of the request to fulfill
     * @param response The HTTP response data
     * @param err Any errors from the Functions request
     */
    function fulfillRequest(
        bytes32 requestId,
        bytes memory response,
        bytes memory err
    ) internal override {
        if (s_lastRequestId != requestId) {
            revert UnexpectedRequestID(requestId); // Check if request IDs match
        }
        // Update the contract's state variables with the response and any errors
        s_lastResponse = response;
        character = string(response);
        s_lastError = err;

        // Emit an event to log the response
        emit Response(requestId, character, s_lastResponse, s_lastError);
    }
}
```

Compile your Contract

You will need to compile your contract, so navigate to the 1. “SOLIDITY COMPILER” icon and then 2. click on the “Compile” button. You will see a green check when it has compiled successfully on the icon.


Deploy your Smart Contract

Time to deploy your contract, perform the following steps:

  1. Go to the "DEPLOY & RUN TRANSACTIONS" tab, and make sure you're connected to Fuji

  2. Click the "Deploy" button at the bottom

  3. MetaMask will pop-up and click the "Confirm" button

Upon a successful deployment, you will see your contract at the bottom the of "DEPLOY & RUN TRANSACTIONS" section:

In the next section, we will create a Chainlink Functions Subscription.

Go to and you will see a "Open in Remix" button, click that and Remix will open with the code loaded.

You can get these configuration details from . Always cross-check that for the correct configs!

Getting Started | Chainlink Documentation
Supported Networks | Chainlink Documentation
Remix - Ethereum IDE
Logo
DEPLOY & RUN TRANSACTIONS ICON
Select Injected Provider - MetaMask
Connected to (43113) - Avalanche Fuji Testnet
Create a new Solidity file
Blank Solidity file
GettingStartedFunctionsConsumer.sol
Successful compiled contract
Deployment
Successfully deployed your contract