Skip to content

DF-21310: Add coinmetrics-lwba adapter #3854

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/heavy-stingrays-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@chainlink/coinmetrics-lwba-adapter': major
---

Initial Release of the coinmetrics-lwba EA
22 changes: 22 additions & 0 deletions .pnp.cjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file.
3 changes: 3 additions & 0 deletions packages/sources/coinmetrics-lwba/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Chainlink External Adapter for coinmetrics-lwba

This README will be generated automatically when code is merged to `main`. If you would like to generate a preview of the README, please run `yarn generate:readme coinmetrics-lwba`.
42 changes: 42 additions & 0 deletions packages/sources/coinmetrics-lwba/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "@chainlink/coinmetrics-lwba-adapter",
"version": "0.0.0",
"description": "Chainlink coinmetrics-lwba adapter.",
"keywords": [
"Chainlink",
"LINK",
"blockchain",
"oracle",
"coinmetrics-lwba"
],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"repository": {
"url": "https://github.com/smartcontractkit/external-adapters-js",
"type": "git"
},
"license": "MIT",
"scripts": {
"clean": "rm -rf dist && rm -f tsconfig.tsbuildinfo",
"prepack": "yarn build",
"build": "tsc -b",
"server": "node -e 'require(\"./index.js\").server()'",
"server:dist": "node -e 'require(\"./dist/index.js\").server()'",
"start": "yarn server:dist"
},
"dependencies": {
"@chainlink/external-adapter-framework": "2.6.0",
"tslib": "2.4.1"
},
"devDependencies": {
"@sinonjs/fake-timers": "9.1.2",
"@types/jest": "^29.5.14",
"@types/node": "22.14.1",
"@types/sinonjs__fake-timers": "8.1.5",
"nock": "13.5.6",
"typescript": "5.8.3"
}
}
22 changes: 22 additions & 0 deletions packages/sources/coinmetrics-lwba/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Quote values are used to find a dynamic property in the DP response, in the form of ReferenceRate{quote}

import { AdapterConfig } from '@chainlink/external-adapter-framework/config'

export const config = new AdapterConfig({
API_KEY: {
description: 'The coinmetrics API key',
type: 'string',
required: true,
sensitive: true,
},
WS_API_ENDPOINT: {
description: 'The websocket url for coinmetrics',
type: 'string',
default: 'wss://api.coinmetrics.io/v4',
},
API_ENDPOINT: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this used ?

description: 'The API url for coinmetrics',
type: 'string',
default: 'https://api.coinmetrics.io/v4',
},
})
28 changes: 28 additions & 0 deletions packages/sources/coinmetrics-lwba/src/endpoint/crypto-lwba.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import {
LwbaEndpoint,
LwbaResponseDataFields,
lwbaEndpointInputParametersDefinition,
} from '@chainlink/external-adapter-framework/adapter'
import { InputParameters } from '@chainlink/external-adapter-framework/validation'
import { config } from '../config'
import { wsTransport } from '../transport/crypto-lwba'

export const inputParameters = new InputParameters(lwbaEndpointInputParametersDefinition, [
{
base: 'ETH',
quote: 'USD',
},
])

export type BaseEndpointTypes = {
Parameters: typeof inputParameters.definition
Settings: typeof config.settings
Response: LwbaResponseDataFields
}

export const endpoint = new LwbaEndpoint({
name: 'crypto-lwba',
aliases: ['crypto', 'price'],
transport: wsTransport,
inputParameters,
})
1 change: 1 addition & 0 deletions packages/sources/coinmetrics-lwba/src/endpoint/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { endpoint as cryptoLwba } from './crypto-lwba'
23 changes: 23 additions & 0 deletions packages/sources/coinmetrics-lwba/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { expose, ServerInstance } from '@chainlink/external-adapter-framework'
import { Adapter } from '@chainlink/external-adapter-framework/adapter'
import { config } from './config'
import { cryptoLwba } from './endpoint'

export const adapter = new Adapter({
defaultEndpoint: cryptoLwba.name,
name: 'COINMETRICS_LWBA',
config,
endpoints: [cryptoLwba],
rateLimiting: {
tiers: {
community: {
rateLimit1m: 100,
},
paid: {
rateLimit1s: 300,
},
},
},
})

export const server = (): Promise<ServerInstance | undefined> => expose(adapter)
124 changes: 124 additions & 0 deletions packages/sources/coinmetrics-lwba/src/transport/crypto-lwba.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { EndpointContext } from '@chainlink/external-adapter-framework/adapter'
import { WebSocketTransport } from '@chainlink/external-adapter-framework/transports/websocket'
import {
makeLogger,
PartialAdapterResponse,
ProviderResult,
ProviderResultGenerics,
} from '@chainlink/external-adapter-framework/util'
import { TypeFromDefinition } from '@chainlink/external-adapter-framework/validation/input-params'
import { BaseEndpointTypes, inputParameters } from '../endpoint/crypto-lwba'
import { logPossibleSolutionForKnownErrors } from './error-handling'
import { ResponseError } from './types'

const logger = makeLogger('CoinMetrics Crypto LWBA WS')

export type MultiVarResult<T extends ProviderResultGenerics> = {
params: TypeFromDefinition<T['Parameters']>
response: PartialAdapterResponse<T['Response']>
}

