|
| 1 | +import { EndpointContext } from '@chainlink/external-adapter-framework/adapter' |
| 2 | +import { calculateHttpRequestKey } from '@chainlink/external-adapter-framework/cache' |
| 3 | +import { TransportDependencies } from '@chainlink/external-adapter-framework/transports' |
| 4 | +import { SubscriptionTransport } from '@chainlink/external-adapter-framework/transports/abstract/subscription' |
| 5 | +import { AdapterResponse, makeLogger, sleep } from '@chainlink/external-adapter-framework/util' |
| 6 | +import { GroupRunner } from '@chainlink/external-adapter-framework/util/group-runner' |
| 7 | +import { Requester } from '@chainlink/external-adapter-framework/util/requester' |
| 8 | +import { AdapterInputError } from '@chainlink/external-adapter-framework/validation/error' |
| 9 | +import { AddressWithBalance, BaseEndpointTypes, inputParameters } from '../endpoint/cardano' |
| 10 | +import { getCardanoRpcUrl } from './cardano-utils' |
| 11 | + |
| 12 | +const logger = makeLogger('Token Balance - Cardano') |
| 13 | + |
| 14 | +type RequestParams = typeof inputParameters.validated |
| 15 | + |
| 16 | +const RESULT_DECIMALS = 6 |
| 17 | + |
| 18 | +type AmountEntry = { |
| 19 | + unit: string |
| 20 | + quantity: number |
| 21 | +} |
| 22 | + |
| 23 | +export class CardanoTransport extends SubscriptionTransport<BaseEndpointTypes> { |
| 24 | + config!: BaseEndpointTypes['Settings'] |
| 25 | + endpointName!: string |
| 26 | + requester!: Requester |
| 27 | + |
| 28 | + async initialize( |
| 29 | + dependencies: TransportDependencies<BaseEndpointTypes>, |
| 30 | + adapterSettings: BaseEndpointTypes['Settings'], |
| 31 | + endpointName: string, |
| 32 | + transportName: string, |
| 33 | + ): Promise<void> { |
| 34 | + await super.initialize(dependencies, adapterSettings, endpointName, transportName) |
| 35 | + this.config = adapterSettings |
| 36 | + this.endpointName = endpointName |
| 37 | + this.requester = dependencies.requester |
| 38 | + } |
| 39 | + |
| 40 | + async backgroundHandler(context: EndpointContext<BaseEndpointTypes>, entries: RequestParams[]) { |
| 41 | + await Promise.all(entries.map(async (param) => this.handleRequest(context, param))) |
| 42 | + await sleep(context.adapterSettings.BACKGROUND_EXECUTE_MS) |
| 43 | + } |
| 44 | + |
| 45 | + async handleRequest(_context: EndpointContext<BaseEndpointTypes>, param: RequestParams) { |
| 46 | + let response: AdapterResponse<BaseEndpointTypes['Response']> |
| 47 | + try { |
| 48 | + response = await this._handleRequest(param) |
| 49 | + } catch (e: unknown) { |
| 50 | + const errorMessage = e instanceof Error ? e.message : 'Unknown error occurred' |
| 51 | + logger.error(e, errorMessage) |
| 52 | + response = { |
| 53 | + statusCode: (e as AdapterInputError)?.statusCode || 502, |
| 54 | + errorMessage, |
| 55 | + timestamps: { |
| 56 | + providerDataRequestedUnixMs: 0, |
| 57 | + providerDataReceivedUnixMs: 0, |
| 58 | + providerIndicatedTimeUnixMs: undefined, |
| 59 | + }, |
| 60 | + } |
| 61 | + } |
| 62 | + await this.responseCache.write(this.name, [{ params: param, response }]) |
| 63 | + } |
| 64 | + |
| 65 | + async _handleRequest( |
| 66 | + param: RequestParams, |
| 67 | + ): Promise<AdapterResponse<BaseEndpointTypes['Response']>> { |
| 68 | + const providerDataRequestedUnixMs = Date.now() |
| 69 | + const result = await this.getTokenBalances(param.addresses) |
| 70 | + |
| 71 | + return { |
| 72 | + data: { |
| 73 | + result, |
| 74 | + decimals: RESULT_DECIMALS, |
| 75 | + }, |
| 76 | + statusCode: 200, |
| 77 | + result: null, |
| 78 | + timestamps: { |
| 79 | + providerDataRequestedUnixMs, |
| 80 | + providerDataReceivedUnixMs: Date.now(), |
| 81 | + providerIndicatedTimeUnixMs: undefined, |
| 82 | + }, |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + async getTokenBalances( |
| 87 | + addresses: { |
| 88 | + address: string |
| 89 | + }[], |
| 90 | + ): Promise<AddressWithBalance[]> { |
| 91 | + const runner = new GroupRunner(this.config.GROUP_SIZE) |
| 92 | + const getBalance = runner.wrapFunction( |
| 93 | + async ({ address }: { address: string }): Promise<AddressWithBalance> => { |
| 94 | + const balance = await this.getTokenBalance(address) |
| 95 | + return { |
| 96 | + address, |
| 97 | + balance, |
| 98 | + } |
| 99 | + }, |
| 100 | + ) |
| 101 | + return await Promise.all(addresses.map(getBalance)) |
| 102 | + } |
| 103 | + |
| 104 | + async getTokenBalance(address: string): Promise<string> { |
| 105 | + const url = `/api/v1/addresses/${encodeURIComponent(address)}/amounts` |
| 106 | + const requestConfig = { |
| 107 | + method: 'GET' as const, |
| 108 | + baseURL: getCardanoRpcUrl(this.config), |
| 109 | + url, |
| 110 | + } |
| 111 | + |
| 112 | + const result = await this.requester.request<AmountEntry[]>( |
| 113 | + calculateHttpRequestKey<BaseEndpointTypes>({ |
| 114 | + context: { |
| 115 | + adapterSettings: this.config, |
| 116 | + inputParameters, |
| 117 | + endpointName: this.endpointName, |
| 118 | + }, |
| 119 | + data: { url }, |
| 120 | + transportName: this.name, |
| 121 | + }), |
| 122 | + requestConfig, |
| 123 | + ) |
| 124 | + |
| 125 | + const balance = result.response.data |
| 126 | + .filter((entry) => entry.unit === 'lovelace') |
| 127 | + .reduce((acc, entry) => acc + BigInt(entry.quantity), 0n) |
| 128 | + return balance.toString() |
| 129 | + } |
| 130 | + |
| 131 | + getSubscriptionTtlFromConfig(adapterSettings: BaseEndpointTypes['Settings']): number { |
| 132 | + return adapterSettings.WARMUP_SUBSCRIPTION_TTL |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +export const cardanoTransport = new CardanoTransport() |
0 commit comments