or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

chains-and-addresses.mdcurrency-system.mdindex.mdmathematical-operations.mdutilities.md

mathematical-operations.mddocs/

0

# Mathematical Operations

1

2

Precise fractional arithmetic and currency amount calculations using JSBI for handling large numbers without precision loss, essential for financial applications.

3

4

## Capabilities

5

6

### Fraction Class

7

8

Core fraction arithmetic with precise decimal operations using JSBI to avoid floating-point errors.

9

10

```typescript { .api }

11

/**

12

* Represents a fraction with numerator and denominator using JSBI for precision

13

*/

14

class Fraction {

15

/** The numerator of the fraction */

16

readonly numerator: JSBI;

17

/** The denominator of the fraction */

18

readonly denominator: JSBI;

19

20

/**

21

* @param numerator - The numerator as BigintIsh

22

* @param denominator - The denominator as BigintIsh (defaults to 1)

23

*/

24

constructor(numerator: BigintIsh, denominator?: BigintIsh);

25

26

/** Performs floor division - returns the quotient */

27

get quotient(): JSBI;

28

29

/** Returns remainder after floor division */

30

get remainder(): Fraction;

31

32

/** Helper method for converting any super class back to a fraction */

33

get asFraction(): Fraction;

34

35

/** Returns the inverted fraction (denominator/numerator) */

36

invert(): Fraction;

37

38

/**

39

* Add another fraction or BigintIsh value

40

* @param other - Fraction or BigintIsh to add

41

*/

42

add(other: Fraction | BigintIsh): Fraction;

43

44

/**

45

* Subtract another fraction or BigintIsh value

46

* @param other - Fraction or BigintIsh to subtract

47

*/

48

subtract(other: Fraction | BigintIsh): Fraction;

49

50

/**

51

* Multiply by another fraction or BigintIsh value

52

* @param other - Fraction or BigintIsh to multiply by

53

*/

54

multiply(other: Fraction | BigintIsh): Fraction;

55

56

/**

57

* Divide by another fraction or BigintIsh value

58

* @param other - Fraction or BigintIsh to divide by

59

*/

60

divide(other: Fraction | BigintIsh): Fraction;

61

62

/**

63

* Check if this fraction is less than another

64

* @param other - Fraction or BigintIsh to compare

65

*/

66

lessThan(other: Fraction | BigintIsh): boolean;

67

68

/**

69

* Check if this fraction equals another

70

* @param other - Fraction or BigintIsh to compare

71

*/

72

equalTo(other: Fraction | BigintIsh): boolean;

73

74

/**

75

* Check if this fraction is greater than another

76

* @param other - Fraction or BigintIsh to compare

77

*/

78

greaterThan(other: Fraction | BigintIsh): boolean;

79

80

/**

81

* Format to string with specified significant digits

82

* @param significantDigits - Number of significant digits

83

* @param format - Formatting options (default: { groupSeparator: '' })

84

* @param rounding - Rounding mode (default: ROUND_HALF_UP)

85

*/

86

toSignificant(

87

significantDigits: number,

88

format?: object,

89

rounding?: Rounding

90

): string;

91

92

/**

93

* Format to string with fixed decimal places

94

* @param decimalPlaces - Number of decimal places

95

* @param format - Formatting options (default: { groupSeparator: '' })

96

* @param rounding - Rounding mode (default: ROUND_HALF_UP)

97

*/

98

toFixed(

99

decimalPlaces: number,

100

format?: object,

101

rounding?: Rounding

102

): string;

103

}

104

```

105

106

### Currency Amount Class

107

108

Represents an amount of a specific currency with automatic decimal scaling.

109

110

