-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Display recent executions #222
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { GET } from '@/shared/api/server/recent-executions'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
import { useQuery } from '@tanstack/react-query'; | ||
import { useRefetchOnNewBlock } from '@/shared/api/compact-block.ts'; | ||
import { usePathSymbols } from '@/pages/trade/model/use-path.ts'; | ||
import { apiFetch } from '@/shared/utils/api-fetch.ts'; | ||
import { RecentExecution } from '@/shared/api/server/recent-executions.ts'; | ||
import { registryQueryFn } from '@/shared/api/registry.ts'; | ||
import { Registry } from '@penumbra-labs/registry'; | ||
import { formatAmount } from '@penumbra-zone/types/amount'; | ||
import { getDisplayDenomExponent } from '@penumbra-zone/getters/metadata'; | ||
import { calculateDisplayPrice } from '@/shared/utils/price-conversion.ts'; | ||
import BigNumber from 'bignumber.js'; | ||
|
||
export interface RecentExecutionVV { | ||
kind: 'buy' | 'sell'; | ||
amount: string; | ||
price: string; | ||
timestamp: string; | ||
} | ||
|
||
const addVV = (res: RecentExecution[], registry: Registry): RecentExecutionVV[] => { | ||
return res.map(r => { | ||
if (!r.amount.assetId || !r.amount.amount) { | ||
throw new Error('No asseId or Amount passed for recent execution'); | ||
} | ||
const baseMetadata = registry.getMetadata(r.amount.assetId); | ||
const baseDisplayDenomExponent = getDisplayDenomExponent.optional(baseMetadata) ?? 0; | ||
|
||
const quoteMetadata = registry.getMetadata(r.price.assetId); | ||
const price = calculateDisplayPrice(r.price.amount, baseMetadata, quoteMetadata); | ||
|
||
return { | ||
kind: r.kind, | ||
amount: formatAmount({ | ||
amount: r.amount.amount, | ||
exponent: baseDisplayDenomExponent, | ||
decimalPlaces: 4, | ||
}), | ||
price: new BigNumber(price).toFormat(4), | ||
timestamp: r.timestamp, | ||
}; | ||
}); | ||
}; | ||
|
||
const LIMIT = 10; | ||
|
||
export const useRecentExecutions = () => { | ||
const { baseSymbol, quoteSymbol } = usePathSymbols(); | ||
|
||
const query = useQuery({ | ||
queryKey: ['recent-executions', baseSymbol, quoteSymbol], | ||
queryFn: async () => { | ||
const results = await apiFetch<RecentExecution[]>('/api/recent-executions', { | ||
baseAsset: baseSymbol, | ||
quoteAsset: quoteSymbol, | ||
limit: String(LIMIT), | ||
}); | ||
|
||
const registry = await registryQueryFn(); | ||
|
||
return addVV(results, registry); | ||
}, | ||
}); | ||
|
||
useRefetchOnNewBlock('recent-executions', query); | ||
|
||
return query; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
import { NextRequest, NextResponse } from 'next/server'; | ||
import { pindexer } from '@/shared/database'; | ||
import { ChainRegistryClient } from '@penumbra-labs/registry'; | ||
import { serialize, Serialized } from '@/shared/utils/serializer'; | ||
import { AssetId, Value } from '@penumbra-zone/protobuf/penumbra/core/asset/v1/asset_pb'; | ||
import { pnum } from '@penumbra-zone/types/pnum'; | ||
|
||
const transformDbVal = ({ | ||
context_asset_end, | ||
context_asset_start, | ||
delta_1, | ||
delta_2, | ||
lambda_1, | ||
lambda_2, | ||
time, | ||
}: { | ||
context_asset_end: Buffer; | ||
context_asset_start: Buffer; | ||
delta_1: string; | ||
delta_2: string; | ||
lambda_1: string; | ||
lambda_2: string; | ||
time: Date; | ||
}): RecentExecution => { | ||
const baseAssetId = new AssetId({ | ||
inner: Uint8Array.from(context_asset_start), | ||
}); | ||
const quoteAssetId = new AssetId({ inner: Uint8Array.from(context_asset_end) }); | ||
|
||
// Determine trade direction | ||
const isBaseAssetInput = BigInt(delta_1) !== 0n; | ||
const kind = isBaseAssetInput ? 'sell' : 'buy'; | ||
|
||
// Amount of base & quote asset being traded in or out of | ||
const baseAmount = isBaseAssetInput ? pnum(delta_1) : pnum(lambda_1); | ||
const quoteAmount = isBaseAssetInput ? pnum(lambda_2) : pnum(delta_2); | ||
|
||
const price = baseAmount.toBigNumber().div(quoteAmount.toBigNumber()).toNumber(); | ||
const timestamp = time.toISOString(); | ||
|
||
return { | ||
kind, | ||
amount: new Value({ amount: baseAmount.toAmount(), assetId: baseAssetId }), | ||
price: { amount: price, assetId: quoteAssetId }, | ||
timestamp, | ||
}; | ||
}; | ||
|
||
export type RecentExecutionsResponse = RecentExecution[] | { error: string }; | ||
|
||
interface FloatValue { | ||
assetId: AssetId; | ||
amount: number; | ||
} | ||
|
||
export interface RecentExecution { | ||
kind: 'buy' | 'sell'; | ||
amount: Value; | ||
price: FloatValue; | ||
timestamp: string; | ||
} | ||
|
||
export async function GET( | ||
req: NextRequest, | ||
): Promise<NextResponse<Serialized<RecentExecutionsResponse>>> { | ||
const chainId = process.env['PENUMBRA_CHAIN_ID']; | ||
if (!chainId) { | ||
return NextResponse.json({ error: 'PENUMBRA_CHAIN_ID is not set' }, { status: 500 }); | ||
} | ||
|
||
const { searchParams } = new URL(req.url); | ||
const baseAssetSymbol = searchParams.get('baseAsset'); | ||
const quoteAssetSymbol = searchParams.get('quoteAsset'); | ||
const limit = searchParams.get('limit'); | ||
if (!baseAssetSymbol || !quoteAssetSymbol || !limit) { | ||
return NextResponse.json( | ||
{ error: 'Missing required baseAsset, quoteAsset, or limit' }, | ||
{ status: 400 }, | ||
); | ||
} | ||
|
||
const registryClient = new ChainRegistryClient(); | ||
const registry = await registryClient.remote.get(chainId); | ||
|
||
// TODO: Add getMetadataBySymbol() helper to registry npm package | ||
const allAssets = registry.getAllAssets(); | ||
const baseAssetMetadata = allAssets.find( | ||
a => a.symbol.toLowerCase() === baseAssetSymbol.toLowerCase(), | ||
); | ||
const quoteAssetMetadata = allAssets.find( | ||
a => a.symbol.toLowerCase() === quoteAssetSymbol.toLowerCase(), | ||
); | ||
if (!baseAssetMetadata?.penumbraAssetId || !quoteAssetMetadata?.penumbraAssetId) { | ||
return NextResponse.json( | ||
{ error: `Base asset or quoteAsset assetId not found in registry` }, | ||
{ status: 400 }, | ||
); | ||
} | ||
|
||
const results = await pindexer.recentExecutions( | ||
baseAssetMetadata.penumbraAssetId, | ||
quoteAssetMetadata.penumbraAssetId, | ||
Number(limit), | ||
); | ||
|
||
const response = results.map(transformDbVal); | ||
|
||
return NextResponse.json(serialize(response)); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This math is very off currently. Need to sync with @erwanor in office hours 😅 .