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": { "ast": {
"absolutePath": "/ocean/ocean-contracts/contracts/metadata/Metadata.sol", "absolutePath": "/ocean/ocean-contracts/contracts/metadata/Metadata.sol",
"exportedSymbols": { "exportedSymbols": {
"Metadata": [ "Metadata": [5158]
5158
]
}, },
"id": 5159, "id": 5159,
"nodeType": "SourceUnit", "nodeType": "SourceUnit",
"nodes": [ "nodes": [
{ {
"id": 5072, "id": 5072,
"literals": [ "literals": ["solidity", "0.5", ".7"],
"solidity",
"0.5",
".7"
],
"nodeType": "PragmaDirective", "nodeType": "PragmaDirective",
"src": "0:22:11" "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", "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, "fullyImplemented": true,
"id": 5158, "id": 5158,
"linearizedBaseContracts": [ "linearizedBaseContracts": [5158],
5158
],
"name": "Metadata", "name": "Metadata",
"nodeType": "ContractDefinition", "nodeType": "ContractDefinition",
"nodes": [ "nodes": [
@ -408,9 +400,7 @@
"src": "886:195:11", "src": "886:195:11",
"statements": [ "statements": [
{ {
"assignments": [ "assignments": [5098],
5098
],
"declarations": [ "declarations": [
{ {
"constant": false, "constant": false,
@ -625,10 +615,7 @@
"id": 5103, "id": 5103,
"name": "require", "name": "require",
"nodeType": "Identifier", "nodeType": "Identifier",
"overloadedDeclarations": [ "overloadedDeclarations": [6536, 6537],
6536,
6537
],
"referencedDeclaration": 6537, "referencedDeclaration": 6537,
"src": "954:7:11", "src": "954:7:11",
"typeDescriptions": { "typeDescriptions": {
@ -1248,20 +1235,14 @@
"legacyAST": { "legacyAST": {
"absolutePath": "/ocean/ocean-contracts/contracts/metadata/Metadata.sol", "absolutePath": "/ocean/ocean-contracts/contracts/metadata/Metadata.sol",
"exportedSymbols": { "exportedSymbols": {
"Metadata": [ "Metadata": [5158]
5158
]
}, },
"id": 5159, "id": 5159,
"nodeType": "SourceUnit", "nodeType": "SourceUnit",
"nodes": [ "nodes": [
{ {
"id": 5072, "id": 5072,
"literals": [ "literals": ["solidity", "0.5", ".7"],
"solidity",
"0.5",
".7"
],
"nodeType": "PragmaDirective", "nodeType": "PragmaDirective",
"src": "0:22:11" "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", "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, "fullyImplemented": true,
"id": 5158, "id": 5158,
"linearizedBaseContracts": [ "linearizedBaseContracts": [5158],
5158
],
"name": "Metadata", "name": "Metadata",
"nodeType": "ContractDefinition", "nodeType": "ContractDefinition",
"nodes": [ "nodes": [
@ -1546,9 +1525,7 @@
"src": "886:195:11", "src": "886:195:11",
"statements": [ "statements": [
{ {
"assignments": [ "assignments": [5098],
5098
],
"declarations": [ "declarations": [
{ {
"constant": false, "constant": false,
@ -1763,10 +1740,7 @@
"id": 5103, "id": 5103,
"name": "require", "name": "require",
"nodeType": "Identifier", "nodeType": "Identifier",
"overloadedDeclarations": [ "overloadedDeclarations": [6536, 6537],
6536,
6537
],
"referencedDeclaration": 6537, "referencedDeclaration": 6537,
"src": "954:7:11", "src": "954:7:11",
"typeDescriptions": { "typeDescriptions": {

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: > To do this, run:
> >
> ``` > ```
> CONTAINER_ID=$(docker container ls | grep graph-node | cut -d' ' -f1) 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}' 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`: > This will print the host's IP address. Then, put it into `docker-compose.yml`:

View File

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

View File

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

View File

@ -1,13 +1,20 @@
import { BigInt, BigDecimal } from '@graphprotocol/graph-ts' import { BigInt, BigDecimal } from '@graphprotocol/graph-ts'
import { OrderStarted, Transfer } from '../@types/templates/DataToken/DataToken' 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 { import {
tokenToDecimal, tokenToDecimal,
updateTokenBalance, updateTokenBalance,
ZERO_BD, ZERO_BD,
MINUS_1_BD, MINUS_1_BD,
saveTokenTransaction saveTokenTransaction,
getGlobalStats
} from '../helpers' } from '../helpers'
/************************************ /************************************
@ -125,8 +132,31 @@ export function handleOrderStarted(event: OrderStarted): void {
order.save() order.save()
datatoken.orderVolume = datatoken.orderVolume.plus(order.amount)
datatoken.orderCount = datatoken.orderCount.plus(BigInt.fromI32(1)) datatoken.orderCount = datatoken.orderCount.plus(BigInt.fromI32(1))
datatoken.save() datatoken.save()
saveTokenTransaction(event, 'OrderStarted') 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.holderCount = BigInt.fromI32(0)
datatoken.orderCount = BigInt.fromI32(0) datatoken.orderCount = BigInt.fromI32(0)
datatoken.orderVolume = BigInt.fromI32(0).toBigDecimal()
datatoken.metadataUpdateCount = BigInt.fromI32(0) datatoken.metadataUpdateCount = BigInt.fromI32(0)
datatoken.createTime = event.block.timestamp.toI32() datatoken.createTime = event.block.timestamp.toI32()

View File

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

View File

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