From d62b0a4fc964b8e0ab6ddeadeb806a6421e25f94 Mon Sep 17 00:00:00 2001 From: teefeh-07 Date: Wed, 30 Apr 2025 20:20:51 +0100 Subject: [PATCH 1/4] code for stacks --- Mathematics/contracts/mlib.clar | 319 +++++++++++++++++++++++++++++++- 1 file changed, 309 insertions(+), 10 deletions(-) diff --git a/Mathematics/contracts/mlib.clar b/Mathematics/contracts/mlib.clar index fdbde04..6e72eba 100644 --- a/Mathematics/contracts/mlib.clar +++ b/Mathematics/contracts/mlib.clar @@ -1,15 +1,314 @@ +;; Enhanced Math Library for Stacks Blockchain +;; Version 2.0 +;; This library provides comprehensive math operations with safety checks +;; All functions return (ok value) on success and (err error-message) on failure -;; mlib -;; +;; ------ BASIC ARITHMETIC OPERATIONS ------ -;; constants -;; +;; Addition Function with overflow check +(define-read-only (add (a int) (b int)) + (let ((result (+ a b))) + (if (or + (and (> a 0) (> b 0) (< result a)) + (and (< a 0) (< b 0) (> result a))) + (err u"Overflow occurred in addition") + (ok result)))) -;; data maps and vars -;; +;; Subtraction Function with underflow check +(define-read-only (subtract (a int) (b int)) + (let ((result (- a b))) + (if (or + (and (> a 0) (< b 0) (< result a)) + (and (< a 0) (> b 0) (> result a))) + (err u"Underflow occurred in subtraction") + (ok result)))) -;; private functions -;; +;; Multiplication Function with overflow check +(define-read-only (multiply (a int) (b int)) + (let ((result (* a b))) + (if (or (is-eq a 0) (is-eq b 0)) + (ok 0) + (if (and (> a 0) (> b 0) (< result a)) + (err u"Overflow occurred in multiplication") + (if (and (< a 0) (< b 0) (> result a)) + (err u"Overflow occurred in multiplication") + (if (and (> a 0) (< b 0) (> result a)) + (err u"Overflow occurred in multiplication") + (if (and (< a 0) (> b 0) (< result a)) + (err u"Overflow occurred in multiplication") + (if (is-eq (/ result a) b) + (ok result) + (err u"Overflow occurred in multiplication"))))))))) -;; public functions -;; +;; Division Function with error handling +(define-read-only (divide (a int) (b int)) + (if (is-eq b 0) + (err u"Cannot divide by zero") + (ok (/ a b)))) + +;; Integer Division Function that returns whole quotient only +(define-read-only (div-integer (a int) (b int)) + (if (is-eq b 0) + (err u"Cannot divide by zero") + (ok (/ a b)))) + +;; ------ MODULAR ARITHMETIC ------ + +;; Modular Function (renamed to avoid conflict with built-in 'mod' function) +(define-read-only (modular (a int) (b int)) + (if (is-eq b 0) + (err u"Cannot perform modulo by zero") + (ok (mod a b)))) + +;; Modular Exponentiation (a^b mod m) - Efficient power calculation with modulo +;; (define-read-only (mod-power (base int) (exponent uint) (modulus int)) +;; (if (is-eq modulus 0) +;; (err u"Cannot perform modulo by zero") +;; (ok (mod-power-internal base exponent modulus 1)))) + +;; Helper function for modular exponentiation using binary exponentiation +;; (define-private (mod-power-internal (base int) (exponent uint) (modulus int) (result int)) +;; (if (is-eq exponent u0) +;; result +;; (let ((next-result (if (is-eq (mod exponent 2) 1) +;; (mod (* result base) modulus) +;; result)) +;; (next-base (mod (* base base) modulus)) +;; (next-exponent (/ exponent u2))) +;; (mod-power-internal next-base next-exponent modulus next-result)))) + +;; ------ BASIC MATH FUNCTIONS ------ + +;; Square Function +(define-read-only (square (a int)) + (multiply a a)) + +;; Power Function (a^n) - Integer exponentiation +;; (define-read-only (power (base int) (exponent uint)) +;; (power-internal base exponent 1)) + +;; ;; Helper function for power calculation +;; ;; Power Function (a^n) - Integer exponentiation +;; (define-read-only (power (base int) (exponent uint)) +;; (ok (power-internal base exponent 1))) + +;; ;; Helper function for power calculation +;; (define-private (power-internal (base int) (exponent uint) (result int)) +;; (cond +;; ((is-eq exponent u0) result) +;; ((is-eq (mod exponent 2) 1) +;; (power-internal (* base base) (/ exponent u2) (* result base))) +;; (true (power-internal (* base base) (/ exponent u2) result)))) +;; (ok a) + +;; Sign Function (-1 for negative, 0 for zero, 1 for positive) +;; (define-read-only (sign (a int)) +;; (cond +;; ((< a 0) (ok -1)) +;; ((> a 0) (ok 1)) +;; (true (ok 0)))) + +;; ------ AGGREGATE OPERATIONS ------ + +;; Average Function with overflow protection +(define-read-only (average (a int) (b int)) + (match (add a b) + sum (ok (/ sum 2)) + error (err error))) + +;; Weighted Average (a*weight_a + b*weight_b)/(weight_a + weight_b) +;; (define-read-only (weighted-average (a int) (weight-a uint) (b int) (weight-b uint)) +;; (begin +;; (if (and (is-eq weight-a u0) (is-eq weight-b u0)) +;; (err u"Both weights cannot be zero") +;; ;; Weighted Average (a*weight_a + b*weight_b)/(weight_a + weight_b) +;; (define-read-only (weighted-average (a int) (weight-a uint) (b int) (weight-b uint)) +;; (if (and (is-eq weight-a u0) (is-eq weight-b u0)) +;; (err u"Both weights cannot be zero") +;; (let +;; ( +;; (prod-a (match (multiply a (unwrap-panic (to-int weight-a))) +;; success success +;; error (err error))) +;; (prod-b (match (multiply b (unwrap-panic (to-int weight-b))) +;; success success +;; error (err error))) +;; ) +;; (match prod-a +;; success-a +;; (match prod-b +;; success-b +;; (match (add success-a success-b) +;; sum (ok (/ sum (unwrap-panic (to-int (+ weight-a weight-b))))) +;; error (err error)) +;; error-b (err error-b)) +;; error-a (err error-a))))) +;; Minimum Function +(define-read-only (minimum (a int) (b int)) + (ok (if (<= a b) a b))) + +;; ------ NUMERIC PROPERTY FUNCTIONS ------ + +;; Is Even Function +(define-read-only (is-even (a int)) + (ok (is-eq (mod a 2) 0))) + +;; Is Odd Function +(define-read-only (is-odd (a int)) + (ok (is-eq (mod a 2) 1))) + +;; Is Positive Function +(define-read-only (is-positive (a int)) + (ok (> a 0))) + +;; Is Negative Function +(define-read-only (is-negative (a int)) + (ok (< a 0))) + +;; Is Zero Function +(define-read-only (is-zero (a int)) + (ok (is-eq a 0))) + +;; ------ CONVERSION FUNCTIONS ------ + +;; Integer to uint conversion with validation +(define-read-only (to-uint (a int)) + (if (>= a 0) + (ok (unwrap-panic (to-uint a))) + (err u"Cannot convert negative number to uint"))) +;; Integer to uint conversion with validation +(define-read-only (to-uint (a int)) + (if (>= a 0) + (ok (unwrap-panic (to-uint a))) + (err u"Cannot convert negative number to uint"))) + +;; Uint to int conversion (always safe) +(define-read-only (to-int (a uint)) + (ok (unwrap-panic (to-int a)))) +(define-constant FIXED-POINT-FACTOR 1000000) + +;; Convert integer to fixed-point representation +(define-read-only (to-fixed-point (a int)) + (multiply a FIXED-POINT-FACTOR)) + +;; Multiply two fixed-point numbers +(define-read-only (fixed-multiply (a int) (b int)) + (match (multiply a b) + product (ok (/ product FIXED-POINT-FACTOR)) + error (err error))) + +;; Divide two fixed-point numbers +(define-read-only (fixed-divide (a int) (b int)) + (if (is-eq b 0) + (err u"Cannot divide by zero") + (match (multiply a FIXED-POINT-FACTOR) + product (ok (/ product b)) + error (err error)))) + +;; Square root approximation for fixed-point numbers using Newton's method +;; Returns result with 6 decimal places precision +(define-public (sqrt (x int)) + (begin + (asserts! (>= x 0) (err u"Cannot calculate square root of negative number")) +;; Square root approximation for fixed-point numbers using Newton's method +;; Returns result with 6 decimal places precision +(define-read-only (sqrt (x int)) + (if (< x 0) + (err u"Cannot calculate square root of negative number") + (if (is-eq x 0) + (ok 0) + (ok (sqrt-newton x (/ (+ x 1) 2) 10))))) ;; 10 iterations for good precision + +;; Helper function for Newton's method of square root approximation +(define-private (sqrt-newton (x int) (guess int) (iterations int)) + (if (is-eq iterations 0) + guess + (let ((new-guess (/ (+ guess (/ x guess)) 2))) + (sqrt-newton x new-guess (- iterations 1))))) + +;; Sine approximation using Taylor series (fixed-point result) +(define-read-only (sin (angle-rad int)) + (let + ((normalized-angle (mod angle-rad (* 2 FIXED-POINT-FACTOR 314159 10)))) ;; Normalize to [0, 2) + (match (add + normalized-angle + (match (multiply + (multiply + (multiply normalized-angle normalized-angle) + normalized-angle) + (/ -1 (* 6 FIXED-POINT-FACTOR))) + term (ok term) + error (err error))) + result (ok result) + error (err error)))) + +;; Cosine approximation using Taylor series (fixed-point result) +(define-read-only (cos (angle-rad int)) + (let + ((normalized-angle (mod angle-rad (* 2 FIXED-POINT-FACTOR 314159 10)))) ;; Normalize to [0, 2) + (match (add + FIXED-POINT-FACTOR + (match (multiply + (multiply normalized-angle normalized-angle) + (/ -1 (* 2 FIXED-POINT-FACTOR))) + term (ok term) + error (err error))) + result (ok result) + error (err error)))) + +;; ------ UTILITY FUNCTIONS ------ + +;; Greatest Common Divisor (GCD) using Euclidean algorithm +(define-read-only (gcd (a int) (b int)) + (match (absolute a) + abs-a (match (absolute b) + abs-b (ok (gcd-internal abs-a abs-b)) + error (err error)) + error (err error))) + +;; Helper function for GCD calculation +(define-private (gcd-internal (a int) (b int)) + (if (is-eq b 0) + a + (gcd-internal b (mod a b)))) + +;; Least Common Multiple (LCM) +(define-read-only (lcm (a int) (b int)) + (match (absolute a) + abs-a (match (absolute b) + abs-b (if (or (is-eq abs-a 0) (is-eq abs-b 0)) + (ok 0) + (match (multiply abs-a abs-b) + product (ok (/ product (gcd-internal abs-a abs-b))) + error (err error))) + error (err error)) + error (err error))) + +;; Factorial function (n!) +(define-read-only (factorial (n uint)) + (if (> n u20) ;; Limit to prevent overflow + (err u"Input too large for factorial calculation") + (ok (factorial-internal n)))) +;; Factorial function (n!) +(define-read-only (factorial (n uint)) + (if (> n u20) ;; Limit to prevent overflow + (err u"Input too large for factorial calculation") + (ok (factorial-internal n 1)))) + +;; Helper function for factorial calculation (tail-recursive) +(define-private (factorial-internal (n uint) (acc int)) + (if (<= n u1) + acc + (factorial-internal (- n u1) (* acc (unwrap-panic (to-int n)))))) + (ok (fibonacci-internal n)))) +;; Fibonacci sequence function +(define-read-only (fibonacci (n uint)) + (if (> n u50) ;; Limit to prevent overflow + (err u"Input too large for Fibonacci calculation") + (ok (fibonacci-internal n 0 1)))) + +;; Helper function for Fibonacci calculation (tail-recursive) +(define-private (fibonacci-internal (n uint) (a int) (b int)) + (if (is-eq n u0) + a + (fibonacci-internal (- n u1) b (+ a b))))))) \ No newline at end of file From 46c89c8f620a3f3e27b58d44fd855dd742cb45e4 Mon Sep 17 00:00:00 2001 From: teefeh-07 Date: Wed, 30 Apr 2025 20:28:19 +0100 Subject: [PATCH 2/4] code for stacks --- Mathematics/contracts/mlib.clar | 517 ++++++++++++++++---------------- 1 file changed, 257 insertions(+), 260 deletions(-) diff --git a/Mathematics/contracts/mlib.clar b/Mathematics/contracts/mlib.clar index 6e72eba..eb9cec7 100644 --- a/Mathematics/contracts/mlib.clar +++ b/Mathematics/contracts/mlib.clar @@ -1,314 +1,311 @@ -;; Enhanced Math Library for Stacks Blockchain -;; Version 2.0 -;; This library provides comprehensive math operations with safety checks -;; All functions return (ok value) on success and (err error-message) on failure +;; Enhanced Math Library in Clarity +;; A comprehensive mathematical utility library with robust error handling +;; and a diverse set of common mathematical operations. -;; ------ BASIC ARITHMETIC OPERATIONS ------ +;; ========== Constants ========== + +(define-constant ERR-OVERFLOW u"Arithmetic overflow occurred") +(define-constant ERR-UNDERFLOW u"Arithmetic underflow occurred") +(define-constant ERR-DIVIDE-BY-ZERO u"Cannot divide by zero") +(define-constant ERR-NEGATIVE-ROOT u"Cannot compute square root of negative number") +(define-constant ERR-NEGATIVE-LOG u"Cannot compute logarithm of non-positive number") +(define-constant ERR-DOMAIN-ERROR u"Input value outside valid domain") + +;; ========== Basic Arithmetic Functions ========== ;; Addition Function with overflow check +;; @param a (int) - First integer operand +;; @param b (int) - Second integer operand +;; @returns (response int string) - Returns result or error message (define-read-only (add (a int) (b int)) (let ((result (+ a b))) (if (or - (and (> a 0) (> b 0) (< result a)) - (and (< a 0) (< b 0) (> result a))) - (err u"Overflow occurred in addition") + ;; Check if signs are the same and overflow occurred + (and (> a 0) (> b 0) (< result 0)) + (and (< a 0) (< b 0) (> result 0))) + (err ERR-OVERFLOW) (ok result)))) ;; Subtraction Function with underflow check +;; @param a (int) - First integer operand +;; @param b (int) - Second integer operand +;; @returns (response int string) - Returns result or error message (define-read-only (subtract (a int) (b int)) (let ((result (- a b))) - (if (or - (and (> a 0) (< b 0) (< result a)) + (if (or + ;; Check for underflow scenarios + (and (> a 0) (< b 0) (< result a)) (and (< a 0) (> b 0) (> result a))) - (err u"Underflow occurred in subtraction") + (err ERR-UNDERFLOW) (ok result)))) -;; Multiplication Function with overflow check +;; Multiplication Function with improved overflow check +;; @param a (int) - First integer operand +;; @param b (int) - Second integer operand +;; @returns (response int string) - Returns result or error message (define-read-only (multiply (a int) (b int)) (let ((result (* a b))) (if (or (is-eq a 0) (is-eq b 0)) (ok 0) - (if (and (> a 0) (> b 0) (< result a)) - (err u"Overflow occurred in multiplication") - (if (and (< a 0) (< b 0) (> result a)) - (err u"Overflow occurred in multiplication") - (if (and (> a 0) (< b 0) (> result a)) - (err u"Overflow occurred in multiplication") - (if (and (< a 0) (> b 0) (< result a)) - (err u"Overflow occurred in multiplication") - (if (is-eq (/ result a) b) - (ok result) - (err u"Overflow occurred in multiplication"))))))))) + (if (or + (is-eq (/ result a) b) + (is-eq (/ result b) a)) + (ok result) + (err ERR-OVERFLOW))))) ;; Division Function with error handling +;; @param a (int) - Numerator +;; @param b (int) - Denominator +;; @returns (response int string) - Returns result or error message (define-read-only (divide (a int) (b int)) (if (is-eq b 0) - (err u"Cannot divide by zero") + (err ERR-DIVIDE-BY-ZERO) (ok (/ a b)))) -;; Integer Division Function that returns whole quotient only -(define-read-only (div-integer (a int) (b int)) +;; Safe division that returns a specified value on division by zero +;; @param a (int) - Numerator +;; @param b (int) - Denominator +;; @param default (int) - Default value to return if b is zero +;; @returns (int) - Result of division or default value +(define-read-only (safe-divide (a int) (b int) (default int)) (if (is-eq b 0) - (err u"Cannot divide by zero") - (ok (/ a b)))) + default + (/ a b))) -;; ------ MODULAR ARITHMETIC ------ +;; ========== Integer Math Functions ========== + +;; Square Function (a^2) with overflow protection +;; @param a (int) - Input value +;; @returns (response int string) - Returns squared value or error message +(define-read-only (square (a int)) + (multiply a a)) + +;; Cube Function (a^3) with overflow protection +;; @param a (int) - Input value +;; @returns (response int string) - Returns cubed value or error message +(define-read-only (cube (a int)) + (match (multiply a a) + success (multiply success a) + error error)) + +;; Power Function for integers with overflow protection +;; Only works with non-negative exponents +;; @param base (int) - Base value +;; @param exponent (uint) - Exponent (must be non-negative) +;; @returns (response int string) - Returns result or error message +(define-read-only (power (base int) (exponent uint)) + (if (is-eq exponent u0) + (ok 1) ;; anything^0 = 1 + (if (is-eq base 0) + (ok 0) ;; 0^n = 0 for n > 0 + (if (is-eq exponent u1) + (ok base) ;; n^1 = n + (power-helper base exponent base u1))))) + +(define-private (power-helper (base int) (exponent uint) (result int) (current-exp uint)) + (if (>= current-exp exponent) + (ok result) + (match (multiply result base) + new-result (power-helper base exponent new-result (+ current-exp u1)) + error error))) + +;; Integer square root approximation +;; Returns the largest integer r such that r*r <= n +;; @param n (uint) - Input value +;; @returns (response uint string) - Returns integer square root or error message +(define-read-only (isqrt (n uint)) + (if (is-eq n u0) + (ok u0) + (let ((x u1) + (y (+ (/ n u2) u1))) + (ok (isqrt-iter x y n))))) + +;; Helper function for isqrt using Newton's method +(define-private (isqrt-iter (x uint) (y uint) (n uint)) + (if (< x y) + (isqrt-iter y (+ (/ n y) y u1 u2) n) + x)) ;; Modular Function (renamed to avoid conflict with built-in 'mod' function) +;; @param a (int) - Dividend +;; @param b (int) - Divisor +;; @returns (response int string) - Returns remainder or error message (define-read-only (modular (a int) (b int)) (if (is-eq b 0) - (err u"Cannot perform modulo by zero") + (err ERR-DIVIDE-BY-ZERO) (ok (mod a b)))) -;; Modular Exponentiation (a^b mod m) - Efficient power calculation with modulo -;; (define-read-only (mod-power (base int) (exponent uint) (modulus int)) -;; (if (is-eq modulus 0) -;; (err u"Cannot perform modulo by zero") -;; (ok (mod-power-internal base exponent modulus 1)))) - -;; Helper function for modular exponentiation using binary exponentiation -;; (define-private (mod-power-internal (base int) (exponent uint) (modulus int) (result int)) -;; (if (is-eq exponent u0) -;; result -;; (let ((next-result (if (is-eq (mod exponent 2) 1) -;; (mod (* result base) modulus) -;; result)) -;; (next-base (mod (* base base) modulus)) -;; (next-exponent (/ exponent u2))) -;; (mod-power-internal next-base next-exponent modulus next-result)))) - -;; ------ BASIC MATH FUNCTIONS ------ - -;; Square Function -(define-read-only (square (a int)) - (multiply a a)) - -;; Power Function (a^n) - Integer exponentiation -;; (define-read-only (power (base int) (exponent uint)) -;; (power-internal base exponent 1)) - -;; ;; Helper function for power calculation -;; ;; Power Function (a^n) - Integer exponentiation -;; (define-read-only (power (base int) (exponent uint)) -;; (ok (power-internal base exponent 1))) - -;; ;; Helper function for power calculation -;; (define-private (power-internal (base int) (exponent uint) (result int)) -;; (cond -;; ((is-eq exponent u0) result) -;; ((is-eq (mod exponent 2) 1) -;; (power-internal (* base base) (/ exponent u2) (* result base))) -;; (true (power-internal (* base base) (/ exponent u2) result)))) -;; (ok a) - -;; Sign Function (-1 for negative, 0 for zero, 1 for positive) -;; (define-read-only (sign (a int)) -;; (cond -;; ((< a 0) (ok -1)) -;; ((> a 0) (ok 1)) -;; (true (ok 0)))) - -;; ------ AGGREGATE OPERATIONS ------ +;; Absolute Value Function +;; @param a (int) - Input value +;; @returns (response int string) - Returns absolute value or error message +(define-read-only (absolute (a int)) + (if (< a 0) + (let ((result (- 0 a))) + (if (< result 0) ;; Check for MIN_INT case + (err ERR-OVERFLOW) + (ok result))) + (ok a))) + +;; Sign Function +;; Returns -1 for negative numbers, 0 for zero, and 1 for positive numbers +;; @param a (int) - Input value +;; @returns (int) - Sign of the input value +(define-read-only (sign (a int)) + (if (> a 0) + 1 + (if (< a 0) + -1 + 0))) + +;; ========== Statistical Functions ========== ;; Average Function with overflow protection +;; @param a (int) - First value +;; @param b (int) - Second value +;; @returns (response int string) - Returns average value or error message (define-read-only (average (a int) (b int)) (match (add a b) - sum (ok (/ sum 2)) - error (err error))) - -;; Weighted Average (a*weight_a + b*weight_b)/(weight_a + weight_b) -;; (define-read-only (weighted-average (a int) (weight-a uint) (b int) (weight-b uint)) -;; (begin -;; (if (and (is-eq weight-a u0) (is-eq weight-b u0)) -;; (err u"Both weights cannot be zero") -;; ;; Weighted Average (a*weight_a + b*weight_b)/(weight_a + weight_b) -;; (define-read-only (weighted-average (a int) (weight-a uint) (b int) (weight-b uint)) -;; (if (and (is-eq weight-a u0) (is-eq weight-b u0)) -;; (err u"Both weights cannot be zero") -;; (let -;; ( -;; (prod-a (match (multiply a (unwrap-panic (to-int weight-a))) -;; success success -;; error (err error))) -;; (prod-b (match (multiply b (unwrap-panic (to-int weight-b))) -;; success success -;; error (err error))) -;; ) -;; (match prod-a -;; success-a -;; (match prod-b -;; success-b -;; (match (add success-a success-b) -;; sum (ok (/ sum (unwrap-panic (to-int (+ weight-a weight-b))))) -;; error (err error)) -;; error-b (err error-b)) -;; error-a (err error-a))))) + sum-result (divide sum-result 2) + error error)) + +;; Calculate weighted average of two values +;; @param a (int) - First value +;; @param weight-a (uint) - Weight for first value +;; @param b (int) - Second value +;; @param weight-b (uint) - Weight for second value +;; @returns (response int string) - Returns weighted average or error message +(define-read-only (weighted-average (a int) (weight-a uint) (b int) (weight-b uint)) + (if (and (is-eq weight-a u0) (is-eq weight-b u0)) + (err ERR-DIVIDE-BY-ZERO) + (let ((total-weight (+ weight-a weight-b))) + (match (multiply a (to-int weight-a)) + weighted-a (match (multiply b (to-int weight-b)) + weighted-b (match (add weighted-a weighted-b) + sum (divide sum (to-int total-weight)) + error error) + error error) + error error)))) + +;; ========== Comparison Functions ========== + +;; Maximum Function +;; @param a (int) - First value +;; @param b (int) - Second value +;; @returns (int) - Larger of the two values +(define-read-only (maximum (a int) (b int)) + (if (>= a b) a b)) + ;; Minimum Function +;; @param a (int) - First value +;; @param b (int) - Second value +;; @returns (int) - Smaller of the two values (define-read-only (minimum (a int) (b int)) - (ok (if (<= a b) a b))) - -;; ------ NUMERIC PROPERTY FUNCTIONS ------ + (if (<= a b) a b)) + +;; Clamp Function +;; Restricts a value to a specified range +;; @param value (int) - Value to clamp +;; @param min-val (int) - Minimum bound +;; @param max-val (int) - Maximum bound +;; @returns (int) - Clamped value +(define-read-only (clamp (value int) (min-val int) (max-val int)) + (if (< value min-val) + min-val + (if (> value max-val) + max-val + value))) + +;; ========== Number Property Functions ========== ;; Is Even Function +;; @param a (int) - Input value +;; @returns (bool) - True if the value is even, false otherwise (define-read-only (is-even (a int)) - (ok (is-eq (mod a 2) 0))) + (is-eq (mod a 2) 0)) ;; Is Odd Function +;; @param a (int) - Input value +;; @returns (bool) - True if the value is odd, false otherwise (define-read-only (is-odd (a int)) - (ok (is-eq (mod a 2) 1))) + (is-eq (mod a 2) 1)) ;; Is Positive Function +;; @param a (int) - Input value +;; @returns (bool) - True if the value is positive, false otherwise (define-read-only (is-positive (a int)) - (ok (> a 0))) + (> a 0)) ;; Is Negative Function +;; @param a (int) - Input value +;; @returns (bool) - True if the value is negative, false otherwise (define-read-only (is-negative (a int)) - (ok (< a 0))) + (< a 0)) -;; Is Zero Function -(define-read-only (is-zero (a int)) - (ok (is-eq a 0))) +;; Is Divisible By Function +;; @param a (int) - Dividend +;; @param b (int) - Divisor +;; @returns (response bool string) - Returns divisibility check or error message +(define-read-only (is-divisible-by (a int) (b int)) + (if (is-eq b 0) + (err ERR-DIVIDE-BY-ZERO) + (ok (is-eq (mod a b) 0)))) -;; ------ CONVERSION FUNCTIONS ------ +;; ========== Utility Conversion Functions ========== -;; Integer to uint conversion with validation -(define-read-only (to-uint (a int)) - (if (>= a 0) - (ok (unwrap-panic (to-uint a))) - (err u"Cannot convert negative number to uint"))) -;; Integer to uint conversion with validation +;; Convert int to uint if possible +;; @param a (int) - Input integer +;; @returns (response uint string) - Returns uint or error message (define-read-only (to-uint (a int)) - (if (>= a 0) - (ok (unwrap-panic (to-uint a))) - (err u"Cannot convert negative number to uint"))) - -;; Uint to int conversion (always safe) -(define-read-only (to-int (a uint)) - (ok (unwrap-panic (to-int a)))) -(define-constant FIXED-POINT-FACTOR 1000000) - -;; Convert integer to fixed-point representation -(define-read-only (to-fixed-point (a int)) - (multiply a FIXED-POINT-FACTOR)) - -;; Multiply two fixed-point numbers -(define-read-only (fixed-multiply (a int) (b int)) - (match (multiply a b) - product (ok (/ product FIXED-POINT-FACTOR)) - error (err error))) - -;; Divide two fixed-point numbers -(define-read-only (fixed-divide (a int) (b int)) - (if (is-eq b 0) - (err u"Cannot divide by zero") - (match (multiply a FIXED-POINT-FACTOR) - product (ok (/ product b)) - error (err error)))) - -;; Square root approximation for fixed-point numbers using Newton's method -;; Returns result with 6 decimal places precision -(define-public (sqrt (x int)) - (begin - (asserts! (>= x 0) (err u"Cannot calculate square root of negative number")) -;; Square root approximation for fixed-point numbers using Newton's method -;; Returns result with 6 decimal places precision -(define-read-only (sqrt (x int)) - (if (< x 0) - (err u"Cannot calculate square root of negative number") - (if (is-eq x 0) - (ok 0) - (ok (sqrt-newton x (/ (+ x 1) 2) 10))))) ;; 10 iterations for good precision - -;; Helper function for Newton's method of square root approximation -(define-private (sqrt-newton (x int) (guess int) (iterations int)) - (if (is-eq iterations 0) - guess - (let ((new-guess (/ (+ guess (/ x guess)) 2))) - (sqrt-newton x new-guess (- iterations 1))))) - -;; Sine approximation using Taylor series (fixed-point result) -(define-read-only (sin (angle-rad int)) - (let - ((normalized-angle (mod angle-rad (* 2 FIXED-POINT-FACTOR 314159 10)))) ;; Normalize to [0, 2) - (match (add - normalized-angle - (match (multiply - (multiply - (multiply normalized-angle normalized-angle) - normalized-angle) - (/ -1 (* 6 FIXED-POINT-FACTOR))) - term (ok term) - error (err error))) - result (ok result) - error (err error)))) - -;; Cosine approximation using Taylor series (fixed-point result) -(define-read-only (cos (angle-rad int)) - (let - ((normalized-angle (mod angle-rad (* 2 FIXED-POINT-FACTOR 314159 10)))) ;; Normalize to [0, 2) - (match (add - FIXED-POINT-FACTOR - (match (multiply - (multiply normalized-angle normalized-angle) - (/ -1 (* 2 FIXED-POINT-FACTOR))) - term (ok term) - error (err error))) - result (ok result) - error (err error)))) - -;; ------ UTILITY FUNCTIONS ------ - -;; Greatest Common Divisor (GCD) using Euclidean algorithm -(define-read-only (gcd (a int) (b int)) - (match (absolute a) - abs-a (match (absolute b) - abs-b (ok (gcd-internal abs-a abs-b)) - error (err error)) - error (err error))) - -;; Helper function for GCD calculation -(define-private (gcd-internal (a int) (b int)) - (if (is-eq b 0) - a - (gcd-internal b (mod a b)))) - -;; Least Common Multiple (LCM) -(define-read-only (lcm (a int) (b int)) - (match (absolute a) - abs-a (match (absolute b) - abs-b (if (or (is-eq abs-a 0) (is-eq abs-b 0)) - (ok 0) - (match (multiply abs-a abs-b) - product (ok (/ product (gcd-internal abs-a abs-b))) - error (err error))) - error (err error)) - error (err error))) - -;; Factorial function (n!) -(define-read-only (factorial (n uint)) - (if (> n u20) ;; Limit to prevent overflow - (err u"Input too large for factorial calculation") - (ok (factorial-internal n)))) -;; Factorial function (n!) -(define-read-only (factorial (n uint)) - (if (> n u20) ;; Limit to prevent overflow - (err u"Input too large for factorial calculation") - (ok (factorial-internal n 1)))) - -;; Helper function for factorial calculation (tail-recursive) -(define-private (factorial-internal (n uint) (acc int)) - (if (<= n u1) - acc - (factorial-internal (- n u1) (* acc (unwrap-panic (to-int n)))))) - (ok (fibonacci-internal n)))) -;; Fibonacci sequence function -(define-read-only (fibonacci (n uint)) - (if (> n u50) ;; Limit to prevent overflow - (err u"Input too large for Fibonacci calculation") - (ok (fibonacci-internal n 0 1)))) - -;; Helper function for Fibonacci calculation (tail-recursive) -(define-private (fibonacci-internal (n uint) (a int) (b int)) - (if (is-eq n u0) - a - (fibonacci-internal (- n u1) b (+ a b))))))) \ No newline at end of file + (if (< a 0) + (err ERR-DOMAIN-ERROR) + (ok (to-uint a)))) + +;; Convert uint to int safely +;; @param a (uint) - Input unsigned integer +;; @returns (response int string) - Returns int or error message +(define-read-only (uint-to-int (a uint)) + (let ((result (to-int a))) + (if (< result 0) ;; Check for overflow + (err ERR-OVERFLOW) + (ok result)))) + +;; ========== Bitwise Operations ========== + +;; Bitwise AND operation +;; @param a (uint) - First operand +;; @param b (uint) - Second operand +;; @returns (uint) - Result of bitwise AND +(define-read-only (bit-and (a uint) (b uint)) + (bit-and a b)) + +;; Bitwise OR operation +;; @param a (uint) - First operand +;; @param b (uint) - Second operand +;; @returns (uint) - Result of bitwise OR +(define-read-only (bit-or (a uint) (b uint)) + (bit-or a b)) + +;; Bitwise XOR operation +;; @param a (uint) - First operand +;; @param b (uint) - Second operand +;; @returns (uint) - Result of bitwise XOR +(define-read-only (bit-xor (a uint) (b uint)) + (bit-xor a b)) + +;; Left shift operation +;; @param a (uint) - Value to shift +;; @param b (uint) - Shift amount +;; @returns (uint) - Result of left shift +(define-read-only (left-shift (a uint) (b uint)) + (if (> b u128) + u0 ;; Shift by more than the bit width results in 0 + (bit-shift-left a b))) + +;; Right shift operation +;; @param a (uint) - Value to shift +;; @param b (uint) - Shift amount +;; @returns (uint) - Result of right shift +(define-read-only (right-shift (a uint) (b uint)) + (if (> b u128) + u0 ;; Shift by more than the bit width results in 0 + (bit-shift-right a b))) \ No newline at end of file From f7d770913b003ce399c0f1677c3753ff829f64a3 Mon Sep 17 00:00:00 2001 From: teefeh-07 Date: Wed, 30 Apr 2025 20:34:28 +0100 Subject: [PATCH 3/4] code for stacks --- Mathematics/contracts/mlib.clar | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Mathematics/contracts/mlib.clar b/Mathematics/contracts/mlib.clar index eb9cec7..7403577 100644 --- a/Mathematics/contracts/mlib.clar +++ b/Mathematics/contracts/mlib.clar @@ -100,14 +100,15 @@ (ok 0) ;; 0^n = 0 for n > 0 (if (is-eq exponent u1) (ok base) ;; n^1 = n - (power-helper base exponent base u1))))) - -(define-private (power-helper (base int) (exponent uint) (result int) (current-exp uint)) - (if (>= current-exp exponent) - (ok result) - (match (multiply result base) - new-result (power-helper base exponent new-result (+ current-exp u1)) - error error))) + (let ((half-exp (/ exponent u2)) + (odd (is-eq (mod exponent u2) u1))) + (match (power base half-exp) + half-result (match (multiply half-result half-result) + squared (if odd + (multiply squared base) + (ok squared)) + error error) + error error)))))) ;; Integer square root approximation ;; Returns the largest integer r such that r*r <= n From 49fe34597dd6f381b050942a8f64838a3849f5be Mon Sep 17 00:00:00 2001 From: teefeh-07 Date: Tue, 17 Jun 2025 18:26:33 +0000 Subject: [PATCH 4/4] Fix critical syntax and logic errors in mlib.clar - Fixed isqrt-iter function: corrected addition syntax in Newton's method calculation - Fixed is-odd function: improved logic to handle negative numbers correctly using negation of is-even - Fixed int-to-uint function: renamed from to-uint to avoid recursive call conflict with built-in - Fixed bitwise functions: renamed bit-and, bit-or, bit-xor to avoid recursive calls with built-ins These fixes resolve syntax errors and infinite recursion issues that would prevent the contract from compiling and functioning correctly. --- Mathematics/contracts/mlib.clar | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Mathematics/contracts/mlib.clar b/Mathematics/contracts/mlib.clar index 7403577..5815bca 100644 --- a/Mathematics/contracts/mlib.clar +++ b/Mathematics/contracts/mlib.clar @@ -124,7 +124,7 @@ ;; Helper function for isqrt using Newton's method (define-private (isqrt-iter (x uint) (y uint) (n uint)) (if (< x y) - (isqrt-iter y (+ (/ n y) y u1 u2) n) + (isqrt-iter y (/ (+ (/ n y) y) u2) n) x)) ;; Modular Function (renamed to avoid conflict with built-in 'mod' function) @@ -228,7 +228,7 @@ ;; @param a (int) - Input value ;; @returns (bool) - True if the value is odd, false otherwise (define-read-only (is-odd (a int)) - (is-eq (mod a 2) 1)) + (not (is-eq (mod a 2) 0))) ;; Is Positive Function ;; @param a (int) - Input value @@ -256,7 +256,7 @@ ;; Convert int to uint if possible ;; @param a (int) - Input integer ;; @returns (response uint string) - Returns uint or error message -(define-read-only (to-uint (a int)) +(define-read-only (int-to-uint (a int)) (if (< a 0) (err ERR-DOMAIN-ERROR) (ok (to-uint a)))) @@ -276,21 +276,21 @@ ;; @param a (uint) - First operand ;; @param b (uint) - Second operand ;; @returns (uint) - Result of bitwise AND -(define-read-only (bit-and (a uint) (b uint)) +(define-read-only (bitwise-and (a uint) (b uint)) (bit-and a b)) ;; Bitwise OR operation ;; @param a (uint) - First operand ;; @param b (uint) - Second operand ;; @returns (uint) - Result of bitwise OR -(define-read-only (bit-or (a uint) (b uint)) +(define-read-only (bitwise-or (a uint) (b uint)) (bit-or a b)) ;; Bitwise XOR operation ;; @param a (uint) - First operand ;; @param b (uint) - Second operand ;; @returns (uint) - Result of bitwise XOR -(define-read-only (bit-xor (a uint) (b uint)) +(define-read-only (bitwise-xor (a uint) (b uint)) (bit-xor a b)) ;; Left shift operation