0

I'm dealing with a problem regarding the decoding of data obtained from a Chainlink function in my Solidity code. Specifically, I'm using a Chainlink custom function that sends an HTTP GET request to my database. A sample URL looks like this:

http://178.79.181.117:80/api/collections/data/records/r2fmq2t2r2dakfi

The response to this request is a JSON string, such as:

{
    "collectionId": "zxl1za6gqm7lfg1",
    "collectionName": "data",
    "created": "2023-11-22 19:46:19.279Z",
    "id": "r2fmq2t2r2dakfi",
    "isActive": true,
    "jsonData": {
        "name": "Blaz",
        "lastName": "Peric",
        "phone": 68347930
    },
    "text": "a",
    "updated": "2023-11-22 19:46:19.279Z"
}

In my Solidity contract, I've defined a custom data type:

    struct Data {
      string text;
      bool isActive;
      string jsonData;
    }

Now, I have smart contract that is just copy of chainlink implementation of chainlinkFunctions. In the function fufilRequest I have bytes32 response I want to convert that response to my custom model.

Big note As you can see in my response I have JSON object inside JSON. I want to keep that as it is because I want to send that part to the other function that will do the same job.

Also, can you help me to write JS code for my function? When I try to run my code in the chainlink playground it does not work at all

This is my code

const apiResponse = await Functions.makeHttpRequest({
  url: 'http://178.79.181.117:80/api/collections/data/records/r2fmq2t2r2dakfi'
});
    
if (apiResponse.error) {
  console.error(apiResponse.error);
  throw Error('Request failed');
}

const { data } = apiResponse;


const result = {
  text: data.text,
  isSelected: data.isActive,
  jsonValue: data.jsonData
};

console.log('API response data:', JSON.stringify(result, null, 2));


return Functions.encodeString(JSON.stringify(result));

1 Answer 1

0

As per the docs currently whilst in beta only certain data types can be returned and they must be encoded into bytes before being sent on chain.

In general it is not advisable to try and send a JSON back (nested or otherwise) as it gets very complex when dealing with it in solidity and will not be gas efficient and may exceed gas limits.

Best step would be to design the app (and source.js) to return just specific pieces of data (specific values) that your smart contract needs.

Each item of data would need to be converted into bytes using a Uint8Array and if you have two or three items of data you need to concatenate those data items.

1
  • This was problem. Thank you very much Commented Nov 28, 2023 at 22:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.