Skip to content

Instantly share code, notes, and snippets.

@pappas999
Last active October 20, 2023 12:38
Show Gist options
  • Save pappas999/f5d335329b23db3f4e53431282344deb to your computer and use it in GitHub Desktop.
Save pappas999/f5d335329b23db3f4e53431282344deb to your computer and use it in GitHub Desktop.
Functions Remix Example
pragma solidity 0.8.19;
import {FunctionsClient} from "@chainlink/contracts/src/v0.8/functions/dev/v1_0_0/FunctionsClient.sol";
import {ConfirmedOwner} from "@chainlink/contracts/src/v0.8/shared/access/ConfirmedOwner.sol";
import {FunctionsRequest} from "@chainlink/contracts/src/v0.8/functions/dev/v1_0_0/libraries/FunctionsRequest.sol";
contract FunctionsConsumerExample is FunctionsClient, ConfirmedOwner {
using FunctionsRequest for FunctionsRequest.Request;
bytes32 public s_lastRequestId;
bytes public s_lastResponse;
bytes public s_lastError;
error UnexpectedRequestID(bytes32 requestId);
event Response(bytes32 indexed requestId, bytes response, bytes err);
// CUSTOM PARAMS - START
//Fuji Router address;
address router = 0xA9d587a00A31A52Ed70D6026794a8FC5E2F5dCb0;
//JavaScript to run
string source = "const characterId = args[0]; const apiResponse = await Functions.makeHttpRequest({ url: `https://swapi.dev/api/people/${characterId}/` }); if (apiResponse.error) { console.error(apiResponse.error); throw Error('Request failed'); } const { data } = apiResponse; console.log('API response data:', JSON.stringify(data, null, 2)); return Functions.encodeString(data.name);";
//Functions Subscription ID
uint64 subscriptionId = 66;
//Gas limit for callback tx do not change
uint32 gasLimit = 300000;
//DoN ID for Fuji, from supported networks in the docs
bytes32 jobId = 0x66756e2d6176616c616e6368652d66756a692d31000000000000000000000000;
//String to store result in
string public character;
// CUSTOM PARAMS - END
constructor() FunctionsClient(router) ConfirmedOwner(msg.sender) {}
function sendRequest() external onlyOwner returns (bytes32 requestId) {
// add parameters to the args array here, before we make the request
string[] memory args = new string[](1);
args[0] = "1";
FunctionsRequest.Request memory req;
req.initializeRequestForInlineJavaScript(source);
if (args.length > 0) req.setArgs(args);
s_lastRequestId = _sendRequest(
req.encodeCBOR(),
subscriptionId,
gasLimit,
jobId
);
return s_lastRequestId;
}
function fulfillRequest(
bytes32 requestId,
bytes memory response,
bytes memory err
) internal override {
if (s_lastRequestId != requestId) {
revert UnexpectedRequestID(requestId);
}
s_lastResponse = response;
character = string(response);
s_lastError = err;
emit Response(requestId, s_lastResponse, s_lastError);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment