Commit 111ffc96 authored by Noah Zinsmeister's avatar Noah Zinsmeister

add JSBI :(

parent c54d97e0
{
"plugins": [] // ["transform-jsbi-to-bigint"]
}
......@@ -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"
......
import JSBI from 'jsbi'
// exports for external consumption
export enum ChainId {
RINKEBY = 4
......@@ -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,
......
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'
import { SolidityType } from '../constants'
import { BigintIsh } from '../types'
......@@ -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))
......@@ -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
......
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'
import { ZERO, ONE, TEN, _100 } from '../constants'
import { BigintIsh } from '../types'
......@@ -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)
......@@ -17,7 +18,7 @@ export class Fraction {
// warning: this can truncate!
get quotient() {
return this.numerator / this.denominator
return JSBI.divide(this.numerator, this.denominator)
}
public invert(): Fraction {
......@@ -25,7 +26,10 @@ export class Fraction {
}
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 {
......@@ -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)
}
......@@ -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)
}
}
......@@ -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)
}
}
import JSBI from 'jsbi'
import { SolidityType } from '../constants'
import { validateChainId, validateAddress, validateSolidityTypeInstance } from '../utils/validateInputs'
......@@ -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) {
......
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'
import { ZERO, ONE, _997, _1000, SolidityType, TradeType } from '../constants'
import { BigintIsh } from '../types'
......@@ -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()
......@@ -39,9 +40,11 @@ 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))
......@@ -49,15 +52,15 @@ function getPercentChange(referenceRate: Price, newRate: Price): Percent {
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)
}
......@@ -65,7 +68,7 @@ export class Trade {
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
......@@ -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
})
......@@ -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
})
......
export type BigintIsh = bigint | string
import JSBI from 'jsbi'
export type BigintIsh = bigint | JSBI | string
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'
......@@ -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
......@@ -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
......
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)
}
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'
import { getAddress } from '@ethersproject/address'
import { ZERO, ChainId, SolidityType } from '../constants'
......@@ -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.`)
}
......@@ -63,12 +63,15 @@ describe('entities', () => {
})
it('Rate via Route.marketRate', () => {
expect(route.midPrice.quote(decimalize(1, route.input.decimals))).toEqual(
decimalize(1234, route.output.decimals)
)
expect(route.midPrice.invert().quote(decimalize(1234, route.output.decimals))).toEqual(
decimalize(1, route.input.decimals)
expect(route.midPrice.quote(decimalize(1, route.input.decimals)).toString()).toEqual(
decimalize(1234, route.output.decimals).toString()
)
expect(
route.midPrice
.invert()
.quote(decimalize(1234, route.output.decimals))
.toString()
).toEqual(decimalize(1, route.input.decimals).toString())
expect(route.midPrice.formatSignificant(1)).toEqual('1000')
expect(route.midPrice.formatSignificant(2)).toEqual('1200')
......@@ -105,13 +108,18 @@ describe('entities', () => {
const route = new Route(exchanges, tokens[1])
const inputAmount = decimalize(1, tokens[1].decimals)
const trade = new Trade(route, inputAmount, TradeType.EXACT_INPUT)
expect(trade.inputAmount).toEqual(inputAmount)
expect(trade.outputAmount).toEqual(BigInt('1662497915624478906'))
expect(trade.inputAmount.toString()).toEqual(inputAmount.toString())
expect(trade.outputAmount.toString()).toEqual('1662497915624478906')
expect(trade.executionPrice.formatSignificant(18)).toEqual('1.66249791562447891')
expect(trade.executionPrice.invert().formatSignificant(18)).toEqual('0.601504513540621866')
expect(trade.executionPrice.quote(inputAmount)).toEqual(trade.outputAmount)
expect(trade.executionPrice.invert().quote(trade.outputAmount)).toEqual(inputAmount)
expect(trade.executionPrice.quote(inputAmount).toString()).toEqual(trade.outputAmount.toString())
expect(
trade.executionPrice
.invert()
.quote(trade.outputAmount)
.toString()
).toEqual(inputAmount.toString())
expect(trade.nextMidPrice.formatSignificant(18)).toEqual('1.38958368072925352')
expect(trade.nextMidPrice.invert().formatSignificant(18)).toEqual('0.71964')
......@@ -128,14 +136,19 @@ describe('entities', () => {
const route = new Route(exchanges, tokens[1])
const outputAmount = BigInt('1662497915624478906')
const trade = new Trade(route, outputAmount, TradeType.EXACT_OUTPUT)
expect(trade.inputAmount).toEqual(decimalize(1, tokens[1].decimals))
expect(trade.outputAmount).toEqual(outputAmount)
expect(trade.inputAmount.toString()).toEqual(decimalize(1, tokens[1].decimals).toString())
expect(trade.outputAmount.toString()).toEqual(outputAmount.toString())
// TODO think about inverse execution price?
expect(trade.executionPrice.formatSignificant(18)).toEqual('1.66249791562447891')
expect(trade.executionPrice.invert().formatSignificant(18)).toEqual('0.601504513540621866')
expect(trade.executionPrice.quote(trade.inputAmount)).toEqual(outputAmount)
expect(trade.executionPrice.invert().quote(outputAmount)).toEqual(trade.inputAmount)
expect(trade.executionPrice.quote(trade.inputAmount).toString()).toEqual(outputAmount.toString())
expect(
trade.executionPrice
.invert()
.quote(outputAmount)
.toString()
).toEqual(trade.inputAmount.toString())
expect(trade.nextMidPrice.formatSignificant(18)).toEqual('1.38958368072925352')
expect(trade.nextMidPrice.invert().formatSignificant(18)).toEqual('0.71964')
......
{
"include": ["src", "types", "test"],
"compilerOptions": {
"target": "es2020",
"target": "es2018",
"module": "esnext",
"importHelpers": true,
"declaration": true,
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment