CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-uniswap--sdk-core

Core TypeScript utilities and abstractions for building applications on top of Uniswap V3

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities

Essential utility functions for address validation, price impact calculations, mathematical operations, and specialized blockchain utilities.

Capabilities

Address Validation

Functions for validating and parsing Ethereum addresses with checksumming support.

/**
 * Validates an address and returns the parsed (checksummed) version of that address
 * @param address - The unchecksummed hex address
 * @returns Checksummed address
 * @throws Error if address is invalid
 */
function validateAndParseAddress(address: string): string;

/**
 * Checks if an address is valid by checking 0x prefix, length === 42 and hex encoding
 * @param address - The unchecksummed hex address
 * @returns The address if valid
 * @throws Error if address is invalid
 */
function checkValidAddress(address: string): string;

Usage Examples:

import { validateAndParseAddress, checkValidAddress } from "@uniswap/sdk-core";

// Validate and checksum an address
const address = "0xa0b86a33e6411e9e6e64d7df6e97e1e27eb3f8e8";
const checksummed = validateAndParseAddress(address);
console.log(checksummed); // "0xA0b86a33E6411e9E6E64d7dF6e97E1E27eB3f8E8"

// Basic validation without checksumming
const validAddress = checkValidAddress("0x1234567890123456789012345678901234567890");
console.log(validAddress); // "0x1234567890123456789012345678901234567890"

// Invalid address throws error
try {
  validateAndParseAddress("invalid-address");
} catch (error) {
  console.log(error.message); // "invalid-address is not a valid address."
}

Price Impact Calculation

Function for calculating price impact percentage between mid price and execution price.

/**
 * Returns the percent difference between the mid price and the execution price, i.e. price impact
 * @param midPrice - Mid price before the trade
 * @param inputAmount - The input amount of the trade
 * @param outputAmount - The output amount of the trade
 * @returns Price impact as a Percent
 */
function computePriceImpact<TBase extends Currency, TQuote extends Currency>(
  midPrice: Price<TBase, TQuote>,
  inputAmount: CurrencyAmount<TBase>,
  outputAmount: CurrencyAmount<TQuote>
): Percent;

Usage Examples:

import { 
  computePriceImpact, 
  Price, 
  CurrencyAmount, 
  Token, 
  Ether,
  ChainId 
} from "@uniswap/sdk-core";

const USDC = new Token(ChainId.MAINNET, "0xA0b86a33E6424b73E63872f681e2230aDC3D3dC", 6, "USDC");
const ether = Ether.onChain(ChainId.MAINNET);

// Mid price: 2000 USDC per ETH
const midPrice = new Price({
  baseAmount: CurrencyAmount.fromRawAmount(ether, "1000000000000000000"), // 1 ETH
  quoteAmount: CurrencyAmount.fromRawAmount(USDC, "2000000000") // 2000 USDC
});

// Trade: 1 ETH input, 1990 USDC output (slippage)
const inputAmount = CurrencyAmount.fromRawAmount(ether, "1000000000000000000"); // 1 ETH
const outputAmount = CurrencyAmount.fromRawAmount(USDC, "1990000000"); // 1990 USDC

const priceImpact = computePriceImpact(midPrice, inputAmount, outputAmount);
console.log(priceImpact.toFixed(2)); // "0.50" (0.5% price impact)

Mathematical Utilities

Core mathematical functions for precise calculations.

/**
 * Maximum safe integer value as JSBI
 */
const MAX_SAFE_INTEGER: JSBI;

/**
 * Computes floor(sqrt(value)) using JSBI for large number support
 * @param value - The value for which to compute the square root, rounded down
 * @returns Square root rounded down
 * @throws Error if value is negative
 */
function sqrt(value: JSBI): JSBI;

Usage Examples:

import { sqrt, MAX_SAFE_INTEGER } from "@uniswap/sdk-core";
import JSBI from "jsbi";

// Calculate square root of large numbers
const largeNumber = JSBI.BigInt("1000000000000000000000000"); // 10^24
const sqrtResult = sqrt(largeNumber);
console.log(sqrtResult.toString()); // "1000000000000"

