Skip to content

Commit

Permalink
Process & map MarketDestroyedEvent (#204)
Browse files Browse the repository at this point in the history
* Generate types for MarketDestroyedEvent

* Init PredictionMarketsMarketDestroyedEvent

* Create handler marketDestroyed

* Connect handler to processor
  • Loading branch information
saboonikhil committed Oct 19, 2022
1 parent 4c87c65 commit fcf1f26
Show file tree
Hide file tree
Showing 7 changed files with 206 additions and 23 deletions.
37 changes: 29 additions & 8 deletions src/mappings/predictionMarkets/index.ts
Expand Up @@ -2,16 +2,15 @@ import { encodeAddress } from '@polkadot/keyring'
import { EventHandlerContext } from '@subsquid/substrate-processor'
import { Store } from '@subsquid/typeorm-store'
import * as ss58 from '@subsquid/ss58'
import { util } from '@zeitgeistpm/sdk'
import { Like } from 'typeorm'
import { Account, AccountBalance, Asset, CategoryMetadata, HistoricalAccountBalance, HistoricalAsset, HistoricalMarket,
Market, MarketDisputeMechanism, MarketPeriod, MarketReport, MarketType, OutcomeReport } from '../../model'
import { createAssetsForMarket, decodeMarketMetadata } from '../helper'
import { Tools } from '../util'
import { getBoughtCompleteSetEvent, getMarketApprovedEvent, getMarketClosedEvent, getMarketCreatedEvent,
getMarketDisputedEvent, getMarketExpiredEvent, getMarketInsufficientSubsidyEvent, getMarketRejectedEvent,
getMarketReportedEvent, getMarketResolvedEvent, getMarketStartedWithSubsidyEvent, getSoldCompleteSetEvent,
getTokensRedeemedEvent } from './types'
getMarketDestroyedEvent, getMarketDisputedEvent, getMarketExpiredEvent, getMarketInsufficientSubsidyEvent,
getMarketRejectedEvent, getMarketReportedEvent, getMarketResolvedEvent, getMarketStartedWithSubsidyEvent,
getSoldCompleteSetEvent, getTokensRedeemedEvent } from './types'


