|
| 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 { AdapterError } from '@chainlink/external-adapter-framework/validation/error' |
| 9 | +import { BaseEndpointTypes, inputParameters } from '../endpoint/totalBalance' |
| 10 | + |
| 11 | +const logger = makeLogger('TotalBalanceTransport') |
| 12 | + |
| 13 | +type RequestParams = typeof inputParameters.validated |
| 14 | + |
| 15 | +export type GetBalanceResult = { |
| 16 | + balance: string |
| 17 | + unlocked: string |
| 18 | + lockedStakeable: string |
| 19 | + lockedNotStakeable: string |
| 20 | + balances: Record<string, string> |
| 21 | + unlockeds: Record<string, string> |
| 22 | + lockedStakeables: Record<string, string> |
| 23 | + lockedNotStakeables: Record<string, string> |
| 24 | + utxoIDs: { |
| 25 | + txID: string |
| 26 | + outputIndex: number |
| 27 | + }[] |
| 28 | +} |
| 29 | + |
| 30 | +export type GetStakeResult = { |
| 31 | + staked: string |
| 32 | + stakeds: Record<string, string> |
| 33 | + stakedOutputs: string[] |
| 34 | + encoding: string |
| 35 | +} |
| 36 | + |
| 37 | +type PlatformResponse<T> = { |
| 38 | + result: T |
| 39 | +} |
| 40 | + |
| 41 | +type BalanceResult = { |
| 42 | + address: string |
| 43 | + balance: string |
| 44 | + unlocked: string |
| 45 | + lockedStakeable: string |
| 46 | + lockedNotStakeable: string |
| 47 | + staked: string |
| 48 | +} |
| 49 | + |
| 50 | +const RESULT_DECIMALS = 18 |
| 51 | +const P_CHAIN_DECIMALS = 9 |
| 52 | + |
| 53 | +const scaleFactor = 10n ** BigInt(RESULT_DECIMALS - P_CHAIN_DECIMALS) |
| 54 | +const scale = (n: string) => (BigInt(n) * scaleFactor).toString() |
| 55 | + |
| 56 | +export class TotalBalanceTransport extends SubscriptionTransport<BaseEndpointTypes> { |
| 57 | + config!: BaseEndpointTypes['Settings'] |
| 58 | + endpointName!: string |
| 59 | + requester!: Requester |
| 60 | + |
| 61 | + async initialize( |
| 62 | + dependencies: TransportDependencies<BaseEndpointTypes>, |
| 63 | + adapterSettings: BaseEndpointTypes['Settings'], |
| 64 | + endpointName: string, |
| 65 | + transportName: string, |
| 66 | + ): Promise<void> { |
| 67 | + await super.initialize(dependencies, adapterSettings, endpointName, transportName) |
| 68 | + this.config = adapterSettings |
| 69 | + this.endpointName = endpointName |
| 70 | + this.requester = dependencies.requester |
| 71 | + } |
| 72 | + |
| 73 | + async backgroundHandler(context: EndpointContext<BaseEndpointTypes>, entries: RequestParams[]) { |
| 74 | + await Promise.all(entries.map(async (param) => this.handleRequest(param))) |
| 75 | + await sleep(context.adapterSettings.BACKGROUND_EXECUTE_MS) |
| 76 | + } |
| 77 | + |
| 78 | + async handleRequest(param: RequestParams) { |
| 79 | + let response: AdapterResponse<BaseEndpointTypes['Response']> |
| 80 | + try { |
| 81 | + response = await this._handleRequest(param) |
| 82 | + } catch (e) { |
| 83 | + const errorMessage = e instanceof Error ? e.message : 'Unknown error occurred' |
| 84 | + logger.error(e, errorMessage) |
| 85 | + response = { |
| 86 | + statusCode: (e as AdapterError)?.statusCode || 502, |
| 87 | + errorMessage, |
| 88 | + timestamps: { |
| 89 | + providerDataRequestedUnixMs: 0, |
| 90 | + providerDataReceivedUnixMs: 0, |
| 91 | + providerIndicatedTimeUnixMs: undefined, |
| 92 | + }, |
| 93 | + } |
| 94 | + } |
| 95 | + await this.responseCache.write(this.name, [{ params: param, response }]) |
| 96 | + } |
| 97 | + |
| 98 | + async _handleRequest( |
| 99 | + params: RequestParams, |
| 100 | + ): Promise<AdapterResponse<BaseEndpointTypes['Response']>> { |
| 101 | + const providerDataRequestedUnixMs = Date.now() |
| 102 | + |
| 103 | + const result = await this.getTotalBalances({ |
| 104 | + addresses: params.addresses, |
| 105 | + assetId: params.assetId, |
| 106 | + }) |
| 107 | + |
| 108 | + return { |
| 109 | + data: { |
| 110 | + result, |
| 111 | + decimals: RESULT_DECIMALS, |
| 112 | + }, |
| 113 | + statusCode: 200, |
| 114 | + result: null, |
| 115 | + timestamps: { |
| 116 | + providerDataRequestedUnixMs, |
| 117 | + providerDataReceivedUnixMs: Date.now(), |
| 118 | + providerIndicatedTimeUnixMs: undefined, |
| 119 | + }, |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + async getTotalBalances({ |
| 124 | + addresses, |
| 125 | + assetId, |
| 126 | + }: { |
| 127 | + addresses: { address: string }[] |
| 128 | + assetId: string |
| 129 | + }): Promise<BalanceResult[]> { |
| 130 | + const runner = new GroupRunner(this.config.GROUP_SIZE) |
| 131 | + |
| 132 | + const getBalance: (address: string) => Promise<GetBalanceResult> = runner.wrapFunction( |
| 133 | + (address: string) => |
| 134 | + this.callPlatformMethod({ |
| 135 | + method: 'getBalance', |
| 136 | + address, |
| 137 | + }), |
| 138 | + ) |
| 139 | + |
| 140 | + const getStake: (address: string) => Promise<GetStakeResult> = runner.wrapFunction( |
| 141 | + (address: string) => |
| 142 | + this.callPlatformMethod({ |
| 143 | + method: 'getStake', |
| 144 | + address, |
| 145 | + }), |
| 146 | + ) |
| 147 | + |
| 148 | + return await Promise.all( |
| 149 | + addresses.map(async ({ address }) => { |
| 150 | + const [balanceResult, stakedResult] = await Promise.all([ |
| 151 | + getBalance(address), |
| 152 | + getStake(address), |
| 153 | + ]) |
| 154 | + const unlocked = scale(balanceResult.unlockeds[assetId] ?? '0') |
| 155 | + const lockedStakeable = scale(balanceResult.lockedStakeables[assetId] ?? '0') |
| 156 | + const lockedNotStakeable = scale(balanceResult.lockedNotStakeables[assetId] ?? '0') |
| 157 | + const staked = scale(stakedResult.stakeds[assetId] ?? '0') |
| 158 | + const balance = [unlocked, lockedStakeable, lockedNotStakeable, staked] |
| 159 | + .reduce((a, b) => a + BigInt(b), 0n) |
| 160 | + .toString() |
| 161 | + return { |
| 162 | + address, |
| 163 | + balance, |
| 164 | + unlocked, |
| 165 | + lockedStakeable, |
| 166 | + lockedNotStakeable, |
| 167 | + staked, |
| 168 | + } |
| 169 | + }), |
| 170 | + ) |
| 171 | + } |
| 172 | + |
| 173 | + async callPlatformMethod<T>({ |
| 174 | + method, |
| 175 | + address, |
| 176 | + }: { |
| 177 | + method: string |
| 178 | + address: string |
| 179 | + }): Promise<T> { |
| 180 | + const requestConfig = { |
| 181 | + method: 'POST', |
| 182 | + baseURL: this.config.P_CHAIN_RPC_URL, |
| 183 | + data: { |
| 184 | + jsonrpc: '2.0', |
| 185 | + method: `platform.${method}`, |
| 186 | + params: { addresses: [address] }, |
| 187 | + id: '1', |
| 188 | + }, |
| 189 | + } |
| 190 | + |
| 191 | + const result = await this.requester.request<PlatformResponse<T>>( |
| 192 | + calculateHttpRequestKey<BaseEndpointTypes>({ |
| 193 | + context: { |
| 194 | + adapterSettings: this.config, |
| 195 | + inputParameters, |
| 196 | + endpointName: this.endpointName, |
| 197 | + }, |
| 198 | + data: requestConfig.data, |
| 199 | + transportName: this.name, |
| 200 | + }), |
| 201 | + requestConfig, |
| 202 | + ) |
| 203 | + |
| 204 | + return result.response.data.result |
| 205 | + } |
| 206 | + |
| 207 | + getSubscriptionTtlFromConfig(adapterSettings: BaseEndpointTypes['Settings']): number { |
| 208 | + return adapterSettings.WARMUP_SUBSCRIPTION_TTL |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +export const totalBalanceTransport = new TotalBalanceTransport() |
0 commit comments