How to use raw Buffer in Chainlink Functions?

137 Views Asked by At

Chainlink Functions currently offer some encoding functions for string, uint256 and int256, but it actually makes sense to send bytes to solidity in scenarios where for example you need to send multiple parameters or information so you can send it abi encoded.

Functions always need to return a Buffer, so if the provided encoders are not used you need to create your own buffer. For doing that in JS Buffer.from can be used, which works perfectly in Chainlink Functions Playground but it fails in practice when the function is used.

For my specific use case I want to do:

return Buffer.from(hexstring, 'hex');

where hexstring is my abi encoded data I want to send to the contract.

The error I got is:

TypeError: Cannot read properties of undefined (reading 'from')

I have also tried the old form of using Buffer like

return new Buffer(hexstring, 'hex');

which also works in the playground, but the error this time was that Buffer is not a constructor.

Given that it simply seems to not be imported one idea will be to just add a require in the Function but requires are not allowed, so it is not the way to go.

3

There are 3 best solutions below

3
On BEST ANSWER

If you're not using one of the encoding tools provided, Chainlink Functions request source code must return a Uint8Array, which represents the bytes that are returned on-chain. You should not need to use the Deno buffer library for this, as Deno natively supports Uint8Arrays without any imports.

As an example, try:

const myArr =  new Uint8Array(ARRAY_LENGTH)
3
On

Looks like Deno doesn't support Buffer.from. It has Buffer, but it doesn't line up with Node it seems.

Here are the docs: https://deno.land/[email protected]?s=Deno.Buffer

Also it's deprecated so maybe you could use a different API and have more luck with it.

0
On

You can try to import Buffer this way:

const { Buffer } = await import("node:buffer")

for istance:

// this is to test how we can call our api, making a call to the healthcheck
const { Buffer } = await import("node:buffer")
// make HTTP request
const url = `https://8c21-93-67-103-124.ngrok-free.app/parse-robots-txt?url=https://www.google.com`; // Update with an ngrock
console.log(`HTTP GET Request to ${url}`);

// construct the HTTP Request object. See: https://github.com/smartcontractkit/functions-hardhat-starter-kit#javascript-code

const request = Functions.makeHttpRequest({
  url: url,
});
// Execute the API request (Promise)
const response = await request;

if (response.error) {
  console.error(response.error);
  throw Error("Request failed");
}

return Buffer.from(response.data, "hex")

I suggest to try out using examples here

source: https://docs.deno.com/runtime/manual/node/compatibility