-
Notifications
You must be signed in to change notification settings - Fork 263
Add solana-balance endpoint to token-balance EA #4020
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
Merged
Merged
Changes from 8 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
2b36bda
Copy xrp
dskloetc faf6184
Add solana-balance endpoint to token-balance
dskloetc e2cb190
Copy solana integration test
dskloetc 5a449a5
Solana balance integration test
dskloetc fb03784
Copy xrp unit test
dskloetc 53607c8
Solana-balance unit test
dskloetc 0c4b5ab
changeset
dskloetc 07ced67
Merge branch 'main' into kloet/solana-balance
app-token-issuer-data-feeds[bot] 22abcf0
this.getConnection()
dskloetc 9c273bb
Merge branch 'main' into kloet/solana-balance
dskloetc 56a0366
Merge branch 'main' into kloet/solana-balance
app-token-issuer-data-feeds[bot] 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 hidden or 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,5 @@ | ||
| --- | ||
| '@chainlink/token-balance-adapter': minor | ||
| --- | ||
|
|
||
| Add solana-balance endpoint |
This file contains hidden or 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
59 changes: 59 additions & 0 deletions
59
packages/sources/token-balance/src/endpoint/solana-balance.ts
This file contains hidden or 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,59 @@ | ||
| import { AdapterEndpoint } from '@chainlink/external-adapter-framework/adapter' | ||
| import { InputParameters } from '@chainlink/external-adapter-framework/validation' | ||
| import { AdapterError } from '@chainlink/external-adapter-framework/validation/error' | ||
| import { config } from '../config' | ||
| import { solanaBalanceTransport } from '../transport/solana-balance' | ||
| import { getSolanaRpcUrl } from '../transport/solana-utils' | ||
|
|
||
| export const inputParameters = new InputParameters( | ||
| { | ||
| addresses: { | ||
| required: true, | ||
| type: { | ||
| address: { | ||
| required: true, | ||
| type: 'string', | ||
| description: 'Address of the account to fetch the balance of', | ||
| }, | ||
| }, | ||
| array: true, | ||
| description: 'List of addresses to read', | ||
| }, | ||
| }, | ||
| [ | ||
| { | ||
| addresses: [ | ||
| { | ||
| address: '7d73NFxuWQ2F248NA4XwxE95oFfbWZrc1sg4wcDJjzTq', | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| ) | ||
|
|
||
| export type AddressWithBalance = { | ||
| address: string | ||
| balance: string | ||
| } | ||
|
|
||
| export type BaseEndpointTypes = { | ||
| Parameters: typeof inputParameters.definition | ||
| Response: { | ||
| Result: null | ||
| Data: { | ||
| result: AddressWithBalance[] | ||
| decimals: number | ||
| } | ||
| } | ||
| Settings: typeof config.settings | ||
| } | ||
|
|
||
| export const endpoint = new AdapterEndpoint({ | ||
| name: 'solana-balance', | ||
| transport: solanaBalanceTransport, | ||
| inputParameters, | ||
| customInputValidation: (_request, settings): AdapterError | undefined => { | ||
| getSolanaRpcUrl(settings) | ||
| return | ||
| }, | ||
| }) |
This file contains hidden or 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 |
|---|---|---|
| @@ -1,13 +1,13 @@ | ||
| import { expose, ServerInstance } from '@chainlink/external-adapter-framework' | ||
| import { Adapter } from '@chainlink/external-adapter-framework/adapter' | ||
| import { config } from './config' | ||
| import { etherFi, evm, solana, solvJlp, tbill, xrp, xrpl } from './endpoint' | ||
| import { etherFi, evm, solana, solanaBalance, solvJlp, tbill, xrp, xrpl } from './endpoint' | ||
|
|
||
| export const adapter = new Adapter({ | ||
| defaultEndpoint: evm.name, | ||
| name: 'TOKEN_BALANCE', | ||
| config, | ||
| endpoints: [evm, solvJlp, etherFi, tbill, xrp, xrpl, solana], | ||
| endpoints: [evm, solvJlp, etherFi, tbill, xrp, xrpl, solana, solanaBalance], | ||
| }) | ||
|
|
||
| export const server = (): Promise<ServerInstance | undefined> => expose(adapter) |
122 changes: 122 additions & 0 deletions
122
packages/sources/token-balance/src/transport/solana-balance.ts
This file contains hidden or 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,122 @@ | ||
| import { EndpointContext } from '@chainlink/external-adapter-framework/adapter' | ||
| import { TransportDependencies } from '@chainlink/external-adapter-framework/transports' | ||
| import { SubscriptionTransport } from '@chainlink/external-adapter-framework/transports/abstract/subscription' | ||
| import { AdapterResponse, makeLogger, sleep } from '@chainlink/external-adapter-framework/util' | ||
| import { GroupRunner } from '@chainlink/external-adapter-framework/util/group-runner' | ||
| import { AdapterInputError } from '@chainlink/external-adapter-framework/validation/error' | ||
| import { Commitment, Connection, PublicKey } from '@solana/web3.js' | ||
| import { AddressWithBalance, BaseEndpointTypes, inputParameters } from '../endpoint/solana-balance' | ||
| import { getSolanaRpcUrl } from './solana-utils' | ||
|
|
||
| const logger = makeLogger('Token Balance - Salana Balance') | ||
|
|
||
| type RequestParams = typeof inputParameters.validated | ||
|
|
||
| const RESULT_DECIMALS = 9 | ||
|
|
||
| export class SolanaBalanceTransport extends SubscriptionTransport<BaseEndpointTypes> { | ||
| config!: BaseEndpointTypes['Settings'] | ||
| connection!: Connection | ||
|
|
||
| async initialize( | ||
| dependencies: TransportDependencies<BaseEndpointTypes>, | ||
| adapterSettings: BaseEndpointTypes['Settings'], | ||
| endpointName: string, | ||
| transportName: string, | ||
| ): Promise<void> { | ||
| await super.initialize(dependencies, adapterSettings, endpointName, transportName) | ||
| this.config = adapterSettings | ||
| if (!adapterSettings.SOLANA_RPC_URL) { | ||
| logger.warn('SOLANA_RPC_URL is missing') | ||
| } else { | ||
| this.connection = new Connection( | ||
| getSolanaRpcUrl(adapterSettings), | ||
| adapterSettings.SOLANA_COMMITMENT as Commitment, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| async backgroundHandler(context: EndpointContext<BaseEndpointTypes>, entries: RequestParams[]) { | ||
| await Promise.all(entries.map(async (param) => this.handleRequest(context, param))) | ||
| await sleep(context.adapterSettings.BACKGROUND_EXECUTE_MS) | ||
| } | ||
|
|
||
| async handleRequest(_context: EndpointContext<BaseEndpointTypes>, param: RequestParams) { | ||
| let response: AdapterResponse<BaseEndpointTypes['Response']> | ||
| try { | ||
| response = await this._handleRequest(param) | ||
| } catch (e: unknown) { | ||
| const errorMessage = e instanceof Error ? e.message : 'Unknown error occurred' | ||
| logger.error(e, errorMessage) | ||
| response = { | ||
| statusCode: (e as AdapterInputError)?.statusCode || 502, | ||
| errorMessage, | ||
| timestamps: { | ||
| providerDataRequestedUnixMs: 0, | ||
| providerDataReceivedUnixMs: 0, | ||
| providerIndicatedTimeUnixMs: undefined, | ||
| }, | ||
| } | ||
| } | ||
| await this.responseCache.write(this.name, [{ params: param, response }]) | ||
| } | ||
|
|
||
| async _handleRequest( | ||
| param: RequestParams, | ||
| ): Promise<AdapterResponse<BaseEndpointTypes['Response']>> { | ||
| const providerDataRequestedUnixMs = Date.now() | ||
| const result = await this.getTokenBalances(param.addresses) | ||
|
|
||
| return { | ||
| data: { | ||
| result, | ||
| decimals: RESULT_DECIMALS, | ||
| }, | ||
| statusCode: 200, | ||
| result: null, | ||
| timestamps: { | ||
| providerDataRequestedUnixMs, | ||
| providerDataReceivedUnixMs: Date.now(), | ||
| providerIndicatedTimeUnixMs: undefined, | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| async getTokenBalances( | ||
| addresses: { | ||
| address: string | ||
| }[], | ||
| ): Promise<AddressWithBalance[]> { | ||
| const runner = new GroupRunner(this.config.GROUP_SIZE) | ||
| const getBalance = runner.wrapFunction( | ||
| async ({ address }: { address: string }): Promise<AddressWithBalance> => { | ||
| const balance = await this.getTokenBalance(address) | ||
| return { | ||
| address, | ||
| balance: balance.toString(), | ||
| } | ||
| }, | ||
| ) | ||
| return await Promise.all(addresses.map(getBalance)) | ||
| } | ||
|
|
||
| async getTokenBalance(address: string): Promise<number> { | ||
| // getSolanaRpcUrl throws if the RPC URL is missing, in which case | ||
| // this.connection would not be initialized. | ||
| getSolanaRpcUrl(this.config) | ||
| const result = await this.connection.getAccountInfo(new PublicKey(address)) | ||
| if (!result) { | ||
| throw new AdapterInputError({ | ||
| statusCode: 400, | ||
| message: `Account not found for address ${address}`, | ||
| }) | ||
| } | ||
| return result.lamports | ||
| } | ||
|
|
||
| getSubscriptionTtlFromConfig(adapterSettings: BaseEndpointTypes['Settings']): number { | ||
| return adapterSettings.WARMUP_SUBSCRIPTION_TTL | ||
| } | ||
| } | ||
|
|
||
| export const solanaBalanceTransport = new SolanaBalanceTransport() | ||
This file contains hidden or 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
21 changes: 21 additions & 0 deletions
21
packages/sources/token-balance/test/integration/__snapshots__/solana-balance.test.ts.snap
This file contains hidden or 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,21 @@ | ||
| // Jest Snapshot v1, https://goo.gl/fbAQLP | ||
|
|
||
| exports[`execute SolanaBalanceTransport endpoint returns success 1`] = ` | ||
| { | ||
| "data": { | ||
| "decimals": 9, | ||
| "result": [ | ||
| { | ||
| "address": "G7v3P9yPtBj1e3JN7B6dq4zbkrrW3e2ovdwAkSTKuUFG", | ||
| "balance": "123000000000", | ||
| }, | ||
| ], | ||
| }, | ||
| "result": null, | ||
| "statusCode": 200, | ||
| "timestamps": { | ||
| "providerDataReceivedUnixMs": 978347471111, | ||
| "providerDataRequestedUnixMs": 978347471111, | ||
| }, | ||
| } | ||
| `; |
71 changes: 71 additions & 0 deletions
71
packages/sources/token-balance/test/integration/solana-balance.test.ts
This file contains hidden or 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,71 @@ | ||
| import { | ||
| TestAdapter, | ||
| setEnvVariables, | ||
| } from '@chainlink/external-adapter-framework/util/testing-utils' | ||
| import { PublicKey } from '@solana/web3.js' | ||
| import * as nock from 'nock' | ||
|
|
||
| const accountBalance = 123_000_000_000 | ||
| const ownerAddress = 'G7v3P9yPtBj1e3JN7B6dq4zbkrrW3e2ovdwAkSTKuUFG' | ||
|
|
||
| jest.mock('@solana/web3.js', () => ({ | ||
| PublicKey: function (): PublicKey { | ||
| return {} as PublicKey | ||
| }, | ||
| Connection: class { | ||
| async getAccountInfo() { | ||
| return { | ||
| lamports: accountBalance, | ||
| } | ||
| } | ||
| }, | ||
| })) | ||
|
|
||
| describe('execute', () => { | ||
| let spy: jest.SpyInstance | ||
| let testAdapter: TestAdapter | ||
| let oldEnv: NodeJS.ProcessEnv | ||
|
|
||
| beforeAll(async () => { | ||
| oldEnv = JSON.parse(JSON.stringify(process.env)) | ||
| process.env.SOLANA_RPC_URL = process.env.SOLANA_RPC_URL ?? 'http://mock-solana' | ||
| process.env.BACKGROUND_EXECUTE_MS = '0' | ||
|
|
||
| const mockDate = new Date('2001-01-01T11:11:11.111Z') | ||
| spy = jest.spyOn(Date, 'now').mockReturnValue(mockDate.getTime()) | ||
|
|
||
| const adapter = (await import('./../../src')).adapter | ||
| adapter.rateLimiting = undefined | ||
|
|
||
| testAdapter = await TestAdapter.startWithMockedCache(adapter, { | ||
| testAdapter: {} as TestAdapter<never>, | ||
| }) | ||
| }) | ||
|
|
||
| afterAll(async () => { | ||
| setEnvVariables(oldEnv) | ||
| await testAdapter.api.close() | ||
| nock.restore() | ||
| nock.cleanAll() | ||
| spy.mockRestore() | ||
| }) | ||
|
|
||
| describe('SolanaBalanceTransport endpoint', () => { | ||
| it('returns success', async () => { | ||
| const data = { | ||
| endpoint: 'solana-balance', | ||
| addresses: [ | ||
| { | ||
| address: ownerAddress, | ||
| }, | ||
| ], | ||
| } | ||
|
|
||
| const response = await testAdapter.request(data) | ||
| console.log('DEBUG response:', response.json()) // helpful if it fails | ||
|
|
||
| expect(response.statusCode).toBe(200) | ||
| expect(response.json()).toMatchSnapshot() | ||
| }) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.