export async function boughtCompleteSet(ctx: EventHandlerContext<Store>) {
Expand Down Expand Up @@ -296,6 +295,28 @@ export async function marketCreated(ctx: EventHandlerContext<Store, {event: {arg
}
}

export async function marketDestroyed(ctx: EventHandlerContext<Store, {event: {args: true}}>) {
const {store, block, event} = ctx
const {marketId} = getMarketDestroyedEvent(ctx)

let market = await store.get(Market, { where: { marketId: marketId } })
if (!market) return

market.status = 'Destroyed'
console.log(`[${event.name}] Saving market: ${JSON.stringify(market, null, 2)}`)
await store.save<Market>(market)

let hm = new HistoricalMarket()
hm.id = event.id + '-' + market.marketId
hm.marketId = market.marketId
hm.event = event.name.split('.')[1]
hm.status = market.status
hm.blockNumber = block.height
hm.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical market: ${JSON.stringify(hm, null, 2)}`)
await store.save<HistoricalMarket>(hm)
}

export async function marketDisputed(ctx: EventHandlerContext<Store, {event: {args: true}}>) {
const {store, block, event} = ctx
const {marketId, status, report} = getMarketDisputedEvent(ctx)
Expand Down Expand Up @@ -480,11 +501,11 @@ export async function marketResolved(ctx: EventHandlerContext<Store, {event: {ar
const oldPrice = asset.price
const oldAssetQty = asset.amountInPool

if (market.marketType.scalar && asset.assetId.indexOf('Long') > -1) {
if (market.marketType.scalar && asset.assetId.includes('Long')) {
const upperRange = Number(market.marketType.scalar!.split(',')[1])
const lowerRange = Number(market.marketType.scalar!.split(',')[0])
asset.price = (+market.resolvedOutcome - lowerRange)/(upperRange - lowerRange)
} else if (market.marketType.scalar && asset.assetId.indexOf('Short') > -1) {
} else if (market.marketType.scalar && asset.assetId.includes('Short')) {
const upperRange = Number(market.marketType.scalar!.split(',')[1])
const lowerRange = Number(market.marketType.scalar!.split(',')[0])
asset.price = (upperRange - +market.resolvedOutcome)/(upperRange - lowerRange)
Expand All @@ -500,8 +521,8 @@ export async function marketResolved(ctx: EventHandlerContext<Store, {event: {ar
ha.assetId = asset.assetId
ha.newPrice = asset.price
ha.newAmountInPool = asset.amountInPool
ha.dPrice = oldPrice && asset.price ? asset.price - oldPrice : null
ha.dAmountInPool = oldAssetQty && asset.amountInPool ? asset.amountInPool - oldAssetQty : null
ha.dPrice = oldPrice ? ha.newPrice - oldPrice : null
ha.dAmountInPool = oldAssetQty && ha.newAmountInPool ? ha.newAmountInPool - oldAssetQty : null
ha.event = event.name.split('.')[1]
ha.blockNumber = block.height
ha.timestamp = new Date(block.timestamp)
Expand Down
23 changes: 19 additions & 4 deletions src/mappings/predictionMarkets/types.ts
Expand Up @@ -5,10 +5,10 @@ import { Store } from '@subsquid/typeorm-store'
import { EventContext } from '../../types/support'
import { MarketDispute, OutcomeReport, Report } from '../../types/v29'
import { PredictionMarketsBoughtCompleteSetEvent, PredictionMarketsMarketApprovedEvent, PredictionMarketsMarketClosedEvent,
PredictionMarketsMarketDisputedEvent, PredictionMarketsMarketExpiredEvent, PredictionMarketsMarketInsufficientSubsidyEvent,
PredictionMarketsMarketRejectedEvent, PredictionMarketsMarketReportedEvent, PredictionMarketsMarketResolvedEvent,
PredictionMarketsMarketStartedWithSubsidyEvent, PredictionMarketsSoldCompleteSetEvent, PredictionMarketsTokensRedeemedEvent
} from '../../types/events'
PredictionMarketsMarketDestroyedEvent, PredictionMarketsMarketDisputedEvent, PredictionMarketsMarketExpiredEvent,
PredictionMarketsMarketInsufficientSubsidyEvent, PredictionMarketsMarketRejectedEvent, PredictionMarketsMarketReportedEvent,
PredictionMarketsMarketResolvedEvent, PredictionMarketsMarketStartedWithSubsidyEvent, PredictionMarketsSoldCompleteSetEvent,
PredictionMarketsTokensRedeemedEvent } from '../../types/events'
import { getAssetId } from '../helper'


Expand Down Expand Up @@ -97,6 +97,17 @@ export function getMarketCreatedEvent(ctx: EventHandlerContext<Store, {event: {a
}
}

export function getMarketDestroyedEvent(ctx: EventContext): MarketDestroyedEvent {
const event = new PredictionMarketsMarketDestroyedEvent(ctx)
if (event.isV32) {
const marketId = Number(event.asV32)
return {marketId}
} else {
const marketId = Number(ctx.event.args)
return {marketId}
}
}

export function getMarketDisputedEvent(ctx: EventContext): MarketDisputedEvent {
const marketDisputedEvent = new PredictionMarketsMarketDisputedEvent(ctx)
if (marketDisputedEvent.isV23) {
Expand Down Expand Up @@ -282,6 +293,10 @@ interface MarketCreatedEvent {
market: any
}

interface MarketDestroyedEvent {
marketId: number
}

interface MarketDisputedEvent {
marketId: number
status: string
Expand Down
7 changes: 4 additions & 3 deletions src/processor.ts
Expand Up @@ -4,9 +4,9 @@ import { balancesBalanceSet, balancesDustLost, balancesEndowed, balancesReserved
balancesTransferOld, balancesUnreserved, balancesWithdraw } from './mappings/balances';
import { currencyDeposited, currencyTransferred, currencyWithdrawn } from './mappings/currency';
import { parachainStakingRewarded } from './mappings/parachainStaking';
import { boughtCompleteSet, marketApproved, marketClosed, marketCreated, marketDisputed, marketExpired,
marketInsufficientSubsidy, marketRejected, marketReported, marketResolved, marketStartedWithSubsidy,
soldCompleteSet, tokensRedeemed} from './mappings/predictionMarkets';
import { boughtCompleteSet, marketApproved, marketClosed, marketCreated, marketDestroyed, marketDisputed,
marketExpired, marketInsufficientSubsidy, marketRejected, marketReported, marketResolved,
marketStartedWithSubsidy, soldCompleteSet, tokensRedeemed} from './mappings/predictionMarkets';
import { poolActive, poolClosed, poolCreate, poolExit, poolJoin, swapExactAmountIn,
swapExactAmountOut } from './mappings/swaps';
import { systemExtrinsicFailed, systemExtrinsicSuccess, systemNewAccount } from './mappings/system';
Expand Down Expand Up @@ -45,6 +45,7 @@ processor.addEventHandler('PredictionMarkets.BoughtCompleteSet', ctx => boughtCo
processor.addEventHandler('PredictionMarkets.MarketApproved', ctx => marketApproved(ctx))
processor.addEventHandler('PredictionMarkets.MarketClosed', ctx => marketClosed(ctx))
processor.addEventHandler('PredictionMarkets.MarketCreated', ctx => marketCreated(ctx))
processor.addEventHandler('PredictionMarkets.MarketDestroyed', ctx => marketDestroyed(ctx))
processor.addEventHandler('PredictionMarkets.MarketDisputed', ctx => marketDisputed(ctx))
processor.addEventHandler('PredictionMarkets.MarketExpired', ctx => marketExpired(ctx))
processor.addEventHandler('PredictionMarkets.MarketInsufficientSubsidy', ctx => marketInsufficientSubsidy(ctx))
Expand Down
98 changes: 94 additions & 4 deletions src/types/events.ts
@@ -1,6 +1,7 @@
import assert from 'assert'
import {Chain, ChainContext, EventContext, Event, Result} from './support'
import * as v23 from './v23'
import * as v26 from './v26'
import * as v29 from './v29'
import * as v32 from './v32'
import * as v34 from './v34'
Expand Down Expand Up @@ -749,6 +750,35 @@ export class PredictionMarketsMarketCreatedEvent {
}
}

export class PredictionMarketsMarketDestroyedEvent {
private readonly _chain: Chain
private readonly event: Event

constructor(ctx: EventContext)
constructor(ctx: ChainContext, event: Event)
constructor(ctx: EventContext, event?: Event) {
event = event || ctx.event
assert(event.name === 'PredictionMarkets.MarketDestroyed')
this._chain = ctx._chain
this.event = event
}

/**
* A market has been created \[market_id, creator\]
*/
get isV32(): boolean {
return this._chain.getEventHash('PredictionMarkets.MarketDestroyed') === '47b59f698451e50cce59979f0121e842fa3f8b2bcef2e388222dbd69849514f9'
}

/**
* A market has been created \[market_id, creator\]
*/
get asV32(): bigint {
assert(this.isV32)
return this._chain.decodeEvent(this.event)
}
}

export class PredictionMarketsMarketDisputedEvent {
private readonly _chain: Chain
private readonly event: Event
Expand Down Expand Up @@ -1281,7 +1311,7 @@ export class SwapsPoolExitEvent {
* Someone has exited a pool. \[PoolAssetsEvent\]
*/
get isV23(): boolean {
return this._chain.getEventHash('Swaps.PoolExit') === '99ab0bd285f6f944198c5f42dd98b41f7b9fcf0c44ef6977cf76c3f99c4c184b'
return this._chain.getEventHash('Swaps.PoolExit') === 'a11030c3c6675fd4762b00dbf07071dd2be36329d8293d6c4d83e95c52a284b0'
}

/**
Expand All @@ -1292,6 +1322,21 @@ export class SwapsPoolExitEvent {
return this._chain.decodeEvent(this.event)
}

/**
* Someone has exited a pool. \[PoolAssetsEvent\]
*/
get isV26(): boolean {
return this._chain.getEventHash('Swaps.PoolExit') === '99ab0bd285f6f944198c5f42dd98b41f7b9fcf0c44ef6977cf76c3f99c4c184b'
}

/**
* Someone has exited a pool. \[PoolAssetsEvent\]
*/
get asV26(): v26.PoolAssetsEvent {
assert(this.isV26)
return this._chain.decodeEvent(this.event)
}

/**
* Someone has exited a pool. \[PoolAssetsEvent\]
*/
Expand Down Expand Up @@ -1340,7 +1385,7 @@ export class SwapsPoolJoinEvent {
* Someone has joined a pool. \[PoolAssetsEvent\]
*/
get isV23(): boolean {
return this._chain.getEventHash('Swaps.PoolJoin') === '99ab0bd285f6f944198c5f42dd98b41f7b9fcf0c44ef6977cf76c3f99c4c184b'
return this._chain.getEventHash('Swaps.PoolJoin') === 'a11030c3c6675fd4762b00dbf07071dd2be36329d8293d6c4d83e95c52a284b0'
}

/**
Expand All @@ -1351,6 +1396,21 @@ export class SwapsPoolJoinEvent {
return this._chain.decodeEvent(this.event)
}

/**
* Someone has joined a pool. \[PoolAssetsEvent\]
*/
get isV26(): boolean {
return this._chain.getEventHash('Swaps.PoolJoin') === '99ab0bd285f6f944198c5f42dd98b41f7b9fcf0c44ef6977cf76c3f99c4c184b'
}

/**
* Someone has joined a pool. \[PoolAssetsEvent\]
*/
get asV26(): v26.PoolAssetsEvent {
assert(this.isV26)
return this._chain.decodeEvent(this.event)
}

/**
* Someone has joined a pool. \[PoolAssetsEvent\]
*/
Expand Down Expand Up @@ -1399,7 +1459,7 @@ export class SwapsSwapExactAmountInEvent {
* An exact amount of an asset is entering the pool. \[SwapEvent\]
*/
get isV23(): boolean {
return this._chain.getEventHash('Swaps.SwapExactAmountIn') === '3890c2f04c258eefbc9739d3d4bde06dfdbb1b5ce6ce3a1f2a3c45220d3db6d9'
return this._chain.getEventHash('Swaps.SwapExactAmountIn') === '69d6a45c326b79e217d8cc5e5b3e79884d92a90749656b63c90a6fcc42de850c'
}

/**
Expand All @@ -1410,6 +1470,21 @@ export class SwapsSwapExactAmountInEvent {
return this._chain.decodeEvent(this.event)
}

/**
* An exact amount of an asset is entering the pool. \[SwapEvent\]
*/
get isV26(): boolean {
return this._chain.getEventHash('Swaps.SwapExactAmountIn') === '3890c2f04c258eefbc9739d3d4bde06dfdbb1b5ce6ce3a1f2a3c45220d3db6d9'
}

/**
* An exact amount of an asset is entering the pool. \[SwapEvent\]
*/
get asV26(): v26.SwapEvent {
assert(this.isV26)
return this._chain.decodeEvent(this.event)
}

/**
* An exact amount of an asset is entering the pool. \[SwapEvent\]
*/
Expand Down Expand Up @@ -1458,7 +1533,7 @@ export class SwapsSwapExactAmountOutEvent {
* An exact amount of an asset is leaving the pool. \[SwapEvent\]
*/
get isV23(): boolean {
return this._chain.getEventHash('Swaps.SwapExactAmountOut') === '3890c2f04c258eefbc9739d3d4bde06dfdbb1b5ce6ce3a1f2a3c45220d3db6d9'
return this._chain.getEventHash('Swaps.SwapExactAmountOut') === '69d6a45c326b79e217d8cc5e5b3e79884d92a90749656b63c90a6fcc42de850c'
}

/**
Expand All @@ -1469,6 +1544,21 @@ export class SwapsSwapExactAmountOutEvent {
return this._chain.decodeEvent(this.event)
}

/**
* An exact amount of an asset is leaving the pool. \[SwapEvent\]
*/
get isV26(): boolean {
return this._chain.getEventHash('Swaps.SwapExactAmountOut') === '3890c2f04c258eefbc9739d3d4bde06dfdbb1b5ce6ce3a1f2a3c45220d3db6d9'
}

/**
* An exact amount of an asset is leaving the pool. \[SwapEvent\]
*/
get asV26(): v26.SwapEvent {
assert(this.isV26)
return this._chain.decodeEvent(this.event)
}

/**
* An exact amount of an asset is leaving the pool. \[SwapEvent\]
*/
Expand Down
3 changes: 0 additions & 3 deletions src/types/v23.ts
Expand Up @@ -70,7 +70,6 @@ export interface Pool {
}

export interface PoolAssetsEvent {
assets: Asset[]
bounds: bigint[]
cpep: CommonPoolEventParams
transferred: bigint[]
Expand All @@ -80,8 +79,6 @@ export interface SwapEvent {
assetAmountIn: bigint
assetAmountOut: bigint
assetBound: bigint
assetIn: Asset
assetOut: Asset
cpep: CommonPoolEventParams
maxPrice: bigint
}
Expand Down
58 changes: 58 additions & 0 deletions src/types/v26.ts
@@ -0,0 +1,58 @@
import type {Result} from './support'

export interface PoolAssetsEvent {
assets: Asset[]
bounds: bigint[]
cpep: CommonPoolEventParams
transferred: bigint[]
}

export interface SwapEvent {
assetAmountIn: bigint
assetAmountOut: bigint
assetBound: bigint
assetIn: Asset
assetOut: Asset
cpep: CommonPoolEventParams
maxPrice: bigint
}

export type Asset = Asset_CategoricalOutcome | Asset_ScalarOutcome | Asset_CombinatorialOutcome | Asset_PoolShare | Asset_Ztg

export interface Asset_CategoricalOutcome {
__kind: 'CategoricalOutcome'
value: [bigint, number]
}

export interface Asset_ScalarOutcome {
__kind: 'ScalarOutcome'
value: [bigint, ScalarPosition]
}

export interface Asset_CombinatorialOutcome {
__kind: 'CombinatorialOutcome'
}

export interface Asset_PoolShare {
__kind: 'PoolShare'
value: bigint
}

export interface Asset_Ztg {
__kind: 'Ztg'
}

export interface CommonPoolEventParams {
poolId: bigint
who: Uint8Array
}

export type ScalarPosition = ScalarPosition_Long | ScalarPosition_Short

export interface ScalarPosition_Long {
__kind: 'Long'
}

export interface ScalarPosition_Short {
__kind: 'Short'
}
3 changes: 2 additions & 1 deletion typegen.json
@@ -1,7 +1,7 @@
{
"outDir": "src/types",
"specVersions": "zeitgeistVersions.jsonl",
"typesBundle": "zeitgeist.json",
"typesBundle": "typesBundle.json",
"events": [
"Balances.BalanceSet",
"Balances.DustLost",
Expand All @@ -18,6 +18,7 @@
"PredictionMarkets.MarketApproved",
"PredictionMarkets.MarketClosed",
"PredictionMarkets.MarketCreated",
"PredictionMarkets.MarketDestroyed",
"PredictionMarkets.MarketDisputed",
"PredictionMarkets.MarketExpired",
"PredictionMarkets.MarketInsufficientSubsidy",
Expand Down

0 comments on commit fcf1f26

Please sign in to comment.