From 9747254297fc79db3de71b564337d0ef6e43d8e9 Mon Sep 17 00:00:00 2001 From: Tristan Menzel Date: Mon, 25 Nov 2024 07:04:43 -0800 Subject: [PATCH] fix: Error when parsing an unsafe numeric literal --- src/awst_build/ast-visitors/base-visitor.ts | 8 ++++++++ tests/expected-output/uint64-expressions.algo.ts | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/src/awst_build/ast-visitors/base-visitor.ts b/src/awst_build/ast-visitors/base-visitor.ts index 5e363539..9e3237da 100644 --- a/src/awst_build/ast-visitors/base-visitor.ts +++ b/src/awst_build/ast-visitors/base-visitor.ts @@ -100,11 +100,19 @@ export abstract class BaseVisitor implements Visitor { } visitNumericLiteral(node: ts.NumericLiteral): InstanceBuilder { + const sourceLocation = this.sourceLocation(node) codeInvariant( !node.text.includes('.'), 'Literals with decimal points are not supported. Use a string literal to capture decimal values', + sourceLocation, ) const literalValue = BigInt(node.text) + if (literalValue > Number.MAX_SAFE_INTEGER || literalValue < Number.MIN_SAFE_INTEGER) { + logger.error( + sourceLocation, + `This number will lose precision at runtime. Use the Uint64 constructor with a bigint or string literal for very large integers.`, + ) + } const ptype = this.context.getPTypeForNode(node) invariant(ptype instanceof TransientType, 'Literals should resolve to transient PTypes') return new BigIntLiteralExpressionBuilder(literalValue, ptype, this.sourceLocation(node)) diff --git a/tests/expected-output/uint64-expressions.algo.ts b/tests/expected-output/uint64-expressions.algo.ts index 992dda1d..e30f2046 100644 --- a/tests/expected-output/uint64-expressions.algo.ts +++ b/tests/expected-output/uint64-expressions.algo.ts @@ -1,5 +1,7 @@ import { Uint64 } from '@algorandfoundation/algorand-typescript' +/* eslint-disable no-loss-of-precision */ + function test() { // @expect-error uint64 overflow or underflow... Uint64(-1) @@ -13,6 +15,8 @@ function test() { Uint64('-1') // @expect-error uint64 overflow or underflow... Uint64(18446744073709551617n) + // @expect-error This number will lose precision... + Uint64(1844674407370955161) // @expect-error uint64 overflow or underflow... Uint64('18446744073709551616') const varStr = '123'