To use the library in your project, you need to load WASM of TFHE first with initFhevm.
import { BrowserProvider } from"ethers";import { initFhevm, createInstance } from"fhevmjs";constcreateFhevmInstance=async () => {constprovider=newBrowserProvider(window.ethereum);constnetwork=awaitprovider.getNetwork();constchainId=+network.chainId.toString();constret=awaitprovider.call({// fhe lib address, may need to be changed depending on network to:"0x000000000000000000000000000000000000005d",// first four bytes of keccak256('fhePubKey(bytes1)') + 1 byte for library data:"0xd9d47bb001", });constdecoded=ethers.AbiCoder.defaultAbiCoder().decode(["bytes"], ret);constpublicKey= decoded[0];returncreateInstance({ chainId, publicKey });};constinit=async () => {awaitinitFhevm(); // Load TFHEreturncreateFhevmInstance();};init().then((instance) => {console.log(instance);});
Troubleshooting
Webpack: "Module not found: Error: Can't resolve 'tfhe_bg.wasm'"
In the codebase, there is a new URL('tfhe_bg.wasm') which triggers a resolve by Webpack. If yo u encounter an issue, you can add a fallback for this file by adding a resolve configuration in y our webpack.config.js:
With a bundler such as Webpack or Rollup, imports will be replaced with the version mentioned in the "browser" field of the package.json. If you encounter issue with typing, you can use this tsconfig.json using TypeScript 5.
If you encounter any other issue, you can force import of the browser package.
If you have an issue with bundling the library (for example with some SSR framework), you can use the prebundled version available in fhevmjs/bundle. Just embed the library with a <script> tag and you're good to go.