Skip to content

Commit

Permalink
add JSBI :(
Browse files Browse the repository at this point in the history
  • Loading branch information
NoahZinsmeister committed Jan 21, 2020
1 parent c54d97e commit 111ffc9
Show file tree
Hide file tree
Showing 14 changed files with 460 additions and 157 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"plugins": [] // ["transform-jsbi-to-bigint"]
}
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@
"@ethersproject/address": "^5.0.0-beta.134",
"big.js": "^5.2.2",
"decimal.js-light": "^2.5.0",
"jsbi": "^3.1.1",
"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"
"babel-plugin-transform-jsbi-to-bigint": "^1.3.1",
"tsdx": "^0.12.3"
},
"engines": {
"node": ">=10"
Expand Down
14 changes: 8 additions & 6 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import JSBI from 'jsbi'

// exports for external consumption
export enum ChainId {
RINKEBY = 4
Expand All @@ -17,12 +19,12 @@ export enum TradeType {
}

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

export enum SolidityType {
uint8,
Expand Down
7 changes: 4 additions & 3 deletions src/entities/exchange.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'

import { SolidityType } from '../constants'
import { BigintIsh } from '../types'
Expand All @@ -8,9 +9,9 @@ import { Token } from './token'

export class Exchange {
public readonly pair: [Token, Token]
public readonly balances: [bigint, bigint]
public readonly balances: [JSBI, JSBI]

static validate(pair: [Token, Token], balances: [bigint, bigint]) {
static validate(pair: [Token, Token], balances: [JSBI, JSBI]) {
// validate components of an Exchange
balances.forEach(balance => validateSolidityTypeInstance(balance, SolidityType.uint256))

Expand All @@ -25,7 +26,7 @@ export class Exchange {
const balancesParsed = balances.map(balance => parseBigintIsh(balance))
const inOrder = pair[0].address < pair[1].address
const orderedPair = (inOrder ? pair : pair.slice().reverse()) as [Token, Token]
const orderedBalances = (inOrder ? balancesParsed : balancesParsed.slice().reverse()) as [bigint, bigint]
const orderedBalances = (inOrder ? balancesParsed : balancesParsed.slice().reverse()) as [JSBI, JSBI]
Exchange.validate(orderedPair, orderedBalances)

this.pair = orderedPair
Expand Down
39 changes: 26 additions & 13 deletions src/entities/fractions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'

import { ZERO, ONE, TEN, _100 } from '../constants'
import { BigintIsh } from '../types'
Expand All @@ -7,8 +8,8 @@ import { formatSignificant, formatFixed } from '../utils/formatOutputs'
import { Route } from './route'

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

constructor(numerator: BigintIsh, denominator: BigintIsh = ONE) {
this.numerator = parseBigintIsh(numerator)
Expand All @@ -17,15 +18,18 @@ export class Fraction {

// warning: this can truncate!
get quotient() {
return this.numerator / this.denominator
return JSBI.divide(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)
return new Fraction(
JSBI.multiply(this.numerator, other.numerator),
JSBI.multiply(this.denominator, other.denominator)
)
}

public formatSignificant(significantDigits: number, ...rest: any[]): string {
Expand All @@ -47,12 +51,21 @@ export class Price {
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)
JSBI.multiply(
exchange.balances[quoteIndex],
JSBI.exponentiate(TEN, JSBI.BigInt(exchange.pair[baseIndex].decimals))
),
JSBI.multiply(
exchange.balances[baseIndex],
JSBI.exponentiate(TEN, JSBI.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))
const scalar = new Fraction(
JSBI.exponentiate(TEN, JSBI.BigInt(route.output.decimals)),
JSBI.exponentiate(TEN, JSBI.BigInt(route.input.decimals))
)
return new Price(price, scalar)
}

Expand All @@ -65,18 +78,18 @@ export class Price {
return new Price(this.price.invert(), this.scalar.invert())
}

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

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

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

public formatFixed(decimalPlaces = 6, ...rest: any[]) {
public formatFixed(decimalPlaces = 6, ...rest: any[]): string {
return this.price.formatFixed(decimalPlaces, ...rest)
}
}
Expand All @@ -88,11 +101,11 @@ export class Percent {
this.percent = percent
}

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

public formatFixed(decimalPlaces = 2, ...rest: any[]) {
public formatFixed(decimalPlaces = 2, ...rest: any[]): string {
return this.percent.multiply(new Fraction(_100)).formatFixed(decimalPlaces, ...rest)
}
}
4 changes: 3 additions & 1 deletion src/entities/token.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import JSBI from 'jsbi'

import { SolidityType } from '../constants'
import { validateChainId, validateAddress, validateSolidityTypeInstance } from '../utils/validateInputs'

Expand All @@ -9,7 +11,7 @@ export class Token {
static validate(chainId: number, address: string, decimals: number) {
validateChainId(chainId)
validateAddress(address)
validateSolidityTypeInstance(BigInt(decimals), SolidityType.uint8)
validateSolidityTypeInstance(JSBI.BigInt(decimals), SolidityType.uint8)
}

constructor(chainId: number, address: string, decimals: number) {
Expand Down
61 changes: 35 additions & 26 deletions src/entities/trade.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'

import { ZERO, ONE, _997, _1000, SolidityType, TradeType } from '../constants'
import { BigintIsh } from '../types'
Expand All @@ -8,29 +9,29 @@ import { Exchange } from './exchange'
import { Route } from './route'
import { Fraction, Price, Percent } from './fractions'

function getOutputAmount(inputAmount: bigint, inputReserve: bigint, outputReserve: bigint): bigint {
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
return numerator / denominator
function getOutputAmount(inputAmount: JSBI, inputReserve: JSBI, outputReserve: JSBI): JSBI {
invariant(JSBI.greaterThan(inputAmount, ZERO), `${inputAmount} is not positive.`)
invariant(JSBI.greaterThan(inputReserve, ZERO), `${inputReserve} is not positive.`)
invariant(JSBI.greaterThan(outputReserve, ZERO), `${outputReserve} is not positive.`)
const inputAmountWithFee = JSBI.multiply(inputAmount, _997)
const numerator = JSBI.multiply(inputAmountWithFee, outputReserve)
const denominator = JSBI.add(JSBI.multiply(inputReserve, _1000), inputAmountWithFee)
return JSBI.divide(numerator, denominator)
}

function getInputAmount(outputAmount: bigint, inputReserve: bigint, outputReserve: bigint): bigint {
invariant(outputAmount > 0, `${outputAmount} is not positive.`)
invariant(inputReserve > 0, `${inputReserve} is not positive.`)
invariant(outputReserve > 0, `${outputReserve} is not positive.`)
const numerator = inputReserve * outputAmount * _1000
const denominator = (outputReserve - outputAmount) * _997
return numerator / denominator + ONE
function getInputAmount(outputAmount: JSBI, inputReserve: JSBI, outputReserve: JSBI): JSBI {
invariant(JSBI.greaterThan(outputAmount, ZERO), `${outputAmount} is not positive.`)
invariant(JSBI.greaterThan(inputReserve, ZERO), `${inputReserve} is not positive.`)
invariant(JSBI.greaterThan(outputReserve, ZERO), `${outputReserve} is not positive.`)
const numerator = JSBI.multiply(JSBI.multiply(inputReserve, outputAmount), _1000)
const denominator = JSBI.multiply(JSBI.subtract(outputReserve, outputAmount), _997)
return JSBI.add(JSBI.divide(numerator, denominator), ONE)
}

function getSlippage(inputAmount: bigint, midPrice: Price, outputAmount: bigint): Percent {
function getSlippage(inputAmount: JSBI, midPrice: Price, outputAmount: JSBI): Percent {
const exactQuote = midPrice.price.multiply(midPrice.scalar).multiply(new Fraction(inputAmount))
const normalizedNumerator = new Fraction(
outputAmount * exactQuote.denominator - exactQuote.numerator,
JSBI.subtract(JSBI.multiply(outputAmount, exactQuote.denominator), exactQuote.numerator),
exactQuote.denominator
)
const invertedDenominator = exactQuote.invert()
Expand All @@ -39,33 +40,35 @@ function getSlippage(inputAmount: bigint, midPrice: Price, outputAmount: bigint)

function getPercentChange(referenceRate: Price, newRate: Price): Percent {
const normalizedNumerator = new Fraction(
newRate.price.numerator * referenceRate.price.denominator -
referenceRate.price.numerator * newRate.price.denominator,
referenceRate.price.denominator * newRate.price.denominator
JSBI.subtract(
JSBI.multiply(newRate.price.numerator, referenceRate.price.denominator),
JSBI.multiply(referenceRate.price.numerator, newRate.price.denominator)
),
JSBI.multiply(referenceRate.price.denominator, newRate.price.denominator)
)
const invertedDenominator = referenceRate.price.invert()
return new Percent(normalizedNumerator.multiply(invertedDenominator))
}

export class Trade {
public readonly route: Route
public readonly inputAmount: bigint
public readonly outputAmount: bigint
public readonly inputAmount: JSBI
public readonly outputAmount: JSBI
public readonly tradeType: TradeType
public readonly executionPrice: Price
public readonly nextMidPrice: Price
public readonly slippage: Percent
public readonly midPricePercentChange: Percent

static validate(amount: bigint) {
static validate(amount: JSBI) {
validateSolidityTypeInstance(amount, SolidityType.uint256)
}

constructor(route: Route, amount: BigintIsh, tradeType: TradeType) {
const amountParsed = parseBigintIsh(amount)
Trade.validate(amountParsed)

const amounts: bigint[] = new Array(route.exchanges.length + 1)
const amounts: JSBI[] = new Array(route.exchanges.length + 1)
const nextExchanges: Exchange[] = new Array(route.exchanges.length)
if (tradeType === TradeType.EXACT_INPUT) {
amounts[0] = amountParsed
Expand All @@ -78,7 +81,10 @@ export class Trade {
amounts[i + 1] = outputAmount
const nextExchange = new Exchange(
[exchange.pair[inputIndex], exchange.pair[outputIndex]],
[exchange.balances[inputIndex] + inputAmount, exchange.balances[outputIndex] - outputAmount]
[
JSBI.add(exchange.balances[inputIndex], inputAmount),
JSBI.subtract(exchange.balances[outputIndex], outputAmount)
]
)
nextExchanges[i] = nextExchange
})
Expand All @@ -101,7 +107,10 @@ export class Trade {
amounts[inverseIndex] = inputAmount
const nextExchange = new Exchange(
[exchange.pair[inputIndex], exchange.pair[outputIndex]],
[exchange.balances[inputIndex] + inputAmount, exchange.balances[outputIndex] - outputAmount]
[
JSBI.add(exchange.balances[inputIndex], inputAmount),
JSBI.subtract(exchange.balances[outputIndex], outputAmount)
]
)
nextExchanges[inverseIndex] = nextExchange
})
Expand Down
4 changes: 3 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export type BigintIsh = bigint | string
import JSBI from 'jsbi'

export type BigintIsh = bigint | JSBI | string
9 changes: 5 additions & 4 deletions src/utils/formatOutputs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'
import _Decimal from 'decimal.js-light'
import _Big, { RoundingMode } from 'big.js'
import toFormat from 'toformat'
Expand All @@ -7,8 +8,8 @@ const Decimal = toFormat(_Decimal)
const Big = toFormat(_Big)

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

export function formatFixed(
numerator: bigint,
denominator: bigint,
numerator: JSBI,
denominator: JSBI,
decimalPlaces: number,
format: object = { groupSeparator: '' },
roundingMode?: RoundingMode
Expand Down
10 changes: 8 additions & 2 deletions src/utils/parseInputs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import JSBI from 'jsbi'

import { BigintIsh } from '../types'

export function parseBigintIsh(bigintIsh: BigintIsh): bigint {
return typeof bigintIsh === 'string' ? BigInt(bigintIsh) : bigintIsh
export function parseBigintIsh(bigintIsh: BigintIsh): JSBI {
return typeof bigintIsh === 'bigint'
? JSBI.BigInt(bigintIsh.toString())
: bigintIsh instanceof JSBI
? bigintIsh
: JSBI.BigInt(bigintIsh)
}
11 changes: 6 additions & 5 deletions src/utils/validateInputs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'
import { getAddress } from '@ethersproject/address'

import { ZERO, ChainId, SolidityType } from '../constants'
Expand All @@ -18,10 +19,10 @@ export function validateAddress(address: string) {
}

const SolidityTypeMaxima = {
[SolidityType.uint8]: BigInt(2 ** 8 - 1),
[SolidityType.uint256]: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff')
[SolidityType.uint8]: JSBI.BigInt(2 ** 8 - 1),
[SolidityType.uint256]: JSBI.BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff')
}
export function validateSolidityTypeInstance(value: bigint, solidityType: SolidityType) {
invariant(value >= ZERO, `${value.toString()} is negative.`)
invariant(value <= SolidityTypeMaxima[solidityType], `${value.toString()} is too large.`)
export function validateSolidityTypeInstance(value: JSBI, solidityType: SolidityType) {
invariant(JSBI.greaterThanOrEqual(value, ZERO), `${value} is negative.`)
invariant(JSBI.lessThanOrEqual(value, SolidityTypeMaxima[solidityType]), `${value} is too large.`)
}
Loading

0 comments on commit 111ffc9

Please sign in to comment.