Remove tracking of pools (#492)

* Removing pool mapping

* Removing pool utils

* Removing pool transaction types

* Removing TokenTransaction from schema

* Removing pool functions from src/mappings/utils/globalUtils.ts

* Removing pool functions from src/mappings/factoryRouter.ts

* Removing pools from the schema

* removing pool events from subgraph.template.yaml

* Fixing TokenAdded in subgraph template

Co-authored-by: mihaisc <mihai@oceanprotocol.com>
This commit is contained in:
Jamie Hewitt 2022-08-01 14:58:09 +03:00 committed by GitHub
parent 61cfdbaf23
commit 1289a085bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 28 additions and 810 deletions

View File

@ -47,9 +47,6 @@ type Token @entity {
"dispensers using this token" "dispensers using this token"
dispensers: [Dispenser!] @derivedFrom(field:"token") dispensers: [Dispenser!] @derivedFrom(field:"token")
"pools, only available for datatokens"
pools: [Pool!] @derivedFrom(field:"datatoken")
"block time datatoken was created" "block time datatoken was created"
createdTimestamp: Int! createdTimestamp: Int!
@ -76,7 +73,7 @@ type Nft @entity{
id: ID! id: ID!
symbol: String! symbol: String!
name: String! name: String!
tokenUri: String! tokenUri: String
"address of the owner of the nft" "address of the owner of the nft"
owner: String! owner: String!
@ -115,134 +112,6 @@ type Nft @entity{
orderCount: BigInt! orderCount: BigInt!
} }
type Pool @entity {
"pool address"
id: ID!
"owner address, pool controller"
controller: String
"only finalized pools are relevant to us"
isFinalized: Boolean!
"pool token symbol"
symbol: String
"pool token name"
name: String
"maximum supply if any, converted from wei"
cap: BigDecimal
baseToken: Token!
baseTokenLiquidity: BigDecimal!
baseTokenWeight: BigDecimal!
datatoken: Token!
datatokenLiquidity: BigDecimal!
datatokenWeight: BigDecimal!
"publisher market fee value"
publishMarketSwapFee: BigDecimal!
"publisher market fee total amount"
publishMarketSwapFeeAmount: BigDecimal
"Liquidty provider fee value"
liquidityProviderSwapFee: BigDecimal
"liquidity provider fee total amount"
liquidityProviderSwapFeeAmount: BigDecimal!
"total pool token shares"
totalShares: BigDecimal!
"total tokens that were swaped"
totalSwapVolume: [TokenValuePair!]!
spotPrice: BigDecimal!
"count for when liquidity has been added"
joinCount: BigInt!
"count for when liquidity has been removed"
exitCount: BigInt!
"count for when tokens were swapped"
swapCount: BigInt!
"number of transactions in this pool involving liquidity changes"
transactionCount: BigInt!
"block time when pool was created"
createdTimestamp: Int!
"pool creation transaction id"
tx: String!
"block number when it was created"
block: Int
shares: [PoolShare!] @derivedFrom(field: "pool")
transactions: [PoolTransaction!] @derivedFrom(field: "pool")
"address of the market where the datatoken was created. This address collects market fees."
publishMarketFeeAddress: String
}
# we will need to track pool share tx between users - bpool transfer tx event
type PoolShare @entity {
"poolAddress + userAddress"
id: ID!
user: User!
pool: Pool!
shares: BigDecimal!
}
enum PoolTransactionType {
JOIN,
EXIT,
SWAP,
SETUP
}
type PoolTransaction @entity {
"tx address + eventIndex"
id: ID!
"pool related to this tx"
pool: Pool!
"user that initiates the tx"
user: User!
type: PoolTransactionType!
"number of shares transfered"
sharesTransferAmount: BigDecimal!
"block time when pool was created"
timestamp: Int!
"pool creation transaction id"
tx: String!
eventIndex: BigInt
"block number when it was created"
block: Int
gasLimit: BigDecimal!
"price expressed in eth"
gasPrice: BigDecimal!
"base tokens transfered"
baseToken: Token
"number of base tokens transfered, for type SWAP if value is negative it means it was removed"
baseTokenValue: BigDecimal
"datatokens transfered"
datatoken: Token
"number of datatokens transfered, for type SWAP if value is negative it means it was removed"
datatokenValue: BigDecimal
}
type OrderReuse @entity { type OrderReuse @entity {
id: ID! id: ID!
order: Order! order: Order!
@ -253,6 +122,7 @@ type OrderReuse @entity {
providerFee: String providerFee: String
providerFeeValidUntil: BigInt providerFeeValidUntil: BigInt
} }
type Order @entity { type Order @entity {
"transaction hash - token address - from address" "transaction hash - token address - from address"
id: ID! id: ID!
@ -286,25 +156,9 @@ type Order @entity {
estimatedUSDValue: BigDecimal! estimatedUSDValue: BigDecimal!
} }
# to be removed, mabye for pool shares only
type TokenTransaction @entity {
id: ID! # Log ID
event: String
token: Token
user: User
block: Int!
gasUsed: BigDecimal!
gasPrice: BigDecimal!
createdTimestamp: Int!
tx: String!
}
type User @entity { type User @entity {
id: ID! id: ID!
sharesOwned: [PoolShare!] @derivedFrom(field: "user")
tokenBalancesOwned: [TokenValuePair!] tokenBalancesOwned: [TokenValuePair!]
poolTransactions: [PoolTransaction!] @derivedFrom(field: "user")
orders: [Order!] @derivedFrom(field: "payer") orders: [Order!] @derivedFrom(field: "payer")
freSwaps: [FixedRateExchangeSwap!] @derivedFrom(field: "by") freSwaps: [FixedRateExchangeSwap!] @derivedFrom(field: "by")
@ -422,28 +276,6 @@ type DispenserTransaction @entity {
tx: String! tx: String!
} }
type PoolSnapshot @entity {
id: ID!
pool: Pool!
"total pool shares at the end of the 24h interval"
totalShares: BigDecimal!
"swap value 24h"
swapVolume: BigDecimal!
"swap fee value 24h"
swapFees: BigDecimal!
"date without time"
date: Int!
"last spot price in the 24h interval"
spotPrice: BigDecimal!
baseToken: Token!
baseTokenLiquidity: BigDecimal!
datatoken: Token!
datatokenLiquidity: BigDecimal!
}
"utility type" "utility type"
type GlobalTotalLiquidityPair @entity { type GlobalTotalLiquidityPair @entity {
"address of the token" "address of the token"
@ -453,15 +285,6 @@ type GlobalTotalLiquidityPair @entity {
value : BigDecimal! value : BigDecimal!
} }
"utility type"
type GlobalTotalPoolSwapPair @entity {
"address of the token"
id : ID!
globalStatistic: GlobalStatistic!
token : Token!
value : BigDecimal!
count: BigInt!
}
"utility type" "utility type"
type GlobalTotalFixedSwapPair @entity { type GlobalTotalFixedSwapPair @entity {
"address of the token" "address of the token"
@ -472,25 +295,18 @@ type GlobalTotalFixedSwapPair @entity {
count: BigInt! count: BigInt!
} }
type GlobalStatistic @entity { type GlobalStatistic @entity {
id: ID! id: ID!
"total liquidity for each base token in pools"
totalLiquidity: [GlobalTotalLiquidityPair!]! @derivedFrom(field: "globalStatistic")
"total swap volume for each base token in pools"
totalPoolSwapVolume: [GlobalTotalPoolSwapPair!]! @derivedFrom(field: "globalStatistic")
"total swap volume for each base token in fixed rate exchanges" "total swap volume for each base token in fixed rate exchanges"
totalFixedSwapVolume: [GlobalTotalFixedSwapPair!] @derivedFrom(field: "globalStatistic") totalFixedSwapVolume: [GlobalTotalFixedSwapPair!] @derivedFrom(field: "globalStatistic")
"number of total orders. pool orders + fixed rate exchange orders + dispenser orders" "number of total orders. fixed rate exchange orders + dispenser orders"
orderCount: Int! orderCount: Int!
"total nfts(erc721) created" "total nfts(erc721) created"
nftCount: Int! nftCount: Int!
"total datatokens (tokens with isDatatoken = true) created" "total datatokens (tokens with isDatatoken = true) created"
datatokenCount:Int! datatokenCount:Int!
"number of pools"
poolCount: Int!
"number of fixed rate exchanges" "number of fixed rate exchanges"
fixedCount: Int! fixedCount: Int!
@ -524,7 +340,7 @@ type OPC @entity {
type NftUpdate @entity { type NftUpdate @entity {
id: ID! # update tx + nft address id: ID! # update tx + nft address
tokenUri: String! tokenUri: String
nft: Nft! nft: Nft!
"provider url that can decrypt the ddo" "provider url that can decrypt the ddo"

View File

@ -17,6 +17,7 @@ import { weiToDecimal } from './utils/generic'
import { addDispenser } from './utils/globalUtils' import { addDispenser } from './utils/globalUtils'
import { getToken } from './utils/tokenUtils' import { getToken } from './utils/tokenUtils'
import { getUser } from './utils/userUtils' import { getUser } from './utils/userUtils'
import { BigDecimal } from '@graphprotocol/graph-ts'
export function handleNewDispenser(event: DispenserCreated): void { export function handleNewDispenser(event: DispenserCreated): void {
const dispenserID = getDispenserGraphID( const dispenserID = getDispenserGraphID(
@ -38,7 +39,7 @@ export function handleNewDispenser(event: DispenserCreated): void {
token.decimals token.decimals
) )
dispenser.active = true dispenser.active = true
dispenser.balance = BigDecimal.zero()
dispenser.allowedSwapper = event.params.allowedSwapper.toHex() dispenser.allowedSwapper = event.params.allowedSwapper.toHex()
dispenser.createdTimestamp = event.block.timestamp.toI32() dispenser.createdTimestamp = event.block.timestamp.toI32()
dispenser.tx = event.transaction.hash.toHex() dispenser.tx = event.transaction.hash.toHex()

View File

@ -1,5 +1,4 @@
import { import {
NewPool,
TokenAdded, TokenAdded,
TokenRemoved, TokenRemoved,
OPCFeeChanged, OPCFeeChanged,
@ -12,19 +11,11 @@ import {
DispenserContractRemoved DispenserContractRemoved
} from '../@types/FactoryRouter/FactoryRouter' } from '../@types/FactoryRouter/FactoryRouter'
import { BigInt } from '@graphprotocol/graph-ts' import { BigInt } from '@graphprotocol/graph-ts'
import { Pool } from '../@types/schema' import { FixedRateExchange, Dispenser } from '../@types/templates'
import { BPool, FixedRateExchange, Dispenser } from '../@types/templates' import { getOPC, getTemplates } from './utils/globalUtils'
import { addPool, getOPC, getTemplates } from './utils/globalUtils'
import { weiToDecimal } from './utils/generic' import { weiToDecimal } from './utils/generic'
import { getToken } from './utils/tokenUtils' import { getToken } from './utils/tokenUtils'
export function handleNewPool(event: NewPool): void {
BPool.create(event.params.poolAddress)
const pool = new Pool(event.params.poolAddress.toHexString())
pool.save()
addPool()
}
export function handleOPCFeeChanged(event: OPCFeeChanged): void { export function handleOPCFeeChanged(event: OPCFeeChanged): void {
const opc = getOPC() const opc = getOPC()
const decimals = BigInt.fromI32(18).toI32() const decimals = BigInt.fromI32(18).toI32()

View File

@ -1,4 +1,4 @@
import { BigInt, Address } from '@graphprotocol/graph-ts' import { BigInt, Address, BigDecimal, log } from '@graphprotocol/graph-ts'
import { import {
ExchangeActivated, ExchangeActivated,
ExchangeAllowedSwapperChanged, ExchangeAllowedSwapperChanged,
@ -38,7 +38,11 @@ export function handleExchangeCreated(event: ExchangeCreated): void {
fixedRateExchange.exchangeId = event.params.exchangeId.toHexString() fixedRateExchange.exchangeId = event.params.exchangeId.toHexString()
fixedRateExchange.datatoken = getToken(event.params.datatoken, true).id fixedRateExchange.datatoken = getToken(event.params.datatoken, true).id
fixedRateExchange.baseToken = getToken(event.params.baseToken, false).id fixedRateExchange.baseToken = getToken(event.params.baseToken, false).id
fixedRateExchange.datatokenSupply = BigDecimal.zero()
fixedRateExchange.baseTokenSupply = BigDecimal.zero()
fixedRateExchange.datatokenBalance = BigDecimal.zero()
fixedRateExchange.baseTokenBalance = BigDecimal.zero()
fixedRateExchange.totalSwapValue = BigDecimal.zero()
fixedRateExchange.active = false fixedRateExchange.active = false
fixedRateExchange.price = weiToDecimal( fixedRateExchange.price = weiToDecimal(
event.params.fixedRate.toBigDecimal(), event.params.fixedRate.toBigDecimal(),
@ -67,7 +71,7 @@ export function handleRateChange(event: ExchangeRateChanged): void {
newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32() newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32()
newExchangeUpdate.tx = event.transaction.hash.toHex() newExchangeUpdate.tx = event.transaction.hash.toHex()
newExchangeUpdate.block = event.block.number.toI32() newExchangeUpdate.block = event.block.number.toI32()
newExchangeUpdate.exchangeId = fixedRateId
fixedRateExchange.price = weiToDecimal( fixedRateExchange.price = weiToDecimal(
event.params.newRate.toBigDecimal(), event.params.newRate.toBigDecimal(),
BigInt.fromI32(18).toI32() BigInt.fromI32(18).toI32()
@ -88,8 +92,6 @@ export function handleMintStateChanged(event: ExchangeMintStateChanged): void {
fixedRateExchange.save() fixedRateExchange.save()
} }
// TODO: implement fre updates/history for changes
export function handleActivated(event: ExchangeActivated): void { export function handleActivated(event: ExchangeActivated): void {
const fixedRateId = getFixedRateGraphID( const fixedRateId = getFixedRateGraphID(
event.params.exchangeId.toHexString(), event.params.exchangeId.toHexString(),
@ -99,6 +101,7 @@ export function handleActivated(event: ExchangeActivated): void {
const newExchangeUpdate = new FixedRateExchangeUpdate( const newExchangeUpdate = new FixedRateExchangeUpdate(
getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId) getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId)
) )
newExchangeUpdate.exchangeId = fixedRateId
newExchangeUpdate.oldActive = fixedRateExchange.active newExchangeUpdate.oldActive = fixedRateExchange.active
newExchangeUpdate.newActive = true newExchangeUpdate.newActive = true
newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32() newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32()
@ -123,6 +126,7 @@ export function handleDeactivated(event: ExchangeDeactivated): void {
newExchangeUpdate.oldActive = fixedRateExchange.active newExchangeUpdate.oldActive = fixedRateExchange.active
newExchangeUpdate.newActive = false newExchangeUpdate.newActive = false
newExchangeUpdate.exchangeId = fixedRateId
newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32() newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32()
newExchangeUpdate.tx = event.transaction.hash.toHex() newExchangeUpdate.tx = event.transaction.hash.toHex()
newExchangeUpdate.block = event.block.number.toI32() newExchangeUpdate.block = event.block.number.toI32()
@ -178,6 +182,7 @@ export function handleSwap(event: Swapped): void {
Address.fromString(fixedRateExchange.baseToken), Address.fromString(fixedRateExchange.baseToken),
false false
) )
swap.baseTokenAmount = weiToDecimal( swap.baseTokenAmount = weiToDecimal(
event.params.baseTokenSwappedAmount.toBigDecimal(), event.params.baseTokenSwappedAmount.toBigDecimal(),
BigInt.fromI32(baseToken.decimals).toI32() BigInt.fromI32(baseToken.decimals).toI32()
@ -188,18 +193,17 @@ export function handleSwap(event: Swapped): void {
) )
swap.save() swap.save()
updateFixedRateExchangeSupply(event.params.exchangeId, event.address) updateFixedRateExchangeSupply(event.params.exchangeId, event.address)
if (event.params.tokenOutAddress.toHexString() == fixedRateExchange.datatoken) log.error('start addFixedSwap', [])
if (event.params.tokenOutAddress.toHexString() == fixedRateExchange.baseToken)
addFixedSwap( addFixedSwap(
event.params.tokenOutAddress.toHexString(), event.params.tokenOutAddress.toHexString(),
swap.dataTokenAmount swap.dataTokenAmount
) )
else else addFixedSwap(fixedRateExchange.baseToken, swap.baseTokenAmount)
addFixedSwap( log.error('addFixedSwap saved', [])
event.params.tokenOutAddress.toHexString(),
swap.baseTokenAmount
)
// update datatoken lastPriceToken and lastPriceValue // update datatoken lastPriceToken and lastPriceValue
const datatoken = getToken( const datatoken = getToken(
Address.fromString(fixedRateExchange.datatoken), Address.fromString(fixedRateExchange.datatoken),

View File

@ -1,363 +0,0 @@
import { BigInt, Address } from '@graphprotocol/graph-ts'
import {
LOG_EXIT,
LOG_JOIN,
LOG_SETUP,
LOG_SWAP,
PublishMarketFeeChanged,
SwapFeeChanged
} from '../@types/templates/BPool/BPool'
import { Transfer } from '../@types/templates/BPool/BToken'
import {
decimal,
integer,
PoolTransactionType,
ZERO_ADDRESS
} from './utils/constants'
import { weiToDecimal } from './utils/generic'
import { addLiquidity, addPoolSwap, removeLiquidity } from './utils/globalUtils'
import {
calcSpotPrice,
getPool,
getPoolTransaction,
getPoolShare,
getPoolSnapshot,
getPoolLpSwapFee,
getPoolPublisherMarketFee
} from './utils/poolUtils'
import { getToken } from './utils/tokenUtils'
import { getUser } from './utils/userUtils'
// kinda redundant code in join/swap/exit
export function handleJoin(event: LOG_JOIN): void {
const pool = getPool(event.address.toHex())
const user = getUser(event.params.caller.toHex())
const poolTx = getPoolTransaction(
event,
user.id,
PoolTransactionType.JOIN,
event.logIndex
)
pool.transactionCount = pool.transactionCount.plus(integer.ONE)
pool.joinCount = pool.joinCount.plus(integer.ONE)
// get token, update pool transaction, poolSnapshot
const token = getToken(event.params.tokenIn, false)
const ammount = weiToDecimal(
event.params.tokenAmountIn.toBigDecimal(),
token.decimals
)
if (token.isDatatoken) {
poolTx.datatoken = token.id
poolTx.datatokenValue = ammount
pool.datatokenLiquidity = pool.datatokenLiquidity.plus(ammount)
} else {
poolTx.baseToken = token.id
poolTx.baseTokenValue = ammount
pool.baseTokenLiquidity = pool.baseTokenLiquidity.plus(ammount)
addLiquidity(token.id, ammount)
}
poolTx.save()
pool.save()
if (pool.isFinalized) {
const poolSnapshot = getPoolSnapshot(pool.id, event.block.timestamp.toI32())
poolSnapshot.baseTokenLiquidity = pool.baseTokenLiquidity
poolSnapshot.datatokenLiquidity = pool.datatokenLiquidity
poolSnapshot.totalShares = pool.totalShares
poolSnapshot.save()
}
}
export function handleExit(event: LOG_EXIT): void {
const pool = getPool(event.address.toHex())
const user = getUser(event.params.caller.toHex())
const poolTx = getPoolTransaction(
event,
user.id,
PoolTransactionType.EXIT,
event.logIndex
)
pool.transactionCount = pool.transactionCount.plus(integer.ONE)
pool.joinCount = pool.joinCount.plus(integer.ONE)
// get token and update pool transaction, value is negative because this is an exit event.
const token = getToken(event.params.tokenOut, false)
const poolSnapshot = getPoolSnapshot(pool.id, event.block.timestamp.toI32())
const ammount = weiToDecimal(
event.params.tokenAmountOut.toBigDecimal(),
token.decimals
)
if (token.isDatatoken) {
poolTx.datatoken = token.id
poolTx.datatokenValue = ammount
pool.datatokenLiquidity = pool.datatokenLiquidity.minus(ammount)
} else {
poolTx.baseToken = token.id
poolTx.baseTokenValue = ammount
pool.baseTokenLiquidity = pool.baseTokenLiquidity.minus(ammount)
removeLiquidity(token.id, ammount)
}
poolSnapshot.baseTokenLiquidity = pool.baseTokenLiquidity
poolSnapshot.datatokenLiquidity = pool.datatokenLiquidity
poolSnapshot.totalShares = pool.totalShares
poolSnapshot.save()
poolTx.save()
pool.save()
}
export function handleSwap(event: LOG_SWAP): void {
const pool = getPool(event.address.toHex())
const user = getUser(event.params.caller.toHex())
const poolTx = getPoolTransaction(
event,
user.id,
PoolTransactionType.SWAP,
event.logIndex
)
pool.transactionCount = pool.transactionCount.plus(integer.ONE)
pool.joinCount = pool.joinCount.plus(integer.ONE)
const poolSnapshot = getPoolSnapshot(pool.id, event.block.timestamp.toI32())
const tokenOut = getToken(event.params.tokenOut, false)
const tokenIn = getToken(event.params.tokenIn, false)
let spotPrice = decimal.ZERO
const ammountOut = weiToDecimal(
event.params.tokenAmountOut.toBigDecimal(),
tokenOut.decimals
)
const tokenOutNewBalance = weiToDecimal(
event.params.outBalance.toBigDecimal(),
tokenOut.decimals
)
const tokenInNewBalance = weiToDecimal(
event.params.inBalance.toBigDecimal(),
tokenIn.decimals
)
if (tokenOut.isDatatoken) {
poolTx.datatoken = tokenOut.id
poolTx.datatokenValue = ammountOut.neg()
pool.datatokenLiquidity = tokenOutNewBalance
} else {
poolTx.baseToken = tokenOut.id
poolTx.baseTokenValue = ammountOut.neg()
spotPrice = decimal.ONE.div(
weiToDecimal(event.params.newSpotPrice.toBigDecimal(), tokenOut.decimals)
)
pool.baseTokenLiquidity = tokenOutNewBalance
poolSnapshot.swapVolume = poolSnapshot.swapVolume.plus(ammountOut)
addPoolSwap(tokenOut.id, ammountOut)
removeLiquidity(tokenOut.id, ammountOut)
}
// update pool token in
const ammountIn = weiToDecimal(
event.params.tokenAmountIn.toBigDecimal(),
tokenIn.decimals
)
if (tokenIn.isDatatoken) {
poolTx.datatoken = tokenIn.id
poolTx.datatokenValue = ammountIn
pool.datatokenLiquidity = tokenInNewBalance
} else {
poolTx.baseToken = tokenIn.id
poolTx.baseTokenValue = ammountIn
spotPrice = weiToDecimal(
event.params.newSpotPrice.toBigDecimal(),
tokenOut.decimals
)
pool.baseTokenLiquidity = tokenInNewBalance
poolSnapshot.swapVolume = poolSnapshot.swapVolume.plus(ammountIn)
addLiquidity(tokenIn.id, ammountIn)
addPoolSwap(tokenIn.id, ammountIn)
}
// update spot price
pool.spotPrice = spotPrice
poolSnapshot.spotPrice = spotPrice
poolSnapshot.baseTokenLiquidity = pool.baseTokenLiquidity
poolSnapshot.datatokenLiquidity = pool.datatokenLiquidity
poolSnapshot.totalShares = pool.totalShares
poolSnapshot.save()
poolTx.save()
pool.save()
// update datatoken lastPriceToken and lastPriceValue
const datatoken = getToken(Address.fromString(pool.datatoken), true)
datatoken.lastPriceToken = pool.baseToken
datatoken.lastPriceValue = spotPrice
datatoken.save()
}
// setup is just to set token weight(it will mostly be 50:50) and spotPrice
export function handleSetup(event: LOG_SETUP): void {
const pool = getPool(event.address.toHex())
pool.controller = event.params.caller.toHexString()
const token = getToken(event.params.baseToken, false)
pool.baseToken = token.id
pool.baseTokenWeight = weiToDecimal(
event.params.baseTokenWeight.toBigDecimal(),
18
)
// decimals hardcoded because datatokens have 18 decimals
const datatoken = getToken(event.params.datatoken, true)
pool.datatoken = datatoken.id
pool.datatokenWeight = weiToDecimal(
event.params.datatokenWeight.toBigDecimal(),
18
)
// calculate spotPrice
const spotPrice = calcSpotPrice(
pool.id,
pool.baseToken,
pool.datatoken,
token.decimals
)
pool.spotPrice = spotPrice
pool.isFinalized = true
// TODO: proper tx , add baseToken, datatoken
const fromUser = getUser(event.transaction.from.toHexString())
const poolTx = getPoolTransaction(
event,
fromUser.id,
PoolTransactionType.SETUP,
event.logIndex
)
poolTx.type = PoolTransactionType.SETUP
poolTx.baseToken = token.id
poolTx.baseTokenValue = weiToDecimal(
event.params.baseTokenAmountIn.toBigDecimal(),
token.decimals
)
pool.save()
poolTx.save()
const lpFee = getPoolLpSwapFee(event.address)
pool.liquidityProviderSwapFee = lpFee
const publisherMarketFee = getPoolPublisherMarketFee(event.address)
pool.publishMarketSwapFee = publisherMarketFee
pool.save()
const poolSnapshot = getPoolSnapshot(pool.id, event.block.timestamp.toI32())
poolSnapshot.spotPrice = spotPrice
poolSnapshot.baseTokenLiquidity = pool.baseTokenLiquidity
poolSnapshot.datatokenLiquidity = pool.datatokenLiquidity
poolSnapshot.totalShares = pool.totalShares
poolSnapshot.save()
datatoken.save()
}
export function handlerBptTransfer(event: Transfer): void {
const fromAddress = event.params.src.toHexString()
const toAddress = event.params.dst.toHexString()
const poolAddress = event.address.toHex()
const caller = getUser(event.transaction.from.toHex())
const poolTx = getPoolTransaction(
event,
caller.id,
PoolTransactionType.SWAP,
event.logIndex
)
// btoken has 18 decimals
const ammount = weiToDecimal(event.params.amt.toBigDecimal(), 18)
if (fromAddress != ZERO_ADDRESS && toAddress != ZERO_ADDRESS) {
poolTx.sharesTransferAmount = poolTx.sharesTransferAmount.plus(ammount)
}
if (fromAddress == ZERO_ADDRESS) {
// add total
const pool = getPool(poolAddress)
pool.totalShares = pool.totalShares.plus(ammount)
// check tx?
if (pool.isFinalized) {
const poolSnapshot = getPoolSnapshot(
poolAddress,
event.block.timestamp.toI32()
)
poolSnapshot.totalShares = pool.totalShares
poolSnapshot.save()
}
pool.save()
} else {
if (poolAddress != fromAddress) {
const fromUser = getPoolShare(poolAddress, fromAddress)
fromUser.shares = fromUser.shares.minus(ammount)
fromUser.save()
}
}
if (toAddress == ZERO_ADDRESS) {
// remove
const pool = getPool(poolAddress)
pool.totalShares = pool.totalShares.minus(ammount)
if (pool.isFinalized) {
const poolSnapshot = getPoolSnapshot(
poolAddress,
event.block.timestamp.toI32()
)
poolSnapshot.totalShares = pool.totalShares
poolSnapshot.save()
}
pool.save()
} else {
if (poolAddress != toAddress) {
const toUser = getPoolShare(poolAddress, toAddress)
toUser.shares = toUser.shares.plus(ammount)
toUser.save()
}
}
poolTx.save()
}
export function handlePublishMarketFeeChanged(
event: PublishMarketFeeChanged
): void {
const pool = getPool(event.address.toHex())
if (pool) {
pool.publishMarketFeeAddress = event.params.newMarketCollector.toHexString()
pool.publishMarketSwapFee = weiToDecimal(
event.params.swapFee.toBigDecimal(),
BigInt.fromI32(18).toI32()
)
pool.save()
}
}
export function handleSwapFeeChanged(event: SwapFeeChanged): void {
const pool = getPool(event.address.toHex())
if (pool) {
pool.liquidityProviderSwapFee = weiToDecimal(
event.params.amount.toBigDecimal(),
BigInt.fromI32(18).toI32()
)
pool.save()
}
}

View File

@ -21,12 +21,6 @@ export namespace decimal {
} }
// string enums don't work in wasm so this was the alternative, not optimal // string enums don't work in wasm so this was the alternative, not optimal
export namespace PoolTransactionType {
export const JOIN = 'JOIN'
export const EXIT = 'EXIT'
export const SWAP = 'SWAP'
export const SETUP = 'SETUP'
}
export namespace NftUpdateType { export namespace NftUpdateType {
export const METADATA_CREATED = 'METADATA_CREATED' export const METADATA_CREATED = 'METADATA_CREATED'

View File

@ -3,7 +3,6 @@ import {
GlobalStatistic, GlobalStatistic,
GlobalTotalFixedSwapPair, GlobalTotalFixedSwapPair,
GlobalTotalLiquidityPair, GlobalTotalLiquidityPair,
GlobalTotalPoolSwapPair,
OPC, OPC,
Template Template
} from '../../@types/schema' } from '../../@types/schema'
@ -18,7 +17,6 @@ export function getGlobalStats(): GlobalStatistic {
globalStats.orderCount = 0 globalStats.orderCount = 0
globalStats.fixedCount = 0 globalStats.fixedCount = 0
globalStats.datatokenCount = 0 globalStats.datatokenCount = 0
globalStats.poolCount = 0
globalStats.dispenserCount = 0 globalStats.dispenserCount = 0
globalStats.nftCount = 0 globalStats.nftCount = 0
globalStats.save() globalStats.save()
@ -74,31 +72,14 @@ export function addDispenser(): void {
globalStats.save() globalStats.save()
} }
export function addPool(): void {
const globalStats = getGlobalStats()
globalStats.poolCount = globalStats.poolCount + 1
globalStats.save()
}
export function addPoolSwap(tokenAddress: string, value: BigDecimal): void {
let poolSwapPair = GlobalTotalPoolSwapPair.load(tokenAddress)
if (!poolSwapPair) {
poolSwapPair = new GlobalTotalPoolSwapPair(tokenAddress)
poolSwapPair.globalStatistic = GLOBAL_ID
poolSwapPair.token = tokenAddress
}
poolSwapPair.value = poolSwapPair.value.plus(value)
poolSwapPair.count = poolSwapPair.count.plus(BigInt.fromI32(1))
poolSwapPair.save()
}
export function addFixedSwap(tokenAddress: string, value: BigDecimal): void { export function addFixedSwap(tokenAddress: string, value: BigDecimal): void {
let fixedSwapPair = GlobalTotalFixedSwapPair.load(tokenAddress) let fixedSwapPair = GlobalTotalFixedSwapPair.load(tokenAddress)
if (!fixedSwapPair) { if (!fixedSwapPair) {
fixedSwapPair = new GlobalTotalFixedSwapPair(tokenAddress) fixedSwapPair = new GlobalTotalFixedSwapPair(tokenAddress)
fixedSwapPair.globalStatistic = GLOBAL_ID fixedSwapPair.globalStatistic = GLOBAL_ID
fixedSwapPair.token = tokenAddress fixedSwapPair.token = tokenAddress
fixedSwapPair.value = BigDecimal.zero()
fixedSwapPair.count = BigInt.zero()
} }
fixedSwapPair.value = fixedSwapPair.value.plus(value) fixedSwapPair.value = fixedSwapPair.value.plus(value)
fixedSwapPair.count = fixedSwapPair.count.plus(BigInt.fromI32(1)) fixedSwapPair.count = fixedSwapPair.count.plus(BigInt.fromI32(1))

View File

@ -1,167 +0,0 @@
import { Address, BigDecimal, BigInt, ethereum } from '@graphprotocol/graph-ts'
import {
Pool,
PoolShare,
PoolSnapshot,
PoolTransaction
} from '../../@types/schema'
import { BPool } from '../../@types/templates/BPool/BPool'
import { DAY, decimal, integer } from './constants'
import { gweiToEth, weiToDecimal } from './generic'
import { getUser } from './userUtils'
export function getPoolShareId(
poolAddress: string,
userAddress: string
): string {
return `${poolAddress}-${userAddress}`
}
export function getPoolTransactionId(
txHash: string,
eventIndex: BigInt
): string {
return `${txHash}-` + eventIndex.toString()
}
export function getPoolTransaction(
event: ethereum.Event,
userAddress: string,
type: string,
eventIndex: BigInt
): PoolTransaction {
const txId = getPoolTransactionId(
event.transaction.hash.toHexString(),
eventIndex
)
let poolTx = PoolTransaction.load(txId)
// create pool transaction and fill basic fields
if (poolTx === null) {
poolTx = new PoolTransaction(txId)
poolTx.user = userAddress
poolTx.pool = event.address.toHex()
poolTx.type = type
poolTx.timestamp = event.block.timestamp.toI32()
poolTx.tx = event.transaction.hash.toHex()
poolTx.eventIndex = eventIndex
poolTx.block = event.block.number.toI32()
poolTx.gasPrice = gweiToEth(event.transaction.gasPrice.toBigDecimal())
poolTx.gasLimit = event.transaction.gasLimit.toBigDecimal()
}
return poolTx
}
export function getPoolShare(
poolAddress: string,
userAddress: string
): PoolShare {
let poolShare = PoolShare.load(getPoolShareId(poolAddress, userAddress))
if (poolShare === null) {
poolShare = new PoolShare(getPoolShareId(poolAddress, userAddress))
poolShare.user = getUser(userAddress).id
poolShare.pool = poolAddress
poolShare.save()
}
return poolShare
}
export function getPool(poolAddress: string): Pool {
const pool = Pool.load(poolAddress)
if (pool === null) {
// what now?
throw new Error(`Didn't find pool with address ${poolAddress} `)
}
return pool
}
export function calcSpotPrice(
poolAddress: string,
baseTokenAddress: string,
datatokenAddress: string,
baseTokenDecimals: i32
): BigDecimal {
const poolContract = BPool.bind(Address.fromString(poolAddress))
// tokenIn is always the baseToken and tokenOut is the datatoken because we want the spot price to be in baseToken eg: 1 DT = 0.5 OCEAN
const weiPrice = poolContract.try_getSpotPrice(
Address.fromString(baseTokenAddress),
Address.fromString(datatokenAddress),
integer.ZERO
).value
const price = weiToDecimal(weiPrice.toBigDecimal(), baseTokenDecimals)
return price
}
export function getDateFromTimestamp(timestamp: i32): i32 {
// date without time
return timestamp - (timestamp % DAY)
}
export function getPoolSnapshotId(poolAddress: string, timestamp: i32): string {
return `${poolAddress}-${getDateFromTimestamp(timestamp)}`
}
export function createPoolSnapshot(
poolAddress: string,
timestamp: i32
): PoolSnapshot {
const snapshotId = getPoolSnapshotId(poolAddress, timestamp)
const pool = getPool(poolAddress)
const snapshot = new PoolSnapshot(snapshotId)
snapshot.pool = poolAddress
snapshot.totalShares = pool.totalShares
snapshot.swapVolume = decimal.ZERO
snapshot.swapFees = decimal.ZERO
snapshot.baseToken = pool.baseToken
snapshot.datatoken = pool.datatoken
snapshot.datatokenLiquidity = decimal.ZERO
snapshot.date = getDateFromTimestamp(timestamp)
snapshot.spotPrice = pool.spotPrice
snapshot.save()
return snapshot
}
export function getPoolSnapshot(
poolAddress: string,
timestamp: i32
): PoolSnapshot {
let snapshot = PoolSnapshot.load(getPoolSnapshotId(poolAddress, timestamp))
if (snapshot === null) {
snapshot = createPoolSnapshot(poolAddress, timestamp)
}
return snapshot
}
export function getPoolLpSwapFee(poolAddress: Address): BigDecimal {
const contract = BPool.bind(poolAddress)
const lpFeeWei = contract.getSwapFee()
const lpFee = weiToDecimal(lpFeeWei.toBigDecimal(), 18)
return lpFee
}
export function getPoolPublisherMarketFee(poolAddress: Address): BigDecimal {
const contract = BPool.bind(poolAddress)
const marketFeeWei = contract.getMarketFee()
const marketFee = weiToDecimal(marketFeeWei.toBigDecimal(), 18)
return marketFee
}
export function getBalance(
poolAddress: Address,
tokenAddress: Address,
tokenDecimals: i32
): BigDecimal {
const contract = BPool.bind(poolAddress)
const balanceWei = contract.getBalance(tokenAddress)
const balance = weiToDecimal(balanceWei.toBigDecimal(), tokenDecimals)
return balance
}

View File

@ -49,8 +49,6 @@ dataSources:
- name: ERC20 - name: ERC20
file: ./abis/ERC20.json file: ./abis/ERC20.json
eventHandlers: eventHandlers:
- event: NewPool(indexed address,bool)
handler: handleNewPool
- event: TokenAdded(indexed address,indexed address) - event: TokenAdded(indexed address,indexed address)
handler: handleTokenAdded handler: handleTokenAdded
- event: TokenRemoved(indexed address,indexed address) - event: TokenRemoved(indexed address,indexed address)
@ -116,43 +114,6 @@ templates:
- event: ProviderFee(indexed address,indexed address,uint256,bytes,uint8,bytes32,bytes32,uint256) - event: ProviderFee(indexed address,indexed address,uint256,bytes,uint8,bytes32,bytes32,uint256)
handler: handleProviderFee handler: handleProviderFee
- name: BPool
kind: ethereum/contract
network: __NETWORK__
source:
abi: BPool
mapping:
kind: ethereum/events
apiVersion: 0.0.6
language: wasm/assemblyscript
file: ./src/mappings/pool.ts
entities:
- BPool
abis:
- name: BPool
file: ./node_modules/@oceanprotocol/contracts/artifacts/contracts/pools/balancer/BPool.sol/BPool.json
- name: BToken
file: ./node_modules/@oceanprotocol/contracts/artifacts/contracts/pools/balancer/BToken.sol/BToken.json
- name: BMath
file: ./node_modules/@oceanprotocol/contracts/artifacts/contracts/pools/balancer/BMath.sol/BMath.json
- name: ERC20
file: ./abis/ERC20.json
eventHandlers:
- event: LOG_SWAP(indexed address,indexed address,indexed address,uint256,uint256,uint256,uint256,uint256,uint256)
handler: handleSwap
- event: LOG_JOIN(indexed address,indexed address,uint256,uint256)
handler: handleJoin
- event: LOG_EXIT(indexed address,indexed address,uint256,uint256)
handler: handleExit
- event: LOG_SETUP(indexed address,indexed address,uint256,uint256,indexed address,uint256,uint256)
handler: handleSetup
- event: Transfer(indexed address,indexed address,uint256)
handler: handlerBptTransfer
- event: PublishMarketFeeChanged(address,address,uint256)
handler: handlePublishMarketFeeChanged
- event: SwapFeeChanged(address,uint256)
handler: handleSwapFeeChanged
- name: ERC721Template - name: ERC721Template
kind: ethereum/contract kind: ethereum/contract
network: __NETWORK__ network: __NETWORK__