Chainlink – How to Return an Array or List of Strings from Functions-request-source.js

byteschainlinkfunctionstring

Hope someone can help.
I am stuck trying to work out how best to extract the different string values from the returned bytes data.
Chainlink Function request source requires the return value to be a buffer so I am including all the values required as per an example I found below from https://www.usechainlinkfunctions.com/ :

// Encode and return the distance (in meters), standard duration (in seconds), and duration in traffic (in seconds) as a string which can be parsed and split
return Functions.encodeString(`${distance},${stdDuration},${duration_in_traffic}`)

I am stuck trying to split the return values in the fulfillRequest function in the FunctionsConsumer contract. Below is the standard function before implementing anything to split out a number of string variables from the response:

function fulfillRequest(
    bytes32 requestId,
    bytes memory response,
    bytes memory err
) internal override {
    latestResponse = response;
    latestError = err;
    emit OCRResponse(requestId, response, err);
}

Here is the github repo link for chainlink functions:
https://github.com/smartcontractkit/functions-hardhat-starter-kit/tree/main#functions-library

Any help is greatly appreciated. Thank you.

Best Answer

since you're returning a string, parsing that string and splitting it would be very expensive. Instead you could return with a buffer.concat to concat your distance, std duration and duration in traffice as uint256 values (assuming they can ONLY be positive integers) and int256 if they can be negative.

Chainlink Functions code with Buffer.Concat example

Then in your Functions Consumer Smart Contract you use abi.decode with the exact int types. See this code example from the same repo

This way you get individual values and dont have to split them on chain.

Hope this helps!

Related Topic