diff --git a/schema.graphql b/schema.graphql index 1fcd6d6..2777df2 100644 --- a/schema.graphql +++ b/schema.graphql @@ -47,9 +47,6 @@ type Token @entity { "dispensers using this token" dispensers: [Dispenser!] @derivedFrom(field:"token") - "pools, only available for datatokens" - pools: [Pool!] @derivedFrom(field:"datatoken") - "block time datatoken was created" createdTimestamp: Int! @@ -76,7 +73,7 @@ type Nft @entity{ id: ID! symbol: String! name: String! - tokenUri: String! + tokenUri: String "address of the owner of the nft" owner: String! @@ -115,134 +112,6 @@ type Nft @entity{ 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 { id: ID! order: Order! @@ -253,6 +122,7 @@ type OrderReuse @entity { providerFee: String providerFeeValidUntil: BigInt } + type Order @entity { "transaction hash - token address - from address" id: ID! @@ -286,25 +156,9 @@ type Order @entity { 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 { id: ID! - sharesOwned: [PoolShare!] @derivedFrom(field: "user") tokenBalancesOwned: [TokenValuePair!] - poolTransactions: [PoolTransaction!] @derivedFrom(field: "user") orders: [Order!] @derivedFrom(field: "payer") freSwaps: [FixedRateExchangeSwap!] @derivedFrom(field: "by") @@ -422,28 +276,6 @@ type DispenserTransaction @entity { 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" type GlobalTotalLiquidityPair @entity { "address of the token" @@ -453,15 +285,6 @@ type GlobalTotalLiquidityPair @entity { value : BigDecimal! } -"utility type" -type GlobalTotalPoolSwapPair @entity { - "address of the token" - id : ID! - globalStatistic: GlobalStatistic! - token : Token! - value : BigDecimal! - count: BigInt! -} "utility type" type GlobalTotalFixedSwapPair @entity { "address of the token" @@ -472,25 +295,18 @@ type GlobalTotalFixedSwapPair @entity { count: BigInt! } type GlobalStatistic @entity { - 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") + id: ID! "total swap volume for each base token in fixed rate exchanges" 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! "total nfts(erc721) created" nftCount: Int! "total datatokens (tokens with isDatatoken = true) created" - datatokenCount:Int! - "number of pools" - poolCount: Int! + datatokenCount:Int! "number of fixed rate exchanges" fixedCount: Int! @@ -524,7 +340,7 @@ type OPC @entity { type NftUpdate @entity { id: ID! # update tx + nft address - tokenUri: String! + tokenUri: String nft: Nft! "provider url that can decrypt the ddo" diff --git a/src/mappings/dispenser.ts b/src/mappings/dispenser.ts index 79e22ab..a2c7a6b 100644 --- a/src/mappings/dispenser.ts +++ b/src/mappings/dispenser.ts @@ -17,6 +17,7 @@ import { weiToDecimal } from './utils/generic' import { addDispenser } from './utils/globalUtils' import { getToken } from './utils/tokenUtils' import { getUser } from './utils/userUtils' +import { BigDecimal } from '@graphprotocol/graph-ts' export function handleNewDispenser(event: DispenserCreated): void { const dispenserID = getDispenserGraphID( @@ -38,7 +39,7 @@ export function handleNewDispenser(event: DispenserCreated): void { token.decimals ) dispenser.active = true - + dispenser.balance = BigDecimal.zero() dispenser.allowedSwapper = event.params.allowedSwapper.toHex() dispenser.createdTimestamp = event.block.timestamp.toI32() dispenser.tx = event.transaction.hash.toHex() diff --git a/src/mappings/factoryRouter.ts b/src/mappings/factoryRouter.ts index 3704129..595634c 100644 --- a/src/mappings/factoryRouter.ts +++ b/src/mappings/factoryRouter.ts @@ -1,5 +1,4 @@ import { - NewPool, TokenAdded, TokenRemoved, OPCFeeChanged, @@ -12,19 +11,11 @@ import { DispenserContractRemoved } from '../@types/FactoryRouter/FactoryRouter' import { BigInt } from '@graphprotocol/graph-ts' -import { Pool } from '../@types/schema' -import { BPool, FixedRateExchange, Dispenser } from '../@types/templates' -import { addPool, getOPC, getTemplates } from './utils/globalUtils' +import { FixedRateExchange, Dispenser } from '../@types/templates' +import { getOPC, getTemplates } from './utils/globalUtils' import { weiToDecimal } from './utils/generic' 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 { const opc = getOPC() const decimals = BigInt.fromI32(18).toI32() diff --git a/src/mappings/fixedRateExchange.ts b/src/mappings/fixedRateExchange.ts index 0dfa05c..ee9d5f0 100644 --- a/src/mappings/fixedRateExchange.ts +++ b/src/mappings/fixedRateExchange.ts @@ -1,4 +1,4 @@ -import { BigInt, Address } from '@graphprotocol/graph-ts' +import { BigInt, Address, BigDecimal, log } from '@graphprotocol/graph-ts' import { ExchangeActivated, ExchangeAllowedSwapperChanged, @@ -38,7 +38,11 @@ export function handleExchangeCreated(event: ExchangeCreated): void { fixedRateExchange.exchangeId = event.params.exchangeId.toHexString() fixedRateExchange.datatoken = getToken(event.params.datatoken, true).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.price = weiToDecimal( event.params.fixedRate.toBigDecimal(), @@ -67,7 +71,7 @@ export function handleRateChange(event: ExchangeRateChanged): void { newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32() newExchangeUpdate.tx = event.transaction.hash.toHex() newExchangeUpdate.block = event.block.number.toI32() - + newExchangeUpdate.exchangeId = fixedRateId fixedRateExchange.price = weiToDecimal( event.params.newRate.toBigDecimal(), BigInt.fromI32(18).toI32() @@ -88,8 +92,6 @@ export function handleMintStateChanged(event: ExchangeMintStateChanged): void { fixedRateExchange.save() } -// TODO: implement fre updates/history for changes - export function handleActivated(event: ExchangeActivated): void { const fixedRateId = getFixedRateGraphID( event.params.exchangeId.toHexString(), @@ -99,6 +101,7 @@ export function handleActivated(event: ExchangeActivated): void { const newExchangeUpdate = new FixedRateExchangeUpdate( getUpdateOrSwapId(event.transaction.hash.toHex(), fixedRateId) ) + newExchangeUpdate.exchangeId = fixedRateId newExchangeUpdate.oldActive = fixedRateExchange.active newExchangeUpdate.newActive = true newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32() @@ -123,6 +126,7 @@ export function handleDeactivated(event: ExchangeDeactivated): void { newExchangeUpdate.oldActive = fixedRateExchange.active newExchangeUpdate.newActive = false + newExchangeUpdate.exchangeId = fixedRateId newExchangeUpdate.createdTimestamp = event.block.timestamp.toI32() newExchangeUpdate.tx = event.transaction.hash.toHex() newExchangeUpdate.block = event.block.number.toI32() @@ -178,6 +182,7 @@ export function handleSwap(event: Swapped): void { Address.fromString(fixedRateExchange.baseToken), false ) + swap.baseTokenAmount = weiToDecimal( event.params.baseTokenSwappedAmount.toBigDecimal(), BigInt.fromI32(baseToken.decimals).toI32() @@ -188,18 +193,17 @@ export function handleSwap(event: Swapped): void { ) swap.save() + 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( event.params.tokenOutAddress.toHexString(), swap.dataTokenAmount ) - else - addFixedSwap( - event.params.tokenOutAddress.toHexString(), - swap.baseTokenAmount - ) - + else addFixedSwap(fixedRateExchange.baseToken, swap.baseTokenAmount) + log.error('addFixedSwap saved', []) // update datatoken lastPriceToken and lastPriceValue const datatoken = getToken( Address.fromString(fixedRateExchange.datatoken), diff --git a/src/mappings/pool.ts b/src/mappings/pool.ts deleted file mode 100644 index 9f49d50..0000000 --- a/src/mappings/pool.ts +++ /dev/null @@ -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() - } -} diff --git a/src/mappings/utils/constants.ts b/src/mappings/utils/constants.ts index 895b18b..5741b9e 100644 --- a/src/mappings/utils/constants.ts +++ b/src/mappings/utils/constants.ts @@ -21,12 +21,6 @@ export namespace decimal { } // 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 const METADATA_CREATED = 'METADATA_CREATED' diff --git a/src/mappings/utils/globalUtils.ts b/src/mappings/utils/globalUtils.ts index cf81b6a..6c0b646 100644 --- a/src/mappings/utils/globalUtils.ts +++ b/src/mappings/utils/globalUtils.ts @@ -3,7 +3,6 @@ import { GlobalStatistic, GlobalTotalFixedSwapPair, GlobalTotalLiquidityPair, - GlobalTotalPoolSwapPair, OPC, Template } from '../../@types/schema' @@ -18,7 +17,6 @@ export function getGlobalStats(): GlobalStatistic { globalStats.orderCount = 0 globalStats.fixedCount = 0 globalStats.datatokenCount = 0 - globalStats.poolCount = 0 globalStats.dispenserCount = 0 globalStats.nftCount = 0 globalStats.save() @@ -74,31 +72,14 @@ export function addDispenser(): void { 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 { let fixedSwapPair = GlobalTotalFixedSwapPair.load(tokenAddress) if (!fixedSwapPair) { fixedSwapPair = new GlobalTotalFixedSwapPair(tokenAddress) fixedSwapPair.globalStatistic = GLOBAL_ID fixedSwapPair.token = tokenAddress + fixedSwapPair.value = BigDecimal.zero() + fixedSwapPair.count = BigInt.zero() } fixedSwapPair.value = fixedSwapPair.value.plus(value) fixedSwapPair.count = fixedSwapPair.count.plus(BigInt.fromI32(1)) diff --git a/src/mappings/utils/poolUtils.ts b/src/mappings/utils/poolUtils.ts deleted file mode 100644 index 84f3c78..0000000 --- a/src/mappings/utils/poolUtils.ts +++ /dev/null @@ -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 -} diff --git a/subgraph.template.yaml b/subgraph.template.yaml index 7250f3a..8a9cea7 100644 --- a/subgraph.template.yaml +++ b/subgraph.template.yaml @@ -49,8 +49,6 @@ dataSources: - name: ERC20 file: ./abis/ERC20.json eventHandlers: - - event: NewPool(indexed address,bool) - handler: handleNewPool - event: TokenAdded(indexed address,indexed address) handler: handleTokenAdded - event: TokenRemoved(indexed address,indexed address) @@ -116,43 +114,6 @@ templates: - event: ProviderFee(indexed address,indexed address,uint256,bytes,uint8,bytes32,bytes32,uint256) 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 kind: ethereum/contract network: __NETWORK__