Skip to content

Commit

Permalink
Rate -> Fraction
Browse files Browse the repository at this point in the history
make new Fraction class more robust / generic

tweak tsconfig
  • Loading branch information
NoahZinsmeister committed Jan 17, 2020
1 parent 8ecdc26 commit 2953d4c
Show file tree
Hide file tree
Showing 13 changed files with 905 additions and 899 deletions.
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,20 @@
"start": "tsdx watch",
"test": "tsdx test"
},
"devDependencies": {
"@types/big.js": "^4.0.5",
"@types/jest": "^24.0.25",
"tsdx": "^0.12.1",
"tslib": "^1.10.0",
"typescript": "^3.7.4"
},
"dependencies": {
"@ethersproject/address": "^5.0.0-beta.134",
"big.js": "^5.2.2",
"decimal.js-light": "^2.5.0",
"tiny-invariant": "^1.0.6",
"toformat": "^2.0.0"
},
"devDependencies": {
"@types/big.js": "^4.0.5",
"@types/jest": "^24.0.25",
"tsdx": "^0.12.1",
"tslib": "^1.10.0",
"typescript": "^3.7.5"
},
"engines": {
"node": ">=10"
},
Expand Down
4 changes: 3 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ export enum TradeType {

// exports for internal consumption
export const ZERO = BigInt(0)
export const ONE = BigInt(1)
export const TEN = BigInt(10)
export const _1000 = BigInt(1000)
export const _100 = BigInt(100)
export const _997 = BigInt(997)
export const _1000 = BigInt(1000)

export enum SolidityType {
uint8,
Expand Down
98 changes: 98 additions & 0 deletions src/entities/fractions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import invariant from 'tiny-invariant'

import { ZERO, ONE, TEN, _100 } from '../constants'
import { BigintIsh } from '../types'
import { parseBigintIsh } from '../utils/parseInputs'
import { formatSignificant, formatFixed } from '../utils/formatOutputs'
import { Route } from './route'

export class Fraction {
public readonly numerator: bigint
public readonly denominator: bigint

constructor(numerator: BigintIsh, denominator: BigintIsh = ONE) {
this.numerator = parseBigintIsh(numerator)
this.denominator = parseBigintIsh(denominator)
}

// warning: this can truncate!
get quotient() {
return this.numerator / this.denominator
}

public invert(): Fraction {
return new Fraction(this.denominator, this.numerator)
}

public multiply(other: Fraction): Fraction {
return new Fraction(this.numerator * other.numerator, this.denominator * other.denominator)
}

public formatSignificant(significantDigits: number, ...rest: any[]): string {
return formatSignificant(this.numerator, this.denominator, significantDigits, ...rest)
}

public formatFixed(decimalPlaces: number, ...rest: any[]): string {
return formatFixed(this.numerator, this.denominator, decimalPlaces, ...rest)
}
}

export class Price {
public readonly price: Fraction // normalized
public readonly scalar: Fraction // used to convert back to raw balances

static fromRoute(route: Route): Price {
const prices: Fraction[] = route.exchanges.map((exchange, i) => {
const input = route.path[i]
const baseIndex = input.address === exchange.pair[0].address ? 0 : 1
const quoteIndex = input.address === exchange.pair[0].address ? 1 : 0
return new Fraction(
exchange.balances[quoteIndex] * TEN ** BigInt(exchange.pair[baseIndex].decimals),
exchange.balances[baseIndex] * TEN ** BigInt(exchange.pair[quoteIndex].decimals)
)
})
const price = prices.reduce((accumulator, currentValue) => accumulator.multiply(currentValue), new Fraction(ONE))
const scalar = new Fraction(TEN ** BigInt(route.output.decimals), TEN ** BigInt(route.input.decimals))
return new Price(price, scalar)
}

constructor(price: Fraction, scalar: Fraction) {
this.price = price
this.scalar = scalar
}

public invert(): Price {
return new Price(this.price.invert(), this.scalar.invert())
}

public quote(amount: BigintIsh): bigint {
const amountParsed = parseBigintIsh(amount)
invariant(amountParsed > ZERO, `${amountParsed} isn't positive.`)

return this.price.multiply(this.scalar).multiply(new Fraction(amount)).quotient
}

public formatSignificant(significantDigits = 6, ...rest: any[]) {
return this.price.formatSignificant(significantDigits, ...rest)
}

public formatFixed(decimalPlaces = 6, ...rest: any[]) {
return this.price.formatFixed(decimalPlaces, ...rest)
}
}

export class Percent {
public readonly percent: Fraction

constructor(percent: Fraction) {
this.percent = percent
}

public formatSignificant(significantDigits = 5, ...rest: any[]) {
return this.percent.multiply(new Fraction(_100)).formatSignificant(significantDigits, ...rest)
}

public formatFixed(decimalPlaces = 2, ...rest: any[]) {
return this.percent.multiply(new Fraction(_100)).formatFixed(decimalPlaces, ...rest)
}
}
2 changes: 2 additions & 0 deletions src/entities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ export * from './token'
export * from './exchange'
export * from './route'
export * from './trade'

export * from './fractions'
82 changes: 0 additions & 82 deletions src/entities/rate.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/entities/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import invariant from 'tiny-invariant'

import { Token } from './token'
import { Exchange } from './exchange'
import { Price } from './rate'
import { Price } from './fractions'

export class Route {
public readonly exchanges: Exchange[]
Expand Down
48 changes: 24 additions & 24 deletions src/entities/trade.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import invariant from 'tiny-invariant'

import { _997, _1000, SolidityType, TradeType } from '../constants'
import { BigintIsh, Fraction } from '../types'
import { ZERO, ONE, _997, _1000, SolidityType, TradeType } from '../constants'
import { BigintIsh } from '../types'
import { parseBigintIsh } from '../utils/parseInputs'
import { validateSolidityTypeInstance } from '../utils/validateInputs'
import { Exchange } from './exchange'
import { Route } from './route'
import { Price, Percent } from './rate'
import { Fraction, Price, Percent } from './fractions'

function getOutputAmount(inputAmount: bigint, inputReserve: bigint, outputReserve: bigint): bigint {
invariant(inputAmount > 0, `${inputAmount} is not positive.`)
invariant(inputReserve > 0, `${inputReserve} is not positive.`)
invariant(outputReserve > 0, `${outputReserve} is not positive.`)
invariant(inputAmount > ZERO, `${inputAmount} is not positive.`)
invariant(inputReserve > ZERO, `${inputReserve} is not positive.`)
invariant(outputReserve > ZERO, `${outputReserve} is not positive.`)
const inputAmountWithFee = inputAmount * _997
const numerator = inputAmountWithFee * outputReserve
const denominator = inputReserve * _1000 + inputAmountWithFee
Expand All @@ -24,26 +24,27 @@ function getInputAmount(outputAmount: bigint, inputReserve: bigint, outputReserv
invariant(outputReserve > 0, `${outputReserve} is not positive.`)
const numerator = inputReserve * outputAmount * _1000
const denominator = (outputReserve - outputAmount) * _997
return numerator / denominator + BigInt(1)
return numerator / denominator + ONE
}

function getSlippage(inputAmount: bigint, midPrice: Price, outputAmount: bigint): Percent {
const exactQuote: Fraction = [
inputAmount * midPrice.rate[0] * midPrice.scalar[0],
midPrice.rate[1] * midPrice.scalar[1]
]
const normalizedNumerator: Fraction = [outputAmount * exactQuote[1] - exactQuote[0], exactQuote[1]]
const invertedDenominator = exactQuote.slice().reverse() as Fraction
return new Percent([normalizedNumerator[0] * invertedDenominator[0], normalizedNumerator[1] * invertedDenominator[1]])
const exactQuote = midPrice.price.multiply(midPrice.scalar).multiply(new Fraction(inputAmount))
const normalizedNumerator = new Fraction(
outputAmount * exactQuote.denominator - exactQuote.numerator,
exactQuote.denominator
)
const invertedDenominator = exactQuote.invert()
return new Percent(normalizedNumerator.multiply(invertedDenominator))
}

function getPercentChange(referenceRate: Price, newRate: Price): Percent {
const normalizedNumerator: Fraction = [
newRate.rate[0] * referenceRate.rate[1] - referenceRate.rate[0] * newRate.rate[1],
referenceRate.rate[1] * newRate.rate[1]
]
const invertedDenominator = referenceRate.rate.slice().reverse() as Fraction
return new Percent([normalizedNumerator[0] * invertedDenominator[0], normalizedNumerator[1] * invertedDenominator[1]])
const normalizedNumerator = new Fraction(
newRate.price.numerator * referenceRate.price.denominator -
referenceRate.price.numerator * newRate.price.denominator,
referenceRate.price.denominator * newRate.price.denominator
)
const invertedDenominator = referenceRate.price.invert()
return new Percent(normalizedNumerator.multiply(invertedDenominator))
}

export class Trade {
Expand Down Expand Up @@ -111,14 +112,13 @@ export class Trade {
this.inputAmount = inputAmount
this.outputAmount = outputAmount
this.tradeType = tradeType
const executionPrice = new Price(
[outputAmount * route.midPrice.scalar[1], inputAmount * route.midPrice.scalar[0]],
this.executionPrice = new Price(
new Fraction(outputAmount, inputAmount).multiply(route.midPrice.scalar.invert()),
route.midPrice.scalar
)
this.executionPrice = executionPrice
this.slippage = getSlippage(inputAmount, route.midPrice, outputAmount)
const nextMidPrice = Price.fromRoute(new Route(nextExchanges, route.input))
this.nextMidPrice = nextMidPrice
this.slippage = getSlippage(inputAmount, route.midPrice, outputAmount)
this.midPricePercentChange = getPercentChange(route.midPrice, nextMidPrice)
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './types'
export { ChainId, WETH, TradeType } from './constants'

export * from './entities'
2 changes: 0 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
export type BigintIsh = bigint | string

export type Fraction = [bigint, bigint]
8 changes: 4 additions & 4 deletions src/utils/formatOutputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import _Decimal from 'decimal.js-light'
import _Big, { RoundingMode } from 'big.js'
import toFormat from 'toformat'

import { Fraction } from '../types'

const Decimal = toFormat(_Decimal)
const Big = toFormat(_Big)

export function formatSignificant(
[numerator, denominator]: Fraction,
numerator: bigint,
denominator: bigint,
significantDigits: number,
format: object = { groupSeparator: '' },
roundingMode?: number
Expand All @@ -23,7 +22,8 @@ export function formatSignificant(
}

export function formatFixed(
[numerator, denominator]: Fraction,
numerator: bigint,
denominator: bigint,
decimalPlaces: number,
format: object = { groupSeparator: '' },
roundingMode?: RoundingMode
Expand Down
Loading

0 comments on commit 2953d4c

Please sign in to comment.