// Check against maximum safe integer
const value = JSBI.BigInt("999999999999999");
if (JSBI.lessThan(value, MAX_SAFE_INTEGER)) {
  console.log("Value is within safe integer range");
}

// Square root throws error for negative values
try {
  sqrt(JSBI.BigInt("-1"));
} catch (error) {
  console.log("Cannot compute square root of negative number");
}

Array Utilities

Utility functions for working with sorted arrays and binary search operations.

/**
 * Given an array of items sorted by `comparator`, insert an item into its sort index 
 * and constrain the size to `maxSize` by removing the last item
 * @param items - Sorted array to insert into
 * @param add - Item to add
 * @param maxSize - Maximum size constraint for the array
 * @param comparator - Comparison function for sorting
 * @returns The removed item if array was at maxSize, null otherwise
 */
function sortedInsert<T>(
  items: T[], 
  add: T, 
  maxSize: number, 
  comparator: (a: T, b: T) => number
): T | null;

Usage Examples:

import { sortedInsert } from "@uniswap/sdk-core";

// Maintain a sorted array of numbers with size limit
const numbers: number[] = [1, 3, 5, 7];
const maxSize = 5;

const numberComparator = (a: number, b: number) => a - b;

// Add number that fits in middle
const removed1 = sortedInsert(numbers, 4, maxSize, numberComparator);
console.log(numbers); // [1, 3, 4, 5, 7]
console.log(removed1); // null (nothing removed)

// Add number when at max size
const removed2 = sortedInsert(numbers, 6, maxSize, numberComparator);
console.log(numbers); // [1, 3, 4, 5, 6] (7 was removed)
console.log(removed2); // 7

// Maintain sorted array of objects
interface PricePoint {
  price: number;
  timestamp: number;
}

const pricePoints: PricePoint[] = [];
const priceComparator = (a: PricePoint, b: PricePoint) => a.price - b.price;

sortedInsert(pricePoints, { price: 100, timestamp: Date.now() }, 10, priceComparator);
sortedInsert(pricePoints, { price: 95, timestamp: Date.now() }, 10, priceComparator);
console.log(pricePoints); // Sorted by price: [{ price: 95, ... }, { price: 100, ... }]

zkSync Utilities

Specialized utilities for zkSync blockchain operations.

/**
 * Compute zkSync CREATE2 address for contract deployment
 * @param sender - Address of the contract deployer
 * @param bytecodeHash - Hash of the contract bytecode
 * @param salt - Salt value for deterministic address generation
 * @param input - Constructor input data (default: '0x')
 * @returns Computed zkSync CREATE2 address
 */
function computeZksyncCreate2Address(
  sender: string,
  bytecodeHash: BytesLike,
  salt: BytesLike,
  input: BytesLike = '0x'
): string;

Usage Examples:

import { computeZksyncCreate2Address } from "@uniswap/sdk-core";
import { keccak256, toUtf8Bytes } from "@ethersproject/strings";

// Compute zkSync CREATE2 address
const deployer = "0x1234567890123456789012345678901234567890";
const bytecodeHash = keccak256(toUtf8Bytes("contract bytecode"));
const salt = keccak256(toUtf8Bytes("unique salt"));

const create2Address = computeZksyncCreate2Address(
  deployer,
  bytecodeHash,
  salt
);

console.log(create2Address); // Computed zkSync CREATE2 address

// With constructor input
const constructorInput = "0x000000000000000000000000abcdefabcdefabcdefabcdefabcdefabcdefabcd";
const create2AddressWithInput = computeZksyncCreate2Address(
  deployer,
  bytecodeHash,
  salt,
  constructorInput
);

console.log(create2AddressWithInput); // Address with constructor parameters

Constants

/**
 * Maximum uint256 value used for amount validation
 */
const MaxUint256: JSBI;

/**
 * Trade type enumeration
 */
enum TradeType {
  EXACT_INPUT,
  EXACT_OUTPUT,
}

Install with Tessl CLI

npx tessl i tessl/npm-uniswap--sdk-core

docs

chains-and-addresses.md

currency-system.md

index.md

mathematical-operations.md

utilities.md

tile.json