add pool transaction count, update pool reserves correctly, prevent div-by-zero errors.

This commit is contained in:
ssallam 2020-12-09 11:54:13 +01:00
parent b47cf07f18
commit 7337d68db7
6 changed files with 97 additions and 103 deletions

View File

@ -7,7 +7,6 @@ type PoolFactory @entity {
poolCount: Int! # Number of pools
finalizedPoolCount: Int! # Number of finalized pools
txCount: BigInt! # Number of txs
pools: [Pool!] @derivedFrom(field: "factoryID")
}
@ -39,6 +38,7 @@ type Pool @entity {
joinCount: BigInt! # liquidity has been added
exitCount: BigInt! # liquidity has been removed
swapCount: BigInt!
transactionCount: BigInt! # Number of transactions in this pool involving liquidity changes
datatokenAddress: String!
createTime: Int! # Block time pool was created
@ -91,6 +91,7 @@ type PoolTransaction @entity {
sharesBalance: BigDecimal!
spotPrice: BigDecimal!
consumePrice: BigDecimal!
tx: Bytes!
event: String
block: Int!
@ -108,7 +109,6 @@ type DatatokenFactory @entity {
id: ID!
tokenCount: Int! # Number of datatokens
txCount: BigInt! # Number of txs
datatokens: [Datatoken!] @derivedFrom(field: "factoryID")
}

View File

@ -10,7 +10,8 @@ import {
tokenToDecimal,
updateTokenBalance,
ZERO_BD,
MINUS_1, saveTokenTransaction
MINUS_1_BD,
saveTokenTransaction
} from './helpers'
/************************************
@ -48,13 +49,13 @@ export function handleTransfer(event: Transfer): void {
tokenBalanceFrom = TokenBalance.load(tokenBalanceFromId)
oldBalanceFrom = (tokenBalanceFrom == null) ? ZERO_BD : tokenBalanceFrom.balance
datatoken.supply = datatoken.supply.minus(amount)
updateTokenBalance(tokenBalanceFromId, tokenId, tokenShareFrom, amount.times(MINUS_1))
updateTokenBalance(tokenBalanceFromId, tokenId, tokenShareFrom, amount.times(MINUS_1_BD))
} else {
tokenBalanceFrom = TokenBalance.load(tokenBalanceFromId)
oldBalanceFrom = (tokenBalanceFrom == null) ? ZERO_BD : tokenBalanceFrom.balance
datatoken.supply = datatoken.supply.minus(amount)
updateTokenBalance(tokenBalanceFromId, tokenId, tokenShareFrom, amount.times(MINUS_1))
updateTokenBalance(tokenBalanceFromId, tokenId, tokenShareFrom, amount.times(MINUS_1_BD))
tokenBalanceTo = TokenBalance.load(tokenBalanceToId)
oldBalanceTo = (tokenBalanceTo == null) ? ZERO_BD : tokenBalanceTo.balance

View File

@ -17,7 +17,6 @@ export function handleNewToken(event: TokenRegistered): void {
if (factory == null) {
factory = new DatatokenFactory('1')
factory.tokenCount = 0
factory.txCount = BigInt.fromI32(0)
}
let datatoken = new DatatokenEntity(event.params.tokenAddress.toHexString())

View File

@ -19,7 +19,6 @@ export function handleNewPool(event: BPoolRegistered): void {
factory.poolCount = 0
factory.finalizedPoolCount = 0
factory.txCount = BigInt.fromI32(0)
}
let pool = new Pool(event.params.bpoolAddress.toHexString())
@ -50,6 +49,7 @@ export function handleNewPool(event: BPoolRegistered): void {
pool.joinCount = BigInt.fromI32(0)
pool.exitCount = BigInt.fromI32(0)
pool.swapCount = BigInt.fromI32(0)
pool.transactionCount = BigInt.fromI32(0)
pool.datatokenAddress = ''

View File

@ -23,15 +23,13 @@ import { log } from '@graphprotocol/graph-ts'
import { Pool } from '../types/templates/Pool/Pool'
export let ZERO_BD = BigDecimal.fromString('0.0')
export let MINUS_1 = BigDecimal.fromString('-1.0')
export let ONE = BigDecimal.fromString('1.0')
export let MINUS_1_BD = BigDecimal.fromString('-1.0')
export let ONE_BD = BigDecimal.fromString('1.0')
export let ONE_INT = BigInt.fromI32(10).pow(18 as u8)
export let ONE_BASE_18 = BigInt.fromI32(10).pow(18 as u8)
export let BONE = BigDecimal.fromString('1000000000000000000')
export let ENABLE_DEBUG = false
export let DEBUG_POOL_ADDRESS = '0x64269ce81a07f21cb3566afa752810c4ca0bcb6f'
let network = dataSource.network()
@ -47,7 +45,7 @@ export function _debuglog(message: string, event: ethereum.Event, args: Array<st
for (let i=0; i < args.length; i++) {
message = message.concat(' {}')
}
log.error('@@@@@@@@@@@@@@@@@@@ ' + message, args)
log.info('@@@@@@ ' + message, args)
}
export function debuglog(message: string, event: ethereum.Event, args: Array<string>): void {
@ -80,10 +78,8 @@ export function decimalToBigInt(value: BigDecimal): BigInt {
}
export function updatePoolTokenBalance(poolToken: PoolToken, balance: BigDecimal, source: string): void {
if (poolToken.poolId == DEBUG_POOL_ADDRESS && poolToken.tokenAddress == OCEAN) {
_debuglog('########## updating poolToken balance (source, oldBalance, newBalance, poolId) ', null,
[source, poolToken.balance.toString(), balance.toString(), poolToken.poolId])
}
debuglog('########## updating poolToken balance (source, oldBalance, newBalance, poolId) ', null,
[source, poolToken.balance.toString(), balance.toString(), poolToken.poolId])
poolToken.balance = balance
}
@ -117,6 +113,7 @@ export function updatePoolTransactionToken(
let ptx = PoolTransaction.load(poolTx)
let poolToken = PoolToken.load(poolTokenId)
let pool = PoolEntity.load(poolToken.poolId)
let ptxTokenValuesId = poolTx.concat('-').concat(poolToken.tokenAddress)
let ptxTokenValues = PoolTransactionTokenValues.load(ptxTokenValuesId)
if (ptxTokenValues == null) {
@ -141,22 +138,23 @@ export function updatePoolTransactionToken(
if (ptxTokenValues.tokenAddress == OCEAN) {
ptx.oceanReserve = ptxTokenValues.tokenReserve
pool.oceanReserve = ptxTokenValues.tokenReserve
} else {
ptx.datatokenReserve = ptxTokenValues.tokenReserve
pool.datatokenReserve = ptxTokenValues.tokenReserve
}
if (poolToken.poolId == DEBUG_POOL_ADDRESS && poolToken.tokenAddress == OCEAN) {
_debuglog('########## updatePoolTransactionToken: ', null,
[
BigInt.fromI32(ptx.block).toString(),
BigInt.fromI32(ptx.timestamp).toString(),
ptxTokenValues.type,
ptxTokenValues.value.toString(),
ptxTokenValues.tokenReserve.toString(),
poolToken.poolId,
])
}
debuglog('########## updatePoolTransactionToken: ', null,
[
BigInt.fromI32(ptx.block).toString(),
BigInt.fromI32(ptx.timestamp).toString(),
ptxTokenValues.type,
ptxTokenValues.value.toString(),
ptxTokenValues.tokenReserve.toString(),
poolToken.poolId,
])
ptx.save()
pool.save()
}
export function createPoolTransaction(event: ethereum.Event, event_type: string, userAddress: string): void {
@ -184,42 +182,45 @@ export function createPoolTransaction(event: ethereum.Event, event_type: string,
poolTx.sharesTransferAmount = ZERO_BD
poolTx.sharesBalance = ZERO_BD
poolTx.spotPrice = calcSpotPrice(
ocnToken.denormWeight, dtToken.denormWeight, ocnToken.balance, dtToken.balance, pool.swapFee)
pool.datatokenReserve = dtToken.balance
pool.oceanReserve = ocnToken.balance
// pool.datatokenReserve = dtToken.balance
// pool.oceanReserve = ocnToken.balance
// Initial reserve values, will be updated in `updatePoolTransactionToken`
poolTx.datatokenReserve = dtToken.balance
poolTx.oceanReserve = ocnToken.balance
let p = Pool.bind(Address.fromString(poolId))
let result = p.try_getSpotPrice(
Address.fromString(ocnToken.tokenAddress),
Address.fromString(dtToken.tokenAddress))
// pool.spotPrice = poolTx.spotPrice
pool.consumePrice = result.reverted ? BigDecimal.fromString('-1') : bigIntToDecimal(result.value, 18)
let priceResult = p.try_calcInGivenOut(
decimalToBigInt(ocnToken.balance), decimalToBigInt(ocnToken.denormWeight),
decimalToBigInt(dtToken.balance), decimalToBigInt(dtToken.denormWeight),
ONE_BASE_18, decimalToBigInt(pool.swapFee)
)
debuglog(
'args to calcInGivenOut (ocnBalance, ocnWeight, dtBalance, dtWeight, dtAmount, swapFee, result)', null,
[
decimalToBigInt(ocnToken.balance).toString(),
decimalToBigInt(ocnToken.denormWeight).toString(),
decimalToBigInt(dtToken.balance).toString(),
decimalToBigInt(dtToken.denormWeight).toString(),
ONE_BASE_18.toString(),
decimalToBigInt(pool.swapFee).toString(),
priceResult.reverted ? 'failed' : priceResult.value.toString()
]
)
poolTx.consumePrice = priceResult.reverted ? MINUS_1_BD : bigIntToDecimal(priceResult.value, 18)
poolTx.spotPrice = calcSpotPrice(
ocnToken.balance, ocnToken.denormWeight,
dtToken.balance, dtToken.denormWeight,
pool.swapFee
)
// let result = p.try_calcInGivenOut(
// decimalToBigInt(ocnToken.balance), decimalToBigInt(ocnToken.denormWeight),
// decimalToBigInt(dtToken.balance), decimalToBigInt(dtToken.denormWeight),
// ONE_INT, decimalToBigInt(pool.swapFee)
// )
// pool.consumePrice = BigDecimal.fromString('-1')//result.reverted ? BigDecimal.fromString('-1') : bigIntToDecimal(result.value, 18)
// debuglog(
// 'args to calcInGivenOut (ocnBalance, ocnWeight, dtBalance, dtWeight, dtAmount, swapFee, result)', null,
// [
// decimalToBigInt(ocnToken.balance).toString(),
// decimalToBigInt(ocnToken.denormWeight).toString(),
// decimalToBigInt(dtToken.balance).toString(),
// decimalToBigInt(dtToken.denormWeight).toString(),
// ONE_INT.toString(),
// decimalToBigInt(pool.swapFee).toString(),
// result.reverted ? 'failed' : result.value.toString()
// ]
// )
pool.consumePrice = poolTx.consumePrice
pool.spotPrice = poolTx.spotPrice
pool.transactionCount = pool.transactionCount.plus(BigInt.fromI32(1))
pool.save()
debuglog('updated pool reserves (source, dtBalance, ocnBalance, dtReserve, ocnReserve): ',
event,
['createPoolTransaction', dtToken.balance.toString(), ocnToken.balance.toString(),
@ -233,28 +234,38 @@ export function createPoolTransaction(event: ethereum.Event, event_type: string,
poolTx.gasPrice = event.transaction.gasPrice.toBigDecimal()
if (poolId == DEBUG_POOL_ADDRESS) {
_debuglog('####################### poolTransaction: ', event,
[
BigInt.fromI32(poolTx.block).toString(),
BigInt.fromI32(poolTx.timestamp).toString(),
pool.oceanReserve.toString()
])
}
debuglog('####################### poolTransaction: ', event,
[
BigInt.fromI32(poolTx.block).toString(),
BigInt.fromI32(poolTx.timestamp).toString(),
pool.oceanReserve.toString()
])
poolTx.save()
}
export function calcSpotPrice(
wIn: BigDecimal, wOut: BigDecimal,
balanceIn: BigDecimal, balanceOut: BigDecimal,
balanceIn: BigDecimal, wIn: BigDecimal,
balanceOut: BigDecimal, wOut: BigDecimal,
swapFee: BigDecimal
): BigDecimal {
if (balanceIn <= ZERO_BD || balanceOut <= ZERO_BD) return MINUS_1_BD
debuglog('################ calcSpotPrice', null,
[balanceIn.toString(), wIn.toString(),
balanceOut.toString(), wOut.toString(),
swapFee.toString()])
let numer = balanceIn.div(wIn)
let denom = balanceOut.div(wOut)
if (denom <= ZERO_BD) return MINUS_1_BD
let ratio = numer.div(denom)
let scale = ONE.div(ONE.minus(swapFee))
return ratio.times(scale)
let scale = ONE_BD.div(ONE_BD.minus(swapFee))
let price = ratio.times(scale)
price.truncate(18)
debuglog('################ calcSpotPrice values:', null,
[numer.toString(), denom.toString(), ratio.toString(), scale.toString(), price.toString()])
return price
}
export function decrPoolCount(finalized: boolean): void {

View File

@ -16,12 +16,12 @@ import {
createPoolShareEntity,
createPoolTokenEntity,
ZERO_BD,
MINUS_1,
MINUS_1_BD,
decrPoolCount,
updatePoolTransactionToken,
createPoolTransaction,
OCEAN,
debuglog, updatePoolTokenBalance, _debuglog, DEBUG_POOL_ADDRESS
debuglog, updatePoolTokenBalance
} from './helpers'
/************************************
@ -67,9 +67,7 @@ export function handleFinalize(event: LOG_CALL): void {
export function handleSetup(event: LOG_CALL): void {
let poolId = event.address.toHex()
if (poolId == DEBUG_POOL_ADDRESS) {
_debuglog('handleSetup: ', event, [])
}
debuglog('handleSetup: ', event, [])
let data = event.params.data.toHexString()
// First 2 chars are 0x
// Next there is 8 chars
@ -98,7 +96,6 @@ export function handleSetup(event: LOG_CALL): void {
handleFinalize(event)
createPoolTransaction(event, 'setup', event.transaction.from.toHex())
let pool = Pool.load(poolId)
// update base token
let amount = hexToDecimal(baseTokenAmount, 18)
@ -141,10 +138,10 @@ export function _handleRebind(event: LOG_CALL, poolId: string, tokenAddress: str
}
}
poolToken.denormWeight = denormWeight
let balance = hexToDecimal(balanceStr, decimals)
updatePoolTokenBalance(poolToken as PoolToken, balance, '_handleRebind')
poolToken.denormWeight = denormWeight
poolToken.save()
if (balance.equals(ZERO_BD)) {
decrPoolCount(pool.finalized)
@ -181,9 +178,7 @@ export function handleJoinPool(event: LOG_JOIN): void {
let ptx = event.transaction.hash.toHexString()
let poolTx = PoolTransaction.load(ptx)
if (poolTx != null) {
if (poolId == DEBUG_POOL_ADDRESS && event.params.tokenIn.toHex() == OCEAN) {
_debuglog('!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!! JOIN JOIN JOIN !!!!!!!!!!!! PoolTransaction EXISTS: ', event, [])
}
debuglog('!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!! JOIN JOIN JOIN !!!!!!!!!!!! PoolTransaction EXISTS: ', event, [])
return
}
@ -191,9 +186,7 @@ export function handleJoinPool(event: LOG_JOIN): void {
let poolTokenId = poolId.concat('-').concat(address)
let poolToken = PoolToken.load(poolTokenId)
if (poolToken == null) {
if (poolToken.poolId == DEBUG_POOL_ADDRESS && poolToken.tokenAddress == OCEAN) {
_debuglog('!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!! JOIN JOIN JOIN !!!!!!!!!!!! NO PoolToken: ', event, [address, poolTokenId])
}
debuglog('!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!! JOIN JOIN JOIN !!!!!!!!!!!! NO PoolToken: ', event, [address, poolTokenId])
return
}
@ -202,10 +195,8 @@ export function handleJoinPool(event: LOG_JOIN): void {
let decimals = datatoken == null ? BigInt.fromI32(18).toI32() : datatoken.decimals
let tokenAmountIn = tokenToDecimal(event.params.tokenAmountIn.toBigDecimal(), decimals)
updatePoolTokenBalance(poolToken as PoolToken, poolToken.balance.plus(tokenAmountIn), 'handleJoinPool')
if (poolToken.poolId == DEBUG_POOL_ADDRESS && poolToken.tokenAddress == OCEAN) {
_debuglog('!!!!!!!!!!!!!!!!!! JOIN JOIN JOIN : (token, amountIn, amountIn) ', event,
debuglog('!!!!!!!!!!!!!!!!!! JOIN JOIN JOIN : (token, amountIn, amountIn) ', event,
[address, tokenAmountIn.toString(), event.params.tokenAmountIn.toString()])
}
poolToken.save()
createPoolTransaction(event, 'join', event.params.caller.toHexString())
@ -223,10 +214,8 @@ export function handleExitPool(event: LOG_EXIT): void {
let poolTokenId = poolId.concat('-').concat(address.toString())
let poolToken = PoolToken.load(poolTokenId)
if (!poolToken) {
if (poolToken.poolId == DEBUG_POOL_ADDRESS && poolToken.tokenAddress == OCEAN) {
_debuglog('!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!! EXIT EXIT EXIT !!!!!!!!!!!! NO PoolToken: ', event, [address, poolTokenId])
}
return
debuglog('!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!! EXIT EXIT EXIT !!!!!!!!!!!! NO PoolToken: ', event, [address, poolTokenId])
return
}
let datatoken: Datatoken | null
@ -236,10 +225,8 @@ export function handleExitPool(event: LOG_EXIT): void {
let newAmount = poolToken.balance.minus(tokenAmountOut)
updatePoolTokenBalance(poolToken as PoolToken, newAmount, 'handleExitPool')
poolToken.save()
if (poolToken.poolId == DEBUG_POOL_ADDRESS && poolToken.tokenAddress == OCEAN) {
_debuglog('!!!!!!!!!!!!!!!!!! EXIT EXIT EXIT : (token, amountOut, amountOut)', event,
[address, tokenAmountOut.toString(), event.params.tokenAmountOut.toString()])
}
debuglog('!!!!!!!!!!!!!!!!!! EXIT EXIT EXIT : (token, amountOut, amountOut)', event,
[address, tokenAmountOut.toString(), event.params.tokenAmountOut.toString()])
let pool = Pool.load(poolId)
pool.exitCount = pool.exitCount.plus(BigInt.fromI32(1))
if (newAmount.equals(ZERO_BD)) {
@ -251,7 +238,7 @@ export function handleExitPool(event: LOG_EXIT): void {
createPoolTransaction(event, 'exit', event.params.caller.toHexString())
updatePoolTransactionToken(
event.transaction.hash.toHexString(), poolTokenId,
tokenAmountOut.times(MINUS_1), poolToken.balance,
tokenAmountOut.times(MINUS_1_BD), poolToken.balance,
tokenAmountOut.times(pool.swapFee)
)
}
@ -268,10 +255,8 @@ export function handleSwap(event: LOG_SWAP): void {
let poolTokenInId = poolId.concat('-').concat(tokenIn.toString())
let poolTokenIn = PoolToken.load(poolTokenInId)
if (!poolTokenIn) {
if (poolId == DEBUG_POOL_ADDRESS) {
_debuglog('!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!! SWAP SWAP SWAP !!!!!!!!!!!! NO PoolToken: ', event,
[tokenIn, poolTokenInId])
}
debuglog('!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!! SWAP SWAP SWAP !!!!!!!!!!!! NO PoolToken: ', event,
[tokenIn, poolTokenInId])
return
}
let dtIn = Datatoken.load(tokenIn)
@ -288,14 +273,12 @@ export function handleSwap(event: LOG_SWAP): void {
let newAmountOut = poolTokenOut.balance.minus(tokenAmountOut)
updatePoolTokenBalance(poolTokenOut as PoolToken, newAmountOut, 'handleSwap.tokenOut')
poolTokenOut.save()
if (poolId == DEBUG_POOL_ADDRESS) {
_debuglog('!!!!!!!!!!!!!!!!!! SWAP SWAP SWAP : (tokenIn, tokenOut, amountIn, amountIn, amountOut, amountOut)', event,
[tokenIn, tokenOut, tokenAmountIn.toString(), event.params.tokenAmountIn.toString(),
tokenAmountOut.toString(), event.params.tokenAmountOut.toString()])
}
debuglog('!!!!!!!!!!!!!!!!!! SWAP SWAP SWAP : (tokenIn, tokenOut, amountIn, amountIn, amountOut, amountOut)', event,
[tokenIn, tokenOut, tokenAmountIn.toString(), event.params.tokenAmountIn.toString(),
tokenAmountOut.toString(), event.params.tokenAmountOut.toString()])
let pool = Pool.load(poolId)
pool.swapCount += BigInt.fromI32(1)
pool.swapCount = pool.swapCount.plus(BigInt.fromI32(1))
if (newAmountIn.equals(ZERO_BD) || newAmountOut.equals(ZERO_BD)) {
decrPoolCount(pool.finalized)
pool.active = false
@ -307,7 +290,7 @@ export function handleSwap(event: LOG_SWAP): void {
ptx, poolTokenIn.id, tokenAmountIn, poolTokenIn.balance,
tokenAmountIn.times(pool.swapFee))
updatePoolTransactionToken(
ptx, poolTokenOut.id, tokenAmountOut.times(MINUS_1), poolTokenOut.balance,
ptx, poolTokenOut.id, tokenAmountOut.times(MINUS_1_BD), poolTokenOut.balance,
BigDecimal.fromString('0.0'))
}