```typescript { .api }

111

/**

112

* Currency amount with automatic decimal scaling and currency-aware operations

113

*/

114

class CurrencyAmount<T extends Currency> extends Fraction {

115

/** The currency this amount represents */

116

readonly currency: T;

117

/** Decimal scale factor for this currency */

118

readonly decimalScale: JSBI;

119

120

/**

121

* Create currency amount from raw amount (smallest unit)

122

* @param currency - The currency

123

* @param rawAmount - Raw amount in smallest unit (e.g., wei for ETH)

124

*/

125

static fromRawAmount<T extends Currency>(

126

currency: T,

127

rawAmount: BigintIsh

128

): CurrencyAmount<T>;

129

130

/**

131

* Create currency amount from fractional amount

132

* @param currency - The currency

133

* @param numerator - Numerator of the fraction

134

* @param denominator - Denominator of the fraction

135

*/

136

static fromFractionalAmount<T extends Currency>(

137

currency: T,

138

numerator: BigintIsh,

139

denominator: BigintIsh

140

): CurrencyAmount<T>;

141

142

/**

143

* Add another currency amount (must be same currency)

144

* @param other - CurrencyAmount to add

145

*/

146

add(other: CurrencyAmount<T>): CurrencyAmount<T>;

147

148

/**

149

* Subtract another currency amount (must be same currency)

150

* @param other - CurrencyAmount to subtract

151

*/

152

subtract(other: CurrencyAmount<T>): CurrencyAmount<T>;

153

154

/**

155

* Multiply by a fraction or BigintIsh

156

* @param other - Fraction or BigintIsh to multiply by

157

*/

158

multiply(other: Fraction | BigintIsh): CurrencyAmount<T>;

159

160

/**

161

* Divide by a fraction or BigintIsh

162

* @param other - Fraction or BigintIsh to divide by

163

*/

164

divide(other: Fraction | BigintIsh): CurrencyAmount<T>;

165

166

/**

167

* Format to string with significant digits

168

* @param significantDigits - Number of significant digits (default: 6)

169

* @param format - Formatting options

170

* @param rounding - Rounding mode (default: ROUND_DOWN)

171

*/

172

toSignificant(

173

significantDigits?: number,

174

format?: object,

175

rounding?: Rounding

176

): string;

177

178

/**

179

* Format to string with fixed decimal places

180

* @param decimalPlaces - Number of decimal places (default: currency.decimals)

181

* @param format - Formatting options

182

* @param rounding - Rounding mode (default: ROUND_DOWN)

183

*/

184

toFixed(

185

decimalPlaces?: number,

186

format?: object,

187

rounding?: Rounding

188

): string;

189

190

/**

191

* Format to exact string representation

192

* @param format - Formatting options (default: { groupSeparator: '' })

193

*/

194

toExact(format?: object): string;

195

196

/** Get wrapped version of this currency amount */

197

get wrapped(): CurrencyAmount<Token>;

198

}

199

```

200

201

### Price Class

202

203

Represents exchange rate between two currencies with type safety.

204

205

```typescript { .api }

206

/**

207

* Represents the exchange rate between two currencies

208

*/

209

class Price<TBase extends Currency, TQuote extends Currency> extends Fraction {

210

/** Input currency (denominator) */

211

readonly baseCurrency: TBase;

212

/** Output currency (numerator) */

213

readonly quoteCurrency: TQuote;

214

/** Scalar used to adjust the raw fraction w/r/t the decimals of the currencies */

215

readonly scalar: Fraction;

216

217

/**

218

* Construct a price with base and quote currencies and amounts

219

* @param args - Either [baseCurrency, quoteCurrency, denominator, numerator] or [{ baseAmount, quoteAmount }]

220

*/

221

constructor(

222

...args:

223

| [TBase, TQuote, BigintIsh, BigintIsh]

224

| [{ baseAmount: CurrencyAmount<TBase>; quoteAmount: CurrencyAmount<TQuote> }]

225

);

226

227

/** Flip the price, switching the base and quote currency */

228

invert(): Price<TQuote, TBase>;

229

230

/**

231

* Multiply the price by another price

232

* @param other - Price to multiply with (must have matching quote/base currencies)

233

*/

234

multiply<TOtherQuote extends Currency>(

235

other: Price<TQuote, TOtherQuote>

236

): Price<TBase, TOtherQuote>;

237

238

/**

239

* Return the amount of quote currency corresponding to a given amount of the base currency

240

* @param currencyAmount - Amount of base currency to quote

241

*/

242

quote(currencyAmount: CurrencyAmount<TBase>): CurrencyAmount<TQuote>;

243

244

/**

245

* Format price to significant digits

246

* @param significantDigits - Number of significant digits (default: 6)

247

* @param format - Formatting options

248

* @param rounding - Rounding mode

249

*/

250

toSignificant(significantDigits?: number, format?: object, rounding?: Rounding): string;

251

252

/**

253

* Format price to fixed decimal places

254

* @param decimalPlaces - Number of decimal places (default: 4)

255

* @param format - Formatting options

256

* @param rounding - Rounding mode

257

*/

258

toFixed(decimalPlaces?: number, format?: object, rounding?: Rounding): string;

259

}

260

```

