diff --git a/.changeset/eight-birds-trade.md b/.changeset/eight-birds-trade.md new file mode 100644 index 00000000000..2e5403ed5b4 --- /dev/null +++ b/.changeset/eight-birds-trade.md @@ -0,0 +1,5 @@ +--- +"@fuel-ts/abi-coder": minor +--- + +ABI coder will throw when encoding a string with a value legnth mismatch diff --git a/packages/abi-coder/src/coders/string.test.ts b/packages/abi-coder/src/coders/string.test.ts index 71628f976f8..c2e09159263 100644 --- a/packages/abi-coder/src/coders/string.test.ts +++ b/packages/abi-coder/src/coders/string.test.ts @@ -44,21 +44,22 @@ describe('StringCoder', () => { expect(actualLength).toBe(expectedLength); }); - it('should not completely encode a string that is too big for the coder', () => { - const coderLength = 0; - const coder = new StringCoder(coderLength); + it('should throw when encoding a string that is too big', () => { + const coder = new StringCoder(0); const invalidInput = STRING_MAX_DECODED; - const actual = coder.encode(invalidInput); - expect(actual).not.toStrictEqual(STRING_MAX_ENCODED); + expect(() => { + coder.encode(invalidInput); + }).toThrow(); }); - it('should not completely encode a string that is too small for the coder', () => { + it('should throw when encoding a string that is too small', () => { const coder = new StringCoder(1); const invalidInput = STRING_MIN_DECODED; - const actual = coder.encode(invalidInput); - expect(actual).not.toStrictEqual(STRING_MIN_ENCODED); + expect(() => { + coder.encode(invalidInput); + }).toThrow(); }); it('should not completely decode a string that is too big for the coder', () => { diff --git a/packages/abi-coder/src/coders/string.ts b/packages/abi-coder/src/coders/string.ts index 2593fd0fb32..55e318e4160 100644 --- a/packages/abi-coder/src/coders/string.ts +++ b/packages/abi-coder/src/coders/string.ts @@ -16,7 +16,11 @@ export default class StringCoder extends Coder< } encode(value: string): Uint8Array { - const encoded = toUtf8Bytes(value.slice(0, this.length)); + if (this.length !== value.length) { + this.throwError('Value length mismatch during encode', value); + } + + const encoded = toUtf8Bytes(value); const padding = new Uint8Array(this.#paddingLength); return concat([encoded, padding]); }