Skip to content

Feature fix base unit conversion#94

Merged
aflament merged 2 commits intomainfrom
feature-fix-base-unit-conversion
Feb 24, 2025
Merged

Feature fix base unit conversion#94
aflament merged 2 commits intomainfrom
feature-fix-base-unit-conversion

Conversation

@aflament
Copy link
Contributor

Bug Report: Token Base Unit Conversion Type Error

Issue
When executing token swaps, the approval transaction was failing with the error "Could not identify the intended function with name approve" due to incorrect type conversion in the token base unit calculation.

Root Cause

In alphaswarm/core/token.py, the TokenInfo.convert_to_base_units() method was returning a Decimal instead of an integer when converting token amounts to base units:

def convert_to_base_units(self, amount: Decimal) -> BaseUnit:
    return BaseUnit(amount * (10**self.decimals))  # Returns Decimal wrapped in BaseUnit

While the type hint BaseUnit = NewType("BaseUnit", int) suggested this should be an integer, the runtime wasn't enforcing the conversion. This caused Web3.py to receive a Decimal value when trying to call the ERC20 contract's approve function, which expects an integer value for the amount parameter.

Fix
Added explicit integer conversion in the base unit calculation:

def convert_to_base_units(self, amount: Decimal) -> BaseUnit:
    return BaseUnit(int(amount * (10**self.decimals)))  # Now returns proper integer

Verification
Before: amount.base_units was Decimal('5000000000000000.000') # Encountered repeatedly in testing
After: amount.base_units is 5000000000000000 (integer) # Observed after applying fix.

Impact
This bug affected any operation requiring token approvals, particularly DEX swaps. The fix ensures proper type conversion when interacting with ERC20 contract functions that expect integer values for token amounts.

Discovery Context
The issue was discovered while debugging token swaps in the PriceMomentumCronAgent. The agent's correct usage of the swap tools helped surface this underlying type conversion issue in the core token handling code. (edited)

@aflament aflament merged commit 3859e0c into main Feb 24, 2025
2 checks passed
@aflament aflament deleted the feature-fix-base-unit-conversion branch February 24, 2025 18:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants