FuelLabs/fuels-ts · error · FuelError
CONVERTING_FAILED
CONVERTING_FAILED
Error message
Cannot convert negative value to hex.
What it means
Thrown by BN.toHex() when the value is negative. Hex output in this SDK is intended for unsigned, fixed-size field encoding (e.g. U256), and a negative sign has no representation in that scheme, so the conversion is rejected.
Source
Thrown at packages/math/src/bn.ts:87
// ANCHOR: HELPERS
// make sure we always include `0x` in hex strings
override toString(base?: number | 'hex', length?: number) {
const output = super.toString(base, length);
if (base === 16 || base === 'hex') {
return `0x${output}`;
}
return output;
}
toHex(bytesPadding?: number): string {
const bytes = bytesPadding || 0;
const bytesLength = bytes * 2;
if (this.isNeg()) {
throw new FuelError(ErrorCode.CONVERTING_FAILED, 'Cannot convert negative value to hex.');
}
if (bytesPadding && this.byteLength() > bytesPadding) {
throw new FuelError(
ErrorCode.CONVERTING_FAILED,
`Provided value ${this} is too large. It should fit within ${bytesPadding} bytes.`
);
}
return this.toString(16, bytesLength);
}
toBytes(bytesPadding?: number): Uint8Array {
if (this.isNeg()) {
throw new FuelError(ErrorCode.CONVERTING_FAILED, 'Cannot convert negative value to bytes.');
}
return Uint8Array.from(this.toArray(undefined, bytesPadding));
}View on GitHub (pinned to b3f37c91ac)
Solutions
- Check `isNeg()` before toHex and decide how to handle it (clamp to 0, absolute value, or surface a domain error).
- Guard the upstream arithmetic so values fed into encoding are non-negative.
- Use `.abs()` if you genuinely want the magnitude.
Example fix
// before
const v = a.sub(b); // may be negative
const hex = v.toHex();
// after
if (v.isNeg()) {
throw new Error('result must be non-negative');
}
const hex = v.toHex(); Defensive patterns
Strategy: validation
Validate before calling
function safeToHex(v: import('@fuel-ts/math').BN, pad?: number): string {
if (v.isNeg()) throw new Error('cannot encode negative value to hex');
return v.toHex(pad);
} Type guard
const isNonNegative = (v: import('@fuel-ts/math').BN): boolean => !v.isNeg(); Prevention
- Check isNeg() before any toHex/toBytes call on computed values.
- Clamp balance arithmetic to zero on underflow where appropriate.
- Keep encoding paths unsigned by construction.
When it happens
Trigger: Calling `.toHex()` on a BN produced by subtraction that went below zero, or constructed from a negative literal like `bn(-5)`.
Common situations: Balance arithmetic underflow (subtracting more than available), signed computation leaking into an unsigned encoding path, unexpected negative result from `fromTwos`/two's-complement misuse.
Related errors
AI-assisted analysis of FuelLabs/fuels-ts@b3f37c91ac (2026-08-12).
Data as JSON: /api/errors/b1000a82e9e25c38.
Report an issue: GitHub.