261

262

### Percent Class

263

264

Specialized fraction for representing percentages with automatic formatting.

265

266

```typescript { .api }

267

/**

268

* Represents a percentage value

269

*/

270

class Percent extends Fraction {

271

/** Boolean identifier for percentage values */

272

readonly isPercent: true;

273

274

/** Add another fraction or BigintIsh, returning a Percent */

275

add(other: Fraction | BigintIsh): Percent;

276

277

/** Subtract another fraction or BigintIsh, returning a Percent */

278

subtract(other: Fraction | BigintIsh): Percent;

279

280

/** Multiply by another fraction or BigintIsh, returning a Percent */

281

multiply(other: Fraction | BigintIsh): Percent;

282

283

/** Divide by another fraction or BigintIsh, returning a Percent */

284

divide(other: Fraction | BigintIsh): Percent;

285

286

/**

287

* Format as percentage with significant digits

288

* @param significantDigits - Number of significant digits (default: 5)

289

* @param format - Formatting options

290

* @param rounding - Rounding mode

291

*/

292

toSignificant(significantDigits?: number, format?: object, rounding?: Rounding): string;

293

294

/**

295

* Format as percentage with fixed decimal places

296

* @param decimalPlaces - Number of decimal places (default: 2)

297

* @param format - Formatting options

298

* @param rounding - Rounding mode

299

*/

300

toFixed(decimalPlaces?: number, format?: object, rounding?: Rounding): string;

301

}

302

```

303

304

**Usage Examples:**

305

306

```typescript

307

import {

308

Fraction,

309

CurrencyAmount,

310

Price,

311

Percent,

312

Token,

313

Ether,

314

ChainId,

315

Rounding

316

} from "@uniswap/sdk-core";

317

318

// Create fractions for precise arithmetic

319

const half = new Fraction(1, 2);

320

const quarter = new Fraction(1, 4);

321

322

console.log(half.add(quarter).toSignificant(2)); // "0.75"

323

console.log(half.multiply(2).toFixed(0)); // "1"

324

325

// Work with currency amounts

326

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

327

const ether = Ether.onChain(ChainId.MAINNET);

328

329

// Create amounts from raw values (smallest units)

330

const usdcAmount = CurrencyAmount.fromRawAmount(USDC, "1000000"); // 1 USDC

331

const etherAmount = CurrencyAmount.fromRawAmount(ether, "1000000000000000000"); // 1 ETH

332

333

console.log(usdcAmount.toExact()); // "1"

334

console.log(etherAmount.toExact()); // "1"

335

336

// Arithmetic with currency amounts

337

const doubleUsdc = usdcAmount.multiply(2);

338

console.log(doubleUsdc.toExact()); // "2"

339

340

const halfEther = etherAmount.divide(2);

341

console.log(halfEther.toExact()); // "0.5"

342

343

// Create prices between currencies

344

const price = new Price({

345

baseAmount: etherAmount,

346

quoteAmount: CurrencyAmount.fromRawAmount(USDC, "2000000000") // 2000 USDC per ETH

347

});

348

349

console.log(price.toSignificant(4)); // "2000"

350

351

// Quote amounts using price

352

const ethToQuote = CurrencyAmount.fromRawAmount(ether, "500000000000000000"); // 0.5 ETH

353

const quotedUsdc = price.quote(ethToQuote);

354

console.log(quotedUsdc.toExact()); // "1000" (0.5 ETH * 2000 USDC/ETH)

355

356

// Work with percentages

357

const fivePercent = new Percent(5, 100);

358

const tenPercent = new Percent(1, 10);

359

360

console.log(fivePercent.toFixed(2)); // "5.00"

361

console.log(tenPercent.add(fivePercent).toFixed(1)); // "15.0"

362

363

// Use different rounding modes

364

const fraction = new Fraction(1, 3);

365

console.log(fraction.toFixed(2, undefined, Rounding.ROUND_DOWN)); // "0.33"

366

console.log(fraction.toFixed(2, undefined, Rounding.ROUND_UP)); // "0.34"

367

```

368

369

## Types

370

371

```typescript { .api }

372

/**

373

* Union type for big integer-like values

374

*/

375

type BigintIsh = JSBI | string | number;

376

377

/**

378

* Rounding modes for decimal formatting

379

*/

380

enum Rounding {

381

ROUND_DOWN,

382

ROUND_HALF_UP,

383

ROUND_UP,

384

}

385

```