Buffer is not defined (fromHex function)

Hi,
I’m trying to make this code work, to fetch the ICP balance from a principal:

import { createAgent } from "@dfinity/utils";
import { LedgerCanister, AccountIdentifier } from "@dfinity/ledger-icp";
import { Principal } from '@dfinity/principal';

...

const agent = await createAgent({
  identity,
  //host: HOST,
});
  
const { accountBalance } = LedgerCanister.create({
  agent,
  canisterId: process.env.CANISTER_ID_ICP_LEDGER_CANISTER,
});

const accountIdentifier = AccountIdentifier.fromPrincipal({
  principal: Principal.fromText(principal),
  //subAccount: principalSubaccount
});
  
let balance = await accountBalance(accountIdentifier);
console.log(balance);

as mentioned here.

I’ve debugged everything until the accountIdentifier (I know that it is correct); However, now I get the following error from the accountBalance method:

Buffer is not defined

That appears to come from the @dfinity/ledger-icp library (this line), so I have no idea how do debug further.

Any idea?
Thanks!

Hey, try to install these packages from NPM.
if after installation still does not work, lemme know

“buffer”: “^6.0.3”,
“buffer-crc32”: “^0.2.13”,
“crypto-js”: “^4.1.1”

1 Like

You actually probably just need buffer and depending of your framework, need to polyfill it accordingly.

For example in SvelteKit I do this for production: https://github.com/dfinity/oisy-wallet/blob/1ec8138c1098d2e754eb559a1a29606cd0334971/src/frontend/src/routes/%2Blayout.ts#L5

There are also plugins for most common bundlers that polyfill nodejs dependencies (but they do not always work in my experience).

Note that the ultimate goal for agent-js and ic-js, I think, is to get rid of this requirement which solve both the polyfill pain and will reduce properly the bundle size.

2 Likes