Add swap volume, consume volume to subgraph (#64)

* Add swap volume, consume volume to subgraph

* add Global object, run lint

Co-authored-by: mihaisc <mihai@oceanprotocol.com>
This commit is contained in:
lacoop6tu 2021-07-30 02:36:44 -05:00 committed by GitHub
parent 9b3c466dff
commit dac185694b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 15149 additions and 15155 deletions

File diff suppressed because one or more lines are too long

View File

@ -110,20 +110,14 @@
"ast": {
"absolutePath": "/ocean/ocean-contracts/contracts/metadata/Metadata.sol",
"exportedSymbols": {
"Metadata": [
5158
]
"Metadata": [5158]
},
"id": 5159,
"nodeType": "SourceUnit",
"nodes": [
{
"id": 5072,
"literals": [
"solidity",
"0.5",
".7"
],
"literals": ["solidity", "0.5", ".7"],
"nodeType": "PragmaDirective",
"src": "0:22:11"
},
@ -145,9 +139,7 @@
"documentation": "@title Metadata\n \n@dev Metadata stands for Decentralized Document. It allows publishers\n to publish their dataset metadata in decentralized way.\n It follows the Ocean DID Document standard: \n https://github.com/oceanprotocol/OEPs/blob/master/7/v0.2/README.md",
"fullyImplemented": true,
"id": 5158,
"linearizedBaseContracts": [
5158
],
"linearizedBaseContracts": [5158],
"name": "Metadata",
"nodeType": "ContractDefinition",
"nodes": [
@ -408,9 +400,7 @@
"src": "886:195:11",
"statements": [
{
"assignments": [
5098
],
"assignments": [5098],
"declarations": [
{
"constant": false,
@ -625,10 +615,7 @@
"id": 5103,
"name": "require",
"nodeType": "Identifier",
"overloadedDeclarations": [
6536,
6537
],
"overloadedDeclarations": [6536, 6537],
"referencedDeclaration": 6537,
"src": "954:7:11",
"typeDescriptions": {
@ -1248,20 +1235,14 @@
"legacyAST": {
"absolutePath": "/ocean/ocean-contracts/contracts/metadata/Metadata.sol",
"exportedSymbols": {
"Metadata": [
5158
]
"Metadata": [5158]
},
"id": 5159,
"nodeType": "SourceUnit",
"nodes": [
{
"id": 5072,
"literals": [
"solidity",
"0.5",
".7"
],
"literals": ["solidity", "0.5", ".7"],
"nodeType": "PragmaDirective",
"src": "0:22:11"
},
@ -1283,9 +1264,7 @@
"documentation": "@title Metadata\n \n@dev Metadata stands for Decentralized Document. It allows publishers\n to publish their dataset metadata in decentralized way.\n It follows the Ocean DID Document standard: \n https://github.com/oceanprotocol/OEPs/blob/master/7/v0.2/README.md",
"fullyImplemented": true,
"id": 5158,
"linearizedBaseContracts": [
5158
],
"linearizedBaseContracts": [5158],
"name": "Metadata",
"nodeType": "ContractDefinition",
"nodes": [
@ -1546,9 +1525,7 @@
"src": "886:195:11",
"statements": [
{
"assignments": [
5098
],
"assignments": [5098],
"declarations": [
{
"constant": false,
@ -1763,10 +1740,7 @@
"id": 5103,
"name": "require",
"nodeType": "Identifier",
"overloadedDeclarations": [
6536,
6537
],
"overloadedDeclarations": [6536, 6537],
"referencedDeclaration": 6537,
"src": "954:7:11",
"typeDescriptions": {
@ -2415,4 +2389,4 @@
"userdoc": {
"methods": {}
}
}
}

View File

@ -1 +1 @@
INFURA_PROJECT_ID="xxx"
INFURA_PROJECT_ID="5dfd675029394431a1a86137a281b9bf"

View File

@ -44,8 +44,8 @@ You can replace this with anything else in `docker-compose.yaml`.
> To do this, run:
>
> ```
> CONTAINER_ID=$(docker container ls | grep graph-node | cut -d' ' -f1)
> docker exec $CONTAINER_ID /bin/bash -c 'apt install -y iproute2 && ip route' | awk '/^default via /{print $3}'
CONTAINER_ID=$(docker container ls | grep graph-node | cut -d' ' -f1)
docker exec $CONTAINER_ID /bin/bash -c 'apt install -y iproute2 && ip route' | awk '/^default via /{print $3}'
> ```
>
> This will print the host's IP address. Then, put it into `docker-compose.yml`:

View File

@ -1,50 +1,67 @@
type PoolFactory @entity {
id: ID!
id: ID!
totalValueLocked: BigDecimal # total value from all pools expressed in OCEAN
totalOceanLiquidity: BigDecimal! # Total of OCEAN liquidity from all pools
totalSwapVolume: BigDecimal! # All the swap volume in Ocean
totalSwapFee: BigDecimal! # All the swap fee in Ocean
poolCount: Int! # Number of pools
finalizedPoolCount: Int! # Number of finalized pools
pools: [Pool!] @derivedFrom(field: "factoryID")
totalValueLocked: BigDecimal # total value from all pools expressed in OCEAN
totalOceanLiquidity: BigDecimal! # Total of OCEAN liquidity from all pools
totalSwapVolume: BigDecimal! # All the swap volume in Ocean
totalSwapFee: BigDecimal! # All the swap fee in Ocean
totalOrderVolume: BigDecimal
poolCount: Int! # Number of pools
finalizedPoolCount: Int! # Number of finalized pools
orderCount: BigInt # Number of total consumes
pools: [Pool!] @derivedFrom(field: "factoryID")
}
type Global @entity {
id: ID!
totalValueLocked: BigDecimal # total value from all pools expressed in OCEAN
totalOceanLiquidity: BigDecimal! # Total of OCEAN liquidity from all pools
totalSwapVolume: BigDecimal! # All the swap volume in Ocean
totalOrderVolume: BigDecimal
orderCount: BigInt
poolCount: Int!
}
type Pool @entity {
id: ID! # Pool address
factoryID: PoolFactory!
controller: Bytes! # Controller address
publicSwap: Boolean! # isPublicSwap
finalized: Boolean! # isFinalized
symbol: String # Pool token symbol
name: String # Pool token name
cap: BigInt # Maximum supply if any
active: Boolean! # isActive
swapFee: BigDecimal! # Swap Fees
totalWeight: BigDecimal!
totalShares: BigDecimal! # Total pool token shares
totalSwapVolume: BigDecimal! # Total swap volume in OCEAN
totalSwapFee: BigDecimal! # Total swap fee in OCEAN
valueLocked: BigDecimal! # value locked in pool expressed in OCEAN (captures both Ocean and Datatoken)
datatokenReserve: BigDecimal! # Total pool reserve of Datatoken
oceanReserve: BigDecimal! # Total pool reserve of OCEAN
spotPrice: BigDecimal!
consumePrice: BigDecimal!
id: ID! # Pool address
factoryID: PoolFactory!
controller: Bytes! # Controller address
publicSwap: Boolean! # isPublicSwap
finalized: Boolean! # isFinalized
symbol: String # Pool token symbol
name: String # Pool token name
cap: BigInt # Maximum supply if any
active: Boolean! # isActive
swapFee: BigDecimal! # Swap Fees
tokenCount: BigInt! # Number of tokens in the pool
holderCount: BigInt! # Number of addresses holding a positive balance of pool shares
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
tx: Bytes # Pool creation transaction id
tokens: [PoolToken!] @derivedFrom(field: "poolId")
shares: [PoolShare!] @derivedFrom(field: "poolId")
transactions: [PoolTransaction!] @derivedFrom(field: "poolAddress")
transactionsTokenValues: [PoolTransactionTokenValues!]
@derivedFrom(field: "poolAddress")
totalWeight: BigDecimal!
totalShares: BigDecimal! # Total pool token shares
totalSwapVolume: BigDecimal! # Total swap volume in OCEAN
totalSwapFee: BigDecimal! # Total swap fee in OCEAN
valueLocked: BigDecimal! # value locked in pool expressed in OCEAN (captures both Ocean and Datatoken)
datatokenReserve: BigDecimal! # Total pool reserve of Datatoken
oceanReserve: BigDecimal! # Total pool reserve of OCEAN
spotPrice: BigDecimal!
consumePrice: BigDecimal!
tokenCount: BigInt! # Number of tokens in the pool
holderCount: BigInt! # Number of addresses holding a positive balance of pool shares
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
tx: Bytes # Pool creation transaction id
tokens: [PoolToken!] @derivedFrom(field: "poolId")
shares: [PoolShare!] @derivedFrom(field: "poolId")
transactions: [PoolTransaction!] @derivedFrom(field: "poolAddress")
transactionsTokenValues: [PoolTransactionTokenValues!] @derivedFrom(field: "poolAddress")
}
@ -118,27 +135,29 @@ type DatatokenFactory @entity {
}
type Datatoken @entity {
id: ID! # token address
factoryID: DatatokenFactory!
id: ID! # token address
factoryID: DatatokenFactory!
symbol: String
name: String
decimals: Int!
address: String!
cap: BigDecimal!
supply: BigDecimal!
minter: User!
publisher: String!
symbol: String
name: String
decimals: Int!
address: String!
cap: BigDecimal!
supply: BigDecimal!
minter: User!
publisher: String!
holderCount: BigInt! # Number of addresses holding a balance of datatoken
orderCount: BigInt! # Number of orders executed for this dataset
metadataUpdateCount: BigInt!
holderCount: BigInt! # Number of addresses holding a balance of datatoken
orderCount: BigInt! # Number of orders executed for this dataset
metadataUpdateCount: BigInt!
orderVolume: BigDecimal
createTime: Int! # Block time datatoken was created
tx: Bytes # Datatoken creation transaction id
createTime: Int! # Block time datatoken was created
tx: Bytes # Datatoken creation transaction id
balances: [TokenBalance!] @derivedFrom(field: "datatokenId")
orders: [TokenOrder!] @derivedFrom(field: "datatokenId")
updates: [MetadataUpdate!] @derivedFrom(field: "datatokenId") # list of MetadataUpdate objects
balances: [TokenBalance!] @derivedFrom(field: "datatokenId")
orders: [TokenOrder!] @derivedFrom(field: "datatokenId")
updates: [MetadataUpdate!] @derivedFrom(field: "datatokenId") # list of MetadataUpdate objects
}
type MetadataUpdate @entity {

View File

@ -18,7 +18,8 @@ import {
Datatoken,
TokenBalance,
TokenTransaction,
PoolTransactionTokenValues
PoolTransactionTokenValues,
Global
} from './@types/schema'
import { Pool } from './@types/templates/Pool/Pool'
@ -37,7 +38,7 @@ export const ENABLE_DEBUG = true
const network = dataSource.network()
function getOceanAddress(): string {
export function getOceanAddress(): string {
// switch is not working for some reason
if (network == 'ropsten') return '0x5e8dcb2afa23844bcc311b00ad1a0c30025aade9'
if (network == 'rinkeby') return '0x8967bcf84170c91b0d24d4302c2376283b0b3a07'
@ -53,6 +54,21 @@ function getOceanAddress(): string {
export const OCEAN: string = getOceanAddress()
export function getGlobalStats(): Global | null {
let gStats: Global | null = Global.load('1')
if (gStats == null) {
gStats = new Global('1')
gStats.totalOceanLiquidity = ZERO_BD
gStats.totalSwapVolume = ZERO_BD
gStats.totalValueLocked = ZERO_BD
gStats.totalOrderVolume = ZERO_BD
gStats.orderCount = BigInt.fromI32(0)
gStats.poolCount = 0
}
return gStats
}
export function _debuglog(
message: string,
event: ethereum.Event,
@ -192,6 +208,30 @@ export function updatePoolTokenBalance(
poolToken.balance = balance
}
export function updatePoolSwapVolume(
pool: Pool,
swapAmount: BigDecimal
// source: string
): void {
debuglog(
'########## updating poolToken balance (source, oldBalance, newBalance, poolId) ',
null,
[source, pool.totalSwapVolume.toString(), swapAmount.toString(), pool.id]
)
if (swapAmount < ZERO_BD || pool.totalSwapVolume < ZERO_BD) {
log.warning(
'EEEEEEEEEEEEEEEEE poolToken.balance < Zero: pool={}, poolToken={}, oldBalance={}, newBalance={}',
[
pool.id,
poolToken.tokenAddress.toString(),
poolToken.balance.toString(),
swapAmount.toString()
]
)
}
poolToken.swapBalanceOcean = poolToken.swapBalanceOcean.plus(swapAmount)
}
export function createUserEntity(address: string): void {
if (User.load(address) == null) {
const user = new User(address)
@ -289,9 +329,15 @@ export function updatePoolTransactionToken(
log.warning('ptxTokenValues {} saved', [ptxTokenValues.id])
if (ptxTokenValues.tokenAddress == OCEAN) {
const factory = PoolFactory.load('1')
factory.totalOceanLiquidity = factory.totalOceanLiquidity
.plus(ptxTokenValues.tokenReserve)
.minus(pool.oceanReserve)
const gStats: Global | null = getGlobalStats()
gStats.totalOceanLiquidity = factory.totalOceanLiquidity
gStats.save()
if (factory.totalOceanLiquidity < ZERO_BD || pool.oceanReserve < ZERO_BD) {
log.warning(
'EEEEEEEEEEEEEEEEE totalOceanLiquidity or oceanReserve < Zero: pool={}, totOcnLiq={}, ocnRes={}',
@ -467,6 +513,11 @@ export function createPoolTransaction(
.minus(oldValueLocked)
.plus(pool.valueLocked)
const gStats: Global | null = getGlobalStats()
gStats.totalValueLocked = factory.totalValueLocked
gStats.save()
pool.transactionCount = pool.transactionCount.plus(BigInt.fromI32(1))
pool.save()

View File

@ -1,13 +1,20 @@
import { BigInt, BigDecimal } from '@graphprotocol/graph-ts'
import { OrderStarted, Transfer } from '../@types/templates/DataToken/DataToken'
import { Datatoken, TokenBalance, TokenOrder } from '../@types/schema'
import {
Datatoken,
Global,
PoolFactory,
TokenBalance,
TokenOrder
} from '../@types/schema'
import {
tokenToDecimal,
updateTokenBalance,
ZERO_BD,
MINUS_1_BD,
saveTokenTransaction
saveTokenTransaction,
getGlobalStats
} from '../helpers'
/************************************
@ -125,8 +132,31 @@ export function handleOrderStarted(event: OrderStarted): void {
order.save()
datatoken.orderVolume = datatoken.orderVolume.plus(order.amount)
datatoken.orderCount = datatoken.orderCount.plus(BigInt.fromI32(1))
datatoken.save()
saveTokenTransaction(event, 'OrderStarted')
let factory = PoolFactory.load('1')
if (factory == null) {
factory = new PoolFactory('1')
factory.totalOceanLiquidity = ZERO_BD
factory.totalSwapVolume = ZERO_BD
factory.totalSwapFee = ZERO_BD
factory.totalValueLocked = ZERO_BD
factory.orderCount = BigInt.fromI32(0)
factory.poolCount = 0
factory.finalizedPoolCount = 0
}
factory.orderCount = factory.orderCount.plus(BigInt.fromI32(1))
factory.totalOrderVolume = factory.totalOrderVolume.plus(order.amount)
factory.save()
const gStats: Global | null = getGlobalStats()
gStats.orderCount = factory.orderCount
gStats.totalOrderVolume = factory.totalOrderVolume
gStats.save()
}

View File

@ -37,6 +37,7 @@ export function handleNewToken(event: TokenRegistered): void {
datatoken.holderCount = BigInt.fromI32(0)
datatoken.orderCount = BigInt.fromI32(0)
datatoken.orderVolume = BigInt.fromI32(0).toBigDecimal()
datatoken.metadataUpdateCount = BigInt.fromI32(0)
datatoken.createTime = event.block.timestamp.toI32()

View File

@ -1,8 +1,8 @@
import { BigInt, BigDecimal, log } from '@graphprotocol/graph-ts'
import { BPoolRegistered } from '../@types/Factory/Factory'
import { PoolFactory, Pool } from '../@types/schema'
import { PoolFactory, Pool, Global } from '../@types/schema'
import { Pool as PoolContract } from '../@types/templates'
import { ZERO_BD } from '../helpers'
import { ZERO_BD, getGlobalStats } from '../helpers'
export function handleNewPool(event: BPoolRegistered): void {
let factory = PoolFactory.load('1')
@ -13,7 +13,7 @@ export function handleNewPool(event: BPoolRegistered): void {
factory.totalSwapVolume = ZERO_BD
factory.totalSwapFee = ZERO_BD
factory.totalValueLocked = ZERO_BD
factory.orderCount = BigInt.fromI32(0)
factory.poolCount = 0
factory.finalizedPoolCount = 0
}
@ -60,6 +60,9 @@ export function handleNewPool(event: BPoolRegistered): void {
factory.poolCount = factory.poolCount + 1
factory.save()
const gStats: Global | null = getGlobalStats()
gStats.poolCount = factory.poolCount
gStats.save()
PoolContract.create(event.params.bpoolAddress)
}

View File

@ -14,7 +14,8 @@ import {
PoolToken,
PoolShare,
Datatoken,
PoolTransaction
PoolTransaction,
Global
} from '../@types/schema'
import {
hexToDecimal,
@ -29,6 +30,8 @@ import {
OCEAN,
debuglog,
updatePoolTokenBalance,
getOceanAddress,
getGlobalStats,
bigIntToDecimal
} from '../helpers'
@ -392,13 +395,28 @@ export function handleSwap(event: LOG_SWAP): void {
]
)
const pool = Pool.load(poolId)
const factory = PoolFactory.load('1')
pool.swapCount = pool.swapCount.plus(BigInt.fromI32(1))
if (newAmountIn.equals(ZERO_BD) || newAmountOut.equals(ZERO_BD)) {
decrPoolCount(pool.finalized)
pool.active = false
}
if (tokenIn === getOceanAddress()) {
pool.totalSwapVolume = pool.totalSwapVolume.plus(tokenAmountIn)
factory.totalSwapVolume = factory.totalSwapVolume.plus(tokenAmountIn)
} else {
pool.totalSwapVolume = pool.totalSwapVolume.plus(tokenAmountOut)
factory.totalSwapVolume = factory.totalSwapVolume.plus(tokenAmountOut)
}
factory.save()
pool.save()
const gStats: Global | null = getGlobalStats()
gStats.totalSwapVolume = factory.totalSwapVolume
gStats.save()
createPoolTransaction(event, 'swap', event.params.caller.toHexString())
updatePoolTransactionToken(
ptx,