export type WsCryptoLwbaSuccessResponse = {
pair: string
time: string
ask_price: string
ask_size: string
bid_price: string
bid_size: string
mid_price: string
spread: string
cm_sequence_id: string
}
export type WsCryptoLwbaErrorResponse = {
error: ResponseError
}
export type WsCryptoLwbaWarningResponse = {
warning: {
type: string
message: string
}
}
export type WsCryptoLwbaReorgResponse = {
time: string
asset: string
height: number
hash: string
parent_hash: string
type: 'reorg'
cm_sequence_id: number
}

export type WsPairQuoteMessage =
| WsCryptoLwbaSuccessResponse
| WsCryptoLwbaWarningResponse
| WsCryptoLwbaErrorResponse
| WsCryptoLwbaReorgResponse

export type WsTransportTypes = BaseEndpointTypes & {
Provider: {
WsMessage: WsPairQuoteMessage
}
}
export const calculateUrl = (
context: EndpointContext<WsTransportTypes>,
desiredSubs: (typeof inputParameters.validated)[],
): string => {
const { API_KEY, WS_API_ENDPOINT } = context.adapterSettings

const generated = new URL('/v4/timeseries-stream/asset-quotes', WS_API_ENDPOINT)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should /v4/timeseries-stream/asset-quotes be part of WS_API_ENDPOINT?

const assets = [...new Set(desiredSubs.map((pair) => pair.base.toLowerCase()))].sort().join(',')
generated.searchParams.append('assets', assets)

generated.searchParams.append('api_key', API_KEY)
logger.debug(`Generated URL: ${generated.toString()}`)
return generated.toString()
}

export const handleCryptoLwbaMessage = (
message: WsPairQuoteMessage,
): MultiVarResult<WsTransportTypes>[] | undefined => {
if ('error' in message) {
logger.error(message, `Error response from websocket`)
logPossibleSolutionForKnownErrors(message.error)
} else if ('warning' in message) {
logger.warn(message, `Warning response from websocket`)
} else if ('type' in message && message.type === 'reorg') {
logger.info(message, `Reorg response from websocket`)
} else if ('mid_price' in message) {
const [base, quote] = message.pair.split('-')
const res = Number(message.mid_price)
return [
{
params: {
base,
quote,
},
response: {
result: null,
data: {
bid: Number(message.bid_price),
mid: res,
ask: Number(message.ask_price),
},
timestamps: {
providerIndicatedTimeUnixMs: new Date(message.time).getTime(),
},
},
},
]
} else {
logger.warn(message, 'Unknown message type from websocket')
}
return undefined
}

export const wsTransport = new WebSocketTransport<WsTransportTypes>({
url: (context, desiredSubs) => {
return calculateUrl(context, desiredSubs)
},
handlers: {
message(message: WsPairQuoteMessage): ProviderResult<WsTransportTypes>[] | undefined {
return handleCryptoLwbaMessage(message)
},
},
})
21 changes: 21 additions & 0 deletions packages/sources/coinmetrics-lwba/src/transport/error-handling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { makeLogger } from '@chainlink/external-adapter-framework/util'
import { ResponseError } from './types'

const logger = makeLogger('CoinMetrics Crypto error handling')

export const logPossibleSolutionForKnownErrors = (error: ResponseError) => {
if (error['type'] === 'wrong_credentials') {
logger.error(`There is something wrong with your credentials.
Possible Solution:
1. Doublecheck your supplied credentials.
2. Contact Data Provider to ensure your subscription is active
3. If credentials are supplied under the node licensing agreement with Chainlink Labs, please make contact with us and we will look into it.`)
}

if (error['type'] === 'bad_parameter') {
logger.error(`This error indicates that the supplied asset or metric parameter is incorrect.
Possible Solution:
1. Confirm you are using the same symbol found in the job spec with the correct case.
2. There maybe an issue with the job spec or the Data Provider may have delisted the asset. Reach out to Chainlink Labs.`)
}
}
4 changes: 4 additions & 0 deletions packages/sources/coinmetrics-lwba/src/transport/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type ResponseError = {
type: string
message: string
}
9 changes: 9 additions & 0 deletions packages/sources/coinmetrics-lwba/test-payload.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"requests": [
{
"from": "ETH",
"to": "USD",
"endpoint": "crypto-lwba"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`websocket lwba endpoint should return error (invariant violation) 1`] = `
{
"error": {
"message": "Invariant violation. Mid price must be between bid and ask prices. Got: (bid: 1562.3384315992228, mid: 1562.3733948803842, ask: 1562.2733948803843)",
"name": "AdapterLWBAError",
},
"status": "errored",
"statusCode": 500,
}
`;

exports[`websocket lwba endpoint should return success 1`] = `
{
"data": {
"ask": 1562.4083581615457,
"bid": 1562.3384315992228,
"mid": 1562.3733948803842,
},
"result": null,
"statusCode": 200,
"timestamps": {
"providerDataReceivedUnixMs": 1024,
"providerDataStreamEstablishedUnixMs": 1010,
"providerIndicatedTimeUnixMs": 1678248273750,
},
}
`;
Loading
Loading