Ethers.js Number Conversion – How to Convert Number to Bytes in Ethers.js?

bytes32ethers.jshardhatuint256

I have a number in javascript:

const oracleResponse = 1

And I have a function that takes a bytes32 as input parameters

function fulfillOracleRequest(
    bytes32 _requestId,
    bytes32 _data
  )

I want to convert oracleResponse in javascript to its bytes edition so that I can call this function. How do I do this?

*Note: const oracleResponse = ethers.utils.hexlify(1) will not work, since this will return 0x1 which is the incorrect length.

Best Answer

ethers also has a padding function where it will add the zeros to make it the correct length. It looks like this

const oracleResponse = ethers.utils.hexZeroPad(ethers.utils.hexlify(1), 32)

This will pad your result to be length 32, and allow it to be accepted by your function.