javascriptchainlink

How to use raw Buffer in Chainlink Functions?


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.


Solution

  • 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)