|
| 1 | +import { EndpointContext } from '@chainlink/external-adapter-framework/adapter' |
| 2 | +import { TransportDependencies } from '@chainlink/external-adapter-framework/transports' |
| 3 | +import { SubscriptionTransport } from '@chainlink/external-adapter-framework/transports/abstract/subscription' |
| 4 | +import { AdapterResponse, makeLogger, sleep } from '@chainlink/external-adapter-framework/util' |
| 5 | +import { |
| 6 | + AdapterError, |
| 7 | + AdapterInputError, |
| 8 | +} from '@chainlink/external-adapter-framework/validation/error' |
| 9 | +import { Commitment, Connection } from '@solana/web3.js' |
| 10 | +import { BaseEndpointTypes, inputParameters } from '../endpoint/solana' |
| 11 | +import { getTokenPrice } from './priceFeed' |
| 12 | +import { getToken } from './solana-utils' |
| 13 | + |
| 14 | +const logger = makeLogger('Token Balance - Solana') |
| 15 | + |
| 16 | +type RequestParams = typeof inputParameters.validated |
| 17 | + |
| 18 | +const RESULT_DECIMALS = 18 |
| 19 | + |
| 20 | +export class SolanaTransport extends SubscriptionTransport<BaseEndpointTypes> { |
| 21 | + connection!: Connection |
| 22 | + |
| 23 | + async initialize( |
| 24 | + dependencies: TransportDependencies<BaseEndpointTypes>, |
| 25 | + adapterSettings: BaseEndpointTypes['Settings'], |
| 26 | + endpointName: string, |
| 27 | + transportName: string, |
| 28 | + ): Promise<void> { |
| 29 | + await super.initialize(dependencies, adapterSettings, endpointName, transportName) |
| 30 | + |
| 31 | + if (!adapterSettings.SOLANA_RPC_URL) { |
| 32 | + logger.warn('SOLANA_RPC_URL is missing') |
| 33 | + } else { |
| 34 | + this.connection = new Connection( |
| 35 | + adapterSettings.SOLANA_RPC_URL, |
| 36 | + adapterSettings.SOLANA_COMMITMENT as Commitment, |
| 37 | + ) |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + async backgroundHandler(context: EndpointContext<BaseEndpointTypes>, entries: RequestParams[]) { |
| 42 | + await Promise.all(entries.map(async (param) => this.handleRequest(param))) |
| 43 | + await sleep(context.adapterSettings.BACKGROUND_EXECUTE_MS) |
| 44 | + } |
| 45 | + |
| 46 | + async handleRequest(param: RequestParams) { |
| 47 | + let response: AdapterResponse<BaseEndpointTypes['Response']> |
| 48 | + |
| 49 | + try { |
| 50 | + response = await this._handleRequest(param) |
| 51 | + } catch (e: unknown) { |
| 52 | + const errorMessage = e instanceof Error ? e.message : 'Unknown error occurred' |
| 53 | + logger.error(e, errorMessage) |
| 54 | + |
| 55 | + response = { |
| 56 | + statusCode: (e as AdapterInputError)?.statusCode || 502, |
| 57 | + errorMessage, |
| 58 | + timestamps: { |
| 59 | + providerDataRequestedUnixMs: 0, |
| 60 | + providerDataReceivedUnixMs: 0, |
| 61 | + providerIndicatedTimeUnixMs: undefined, |
| 62 | + }, |
| 63 | + } |
| 64 | + } |
| 65 | + await this.responseCache.write(this.name, [{ params: param, response }]) |
| 66 | + } |
| 67 | + |
| 68 | + async _handleRequest( |
| 69 | + param: RequestParams, |
| 70 | + ): Promise<AdapterResponse<BaseEndpointTypes['Response']>> { |
| 71 | + const { addresses, tokenMint } = param |
| 72 | + const providerDataRequestedUnixMs = Date.now() |
| 73 | + |
| 74 | + // 1. Fetch token price ONCE from oracle contract |
| 75 | + const tokenPrice = await getTokenPrice({ |
| 76 | + priceOracleAddress: param.priceOracle.contractAddress, |
| 77 | + priceOracleNetwork: param.priceOracle.network, |
| 78 | + }) |
| 79 | + |
| 80 | + // 2. Fetch balances for each Solana wallet and calculate their USD value using the SINGLE tokenPrice |
| 81 | + const totalTokenUSD = await this.calculateTokenAumUSD(addresses, tokenMint, tokenPrice) |
| 82 | + |
| 83 | + // 3. Build adapter response object |
| 84 | + return { |
| 85 | + data: { |
| 86 | + result: String(totalTokenUSD), // formatted as string for API |
| 87 | + decimals: RESULT_DECIMALS, |
| 88 | + }, |
| 89 | + statusCode: 200, |
| 90 | + result: String(totalTokenUSD), |
| 91 | + timestamps: { |
| 92 | + providerDataRequestedUnixMs, |
| 93 | + providerDataReceivedUnixMs: Date.now(), |
| 94 | + providerIndicatedTimeUnixMs: undefined, |
| 95 | + }, |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + async calculateTokenAumUSD( |
| 100 | + addresses: typeof inputParameters.validated.addresses, |
| 101 | + tokenMint: typeof inputParameters.validated.tokenMint, |
| 102 | + tokenPrice: { value: bigint; decimal: number }, |
| 103 | + ): Promise<bigint> { |
| 104 | + // 1. Transform new schema → getToken schema |
| 105 | + const addressesForGetToken = [ |
| 106 | + { |
| 107 | + token: tokenMint.token, |
| 108 | + contractAddress: tokenMint.contractAddress, |
| 109 | + wallets: addresses.map((a) => a.address), |
| 110 | + }, |
| 111 | + ] |
| 112 | + |
| 113 | + // 2. Fetch token balances for the given address on Solana |
| 114 | + const { result: balances } = await getToken( |
| 115 | + addressesForGetToken, |
| 116 | + tokenMint.token, |
| 117 | + this.connection, |
| 118 | + ) |
| 119 | + |
| 120 | + // 3. Sum raw balances (all balances are for the same mint, so same decimals) |
| 121 | + let totalRaw = 0n |
| 122 | + |
| 123 | + let tokenDecimals = undefined |
| 124 | + for (const bal of balances) { |
| 125 | + totalRaw += bal.value |
| 126 | + if (!bal.decimals) { |
| 127 | + throw new AdapterError({ |
| 128 | + statusCode: 400, |
| 129 | + message: 'Missing decimals on balance response', |
| 130 | + }) |
| 131 | + } |
| 132 | + if (tokenDecimals !== undefined && bal.decimals !== tokenDecimals) { |
| 133 | + throw new AdapterError({ |
| 134 | + statusCode: 400, |
| 135 | + message: `Inconsistent balance decimals: ${tokenDecimals} != ${bal.decimals}`, |
| 136 | + }) |
| 137 | + } |
| 138 | + tokenDecimals = bal.decimals |
| 139 | + } |
| 140 | + tokenDecimals ??= RESULT_DECIMALS |
| 141 | + |
| 142 | + // 4. Calculate AUM |
| 143 | + const totalAumUSD = |
| 144 | + (totalRaw * tokenPrice.value * 10n ** BigInt(RESULT_DECIMALS)) / |
| 145 | + 10n ** BigInt(tokenDecimals) / |
| 146 | + 10n ** BigInt(tokenPrice.decimal) |
| 147 | + |
| 148 | + // 5. Return total USD value for this address |
| 149 | + return totalAumUSD |
| 150 | + } |
| 151 | + |
| 152 | + getSubscriptionTtlFromConfig(adapterSettings: BaseEndpointTypes['Settings']): number { |
| 153 | + return adapterSettings.WARMUP_SUBSCRIPTION_TTL |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +export const solanaTransport = new SolanaTransport() |
0 commit comments