0
# Utilities
1
2
Essential utility functions for address validation, price impact calculations, mathematical operations, and specialized blockchain utilities.
3
4
## Capabilities
5
6
### Address Validation
7
8
Functions for validating and parsing Ethereum addresses with checksumming support.
9
10
```typescript { .api }
11
/**
12
* Validates an address and returns the parsed (checksummed) version of that address
13
* @param address - The unchecksummed hex address
14
* @returns Checksummed address
15
* @throws Error if address is invalid
16
*/
17
function validateAndParseAddress(address: string): string;
18
19
/**
20
* Checks if an address is valid by checking 0x prefix, length === 42 and hex encoding
21
* @param address - The unchecksummed hex address
22
* @returns The address if valid
23
* @throws Error if address is invalid
24
*/
25
function checkValidAddress(address: string): string;
26
```
27
28
**Usage Examples:**
29
30
```typescript
31
import { validateAndParseAddress, checkValidAddress } from "@uniswap/sdk-core";
32
33
// Validate and checksum an address
34
const address = "0xa0b86a33e6411e9e6e64d7df6e97e1e27eb3f8e8";
35
const checksummed = validateAndParseAddress(address);
36
console.log(checksummed); // "0xA0b86a33E6411e9E6E64d7dF6e97E1E27eB3f8E8"
37
38
// Basic validation without checksumming
39
const validAddress = checkValidAddress("0x1234567890123456789012345678901234567890");
40
console.log(validAddress); // "0x1234567890123456789012345678901234567890"
41
42
// Invalid address throws error
43
try {
44
validateAndParseAddress("invalid-address");
45
} catch (error) {
46
console.log(error.message); // "invalid-address is not a valid address."
47
}
48
```
49
50
### Price Impact Calculation
51
52
Function for calculating price impact percentage between mid price and execution price.
53
54
```typescript { .api }
55
/**
56
* Returns the percent difference between the mid price and the execution price, i.e. price impact
57
* @param midPrice - Mid price before the trade
58
* @param inputAmount - The input amount of the trade
59
* @param outputAmount - The output amount of the trade
60
* @returns Price impact as a Percent
61
*/
62
function computePriceImpact<TBase extends Currency, TQuote extends Currency>(
63
midPrice: Price<TBase, TQuote>,
64
inputAmount: CurrencyAmount<TBase>,
65
outputAmount: CurrencyAmount<TQuote>
66
): Percent;
67
```
68
69
**Usage Examples:**
70
71
```typescript
72
import {
73
computePriceImpact,
74
Price,
75
CurrencyAmount,
76
Token,
77
Ether,
78
ChainId
79
} from "@uniswap/sdk-core";
80
81
const USDC = new Token(ChainId.MAINNET, "0xA0b86a33E6424b73E63872f681e2230aDC3D3dC", 6, "USDC");
82
const ether = Ether.onChain(ChainId.MAINNET);
83
84
// Mid price: 2000 USDC per ETH
85
const midPrice = new Price({
86
baseAmount: CurrencyAmount.fromRawAmount(ether, "1000000000000000000"), // 1 ETH
87
quoteAmount: CurrencyAmount.fromRawAmount(USDC, "2000000000") // 2000 USDC
88
});
89
90
// Trade: 1 ETH input, 1990 USDC output (slippage)
91
const inputAmount = CurrencyAmount.fromRawAmount(ether, "1000000000000000000"); // 1 ETH
92
const outputAmount = CurrencyAmount.fromRawAmount(USDC, "1990000000"); // 1990 USDC
93
94
const priceImpact = computePriceImpact(midPrice, inputAmount, outputAmount);
95
console.log(priceImpact.toFixed(2)); // "0.50" (0.5% price impact)
96
```
97
98
### Mathematical Utilities
99
100
Core mathematical functions for precise calculations.
101
102
```typescript { .api }
103
/**
104
* Maximum safe integer value as JSBI
105
*/
106
const MAX_SAFE_INTEGER: JSBI;
107
108
/**
109
* Computes floor(sqrt(value)) using JSBI for large number support
110
* @param value - The value for which to compute the square root, rounded down
111
* @returns Square root rounded down
112
* @throws Error if value is negative
113
*/
114
function sqrt(value: JSBI): JSBI;
115
```
116
117
**Usage Examples:**
118
119
```typescript
120
import { sqrt, MAX_SAFE_INTEGER } from "@uniswap/sdk-core";
121
import JSBI from "jsbi";
122
123
// Calculate square root of large numbers
124
const largeNumber = JSBI.BigInt("1000000000000000000000000"); // 10^24
125
const sqrtResult = sqrt(largeNumber);
126
console.log(sqrtResult.toString()); // "1000000000000"
127
128
// Check against maximum safe integer
129
const value = JSBI.BigInt("999999999999999");
130
if (JSBI.lessThan(value, MAX_SAFE_INTEGER)) {
131
console.log("Value is within safe integer range");
132
}
133
134
// Square root throws error for negative values
135
try {
136
sqrt(JSBI.BigInt("-1"));
137
} catch (error) {
138
console.log("Cannot compute square root of negative number");
139
}
140
```
141
142
### Array Utilities
143
144
Utility functions for working with sorted arrays and binary search operations.
145
146
```typescript { .api }
147
/**
148
* Given an array of items sorted by `comparator`, insert an item into its sort index
149
* and constrain the size to `maxSize` by removing the last item
150
* @param items - Sorted array to insert into
151
* @param add - Item to add
152
* @param maxSize - Maximum size constraint for the array
153
* @param comparator - Comparison function for sorting
154
* @returns The removed item if array was at maxSize, null otherwise
155
*/
156
function sortedInsert<T>(
157
items: T[],
158
add: T,
159
maxSize: number,
160
comparator: (a: T, b: T) => number
161
): T | null;
162
```
163
164
**Usage Examples:**
165
166
```typescript
167
import { sortedInsert } from "@uniswap/sdk-core";
168
169
// Maintain a sorted array of numbers with size limit
170
const numbers: number[] = [1, 3, 5, 7];
171
const maxSize = 5;
172
173
const numberComparator = (a: number, b: number) => a - b;
174
175
// Add number that fits in middle
176
const removed1 = sortedInsert(numbers, 4, maxSize, numberComparator);
177
console.log(numbers); // [1, 3, 4, 5, 7]
178
console.log(removed1); // null (nothing removed)
179
180
// Add number when at max size
181
const removed2 = sortedInsert(numbers, 6, maxSize, numberComparator);
182
console.log(numbers); // [1, 3, 4, 5, 6] (7 was removed)
183
console.log(removed2); // 7
184
185
// Maintain sorted array of objects
186
interface PricePoint {
187
price: number;
188
timestamp: number;
189
}
190
191
const pricePoints: PricePoint[] = [];
192
const priceComparator = (a: PricePoint, b: PricePoint) => a.price - b.price;
193
194
sortedInsert(pricePoints, { price: 100, timestamp: Date.now() }, 10, priceComparator);
195
sortedInsert(pricePoints, { price: 95, timestamp: Date.now() }, 10, priceComparator);
196
console.log(pricePoints); // Sorted by price: [{ price: 95, ... }, { price: 100, ... }]
197
```
198
199
### zkSync Utilities
200
201
Specialized utilities for zkSync blockchain operations.
202
203
```typescript { .api }
204
/**
205
* Compute zkSync CREATE2 address for contract deployment
206
* @param sender - Address of the contract deployer
207
* @param bytecodeHash - Hash of the contract bytecode
208
* @param salt - Salt value for deterministic address generation
209
* @param input - Constructor input data (default: '0x')
210
* @returns Computed zkSync CREATE2 address
211
*/
212
function computeZksyncCreate2Address(
213
sender: string,
214
bytecodeHash: BytesLike,
215
salt: BytesLike,
216
input: BytesLike = '0x'
217
): string;
218
```
219
220
**Usage Examples:**
221
222
```typescript
223
import { computeZksyncCreate2Address } from "@uniswap/sdk-core";
224
import { keccak256, toUtf8Bytes } from "@ethersproject/strings";
225
226
// Compute zkSync CREATE2 address
227
const deployer = "0x1234567890123456789012345678901234567890";
228
const bytecodeHash = keccak256(toUtf8Bytes("contract bytecode"));
229
const salt = keccak256(toUtf8Bytes("unique salt"));
230
231
const create2Address = computeZksyncCreate2Address(
232
deployer,
233
bytecodeHash,
234
salt
235
);
236
237
console.log(create2Address); // Computed zkSync CREATE2 address
238
239
// With constructor input
240
const constructorInput = "0x000000000000000000000000abcdefabcdefabcdefabcdefabcdefabcdefabcd";
241
const create2AddressWithInput = computeZksyncCreate2Address(
242
deployer,
243
bytecodeHash,
244
salt,
245
constructorInput
246
);
247
248
console.log(create2AddressWithInput); // Address with constructor parameters
249
```
250
251
## Constants
252
253
```typescript { .api }
254
/**
255
* Maximum uint256 value used for amount validation
256
*/
257
const MaxUint256: JSBI;
258
259
/**
260
* Trade type enumeration
261
*/
262
enum TradeType {
263
EXACT_INPUT,
264
EXACT_OUTPUT,
265
}
266
```