I am working on a blockhain game, using Chainlink Automation && Functions to manage game logic and API interactions.
The game itself deployed on “Vercel” as a client side, and server deployed to “Replit”.
The game contract uses Chainlink’s Keeper to regularly check the state of the game and call an external API to determine the winner once two players are active in a game. The expected behavior is for the Keeper to initiate a request via Chainlink Functions every minute if the game is active and not yet decided.
Problem:
Despite the setup, Keeper functions do not trigger the performUpkeep method following the checkUpkeep indication that upkeep is needed. This is perplexing because manual simulation of the API request through a JS script works flawlessly, indicating that the API and network configurations are correct.
CL Automation code snippets:
function checkUpkeep(bytes calldata checkData) external view override returns (bool upkeepNeeded, bytes memory performData) {
uint256 gameId = abi.decode(checkData, (uint256));
Game storage game = games[gameId];
upkeepNeeded = game.isActive && game.player2 != address(0) && !game.winnerDetermined && (block.timestamp - game.lastCheckedTime > 1 minutes);
performData = abi.encode(gameId);
}
function performUpkeep(bytes calldata performData) external override {
uint256 gameId = abi.decode(performData, (uint256));
Game storage game = games[gameId];
if (game.isActive && !game.winnerDetermined) {
requestGameResult(gameId);
game.lastCheckedTime = block.timestamp;
}
}
function requestGameResult(uint256 gameId) internal {
FunctionsRequest.Request memory req;
req.initializeRequestForInlineJavaScript(
string.concat(
"const gameId = args[0];",
"const response = await Functions.makeHttpRequest({",
" url: `https://tictactoe-server.replit.app/game/${gameId}/winner`",
"});",
"if (response.error) {",
" console.error(response.error);",
" throw new Error('Request failed');",
"}",
"const { data } = response;",
"console.log('API response data:', JSON.stringify(data, null, 2));",
"return Functions.encodeString(data.winner);"
)
);
string[] memory args = new string[](1);
args[0] = uint2str(gameId);
req.setArgs(args);
_sendRequest(
req.encodeCBOR(),
subscriptionId,
gasLimit,
donID
);
emit GameResultRequested(gameId);
}
function fulfillRequest(bytes32 requestId, bytes memory response, bytes memory) internal override {
(uint256 gameId, address winner) = abi.decode(response, (uint256, address));
_endGame(gameId, winner);
emit GameResultFulfilled(requestId, gameId, winner);
}
Simulation code snippets:
// simulate-script.js
const { simulateScript, Location, ReturnType, CodeLanguage, decodeResult } = require("@chainlink/functions-toolkit");
const fs = require("fs");
async function main() {
const gameId = process.argv[2];
const { responseBytesHexstring, capturedTerminalOutput, errorString } = await simulateScript({
source: fs.readFileSync("./example.js").toString(),
codeLocation: Location.Inline,
secrets: { secretKey: process.env.SECRET_KEY ?? "" },
secretsLocation: Location.DONHosted,
args: [gameId],
codeLanguage: CodeLanguage.JavaScript,
expectedReturnType: ReturnType.string,
});
console.log("Response Bytes Hex String:", responseBytesHexstring);
console.log("Error String:", errorString);
console.log("Captured Terminal Output:", capturedTerminalOutput);
if (responseBytesHexstring) {
console.log("Decoded Result: ", decodeResult(responseBytesHexstring, ReturnType.string));
} else {
console.log("No response to decode.");
}
}
main();
...
// example.js
const gameId = args[0]
const response = await Functions.makeHttpRequest({
url: `https://tictactoe-server.replit.app/game/${gameId}/winner`
})
if (response.error) {
console.error(response.error)
throw new Error("Request failed")
}
const { data } = response;
console.log('API response data:', JSON.stringify(data, null, 2));
return Functions.encodeString(data.winner)
ruffbuff node simulate-script.js 0
secp256k1 unavailable, reverting to browser version
Response Bytes Hex String: 0x307863646635623165643866643562383964653938633332353835343333316165346234653939366536
Error String: undefined
Captured Terminal Output: API response data: {
"winner": "0xcdf5b1ed8fd5b89de98c325854331ae4b4e996e6"
}
Decoded Result: 0xcdf5b1ed8fd5b89de98c325854331ae4b4e996e6
1