From d599d3ccb7f9b0872177ab69091344be4208132d Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Mon, 27 May 2024 16:34:17 -0400 Subject: [PATCH 01/28] initial work --- src/__swaps__/safe-math/SafeMath.ts | 297 ++++++++++++++---- .../safe-math/__tests__/SafeMath.test.ts | 52 ++- .../Swap/hooks/useSwapInputsController.ts | 2 +- src/__swaps__/utils/swaps.ts | 69 ++-- 4 files changed, 337 insertions(+), 83 deletions(-) diff --git a/src/__swaps__/safe-math/SafeMath.ts b/src/__swaps__/safe-math/SafeMath.ts index 017ed7a22b2..41a1d40539a 100644 --- a/src/__swaps__/safe-math/SafeMath.ts +++ b/src/__swaps__/safe-math/SafeMath.ts @@ -1,5 +1,13 @@ +import { consoleLogWorklet } from '@/debugging/workletUtils'; + +const SCALE_FACTOR = () => { + 'worklet'; + return 20; +}; + // Utility function to remove the decimal point and keep track of the number of decimal places const removeDecimal = (num: string): [bigint, number] => { + 'worklet'; const parts = num.split('.'); const decimalPlaces = parts.length === 2 ? parts[1].length : 0; const bigIntNum = BigInt(parts.join('')); @@ -7,45 +15,52 @@ const removeDecimal = (num: string): [bigint, number] => { }; const isNumberString = (value: string): boolean => { + 'worklet'; return /^\d+(\.\d+)?$/.test(value); }; const isZero = (value: string): boolean => { + 'worklet'; if (parseFloat(value) === 0) { return true; } return false; }; -// Utility function to scale the number up to 20 decimal places +// Utility function to scale the number up to SCALE_FACTOR decimal places const scaleUp = (bigIntNum: bigint, decimalPlaces: number): bigint => { - const scaleFactor = BigInt(10) ** (BigInt(20) - BigInt(decimalPlaces)); + 'worklet'; + const scaleFactor = BigInt(10) ** (BigInt(SCALE_FACTOR()) - BigInt(Math.min(decimalPlaces, 20))); return bigIntNum * scaleFactor; }; -// Utility function to format the result with 20 decimal places and remove trailing zeros +// Utility function to format the result with SCALE_FACTOR decimal places and remove trailing zeros const formatResult = (result: bigint): string => { - const resultStr = result.toString().padStart(21, '0'); // 20 decimal places + at least 1 integer place - const integerPart = resultStr.slice(0, -20) || '0'; - let fractionalPart = resultStr.slice(-20); + 'worklet'; + const resultStr = result.toString().padStart(SCALE_FACTOR() + 1, '0'); // SCALE_FACTOR decimal places + at least 1 integer place + const integerPart = resultStr.slice(0, -SCALE_FACTOR()) || '0'; + let fractionalPart = resultStr.slice(-SCALE_FACTOR()); fractionalPart = fractionalPart.replace(/0+$/, ''); // Remove trailing zeros return fractionalPart.length > 0 ? `${integerPart}.${fractionalPart}` : integerPart; }; // Sum function -export function sum(num1: string, num2: string): string { - if (!isNumberString(num1) || !isNumberString(num2)) { - throw new Error('Arguments must be a numeric string'); +export function sum(num1: string | number, num2: string | number): string { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; + + if (!isNumberString(num1Str) || !isNumberString(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZero(num1)) { - return num2; + if (isZero(num1Str)) { + return num2Str; } - - if (isZero(num2)) { - return num1; + if (isZero(num2Str)) { + return num1Str; } - const [bigInt1, decimalPlaces1] = removeDecimal(num1); - const [bigInt2, decimalPlaces2] = removeDecimal(num2); + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); const result = scaledBigInt1 + scaledBigInt2; @@ -53,17 +68,19 @@ export function sum(num1: string, num2: string): string { } // Subtract function -export function sub(num1: string, num2: string): string { - if (!isNumberString(num1) || !isNumberString(num2)) { - throw new Error('Arguments must be a numeric string'); - } +export function sub(num1: string | number, num2: string | number): string { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - if (isZero(num2)) { - return num1; + if (!isNumberString(num1Str) || !isNumberString(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - - const [bigInt1, decimalPlaces1] = removeDecimal(num1); - const [bigInt2, decimalPlaces2] = removeDecimal(num2); + if (isZero(num2Str)) { + return num1Str; + } + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); const result = scaledBigInt1 - scaledBigInt2; @@ -71,53 +88,65 @@ export function sub(num1: string, num2: string): string { } // Multiply function -export function mul(num1: string, num2: string): string { - if (!isNumberString(num1) || !isNumberString(num2)) { - throw new Error('Arguments must be a numeric string'); +export function mul(num1: string | number, num2: string | number): string { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; + + if (!isNumberString(num1Str) || !isNumberString(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZero(num1) || isZero(num2)) { + if (isZero(num1Str) || isZero(num2Str)) { return '0'; } - const [bigInt1, decimalPlaces1] = removeDecimal(num1); - const [bigInt2, decimalPlaces2] = removeDecimal(num2); + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); - const result = (scaledBigInt1 * scaledBigInt2) / BigInt(10) ** BigInt(20); + const result = (scaledBigInt1 * scaledBigInt2) / BigInt(10) ** BigInt(SCALE_FACTOR()); return formatResult(result); } // Divide function -export function div(num1: string, num2: string): string { - if (!isNumberString(num1) || !isNumberString(num2)) { - throw new Error('Arguments must be a numeric string'); +export function div(num1: string | number, num2: string | number): string { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; + + if (!isNumberString(num1Str) || !isNumberString(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZero(num2)) { + if (isZero(num2Str)) { throw new Error('Division by zero'); } - if (isZero(num1)) { + if (isZero(num1Str)) { return '0'; } - const [bigInt1, decimalPlaces1] = removeDecimal(num1); - const [bigInt2, decimalPlaces2] = removeDecimal(num2); + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); - const result = (scaledBigInt1 * BigInt(10) ** BigInt(20)) / scaledBigInt2; + const result = (scaledBigInt1 * BigInt(10) ** BigInt(SCALE_FACTOR())) / scaledBigInt2; return formatResult(result); } // Modulus function -export function mod(num1: string, num2: string): string { - if (!isNumberString(num1) || !isNumberString(num2)) { - throw new Error('Arguments must be a numeric string'); +export function mod(num1: string | number, num2: string | number): string { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; + + if (!isNumberString(num1Str) || !isNumberString(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZero(num2)) { + if (isZero(num2Str)) { throw new Error('Division by zero'); } - if (isZero(num1)) { + if (isZero(num1Str)) { return '0'; } - const [bigInt1, decimalPlaces1] = removeDecimal(num1); - const [bigInt2, decimalPlaces2] = removeDecimal(num2); + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); const result = scaledBigInt1 % scaledBigInt2; @@ -125,18 +154,178 @@ export function mod(num1: string, num2: string): string { } // Power function -export function pow(base: string, exponent: string): string { - if (!isNumberString(base) || !isNumberString(exponent)) { - throw new Error('Arguments must be a numeric string'); +export function pow(base: string | number, exponent: string | number): string { + 'worklet'; + const baseStr = typeof base === 'number' ? base.toString() : base; + const exponentStr = typeof exponent === 'number' ? exponent.toString() : exponent; + + if (!isNumberString(baseStr) || !isNumberString(exponentStr)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZero(base)) { + if (isZero(baseStr)) { return '0'; } - if (isZero(exponent)) { + if (isZero(exponentStr)) { return '1'; } - const [bigIntBase, decimalPlaces] = removeDecimal(base); + const [bigIntBase, decimalPlaces] = removeDecimal(baseStr); const scaledBigIntBase = scaleUp(bigIntBase, decimalPlaces); - const result = scaledBigIntBase ** BigInt(exponent) / BigInt(10) ** BigInt(20); + const result = scaledBigIntBase ** BigInt(exponentStr) / BigInt(10) ** BigInt(SCALE_FACTOR()); return formatResult(result); } + +// Logarithm base 10 function +export function log10(num: string | number): string { + 'worklet'; + const numStr = typeof num === 'number' ? num.toString() : num; + + if (!isNumberString(numStr)) { + throw new Error('Arguments must be a numeric string or number'); + } + if (isZero(numStr)) { + throw new Error('Argument must be greater than 0'); + } + + const [bigIntNum, decimalPlaces] = removeDecimal(numStr); + const scaledBigIntNum = scaleUp(bigIntNum, decimalPlaces); + const result = Math.log10(Number(scaledBigIntNum)) - SCALE_FACTOR(); // Adjust the scale factor for log10 + const resultBigInt = BigInt(result * 10 ** SCALE_FACTOR()); + return formatResult(resultBigInt); +} + +// Comparison functions +export function gt(num1: string | number, num2: string | number): boolean { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; + + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); + const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); + const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); + return scaledBigInt1 > scaledBigInt2; +} + +export function lt(num1: string | number, num2: string | number): boolean { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; + + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); + const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); + const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); + return scaledBigInt1 < scaledBigInt2; +} + +export function gte(num1: string | number, num2: string | number): boolean { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; + + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); + const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); + const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); + return scaledBigInt1 >= scaledBigInt2; +} + +export function lte(num1: string | number, num2: string | number): boolean { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; + + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); + const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); + const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); + return scaledBigInt1 <= scaledBigInt2; +} + +export function equals(num1: string | number, num2: string | number): boolean { + 'worklet'; + const num1Str = typeof num1 === 'number' ? num1.toString() : num1; + const num2Str = typeof num2 === 'number' ? num2.toString() : num2; + + const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); + const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); + const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); + return scaledBigInt1 === scaledBigInt2; +} + +// toFixed function +export function toFixed(num: string | number, decimalPlaces: number): string { + 'worklet'; + const numStr = typeof num === 'number' ? num.toString() : num; + + if (!isNumberString(numStr)) { + throw new Error('Argument must be a numeric string or number'); + } + + const [bigIntNum, numDecimalPlaces] = removeDecimal(numStr); + const scaledBigIntNum = scaleUp(bigIntNum, numDecimalPlaces); + + const scaleFactor = BigInt(10) ** BigInt(SCALE_FACTOR() - decimalPlaces); + const roundedBigInt = ((scaledBigIntNum + scaleFactor / BigInt(2)) / scaleFactor) * scaleFactor; + + const resultStr = roundedBigInt.toString().padStart(SCALE_FACTOR() + 1, '0'); // SCALE_FACTOR decimal places + at least 1 integer place + const integerPart = resultStr.slice(0, -SCALE_FACTOR()) || '0'; + const fractionalPart = resultStr.slice(-SCALE_FACTOR(), -SCALE_FACTOR() + decimalPlaces).padEnd(decimalPlaces, '0'); + + return `${integerPart}.${fractionalPart}`; +} + +// Ceil function +export function ceil(num: string | number): string { + 'worklet'; + const numStr = typeof num === 'number' ? num.toString() : num; + + if (!isNumberString(numStr)) { + throw new Error('Argument must be a numeric string or number'); + } + + const [bigIntNum, decimalPlaces] = removeDecimal(numStr); + const scaledBigIntNum = scaleUp(bigIntNum, decimalPlaces); + + const scaleFactor = BigInt(10) ** BigInt(SCALE_FACTOR()); + const ceilBigInt = ((scaledBigIntNum + scaleFactor - BigInt(1)) / scaleFactor) * scaleFactor; + + return formatResult(ceilBigInt); +} + +// Floor function +export function floor(num: string | number): string { + 'worklet'; + const numStr = typeof num === 'number' ? num.toString() : num; + + if (!isNumberString(numStr)) { + throw new Error('Argument must be a numeric string or number'); + } + + const [bigIntNum, decimalPlaces] = removeDecimal(numStr); + const scaledBigIntNum = scaleUp(bigIntNum, decimalPlaces); + + const scaleFactor = BigInt(10) ** BigInt(SCALE_FACTOR()); + const floorBigInt = (scaledBigIntNum / scaleFactor) * scaleFactor; + + return formatResult(floorBigInt); +} + +// Round function +export function round(num: string | number): string { + 'worklet'; + const numStr = typeof num === 'number' ? num.toString() : num; + + if (!isNumberString(numStr)) { + throw new Error('Argument must be a numeric string or number'); + } + + const [bigIntNum, decimalPlaces] = removeDecimal(numStr); + const scaledBigIntNum = scaleUp(bigIntNum, decimalPlaces); + + const scaleFactor = BigInt(10) ** BigInt(SCALE_FACTOR()); + const roundBigInt = ((scaledBigIntNum + scaleFactor / BigInt(2)) / scaleFactor) * scaleFactor; + + return formatResult(roundBigInt); +} diff --git a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts b/src/__swaps__/safe-math/__tests__/SafeMath.test.ts index ee2c4b55beb..26bdebfc26d 100644 --- a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts +++ b/src/__swaps__/safe-math/__tests__/SafeMath.test.ts @@ -1,4 +1,4 @@ -import { sum, sub, mul, div, mod, pow } from '../SafeMath'; +import { sum, sub, mul, div, mod, pow, log10, gt, lt, gte, lte, equals, toFixed, ceil, floor, round } from '../SafeMath'; import BigNumber from 'bignumber.js'; const RESULTS = { @@ -8,6 +8,7 @@ const RESULTS = { div: '325.56878986395199044836', mod: '2172.345', pow: '1546106588588.369025', + log10: '0.30102999566398124032', }; const VALUE_A = '1243425.345'; @@ -25,6 +26,7 @@ describe('SafeMath', () => { expect(sum(VALUE_A, ZERO)).toBe(VALUE_A); expect(sum(ZERO, VALUE_B)).toBe(VALUE_B); expect(sum(VALUE_A, VALUE_B)).toBe(RESULTS.sum); + expect(sum(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.sum); }); test('sub', () => { @@ -34,6 +36,7 @@ describe('SafeMath', () => { expect(sub(VALUE_A, ZERO)).toBe(VALUE_A); expect(sub(ZERO, VALUE_B)).toBe(`-${VALUE_B}`); expect(sub(VALUE_A, VALUE_B)).toBe(RESULTS.sub); + expect(sub(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.sub); }); test('mul', () => { @@ -43,6 +46,7 @@ describe('SafeMath', () => { expect(mul(VALUE_A, ZERO)).toBe(ZERO); expect(mul(ZERO, VALUE_B)).toBe(ZERO); expect(mul(VALUE_A, VALUE_B)).toBe(RESULTS.mul); + expect(mul(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.mul); }); test('div', () => { @@ -52,6 +56,7 @@ describe('SafeMath', () => { expect(() => div(VALUE_A, ZERO)).toThrow('Division by zero'); expect(div(ZERO, VALUE_B)).toBe(ZERO); expect(div(VALUE_A, VALUE_B)).toBe(RESULTS.div); + expect(div(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.div); }); test('mod', () => { @@ -61,6 +66,7 @@ describe('SafeMath', () => { expect(() => mod(VALUE_A, ZERO)).toThrow('Division by zero'); expect(mod(ZERO, VALUE_B)).toBe(ZERO); expect(mod(VALUE_A, VALUE_B)).toBe(RESULTS.mod); + expect(mod(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.mod); }); test('pow', () => { expect(() => pow(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); @@ -69,6 +75,50 @@ describe('SafeMath', () => { expect(pow(VALUE_A, ZERO)).toBe(ONE); expect(pow(ZERO, VALUE_B)).toBe(ZERO); expect(pow(VALUE_A, VALUE_C)).toBe(RESULTS.pow); + expect(pow(Number(VALUE_A), Number(VALUE_C))).toBe(RESULTS.pow); + }); + test('log10', () => { + expect(() => log10(NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); + expect(() => log10(ZERO)).toThrow('Argument must be greater than 0'); + expect(log10(VALUE_C)).toBe(RESULTS.log10); + expect(log10(Number(VALUE_C))).toBe(RESULTS.log10); + }); + + test('gt', () => { + expect(gt(VALUE_A, VALUE_B)).toBe(true); + }); + + test('lt', () => { + expect(lt(VALUE_A, VALUE_B)).toBe(false); + }); + + test('gte', () => { + expect(gte(VALUE_A, VALUE_A)).toBe(true); + }); + + test('lte', () => { + expect(lte(VALUE_A, VALUE_A)).toBe(true); + }); + + test('equals', () => { + expect(equals(VALUE_A, VALUE_A)).toBe(true); + }); + + test('toFixed', () => { + expect(toFixed(VALUE_A, Number(VALUE_C))).toBe('1243425.35'); + }); + + test('ceil', () => { + expect(ceil(VALUE_A)).toBe('1243426'); + }); + + test('floor', () => { + expect(floor('1243425.345')).toBe('1243425'); + }); + + test('round', () => { + expect(round('1243425.345')).toBe('1243425'); + expect(round('1243425.745')).toBe('1243426'); }); }); diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index df5d5cdfdae..10d62026005 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -69,7 +69,7 @@ export function useSwapInputsController({ const niceIncrement = useDerivedValue(() => { if (!internalSelectedInputAsset.value?.balance.amount) return 0.1; - return findNiceIncrement(Number(internalSelectedInputAsset.value?.balance.amount)); + return findNiceIncrement(internalSelectedInputAsset.value?.balance.amount); }); const incrementDecimalPlaces = useDerivedValue(() => countDecimalPlaces(niceIncrement.value)); diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index 1d2338becbe..bc5ed78f283 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -16,6 +16,8 @@ import { BigNumberish } from '@ethersproject/bignumber'; import { TokenColors } from '@/graphql/__generated__/metadata'; import { colors } from '@/styles'; import { convertAmountToRawAmount } from './numbers'; +import { ceil, div, equals, floor, log10, lte, mul, pow, round, toFixed } from '../safe-math/SafeMath'; +import { consoleLogWorklet } from '@/debugging/workletUtils'; // /---- 🎨 Color functions 🎨 ----/ // // @@ -109,10 +111,10 @@ export const clampJS = (value: number, lowerBound: number, upperBound: number) = return Math.min(Math.max(lowerBound, value), upperBound); }; -export const countDecimalPlaces = (number: number): number => { +export const countDecimalPlaces = (number: number | string): number => { 'worklet'; - const numAsString = number.toString(); + const numAsString = typeof number === 'string' ? number : number.toString(); if (numAsString.includes('.')) { // Return the number of digits after the decimal point, excluding trailing zeros @@ -123,7 +125,7 @@ export const countDecimalPlaces = (number: number): number => { return 0; }; -export const findNiceIncrement = (availableBalance: number): number => { +export const findNiceIncrement = (availableBalance: string) => { 'worklet'; // We'll use one of these factors to adjust the base increment @@ -133,18 +135,18 @@ export const findNiceIncrement = (availableBalance: number): number => { const niceFactors = [1, 2, 10]; // Calculate the exact increment for 100 steps - const exactIncrement = availableBalance / 100; + const exactIncrement = div(availableBalance, 100); // Calculate the order of magnitude of the exact increment - const orderOfMagnitude = Math.floor(Math.log10(exactIncrement)); - const baseIncrement = Math.pow(10, orderOfMagnitude); + const orderOfMagnitude = Math.floor(Number(log10(exactIncrement))); + const baseIncrement = pow(10, orderOfMagnitude); let adjustedIncrement = baseIncrement; // Find the first nice increment that ensures at least 100 steps for (let i = niceFactors.length - 1; i >= 0; i--) { - const potentialIncrement = baseIncrement * niceFactors[i]; - if (potentialIncrement <= exactIncrement) { + const potentialIncrement = mul(baseIncrement, niceFactors[i]); + if (lte(potentialIncrement, exactIncrement)) { adjustedIncrement = potentialIncrement; break; } @@ -198,7 +200,7 @@ export function valueBasedDecimalFormatter({ isStablecoin, stripSeparators = true, }: { - amount: number; + amount: number | string; usdTokenPrice: number; roundingMode?: 'up' | 'down'; precisionAdjustment?: number; @@ -221,17 +223,17 @@ export function valueBasedDecimalFormatter({ const decimalPlaces = isStablecoin ? 2 : calculateDecimalPlaces(usdTokenPrice, precisionAdjustment); - let roundedAmount: number; + let roundedAmount; const factor = Math.pow(10, decimalPlaces); // Apply rounding based on the specified rounding mode if (roundingMode === 'up') { - roundedAmount = Math.ceil(amount * factor) / factor; + roundedAmount = div(ceil(mul(amount, factor)), factor); } else if (roundingMode === 'down') { - roundedAmount = Math.floor(amount * factor) / factor; + roundedAmount = div(floor(mul(amount, factor)), factor); } else { // Default to normal rounding if no rounding mode is specified - roundedAmount = Math.round(amount * factor) / factor; + roundedAmount = div(round(mul(amount, factor)), factor); } // Format the number to add separators and trim trailing zeros @@ -241,9 +243,9 @@ export function valueBasedDecimalFormatter({ useGrouping: true, }); - if (stripSeparators) return stripCommas(numberFormatter.format(roundedAmount)); + if (stripSeparators) return stripCommas(numberFormatter.format(Number(roundedAmount))); - return numberFormatter.format(roundedAmount); + return numberFormatter.format(Number(roundedAmount)); } export function niceIncrementFormatter({ @@ -256,9 +258,9 @@ export function niceIncrementFormatter({ stripSeparators, }: { incrementDecimalPlaces: number; - inputAssetBalance: number; + inputAssetBalance: number | string; inputAssetUsdPrice: number; - niceIncrement: number; + niceIncrement: number | string; percentageToSwap: number; sliderXPosition: number; stripSeparators?: boolean; @@ -267,21 +269,21 @@ export function niceIncrementFormatter({ if (percentageToSwap === 0) return '0'; if (percentageToSwap === 0.25) return valueBasedDecimalFormatter({ - amount: inputAssetBalance * 0.25, + amount: mul(inputAssetBalance, 0.25), usdTokenPrice: inputAssetUsdPrice, roundingMode: 'up', precisionAdjustment: -3, }); if (percentageToSwap === 0.5) return valueBasedDecimalFormatter({ - amount: inputAssetBalance * 0.5, + amount: mul(inputAssetBalance, 0.5), usdTokenPrice: inputAssetUsdPrice, roundingMode: 'up', precisionAdjustment: -3, }); if (percentageToSwap === 0.75) return valueBasedDecimalFormatter({ - amount: inputAssetBalance * 0.75, + amount: mul(inputAssetBalance, 0.75), usdTokenPrice: inputAssetUsdPrice, roundingMode: 'up', precisionAdjustment: -3, @@ -293,16 +295,29 @@ export function niceIncrementFormatter({ roundingMode: 'up', }); - const exactIncrement = inputAssetBalance / 100; - const isIncrementExact = niceIncrement === exactIncrement; - const numberOfIncrements = inputAssetBalance / niceIncrement; - const incrementStep = 1 / numberOfIncrements; + consoleLogWorklet('niceIncrement:' + niceIncrement); + const exactIncrement = div(inputAssetBalance, 100); + consoleLogWorklet('exactIncrement:' + exactIncrement); + const isIncrementExact = equals(niceIncrement, exactIncrement); + consoleLogWorklet('isIncrementExact:' + isIncrementExact); + const numberOfIncrements = div(inputAssetBalance, niceIncrement); + consoleLogWorklet('numberOfIncrements:' + numberOfIncrements); + const incrementStep = div(1, numberOfIncrements); + consoleLogWorklet('numberOfIncrements:' + numberOfIncrements); const percentage = isIncrementExact ? percentageToSwap - : Math.round(clamp((sliderXPosition - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1) * (1 / incrementStep)) / (1 / incrementStep); + : Math.round( + (clamp((sliderXPosition - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1) * Number(div(1, incrementStep))) / + Number(div(1, incrementStep)) + ); - const rawAmount = Math.round((percentage * inputAssetBalance) / niceIncrement) * niceIncrement; - const amountToFixedDecimals = rawAmount.toFixed(incrementDecimalPlaces); + consoleLogWorklet('percentage:' + percentage); + + const rawAmount = mul(Math.round(Number(div(mul(percentage, inputAssetBalance), niceIncrement))), niceIncrement); + consoleLogWorklet('rawAmount:' + rawAmount); + + const amountToFixedDecimals = toFixed(rawAmount, incrementDecimalPlaces); + consoleLogWorklet('amountToFixedDecimals:' + amountToFixedDecimals); const formattedAmount = `${Number(amountToFixedDecimals).toLocaleString('en-US', { useGrouping: true, From f64b70e08d274be918a5064a4933c4a2c87ad500 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 28 May 2024 11:53:34 -0400 Subject: [PATCH 02/28] more fixes --- .../safe-math/__tests__/SafeMath.test.ts | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts b/src/__swaps__/safe-math/__tests__/SafeMath.test.ts index 87e65e8fd83..ddb291948c8 100644 --- a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts +++ b/src/__swaps__/safe-math/__tests__/SafeMath.test.ts @@ -1,16 +1,21 @@ import BigNumber from 'bignumber.js'; import { + ceilWorklet, divWorklet, equalWorklet, + floorWorklet, greaterThanOrEqualToWorklet, greaterThanWorklet, lessThanOrEqualToWorklet, lessThanWorklet, + log10Worklet, modWorklet, mulWorklet, powWorklet, + roundWorklet, subWorklet, sumWorklet, + toFixedWorklet, } from '../SafeMath'; const RESULTS = { @@ -21,11 +26,15 @@ const RESULTS = { mod: '2172.345', pow: '1546106588588.369025', log10: '0.30102999566398124032', + toFixed: '1243425.35', + ceil: '1243426', + floor: '1243425', }; const VALUE_A = '1243425.345'; const VALUE_B = '3819.24'; const VALUE_C = '2'; +const VALUE_D = '1243425.745'; const NEGATIVE_VALUE = '-2412.12'; const ZERO = '0'; const ONE = '1'; @@ -87,6 +96,13 @@ describe('SafeMath', () => { expect(powWorklet(VALUE_A, VALUE_C)).toBe(RESULTS.pow); }); + test('log10Worklet', () => { + expect(() => log10Worklet(NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); + expect(() => log10Worklet(ZERO)).toThrow('Argument must be greater than 0'); + expect(log10Worklet(VALUE_C)).toBe(RESULTS.log10); + expect(log10Worklet(Number(VALUE_C))).toBe(RESULTS.log10); + }); + test('equalWorklet', () => { expect(() => equalWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); expect(() => equalWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); @@ -131,6 +147,23 @@ describe('SafeMath', () => { expect(lessThanOrEqualToWorklet(VALUE_A, VALUE_A)).toBe(true); expect(lessThanOrEqualToWorklet(NEGATIVE_VALUE, VALUE_A)).toBe(true); }); + + test('toFixedWorklet', () => { + expect(toFixedWorklet(VALUE_A, 2)).toBe(RESULTS.toFixed); + }); + + test('ceilWorklet', () => { + expect(ceilWorklet(VALUE_A)).toBe(RESULTS.ceil); + }); + + test('floorWorklet', () => { + expect(floorWorklet(VALUE_A)).toBe(RESULTS.floor); + }); + + test('roundWorklet', () => { + expect(roundWorklet(VALUE_A)).toBe(RESULTS.floor); + expect(roundWorklet(VALUE_D)).toBe(RESULTS.ceil); + }); }); describe('BigNumber', () => { From 95f41f0c6d34d8c784ebd9f54799da5a19dd5808 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 28 May 2024 15:01:37 -0400 Subject: [PATCH 03/28] updates --- src/__swaps__/safe-math/SafeMath.ts | 185 +++++++++++++++++----------- src/__swaps__/utils/swaps.ts | 51 +++++--- 2 files changed, 143 insertions(+), 93 deletions(-) diff --git a/src/__swaps__/safe-math/SafeMath.ts b/src/__swaps__/safe-math/SafeMath.ts index 66ebbac8e04..4d0eb500112 100644 --- a/src/__swaps__/safe-math/SafeMath.ts +++ b/src/__swaps__/safe-math/SafeMath.ts @@ -40,21 +40,30 @@ const formatResultWorklet = (result: bigint): string => { return isNegative ? `-${formattedResult}` : formattedResult; }; +// Helper function to handle string and number input types +const toStringWorklet = (value: string | number): string => { + 'worklet'; + return typeof value === 'number' ? value.toString() : value; +}; + // Sum function -export function sumWorklet(num1: string, num2: string): string { +export function sumWorklet(num1: string | number, num2: string | number): string { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZeroWorklet(num1)) { - return num2; + if (isZeroWorklet(num1Str)) { + return num2Str; } - if (isZeroWorklet(num2)) { - return num1; + if (isZeroWorklet(num2Str)) { + return num1Str; } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); const result = scaledBigInt1 + scaledBigInt2; @@ -62,18 +71,21 @@ export function sumWorklet(num1: string, num2: string): string { } // Subtract function -export function subWorklet(num1: string, num2: string): string { +export function subWorklet(num1: string | number, num2: string | number): string { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZeroWorklet(num2)) { - return num1; + if (isZeroWorklet(num2Str)) { + return num1Str; } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); const result = scaledBigInt1 - scaledBigInt2; @@ -81,16 +93,19 @@ export function subWorklet(num1: string, num2: string): string { } // Multiply function -export function mulWorklet(num1: string, num2: string): string { +export function mulWorklet(num1: string | number, num2: string | number): string { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZeroWorklet(num1) || isZeroWorklet(num2)) { + if (isZeroWorklet(num1Str) || isZeroWorklet(num2Str)) { return '0'; } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); const result = (scaledBigInt1 * scaledBigInt2) / BigInt(10) ** BigInt(20); @@ -98,19 +113,22 @@ export function mulWorklet(num1: string, num2: string): string { } // Divide function -export function divWorklet(num1: string, num2: string): string { +export function divWorklet(num1: string | number, num2: string | number): string { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZeroWorklet(num2)) { + if (isZeroWorklet(num2Str)) { throw new Error('Division by zero'); } - if (isZeroWorklet(num1)) { + if (isZeroWorklet(num1Str)) { return '0'; } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); const result = (scaledBigInt1 * BigInt(10) ** BigInt(20)) / scaledBigInt2; @@ -118,19 +136,22 @@ export function divWorklet(num1: string, num2: string): string { } // Modulus function -export function modWorklet(num1: string, num2: string): string { +export function modWorklet(num1: string | number, num2: string | number): string { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZeroWorklet(num2)) { + if (isZeroWorklet(num2Str)) { throw new Error('Division by zero'); } - if (isZeroWorklet(num1)) { + if (isZeroWorklet(num1Str)) { return '0'; } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); const result = scaledBigInt1 % scaledBigInt2; @@ -138,27 +159,30 @@ export function modWorklet(num1: string, num2: string): string { } // Power function -export function powWorklet(base: string, exponent: string): string { +export function powWorklet(base: string | number, exponent: string | number): string { 'worklet'; - if (!isNumberStringWorklet(base) || !isNumberStringWorklet(exponent)) { - throw new Error('Arguments must be a numeric string'); + const baseStr = toStringWorklet(base); + const exponentStr = toStringWorklet(exponent); + + if (!isNumberStringWorklet(baseStr) || !isNumberStringWorklet(exponentStr)) { + throw new Error('Arguments must be a numeric string or number'); } - if (isZeroWorklet(base)) { + if (isZeroWorklet(baseStr)) { return '0'; } - if (isZeroWorklet(exponent)) { + if (isZeroWorklet(exponentStr)) { return '1'; } - const [bigIntBase, decimalPlaces] = removeDecimalWorklet(base); + const [bigIntBase, decimalPlaces] = removeDecimalWorklet(baseStr); const scaledBigIntBase = scaleUpWorklet(bigIntBase, decimalPlaces); - const result = scaledBigIntBase ** BigInt(exponent) / BigInt(10) ** BigInt(20); + const result = scaledBigIntBase ** BigInt(exponentStr) / BigInt(10) ** BigInt(20); return formatResultWorklet(result); } // Logarithm base 10 function export function log10Worklet(num: string | number): string { 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; + const numStr = toStringWorklet(num); if (!isNumberStringWorklet(numStr)) { throw new Error('Arguments must be a numeric string or number'); @@ -175,65 +199,80 @@ export function log10Worklet(num: string | number): string { } // Equality function -export function equalWorklet(num1: string, num2: string): boolean { +export function equalWorklet(num1: string | number, num2: string | number): boolean { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); return scaledBigInt1 === scaledBigInt2; } // Greater than function -export function greaterThanWorklet(num1: string, num2: string): boolean { +export function greaterThanWorklet(num1: string | number, num2: string | number): boolean { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); return scaledBigInt1 > scaledBigInt2; } // Greater than or equal to function -export function greaterThanOrEqualToWorklet(num1: string, num2: string): boolean { +export function greaterThanOrEqualToWorklet(num1: string | number, num2: string | number): boolean { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); return scaledBigInt1 >= scaledBigInt2; } // Less than function -export function lessThanWorklet(num1: string, num2: string): boolean { +export function lessThanWorklet(num1: string | number, num2: string | number): boolean { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); return scaledBigInt1 < scaledBigInt2; } // Less than or equal to function -export function lessThanOrEqualToWorklet(num1: string, num2: string): boolean { +export function lessThanOrEqualToWorklet(num1: string | number, num2: string | number): boolean { 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); + const num1Str = toStringWorklet(num1); + const num2Str = toStringWorklet(num2); + + if (!isNumberStringWorklet(num1Str) || !isNumberStringWorklet(num2Str)) { + throw new Error('Arguments must be a numeric string or number'); } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); + const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1Str); + const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2Str); const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); return scaledBigInt1 <= scaledBigInt2; @@ -242,7 +281,7 @@ export function lessThanOrEqualToWorklet(num1: string, num2: string): boolean { // toFixed function export function toFixedWorklet(num: string | number, decimalPlaces: number): string { 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; + const numStr = toStringWorklet(num); if (!isNumberStringWorklet(numStr)) { throw new Error('Argument must be a numeric string or number'); @@ -264,7 +303,7 @@ export function toFixedWorklet(num: string | number, decimalPlaces: number): str // Ceil function export function ceilWorklet(num: string | number): string { 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; + const numStr = toStringWorklet(num); if (!isNumberStringWorklet(numStr)) { throw new Error('Argument must be a numeric string or number'); @@ -282,7 +321,7 @@ export function ceilWorklet(num: string | number): string { // Floor function export function floorWorklet(num: string | number): string { 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; + const numStr = toStringWorklet(num); if (!isNumberStringWorklet(numStr)) { throw new Error('Argument must be a numeric string or number'); @@ -300,7 +339,7 @@ export function floorWorklet(num: string | number): string { // Round function export function roundWorklet(num: string | number): string { 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; + const numStr = toStringWorklet(num); if (!isNumberStringWorklet(numStr)) { throw new Error('Argument must be a numeric string or number'); diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index bc5ed78f283..36b707fd363 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -16,7 +16,18 @@ import { BigNumberish } from '@ethersproject/bignumber'; import { TokenColors } from '@/graphql/__generated__/metadata'; import { colors } from '@/styles'; import { convertAmountToRawAmount } from './numbers'; -import { ceil, div, equals, floor, log10, lte, mul, pow, round, toFixed } from '../safe-math/SafeMath'; +import { + ceilWorklet, + divWorklet, + equalWorklet, + floorWorklet, + log10Worklet, + lessThanOrEqualToWorklet, + mulWorklet, + powWorklet, + roundWorklet, + toFixedWorklet, +} from '../safe-math/SafeMath'; import { consoleLogWorklet } from '@/debugging/workletUtils'; // /---- 🎨 Color functions 🎨 ----/ // @@ -135,18 +146,18 @@ export const findNiceIncrement = (availableBalance: string) => { const niceFactors = [1, 2, 10]; // Calculate the exact increment for 100 steps - const exactIncrement = div(availableBalance, 100); + const exactIncrement = divWorklet(availableBalance, 100); // Calculate the order of magnitude of the exact increment - const orderOfMagnitude = Math.floor(Number(log10(exactIncrement))); - const baseIncrement = pow(10, orderOfMagnitude); + const orderOfMagnitude = Math.floor(Number(log10Worklet(exactIncrement))); + const baseIncrement = powWorklet(10, orderOfMagnitude); let adjustedIncrement = baseIncrement; // Find the first nice increment that ensures at least 100 steps for (let i = niceFactors.length - 1; i >= 0; i--) { - const potentialIncrement = mul(baseIncrement, niceFactors[i]); - if (lte(potentialIncrement, exactIncrement)) { + const potentialIncrement = mulWorklet(baseIncrement, niceFactors[i]); + if (lessThanOrEqualToWorklet(potentialIncrement, exactIncrement)) { adjustedIncrement = potentialIncrement; break; } @@ -228,12 +239,12 @@ export function valueBasedDecimalFormatter({ // Apply rounding based on the specified rounding mode if (roundingMode === 'up') { - roundedAmount = div(ceil(mul(amount, factor)), factor); + roundedAmount = divWorklet(ceilWorklet(mulWorklet(amount, factor)), factor); } else if (roundingMode === 'down') { - roundedAmount = div(floor(mul(amount, factor)), factor); + roundedAmount = divWorklet(floorWorklet(mulWorklet(amount, factor)), factor); } else { // Default to normal rounding if no rounding mode is specified - roundedAmount = div(round(mul(amount, factor)), factor); + roundedAmount = divWorklet(roundWorklet(mulWorklet(amount, factor)), factor); } // Format the number to add separators and trim trailing zeros @@ -269,21 +280,21 @@ export function niceIncrementFormatter({ if (percentageToSwap === 0) return '0'; if (percentageToSwap === 0.25) return valueBasedDecimalFormatter({ - amount: mul(inputAssetBalance, 0.25), + amount: mulWorklet(inputAssetBalance, 0.25), usdTokenPrice: inputAssetUsdPrice, roundingMode: 'up', precisionAdjustment: -3, }); if (percentageToSwap === 0.5) return valueBasedDecimalFormatter({ - amount: mul(inputAssetBalance, 0.5), + amount: mulWorklet(inputAssetBalance, 0.5), usdTokenPrice: inputAssetUsdPrice, roundingMode: 'up', precisionAdjustment: -3, }); if (percentageToSwap === 0.75) return valueBasedDecimalFormatter({ - amount: mul(inputAssetBalance, 0.75), + amount: mulWorklet(inputAssetBalance, 0.75), usdTokenPrice: inputAssetUsdPrice, roundingMode: 'up', precisionAdjustment: -3, @@ -296,27 +307,27 @@ export function niceIncrementFormatter({ }); consoleLogWorklet('niceIncrement:' + niceIncrement); - const exactIncrement = div(inputAssetBalance, 100); + const exactIncrement = divWorklet(inputAssetBalance, 100); consoleLogWorklet('exactIncrement:' + exactIncrement); - const isIncrementExact = equals(niceIncrement, exactIncrement); + const isIncrementExact = equalWorklet(niceIncrement, exactIncrement); consoleLogWorklet('isIncrementExact:' + isIncrementExact); - const numberOfIncrements = div(inputAssetBalance, niceIncrement); + const numberOfIncrements = divWorklet(inputAssetBalance, niceIncrement); consoleLogWorklet('numberOfIncrements:' + numberOfIncrements); - const incrementStep = div(1, numberOfIncrements); + const incrementStep = divWorklet(1, numberOfIncrements); consoleLogWorklet('numberOfIncrements:' + numberOfIncrements); const percentage = isIncrementExact ? percentageToSwap : Math.round( - (clamp((sliderXPosition - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1) * Number(div(1, incrementStep))) / - Number(div(1, incrementStep)) + (clamp((sliderXPosition - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1) * Number(divWorklet(1, incrementStep))) / + Number(divWorklet(1, incrementStep)) ); consoleLogWorklet('percentage:' + percentage); - const rawAmount = mul(Math.round(Number(div(mul(percentage, inputAssetBalance), niceIncrement))), niceIncrement); + const rawAmount = mulWorklet(Math.round(Number(divWorklet(mulWorklet(percentage, inputAssetBalance), niceIncrement))), niceIncrement); consoleLogWorklet('rawAmount:' + rawAmount); - const amountToFixedDecimals = toFixed(rawAmount, incrementDecimalPlaces); + const amountToFixedDecimals = toFixedWorklet(rawAmount, incrementDecimalPlaces); consoleLogWorklet('amountToFixedDecimals:' + amountToFixedDecimals); const formattedAmount = `${Number(amountToFixedDecimals).toLocaleString('en-US', { From 59f6fb560d65de3335b37ed4b6f518e748e4242c Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 28 May 2024 15:13:29 -0400 Subject: [PATCH 04/28] remove diff files --- src/__swaps__/safe-math/SafeMath.ts.orig | 537 ------------------ .../safe-math/__tests__/SafeMath.test.ts.orig | 294 ---------- 2 files changed, 831 deletions(-) delete mode 100644 src/__swaps__/safe-math/SafeMath.ts.orig delete mode 100644 src/__swaps__/safe-math/__tests__/SafeMath.test.ts.orig diff --git a/src/__swaps__/safe-math/SafeMath.ts.orig b/src/__swaps__/safe-math/SafeMath.ts.orig deleted file mode 100644 index 955d303cb60..00000000000 --- a/src/__swaps__/safe-math/SafeMath.ts.orig +++ /dev/null @@ -1,537 +0,0 @@ -import { consoleLogWorklet } from '@/debugging/workletUtils'; - -const SCALE_FACTOR = () => { - 'worklet'; - return 20; -}; - -// Utility function to remove the decimal point and keep track of the number of decimal places -<<<<<<< HEAD -const removeDecimal = (num: string): [bigint, number] => { -======= -const removeDecimalWorklet = (num: string): [bigint, number] => { ->>>>>>> 0889e092afe774d0e8db6885e5962c4a8278b6cf - 'worklet'; - const parts = num.split('.'); - const decimalPlaces = parts.length === 2 ? parts[1].length : 0; - const bigIntNum = BigInt(parts.join('')); - return [bigIntNum, decimalPlaces]; -}; - -<<<<<<< HEAD -const isNumberString = (value: string): boolean => { - 'worklet'; - return /^\d+(\.\d+)?$/.test(value); -}; - -const isZero = (value: string): boolean => { -======= -const isNumberStringWorklet = (value: string): boolean => { - 'worklet'; - return /^-?\d+(\.\d+)?$/.test(value); -}; - -const isZeroWorklet = (value: string): boolean => { ->>>>>>> 0889e092afe774d0e8db6885e5962c4a8278b6cf - 'worklet'; - if (parseFloat(value) === 0) { - return true; - } - return false; -}; - -<<<<<<< HEAD -// Utility function to scale the number up to SCALE_FACTOR decimal places -const scaleUp = (bigIntNum: bigint, decimalPlaces: number): bigint => { - 'worklet'; - const scaleFactor = BigInt(10) ** (BigInt(SCALE_FACTOR()) - BigInt(Math.min(decimalPlaces, 20))); - return bigIntNum * scaleFactor; -}; - -// Utility function to format the result with SCALE_FACTOR decimal places and remove trailing zeros -const formatResult = (result: bigint): string => { - 'worklet'; - const resultStr = result.toString().padStart(SCALE_FACTOR() + 1, '0'); // SCALE_FACTOR decimal places + at least 1 integer place - const integerPart = resultStr.slice(0, -SCALE_FACTOR()) || '0'; - let fractionalPart = resultStr.slice(-SCALE_FACTOR()); -======= -// Utility function to scale the number up to 20 decimal places -const scaleUpWorklet = (bigIntNum: bigint, decimalPlaces: number): bigint => { - 'worklet'; - const scaleFactor = BigInt(10) ** BigInt(20); - return (bigIntNum * scaleFactor) / BigInt(10) ** BigInt(decimalPlaces); -}; - -// Utility function to format the result with 20 decimal places and remove trailing zeros -const formatResultWorklet = (result: bigint): string => { - 'worklet'; - const isNegative = result < 0; - const absResult = isNegative ? -result : result; - const resultStr = absResult.toString().padStart(21, '0'); // 20 decimal places + at least 1 integer place - const integerPart = resultStr.slice(0, -20) || '0'; - let fractionalPart = resultStr.slice(-20); ->>>>>>> 0889e092afe774d0e8db6885e5962c4a8278b6cf - fractionalPart = fractionalPart.replace(/0+$/, ''); // Remove trailing zeros - const formattedResult = fractionalPart.length > 0 ? `${integerPart}.${fractionalPart}` : integerPart; - return isNegative ? `-${formattedResult}` : formattedResult; -}; - -// Sum function -<<<<<<< HEAD -export function sum(num1: string | number, num2: string | number): string { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - if (!isNumberString(num1Str) || !isNumberString(num2Str)) { - throw new Error('Arguments must be a numeric string or number'); - } - if (isZero(num1Str)) { - return num2Str; - } - if (isZero(num2Str)) { - return num1Str; - } - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); -======= -export function sumWorklet(num1: string, num2: string): string { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - if (isZeroWorklet(num1)) { - return num2; - } - - if (isZeroWorklet(num2)) { - return num1; - } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); ->>>>>>> 0889e092afe774d0e8db6885e5962c4a8278b6cf - const result = scaledBigInt1 + scaledBigInt2; - return formatResultWorklet(result); -} - -// Subtract function -<<<<<<< HEAD -export function sub(num1: string | number, num2: string | number): string { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - if (!isNumberString(num1Str) || !isNumberString(num2Str)) { - throw new Error('Arguments must be a numeric string or number'); - } - if (isZero(num2Str)) { - return num1Str; - } - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); -======= -export function subWorklet(num1: string, num2: string): string { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - - if (isZeroWorklet(num2)) { - return num1; - } - - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); ->>>>>>> 0889e092afe774d0e8db6885e5962c4a8278b6cf - const result = scaledBigInt1 - scaledBigInt2; - return formatResultWorklet(result); -} - -// Multiply function -<<<<<<< HEAD -export function mul(num1: string | number, num2: string | number): string { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - if (!isNumberString(num1Str) || !isNumberString(num2Str)) { - throw new Error('Arguments must be a numeric string or number'); - } - if (isZero(num1Str) || isZero(num2Str)) { - return '0'; - } - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); - const result = (scaledBigInt1 * scaledBigInt2) / BigInt(10) ** BigInt(SCALE_FACTOR()); - return formatResult(result); -} - -// Divide function -export function div(num1: string | number, num2: string | number): string { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - if (!isNumberString(num1Str) || !isNumberString(num2Str)) { - throw new Error('Arguments must be a numeric string or number'); - } - if (isZero(num2Str)) { - throw new Error('Division by zero'); - } - if (isZero(num1Str)) { - return '0'; - } - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); - const result = (scaledBigInt1 * BigInt(10) ** BigInt(SCALE_FACTOR())) / scaledBigInt2; - return formatResult(result); -} - -// Modulus function -export function mod(num1: string | number, num2: string | number): string { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - if (!isNumberString(num1Str) || !isNumberString(num2Str)) { - throw new Error('Arguments must be a numeric string or number'); - } - if (isZero(num2Str)) { - throw new Error('Division by zero'); - } - if (isZero(num1Str)) { - return '0'; - } - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); -======= -export function mulWorklet(num1: string, num2: string): string { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - if (isZeroWorklet(num1) || isZeroWorklet(num2)) { - return '0'; - } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); - const result = (scaledBigInt1 * scaledBigInt2) / BigInt(10) ** BigInt(20); - return formatResultWorklet(result); -} - -// Divide function -export function divWorklet(num1: string, num2: string): string { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - if (isZeroWorklet(num2)) { - throw new Error('Division by zero'); - } - if (isZeroWorklet(num1)) { - return '0'; - } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); - const result = (scaledBigInt1 * BigInt(10) ** BigInt(20)) / scaledBigInt2; - return formatResultWorklet(result); -} - -// Modulus function -export function modWorklet(num1: string, num2: string): string { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - if (isZeroWorklet(num2)) { - throw new Error('Division by zero'); - } - if (isZeroWorklet(num1)) { - return '0'; - } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); ->>>>>>> 0889e092afe774d0e8db6885e5962c4a8278b6cf - const result = scaledBigInt1 % scaledBigInt2; - return formatResultWorklet(result); -} - -// Power function -<<<<<<< HEAD -export function pow(base: string | number, exponent: string | number): string { - 'worklet'; - const baseStr = typeof base === 'number' ? base.toString() : base; - const exponentStr = typeof exponent === 'number' ? exponent.toString() : exponent; - - if (!isNumberString(baseStr) || !isNumberString(exponentStr)) { - throw new Error('Arguments must be a numeric string or number'); - } - if (isZero(baseStr)) { - return '0'; - } - if (isZero(exponentStr)) { - return '1'; - } - const [bigIntBase, decimalPlaces] = removeDecimal(baseStr); - const scaledBigIntBase = scaleUp(bigIntBase, decimalPlaces); - const result = scaledBigIntBase ** BigInt(exponentStr) / BigInt(10) ** BigInt(SCALE_FACTOR()); - return formatResult(result); -======= -export function powWorklet(base: string, exponent: string): string { - 'worklet'; - if (!isNumberStringWorklet(base) || !isNumberStringWorklet(exponent)) { - throw new Error('Arguments must be a numeric string'); - } - if (isZeroWorklet(base)) { - return '0'; - } - if (isZeroWorklet(exponent)) { - return '1'; - } - const [bigIntBase, decimalPlaces] = removeDecimalWorklet(base); - const scaledBigIntBase = scaleUpWorklet(bigIntBase, decimalPlaces); - const result = scaledBigIntBase ** BigInt(exponent) / BigInt(10) ** BigInt(20); - return formatResultWorklet(result); -} - -// Equality function -export function equalWorklet(num1: string, num2: string): boolean { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); - return scaledBigInt1 === scaledBigInt2; -} - -// Greater than function -export function greaterThanWorklet(num1: string, num2: string): boolean { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); - return scaledBigInt1 > scaledBigInt2; -} - -// Greater than or equal to function -export function greaterThanOrEqualToWorklet(num1: string, num2: string): boolean { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); - return scaledBigInt1 >= scaledBigInt2; -} - -// Less than function -export function lessThanWorklet(num1: string, num2: string): boolean { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); - return scaledBigInt1 < scaledBigInt2; -} - -// Less than or equal to function -export function lessThanOrEqualToWorklet(num1: string, num2: string): boolean { - 'worklet'; - if (!isNumberStringWorklet(num1) || !isNumberStringWorklet(num2)) { - throw new Error('Arguments must be a numeric string'); - } - const [bigInt1, decimalPlaces1] = removeDecimalWorklet(num1); - const [bigInt2, decimalPlaces2] = removeDecimalWorklet(num2); - const scaledBigInt1 = scaleUpWorklet(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUpWorklet(bigInt2, decimalPlaces2); - return scaledBigInt1 <= scaledBigInt2; ->>>>>>> 0889e092afe774d0e8db6885e5962c4a8278b6cf -} - -// Logarithm base 10 function -export function log10(num: string | number): string { - 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; - - if (!isNumberString(numStr)) { - throw new Error('Arguments must be a numeric string or number'); - } - if (isZero(numStr)) { - throw new Error('Argument must be greater than 0'); - } - - const [bigIntNum, decimalPlaces] = removeDecimal(numStr); - const scaledBigIntNum = scaleUp(bigIntNum, decimalPlaces); - const result = Math.log10(Number(scaledBigIntNum)) - SCALE_FACTOR(); // Adjust the scale factor for log10 - const resultBigInt = BigInt(result * 10 ** SCALE_FACTOR()); - return formatResult(resultBigInt); -} - -// Comparison functions -export function gt(num1: string | number, num2: string | number): boolean { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); - return scaledBigInt1 > scaledBigInt2; -} - -export function lt(num1: string | number, num2: string | number): boolean { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); - return scaledBigInt1 < scaledBigInt2; -} - -export function gte(num1: string | number, num2: string | number): boolean { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); - return scaledBigInt1 >= scaledBigInt2; -} - -export function lte(num1: string | number, num2: string | number): boolean { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); - return scaledBigInt1 <= scaledBigInt2; -} - -export function equals(num1: string | number, num2: string | number): boolean { - 'worklet'; - const num1Str = typeof num1 === 'number' ? num1.toString() : num1; - const num2Str = typeof num2 === 'number' ? num2.toString() : num2; - - const [bigInt1, decimalPlaces1] = removeDecimal(num1Str); - const [bigInt2, decimalPlaces2] = removeDecimal(num2Str); - const scaledBigInt1 = scaleUp(bigInt1, decimalPlaces1); - const scaledBigInt2 = scaleUp(bigInt2, decimalPlaces2); - return scaledBigInt1 === scaledBigInt2; -} - -// toFixed function -export function toFixed(num: string | number, decimalPlaces: number): string { - 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; - - if (!isNumberString(numStr)) { - throw new Error('Argument must be a numeric string or number'); - } - - const [bigIntNum, numDecimalPlaces] = removeDecimal(numStr); - const scaledBigIntNum = scaleUp(bigIntNum, numDecimalPlaces); - - const scaleFactor = BigInt(10) ** BigInt(SCALE_FACTOR() - decimalPlaces); - const roundedBigInt = ((scaledBigIntNum + scaleFactor / BigInt(2)) / scaleFactor) * scaleFactor; - - const resultStr = roundedBigInt.toString().padStart(SCALE_FACTOR() + 1, '0'); // SCALE_FACTOR decimal places + at least 1 integer place - const integerPart = resultStr.slice(0, -SCALE_FACTOR()) || '0'; - const fractionalPart = resultStr.slice(-SCALE_FACTOR(), -SCALE_FACTOR() + decimalPlaces).padEnd(decimalPlaces, '0'); - - return `${integerPart}.${fractionalPart}`; -} - -// Ceil function -export function ceil(num: string | number): string { - 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; - - if (!isNumberString(numStr)) { - throw new Error('Argument must be a numeric string or number'); - } - - const [bigIntNum, decimalPlaces] = removeDecimal(numStr); - const scaledBigIntNum = scaleUp(bigIntNum, decimalPlaces); - - const scaleFactor = BigInt(10) ** BigInt(SCALE_FACTOR()); - const ceilBigInt = ((scaledBigIntNum + scaleFactor - BigInt(1)) / scaleFactor) * scaleFactor; - - return formatResult(ceilBigInt); -} - -// Floor function -export function floor(num: string | number): string { - 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; - - if (!isNumberString(numStr)) { - throw new Error('Argument must be a numeric string or number'); - } - - const [bigIntNum, decimalPlaces] = removeDecimal(numStr); - const scaledBigIntNum = scaleUp(bigIntNum, decimalPlaces); - - const scaleFactor = BigInt(10) ** BigInt(SCALE_FACTOR()); - const floorBigInt = (scaledBigIntNum / scaleFactor) * scaleFactor; - - return formatResult(floorBigInt); -} - -// Round function -export function round(num: string | number): string { - 'worklet'; - const numStr = typeof num === 'number' ? num.toString() : num; - - if (!isNumberString(numStr)) { - throw new Error('Argument must be a numeric string or number'); - } - - const [bigIntNum, decimalPlaces] = removeDecimal(numStr); - const scaledBigIntNum = scaleUp(bigIntNum, decimalPlaces); - - const scaleFactor = BigInt(10) ** BigInt(SCALE_FACTOR()); - const roundBigInt = ((scaledBigIntNum + scaleFactor / BigInt(2)) / scaleFactor) * scaleFactor; - - return formatResult(roundBigInt); -} diff --git a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts.orig b/src/__swaps__/safe-math/__tests__/SafeMath.test.ts.orig deleted file mode 100644 index 47390398214..00000000000 --- a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts.orig +++ /dev/null @@ -1,294 +0,0 @@ -<<<<<<< HEAD -import { sum, sub, mul, div, mod, pow, log10, gt, lt, gte, lte, equals, toFixed, ceil, floor, round } from '../SafeMath'; -======= ->>>>>>> 0889e092afe774d0e8db6885e5962c4a8278b6cf -import BigNumber from 'bignumber.js'; -import { - divWorklet, - equalWorklet, - greaterThanOrEqualToWorklet, - greaterThanWorklet, - lessThanOrEqualToWorklet, - lessThanWorklet, - modWorklet, - mulWorklet, - powWorklet, - subWorklet, - sumWorklet, -} from '../SafeMath'; - -const RESULTS = { - sum: '1247244.585', - sub: '1239606.105', - mul: '4748939814.6378', - div: '325.56878986395199044836', - mod: '2172.345', - pow: '1546106588588.369025', - log10: '0.30102999566398124032', -}; - -const VALUE_A = '1243425.345'; -const VALUE_B = '3819.24'; -const VALUE_C = '2'; -const NEGATIVE_VALUE = '-2412.12'; -const ZERO = '0'; -const ONE = '1'; -const NON_NUMERIC_STRING = 'abc'; - -describe('SafeMath', () => { -<<<<<<< HEAD - test('sum', () => { - expect(() => sum(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => sum(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(sum(ZERO, ZERO)).toBe(ZERO); - expect(sum(VALUE_A, ZERO)).toBe(VALUE_A); - expect(sum(ZERO, VALUE_B)).toBe(VALUE_B); - expect(sum(VALUE_A, VALUE_B)).toBe(RESULTS.sum); - expect(sum(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.sum); - }); - - test('sub', () => { - expect(() => sub(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => sub(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(sub(ZERO, ZERO)).toBe(ZERO); - expect(sub(VALUE_A, ZERO)).toBe(VALUE_A); - expect(sub(ZERO, VALUE_B)).toBe(`-${VALUE_B}`); - expect(sub(VALUE_A, VALUE_B)).toBe(RESULTS.sub); - expect(sub(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.sub); - }); - - test('mul', () => { - expect(() => mul(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => mul(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(mul(ZERO, ZERO)).toBe(ZERO); - expect(mul(VALUE_A, ZERO)).toBe(ZERO); - expect(mul(ZERO, VALUE_B)).toBe(ZERO); - expect(mul(VALUE_A, VALUE_B)).toBe(RESULTS.mul); - expect(mul(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.mul); - }); - - test('div', () => { - expect(() => div(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => div(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(() => div(ZERO, ZERO)).toThrow('Division by zero'); - expect(() => div(VALUE_A, ZERO)).toThrow('Division by zero'); - expect(div(ZERO, VALUE_B)).toBe(ZERO); - expect(div(VALUE_A, VALUE_B)).toBe(RESULTS.div); - expect(div(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.div); - }); - - test('mod', () => { - expect(() => mod(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => mod(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(() => mod(ZERO, ZERO)).toThrow('Division by zero'); - expect(() => mod(VALUE_A, ZERO)).toThrow('Division by zero'); - expect(mod(ZERO, VALUE_B)).toBe(ZERO); - expect(mod(VALUE_A, VALUE_B)).toBe(RESULTS.mod); - expect(mod(Number(VALUE_A), Number(VALUE_B))).toBe(RESULTS.mod); - }); - test('pow', () => { - expect(() => pow(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => pow(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(pow(ZERO, VALUE_B)).toBe(ZERO); - expect(pow(VALUE_A, ZERO)).toBe(ONE); - expect(pow(ZERO, VALUE_B)).toBe(ZERO); - expect(pow(VALUE_A, VALUE_C)).toBe(RESULTS.pow); - expect(pow(Number(VALUE_A), Number(VALUE_C))).toBe(RESULTS.pow); - }); - test('log10', () => { - expect(() => log10(NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(() => log10(ZERO)).toThrow('Argument must be greater than 0'); - expect(log10(VALUE_C)).toBe(RESULTS.log10); - expect(log10(Number(VALUE_C))).toBe(RESULTS.log10); - }); - - test('gt', () => { - expect(gt(VALUE_A, VALUE_B)).toBe(true); - }); - - test('lt', () => { - expect(lt(VALUE_A, VALUE_B)).toBe(false); - }); - - test('gte', () => { - expect(gte(VALUE_A, VALUE_A)).toBe(true); - }); - - test('lte', () => { - expect(lte(VALUE_A, VALUE_A)).toBe(true); - }); - - test('equals', () => { - expect(equals(VALUE_A, VALUE_A)).toBe(true); - }); - - test('toFixed', () => { - expect(toFixed(VALUE_A, Number(VALUE_C))).toBe('1243425.35'); - }); - - test('ceil', () => { - expect(ceil(VALUE_A)).toBe('1243426'); - }); - - test('floor', () => { - expect(floor('1243425.345')).toBe('1243425'); - }); - - test('round', () => { - expect(round('1243425.345')).toBe('1243425'); - expect(round('1243425.745')).toBe('1243426'); -======= - test('sumWorklet', () => { - expect(() => sumWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => sumWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(sumWorklet(ZERO, ZERO)).toBe(ZERO); - expect(sumWorklet(VALUE_A, ZERO)).toBe(VALUE_A); - expect(sumWorklet(ZERO, VALUE_B)).toBe(VALUE_B); - expect(sumWorklet(VALUE_A, VALUE_B)).toBe(RESULTS.sum); - }); - - test('subWorklet', () => { - expect(() => subWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => subWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(subWorklet(ZERO, ZERO)).toBe(ZERO); - expect(subWorklet(VALUE_A, ZERO)).toBe(VALUE_A); - expect(subWorklet(ZERO, VALUE_B)).toBe(`-${VALUE_B}`); - expect(subWorklet(NEGATIVE_VALUE, ZERO)).toBe(NEGATIVE_VALUE); - expect(subWorklet(VALUE_A, VALUE_B)).toBe(RESULTS.sub); - }); - - test('mulWorklet', () => { - expect(() => mulWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => mulWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(mulWorklet(ZERO, ZERO)).toBe(ZERO); - expect(mulWorklet(VALUE_A, ZERO)).toBe(ZERO); - expect(mulWorklet(ZERO, VALUE_B)).toBe(ZERO); - expect(mulWorklet(VALUE_A, VALUE_B)).toBe(RESULTS.mul); - }); - - test('divWorklet', () => { - expect(() => divWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => divWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(() => divWorklet(ZERO, ZERO)).toThrow('Division by zero'); - expect(() => divWorklet(VALUE_A, ZERO)).toThrow('Division by zero'); - expect(divWorklet(ZERO, VALUE_B)).toBe(ZERO); - expect(divWorklet(VALUE_A, VALUE_B)).toBe(RESULTS.div); - }); - - test('modWorklet', () => { - expect(() => modWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => modWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(() => modWorklet(ZERO, ZERO)).toThrow('Division by zero'); - expect(() => modWorklet(VALUE_A, ZERO)).toThrow('Division by zero'); - expect(modWorklet(ZERO, VALUE_B)).toBe(ZERO); - expect(modWorklet(VALUE_A, VALUE_B)).toBe(RESULTS.mod); - }); - - test('powWorklet', () => { - expect(() => powWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => powWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(powWorklet(ZERO, VALUE_B)).toBe(ZERO); - expect(powWorklet(VALUE_A, ZERO)).toBe(ONE); - expect(powWorklet(ZERO, VALUE_B)).toBe(ZERO); - expect(powWorklet(VALUE_A, VALUE_C)).toBe(RESULTS.pow); - }); - - test('equalWorklet', () => { - expect(() => equalWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => equalWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(equalWorklet(ZERO, ZERO)).toBe(true); - expect(equalWorklet(VALUE_A, VALUE_A)).toBe(true); - expect(equalWorklet(VALUE_A, VALUE_B)).toBe(false); - expect(equalWorklet(NEGATIVE_VALUE, NEGATIVE_VALUE)).toBe(true); - }); - - test('greaterThanWorklet', () => { - expect(() => greaterThanWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => greaterThanWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(greaterThanWorklet(VALUE_A, VALUE_B)).toBe(true); - expect(greaterThanWorklet(VALUE_B, VALUE_A)).toBe(false); - expect(greaterThanWorklet(VALUE_A, VALUE_A)).toBe(false); - expect(greaterThanWorklet(NEGATIVE_VALUE, VALUE_A)).toBe(false); - }); - - test('greaterThanOrEqualToWorklet', () => { - expect(() => greaterThanOrEqualToWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => greaterThanOrEqualToWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(greaterThanOrEqualToWorklet(VALUE_A, VALUE_B)).toBe(true); - expect(greaterThanOrEqualToWorklet(VALUE_B, VALUE_A)).toBe(false); - expect(greaterThanOrEqualToWorklet(VALUE_A, VALUE_A)).toBe(true); - expect(greaterThanOrEqualToWorklet(NEGATIVE_VALUE, VALUE_A)).toBe(false); - }); - - test('lessThanWorklet', () => { - expect(() => lessThanWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => lessThanWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(lessThanWorklet(VALUE_A, VALUE_B)).toBe(false); - expect(lessThanWorklet(VALUE_B, VALUE_A)).toBe(true); - expect(lessThanWorklet(VALUE_A, VALUE_A)).toBe(false); - expect(lessThanWorklet(NEGATIVE_VALUE, VALUE_A)).toBe(true); - }); - - test('lessThanOrEqualToWorklet', () => { - expect(() => lessThanOrEqualToWorklet(NON_NUMERIC_STRING, VALUE_B)).toThrow('Arguments must be a numeric string'); - expect(() => lessThanOrEqualToWorklet(VALUE_A, NON_NUMERIC_STRING)).toThrow('Arguments must be a numeric string'); - expect(lessThanOrEqualToWorklet(VALUE_A, VALUE_B)).toBe(false); - expect(lessThanOrEqualToWorklet(VALUE_B, VALUE_A)).toBe(true); - expect(lessThanOrEqualToWorklet(VALUE_A, VALUE_A)).toBe(true); - expect(lessThanOrEqualToWorklet(NEGATIVE_VALUE, VALUE_A)).toBe(true); ->>>>>>> 0889e092afe774d0e8db6885e5962c4a8278b6cf - }); -}); - -describe('BigNumber', () => { - test('sum', () => { - expect(new BigNumber(VALUE_A).plus(VALUE_B).toString()).toBe(RESULTS.sum); - }); - - test('sub', () => { - expect(new BigNumber(VALUE_A).minus(VALUE_B).toString()).toBe(RESULTS.sub); - }); - - test('mul', () => { - expect(new BigNumber(VALUE_A).multipliedBy(VALUE_B).toString()).toBe(RESULTS.mul); - }); - - test('div', () => { - expect(new BigNumber(VALUE_A).dividedBy(VALUE_B).toString()).toBe(RESULTS.div); - }); - - test('mod', () => { - expect(new BigNumber(VALUE_A).mod(VALUE_B).toString()).toBe(RESULTS.mod); - }); - - test('pow', () => { - expect(new BigNumber(VALUE_A).pow(VALUE_C).toString()).toBe(RESULTS.pow); - }); - - test('equal', () => { - expect(new BigNumber(VALUE_A).eq(VALUE_B)).toBe(false); - expect(new BigNumber(VALUE_A).eq(VALUE_A)).toBe(true); - }); - - test('greaterThan', () => { - expect(new BigNumber(VALUE_A).gt(VALUE_B)).toBe(true); - expect(new BigNumber(VALUE_B).gt(VALUE_A)).toBe(false); - }); - - test('greaterThanOrEqualTo', () => { - expect(new BigNumber(VALUE_A).gte(VALUE_B)).toBe(true); - expect(new BigNumber(VALUE_B).gte(VALUE_A)).toBe(false); - expect(new BigNumber(VALUE_A).gte(VALUE_A)).toBe(true); - }); - - test('lessThan', () => { - expect(new BigNumber(VALUE_A).lt(VALUE_B)).toBe(false); - expect(new BigNumber(VALUE_B).lt(VALUE_A)).toBe(true); - }); - - test('lessThanOrEqualTo', () => { - expect(new BigNumber(VALUE_A).lte(VALUE_B)).toBe(false); - expect(new BigNumber(VALUE_B).lte(VALUE_A)).toBe(true); - expect(new BigNumber(VALUE_A).lte(VALUE_A)).toBe(true); - }); -}); From ac891a259a123471d4a227da0bbf12007134e2ef Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 28 May 2024 17:53:40 -0400 Subject: [PATCH 05/28] added SafeMath for increments --- src/__swaps__/safe-math/SafeMath.ts | 16 +++++++++++++--- .../safe-math/__tests__/SafeMath.test.ts | 1 + src/__swaps__/utils/swaps.ts | 15 +++------------ 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/__swaps__/safe-math/SafeMath.ts b/src/__swaps__/safe-math/SafeMath.ts index 4d0eb500112..ca3571910a6 100644 --- a/src/__swaps__/safe-math/SafeMath.ts +++ b/src/__swaps__/safe-math/SafeMath.ts @@ -173,10 +173,20 @@ export function powWorklet(base: string | number, exponent: string | number): st if (isZeroWorklet(exponentStr)) { return '1'; } + if (exponentStr === '1') { + return baseStr; + } + const [bigIntBase, decimalPlaces] = removeDecimalWorklet(baseStr); - const scaledBigIntBase = scaleUpWorklet(bigIntBase, decimalPlaces); - const result = scaledBigIntBase ** BigInt(exponentStr) / BigInt(10) ** BigInt(20); - return formatResultWorklet(result); + let result; + if (decimalPlaces > 0) { + const scaledBigIntBase = scaleUpWorklet(bigIntBase, decimalPlaces); + result = scaledBigIntBase ** BigInt(exponentStr) / BigInt(10) ** BigInt(20); + return formatResultWorklet(result); + } else { + result = bigIntBase ** BigInt(exponentStr); + return result.toString(); + } } // Logarithm base 10 function diff --git a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts b/src/__swaps__/safe-math/__tests__/SafeMath.test.ts index ddb291948c8..f36708903c6 100644 --- a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts +++ b/src/__swaps__/safe-math/__tests__/SafeMath.test.ts @@ -94,6 +94,7 @@ describe('SafeMath', () => { expect(powWorklet(VALUE_A, ZERO)).toBe(ONE); expect(powWorklet(ZERO, VALUE_B)).toBe(ZERO); expect(powWorklet(VALUE_A, VALUE_C)).toBe(RESULTS.pow); + expect(powWorklet(10, 4)).toBe('10000'); }); test('log10Worklet', () => { diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index 36b707fd363..0f492a745e3 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -28,7 +28,6 @@ import { roundWorklet, toFixedWorklet, } from '../safe-math/SafeMath'; -import { consoleLogWorklet } from '@/debugging/workletUtils'; // /---- 🎨 Color functions 🎨 ----/ // // @@ -149,7 +148,8 @@ export const findNiceIncrement = (availableBalance: string) => { const exactIncrement = divWorklet(availableBalance, 100); // Calculate the order of magnitude of the exact increment - const orderOfMagnitude = Math.floor(Number(log10Worklet(exactIncrement))); + const orderOfMagnitude = floorWorklet(log10Worklet(exactIncrement)); + const baseIncrement = powWorklet(10, orderOfMagnitude); let adjustedIncrement = baseIncrement; @@ -162,9 +162,9 @@ export const findNiceIncrement = (availableBalance: string) => { break; } } - return adjustedIncrement; }; + // // /---- END JS utils ----/ // @@ -306,15 +306,10 @@ export function niceIncrementFormatter({ roundingMode: 'up', }); - consoleLogWorklet('niceIncrement:' + niceIncrement); const exactIncrement = divWorklet(inputAssetBalance, 100); - consoleLogWorklet('exactIncrement:' + exactIncrement); const isIncrementExact = equalWorklet(niceIncrement, exactIncrement); - consoleLogWorklet('isIncrementExact:' + isIncrementExact); const numberOfIncrements = divWorklet(inputAssetBalance, niceIncrement); - consoleLogWorklet('numberOfIncrements:' + numberOfIncrements); const incrementStep = divWorklet(1, numberOfIncrements); - consoleLogWorklet('numberOfIncrements:' + numberOfIncrements); const percentage = isIncrementExact ? percentageToSwap : Math.round( @@ -322,13 +317,9 @@ export function niceIncrementFormatter({ Number(divWorklet(1, incrementStep)) ); - consoleLogWorklet('percentage:' + percentage); - const rawAmount = mulWorklet(Math.round(Number(divWorklet(mulWorklet(percentage, inputAssetBalance), niceIncrement))), niceIncrement); - consoleLogWorklet('rawAmount:' + rawAmount); const amountToFixedDecimals = toFixedWorklet(rawAmount, incrementDecimalPlaces); - consoleLogWorklet('amountToFixedDecimals:' + amountToFixedDecimals); const formattedAmount = `${Number(amountToFixedDecimals).toLocaleString('en-US', { useGrouping: true, From 02b155ecf44835c457df5c8165915cfb49751a46 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 28 May 2024 18:17:26 -0400 Subject: [PATCH 06/28] fix --- src/__swaps__/utils/swaps.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index 0f492a745e3..fc86cc666fc 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -317,7 +317,7 @@ export function niceIncrementFormatter({ Number(divWorklet(1, incrementStep)) ); - const rawAmount = mulWorklet(Math.round(Number(divWorklet(mulWorklet(percentage, inputAssetBalance), niceIncrement))), niceIncrement); + const rawAmount = mulWorklet(roundWorklet(divWorklet(mulWorklet(percentage, inputAssetBalance), niceIncrement)), niceIncrement); const amountToFixedDecimals = toFixedWorklet(rawAmount, incrementDecimalPlaces); From 15f9e9323ef3f3b165ac3848d893abc340d5a32e Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Wed, 29 May 2024 17:54:24 -0400 Subject: [PATCH 07/28] useSwapInputsController --- src/__swaps__/safe-math/SafeMath.ts | 8 ++++ .../Swap/hooks/useSwapInputsController.ts | 42 ++++++++++--------- src/__swaps__/utils/swaps.ts | 11 +++-- 3 files changed, 37 insertions(+), 24 deletions(-) diff --git a/src/__swaps__/safe-math/SafeMath.ts b/src/__swaps__/safe-math/SafeMath.ts index ca3571910a6..e8eb3442e6e 100644 --- a/src/__swaps__/safe-math/SafeMath.ts +++ b/src/__swaps__/safe-math/SafeMath.ts @@ -363,3 +363,11 @@ export function roundWorklet(num: string | number): string { return formatResultWorklet(roundBigInt); } + +export function minWorklet(numA: string | number, numB: string | number) { + return lessThanOrEqualToWorklet(numA, numB) ? numA : numB; +} + +export function maxWorklet(numA: string | number, numB: string | number) { + return greaterThanOrEqualToWorklet(numA, numB) ? numA : numB; +} diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index 10d62026005..2bc3873bf8d 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -31,6 +31,7 @@ import { } from '@/resources/assets/externalAssetsQuery'; import { ethereumUtils } from '@/utils'; import { queryClient } from '@/react-query'; +import { divWorklet, equalWorklet, greaterThanWorklet, mulWorklet } from '@/__swaps__/safe-math/SafeMath'; export function useSwapInputsController({ focusedInput, @@ -64,7 +65,8 @@ export function useSwapInputsController({ const inputMethod = useSharedValue('slider'); const percentageToSwap = useDerivedValue(() => { - return Math.round(clamp((sliderXPosition.value - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1) * 100) / 100; + const clampResult = Number(clamp((sliderXPosition.value - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1)); + return Math.round(clampResult * 100) / 100; }); const niceIncrement = useDerivedValue(() => { @@ -95,7 +97,7 @@ export function useSwapInputsController({ }); } - const balance = Number(internalSelectedInputAsset.value?.balance.amount || 0); + const balance = internalSelectedInputAsset.value?.balance.amount || 0; return niceIncrementFormatter({ incrementDecimalPlaces: incrementDecimalPlaces.value, @@ -183,8 +185,8 @@ export function useSwapInputsController({ if (inputAmount === 0) { sliderXPosition.value = withSpring(0, snappySpringConfig); } else { - const inputBalance = Number(internalSelectedInputAsset.value?.balance.amount || '0'); - const updatedSliderPosition = clamp((inputAmount / inputBalance) * SLIDER_WIDTH, 0, SLIDER_WIDTH); + const inputBalance = internalSelectedInputAsset.value?.balance.amount || '0'; + const updatedSliderPosition = Number(clamp(mulWorklet(divWorklet(inputAmount, inputBalance), SLIDER_WIDTH), 0, SLIDER_WIDTH)); if (Number.isNaN(updatedSliderPosition)) { sliderXPosition.value = withSpring(0, snappySpringConfig); } else { @@ -418,7 +420,8 @@ export function useSwapInputsController({ // reset the quote data immediately, so we don't use stale data setQuote({ data: null }); - const isSomeInputGreaterThanZero = Number(inputValues.value.inputAmount) > 0 || Number(inputValues.value.outputAmount) > 0; + const isSomeInputGreaterThanZero = + greaterThanWorklet(inputValues.value.inputAmount, 0) || greaterThanWorklet(inputValues.value.outputAmount, 0); // If both inputs are 0 or the assets aren't set, return early if (!internalSelectedInputAsset.value || !internalSelectedOutputAsset.value || !isSomeInputGreaterThanZero) { @@ -471,7 +474,7 @@ export function useSwapInputsController({ // if the user types in the inputAmount let's optimistically update the slider position if (inputKey === 'inputAmount') { const inputAssetBalance = Number(internalSelectedInputAsset.value?.balance.amount || '0'); - const updatedSliderPosition = clamp((amount / inputAssetBalance) * SLIDER_WIDTH, 0, SLIDER_WIDTH); + const updatedSliderPosition = Number(clamp((amount / inputAssetBalance) * SLIDER_WIDTH, 0, SLIDER_WIDTH)); // Update slider position sliderXPosition.value = withSpring(updatedSliderPosition, snappySpringConfig); @@ -525,7 +528,7 @@ export function useSwapInputsController({ (current, previous) => { if (previous && current !== previous && typeof inputValues.value[previous.focusedInput] === 'string') { const typedValue = inputValues.value[previous.focusedInput].toString(); - if (Number(typedValue) === 0) { + if (equalWorklet(typedValue, 0)) { inputValues.modify(values => { return { ...values, @@ -581,7 +584,7 @@ export function useSwapInputsController({ sliderXPosition: sliderXPosition.value, stripSeparators: true, }); - const inputNativeValue = Number(inputAmount) * internalSelectedInputAsset.value?.nativePrice; + const inputNativeValue = mulWorklet(inputAmount, internalSelectedInputAsset.value?.nativePrice); inputValues.modify(values => { return { ...values, @@ -613,9 +616,9 @@ export function useSwapInputsController({ stripSeparators: true, }); - const inputNativeValue = Number(inputAmount) * current.assetToSell.nativePrice; - const outputAmount = (inputNativeValue / current.assetToBuy.nativePrice) * (1 - SWAP_FEE); // TODO: Implement swap fee - const outputNativeValue = outputAmount * current.assetToBuy.nativePrice; + const inputNativeValue = mulWorklet(inputAmount, current.assetToSell.nativePrice); + const outputAmount = mulWorklet(divWorklet(inputNativeValue, current.assetToBuy.nativePrice), 1 - SWAP_FEE); // TODO: Implement swap fee + const outputNativeValue = mulWorklet(outputAmount, current.assetToBuy.nativePrice); inputValues.modify(values => { return { @@ -671,7 +674,7 @@ export function useSwapInputsController({ sliderXPosition: sliderXPosition.value, stripSeparators: true, }); - const inputNativeValue = Number(inputAmount) * current.assetToSell.nativePrice; + const inputNativeValue = mulWorklet(inputAmount, current.assetToSell.nativePrice); inputValues.modify(values => { return { ...values, @@ -683,9 +686,9 @@ export function useSwapInputsController({ isQuoteStale.value = 1; } } - if (inputMethod.value === 'inputAmount' && Number(current.values.inputAmount) !== Number(previous.values.inputAmount)) { + if (inputMethod.value === 'inputAmount' && !equalWorklet(current.values.inputAmount, previous.values.inputAmount)) { // If the number in the input field changes - if (Number(current.values.inputAmount) === 0) { + if (equalWorklet(current.values.inputAmount, 0)) { // If the input amount was set to 0 const hasDecimal = current.values.inputAmount.toString().includes('.'); @@ -707,7 +710,7 @@ export function useSwapInputsController({ } else { if (!current.assetToSell || !current.assetToSell?.nativePrice) return; // If the input amount was set to a non-zero value - const inputNativeValue = Number(current.values.inputAmount) * current.assetToSell.nativePrice; + const inputNativeValue = mulWorklet(current.values.inputAmount, current.assetToSell.nativePrice); inputValues.modify(values => { return { ...values, @@ -718,9 +721,9 @@ export function useSwapInputsController({ runOnJS(onTypedNumber)(Number(current.values.inputAmount), 'inputAmount', true); } } - if (inputMethod.value === 'outputAmount' && Number(current.values.outputAmount) !== Number(previous.values.outputAmount)) { + if (inputMethod.value === 'outputAmount' && !equalWorklet(current.values.outputAmount, previous.values.outputAmount)) { // If the number in the output field changes - if (Number(current.values.outputAmount) === 0) { + if (equalWorklet(current.values.outputAmount, 0)) { // If the output amount was set to 0 const hasDecimal = current.values.outputAmount.toString().includes('.'); @@ -743,12 +746,11 @@ export function useSwapInputsController({ } else { runOnJS(onTypedNumber)(0, 'outputAmount'); } - } else if (Number(current.values.outputAmount) > 0) { + } else if (greaterThanWorklet(current.values.outputAmount, 0)) { // If the output amount was set to a non-zero value if (!current.assetToBuy?.nativePrice) return; - const outputAmount = Number(current.values.outputAmount); - const outputNativeValue = outputAmount * current.assetToBuy.nativePrice; + const outputNativeValue = mulWorklet(current.values.outputAmount, current.assetToBuy.nativePrice); inputValues.modify(values => { return { diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index 00e9190118c..c47c25ec317 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -27,6 +27,9 @@ import { powWorklet, roundWorklet, toFixedWorklet, + greaterThanOrEqualToWorklet, + minWorklet, + maxWorklet, } from '../safe-math/SafeMath'; // /---- 🎨 Color functions 🎨 ----/ // @@ -187,7 +190,7 @@ export function addCommasToNumber(number: string | number) { return numberString; } - if (Number(number) >= 1000) { + if (greaterThanOrEqualToWorklet(number, 1000)) { const parts = numberString.split('.'); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); return parts.join('.'); @@ -196,9 +199,9 @@ export function addCommasToNumber(number: string | number) { } } -export function clamp(value: number, lowerBound: number, upperBound: number) { +export function clamp(value: number | string, lowerBound: number | string, upperBound: number | string) { 'worklet'; - return Math.min(Math.max(lowerBound, value), upperBound); + return minWorklet(maxWorklet(lowerBound, value), upperBound); } export function stripCommas(value: string) { @@ -322,7 +325,7 @@ export function niceIncrementFormatter({ const percentage = isIncrementExact ? percentageToSwap : Math.round( - (clamp((sliderXPosition - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1) * Number(divWorklet(1, incrementStep))) / + (Number(clamp((sliderXPosition - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1)) * Number(divWorklet(1, incrementStep))) / Number(divWorklet(1, incrementStep)) ); From 8bfb3c5a2b36157fae38c2c09f25f0132a285049 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Wed, 29 May 2024 17:57:00 -0400 Subject: [PATCH 08/28] useSwapTextStyles --- .../screens/Swap/hooks/useSwapTextStyles.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/__swaps__/screens/Swap/hooks/useSwapTextStyles.ts b/src/__swaps__/screens/Swap/hooks/useSwapTextStyles.ts index 4cffda6fdca..192737763cf 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapTextStyles.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapTextStyles.ts @@ -24,6 +24,7 @@ import { import { inputKeys, inputMethods } from '@/__swaps__/types/swap'; import { getColorValueForThemeWorklet, opacity } from '@/__swaps__/utils/swaps'; import { ExtendedAnimatedAssetWithColors } from '@/__swaps__/types/assets'; +import { equalWorklet } from '@/__swaps__/safe-math/SafeMath'; export function useSwapTextStyles({ inputMethod, @@ -79,12 +80,12 @@ export function useSwapTextStyles({ const isZero = !internalSelectedInputAsset.value || (inputValues.value.inputAmount === 0 && inputMethod.value !== 'slider') || - (inputMethod.value === 'slider' && Number(inputValues.value.inputAmount) === 0); + (inputMethod.value === 'slider' && equalWorklet(inputValues.value.inputAmount, 0)); return isZero; }); const isOutputZero = useDerivedValue(() => { - const isZero = !internalSelectedOutputAsset.value || inputValues.value.outputAmount === 0; + const isZero = !internalSelectedOutputAsset.value || equalWorklet(inputValues.value.outputAmount, 0); return isZero; }); @@ -163,7 +164,7 @@ export function useSwapTextStyles({ inputProgress.value === 0 && outputProgress.value === 0 && (inputMethod.value !== 'slider' || - (inputMethod.value === 'slider' && Number(inputValues.value.inputAmount) === 0) || + (inputMethod.value === 'slider' && equalWorklet(inputValues.value.inputAmount, 0)) || (sliderPressProgress.value === SLIDER_COLLAPSED_HEIGHT / SLIDER_HEIGHT && isQuoteStale.value === 0)); const opacity = shouldShow @@ -181,7 +182,7 @@ export function useSwapTextStyles({ const isZero = (inputMethod.value !== 'slider' && inputValues.value.inputAmount === 0) || - (inputMethod.value === 'slider' && Number(inputValues.value.inputAmount) === 0); + (inputMethod.value === 'slider' && equalWorklet(inputValues.value.inputAmount, 0)); return { display: shouldShow ? 'flex' : 'none', @@ -196,7 +197,7 @@ export function useSwapTextStyles({ inputProgress.value === 0 && outputProgress.value === 0 && (inputMethod.value !== 'slider' || - (inputMethod.value === 'slider' && Number(inputValues.value.inputAmount) === 0) || + (inputMethod.value === 'slider' && equalWorklet(inputValues.value.inputAmount, 0)) || (sliderPressProgress.value === SLIDER_COLLAPSED_HEIGHT / SLIDER_HEIGHT && isQuoteStale.value === 0)); const opacity = shouldShow @@ -214,7 +215,7 @@ export function useSwapTextStyles({ const isZero = (inputMethod.value !== 'slider' && inputValues.value.outputAmount === 0) || - (inputMethod.value === 'slider' && Number(inputValues.value.inputAmount) === 0); + (inputMethod.value === 'slider' && equalWorklet(inputValues.value.inputAmount, 0)); return { display: shouldShow ? 'flex' : 'none', From 1a1f73ab893f54bf9cb71cb1f821bf273ad8f3a6 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Wed, 29 May 2024 17:58:43 -0400 Subject: [PATCH 09/28] swapProvider --- .../screens/Swap/providers/swap-provider.tsx | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/__swaps__/screens/Swap/providers/swap-provider.tsx b/src/__swaps__/screens/Swap/providers/swap-provider.tsx index d54ddc4f660..5f4cc40d77e 100644 --- a/src/__swaps__/screens/Swap/providers/swap-provider.tsx +++ b/src/__swaps__/screens/Swap/providers/swap-provider.tsx @@ -25,6 +25,7 @@ import { useSharedValue, } from 'react-native-reanimated'; import { useSwapSettings } from '../hooks/useSwapSettings'; +import { equalWorklet } from '@/__swaps__/safe-math/SafeMath'; interface SwapContextType { isFetching: SharedValue; @@ -255,8 +256,8 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { return ''; } - const isInputZero = Number(SwapInputController.inputValues.value.inputAmount) === 0; - const isOutputZero = Number(SwapInputController.inputValues.value.outputAmount) === 0; + const isInputZero = equalWorklet(SwapInputController.inputValues.value.inputAmount, 0); + const isOutputZero = equalWorklet(SwapInputController.inputValues.value.outputAmount, 0); if (SwapInputController.inputMethod.value !== 'slider' && (isInputZero || isOutputZero) && !isFetching.value) { return ''; @@ -278,8 +279,8 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { return 'Fetching prices'; } - const isInputZero = Number(SwapInputController.inputValues.value.inputAmount) === 0; - const isOutputZero = Number(SwapInputController.inputValues.value.outputAmount) === 0; + const isInputZero = equalWorklet(SwapInputController.inputValues.value.inputAmount, 0); + const isOutputZero = equalWorklet(SwapInputController.inputValues.value.outputAmount, 0); if (SwapInputController.inputMethod.value !== 'slider' && (isInputZero || isOutputZero) && !isFetching.value) { return 'Enter Amount'; @@ -294,8 +295,8 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { }); const confirmButtonIconStyle = useAnimatedStyle(() => { - const isInputZero = Number(SwapInputController.inputValues.value.inputAmount) === 0; - const isOutputZero = Number(SwapInputController.inputValues.value.outputAmount) === 0; + const isInputZero = equalWorklet(SwapInputController.inputValues.value.inputAmount, 0); + const isOutputZero = equalWorklet(SwapInputController.inputValues.value.outputAmount, 0); const sliderCondition = SwapInputController.inputMethod.value === 'slider' && From 773ccd0277103ccafa1aa81b7be8a37aff96b9d6 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Wed, 29 May 2024 18:15:55 -0400 Subject: [PATCH 10/28] missing worklet declaration --- src/__swaps__/safe-math/SafeMath.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/__swaps__/safe-math/SafeMath.ts b/src/__swaps__/safe-math/SafeMath.ts index e8eb3442e6e..dfc18c72841 100644 --- a/src/__swaps__/safe-math/SafeMath.ts +++ b/src/__swaps__/safe-math/SafeMath.ts @@ -365,9 +365,11 @@ export function roundWorklet(num: string | number): string { } export function minWorklet(numA: string | number, numB: string | number) { + 'worklet'; return lessThanOrEqualToWorklet(numA, numB) ? numA : numB; } export function maxWorklet(numA: string | number, numB: string | number) { + 'worklet'; return greaterThanOrEqualToWorklet(numA, numB) ? numA : numB; } From 4a29b001876797b3e53d696a080e454f85d13fa5 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Wed, 29 May 2024 18:40:06 -0400 Subject: [PATCH 11/28] clean up numbers --- src/__swaps__/utils/numbers.ts | 95 ---------------------------------- 1 file changed, 95 deletions(-) diff --git a/src/__swaps__/utils/numbers.ts b/src/__swaps__/utils/numbers.ts index 04fb8be2836..8cf984850e2 100644 --- a/src/__swaps__/utils/numbers.ts +++ b/src/__swaps__/utils/numbers.ts @@ -138,12 +138,6 @@ export const convertStringToNumber = (value: BigNumberish) => new BigNumber(valu export const lessThan = (numberOne: BigNumberish, numberTwo: BigNumberish): boolean => new BigNumber(numberOne).lt(numberTwo); -export const lessThanWorklet = (numberOne: BigNumberish, numberTwo: BigNumberish): boolean => { - 'worklet'; - - return new BigNumber(numberOne).lt(numberTwo); -}; - export const lessOrEqualThan = (numberOne: BigNumberish, numberTwo: BigNumberish): boolean => new BigNumber(numberOne).lt(numberTwo) || new BigNumber(numberOne).eq(numberTwo); @@ -165,21 +159,6 @@ export const handleSignificantDecimals = (value: BigNumberish, decimals: number, return resultBN.dp() <= 2 ? resultBN.toFormat(skipDecimals ? 0 : 2) : resultBN.toFormat(); }; -export const handleSignificantDecimalsWorklet = (value: BigNumberish, decimals: number, buffer = 3, skipDecimals = false): string => { - 'worklet'; - - let dec; - if (lessThanWorklet(new BigNumber(value).abs(), 1)) { - dec = new BigNumber(value).toFixed()?.slice?.(2).search(/[^0]/g) + buffer; - dec = Math.min(decimals, 8); - } else { - dec = Math.min(decimals, buffer); - } - const result = new BigNumber(new BigNumber(value).toFixed(dec)).toFixed(); - const resultBN = new BigNumber(result); - return resultBN.dp() <= 2 ? resultBN.toFormat(skipDecimals ? 0 : 2) : resultBN.toFormat(); -}; - export const handleSignificantDecimalsAsNumber = (value: BigNumberish, decimals: number): string => { return new BigNumber(new BigNumber(multiply(value, new BigNumber(10).pow(decimals))).toFixed(0)) .dividedBy(new BigNumber(10).pow(decimals)) @@ -191,15 +170,6 @@ export const handleSignificantDecimalsAsNumber = (value: BigNumberish, decimals: */ export const convertAmountToNativeAmount = (amount: BigNumberish, priceUnit: BigNumberish): string => multiply(amount, priceUnit); -/** - * @desc convert from asset BigNumber amount to native price BigNumber amount - */ -export const convertAmountToNativeAmountWorklet = (amount: BigNumberish, priceUnit: BigNumberish): string => { - 'worklet'; - - return multiply(amount, priceUnit); -}; - /** * @desc convert from amount to display formatted string */ @@ -218,26 +188,6 @@ export const convertAmountAndPriceToNativeDisplay = ( }; }; -/** - * @desc convert from amount to display formatted string - */ -export const convertAmountAndPriceToNativeDisplayWorklet = ( - amount: BigNumberish, - priceUnit: BigNumberish, - nativeCurrency: keyof nativeCurrencyType, - buffer?: number, - skipDecimals = false -): { amount: string; display: string } => { - 'worklet'; - - const nativeBalanceRaw = convertAmountToNativeAmountWorklet(amount, priceUnit); - const nativeDisplay = convertAmountToNativeDisplayWorklet(nativeBalanceRaw, nativeCurrency, buffer, skipDecimals); - return { - amount: nativeBalanceRaw, - display: nativeDisplay, - }; -}; - export const convertAmountAndPriceToNativeDisplayWithThreshold = ( amount: BigNumberish, priceUnit: BigNumberish, @@ -266,23 +216,6 @@ export const convertRawAmountToNativeDisplay = ( return ret; }; -/** - * @desc convert from raw amount to display formatted string - */ -export const convertRawAmountToNativeDisplayWorklet = ( - rawAmount: BigNumberish, - assetDecimals: number, - priceUnit: BigNumberish, - nativeCurrency: keyof nativeCurrencyType, - buffer?: number -) => { - 'worklet'; - - const assetBalance = convertRawAmountToDecimalFormatWorklet(rawAmount, assetDecimals); - const ret = convertAmountAndPriceToNativeDisplayWorklet(assetBalance, priceUnit, nativeCurrency, buffer); - return ret; -}; - /** * @desc convert from raw amount to balance object */ @@ -352,26 +285,6 @@ export const convertAmountToNativeDisplay = ( return `${display} ${nativeSelected.symbol}`; }; -/** - * @desc convert from amount value to display formatted string - */ -export const convertAmountToNativeDisplayWorklet = ( - value: BigNumberish, - nativeCurrency: keyof nativeCurrencyType, - buffer?: number, - skipDecimals?: boolean -) => { - 'worklet'; - - const nativeSelected = supportedNativeCurrencies?.[nativeCurrency]; - const { decimals } = nativeSelected; - const display = handleSignificantDecimalsWorklet(value, decimals, buffer, skipDecimals); - if (nativeSelected.alignment === 'left') { - return `${nativeSelected.symbol}${display}`; - } - return `${display} ${nativeSelected.symbol}`; -}; - export const convertAmountToNativeDisplayWithThreshold = (value: BigNumberish, nativeCurrency: keyof nativeCurrencyType) => { const nativeSelected = supportedNativeCurrencies?.[nativeCurrency]; const display = handleSignificantDecimalsWithThreshold(value, nativeSelected.decimals, nativeSelected.decimals < 4 ? '0.01' : '0.0001'); @@ -387,14 +300,6 @@ export const convertAmountToNativeDisplayWithThreshold = (value: BigNumberish, n export const convertRawAmountToDecimalFormat = (value: BigNumberish, decimals = 18): string => new BigNumber(value).dividedBy(new BigNumber(10).pow(decimals)).toFixed(); -/** - * @desc convert from raw amount to decimal format - */ -export const convertRawAmountToDecimalFormatWorklet = (value: BigNumberish, decimals = 18): string => { - 'worklet'; - return new BigNumber(value).dividedBy(new BigNumber(10).pow(decimals)).toFixed(); -}; - /** * @desc convert from decimal format to raw amount */ From b6ea8ea0666a1aa45c01ddf8266c1db50d80ba22 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 18:23:39 -0400 Subject: [PATCH 12/28] add logs --- src/__swaps__/utils/swaps.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index c47c25ec317..6121658b197 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -31,6 +31,7 @@ import { minWorklet, maxWorklet, } from '../safe-math/SafeMath'; +import { consoleLogWorklet } from '@/debugging/workletUtils'; // /---- 🎨 Color functions 🎨 ----/ // // @@ -341,6 +342,15 @@ export function niceIncrementFormatter({ if (stripSeparators) return stripCommas(formattedAmount); + consoleLogWorklet('niceIncrementFormatter::exactIncrement: ' + exactIncrement); + consoleLogWorklet('niceIncrementFormatter::isIncrementExact: ' + isIncrementExact); + consoleLogWorklet('niceIncrementFormatter::numberOfIncrements: ' + numberOfIncrements); + consoleLogWorklet('niceIncrementFormatter::incrementStep: ' + incrementStep); + consoleLogWorklet('niceIncrementFormatter::percentage: ' + percentage); + consoleLogWorklet('niceIncrementFormatter::rawAmount: ' + rawAmount); + consoleLogWorklet('niceIncrementFormatter::amountToFixedDecimals: ' + amountToFixedDecimals); + consoleLogWorklet('niceIncrementFormatter::formattedAmount: ' + formattedAmount); + return formattedAmount; } From 08ab49fa22984019e762ed469b1e6e6b5912712c Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 18:40:04 -0400 Subject: [PATCH 13/28] logs --- src/__swaps__/utils/swaps.ts | 21 ++++++++++++--------- src/handlers/web3.ts | 32 ++++++++++++++++---------------- 2 files changed, 28 insertions(+), 25 deletions(-) diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index 6121658b197..7475bbbd163 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -290,6 +290,7 @@ export function niceIncrementFormatter({ stripSeparators?: boolean; }) { 'worklet'; + console.log('niceIncrementFormatter::percentageToSwap: ' + percentageToSwap); if (percentageToSwap === 0) return '0'; if (percentageToSwap === 0.25) return valueBasedDecimalFormatter({ @@ -319,6 +320,8 @@ export function niceIncrementFormatter({ roundingMode: 'up', }); + console.log('niceIncrementFormatter:: time for calculations'); + const exactIncrement = divWorklet(inputAssetBalance, 100); const isIncrementExact = equalWorklet(niceIncrement, exactIncrement); const numberOfIncrements = divWorklet(inputAssetBalance, niceIncrement); @@ -340,16 +343,16 @@ export function niceIncrementFormatter({ maximumFractionDigits: 8, })}`; - if (stripSeparators) return stripCommas(formattedAmount); + console.log('niceIncrementFormatter::exactIncrement: ' + exactIncrement); + console.log('niceIncrementFormatter::isIncrementExact: ' + isIncrementExact); + console.log('niceIncrementFormatter::numberOfIncrements: ' + numberOfIncrements); + console.log('niceIncrementFormatter::incrementStep: ' + incrementStep); + console.log('niceIncrementFormatter::percentage: ' + percentage); + console.log('niceIncrementFormatter::rawAmount: ' + rawAmount); + console.log('niceIncrementFormatter::amountToFixedDecimals: ' + amountToFixedDecimals); + console.log('niceIncrementFormatter::formattedAmount: ' + formattedAmount); - consoleLogWorklet('niceIncrementFormatter::exactIncrement: ' + exactIncrement); - consoleLogWorklet('niceIncrementFormatter::isIncrementExact: ' + isIncrementExact); - consoleLogWorklet('niceIncrementFormatter::numberOfIncrements: ' + numberOfIncrements); - consoleLogWorklet('niceIncrementFormatter::incrementStep: ' + incrementStep); - consoleLogWorklet('niceIncrementFormatter::percentage: ' + percentage); - consoleLogWorklet('niceIncrementFormatter::rawAmount: ' + rawAmount); - consoleLogWorklet('niceIncrementFormatter::amountToFixedDecimals: ' + amountToFixedDecimals); - consoleLogWorklet('niceIncrementFormatter::formattedAmount: ' + formattedAmount); + if (stripSeparators) return stripCommas(formattedAmount); return formattedAmount; } diff --git a/src/handlers/web3.ts b/src/handlers/web3.ts index 5b05dcd8775..284c862d033 100644 --- a/src/handlers/web3.ts +++ b/src/handlers/web3.ts @@ -383,16 +383,16 @@ export async function estimateGasWithPadding( const code = to ? await p.getCode(to) : undefined; // 2 - if it's not a contract AND it doesn't have any data use the default gas limit if ((!contractCallEstimateGas && !to) || (to && !data && (!code || code === '0x'))) { - logger.info('⛽ Skipping estimates, using default', { - ethUnits: ethUnits.basic_tx.toString(), - }); + //logger.info('⛽ Skipping estimates, using default', { + // ethUnits: ethUnits.basic_tx.toString(), + // }); return ethUnits.basic_tx.toString(); } - logger.info('⛽ Calculating safer gas limit for last block'); + // logger.info('⛽ Calculating safer gas limit for last block'); // 3 - If it is a contract, call the RPC method `estimateGas` with a safe value const saferGasLimit = fraction(gasLimit.toString(), 19, 20); - logger.info('⛽ safer gas limit for last block is', { saferGasLimit }); + // logger.info('⛽ safer gas limit for last block is', { saferGasLimit }); txPayloadToEstimate[contractCallEstimateGas ? 'gasLimit' : 'gas'] = toHex(saferGasLimit); @@ -404,27 +404,27 @@ export async function estimateGasWithPadding( const lastBlockGasLimit = addBuffer(gasLimit.toString(), 0.9); const paddedGas = addBuffer(estimatedGas.toString(), paddingFactor.toString()); - logger.info('⛽ GAS CALCULATIONS!', { - estimatedGas: estimatedGas.toString(), - gasLimit: gasLimit.toString(), - lastBlockGasLimit: lastBlockGasLimit, - paddedGas: paddedGas, - }); + // logger.info('⛽ GAS CALCULATIONS!', { + // estimatedGas: estimatedGas.toString(), + // gasLimit: gasLimit.toString(), + // lastBlockGasLimit: lastBlockGasLimit, + // paddedGas: paddedGas, + // }); // If the safe estimation is above the last block gas limit, use it if (greaterThan(estimatedGas.toString(), lastBlockGasLimit)) { - logger.info('⛽ returning orginal gas estimation', { - esimatedGas: estimatedGas.toString(), - }); + // logger.info('⛽ returning orginal gas estimation', { + // esimatedGas: estimatedGas.toString(), + // }); return estimatedGas.toString(); } // If the estimation is below the last block gas limit, use the padded estimate if (greaterThan(lastBlockGasLimit, paddedGas)) { - logger.info('⛽ returning padded gas estimation', { paddedGas }); + // logger.info('⛽ returning padded gas estimation', { paddedGas }); return paddedGas; } // otherwise default to the last block gas limit - logger.info('⛽ returning last block gas limit', { lastBlockGasLimit }); + // logger.info('⛽ returning last block gas limit', { lastBlockGasLimit }); return lastBlockGasLimit; } catch (e: any) { /* From bd7d5a1e79dbbea3f11256b566da542a4374504b Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 18:56:52 -0400 Subject: [PATCH 14/28] fix wrong calculations for increments --- src/__swaps__/utils/swaps.ts | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index 7475bbbd163..099e1c0165a 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -31,7 +31,6 @@ import { minWorklet, maxWorklet, } from '../safe-math/SafeMath'; -import { consoleLogWorklet } from '@/debugging/workletUtils'; // /---- 🎨 Color functions 🎨 ----/ // // @@ -290,7 +289,6 @@ export function niceIncrementFormatter({ stripSeparators?: boolean; }) { 'worklet'; - console.log('niceIncrementFormatter::percentageToSwap: ' + percentageToSwap); if (percentageToSwap === 0) return '0'; if (percentageToSwap === 0.25) return valueBasedDecimalFormatter({ @@ -320,17 +318,17 @@ export function niceIncrementFormatter({ roundingMode: 'up', }); - console.log('niceIncrementFormatter:: time for calculations'); - const exactIncrement = divWorklet(inputAssetBalance, 100); const isIncrementExact = equalWorklet(niceIncrement, exactIncrement); const numberOfIncrements = divWorklet(inputAssetBalance, niceIncrement); const incrementStep = divWorklet(1, numberOfIncrements); const percentage = isIncrementExact ? percentageToSwap - : Math.round( - (Number(clamp((sliderXPosition - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1)) * Number(divWorklet(1, incrementStep))) / - Number(divWorklet(1, incrementStep)) + : divWorklet( + roundWorklet( + mulWorklet(clamp((sliderXPosition - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1), divWorklet(1, incrementStep)) + ), + divWorklet(1, incrementStep) ); const rawAmount = mulWorklet(roundWorklet(divWorklet(mulWorklet(percentage, inputAssetBalance), niceIncrement)), niceIncrement); @@ -343,15 +341,6 @@ export function niceIncrementFormatter({ maximumFractionDigits: 8, })}`; - console.log('niceIncrementFormatter::exactIncrement: ' + exactIncrement); - console.log('niceIncrementFormatter::isIncrementExact: ' + isIncrementExact); - console.log('niceIncrementFormatter::numberOfIncrements: ' + numberOfIncrements); - console.log('niceIncrementFormatter::incrementStep: ' + incrementStep); - console.log('niceIncrementFormatter::percentage: ' + percentage); - console.log('niceIncrementFormatter::rawAmount: ' + rawAmount); - console.log('niceIncrementFormatter::amountToFixedDecimals: ' + amountToFixedDecimals); - console.log('niceIncrementFormatter::formattedAmount: ' + formattedAmount); - if (stripSeparators) return stripCommas(formattedAmount); return formattedAmount; From ec4e022b81d94847c484c583c0c8a3ebee3dbc62 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 19:01:39 -0400 Subject: [PATCH 15/28] parse to number percentages --- .../screens/Swap/components/SwapSlider.tsx | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/__swaps__/screens/Swap/components/SwapSlider.tsx b/src/__swaps__/screens/Swap/components/SwapSlider.tsx index e96c1e0b478..1878c860ae2 100644 --- a/src/__swaps__/screens/Swap/components/SwapSlider.tsx +++ b/src/__swaps__/screens/Swap/components/SwapSlider.tsx @@ -107,11 +107,11 @@ export const SwapSlider = ({ // This is a hacky way to prevent the slider from shifting when it reaches the right limit const uiXPercentage = useDerivedValue(() => { - return xPercentage.value * (1 - SCRUBBER_WIDTH / width); + return Number(xPercentage.value) * (1 - SCRUBBER_WIDTH / width); }, [xPercentage.value]); const percentageText = useDerivedValue(() => { - return `${Math.round((xPercentage.value ?? initialPercentage) * 100)}%`; + return `${Math.round(Number(xPercentage.value ?? initialPercentage) * 100)}%`; }, [xPercentage.value]); useAnimatedReaction( @@ -166,11 +166,11 @@ export const SwapSlider = ({ return adjustedMovement; }; - if (ctx.startX === width && clamp(rawX, 0, width) >= width * 0.995) { + if (ctx.startX === width && Number(clamp(rawX, 0, width)) >= width * 0.995) { isQuoteStale.value = 0; } - sliderXPosition.value = clamp(rawX, 0, width); + sliderXPosition.value = Number(clamp(rawX, 0, width)); // Handle slider overscroll if (rawX < 0 || rawX > width) { @@ -187,17 +187,17 @@ export const SwapSlider = ({ onFinish: (event, ctx: { startX: number }) => { const onFinished = () => { overshoot.value = withSpring(0, sliderConfig); - if (xPercentage.value >= 0.995) { + if (Number(xPercentage.value) >= 0.995) { if (isQuoteStale.value === 1) { runOnJS(onChangeWrapper)(1); } sliderXPosition.value = withSpring(width, snappySpringConfig); - } else if (xPercentage.value < 0.005) { + } else if (Number(xPercentage.value) < 0.005) { runOnJS(onChangeWrapper)(0); sliderXPosition.value = withSpring(0, snappySpringConfig); // SwapInputController.isQuoteStale.value = 0; } else { - runOnJS(onChangeWrapper)(xPercentage.value); + runOnJS(onChangeWrapper)(Number(xPercentage.value)); } }; @@ -303,7 +303,7 @@ export const SwapSlider = ({ springConfig ), borderWidth: interpolate( - xPercentage.value, + Number(xPercentage.value), [0, (THICK_BORDER_WIDTH * 2) / width, (THICK_BORDER_WIDTH * 4) / width, 1], [0, 0, THICK_BORDER_WIDTH, THICK_BORDER_WIDTH], 'clamp' @@ -315,7 +315,7 @@ export const SwapSlider = ({ const rightBarContainerStyle = useAnimatedStyle(() => { return { borderWidth: interpolate( - xPercentage.value, + Number(xPercentage.value), [0, 1 - (THICK_BORDER_WIDTH * 4) / width, 1 - (THICK_BORDER_WIDTH * 2) / width, 1], [THICK_BORDER_WIDTH, THICK_BORDER_WIDTH, 0, 0], 'clamp' @@ -347,7 +347,7 @@ export const SwapSlider = ({ isStale, [0, 1], [ - (SwapInputController.inputMethod.value === 'slider' ? xPercentage.value < 0.005 : sliderXPosition.value === 0) + (SwapInputController.inputMethod.value === 'slider' ? Number(xPercentage.value) < 0.005 : sliderXPosition.value === 0) ? zeroAmountColor : labelSecondary, zeroAmountColor, From 6156f557a0095db03fc71bea2362f16d60255cd9 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 19:12:14 -0400 Subject: [PATCH 16/28] revert clamp conversion --- src/__swaps__/screens/Swap/components/SwapSlider.tsx | 4 ++-- .../screens/Swap/hooks/useSwapInputsController.ts | 7 +++---- src/__swaps__/utils/swaps.ts | 4 ++-- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/__swaps__/screens/Swap/components/SwapSlider.tsx b/src/__swaps__/screens/Swap/components/SwapSlider.tsx index 1878c860ae2..31bef35d1d3 100644 --- a/src/__swaps__/screens/Swap/components/SwapSlider.tsx +++ b/src/__swaps__/screens/Swap/components/SwapSlider.tsx @@ -166,11 +166,11 @@ export const SwapSlider = ({ return adjustedMovement; }; - if (ctx.startX === width && Number(clamp(rawX, 0, width)) >= width * 0.995) { + if (ctx.startX === width && clamp(rawX, 0, width) >= width * 0.995) { isQuoteStale.value = 0; } - sliderXPosition.value = Number(clamp(rawX, 0, width)); + sliderXPosition.value = clamp(rawX, 0, width); // Handle slider overscroll if (rawX < 0 || rawX > width) { diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index 2bc3873bf8d..1f9682aa902 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -65,8 +65,7 @@ export function useSwapInputsController({ const inputMethod = useSharedValue('slider'); const percentageToSwap = useDerivedValue(() => { - const clampResult = Number(clamp((sliderXPosition.value - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1)); - return Math.round(clampResult * 100) / 100; + return Math.round(clamp((sliderXPosition.value - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1) * 100) / 100; }); const niceIncrement = useDerivedValue(() => { @@ -186,7 +185,7 @@ export function useSwapInputsController({ sliderXPosition.value = withSpring(0, snappySpringConfig); } else { const inputBalance = internalSelectedInputAsset.value?.balance.amount || '0'; - const updatedSliderPosition = Number(clamp(mulWorklet(divWorklet(inputAmount, inputBalance), SLIDER_WIDTH), 0, SLIDER_WIDTH)); + const updatedSliderPosition = clamp(Number(mulWorklet(divWorklet(inputAmount, inputBalance), SLIDER_WIDTH)), 0, SLIDER_WIDTH); if (Number.isNaN(updatedSliderPosition)) { sliderXPosition.value = withSpring(0, snappySpringConfig); } else { @@ -474,7 +473,7 @@ export function useSwapInputsController({ // if the user types in the inputAmount let's optimistically update the slider position if (inputKey === 'inputAmount') { const inputAssetBalance = Number(internalSelectedInputAsset.value?.balance.amount || '0'); - const updatedSliderPosition = Number(clamp((amount / inputAssetBalance) * SLIDER_WIDTH, 0, SLIDER_WIDTH)); + const updatedSliderPosition = clamp(Number(divWorklet(amount, inputAssetBalance)) * SLIDER_WIDTH, 0, SLIDER_WIDTH); // Update slider position sliderXPosition.value = withSpring(updatedSliderPosition, snappySpringConfig); diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index 099e1c0165a..b71bef27205 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -199,9 +199,9 @@ export function addCommasToNumber(number: string | number) { } } -export function clamp(value: number | string, lowerBound: number | string, upperBound: number | string) { +export function clamp(value: number, lowerBound: number, upperBound: number) { 'worklet'; - return minWorklet(maxWorklet(lowerBound, value), upperBound); + return Math.min(Math.max(lowerBound, value), upperBound); } export function stripCommas(value: string) { From 61a3744b01f8f1c543270113f4a14ff0a4d4f558 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 19:15:41 -0400 Subject: [PATCH 17/28] clean up --- src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index 1f9682aa902..67756126452 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -208,7 +208,7 @@ export function useSwapInputsController({ return { ...prev, inputAmount, - inputNativeValue: inputAmount * price, + inputNativeValue: mulWorklet(inputAmount, price), }; }); } @@ -219,7 +219,7 @@ export function useSwapInputsController({ return { ...prev, outputAmount, - outputNativeValue: outputAmount * price, + outputNativeValue: mulWorklet(outputAmount, price), }; }); } From f868e3e053facb3296d535f1363311eb0c10b07e Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 23:09:47 -0400 Subject: [PATCH 18/28] final fixes for formatting functions --- src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts | 5 ++--- src/__swaps__/utils/swaps.ts | 2 -- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index 67756126452..fb7bbadb642 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -113,7 +113,7 @@ export function useSwapInputsController({ return '$0.00'; } - const nativeValue = `$${inputValues.value.inputNativeValue.toLocaleString('en-US', { + const nativeValue = `$${parseFloat(inputValues.value.inputNativeValue.toString()).toLocaleString('en-US', { useGrouping: true, minimumFractionDigits: 2, maximumFractionDigits: 2, @@ -148,12 +148,11 @@ export function useSwapInputsController({ return '$0.00'; } - const nativeValue = `$${inputValues.value.outputNativeValue.toLocaleString('en-US', { + const nativeValue = `$${parseFloat(inputValues.value.outputNativeValue.toString()).toLocaleString('en-US', { useGrouping: true, minimumFractionDigits: 2, maximumFractionDigits: 2, })}`; - return nativeValue || '$0.00'; }); diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index b71bef27205..d77ce3beef3 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -28,8 +28,6 @@ import { roundWorklet, toFixedWorklet, greaterThanOrEqualToWorklet, - minWorklet, - maxWorklet, } from '../safe-math/SafeMath'; // /---- 🎨 Color functions 🎨 ----/ // From b84caa3eee7e5b2ba6195a226f9bf90eef573409 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 23:11:57 -0400 Subject: [PATCH 19/28] revert casting --- .../screens/Swap/components/SwapSlider.tsx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/__swaps__/screens/Swap/components/SwapSlider.tsx b/src/__swaps__/screens/Swap/components/SwapSlider.tsx index 31bef35d1d3..9b1b5ae6424 100644 --- a/src/__swaps__/screens/Swap/components/SwapSlider.tsx +++ b/src/__swaps__/screens/Swap/components/SwapSlider.tsx @@ -107,11 +107,11 @@ export const SwapSlider = ({ // This is a hacky way to prevent the slider from shifting when it reaches the right limit const uiXPercentage = useDerivedValue(() => { - return Number(xPercentage.value) * (1 - SCRUBBER_WIDTH / width); + return xPercentage.value * (1 - SCRUBBER_WIDTH / width); }, [xPercentage.value]); const percentageText = useDerivedValue(() => { - return `${Math.round(Number(xPercentage.value ?? initialPercentage) * 100)}%`; + return `${Math.round(xPercentage.value ?? initialPercentage * 100)}%`; }, [xPercentage.value]); useAnimatedReaction( @@ -187,17 +187,17 @@ export const SwapSlider = ({ onFinish: (event, ctx: { startX: number }) => { const onFinished = () => { overshoot.value = withSpring(0, sliderConfig); - if (Number(xPercentage.value) >= 0.995) { + if (xPercentage.value >= 0.995) { if (isQuoteStale.value === 1) { runOnJS(onChangeWrapper)(1); } sliderXPosition.value = withSpring(width, snappySpringConfig); - } else if (Number(xPercentage.value) < 0.005) { + } else if (xPercentage.value < 0.005) { runOnJS(onChangeWrapper)(0); sliderXPosition.value = withSpring(0, snappySpringConfig); // SwapInputController.isQuoteStale.value = 0; } else { - runOnJS(onChangeWrapper)(Number(xPercentage.value)); + runOnJS(onChangeWrapper)(xPercentage.value); } }; @@ -303,7 +303,7 @@ export const SwapSlider = ({ springConfig ), borderWidth: interpolate( - Number(xPercentage.value), + xPercentage.value, [0, (THICK_BORDER_WIDTH * 2) / width, (THICK_BORDER_WIDTH * 4) / width, 1], [0, 0, THICK_BORDER_WIDTH, THICK_BORDER_WIDTH], 'clamp' @@ -315,7 +315,7 @@ export const SwapSlider = ({ const rightBarContainerStyle = useAnimatedStyle(() => { return { borderWidth: interpolate( - Number(xPercentage.value), + xPercentage.value, [0, 1 - (THICK_BORDER_WIDTH * 4) / width, 1 - (THICK_BORDER_WIDTH * 2) / width, 1], [THICK_BORDER_WIDTH, THICK_BORDER_WIDTH, 0, 0], 'clamp' @@ -347,7 +347,7 @@ export const SwapSlider = ({ isStale, [0, 1], [ - (SwapInputController.inputMethod.value === 'slider' ? Number(xPercentage.value) < 0.005 : sliderXPosition.value === 0) + (SwapInputController.inputMethod.value === 'slider' ? xPercentage.value < 0.005 : sliderXPosition.value === 0) ? zeroAmountColor : labelSecondary, zeroAmountColor, From 2fd2663d918cc23f8a74fc761543fce07ce9c72f Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 23:15:22 -0400 Subject: [PATCH 20/28] more clean up --- src/__swaps__/screens/Swap/components/SwapSlider.tsx | 2 +- src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/__swaps__/screens/Swap/components/SwapSlider.tsx b/src/__swaps__/screens/Swap/components/SwapSlider.tsx index 9b1b5ae6424..e96c1e0b478 100644 --- a/src/__swaps__/screens/Swap/components/SwapSlider.tsx +++ b/src/__swaps__/screens/Swap/components/SwapSlider.tsx @@ -111,7 +111,7 @@ export const SwapSlider = ({ }, [xPercentage.value]); const percentageText = useDerivedValue(() => { - return `${Math.round(xPercentage.value ?? initialPercentage * 100)}%`; + return `${Math.round((xPercentage.value ?? initialPercentage) * 100)}%`; }, [xPercentage.value]); useAnimatedReaction( diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index fb7bbadb642..cae850083ae 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -113,7 +113,7 @@ export function useSwapInputsController({ return '$0.00'; } - const nativeValue = `$${parseFloat(inputValues.value.inputNativeValue.toString()).toLocaleString('en-US', { + const nativeValue = `$${Number(inputValues.value.inputNativeValue).toLocaleString('en-US', { useGrouping: true, minimumFractionDigits: 2, maximumFractionDigits: 2, @@ -148,7 +148,7 @@ export function useSwapInputsController({ return '$0.00'; } - const nativeValue = `$${parseFloat(inputValues.value.outputNativeValue.toString()).toLocaleString('en-US', { + const nativeValue = `$${Number(inputValues.value.outputNativeValue).toLocaleString('en-US', { useGrouping: true, minimumFractionDigits: 2, maximumFractionDigits: 2, From fced72a16cb9bb5ce9a9d7d4294149b61ccebf6b Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Thu, 30 May 2024 23:29:58 -0400 Subject: [PATCH 21/28] add logs back --- src/handlers/web3.ts | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/handlers/web3.ts b/src/handlers/web3.ts index 284c862d033..5b05dcd8775 100644 --- a/src/handlers/web3.ts +++ b/src/handlers/web3.ts @@ -383,16 +383,16 @@ export async function estimateGasWithPadding( const code = to ? await p.getCode(to) : undefined; // 2 - if it's not a contract AND it doesn't have any data use the default gas limit if ((!contractCallEstimateGas && !to) || (to && !data && (!code || code === '0x'))) { - //logger.info('⛽ Skipping estimates, using default', { - // ethUnits: ethUnits.basic_tx.toString(), - // }); + logger.info('⛽ Skipping estimates, using default', { + ethUnits: ethUnits.basic_tx.toString(), + }); return ethUnits.basic_tx.toString(); } - // logger.info('⛽ Calculating safer gas limit for last block'); + logger.info('⛽ Calculating safer gas limit for last block'); // 3 - If it is a contract, call the RPC method `estimateGas` with a safe value const saferGasLimit = fraction(gasLimit.toString(), 19, 20); - // logger.info('⛽ safer gas limit for last block is', { saferGasLimit }); + logger.info('⛽ safer gas limit for last block is', { saferGasLimit }); txPayloadToEstimate[contractCallEstimateGas ? 'gasLimit' : 'gas'] = toHex(saferGasLimit); @@ -404,27 +404,27 @@ export async function estimateGasWithPadding( const lastBlockGasLimit = addBuffer(gasLimit.toString(), 0.9); const paddedGas = addBuffer(estimatedGas.toString(), paddingFactor.toString()); - // logger.info('⛽ GAS CALCULATIONS!', { - // estimatedGas: estimatedGas.toString(), - // gasLimit: gasLimit.toString(), - // lastBlockGasLimit: lastBlockGasLimit, - // paddedGas: paddedGas, - // }); + logger.info('⛽ GAS CALCULATIONS!', { + estimatedGas: estimatedGas.toString(), + gasLimit: gasLimit.toString(), + lastBlockGasLimit: lastBlockGasLimit, + paddedGas: paddedGas, + }); // If the safe estimation is above the last block gas limit, use it if (greaterThan(estimatedGas.toString(), lastBlockGasLimit)) { - // logger.info('⛽ returning orginal gas estimation', { - // esimatedGas: estimatedGas.toString(), - // }); + logger.info('⛽ returning orginal gas estimation', { + esimatedGas: estimatedGas.toString(), + }); return estimatedGas.toString(); } // If the estimation is below the last block gas limit, use the padded estimate if (greaterThan(lastBlockGasLimit, paddedGas)) { - // logger.info('⛽ returning padded gas estimation', { paddedGas }); + logger.info('⛽ returning padded gas estimation', { paddedGas }); return paddedGas; } // otherwise default to the last block gas limit - // logger.info('⛽ returning last block gas limit', { lastBlockGasLimit }); + logger.info('⛽ returning last block gas limit', { lastBlockGasLimit }); return lastBlockGasLimit; } catch (e: any) { /* From 832f927b2a05fcdd04d9b88c5aa0b83ce2efe7cc Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Fri, 31 May 2024 21:22:52 -0400 Subject: [PATCH 22/28] fix types --- src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts | 2 +- src/__swaps__/utils/swaps.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index 32f2a75eb73..16726bc2285 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -35,7 +35,7 @@ import { userAssetsStore } from '@/state/assets/userAssets'; function getInitialInputValues() { const initialSelectedInputAsset = userAssetsStore.getState().getHighestValueAsset(); const initialBalance = initialSelectedInputAsset?.balance.amount ?? 0; - const initialNiceIncrement = findNiceIncrement(initialBalance.toString()); + const initialNiceIncrement = findNiceIncrement(initialBalance); const initialDecimalPlaces = countDecimalPlaces(initialNiceIncrement); const initialInputAmount = niceIncrementFormatter({ diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index d1c886727eb..d6eb1bb25e1 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -146,7 +146,7 @@ export const countDecimalPlaces = (number: number | string): number => { return 0; }; -export const findNiceIncrement = (availableBalance: string) => { +export const findNiceIncrement = (availableBalance: string | number) => { 'worklet'; // We'll use one of these factors to adjust the base increment From 7ee09e6a7928bf8a3a1d3a40c1725136050300d7 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 4 Jun 2024 14:03:33 -0400 Subject: [PATCH 23/28] support negative exponents --- src/__swaps__/safe-math/SafeMath.ts | 8 +++++++- src/__swaps__/safe-math/__tests__/SafeMath.test.ts | 5 +++++ src/__swaps__/utils/swaps.ts | 2 ++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/__swaps__/safe-math/SafeMath.ts b/src/__swaps__/safe-math/SafeMath.ts index cffe166e82d..a5e204253d8 100644 --- a/src/__swaps__/safe-math/SafeMath.ts +++ b/src/__swaps__/safe-math/SafeMath.ts @@ -1,3 +1,5 @@ +import { lessThan } from '@/helpers/utilities'; + // Utility function to remove the decimal point and keep track of the number of decimal places const removeDecimalWorklet = (num: string): [bigint, number] => { 'worklet'; @@ -21,7 +23,7 @@ const isZeroWorklet = (value: string): boolean => { }; // Utility function to scale the number up to 20 decimal places -const scaleUpWorklet = (bigIntNum: bigint, decimalPlaces: number): bigint => { +export const scaleUpWorklet = (bigIntNum: bigint, decimalPlaces: number): bigint => { 'worklet'; const scaleFactor = BigInt(10) ** BigInt(20); return (bigIntNum * scaleFactor) / BigInt(10) ** BigInt(decimalPlaces); @@ -190,6 +192,10 @@ export function powWorklet(base: string | number, exponent: string | number): st return baseStr; } + if (lessThan(exponentStr, 0)) { + return divWorklet(1, powWorklet(base, Math.abs(Number(exponent)))); + } + const [bigIntBase, decimalPlaces] = removeDecimalWorklet(baseStr); let result; if (decimalPlaces > 0) { diff --git a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts b/src/__swaps__/safe-math/__tests__/SafeMath.test.ts index 634d159d41f..60933f3fb98 100644 --- a/src/__swaps__/safe-math/__tests__/SafeMath.test.ts +++ b/src/__swaps__/safe-math/__tests__/SafeMath.test.ts @@ -31,6 +31,7 @@ const RESULTS = { ceil: '1243426', floor: '1243425', toScaledInteger: '57464009350560633', + negativePow: '0.001', }; const VALUE_A = '1243425.345'; @@ -38,9 +39,12 @@ const VALUE_B = '3819.24'; const VALUE_C = '2'; const VALUE_D = '1243425.745'; const VALUE_E = '0.057464009350560633'; +const VALUE_F = '0.001'; const NEGATIVE_VALUE = '-2412.12'; const ZERO = '0'; const ONE = '1'; +const TEN = '10'; +const MINUS_3 = '-3'; const NON_NUMERIC_STRING = 'abc'; describe('SafeMath', () => { @@ -108,6 +112,7 @@ describe('SafeMath', () => { expect(powWorklet(VALUE_A, VALUE_C)).toBe(RESULTS.pow); expect(powWorklet(Number(VALUE_A), VALUE_C)).toBe(RESULTS.pow); expect(powWorklet(VALUE_A, Number(VALUE_C))).toBe(RESULTS.pow); + expect(powWorklet(TEN, Number(MINUS_3))).toBe(RESULTS.negativePow); }); test('log10Worklet', () => { diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index d6eb1bb25e1..eed3b3bfee8 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -29,6 +29,8 @@ import { roundWorklet, toFixedWorklet, greaterThanOrEqualToWorklet, + greaterThanWorklet, + scaleUpWorklet, } from '../safe-math/SafeMath'; // /---- 🎨 Color functions 🎨 ----/ // From d5cea1a62d20b2dc2b6b423334126e5ea63c1740 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 4 Jun 2024 14:09:24 -0400 Subject: [PATCH 24/28] fix import --- src/__swaps__/safe-math/SafeMath.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/__swaps__/safe-math/SafeMath.ts b/src/__swaps__/safe-math/SafeMath.ts index a5e204253d8..c32c41a7c56 100644 --- a/src/__swaps__/safe-math/SafeMath.ts +++ b/src/__swaps__/safe-math/SafeMath.ts @@ -1,5 +1,3 @@ -import { lessThan } from '@/helpers/utilities'; - // Utility function to remove the decimal point and keep track of the number of decimal places const removeDecimalWorklet = (num: string): [bigint, number] => { 'worklet'; @@ -192,7 +190,7 @@ export function powWorklet(base: string | number, exponent: string | number): st return baseStr; } - if (lessThan(exponentStr, 0)) { + if (lessThanWorklet(exponentStr, 0)) { return divWorklet(1, powWorklet(base, Math.abs(Number(exponent)))); } From 48e7ae1604822138113fbf9f23d1e89a5665ef04 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 4 Jun 2024 14:13:03 -0400 Subject: [PATCH 25/28] reorder --- src/__swaps__/safe-math/SafeMath.ts | 70 ++++++++++++++--------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/src/__swaps__/safe-math/SafeMath.ts b/src/__swaps__/safe-math/SafeMath.ts index c32c41a7c56..be161c34fcf 100644 --- a/src/__swaps__/safe-math/SafeMath.ts +++ b/src/__swaps__/safe-math/SafeMath.ts @@ -171,41 +171,6 @@ export function modWorklet(num1: string | number, num2: string | number): string return formatResultWorklet(result); } -// Power function -export function powWorklet(base: string | number, exponent: string | number): string { - 'worklet'; - const baseStr = toStringWorklet(base); - const exponentStr = toStringWorklet(exponent); - - if (!isNumberStringWorklet(baseStr) || !isNumberStringWorklet(exponentStr)) { - throw new Error('Arguments must be a numeric string or number'); - } - if (isZeroWorklet(baseStr)) { - return '0'; - } - if (isZeroWorklet(exponentStr)) { - return '1'; - } - if (exponentStr === '1') { - return baseStr; - } - - if (lessThanWorklet(exponentStr, 0)) { - return divWorklet(1, powWorklet(base, Math.abs(Number(exponent)))); - } - - const [bigIntBase, decimalPlaces] = removeDecimalWorklet(baseStr); - let result; - if (decimalPlaces > 0) { - const scaledBigIntBase = scaleUpWorklet(bigIntBase, decimalPlaces); - result = scaledBigIntBase ** BigInt(exponentStr) / BigInt(10) ** BigInt(20); - return formatResultWorklet(result); - } else { - result = bigIntBase ** BigInt(exponentStr); - return result.toString(); - } -} - // Logarithm base 10 function export function log10Worklet(num: string | number): string { 'worklet'; @@ -305,6 +270,41 @@ export function lessThanOrEqualToWorklet(num1: string | number, num2: string | n return scaledBigInt1 <= scaledBigInt2; } +// Power function +export function powWorklet(base: string | number, exponent: string | number): string { + 'worklet'; + const baseStr = toStringWorklet(base); + const exponentStr = toStringWorklet(exponent); + + if (!isNumberStringWorklet(baseStr) || !isNumberStringWorklet(exponentStr)) { + throw new Error('Arguments must be a numeric string or number'); + } + if (isZeroWorklet(baseStr)) { + return '0'; + } + if (isZeroWorklet(exponentStr)) { + return '1'; + } + if (exponentStr === '1') { + return baseStr; + } + + if (lessThanWorklet(exponentStr, 0)) { + return divWorklet(1, powWorklet(base, Math.abs(Number(exponent)))); + } + + const [bigIntBase, decimalPlaces] = removeDecimalWorklet(baseStr); + let result; + if (decimalPlaces > 0) { + const scaledBigIntBase = scaleUpWorklet(bigIntBase, decimalPlaces); + result = scaledBigIntBase ** BigInt(exponentStr) / BigInt(10) ** BigInt(20); + return formatResultWorklet(result); + } else { + result = bigIntBase ** BigInt(exponentStr); + return result.toString(); + } +} + // toFixed function export function toFixedWorklet(num: string | number, decimalPlaces: number): string { 'worklet'; From 083a97f5a4e4bae2a626c22ac5b86f960563036a Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 4 Jun 2024 14:50:12 -0400 Subject: [PATCH 26/28] remove old imports --- src/__swaps__/utils/swaps.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index eed3b3bfee8..d6eb1bb25e1 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -29,8 +29,6 @@ import { roundWorklet, toFixedWorklet, greaterThanOrEqualToWorklet, - greaterThanWorklet, - scaleUpWorklet, } from '../safe-math/SafeMath'; // /---- 🎨 Color functions 🎨 ----/ // From 76abf6d35873cfc2f588b1d45615405835e145d0 Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 4 Jun 2024 15:45:51 -0400 Subject: [PATCH 27/28] fix types --- src/__swaps__/utils/swaps.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index 3a8b4949c4a..dc57412ed99 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -29,6 +29,7 @@ import { roundWorklet, toFixedWorklet, greaterThanOrEqualToWorklet, + sumWorklet, } from '../safe-math/SafeMath'; // /---- 🎨 Color functions 🎨 ----/ // @@ -234,8 +235,8 @@ export function valueBasedDecimalFormatter({ }): string { 'worklet'; - function precisionBasedOffMagnitude(amount: number): number { - const magnitude = -Math.floor(Math.log10(amount) + 1); + function precisionBasedOffMagnitude(amount: number | string): number { + const magnitude = -Number(floorWorklet(sumWorklet(log10Worklet(amount), 1))); return (precisionAdjustment ?? 0) + magnitude; } From 99a3d9639f93ca22886e5d0cf0fd2ba54a82b2bc Mon Sep 17 00:00:00 2001 From: Bruno Barbieri Date: Tue, 4 Jun 2024 17:24:48 -0400 Subject: [PATCH 28/28] remove import --- src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index beb2f6567dc..f1aa2851d3d 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -30,7 +30,6 @@ import { import { ethereumUtils } from '@/utils'; import { queryClient } from '@/react-query'; import { divWorklet, equalWorklet, greaterThanWorklet, mulWorklet, toFixedWorklet } from '@/__swaps__/safe-math/SafeMath'; -import { userAssetsStore } from '@/state/assets/userAssets'; function getInitialInputValues(initialSelectedInputAsset: ExtendedAnimatedAssetWithColors | null) { const initialBalance = Number(initialSelectedInputAsset?.balance.amount) ?? 0;