prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import { FetchAdapter } from 'requete/adapter' import { RequestError } from 'requete/shared' import { toAny } from 'test/utils' import { Requete } from '../Requete' describe('Requete exceptions specs', () => { beforeEach(() => { vi.spyOn(FetchAdapter.prototype, 'request').mockImplementation( vi.fn().mockResolvedValue({ ok: true, status: 200, statusText: 'OK', url: '/do-mock', data: 'null', }) ) // disable console.error vi.spyOn(global.console, 'error').mockImplementation(toAny(vi.fn())) }) it('should caught RequestError when response`s status != 200', async () => { vi.spyOn(FetchAdapter.prototype, 'request').mockImplementation( vi.fn().mockResolvedValue({ ok: false, status: 500, statusText: 'Internal Server Error', url: '/do-mock', data: 'null', }) ) const requete = new Requete() await expect(requete.get('https:api.com/do-mock')).rejects.toThrow( RequestError ) await expect(requete.get('/do-mock')).rejects.toThrow( 'GET /do-mock 500 (Internal Server Error)' ) }) it('should caught RequestError when middleware throws', async () => {
const requete = new Requete().use(async (ctx, next) => {
if (ctx.request.method === 'GET') throw new Error('not allowed') await next() if (ctx.request.method === 'POST') throw new Error('post error') }) await expect(requete.get('/do-mock')).rejects.toThrow(RequestError) await expect(requete.get('/do-mock')).rejects.toThrow('not allowed') await expect(requete.post('/do-mock')).rejects.toThrow(RequestError) await expect(requete.post('/do-mock')).rejects.toThrow('post error') }) it('should caught when call ctx funcs in wrong way', async () => { // ctx.abort() await expect( new Requete() .use(async (ctx, next) => { await next() ctx.abort() }) .get('/do-mock') ).rejects.toThrow('Cannot set abortSignal after next().') // ctx.set() await expect( new Requete() .use(async (ctx, next) => { await next() ctx.set('a', 'b') }) .get('/do-mock') ).rejects.toThrow('Cannot set request headers after next().') }) it('should caught when request aborted', async () => { vi.spyOn(FetchAdapter.prototype, 'request').mockImplementation( async (ctx) => { const abort = ctx.abort() if (abort.signal.aborted) { throw new Error(abort.signal.reason) } return toAny({ ok: false, status: 500, statusText: 'Internal Server Error', url: '/do-mock', data: 'null', }) } ) const requete = new Requete().use(async (ctx, next) => { ctx.abort().abort('abort request') await next() }) await expect(requete.get('/do-mock', { timeout: 1000 })).rejects.toThrow( 'abort request' ) }) it('should caught RequestError when parse body with throws', async () => { vi.spyOn(FetchAdapter.prototype, 'request').mockImplementation( vi.fn().mockResolvedValue({ ok: true, status: 200, statusText: 'OK', url: '/do-mock', data: 'bad', }) ) const requete = new Requete() await expect(requete.get('/do-mock')).rejects.toThrow(RequestError) await expect(requete.get('/do-mock')).rejects.toThrow(/Unexpected token/) }) })
src/core/__tests__/requete-exceptions.test.ts
rexerwang-requete-e7d4979
[ { "filename": "src/core/__tests__/requete-middleware.test.ts", "retrieved_chunk": " await next()\n })\n await expect(requete.post('/do-mock')).rejects.toThrow(\n 'next() called multiple times'\n )\n })\n it('should set request header correctly in middleware', async () => {\n const requete = new Requete()\n requete.use(async (ctx, next) => {\n ctx.set('Authorization', 'mock')", "score": 64.02205079893966 }, { "filename": "src/core/__tests__/requete-request.test.ts", "retrieved_chunk": " )\n it('should make a request with correct url', async () => {\n const requete = new Requete({ baseURL: 'https://api.mock.com/api/v1/' })\n let ctx = await requete.post('https://api.mock.com/api/v2/do-mock?id=1')\n expect(ctx.request.url).toBe('https://api.mock.com/api/v2/do-mock?id=1')\n ctx = await requete.get('do-mock?id=1', { params: { id: '2' } })\n expect(ctx.request.url).toBe(\n 'https://api.mock.com/api/v1/do-mock?id=1&id=2'\n )\n ctx = await requete.get('do-mock', { params: 'id=2' })", "score": 55.925127514166455 }, { "filename": "src/core/__tests__/requete-middleware.test.ts", "retrieved_chunk": " expect(res.request.url).toBe('/do-mock?a=1&b=2')\n })\n it('should set abortSignal correctly in middleware', async () => {\n const requete = new Requete()\n let controller: any\n requete.use(async (ctx, next) => {\n controller = ctx.abort()\n await next()\n })\n const res = await requete.post('/do-mock', undefined)", "score": 50.66627725708636 }, { "filename": "src/core/__tests__/requete-middleware.test.ts", "retrieved_chunk": " })\n )\n })\n it('should set params correctly in middleware', async () => {\n const requete = new Requete()\n requete.use(async (ctx, next) => {\n ctx.params({ a: 1, b: 2 })\n await next()\n })\n const res = await requete.post('/do-mock', { params: { b: 1 } })", "score": 49.82524649012799 }, { "filename": "src/core/__tests__/requete-middleware.test.ts", "retrieved_chunk": " expect(res.request.abort).toEqual(controller)\n })\n it('should replay the request in middleware', async () => {\n const requete = new Requete()\n requete.use(async (ctx, next) => {\n await next()\n if (!ctx.request.custom?.replay) {\n await ctx.replay()\n }\n })", "score": 41.452239619650264 } ]
typescript
const requete = new Requete().use(async (ctx, next) => {
import { Adapter, createAdapter } from 'requete/adapter' import { getUri, Logger, mergeHeaders, pick, RequestError, stringifyUrl, } from 'requete/shared' import { TimeoutAbortController } from './AbortController' import { compose } from './compose' export type Method = | 'GET' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT' | 'PATCH' export type RequestBody = | BodyInit | null | Record<string, any> | Record<string, any>[] export type RequestQueryRecord = Record< string, | string | number | boolean | null | undefined | Array<string | number | boolean> > export type RequestQuery = string | URLSearchParams | RequestQueryRecord export interface RequestConfig { baseURL?: string /** request timeout (ms) */ timeout?: number /** response body type */ responseType?: 'json' | 'formData' | 'text' | 'blob' | 'arrayBuffer' /** A string indicating how the request will interact with the browser's cache to set request's cache. */ cache?: RequestCache /** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */ credentials?: RequestCredentials /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ headers?: HeadersInit /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ integrity?: string /** A boolean to set request's keepalive. */ keepalive?: boolean /** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */ mode?: RequestMode /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ redirect?: RequestRedirect /** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */ referrer?: string /** A referrer policy to set request's referrerPolicy. */ referrerPolicy?: ReferrerPolicy /** enable logger or set logger level # */ verbose?: boolean | number /** * parse json function * (for transform response) * @default JSON.parse */ toJSON?(body: string): any } export interface IRequest extends Omit<RequestConfig, 'verbose'> { url: string /** * A string to set request's method. * @default GET */ method?: Method /** A string or object to set querystring of url */ params?: RequestQuery /** request`s body */ data?: RequestBody /** * A TimeoutAbortController to set request's signal. * @default TimeoutAbortController */ abort?: TimeoutAbortController | null /** specify request adapter */ adapter?: Adapter /** flexible custom field */ custom?: Record<string, any> } /** {@link https://developer.mozilla.org/en-US/docs/Web/API/Response} */ export interface IResponse<Data = any> { headers: Headers ok: boolean redirected: boolean status: number statusText: string type: ResponseType url: string data: Data responseText?: string } export interface IContext<Data = any> extends IResponse<Data> { /** * request config. * and empty `Headers` object as default */ request: IRequest & { method: Method; headers: Headers } /** * set `ctx.request.headers` * * *And header names are matched by case-insensitive byte sequence.* * * @example * ```ts * // set a header * ctx.set('name', '<value>') * * // remove a header * ctx.set('name', null) * ctx.set('name') * * // set headers * ctx.set({ name1: '<value>', name2: '<value>' }) * ``` */ set(headerOrName: HeadersInit | string, value?: string | null): this /** * Add extra params to `request.url`. * If there are duplicate keys, then the original key-values will be removed. */ params(params: RequestQuery): this /** * get `ctx.request.abort`, * and **create one if not exist** * @throws {RequestError} */ abort(): TimeoutAbortController /** throw {@link RequestError} */ throw(e: string | Error): void /** * Assign to current context */ assign(context: Partial<IContext>): void /** * Replay current request * And assign new context to current, with replay`s response */ replay(): Promise<void> } export type Middleware = ( ctx: IContext, next: () => Promise<void> ) => Promise<void> type AliasConfig = Omit<IRequest, 'url' | 'data'> export class Requete { static defaults: RequestConfig = { timeout: 0, responseType: 'json', headers: { Accept: 'application/json, text/plain, */*', }, verbose: 1, toJSON: (text: string | null | undefined) => { if (text) return JSON.parse(text) }, } private configs?: RequestConfig private adapter: Adapter private middlewares: Middleware[] = [] logger: Logger constructor(config?: RequestConfig) { this.configs = Object.assign({ method: 'GET' }, Requete.defaults, config) this.adapter = createAdapter() this.logger = new Logger( 'Requete', this.configs.verbose === true ? 2 : Number(this.configs.verbose ?? 0) ) } /** * add middleware function * * @attention * - The calling order of middleware should follow the **Onion Model**. * like {@link https://github.com/koajs/koa/blob/master/docs/guide.md#writing-middleware Koajs}. * - `next()` must be called asynchronously in middleware * * @example * ```ts * http.use(async (ctx, next) => { * // set request header * ctx.set('Authorization', '<token>') * * // wait for request responding * await next() * * // transformed response body * console.log(ctx.data) * * // throw a request error * if (!ctx.data) ctx.throw('no response data') * }) * ``` */ use(middleware: Middleware) { this.middlewares.push(middleware) this.logger.info( `Use middleware #${this.middlewares.length}:`, middleware.name || middleware ) return this } private createRequest(config: IRequest) { const request: IRequest = Object.assign({}, this.configs, config) request.url = getUri(request) request.headers = mergeHeaders( Requete.defaults.headers, this.configs?.headers, config.headers ) // add default AbortController for timeout if (!request.abort && request.timeout && TimeoutAbortController.supported) { request.abort = new TimeoutAbortController(request.timeout) } return request as IContext['request'] } private createContext<D>(config: IRequest) { const request = this.createRequest(config) const doRequest = this.request.bind(this) const ctx: IContext<D> = { request, status: -1, data: undefined as D, ok: false, redirected: false, headers: undefined as unknown as Headers, statusText: undefined as unknown as string, type: undefined as unknown as ResponseType, url: request.url, set(headerOrName, value) { if (this.status !== -1) this.throw('Cannot set request headers after next().') let headers = this.request.headers if (typeof headerOrName === 'string') { value == null ? headers.delete(headerOrName) : headers.set(headerOrName, value) } else { headers = mergeHeaders(headers, headerOrName) } this.request.headers = headers return this }, params(params) { this.request.url = stringifyUrl(this.request.url, params, false) return this }, abort() { if (!this.request.abort) { if (this.status !== -1) this.throw('Cannot set abortSignal after next().')
this.request.abort = new TimeoutAbortController( this.request.timeout ?? 0 ) }
return this.request.abort }, throw(e) { if (e instanceof RequestError) throw e throw new RequestError(e, this) }, assign(context) { Object.assign(this, context) }, async replay() { // count replay # this.request.custom = Object.assign({}, this.request.custom, { replay: (this.request.custom?.replay ?? 0) + 1, }) const context = await doRequest(this.request) this.assign(context) }, } return ctx } private async invoke(ctx: IContext) { this.logger.request(ctx) const adapter = ctx.request.adapter ?? this.adapter const response = await adapter.request(ctx) // assign to ctx Object.assign( ctx, pick(response, [ 'ok', 'status', 'statusText', 'headers', 'data', 'responseText', 'redirected', 'type', 'url', ]) ) if (ctx.request.responseType === 'json') { ctx.data = ctx.request.toJSON!(response.data) } } async request<D = any>(config: IRequest) { // create context const context = this.createContext<D>(config) // exec middleware try { await compose(this.middlewares)(context, this.invoke.bind(this)) if (!context.ok) { context.throw( `${context.request.method} ${context.url} ${context.status} (${context.statusText})` ) } this.logger.response(context) return context } catch (e: any) { this.logger.error(e) throw e } finally { context.request.abort?.clear() } } get<D = any>(url: string, config?: AliasConfig) { return this.request<D>({ ...config, url, method: 'GET' }) } delete<D = any>(url: string, config?: AliasConfig) { return this.request<D>({ ...config, url, method: 'DELETE' }) } head<D = any>(url: string, config?: AliasConfig) { return this.request<D>({ ...config, url, method: 'HEAD' }) } options<D = any>(url: string, config?: AliasConfig) { return this.request<D>({ ...config, url, method: 'OPTIONS' }) } post<D = any>(url: string, data?: RequestBody, config?: AliasConfig) { return this.request<D>({ ...config, url, data, method: 'POST' }) } put<D = any>(url: string, data?: RequestBody, config?: AliasConfig) { return this.request<D>({ ...config, url, data, method: 'PUT' }) } patch<D = any>(url: string, data?: RequestBody, config?: AliasConfig) { return this.request<D>({ ...config, url, data, method: 'PATCH' }) } }
src/core/Requete.ts
rexerwang-requete-e7d4979
[ { "filename": "src/core/AbortController.ts", "retrieved_chunk": " if (timeout > 0) {\n this.timeoutId = setTimeout(\n () => this.controller.abort('timeout'),\n timeout\n )\n }\n }\n get signal() {\n return this.controller.signal\n }", "score": 44.10574549693209 }, { "filename": "src/core/AbortController.ts", "retrieved_chunk": " abort(reason?: any) {\n this.controller.abort(reason)\n this.clear()\n }\n clear() {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = null\n }\n }", "score": 39.21109247737484 }, { "filename": "src/shared/logger.ts", "retrieved_chunk": " if (this.level < 2) return\n console.log(this.name, ...message)\n }\n error(e: Error | string) {\n if (this.level < 1) return\n if (!(e instanceof RequestError)) return console.error(e)\n const { ctx } = e as RequestError\n const { request, url, status, statusText } = ctx\n console.error(\n `${this.name} ${request.method} ${url} ${status} (${", "score": 31.55891810185585 }, { "filename": "src/adapter/XhrAdapter.ts", "retrieved_chunk": " }\n xhr.onloadend = () => {\n if (!xhr) return\n resolve(this.transformResponse(xhr, ctx))\n ctx.request.abort?.signal.removeEventListener('abort', onabort)\n xhr = null\n }\n xhr.onerror = () => {\n if (!xhr) return\n reject(new RequestError('Network Error', ctx))", "score": 27.979048972850123 }, { "filename": "src/core/__tests__/requete-exceptions.test.ts", "retrieved_chunk": " new Requete()\n .use(async (ctx, next) => {\n await next()\n ctx.abort()\n })\n .get('/do-mock')\n ).rejects.toThrow('Cannot set abortSignal after next().')\n // ctx.set()\n await expect(\n new Requete()", "score": 27.742083661838887 } ]
typescript
this.request.abort = new TimeoutAbortController( this.request.timeout ?? 0 ) }
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const
response: ChargeDataResponseType = await getData({
url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 21.497048939967048 }, { "filename": "src/utils.ts", "retrieved_chunk": " if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;", "score": 16.73952263958344 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 16.41929620136234 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 13.8098397570729 }, { "filename": "src/utils.ts", "retrieved_chunk": " 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',", "score": 11.638064257476078 } ]
typescript
response: ChargeDataResponseType = await getData({
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options;
const response : ChargeDataResponseType = await postData({
url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 16.287435718872942 }, { "filename": "src/zbd.d.ts", "retrieved_chunk": "import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType } from './types/index';\ndeclare class zbd {\n apiBaseUrl: string;\n apiCoreHeaders: {\n apikey: string;\n };\n constructor(apiKey: string);\n createCharge(options: ChargeOptionsType): Promise<ChargeDataResponseType>;\n getCharge(chargeId: string): Promise<ChargeDataResponseType>;\n decodeCharge(options: DecodeChargeOptionsType): Promise<DecodeChargeResponseType>;", "score": 13.8345286761354 }, { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 13.564732619954995 }, { "filename": "src/utils.ts", "retrieved_chunk": " if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;", "score": 13.178413821902689 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 12.184965907238743 } ]
typescript
const response : ChargeDataResponseType = await postData({
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({
url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, });
return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 32.56411641944872 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 29.734605691774256 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 27.339250665167494 }, { "filename": "src/utils.ts", "retrieved_chunk": " url: string;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });", "score": 26.786771875692427 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 26.307526395086494 } ]
typescript
url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, });
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({
url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 22.99176978730359 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 20.00436282177095 }, { "filename": "src/utils.d.ts", "retrieved_chunk": "export declare const cleanup: (obj: any) => {};\nexport declare function postData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;\n}): Promise<any>;\nexport declare function patchData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;", "score": 16.583760552311066 }, { "filename": "src/utils.ts", "retrieved_chunk": " 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',", "score": 15.802529575491432 }, { "filename": "src/utils.ts", "retrieved_chunk": " method: \"POST\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {", "score": 15.34612854859738 } ]
typescript
url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({
url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 22.99176978730359 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 20.00436282177095 }, { "filename": "src/utils.d.ts", "retrieved_chunk": "export declare const cleanup: (obj: any) => {};\nexport declare function postData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;\n}): Promise<any>;\nexport declare function patchData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;", "score": 16.583760552311066 }, { "filename": "src/utils.ts", "retrieved_chunk": " 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',", "score": 15.802529575491432 }, { "filename": "src/utils.ts", "retrieved_chunk": " method: \"POST\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {", "score": 15.34612854859738 } ]
typescript
url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) {
const response = await patchData({
url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 19.751260736557718 }, { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 17.43375648154005 }, { "filename": "src/utils.ts", "retrieved_chunk": " if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;", "score": 16.73952263958344 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 13.8098397570729 }, { "filename": "src/types/static-charges.ts", "retrieved_chunk": "export interface StaticChargeOptionsType {\n allowedSlots: string | null;\n minAmount: string;\n maxAmount: string;\n description: string;\n internalId: string;\n callbackUrl: string;\n successMessage: string;\n}\nexport interface StaticChargeDataResponseType {", "score": 12.555578368721193 } ]
typescript
const response = await patchData({
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url
: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, });
return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 29.725345071754695 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 25.34078647943461 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 23.438248744230233 }, { "filename": "src/utils.ts", "retrieved_chunk": " url: string;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });", "score": 22.957947645574823 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 21.363411298224417 } ]
typescript
: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, });
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({
url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, });
return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 32.56411641944872 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 28.87737759477161 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 26.436240713122093 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 26.307526395086494 }, { "filename": "src/utils.ts", "retrieved_chunk": " url: string;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });", "score": 25.90724821900865 } ]
typescript
url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, });
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}
${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, });
return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 27.030582679707887 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 21.363411298224417 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 20.914994627420935 }, { "filename": "src/utils.ts", "retrieved_chunk": " if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;", "score": 19.09125368458794 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 18.242795306799962 } ]
typescript
${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, });
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url
: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, });
return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 29.725345071754695 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 24.483558382431966 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 22.53523879218483 }, { "filename": "src/utils.ts", "retrieved_chunk": " url: string;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });", "score": 22.078423988891043 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 21.363411298224417 } ]
typescript
: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, });
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({
url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 34.53328706791535 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 29.100550202729288 }, { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 27.90282993917545 }, { "filename": "src/utils.ts", "retrieved_chunk": " method: \"POST\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {", "score": 24.60924633897227 }, { "filename": "src/utils.ts", "retrieved_chunk": " url: string;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });", "score": 24.202641008852286 } ]
typescript
url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
import { Post } from '../domain/Post'; import { PostDataCreate } from '../domain/PostDataCreate'; import { PostDataResponse } from '../domain/PostDataResponse'; import { PostRepository } from '../domain/PostRepository'; const JSONPLACEHOLDER_URL = 'https://jsonplaceholder.typicode.com'; export function createApiPostRepository(): PostRepository { const cache = new Map<number, Post>(); async function get(postId: number): Promise<Post> { if (cache.has(postId)) { return cache.get(postId) as Post; } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts/${postId}`); const post = await response.json(); cache.set(postId, post); return post; } async function getAllWithPagination( limit: number, page: number, ): Promise<Post[]> { const offset = (page - 1) * limit; const response = await fetch( `${JSONPLACEHOLDER_URL}/posts?_start=${offset}&_limit=${limit}`, ); const posts = await response.json(); return posts; } async function getAll(): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()); } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function getByUser(userId: number): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()).filter(post => post.userId === userId); } const response = await fetch( `${JSONPLACEHOLDER_URL}/users/${userId}/posts`, ); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function create(post: PostDataCreate): Promise<PostDataResponse> { const {
title, body, userId } = post;
const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`, { method: 'POST', body: JSON.stringify({ title, body, userId, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }); const createdPost = await response.json(); return createdPost; } return { create, get, getAllWithPagination, getAll, getByUser, }; }
src/modules/posts/infra/ApiPostRepository.ts
carlosazaustre-next-hexagonal-starter-8f45880
[ { "filename": "src/modules/users/infra/ApiUserRepository.ts", "retrieved_chunk": "\t\tconst user = await response.json();\n\t\tcache.set(id, user);\n\t\treturn user;\n\t}\n\tasync function getAll(): Promise<User[]> {\n\t\tif (cache.size > 0) {\n\t\t\treturn Array.from(cache.values());\n\t\t}\n\t\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/users`);\n\t\tconst users = await response.json();", "score": 41.61335914551855 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function getAllByPost(postId: number) {\n\tconst response = await fetch(\n\t\t`${JSONPLACEHOLDER_URL}/posts/${postId}/comments`,\n\t);\n\tconst comments = await response.json();\n\treturn comments;\n}\nasync function getAllByUser(userId: number) {\n\tconst response = await fetch(", "score": 41.091175349952756 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function get(commentId: number): Promise<Comment> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments/${commentId}`);\n\tconst comment = (await response.json()) as Promise<Comment>;\n\treturn comment;\n}\nasync function getAll(): Promise<Comment[]> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments`);\n\tconst comments = await response.json();\n\treturn comments;", "score": 34.226154663180445 }, { "filename": "src/modules/posts/application/mappers/PostMapper.ts", "retrieved_chunk": "}\nasync function addAuthorAndCommentCountToPosts(\n\tposts: Post[],\n\tuserMap = new Map<number, User>(),\n\tcommentCountByPostId: Map<number, number>,\n): Promise<Post[]> {\n\tconst postsWithDetails = posts.map(post => {\n\t\tconst author = userMap.get(post.userId);\n\t\treturn {\n\t\t\t...post,", "score": 34.09304043506534 }, { "filename": "src/modules/posts/application/create/createPost.ts", "retrieved_chunk": "\t\tconst createdPost = await postRepository.create(post) as PostDataResponse;\n\t\tconst commentCount = 0;\n\t\tconst author = await userRepository.get(post.userId);\n\t\t//TODO: ensurePostIsValid\n\t\treturn {\n\t\t\t...createdPost,\n\t\t\tauthor,\n\t\t\tcommentCount,\n\t\t};\n\t};", "score": 31.461068285413763 } ]
typescript
title, body, userId } = post;
import { Post } from '../domain/Post'; import { PostDataCreate } from '../domain/PostDataCreate'; import { PostDataResponse } from '../domain/PostDataResponse'; import { PostRepository } from '../domain/PostRepository'; const JSONPLACEHOLDER_URL = 'https://jsonplaceholder.typicode.com'; export function createApiPostRepository(): PostRepository { const cache = new Map<number, Post>(); async function get(postId: number): Promise<Post> { if (cache.has(postId)) { return cache.get(postId) as Post; } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts/${postId}`); const post = await response.json(); cache.set(postId, post); return post; } async function getAllWithPagination( limit: number, page: number, ): Promise<Post[]> { const offset = (page - 1) * limit; const response = await fetch( `${JSONPLACEHOLDER_URL}/posts?_start=${offset}&_limit=${limit}`, ); const posts = await response.json(); return posts; } async function getAll(): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()); } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function getByUser(userId: number): Promise<Post[]> { if (cache.size > 0) {
return Array.from(cache.values()).filter(post => post.userId === userId);
} const response = await fetch( `${JSONPLACEHOLDER_URL}/users/${userId}/posts`, ); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function create(post: PostDataCreate): Promise<PostDataResponse> { const { title, body, userId } = post; const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`, { method: 'POST', body: JSON.stringify({ title, body, userId, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }); const createdPost = await response.json(); return createdPost; } return { create, get, getAllWithPagination, getAll, getByUser, }; }
src/modules/posts/infra/ApiPostRepository.ts
carlosazaustre-next-hexagonal-starter-8f45880
[ { "filename": "src/modules/users/infra/ApiUserRepository.ts", "retrieved_chunk": "\t\tconst user = await response.json();\n\t\tcache.set(id, user);\n\t\treturn user;\n\t}\n\tasync function getAll(): Promise<User[]> {\n\t\tif (cache.size > 0) {\n\t\t\treturn Array.from(cache.values());\n\t\t}\n\t\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/users`);\n\t\tconst users = await response.json();", "score": 80.08146379660585 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function getAllByPost(postId: number) {\n\tconst response = await fetch(\n\t\t`${JSONPLACEHOLDER_URL}/posts/${postId}/comments`,\n\t);\n\tconst comments = await response.json();\n\treturn comments;\n}\nasync function getAllByUser(userId: number) {\n\tconst response = await fetch(", "score": 43.644894761257255 }, { "filename": "src/modules/users/infra/ApiUserRepository.ts", "retrieved_chunk": "import { User } from '../domain/User';\nimport { UserRepository } from '../domain/UserRepository';\nconst JSONPLACEHOLDER_URL = 'https://jsonplaceholder.typicode.com';\nexport function createApiUserRepository(): UserRepository {\n\tconst cache: Map<number, User> = new Map();\n\tasync function get(id: number): Promise<User | undefined> {\n\t\tif (cache.has(id)) {\n\t\t\treturn cache.get(id) as User;\n\t\t}\n\t\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/users/${id}`);", "score": 43.41788785642986 }, { "filename": "src/modules/posts/application/mappers/PostMapper.ts", "retrieved_chunk": "}\nasync function addAuthorAndCommentCountToPosts(\n\tposts: Post[],\n\tuserMap = new Map<number, User>(),\n\tcommentCountByPostId: Map<number, number>,\n): Promise<Post[]> {\n\tconst postsWithDetails = posts.map(post => {\n\t\tconst author = userMap.get(post.userId);\n\t\treturn {\n\t\t\t...post,", "score": 38.39303510263935 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function get(commentId: number): Promise<Comment> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments/${commentId}`);\n\tconst comment = (await response.json()) as Promise<Comment>;\n\treturn comment;\n}\nasync function getAll(): Promise<Comment[]> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments`);\n\tconst comments = await response.json();\n\treturn comments;", "score": 34.22694428254856 } ]
typescript
return Array.from(cache.values()).filter(post => post.userId === userId);
import { Post } from '../domain/Post'; import { PostDataCreate } from '../domain/PostDataCreate'; import { PostDataResponse } from '../domain/PostDataResponse'; import { PostRepository } from '../domain/PostRepository'; const JSONPLACEHOLDER_URL = 'https://jsonplaceholder.typicode.com'; export function createApiPostRepository(): PostRepository { const cache = new Map<number, Post>(); async function get(postId: number): Promise<Post> { if (cache.has(postId)) { return cache.get(postId) as Post; } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts/${postId}`); const post = await response.json(); cache.set(postId, post); return post; } async function getAllWithPagination( limit: number, page: number, ): Promise<Post[]> { const offset = (page - 1) * limit; const response = await fetch( `${JSONPLACEHOLDER_URL}/posts?_start=${offset}&_limit=${limit}`, ); const posts = await response.json(); return posts; } async function getAll(): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()); } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function getByUser(userId: number): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()).filter(post => post.userId === userId); } const response = await fetch( `${JSONPLACEHOLDER_URL}/users/${userId}/posts`, ); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function create(post
: PostDataCreate): Promise<PostDataResponse> {
const { title, body, userId } = post; const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`, { method: 'POST', body: JSON.stringify({ title, body, userId, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }); const createdPost = await response.json(); return createdPost; } return { create, get, getAllWithPagination, getAll, getByUser, }; }
src/modules/posts/infra/ApiPostRepository.ts
carlosazaustre-next-hexagonal-starter-8f45880
[ { "filename": "src/modules/users/infra/ApiUserRepository.ts", "retrieved_chunk": "\t\tconst user = await response.json();\n\t\tcache.set(id, user);\n\t\treturn user;\n\t}\n\tasync function getAll(): Promise<User[]> {\n\t\tif (cache.size > 0) {\n\t\t\treturn Array.from(cache.values());\n\t\t}\n\t\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/users`);\n\t\tconst users = await response.json();", "score": 40.520661833532095 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function getAllByPost(postId: number) {\n\tconst response = await fetch(\n\t\t`${JSONPLACEHOLDER_URL}/posts/${postId}/comments`,\n\t);\n\tconst comments = await response.json();\n\treturn comments;\n}\nasync function getAllByUser(userId: number) {\n\tconst response = await fetch(", "score": 38.113510079483 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function get(commentId: number): Promise<Comment> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments/${commentId}`);\n\tconst comment = (await response.json()) as Promise<Comment>;\n\treturn comment;\n}\nasync function getAll(): Promise<Comment[]> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments`);\n\tconst comments = await response.json();\n\treturn comments;", "score": 33.069399899103374 }, { "filename": "src/modules/posts/application/mappers/PostMapper.ts", "retrieved_chunk": "}\nasync function addAuthorAndCommentCountToPosts(\n\tposts: Post[],\n\tuserMap = new Map<number, User>(),\n\tcommentCountByPostId: Map<number, number>,\n): Promise<Post[]> {\n\tconst postsWithDetails = posts.map(post => {\n\t\tconst author = userMap.get(post.userId);\n\t\treturn {\n\t\t\t...post,", "score": 28.49540036462551 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "\t\t`${JSONPLACEHOLDER_URL}/users/${userId}/comments`,\n\t);\n\tconst comments = await response.json();\n\treturn comments;\n}", "score": 26.640649928598915 } ]
typescript
: PostDataCreate): Promise<PostDataResponse> {
import { Post } from '../domain/Post'; import { PostDataCreate } from '../domain/PostDataCreate'; import { PostDataResponse } from '../domain/PostDataResponse'; import { PostRepository } from '../domain/PostRepository'; const JSONPLACEHOLDER_URL = 'https://jsonplaceholder.typicode.com'; export function createApiPostRepository(): PostRepository { const cache = new Map<number, Post>(); async function get(postId: number): Promise<Post> { if (cache.has(postId)) { return cache.get(postId) as Post; } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts/${postId}`); const post = await response.json(); cache.set(postId, post); return post; } async function getAllWithPagination( limit: number, page: number, ): Promise<Post[]> { const offset = (page - 1) * limit; const response = await fetch( `${JSONPLACEHOLDER_URL}/posts?_start=${offset}&_limit=${limit}`, ); const posts = await response.json(); return posts; } async function getAll(): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()); } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function getByUser(userId: number): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()).filter(post => post.userId === userId); } const response = await fetch( `${JSONPLACEHOLDER_URL}/users/${userId}/posts`, ); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; }
async function create(post: PostDataCreate): Promise<PostDataResponse> {
const { title, body, userId } = post; const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`, { method: 'POST', body: JSON.stringify({ title, body, userId, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }); const createdPost = await response.json(); return createdPost; } return { create, get, getAllWithPagination, getAll, getByUser, }; }
src/modules/posts/infra/ApiPostRepository.ts
carlosazaustre-next-hexagonal-starter-8f45880
[ { "filename": "src/modules/users/infra/ApiUserRepository.ts", "retrieved_chunk": "\t\tconst user = await response.json();\n\t\tcache.set(id, user);\n\t\treturn user;\n\t}\n\tasync function getAll(): Promise<User[]> {\n\t\tif (cache.size > 0) {\n\t\t\treturn Array.from(cache.values());\n\t\t}\n\t\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/users`);\n\t\tconst users = await response.json();", "score": 54.097272551356795 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function getAllByPost(postId: number) {\n\tconst response = await fetch(\n\t\t`${JSONPLACEHOLDER_URL}/posts/${postId}/comments`,\n\t);\n\tconst comments = await response.json();\n\treturn comments;\n}\nasync function getAllByUser(userId: number) {\n\tconst response = await fetch(", "score": 41.79122515978093 }, { "filename": "src/modules/posts/application/mappers/PostMapper.ts", "retrieved_chunk": "}\nasync function addAuthorAndCommentCountToPosts(\n\tposts: Post[],\n\tuserMap = new Map<number, User>(),\n\tcommentCountByPostId: Map<number, number>,\n): Promise<Post[]> {\n\tconst postsWithDetails = posts.map(post => {\n\t\tconst author = userMap.get(post.userId);\n\t\treturn {\n\t\t\t...post,", "score": 37.73747215759206 }, { "filename": "src/modules/posts/application/create/createPost.ts", "retrieved_chunk": "\t\tconst createdPost = await postRepository.create(post) as PostDataResponse;\n\t\tconst commentCount = 0;\n\t\tconst author = await userRepository.get(post.userId);\n\t\t//TODO: ensurePostIsValid\n\t\treturn {\n\t\t\t...createdPost,\n\t\t\tauthor,\n\t\t\tcommentCount,\n\t\t};\n\t};", "score": 34.790965231700056 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function get(commentId: number): Promise<Comment> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments/${commentId}`);\n\tconst comment = (await response.json()) as Promise<Comment>;\n\treturn comment;\n}\nasync function getAll(): Promise<Comment[]> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments`);\n\tconst comments = await response.json();\n\treturn comments;", "score": 33.11359124157612 } ]
typescript
async function create(post: PostDataCreate): Promise<PostDataResponse> {
import { Post } from '../domain/Post'; import { PostDataCreate } from '../domain/PostDataCreate'; import { PostDataResponse } from '../domain/PostDataResponse'; import { PostRepository } from '../domain/PostRepository'; const JSONPLACEHOLDER_URL = 'https://jsonplaceholder.typicode.com'; export function createApiPostRepository(): PostRepository { const cache = new Map<number, Post>(); async function get(postId: number): Promise<Post> { if (cache.has(postId)) { return cache.get(postId) as Post; } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts/${postId}`); const post = await response.json(); cache.set(postId, post); return post; } async function getAllWithPagination( limit: number, page: number, ): Promise<Post[]> { const offset = (page - 1) * limit; const response = await fetch( `${JSONPLACEHOLDER_URL}/posts?_start=${offset}&_limit=${limit}`, ); const posts = await response.json(); return posts; } async function getAll(): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()); } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function getByUser(userId: number): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()).filter(post => post.userId === userId); } const response = await fetch( `${JSONPLACEHOLDER_URL}/users/${userId}/posts`, ); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function create(post: PostDataCreate): Promise<PostDataResponse> { const { title, body,
userId } = post;
const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`, { method: 'POST', body: JSON.stringify({ title, body, userId, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }); const createdPost = await response.json(); return createdPost; } return { create, get, getAllWithPagination, getAll, getByUser, }; }
src/modules/posts/infra/ApiPostRepository.ts
carlosazaustre-next-hexagonal-starter-8f45880
[ { "filename": "src/modules/users/infra/ApiUserRepository.ts", "retrieved_chunk": "\t\tconst user = await response.json();\n\t\tcache.set(id, user);\n\t\treturn user;\n\t}\n\tasync function getAll(): Promise<User[]> {\n\t\tif (cache.size > 0) {\n\t\t\treturn Array.from(cache.values());\n\t\t}\n\t\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/users`);\n\t\tconst users = await response.json();", "score": 41.61335914551855 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function getAllByPost(postId: number) {\n\tconst response = await fetch(\n\t\t`${JSONPLACEHOLDER_URL}/posts/${postId}/comments`,\n\t);\n\tconst comments = await response.json();\n\treturn comments;\n}\nasync function getAllByUser(userId: number) {\n\tconst response = await fetch(", "score": 41.091175349952756 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function get(commentId: number): Promise<Comment> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments/${commentId}`);\n\tconst comment = (await response.json()) as Promise<Comment>;\n\treturn comment;\n}\nasync function getAll(): Promise<Comment[]> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments`);\n\tconst comments = await response.json();\n\treturn comments;", "score": 34.226154663180445 }, { "filename": "src/modules/posts/application/mappers/PostMapper.ts", "retrieved_chunk": "}\nasync function addAuthorAndCommentCountToPosts(\n\tposts: Post[],\n\tuserMap = new Map<number, User>(),\n\tcommentCountByPostId: Map<number, number>,\n): Promise<Post[]> {\n\tconst postsWithDetails = posts.map(post => {\n\t\tconst author = userMap.get(post.userId);\n\t\treturn {\n\t\t\t...post,", "score": 34.09304043506534 }, { "filename": "src/modules/posts/application/create/createPost.ts", "retrieved_chunk": "\t\tconst createdPost = await postRepository.create(post) as PostDataResponse;\n\t\tconst commentCount = 0;\n\t\tconst author = await userRepository.get(post.userId);\n\t\t//TODO: ensurePostIsValid\n\t\treturn {\n\t\t\t...createdPost,\n\t\t\tauthor,\n\t\t\tcommentCount,\n\t\t};\n\t};", "score": 31.461068285413763 } ]
typescript
userId } = post;
import { Post } from '../domain/Post'; import { PostDataCreate } from '../domain/PostDataCreate'; import { PostDataResponse } from '../domain/PostDataResponse'; import { PostRepository } from '../domain/PostRepository'; const JSONPLACEHOLDER_URL = 'https://jsonplaceholder.typicode.com'; export function createApiPostRepository(): PostRepository { const cache = new Map<number, Post>(); async function get(postId: number): Promise<Post> { if (cache.has(postId)) { return cache.get(postId) as Post; } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts/${postId}`); const post = await response.json(); cache.set(postId, post); return post; } async function getAllWithPagination( limit: number, page: number, ): Promise<Post[]> { const offset = (page - 1) * limit; const response = await fetch( `${JSONPLACEHOLDER_URL}/posts?_start=${offset}&_limit=${limit}`, ); const posts = await response.json(); return posts; } async function getAll(): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()); } const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function getByUser(userId: number): Promise<Post[]> { if (cache.size > 0) { return Array.from(cache.values()).filter(post => post.userId === userId); } const response = await fetch( `${JSONPLACEHOLDER_URL}/users/${userId}/posts`, ); const posts = await response.json(); posts.forEach((post: Post) => cache.set(post.id, post)); return posts; } async function create(post: PostDataCreate): Promise<PostDataResponse> { const
{ title, body, userId } = post;
const response = await fetch(`${JSONPLACEHOLDER_URL}/posts`, { method: 'POST', body: JSON.stringify({ title, body, userId, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }); const createdPost = await response.json(); return createdPost; } return { create, get, getAllWithPagination, getAll, getByUser, }; }
src/modules/posts/infra/ApiPostRepository.ts
carlosazaustre-next-hexagonal-starter-8f45880
[ { "filename": "src/modules/users/infra/ApiUserRepository.ts", "retrieved_chunk": "\t\tconst user = await response.json();\n\t\tcache.set(id, user);\n\t\treturn user;\n\t}\n\tasync function getAll(): Promise<User[]> {\n\t\tif (cache.size > 0) {\n\t\t\treturn Array.from(cache.values());\n\t\t}\n\t\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/users`);\n\t\tconst users = await response.json();", "score": 41.61335914551855 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function getAllByPost(postId: number) {\n\tconst response = await fetch(\n\t\t`${JSONPLACEHOLDER_URL}/posts/${postId}/comments`,\n\t);\n\tconst comments = await response.json();\n\treturn comments;\n}\nasync function getAllByUser(userId: number) {\n\tconst response = await fetch(", "score": 41.091175349952756 }, { "filename": "src/modules/comments/infra/ApiCommentRepository.ts", "retrieved_chunk": "}\nasync function get(commentId: number): Promise<Comment> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments/${commentId}`);\n\tconst comment = (await response.json()) as Promise<Comment>;\n\treturn comment;\n}\nasync function getAll(): Promise<Comment[]> {\n\tconst response = await fetch(`${JSONPLACEHOLDER_URL}/comments`);\n\tconst comments = await response.json();\n\treturn comments;", "score": 34.226154663180445 }, { "filename": "src/modules/posts/application/mappers/PostMapper.ts", "retrieved_chunk": "}\nasync function addAuthorAndCommentCountToPosts(\n\tposts: Post[],\n\tuserMap = new Map<number, User>(),\n\tcommentCountByPostId: Map<number, number>,\n): Promise<Post[]> {\n\tconst postsWithDetails = posts.map(post => {\n\t\tconst author = userMap.get(post.userId);\n\t\treturn {\n\t\t\t...post,", "score": 34.09304043506534 }, { "filename": "src/modules/posts/application/create/createPost.ts", "retrieved_chunk": "\t\tconst createdPost = await postRepository.create(post) as PostDataResponse;\n\t\tconst commentCount = 0;\n\t\tconst author = await userRepository.get(post.userId);\n\t\t//TODO: ensurePostIsValid\n\t\treturn {\n\t\t\t...createdPost,\n\t\t\tauthor,\n\t\t\tcommentCount,\n\t\t};\n\t};", "score": 31.461068285413763 } ]
typescript
{ title, body, userId } = post;
import * as fs from 'fs-extra'; import { SyncHook } from 'tapable'; import { Asset, AssetPath } from './Asset'; import { Compilation } from './Compilation'; import { Compiler } from './Compiler'; export type EmitterHooks = Readonly<{ beforeAssetAction: SyncHook<[Asset]>; afterAssetAction: SyncHook<[Asset]>; }>; export class Emitter { compiler: Compiler; compilation: Compilation; hooks: EmitterHooks; constructor(compiler: Compiler, compilation: Compilation) { this.compiler = compiler; this.compilation = compilation; this.hooks = { beforeAssetAction: new SyncHook(['asset']), afterAssetAction: new SyncHook(['asset']), }; } emit() { this.compilation.assets.forEach((asset) => { this.hooks.beforeAssetAction.call(asset); if (typeof asset.target === 'undefined') { this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`); return; } switch (asset.action) { case 'add': case 'update': { this.writeFile(asset.target.absolute, asset.content); break; } case 'remove': { this.removeFile(asset.target.absolute); break; } // No default. } this.hooks.afterAssetAction.call(asset); }); } private writeFile(targetPath
: AssetPath['absolute'], content: Asset['content']) {
try { fs.ensureFileSync(targetPath); fs.writeFileSync(targetPath, content); } catch (error: any) { this.compilation.addError(error.message); } } private removeFile(targetPath: AssetPath['absolute']) { try { fs.removeSync(targetPath); } catch (error: any) { this.compilation.addError(error.message); } } }
src/Emitter.ts
unshopable-melter-b347450
[ { "filename": "src/Asset.ts", "retrieved_chunk": " links: Set<Asset>;\n /**\n * The asset's content.\n */\n content: Buffer;\n /**\n * The action that created this asset.\n */\n action: CompilerEvent;\n constructor(type: AssetType, source: AssetPath, links: Set<Asset>, action: CompilerEvent) {", "score": 19.515795023803495 }, { "filename": "src/Asset.ts", "retrieved_chunk": " * The absolute and relative path to the asset's file.\n */\n source: AssetPath;\n /**\n * The absolute and relative path to the asset's file.\n */\n target?: AssetPath;\n /**\n * A set of assets the asset is linked with.\n */", "score": 19.08393167749984 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 18.695002049332423 }, { "filename": "src/Asset.ts", "retrieved_chunk": " this.type = type;\n this.source = source;\n this.links = new Set<Asset>(links);\n this.content = this.getContent();\n this.action = action;\n }\n private getContent() {\n try {\n return fs.readFileSync(this.source.absolute);\n } catch {", "score": 16.02857835034564 }, { "filename": "src/Asset.ts", "retrieved_chunk": "export type AssetPath = {\n absolute: string;\n relative: string;\n};\nexport class Asset {\n /**\n * The type of the asset.\n */\n type: AssetType;\n /**", "score": 15.41684424477134 } ]
typescript
: AssetPath['absolute'], content: Asset['content']) {
import * as fs from 'fs-extra'; import { CompilerEvent } from './Compiler'; export type AssetType = | 'assets' | 'config' | 'layout' | 'locales' | 'sections' | 'snippets' | 'templates'; export type AssetPath = { absolute: string; relative: string; }; export class Asset { /** * The type of the asset. */ type: AssetType; /** * The absolute and relative path to the asset's file. */ source: AssetPath; /** * The absolute and relative path to the asset's file. */ target?: AssetPath; /** * A set of assets the asset is linked with. */ links: Set<Asset>; /** * The asset's content. */ content: Buffer; /** * The action that created this asset. */ action: CompilerEvent; constructor(type: AssetType,
source: AssetPath, links: Set<Asset>, action: CompilerEvent) {
this.type = type; this.source = source; this.links = new Set<Asset>(links); this.content = this.getContent(); this.action = action; } private getContent() { try { return fs.readFileSync(this.source.absolute); } catch { return Buffer.from(''); } } }
src/Asset.ts
unshopable-melter-b347450
[ { "filename": "src/Emitter.ts", "retrieved_chunk": " }\n emit() {\n this.compilation.assets.forEach((asset) => {\n this.hooks.beforeAssetAction.call(asset);\n if (typeof asset.target === 'undefined') {\n this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`);\n return;\n }\n switch (asset.action) {\n case 'add':", "score": 21.309578086858714 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " assets: Set<Asset>;\n stats: CompilationStats;\n hooks: Readonly<CompilationHooks>;\n /**\n * Creates an instance of `Compilation`.\n *\n * @param compiler The compiler which created the compilation.\n * @param assetPaths A set of paths to assets that should be compiled.\n */\n constructor(compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) {", "score": 19.856946990701136 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " this.hooks.afterAssetAction.call(asset);\n });\n }\n private writeFile(targetPath: AssetPath['absolute'], content: Asset['content']) {\n try {\n fs.ensureFileSync(targetPath);\n fs.writeFileSync(targetPath, content);\n } catch (error: any) {\n this.compilation.addError(error.message);\n }", "score": 17.59378166026285 }, { "filename": "src/Compilation.ts", "retrieved_chunk": "import * as path from 'path';\nimport { SyncHook } from 'tapable';\nimport { Asset } from './Asset';\nimport { Compiler, CompilerEvent } from './Compiler';\nexport type CompilationStats = {\n /**\n * The compilation time in milliseconds.\n */\n time: number;\n /**", "score": 14.273063086461867 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " case 'update': {\n this.writeFile(asset.target.absolute, asset.content);\n break;\n }\n case 'remove': {\n this.removeFile(asset.target.absolute);\n break;\n }\n // No default.\n }", "score": 13.665310681003376 } ]
typescript
source: AssetPath, links: Set<Asset>, action: CompilerEvent) {
import * as fs from 'fs-extra'; import { CompilerEvent } from './Compiler'; export type AssetType = | 'assets' | 'config' | 'layout' | 'locales' | 'sections' | 'snippets' | 'templates'; export type AssetPath = { absolute: string; relative: string; }; export class Asset { /** * The type of the asset. */ type: AssetType; /** * The absolute and relative path to the asset's file. */ source: AssetPath; /** * The absolute and relative path to the asset's file. */ target?: AssetPath; /** * A set of assets the asset is linked with. */ links: Set<Asset>; /** * The asset's content. */ content: Buffer; /** * The action that created this asset. */
action: CompilerEvent;
constructor(type: AssetType, source: AssetPath, links: Set<Asset>, action: CompilerEvent) { this.type = type; this.source = source; this.links = new Set<Asset>(links); this.content = this.getContent(); this.action = action; } private getContent() { try { return fs.readFileSync(this.source.absolute); } catch { return Buffer.from(''); } } }
src/Asset.ts
unshopable-melter-b347450
[ { "filename": "src/Compilation.ts", "retrieved_chunk": " assets: Set<Asset>;\n stats: CompilationStats;\n hooks: Readonly<CompilationHooks>;\n /**\n * Creates an instance of `Compilation`.\n *\n * @param compiler The compiler which created the compilation.\n * @param assetPaths A set of paths to assets that should be compiled.\n */\n constructor(compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) {", "score": 15.966802317267168 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " this.hooks.afterAssetAction.call(asset);\n });\n }\n private writeFile(targetPath: AssetPath['absolute'], content: Asset['content']) {\n try {\n fs.ensureFileSync(targetPath);\n fs.writeFileSync(targetPath, content);\n } catch (error: any) {\n this.compilation.addError(error.message);\n }", "score": 15.189087634256294 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " }\n emit() {\n this.compilation.assets.forEach((asset) => {\n this.hooks.beforeAssetAction.call(asset);\n if (typeof asset.target === 'undefined') {\n this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`);\n return;\n }\n switch (asset.action) {\n case 'add':", "score": 14.556459767270853 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " case 'update': {\n this.writeFile(asset.target.absolute, asset.content);\n break;\n }\n case 'remove': {\n this.removeFile(asset.target.absolute);\n break;\n }\n // No default.\n }", "score": 13.665310681003376 }, { "filename": "src/Compilation.ts", "retrieved_chunk": "import * as path from 'path';\nimport { SyncHook } from 'tapable';\nimport { Asset } from './Asset';\nimport { Compiler, CompilerEvent } from './Compiler';\nexport type CompilationStats = {\n /**\n * The compilation time in milliseconds.\n */\n time: number;\n /**", "score": 10.592290747491914 } ]
typescript
action: CompilerEvent;
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({
url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 22.99176978730359 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 20.00436282177095 }, { "filename": "src/utils.d.ts", "retrieved_chunk": "export declare const cleanup: (obj: any) => {};\nexport declare function postData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;\n}): Promise<any>;\nexport declare function patchData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;", "score": 16.583760552311066 }, { "filename": "src/utils.ts", "retrieved_chunk": " 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',", "score": 15.802529575491432 }, { "filename": "src/utils.ts", "retrieved_chunk": " method: \"POST\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {", "score": 15.34612854859738 } ]
typescript
url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
import { After, AfterStep, AfterAll, Before, BeforeStep, BeforeAll } from '@cucumber/cucumber'; import defaultTimeouts from './defaultTimeouts'; import { po } from '@qavajs/po-testcafe'; import { saveScreenshotAfterStep, saveScreenshotBeforeStep, takeScreenshot } from './utils/utils'; import createTestCafe from 'testcafe'; import { join } from 'path'; declare global { var t: TestController; var testcafe: TestCafe; var runner: Runner; var taskPromise: any; var config: any; } BeforeAll(async function (){ global.testcafe = await createTestCafe('localhost'); }) Before(async function () { const driverConfig = config.browser ?? config.driver; driverConfig.timeout = { ...defaultTimeouts, ...driverConfig.timeout } global.config.driverConfig = driverConfig; if (!global.t || !config.driverConfig.reuseSession) { global.runner = await testcafe.createRunner(); global.taskPromise = global.runner .src(join(__dirname, 'testController/bootstrap.{ts,js}')) .browsers([config.driverConfig.capabilities.browserName]) .run({ nativeAutomation: config.driverConfig.capabilities.nativeAutomation ?? false }); await new Promise((resolve) => { const interval = setInterval(() => { if (global.t) { clearInterval(interval) resolve(t); } }, 500) }); } po.init({timeout: config.driverConfig.timeout.present}); po.register(config.pageObject); this.log(`browser instance started:\n${JSON.stringify(config.driverConfig, null, 2)}`); }); BeforeStep(async function () { if (saveScreenshotBeforeStep(config)) { try { this.attach
(await takeScreenshot(), 'image/png');
} catch (err) { console.warn(err) } } }); AfterStep(async function (step) { try { if (saveScreenshotAfterStep(config, step)) { this.attach(await takeScreenshot(), 'image/png'); } } catch (err) { console.warn(err) } }); After(async function (scenario) { if (global.config.driverConfig.reuseSession) { let close = true; while (close) { try { await t.closeWindow(); } catch (err) { close = false } } } if (global.t && !global.config.driverConfig.reuseSession) { await global.taskPromise.cancel(); await global.runner.stop(); // @ts-ignore global.t = null; // @ts-ignore global.runner = null; // @ts-ignore global.taskPromise = null; } }); AfterAll(async function () { await global.testcafe.close(); });
src/hooks.ts
qavajs-steps-testcafe-b1ff199
[ { "filename": "src/utils/utils.ts", "retrieved_chunk": "export function saveScreenshotBeforeStep(config: any): boolean {\n return equalOrIncludes(config.screenshot, ScreenshotEvent.BEFORE_STEP)\n}\nexport function saveTrace(driverConfig: any, scenario: ITestCaseHookParameter): boolean {\n return driverConfig?.trace && (\n (equalOrIncludes(driverConfig?.trace.event, TraceEvent.AFTER_SCENARIO)) ||\n (scenario.result?.status === Status.FAILED && equalOrIncludes(driverConfig?.trace.event, TraceEvent.ON_FAIL))\n )\n}\nfunction normalizeScenarioName(name: string): string {", "score": 34.91259578114088 }, { "filename": "src/waits.ts", "retrieved_chunk": " 'I wait until page title {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const expectedValue = await getValue(value);\n const getValueFn = await ClientFunction(() => window.document.title )\n .with({ boundTestRun: t });\n await wait(getValueFn(), expectedValue, timeout ? timeout : config.browser.timeout.page);\n }\n);", "score": 22.552796828644308 }, { "filename": "src/waits.ts", "retrieved_chunk": " const expectedValue = await getValue(value);\n await wait(\n collection.with({ boundTestRun: t }).count,\n parseFloat(expectedValue),\n timeout ? timeout : config.browser.timeout.page\n );\n }\n);\n/**\n * Wait for element property condition", "score": 22.37792554807284 }, { "filename": "src/waits.ts", "retrieved_chunk": "When(\n 'I wait until current url {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const expectedValue = await getValue(value);\n const getValueFn = await ClientFunction(() => window.location.href )\n .with({ boundTestRun: t });\n await wait(getValueFn(), expectedValue, timeout ? timeout : config.browser.timeout.page);\n }\n);", "score": 22.35966036273226 }, { "filename": "src/waits.ts", "retrieved_chunk": " async function (property: string, alias: string, waitType: string, value: string, timeout: number | null) {\n const propertyName = await getValue(property);\n const wait = getValueWait(waitType);\n const element = await getElement(alias);\n const expectedValue = await getValue(value);\n // @ts-ignore\n const getValueFn = element.with({ boundTestRun: t })[propertyName];\n await wait(getValueFn, expectedValue, timeout ? timeout : config.browser.timeout.page);\n }\n);", "score": 21.768792593554863 } ]
typescript
(await takeScreenshot(), 'image/png');
import fg from 'fast-glob'; import * as fs from 'fs-extra'; import * as path from 'path'; import { BaseCompilerConfig, MelterConfig, defaultBaseCompilerConfig } from '.'; import { getFilenameFromPath, parseJSON } from '../utils'; function getConfigFiles(cwd: string): string[] { const configFilePattern = 'melter.config.*'; // flat-glob only supports POSIX path syntax, so we use convertPathToPattern() for windows return fg.sync(fg.convertPathToPattern(cwd) + '/' + configFilePattern); } function parseConfigFile(file: string): { config: MelterConfig | null; errors: string[] } { if (file.endsWith('json')) { const content = fs.readFileSync(file, 'utf8'); const { data, error } = parseJSON<MelterConfig>(content); if (error) { return { config: null, errors: [error], }; } return { config: data, errors: [], }; } return { config: require(file).default || require(file), errors: [], }; } export function loadConfig(): { config: MelterConfig | BaseCompilerConfig | null; warnings: string[]; errors: string[]; } { const configFiles = getConfigFiles(process.cwd()); if (configFiles.length === 0) { return { config: defaultBaseCompilerConfig, warnings: [ 'No config found. Loaded default config. To disable this warning create a custom config.', ], errors: [], }; } const firstConfigFile = configFiles[0]; const warnings: string[] = []; if (configFiles.length > 1) { warnings.push(
`Multiple configs found. Loaded '${getFilenameFromPath( firstConfigFile, )}'. To disable this warning remove unused configs.`, );
} const { config, errors } = parseConfigFile(firstConfigFile); return { config, warnings, errors, }; }
src/config/load.ts
unshopable-melter-b347450
[ { "filename": "src/plugins/StatsPlugin.ts", "retrieved_chunk": " this.config = config;\n }\n apply(compiler: Compiler): void {\n if (this.config.stats === false) return;\n compiler.hooks.done.tap('StatsPlugin', (compilationStats: CompilationStats) => {\n if (compilationStats.errors.length > 0) {\n compiler.logger.error('Compilation failed', compilationStats.errors);\n } else if (compilationStats.warnings.length > 0) {\n compiler.logger.warning(\n `Compiled with ${compilationStats.warnings.length} warnings`,", "score": 17.48516009921522 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " this.stats.time = Number((endTime - startTime).toFixed(2));\n }\n addWarning(warning: string) {\n this.stats.warnings.push(warning);\n }\n addError(error: string) {\n this.stats.errors.push(error);\n }\n}", "score": 14.738617099549316 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " });\n });\n }\n private determineAssetType(paths: Paths, assetPath: string): AssetType | null {\n const pathEntries = Object.entries(paths);\n for (let i = 0; i < pathEntries.length; i += 1) {\n const [name, patterns] = pathEntries[i];\n for (let j = 0; j < patterns.length; j++) {\n if (assetPath.match(patterns[j])) {\n return name as AssetType;", "score": 12.81498207428356 }, { "filename": "src/Logger.ts", "retrieved_chunk": "export type LoggerDataType = 'warning' | 'error';\nexport class Logger {\n success(message: string) {\n console.log(this.formatSuccess(message));\n console.log('');\n }\n warning(message: string, data: string[]) {\n console.log(this.formatWarning(message));\n if (data.length > 0) {\n console.log('');", "score": 10.58202848314234 }, { "filename": "src/Logger.ts", "retrieved_chunk": " console.log(this.formatLogData('warning', data));\n console.log('');\n }\n }\n error(message: string, data: string[]) {\n console.log(this.formatError(message));\n if (data.length > 0) {\n console.log('');\n console.log(this.formatLogData('error', data));\n console.log('');", "score": 9.682594200517247 } ]
typescript
`Multiple configs found. Loaded '${getFilenameFromPath( firstConfigFile, )}'. To disable this warning remove unused configs.`, );
import { After, AfterStep, AfterAll, Before, BeforeStep, BeforeAll } from '@cucumber/cucumber'; import defaultTimeouts from './defaultTimeouts'; import { po } from '@qavajs/po-testcafe'; import { saveScreenshotAfterStep, saveScreenshotBeforeStep, takeScreenshot } from './utils/utils'; import createTestCafe from 'testcafe'; import { join } from 'path'; declare global { var t: TestController; var testcafe: TestCafe; var runner: Runner; var taskPromise: any; var config: any; } BeforeAll(async function (){ global.testcafe = await createTestCafe('localhost'); }) Before(async function () { const driverConfig = config.browser ?? config.driver; driverConfig.timeout = { ...defaultTimeouts, ...driverConfig.timeout } global.config.driverConfig = driverConfig; if (!global.t || !config.driverConfig.reuseSession) { global.runner = await testcafe.createRunner(); global.taskPromise = global.runner .src(join(__dirname, 'testController/bootstrap.{ts,js}')) .browsers([config.driverConfig.capabilities.browserName]) .run({ nativeAutomation: config.driverConfig.capabilities.nativeAutomation ?? false }); await new Promise((resolve) => { const interval = setInterval(() => { if (global.t) { clearInterval(interval) resolve(t); } }, 500) }); } po.init({timeout: config.driverConfig.timeout.present}); po.register(config.pageObject); this.log(`browser instance started:\n${JSON.stringify(config.driverConfig, null, 2)}`); }); BeforeStep(async function () { if (saveScreenshotBeforeStep(config)) { try { this.attach(await takeScreenshot(), 'image/png'); } catch (err) { console.warn(err) } } }); AfterStep(async function (step) { try { if (
saveScreenshotAfterStep(config, step)) {
this.attach(await takeScreenshot(), 'image/png'); } } catch (err) { console.warn(err) } }); After(async function (scenario) { if (global.config.driverConfig.reuseSession) { let close = true; while (close) { try { await t.closeWindow(); } catch (err) { close = false } } } if (global.t && !global.config.driverConfig.reuseSession) { await global.taskPromise.cancel(); await global.runner.stop(); // @ts-ignore global.t = null; // @ts-ignore global.runner = null; // @ts-ignore global.taskPromise = null; } }); AfterAll(async function () { await global.testcafe.close(); });
src/hooks.ts
qavajs-steps-testcafe-b1ff199
[ { "filename": "src/utils/utils.ts", "retrieved_chunk": "}\nexport async function throwTimeoutError(fn: Function, message: string) {\n try {\n await fn()\n } catch (err: any) {\n if (err.message.includes('exceeded while waiting on the predicate')) {\n throw new Error(message);\n }\n throw err\n }", "score": 34.00867947863587 }, { "filename": "src/utils/utils.ts", "retrieved_chunk": "import { ScreenshotEvent } from './screenshotEvent';\nimport { TraceEvent } from './traceEvent';\nimport { Status, ITestStepHookParameter, ITestCaseHookParameter } from '@cucumber/cucumber';\nimport { join } from 'path';\nimport { readFile } from 'fs/promises';\nexport function saveScreenshotAfterStep(config: any, step: ITestStepHookParameter): boolean {\n const isAfterStepScreenshot = equalOrIncludes(config.screenshot, ScreenshotEvent.AFTER_STEP);\n const isOnFailScreenshot = equalOrIncludes(config.screenshot, ScreenshotEvent.ON_FAIL);\n return (isOnFailScreenshot && step.result.status === Status.FAILED) || isAfterStepScreenshot\n}", "score": 19.62366635677952 }, { "filename": "src/actions.ts", "retrieved_chunk": " * testcafe automatically dismisses all dialogs. This step is just to make it implicitly.\n * @example I will dismiss alert\n */\nWhen('I will dismiss alert', async function () {\n await t.setNativeDialogHandler(() => false);\n});\n/**\n * Type text to prompt\n * I type {string} to alert\n * @example I will type 'coffee' to alert", "score": 10.696195681699143 }, { "filename": "src/utils/utils.ts", "retrieved_chunk": "}\nexport async function takeScreenshot(): Promise<string> {\n const screenshotPath = await t.takeScreenshot();\n const screenshot = await readFile(screenshotPath);\n return screenshot.toString('base64');\n}\nexport function isChromium(browserName: string): boolean {\n return browserName.includes('chrom')\n}", "score": 10.437884219742902 }, { "filename": "src/validations.ts", "retrieved_chunk": " async function (validationType: string, expected: string) {\n const validation = getValidation(validationType);\n const expectedUrl = await getValue(expected);\n const actualUrl = await ClientFunction(() => window.location.href )\n .with({ boundTestRun: t })();\n this.log(`AR: ${actualUrl}`);\n this.log(`ER: ${expectedUrl}`);\n validation(actualUrl, expectedUrl);\n }\n);", "score": 7.609797775139825 } ]
typescript
saveScreenshotAfterStep(config, step)) {
import { When } from '@cucumber/cucumber'; import { getValue, getElement } from './transformers'; import { ClientFunction, Selector } from 'testcafe'; import {parseCoords} from './utils/utils'; /** * Opens provided url * @param {string} url - url to navigate * @example I open 'https://google.com' */ When('I open {string} url', async function (url: string) { const urlValue = await getValue(url); await t.navigateTo(urlValue); }); /** * Type text to element * @param {string} alias - element to type * @param {string} value - value to type * @example I type 'wikipedia' to 'Google Input' */ When('I type {string} to {string}', async function (value: string, alias: string) { const element = await getElement(alias); const typeValue = await getValue(value); await t.typeText(element, typeValue); }); /** * Click element * @param {string} alias - element to click * @example I click 'Google Button' */ When('I click {string}', async function (alias: string) { const element = await getElement(alias); await t.click(element); }); /** * Click element via script * @param {string} alias - element to click * @example I force click 'Google Button' */ When('I force click {string}', async function (alias: string) { const element = await getElement(alias); // @ts-ignore await t.eval(() => element().click(), { dependencies: { element } }); }); /** * Right click element * @param {string} alias - element to right click * @example I right click 'Google Button' */ When('I right click {string}', async function (alias: string) { const element = await getElement(alias); await t.rightClick(element); }); /** * Double click element * @param {string} alias - double element to click * @example I double click 'Google Button' */ When('I double click {string}', async function (alias: string) { const element = await getElement(alias); await t.doubleClick(element); }); /** * Clear input * @param {string} alias - element to clear * @example I clear 'Google Input' */ When('I clear {string}', async function (alias: string) { const element = await getElement(alias); await t.selectText(element).pressKey('delete'); }); /** * Switch to parent frame * @example I switch to parent frame */ When('I switch to parent frame', async function () { await t.switchToMainWindow(); }); /** * Switch to frame by index * @param {number} index - index to switch * @example I switch to 2 frame */ When('I switch to {int} frame', async function (index: number) { await t.switchToIframe(Selector('iframe').nth(index - 1)); }); /** * Switch to frame by index * @param {number} index - index to switch * @example I switch to 2 frame */ When('I switch to {string} window', async function (hrefOrTitleKey: string) { const hrefOrTitle = await getValue(hrefOrTitleKey); await t.switchToWindow((win: WindowFilterData) => win.title.includes(hrefOrTitle) || win.url.href.includes(hrefOrTitle) ); }); /** * Refresh current page * @example I refresh page */ When('I refresh page', async function () { await ClientFunction(() => { document.location.reload(); }).with({ boundTestRun: t })(); }); /** * Press button * @param {string} key - key to press * @example I press 'Enter' key * @example I press 'Control+C' keys */ When('I press {string} key(s)', async function (key: string) { const resolvedKey = await getValue(key); await t.pressKey(resolvedKey.toLowerCase()); }); /** * Press button given number of times * @param {string} key - key to press * @param {number} num - number of times * @example I press 'Enter' key 5 times * @example I press 'Control+V' keys 5 times */ When('I press {string} key(s) {int} time(s)', async function (key: string, num: number) { const resolvedKey = await getValue(key) for (let i: number = 0; i < num; i++) { await t.pressKey(resolvedKey.toLowerCase()); } }); /** * Hover over element * @param {string} alias - element to hover over * @example I hover over 'Google Button' */ When('I hover over {string}', async function (alias: string) { const element = await getElement(alias); await t.hover(element); }); /** * Select option with certain text from select element * @param {string} option - option to select * @param {string} alias - alias of select * @example I select '1900' option from 'Registration Form > Date Of Birth' * @example I select '$dateOfBirth' option from 'Registration Form > Date Of Birth' dropdown */ When('I select {string} option from {string} dropdown', async function (option: string, alias: string) { const optionValue = await getValue(option); const select = await getElement(alias); await t .click(select) .click(select.find('option').withText(optionValue)); }); /** * Select option with certain text from select element * @param {number} optionIndex - index of option to select * @param {string} alias - alias of select * @example I select 1 option from 'Registration Form > Date Of Birth' dropdown */ When('I select {int}(st|nd|rd|th) option from {string} dropdown', async function (optionIndex: number, alias: string) { const select = await getElement(alias); await t .click(select) .click(select.find('option').nth(optionIndex - 1)); }); /** * Click on element with desired text in collection * @param {string} expectedText - text to click * @param {string} alias - collection to search text * @example I click 'google' text in 'Search Engines' collection * @example I click '$someVarWithText' text in 'Search Engines' collection */ When( 'I click {string} text in {string} collection', async function (value: string, alias: string) { const resolvedValue = await getValue(value); const collection = await getElement(alias); await t.click(collection.withText(resolvedValue)); } ); /** * Scroll by provided offset * @param {string} - offset string in 'x, y' format * @example * When I scroll by '0, 100' */ When('I scroll by {string}', async function (offset: string) { const [x, y]
= parseCoords(await getValue(offset));
await t.scrollBy(x, y); }); /** * Scroll by provided offset in element * @param {string} - offset string in 'x, y' format * @param {string} - element alias * @example * When I scroll by '0, 100' in 'Overflow Container' */ When('I scroll by {string} in {string}', async function (offset: string, alias: string) { const element = await getElement(alias); const [x, y] = parseCoords(await getValue(offset)); await t.scrollBy(element, x, y); }); /** * Provide file url to upload input * @param {string} alias - element to upload file * @param {string} value - file path * @example I upload '/folder/file.txt' to 'File Input' */ When('I upload {string} file to {string}', async function (value: string, alias: string) { const element = await getElement(alias); const filePath = await getValue(value); await t.setFilesToUpload(element, [filePath]).click(element); }); /** * Set alert handler * @example I will accept alert */ When('I will accept alert', async function () { await t.setNativeDialogHandler(() => true); }); /** * Dismiss alert * testcafe automatically dismisses all dialogs. This step is just to make it implicitly. * @example I will dismiss alert */ When('I will dismiss alert', async function () { await t.setNativeDialogHandler(() => false); }); /** * Type text to prompt * I type {string} to alert * @example I will type 'coffee' to alert */ When('I will type {string} to alert', async function (valueKey: string) { const value = await getValue(valueKey); await t.setNativeDialogHandler(() => value, { dependencies: { value }}); });
src/actions.ts
qavajs-steps-testcafe-b1ff199
[ { "filename": "src/utils/utils.ts", "retrieved_chunk": " * @param {string} coords - 'x, y' string\n * @return {number[]} - coords array\n */\nexport function parseCoords(coords: string): number[] {\n return coords.split(/\\s?,\\s?/).map((c: string) => parseFloat(c ?? 0))\n}\nexport function equalOrIncludes(value: string | string[], argument: string) {\n return Array.isArray(value)\n ? value.includes(argument)\n : value === argument;", "score": 31.084065050575465 }, { "filename": "src/utils/utils.ts", "retrieved_chunk": " return name.replace(/\\W/g, '-')\n}\nexport function traceArchive(driverConfig: any, scenario: ITestCaseHookParameter): string {\n return join(\n driverConfig.trace?.dir ?? 'traces',\n `${normalizeScenarioName(scenario.pickle.name)}-${scenario.testCaseStartedId}.zip`\n )\n}\n/**\n * Parse 'x, y' string to coordinates array", "score": 23.966103902615274 }, { "filename": "src/execute.ts", "retrieved_chunk": " * @example I execute '$fn' function and save result as 'result' // fn is function reference\n * @example I execute 'window.scrollY' function and save result as 'scroll'\n */\nWhen('I execute {string} function and save result as {string}', async function (functionKey, memoryKey) {\n const fnDef = await getValue(functionKey);\n const clientFunction = ClientFunction(resolveFunction(fnDef));\n memory.setValue(memoryKey, await clientFunction.with({ boundTestRun: t })());\n});\n/**\n * Execute client function on certain element", "score": 20.281554509738598 }, { "filename": "src/execute.ts", "retrieved_chunk": "import { When } from '@cucumber/cucumber';\nimport { getValue, getElement } from './transformers';\nimport memory from '@qavajs/memory';\nimport { ClientFunction } from 'testcafe';\nconst resolveFunction = (fnDef: string | Function) => typeof fnDef === 'string' ? eval(`() => ${fnDef}`) : fnDef;\n/**\n * Execute client function\n * @param {string} functionKey - memory key of function\n * @example I execute '$fn' function // fn is function reference\n * @example I execute 'window.scrollBy(0, 100)' function", "score": 18.417109427865224 }, { "filename": "src/poDefine.ts", "retrieved_chunk": " *\n * When I define 'li.selected' as 'Selected Items' collection\n * And I expect number of element in 'Selected Items' collection to equal '3'\n */\nWhen('I define {string} as {string} {testcafePoType}', async function (\n selectorKey: string, aliasKey: string, poType: string\n) {\n const selector = await getValue(selectorKey);\n const alias = (await getValue(aliasKey)).replace(/\\s/g, '');\n const defineElement = poType === 'element' ? $ : $$;", "score": 16.630886569770503 } ]
typescript
= parseCoords(await getValue(offset));
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL
}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 22.99176978730359 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 20.00436282177095 }, { "filename": "src/utils.d.ts", "retrieved_chunk": "export declare const cleanup: (obj: any) => {};\nexport declare function postData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;\n}): Promise<any>;\nexport declare function patchData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;", "score": 16.583760552311066 }, { "filename": "src/utils.ts", "retrieved_chunk": " 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',", "score": 15.802529575491432 }, { "filename": "src/utils.ts", "retrieved_chunk": " method: \"POST\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {", "score": 15.34612854859738 } ]
typescript
}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
import { After, AfterStep, AfterAll, Before, BeforeStep, BeforeAll } from '@cucumber/cucumber'; import defaultTimeouts from './defaultTimeouts'; import { po } from '@qavajs/po-testcafe'; import { saveScreenshotAfterStep, saveScreenshotBeforeStep, takeScreenshot } from './utils/utils'; import createTestCafe from 'testcafe'; import { join } from 'path'; declare global { var t: TestController; var testcafe: TestCafe; var runner: Runner; var taskPromise: any; var config: any; } BeforeAll(async function (){ global.testcafe = await createTestCafe('localhost'); }) Before(async function () { const driverConfig = config.browser ?? config.driver; driverConfig.timeout = { ...defaultTimeouts, ...driverConfig.timeout } global.config.driverConfig = driverConfig; if (!global.t || !config.driverConfig.reuseSession) { global.runner = await testcafe.createRunner(); global.taskPromise = global.runner .src(join(__dirname, 'testController/bootstrap.{ts,js}')) .browsers([config.driverConfig.capabilities.browserName]) .run({ nativeAutomation: config.driverConfig.capabilities.nativeAutomation ?? false }); await new Promise((resolve) => { const interval = setInterval(() => { if (global.t) { clearInterval(interval) resolve(t); } }, 500) }); } po.init({timeout: config.driverConfig.timeout.present}); po.register(config.pageObject); this.log(`browser instance started:\n${JSON.stringify(config.driverConfig, null, 2)}`); }); BeforeStep(async function () { if (saveScreenshotBeforeStep(config)) { try { this.attach(await takeScreenshot(), 'image/png'); } catch (err) { console.warn(err) } } }); AfterStep(async function (step) { try { if
(saveScreenshotAfterStep(config, step)) {
this.attach(await takeScreenshot(), 'image/png'); } } catch (err) { console.warn(err) } }); After(async function (scenario) { if (global.config.driverConfig.reuseSession) { let close = true; while (close) { try { await t.closeWindow(); } catch (err) { close = false } } } if (global.t && !global.config.driverConfig.reuseSession) { await global.taskPromise.cancel(); await global.runner.stop(); // @ts-ignore global.t = null; // @ts-ignore global.runner = null; // @ts-ignore global.taskPromise = null; } }); AfterAll(async function () { await global.testcafe.close(); });
src/hooks.ts
qavajs-steps-testcafe-b1ff199
[ { "filename": "src/utils/utils.ts", "retrieved_chunk": "}\nexport async function throwTimeoutError(fn: Function, message: string) {\n try {\n await fn()\n } catch (err: any) {\n if (err.message.includes('exceeded while waiting on the predicate')) {\n throw new Error(message);\n }\n throw err\n }", "score": 34.00867947863587 }, { "filename": "src/utils/utils.ts", "retrieved_chunk": "import { ScreenshotEvent } from './screenshotEvent';\nimport { TraceEvent } from './traceEvent';\nimport { Status, ITestStepHookParameter, ITestCaseHookParameter } from '@cucumber/cucumber';\nimport { join } from 'path';\nimport { readFile } from 'fs/promises';\nexport function saveScreenshotAfterStep(config: any, step: ITestStepHookParameter): boolean {\n const isAfterStepScreenshot = equalOrIncludes(config.screenshot, ScreenshotEvent.AFTER_STEP);\n const isOnFailScreenshot = equalOrIncludes(config.screenshot, ScreenshotEvent.ON_FAIL);\n return (isOnFailScreenshot && step.result.status === Status.FAILED) || isAfterStepScreenshot\n}", "score": 19.62366635677952 }, { "filename": "src/actions.ts", "retrieved_chunk": " * testcafe automatically dismisses all dialogs. This step is just to make it implicitly.\n * @example I will dismiss alert\n */\nWhen('I will dismiss alert', async function () {\n await t.setNativeDialogHandler(() => false);\n});\n/**\n * Type text to prompt\n * I type {string} to alert\n * @example I will type 'coffee' to alert", "score": 10.696195681699143 }, { "filename": "src/utils/utils.ts", "retrieved_chunk": "}\nexport async function takeScreenshot(): Promise<string> {\n const screenshotPath = await t.takeScreenshot();\n const screenshot = await readFile(screenshotPath);\n return screenshot.toString('base64');\n}\nexport function isChromium(browserName: string): boolean {\n return browserName.includes('chrom')\n}", "score": 10.437884219742902 }, { "filename": "src/validations.ts", "retrieved_chunk": " async function (validationType: string, expected: string) {\n const validation = getValidation(validationType);\n const expectedUrl = await getValue(expected);\n const actualUrl = await ClientFunction(() => window.location.href )\n .with({ boundTestRun: t })();\n this.log(`AR: ${actualUrl}`);\n this.log(`ER: ${expectedUrl}`);\n validation(actualUrl, expectedUrl);\n }\n);", "score": 7.609797775139825 } ]
typescript
(saveScreenshotAfterStep(config, step)) {
import { When } from '@cucumber/cucumber'; import { getValue, getElement, getConditionWait, getValueWait } from './transformers'; import {ClientFunction} from 'testcafe'; /** * Wait for element condition * @param {string} alias - element to wait condition * @param {string} wait - wait condition * @param {number|null} [timeout] - custom timeout in ms * @example I wait until 'Header' to be visible * @example I wait until 'Loading' not to be present * @example I wait until 'Search Bar > Submit Button' to be clickable * @example I wait until 'Search Bar > Submit Button' to be clickable (timeout: 3000) */ When( 'I wait until {string} {testcafeConditionWait}( ){testcafeTimeout}', async function (alias: string, waitType: string, timeout: number | null) { const wait = getConditionWait(waitType); const element = await getElement(alias); await wait(element, timeout ? timeout : config.browser.timeout.page); } ); /** * Wait for element text condition * @param {string} alias - element to wait condition * @param {string} wait - wait condition * @param {string} value - expected value to wait * @param {number|null} [timeout] - custom timeout in ms * @example I wait until text of 'Header' to be equal 'Javascript' * @example I wait until text of 'Header' not to be equal 'Python' * @example I wait until text of 'Header' to be equal 'Javascript' (timeout: 3000) */ When( 'I wait until text of {string} {testcafeValueWait} {string}( ){testcafeTimeout}', async function (alias: string, waitType: string, value: string, timeout: number | null) {
const wait = getValueWait(waitType);
const element = await getElement(alias); const expectedValue = await getValue(value); await wait( element.with({ boundTestRun: t }).innerText, expectedValue, timeout ? timeout : config.browser.timeout.page ); } ); /** * Wait for collection length condition * @param {string} alias - element to wait condition * @param {string} wait - wait condition * @param {string} value - expected value to wait * @param {number|null} [timeout] - custom timeout in ms * @example I wait until number of elements in 'Search Results' collection to be equal '50' * @example I wait until number of elements in 'Search Results' collection to be above '49' * @example I wait until number of elements in 'Search Results' collection to be below '51' * @example I wait until number of elements in 'Search Results' collection to be below '51' (timeout: 3000) */ When( 'I wait until number of elements in {string} collection {testcafeValueWait} {string}( ){testcafeTimeout}', async function (alias: string, waitType: string, value: string, timeout: number | null) { const wait = getValueWait(waitType); const collection = await getElement(alias); const expectedValue = await getValue(value); await wait( collection.with({ boundTestRun: t }).count, parseFloat(expectedValue), timeout ? timeout : config.browser.timeout.page ); } ); /** * Wait for element property condition * @param {string} property - property * @param {string} alias - element to wait condition * @param {string} wait - wait condition * @param {string} value - expected value to wait * @param {number|null} [timeout] - custom timeout in ms * @example I wait until 'value' property of 'Search Input' to be equal 'Javascript' * @example I wait until 'value' property of 'Search Input' to be equal 'Javascript' (timeout: 3000) */ When( 'I wait until {string} property of {string} {testcafeValueWait} {string}( ){testcafeTimeout}', async function (property: string, alias: string, waitType: string, value: string, timeout: number | null) { const propertyName = await getValue(property); const wait = getValueWait(waitType); const element = await getElement(alias); const expectedValue = await getValue(value); // @ts-ignore const getValueFn = element.with({ boundTestRun: t })[propertyName]; await wait(getValueFn, expectedValue, timeout ? timeout : config.browser.timeout.page); } ); /** * Wait for element attribute condition * @param {string} attribute - attribute * @param {string} alias - element to wait condition * @param {string} wait - wait condition * @param {string} value - expected value to wait * @param {number|null} [timeout] - custom timeout in ms * @example I wait until 'href' attribute of 'Home Link' to be equal '/javascript' * @example I wait until 'href' attribute of 'Home Link' to be equal '/javascript' (timeout: 3000) */ When( 'I wait until {string} attribute of {string} {testcafeValueWait} {string}( ){testcafeTimeout}', async function (attribute: string, alias: string, waitType: string, value: string, timeout: number | null) { const attributeName = await getValue(attribute); const wait = getValueWait(waitType); const element = await getElement(alias); const expectedValue = await getValue(value); const getValueFn = element.with({ boundTestRun: t }).getAttribute(attributeName); await wait(getValueFn, expectedValue, timeout ? timeout : config.browser.timeout.page); } ); /** * Wait * @param {number} ms - milliseconds * @example I wait 1000 ms */ When('I wait {int} ms', async function (ms) { await new Promise((resolve: Function): void => { setTimeout(() => resolve(), ms) }); }); /** * Wait for url condition * @param {string} wait - wait condition * @param {string} value - expected value to wait * @param {number|null} [timeout] - custom timeout in ms * @example I wait until current url to be equal 'https://qavajs.github.io/' * @example I wait until current url not to contain 'java' * @example I wait until current url not to contain 'java' (timeout: 3000) */ When( 'I wait until current url {testcafeValueWait} {string}( ){testcafeTimeout}', async function (waitType: string, value: string, timeout: number | null) { const wait = getValueWait(waitType); const expectedValue = await getValue(value); const getValueFn = await ClientFunction(() => window.location.href ) .with({ boundTestRun: t }); await wait(getValueFn(), expectedValue, timeout ? timeout : config.browser.timeout.page); } ); /** * Wait for title condition * @param {string} wait - wait condition * @param {string} value - expected value to wait * @param {number|null} [timeout] - custom timeout in ms * @example I wait until page title to be equal 'qavajs' * @example I wait until page title not to contain 'java' * @example I wait until page title to be equal 'qavajs' (timeout: 3000) */ When( 'I wait until page title {testcafeValueWait} {string}( ){testcafeTimeout}', async function (waitType: string, value: string, timeout: number | null) { const wait = getValueWait(waitType); const expectedValue = await getValue(value); const getValueFn = await ClientFunction(() => window.document.title ) .with({ boundTestRun: t }); await wait(getValueFn(), expectedValue, timeout ? timeout : config.browser.timeout.page); } );
src/waits.ts
qavajs-steps-testcafe-b1ff199
[ { "filename": "src/validations.ts", "retrieved_chunk": " * @example I expect 'Search Bar > Submit Button' to be clickable\n */\nThen('I expect {string} {testcafeConditionWait}', async function (alias: string, condition: string) {\n const element = await getElement(alias);\n const wait = getConditionWait(condition);\n await wait(element, config.browser.timeout.page);\n});\n/**\n * Verify that text of element satisfies condition\n * @param {string} alias - element to get text", "score": 70.02275304233133 }, { "filename": "src/validations.ts", "retrieved_chunk": "import { Then } from '@cucumber/cucumber';\nimport { getValue, getElement, getConditionWait } from './transformers';\nimport { getValidation } from '@qavajs/validation';\nimport { ClientFunction } from 'testcafe';\n/**\n * Verify element condition\n * @param {string} alias - element to wait condition\n * @param {string} condition - wait condition\n * @example I expect 'Header' to be visible\n * @example I expect 'Loading' not to be present", "score": 62.81860575517477 }, { "filename": "src/validations.ts", "retrieved_chunk": " * @param {string} alias - element to verify\n * @param {string} validationType - validation\n * @param {string} value - expected value\n * @example I expect 'value' property of 'Search Input' to be equal 'text'\n * @example I expect 'innerHTML' property of 'Label' to contain '<b>'\n */\nThen(\n 'I expect {string} property of {string} {testcafeValidation} {string}',\n async function (property: string, alias: string, validationType: string, value: string) {\n const propertyName = await getValue(property);", "score": 52.215319377160476 }, { "filename": "src/validations.ts", "retrieved_chunk": "//\n/**\n * Verify that number of element in collection satisfies condition\n * @param {string} alias - collection to verify\n * @param {string} validationType - validation\n * @param {string} value - expected value\n * @example I expect number of elements in 'Search Results' collection to be equal '50'\n * @example I expect number of elements in 'Search Results' collection to be above '49'\n * @example I expect number of elements in 'Search Results' collection to be below '51'\n */", "score": 51.75011269075714 }, { "filename": "src/valueWait.ts", "retrieved_chunk": "/**\n * Wait for condition\n * @param {any} valueFn - function to return value\n * @param {any} expected - expected value\n * @param {string} validationType - validation to perform\n * @param {number} [timeout] - timeout to wait\n * @param {boolean} [reverse] - negate flag\n * @return {Promise<void>}\n */\nexport async function valueWait(", "score": 46.79737494476568 } ]
typescript
const wait = getValueWait(waitType);
import * as path from 'path'; import { SyncHook } from 'tapable'; import { Asset } from './Asset'; import { Compiler, CompilerEvent } from './Compiler'; export type CompilationStats = { /** * The compilation time in milliseconds. */ time: number; /** * A list of asset objects. */ assets: Asset[]; /** * A list of warnings. */ warnings: string[]; /** * A list of errors. */ errors: string[]; }; export type CompilationHooks = { beforeAddAsset: SyncHook<[Asset]>; afterAddAsset: SyncHook<[Asset]>; }; export class Compilation { compiler: Compiler; event: CompilerEvent; assetPaths: Set<string>; assets: Set<Asset>; stats: CompilationStats; hooks: Readonly<CompilationHooks>; /** * Creates an instance of `Compilation`. * * @param compiler The compiler which created the compilation. * @param assetPaths A set of paths to assets that should be compiled. */
constructor(compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) {
this.compiler = compiler; this.event = event; this.assetPaths = assetPaths; this.assets = new Set<Asset>(); this.stats = { time: 0, assets: [], warnings: [], errors: [], }; this.hooks = Object.freeze<CompilationHooks>({ beforeAddAsset: new SyncHook(['asset']), afterAddAsset: new SyncHook(['asset']), }); } create() { const startTime = performance.now(); this.assetPaths.forEach((assetPath) => { const assetType = 'sections'; const sourcePath = { absolute: path.resolve(this.compiler.cwd, assetPath), relative: assetPath, }; const asset = new Asset(assetType, sourcePath, new Set(), this.event); this.hooks.beforeAddAsset.call(asset); this.assets.add(asset); this.stats.assets.push(asset); this.hooks.afterAddAsset.call(asset); }); const endTime = performance.now(); this.stats.time = Number((endTime - startTime).toFixed(2)); } addWarning(warning: string) { this.stats.warnings.push(warning); } addError(error: string) { this.stats.errors.push(error); } }
src/Compilation.ts
unshopable-melter-b347450
[ { "filename": "src/Compiler.ts", "retrieved_chunk": " }\n compile(event: CompilerEvent, assetPaths: Set<string>) {\n this.hooks.beforeCompile.call();\n const compilation = new Compilation(this, event, assetPaths);\n this.hooks.compilation.call(compilation);\n compilation.create();\n this.hooks.afterCompile.call(compilation);\n // If no output directory is specified we do not want to emit assets.\n if (this.config.output) {\n this.hooks.beforeEmit.call(compilation);", "score": 30.044235650334915 }, { "filename": "src/Asset.ts", "retrieved_chunk": " links: Set<Asset>;\n /**\n * The asset's content.\n */\n content: Buffer;\n /**\n * The action that created this asset.\n */\n action: CompilerEvent;\n constructor(type: AssetType, source: AssetPath, links: Set<Asset>, action: CompilerEvent) {", "score": 25.722200484968173 }, { "filename": "src/config/index.ts", "retrieved_chunk": " * Where to write the compiled files to. The emitter won't emit any assets if undefined.\n */\n output: string;\n /**\n * A list of additional plugins to add to the compiler.\n */\n plugins: Plugin[];\n};\nexport const defaultBaseCompilerConfig: BaseCompilerConfig = {\n input: 'src',", "score": 23.96475950972482 }, { "filename": "src/Asset.ts", "retrieved_chunk": " * The absolute and relative path to the asset's file.\n */\n source: AssetPath;\n /**\n * The absolute and relative path to the asset's file.\n */\n target?: AssetPath;\n /**\n * A set of assets the asset is linked with.\n */", "score": 22.96483696511541 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " /**\n * An array of paths pointing to files that should be processed as `config`.\n */\n config?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `layout`.\n */\n layout?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `locales`.", "score": 21.2140533250387 } ]
typescript
constructor(compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) {
import * as path from 'path'; import { SyncHook } from 'tapable'; import { Asset } from './Asset'; import { Compiler, CompilerEvent } from './Compiler'; export type CompilationStats = { /** * The compilation time in milliseconds. */ time: number; /** * A list of asset objects. */ assets: Asset[]; /** * A list of warnings. */ warnings: string[]; /** * A list of errors. */ errors: string[]; }; export type CompilationHooks = { beforeAddAsset: SyncHook<[Asset]>; afterAddAsset: SyncHook<[Asset]>; }; export class Compilation { compiler: Compiler; event: CompilerEvent; assetPaths: Set<string>; assets: Set<Asset>; stats: CompilationStats; hooks: Readonly<CompilationHooks>; /** * Creates an instance of `Compilation`. * * @param compiler The compiler which created the compilation. * @param assetPaths A set of paths to assets that should be compiled. */ constructor(compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) { this.compiler = compiler; this.event = event; this.assetPaths = assetPaths;
this.assets = new Set<Asset>();
this.stats = { time: 0, assets: [], warnings: [], errors: [], }; this.hooks = Object.freeze<CompilationHooks>({ beforeAddAsset: new SyncHook(['asset']), afterAddAsset: new SyncHook(['asset']), }); } create() { const startTime = performance.now(); this.assetPaths.forEach((assetPath) => { const assetType = 'sections'; const sourcePath = { absolute: path.resolve(this.compiler.cwd, assetPath), relative: assetPath, }; const asset = new Asset(assetType, sourcePath, new Set(), this.event); this.hooks.beforeAddAsset.call(asset); this.assets.add(asset); this.stats.assets.push(asset); this.hooks.afterAddAsset.call(asset); }); const endTime = performance.now(); this.stats.time = Number((endTime - startTime).toFixed(2)); } addWarning(warning: string) { this.stats.warnings.push(warning); } addError(error: string) { this.stats.errors.push(error); } }
src/Compilation.ts
unshopable-melter-b347450
[ { "filename": "src/Compiler.ts", "retrieved_chunk": " }\n compile(event: CompilerEvent, assetPaths: Set<string>) {\n this.hooks.beforeCompile.call();\n const compilation = new Compilation(this, event, assetPaths);\n this.hooks.compilation.call(compilation);\n compilation.create();\n this.hooks.afterCompile.call(compilation);\n // If no output directory is specified we do not want to emit assets.\n if (this.config.output) {\n this.hooks.beforeEmit.call(compilation);", "score": 47.46088766854351 }, { "filename": "src/Asset.ts", "retrieved_chunk": " links: Set<Asset>;\n /**\n * The asset's content.\n */\n content: Buffer;\n /**\n * The action that created this asset.\n */\n action: CompilerEvent;\n constructor(type: AssetType, source: AssetPath, links: Set<Asset>, action: CompilerEvent) {", "score": 26.932753749760217 }, { "filename": "src/config/index.ts", "retrieved_chunk": " * Where to write the compiled files to. The emitter won't emit any assets if undefined.\n */\n output: string;\n /**\n * A list of additional plugins to add to the compiler.\n */\n plugins: Plugin[];\n};\nexport const defaultBaseCompilerConfig: BaseCompilerConfig = {\n input: 'src',", "score": 25.896508271270374 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " compiler: Compiler;\n compilation: Compilation;\n hooks: EmitterHooks;\n constructor(compiler: Compiler, compilation: Compilation) {\n this.compiler = compiler;\n this.compilation = compilation;\n this.hooks = {\n beforeAssetAction: new SyncHook(['asset']),\n afterAssetAction: new SyncHook(['asset']),\n };", "score": 24.327974171903534 }, { "filename": "src/Watcher.ts", "retrieved_chunk": " initialAssetPaths: Set<string>;\n constructor(compiler: Compiler, watcherPath: string, watchOptions: WatchOptions) {\n this.compiler = compiler;\n this.watcher = null;\n this.watcherPath = watcherPath;\n this.watchOptions = watchOptions;\n this.initial = true;\n this.initialAssetPaths = new Set<string>();\n }\n start() {", "score": 23.8282978340593 } ]
typescript
this.assets = new Set<Asset>();
import { When } from '@cucumber/cucumber'; import { getValue, getElement } from './transformers'; import { ClientFunction, Selector } from 'testcafe'; import {parseCoords} from './utils/utils'; /** * Opens provided url * @param {string} url - url to navigate * @example I open 'https://google.com' */ When('I open {string} url', async function (url: string) { const urlValue = await getValue(url); await t.navigateTo(urlValue); }); /** * Type text to element * @param {string} alias - element to type * @param {string} value - value to type * @example I type 'wikipedia' to 'Google Input' */ When('I type {string} to {string}', async function (value: string, alias: string) { const element = await getElement(alias); const typeValue = await getValue(value); await t.typeText(element, typeValue); }); /** * Click element * @param {string} alias - element to click * @example I click 'Google Button' */ When('I click {string}', async function (alias: string) { const element = await getElement(alias); await t.click(element); }); /** * Click element via script * @param {string} alias - element to click * @example I force click 'Google Button' */ When('I force click {string}', async function (alias: string) { const element = await getElement(alias); // @ts-ignore await t.eval(() => element().click(), { dependencies: { element } }); }); /** * Right click element * @param {string} alias - element to right click * @example I right click 'Google Button' */ When('I right click {string}', async function (alias: string) { const element = await getElement(alias); await t.rightClick(element); }); /** * Double click element * @param {string} alias - double element to click * @example I double click 'Google Button' */ When('I double click {string}', async function (alias: string) { const element = await getElement(alias); await t.doubleClick(element); }); /** * Clear input * @param {string} alias - element to clear * @example I clear 'Google Input' */ When('I clear {string}', async function (alias: string) { const element = await getElement(alias); await t.selectText(element).pressKey('delete'); }); /** * Switch to parent frame * @example I switch to parent frame */ When('I switch to parent frame', async function () { await t.switchToMainWindow(); }); /** * Switch to frame by index * @param {number} index - index to switch * @example I switch to 2 frame */ When('I switch to {int} frame', async function (index: number) { await t.switchToIframe(Selector('iframe').nth(index - 1)); }); /** * Switch to frame by index * @param {number} index - index to switch * @example I switch to 2 frame */ When('I switch to {string} window', async function (hrefOrTitleKey: string) { const hrefOrTitle = await getValue(hrefOrTitleKey); await t.switchToWindow((win: WindowFilterData) => win.title.includes(hrefOrTitle) || win.url.href.includes(hrefOrTitle) ); }); /** * Refresh current page * @example I refresh page */ When('I refresh page', async function () { await ClientFunction(() => { document.location.reload(); }).with({ boundTestRun: t })(); }); /** * Press button * @param {string} key - key to press * @example I press 'Enter' key * @example I press 'Control+C' keys */ When('I press {string} key(s)', async function (key: string) { const resolvedKey = await getValue(key); await t.pressKey(resolvedKey.toLowerCase()); }); /** * Press button given number of times * @param {string} key - key to press * @param {number} num - number of times * @example I press 'Enter' key 5 times * @example I press 'Control+V' keys 5 times */ When('I press {string} key(s) {int} time(s)', async function (key: string, num: number) { const resolvedKey = await getValue(key) for (let i: number = 0; i < num; i++) { await t.pressKey(resolvedKey.toLowerCase()); } }); /** * Hover over element * @param {string} alias - element to hover over * @example I hover over 'Google Button' */ When('I hover over {string}', async function (alias: string) { const element = await getElement(alias); await t.hover(element); }); /** * Select option with certain text from select element * @param {string} option - option to select * @param {string} alias - alias of select * @example I select '1900' option from 'Registration Form > Date Of Birth' * @example I select '$dateOfBirth' option from 'Registration Form > Date Of Birth' dropdown */ When('I select {string} option from {string} dropdown', async function (option: string, alias: string) { const optionValue = await getValue(option); const select = await getElement(alias); await t .click(select) .click(select.find('option').withText(optionValue)); }); /** * Select option with certain text from select element * @param {number} optionIndex - index of option to select * @param {string} alias - alias of select * @example I select 1 option from 'Registration Form > Date Of Birth' dropdown */ When('I select {int}(st|nd|rd|th) option from {string} dropdown', async function (optionIndex: number, alias: string) { const select = await getElement(alias); await t .click(select) .click(select.find('option').nth(optionIndex - 1)); }); /** * Click on element with desired text in collection * @param {string} expectedText - text to click * @param {string} alias - collection to search text * @example I click 'google' text in 'Search Engines' collection * @example I click '$someVarWithText' text in 'Search Engines' collection */ When( 'I click {string} text in {string} collection', async function (value: string, alias: string) { const resolvedValue = await getValue(value); const collection = await getElement(alias); await t.click(collection.withText(resolvedValue)); } ); /** * Scroll by provided offset * @param {string} - offset string in 'x, y' format * @example * When I scroll by '0, 100' */ When('I scroll by {string}', async function (offset: string) { const [x, y] =
parseCoords(await getValue(offset));
await t.scrollBy(x, y); }); /** * Scroll by provided offset in element * @param {string} - offset string in 'x, y' format * @param {string} - element alias * @example * When I scroll by '0, 100' in 'Overflow Container' */ When('I scroll by {string} in {string}', async function (offset: string, alias: string) { const element = await getElement(alias); const [x, y] = parseCoords(await getValue(offset)); await t.scrollBy(element, x, y); }); /** * Provide file url to upload input * @param {string} alias - element to upload file * @param {string} value - file path * @example I upload '/folder/file.txt' to 'File Input' */ When('I upload {string} file to {string}', async function (value: string, alias: string) { const element = await getElement(alias); const filePath = await getValue(value); await t.setFilesToUpload(element, [filePath]).click(element); }); /** * Set alert handler * @example I will accept alert */ When('I will accept alert', async function () { await t.setNativeDialogHandler(() => true); }); /** * Dismiss alert * testcafe automatically dismisses all dialogs. This step is just to make it implicitly. * @example I will dismiss alert */ When('I will dismiss alert', async function () { await t.setNativeDialogHandler(() => false); }); /** * Type text to prompt * I type {string} to alert * @example I will type 'coffee' to alert */ When('I will type {string} to alert', async function (valueKey: string) { const value = await getValue(valueKey); await t.setNativeDialogHandler(() => value, { dependencies: { value }}); });
src/actions.ts
qavajs-steps-testcafe-b1ff199
[ { "filename": "src/utils/utils.ts", "retrieved_chunk": " * @param {string} coords - 'x, y' string\n * @return {number[]} - coords array\n */\nexport function parseCoords(coords: string): number[] {\n return coords.split(/\\s?,\\s?/).map((c: string) => parseFloat(c ?? 0))\n}\nexport function equalOrIncludes(value: string | string[], argument: string) {\n return Array.isArray(value)\n ? value.includes(argument)\n : value === argument;", "score": 31.084065050575465 }, { "filename": "src/utils/utils.ts", "retrieved_chunk": " return name.replace(/\\W/g, '-')\n}\nexport function traceArchive(driverConfig: any, scenario: ITestCaseHookParameter): string {\n return join(\n driverConfig.trace?.dir ?? 'traces',\n `${normalizeScenarioName(scenario.pickle.name)}-${scenario.testCaseStartedId}.zip`\n )\n}\n/**\n * Parse 'x, y' string to coordinates array", "score": 23.966103902615274 }, { "filename": "src/execute.ts", "retrieved_chunk": " * @example I execute '$fn' function and save result as 'result' // fn is function reference\n * @example I execute 'window.scrollY' function and save result as 'scroll'\n */\nWhen('I execute {string} function and save result as {string}', async function (functionKey, memoryKey) {\n const fnDef = await getValue(functionKey);\n const clientFunction = ClientFunction(resolveFunction(fnDef));\n memory.setValue(memoryKey, await clientFunction.with({ boundTestRun: t })());\n});\n/**\n * Execute client function on certain element", "score": 20.281554509738598 }, { "filename": "src/execute.ts", "retrieved_chunk": "import { When } from '@cucumber/cucumber';\nimport { getValue, getElement } from './transformers';\nimport memory from '@qavajs/memory';\nimport { ClientFunction } from 'testcafe';\nconst resolveFunction = (fnDef: string | Function) => typeof fnDef === 'string' ? eval(`() => ${fnDef}`) : fnDef;\n/**\n * Execute client function\n * @param {string} functionKey - memory key of function\n * @example I execute '$fn' function // fn is function reference\n * @example I execute 'window.scrollBy(0, 100)' function", "score": 18.417109427865224 }, { "filename": "src/poDefine.ts", "retrieved_chunk": " *\n * When I define 'li.selected' as 'Selected Items' collection\n * And I expect number of element in 'Selected Items' collection to equal '3'\n */\nWhen('I define {string} as {string} {testcafePoType}', async function (\n selectorKey: string, aliasKey: string, poType: string\n) {\n const selector = await getValue(selectorKey);\n const alias = (await getValue(aliasKey)).replace(/\\s/g, '');\n const defineElement = poType === 'element' ? $ : $$;", "score": 16.630886569770503 } ]
typescript
parseCoords(await getValue(offset));
import * as path from 'path'; import { Asset, AssetPath, AssetType } from '../Asset'; import { Compiler } from '../Compiler'; import { Emitter } from '../Emitter'; import { Plugin } from '../Plugin'; type Paths = { /** * An array of paths pointing to files that should be processed as `assets`. */ assets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `config`. */ config?: RegExp[]; /** * An array of paths pointing to files that should be processed as `layout`. */ layout?: RegExp[]; /** * An array of paths pointing to files that should be processed as `locales`. */ locales?: RegExp[]; /** * An array of paths pointing to files that should be processed as `sections`. */ sections?: RegExp[]; /** * An array of paths pointing to files that should be processed as `snippets`. */ snippets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `templates`. */ templates?: RegExp[]; }; /** * Path plugin configuration object. */ export type PathsPluginConfig = { /** * A map of Shopify's directory structure and component types. * * @see [Shopify Docs Reference](https://shopify.dev/docs/themes/architecture#directory-structure-and-component-types) */ paths?: Paths | false; }; const defaultPathsPluginConfig: PathsPluginConfig = { paths: { assets: [/assets\/[^\/]*\.*$/], config: [/config\/[^\/]*\.json$/], layout: [/layout\/[^\/]*\.liquid$/], locales: [/locales\/[^\/]*\.json$/], sections: [/sections\/[^\/]*\.liquid$/], snippets: [/snippets\/[^\/]*\.liquid$/], templates: [ /templates\/[^\/]*\.liquid$/, /templates\/[^\/]*\.json$/, /templates\/customers\/[^\/]*\.liquid$/, /templates\/customers\/[^\/]*\.json$/, ], }, }; export class PathsPlugin extends Plugin { config: PathsPluginConfig; constructor(config: PathsPluginConfig) { super(); this.config = config.paths !== false ? { paths: { ...defaultPathsPluginConfig.paths, ...config.paths, }, } : {}; } apply(compiler: Compiler): void { const output = compiler.config.output; if (!output) return; const paths = this.config.paths; if (!paths) return;
compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => {
emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => { const assetType = this.determineAssetType(paths, asset.source.relative); if (!assetType) return; asset.type = assetType; const assetSourcePathParts = asset.source.relative.split('/'); let assetFilename: string = ''; if (assetSourcePathParts.at(-2) === 'customers') { assetFilename = assetSourcePathParts.slice(-2).join('/'); } else { assetFilename = assetSourcePathParts.at(-1)!; } const assetTargetPath = this.resolveAssetTargetPath( compiler.cwd, output, assetType, assetFilename, ); asset.target = assetTargetPath; }); }); } private determineAssetType(paths: Paths, assetPath: string): AssetType | null { const pathEntries = Object.entries(paths); for (let i = 0; i < pathEntries.length; i += 1) { const [name, patterns] = pathEntries[i]; for (let j = 0; j < patterns.length; j++) { if (assetPath.match(patterns[j])) { return name as AssetType; } } } return null; } private resolveAssetTargetPath( cwd: string, output: string, assetType: AssetType, filename: string, ): AssetPath { const relativeAssetTargetPath = path.resolve(output, assetType, filename); const absoluteAssetTargetPath = path.resolve(cwd, relativeAssetTargetPath); return { absolute: absoluteAssetTargetPath, relative: relativeAssetTargetPath, }; } }
src/plugins/PathsPlugin.ts
unshopable-melter-b347450
[ { "filename": "src/config/defaults.ts", "retrieved_chunk": " }),\n new PathsPlugin({\n paths: config.paths,\n }),\n ],\n );\n return plugins;\n}\nexport function applyConfigDefaults(config: MelterConfig): CompilerConfig {\n const compilerConfig = {", "score": 26.8654120404371 }, { "filename": "src/Compiler.ts", "retrieved_chunk": " const emitter = new Emitter(this, compilation);\n this.hooks.emitter.call(emitter);\n emitter.emit();\n this.hooks.afterEmit.call(compilation);\n }\n this.hooks.done.call(compilation.stats);\n }\n close() {\n if (this.watcher) {\n // Close active watcher if compiler has one.", "score": 20.744230295041255 }, { "filename": "src/plugins/StatsPlugin.ts", "retrieved_chunk": " this.config = config;\n }\n apply(compiler: Compiler): void {\n if (this.config.stats === false) return;\n compiler.hooks.done.tap('StatsPlugin', (compilationStats: CompilationStats) => {\n if (compilationStats.errors.length > 0) {\n compiler.logger.error('Compilation failed', compilationStats.errors);\n } else if (compilationStats.warnings.length > 0) {\n compiler.logger.warning(\n `Compiled with ${compilationStats.warnings.length} warnings`,", "score": 20.560037603256472 }, { "filename": "src/config/index.ts", "retrieved_chunk": " * Where to write the compiled files to. The emitter won't emit any assets if undefined.\n */\n output: string;\n /**\n * A list of additional plugins to add to the compiler.\n */\n plugins: Plugin[];\n};\nexport const defaultBaseCompilerConfig: BaseCompilerConfig = {\n input: 'src',", "score": 17.949664863352673 }, { "filename": "src/Compiler.ts", "retrieved_chunk": " }\n compile(event: CompilerEvent, assetPaths: Set<string>) {\n this.hooks.beforeCompile.call();\n const compilation = new Compilation(this, event, assetPaths);\n this.hooks.compilation.call(compilation);\n compilation.create();\n this.hooks.afterCompile.call(compilation);\n // If no output directory is specified we do not want to emit assets.\n if (this.config.output) {\n this.hooks.beforeEmit.call(compilation);", "score": 16.186693424697186 } ]
typescript
compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => {
import { After, AfterStep, AfterAll, Before, BeforeStep, BeforeAll } from '@cucumber/cucumber'; import defaultTimeouts from './defaultTimeouts'; import { po } from '@qavajs/po-testcafe'; import { saveScreenshotAfterStep, saveScreenshotBeforeStep, takeScreenshot } from './utils/utils'; import createTestCafe from 'testcafe'; import { join } from 'path'; declare global { var t: TestController; var testcafe: TestCafe; var runner: Runner; var taskPromise: any; var config: any; } BeforeAll(async function (){ global.testcafe = await createTestCafe('localhost'); }) Before(async function () { const driverConfig = config.browser ?? config.driver; driverConfig.timeout = { ...defaultTimeouts, ...driverConfig.timeout } global.config.driverConfig = driverConfig; if (!global.t || !config.driverConfig.reuseSession) { global.runner = await testcafe.createRunner(); global.taskPromise = global.runner .src(join(__dirname, 'testController/bootstrap.{ts,js}')) .browsers([config.driverConfig.capabilities.browserName]) .run({ nativeAutomation: config.driverConfig.capabilities.nativeAutomation ?? false }); await new Promise((resolve) => { const interval = setInterval(() => { if (global.t) { clearInterval(interval) resolve(t); } }, 500) }); } po.init({timeout: config.driverConfig.timeout.present}); po.register(config.pageObject); this.log(`browser instance started:\n${JSON.stringify(config.driverConfig, null, 2)}`); }); BeforeStep(async function () {
if (saveScreenshotBeforeStep(config)) {
try { this.attach(await takeScreenshot(), 'image/png'); } catch (err) { console.warn(err) } } }); AfterStep(async function (step) { try { if (saveScreenshotAfterStep(config, step)) { this.attach(await takeScreenshot(), 'image/png'); } } catch (err) { console.warn(err) } }); After(async function (scenario) { if (global.config.driverConfig.reuseSession) { let close = true; while (close) { try { await t.closeWindow(); } catch (err) { close = false } } } if (global.t && !global.config.driverConfig.reuseSession) { await global.taskPromise.cancel(); await global.runner.stop(); // @ts-ignore global.t = null; // @ts-ignore global.runner = null; // @ts-ignore global.taskPromise = null; } }); AfterAll(async function () { await global.testcafe.close(); });
src/hooks.ts
qavajs-steps-testcafe-b1ff199
[ { "filename": "src/utils/utils.ts", "retrieved_chunk": "export function saveScreenshotBeforeStep(config: any): boolean {\n return equalOrIncludes(config.screenshot, ScreenshotEvent.BEFORE_STEP)\n}\nexport function saveTrace(driverConfig: any, scenario: ITestCaseHookParameter): boolean {\n return driverConfig?.trace && (\n (equalOrIncludes(driverConfig?.trace.event, TraceEvent.AFTER_SCENARIO)) ||\n (scenario.result?.status === Status.FAILED && equalOrIncludes(driverConfig?.trace.event, TraceEvent.ON_FAIL))\n )\n}\nfunction normalizeScenarioName(name: string): string {", "score": 34.91259578114088 }, { "filename": "src/waits.ts", "retrieved_chunk": " 'I wait until page title {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const expectedValue = await getValue(value);\n const getValueFn = await ClientFunction(() => window.document.title )\n .with({ boundTestRun: t });\n await wait(getValueFn(), expectedValue, timeout ? timeout : config.browser.timeout.page);\n }\n);", "score": 21.021412722456645 }, { "filename": "src/waits.ts", "retrieved_chunk": " timeout ? timeout : config.browser.timeout.page\n );\n }\n);\n/**\n * Wait for collection length condition\n * @param {string} alias - element to wait condition\n * @param {string} wait - wait condition\n * @param {string} value - expected value to wait\n * @param {number|null} [timeout] - custom timeout in ms", "score": 20.916382421508832 }, { "filename": "src/waits.ts", "retrieved_chunk": "When(\n 'I wait until current url {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const expectedValue = await getValue(value);\n const getValueFn = await ClientFunction(() => window.location.href )\n .with({ boundTestRun: t });\n await wait(getValueFn(), expectedValue, timeout ? timeout : config.browser.timeout.page);\n }\n);", "score": 20.836891467632853 }, { "filename": "src/waits.ts", "retrieved_chunk": " const expectedValue = await getValue(value);\n await wait(\n collection.with({ boundTestRun: t }).count,\n parseFloat(expectedValue),\n timeout ? timeout : config.browser.timeout.page\n );\n }\n);\n/**\n * Wait for element property condition", "score": 20.835758128520848 } ]
typescript
if (saveScreenshotBeforeStep(config)) {
import * as path from 'path'; import { SyncHook } from 'tapable'; import { Asset } from './Asset'; import { Compiler, CompilerEvent } from './Compiler'; export type CompilationStats = { /** * The compilation time in milliseconds. */ time: number; /** * A list of asset objects. */ assets: Asset[]; /** * A list of warnings. */ warnings: string[]; /** * A list of errors. */ errors: string[]; }; export type CompilationHooks = { beforeAddAsset: SyncHook<[Asset]>; afterAddAsset: SyncHook<[Asset]>; }; export class Compilation { compiler: Compiler; event: CompilerEvent; assetPaths: Set<string>; assets: Set<Asset>; stats: CompilationStats; hooks: Readonly<CompilationHooks>; /** * Creates an instance of `Compilation`. * * @param compiler The compiler which created the compilation. * @param assetPaths A set of paths to assets that should be compiled. */ constructor(
compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) {
this.compiler = compiler; this.event = event; this.assetPaths = assetPaths; this.assets = new Set<Asset>(); this.stats = { time: 0, assets: [], warnings: [], errors: [], }; this.hooks = Object.freeze<CompilationHooks>({ beforeAddAsset: new SyncHook(['asset']), afterAddAsset: new SyncHook(['asset']), }); } create() { const startTime = performance.now(); this.assetPaths.forEach((assetPath) => { const assetType = 'sections'; const sourcePath = { absolute: path.resolve(this.compiler.cwd, assetPath), relative: assetPath, }; const asset = new Asset(assetType, sourcePath, new Set(), this.event); this.hooks.beforeAddAsset.call(asset); this.assets.add(asset); this.stats.assets.push(asset); this.hooks.afterAddAsset.call(asset); }); const endTime = performance.now(); this.stats.time = Number((endTime - startTime).toFixed(2)); } addWarning(warning: string) { this.stats.warnings.push(warning); } addError(error: string) { this.stats.errors.push(error); } }
src/Compilation.ts
unshopable-melter-b347450
[ { "filename": "src/Compiler.ts", "retrieved_chunk": " }\n compile(event: CompilerEvent, assetPaths: Set<string>) {\n this.hooks.beforeCompile.call();\n const compilation = new Compilation(this, event, assetPaths);\n this.hooks.compilation.call(compilation);\n compilation.create();\n this.hooks.afterCompile.call(compilation);\n // If no output directory is specified we do not want to emit assets.\n if (this.config.output) {\n this.hooks.beforeEmit.call(compilation);", "score": 26.813265643409743 }, { "filename": "src/config/index.ts", "retrieved_chunk": " * Where to write the compiled files to. The emitter won't emit any assets if undefined.\n */\n output: string;\n /**\n * A list of additional plugins to add to the compiler.\n */\n plugins: Plugin[];\n};\nexport const defaultBaseCompilerConfig: BaseCompilerConfig = {\n input: 'src',", "score": 22.17647641873888 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " /**\n * An array of paths pointing to files that should be processed as `config`.\n */\n config?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `layout`.\n */\n layout?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `locales`.", "score": 21.2140533250387 }, { "filename": "src/Asset.ts", "retrieved_chunk": " * The absolute and relative path to the asset's file.\n */\n source: AssetPath;\n /**\n * The absolute and relative path to the asset's file.\n */\n target?: AssetPath;\n /**\n * A set of assets the asset is linked with.\n */", "score": 21.068928031930252 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " */\n locales?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `sections`.\n */\n sections?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `snippets`.\n */\n snippets?: RegExp[];", "score": 19.707939454996495 } ]
typescript
compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) {
import { After, AfterStep, AfterAll, Before, BeforeStep, BeforeAll } from '@cucumber/cucumber'; import defaultTimeouts from './defaultTimeouts'; import { po } from '@qavajs/po-testcafe'; import { saveScreenshotAfterStep, saveScreenshotBeforeStep, takeScreenshot } from './utils/utils'; import createTestCafe from 'testcafe'; import { join } from 'path'; declare global { var t: TestController; var testcafe: TestCafe; var runner: Runner; var taskPromise: any; var config: any; } BeforeAll(async function (){ global.testcafe = await createTestCafe('localhost'); }) Before(async function () { const driverConfig = config.browser ?? config.driver; driverConfig.timeout = { ...defaultTimeouts, ...driverConfig.timeout } global.config.driverConfig = driverConfig; if (!global.t || !config.driverConfig.reuseSession) { global.runner = await testcafe.createRunner(); global.taskPromise = global.runner .src(join(__dirname, 'testController/bootstrap.{ts,js}')) .browsers([config.driverConfig.capabilities.browserName]) .run({ nativeAutomation: config.driverConfig.capabilities.nativeAutomation ?? false }); await new Promise((resolve) => { const interval = setInterval(() => { if (global.t) { clearInterval(interval) resolve(t); } }, 500) }); } po.init({timeout: config.driverConfig.timeout.present}); po.register(config.pageObject); this.log(`browser instance started:\n${JSON.stringify(config.driverConfig, null, 2)}`); }); BeforeStep(async function () { if (saveScreenshotBeforeStep(config)) { try { this.attach(
await takeScreenshot(), 'image/png');
} catch (err) { console.warn(err) } } }); AfterStep(async function (step) { try { if (saveScreenshotAfterStep(config, step)) { this.attach(await takeScreenshot(), 'image/png'); } } catch (err) { console.warn(err) } }); After(async function (scenario) { if (global.config.driverConfig.reuseSession) { let close = true; while (close) { try { await t.closeWindow(); } catch (err) { close = false } } } if (global.t && !global.config.driverConfig.reuseSession) { await global.taskPromise.cancel(); await global.runner.stop(); // @ts-ignore global.t = null; // @ts-ignore global.runner = null; // @ts-ignore global.taskPromise = null; } }); AfterAll(async function () { await global.testcafe.close(); });
src/hooks.ts
qavajs-steps-testcafe-b1ff199
[ { "filename": "src/utils/utils.ts", "retrieved_chunk": "export function saveScreenshotBeforeStep(config: any): boolean {\n return equalOrIncludes(config.screenshot, ScreenshotEvent.BEFORE_STEP)\n}\nexport function saveTrace(driverConfig: any, scenario: ITestCaseHookParameter): boolean {\n return driverConfig?.trace && (\n (equalOrIncludes(driverConfig?.trace.event, TraceEvent.AFTER_SCENARIO)) ||\n (scenario.result?.status === Status.FAILED && equalOrIncludes(driverConfig?.trace.event, TraceEvent.ON_FAIL))\n )\n}\nfunction normalizeScenarioName(name: string): string {", "score": 34.91259578114088 }, { "filename": "src/waits.ts", "retrieved_chunk": " 'I wait until page title {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const expectedValue = await getValue(value);\n const getValueFn = await ClientFunction(() => window.document.title )\n .with({ boundTestRun: t });\n await wait(getValueFn(), expectedValue, timeout ? timeout : config.browser.timeout.page);\n }\n);", "score": 22.552796828644308 }, { "filename": "src/waits.ts", "retrieved_chunk": " const expectedValue = await getValue(value);\n await wait(\n collection.with({ boundTestRun: t }).count,\n parseFloat(expectedValue),\n timeout ? timeout : config.browser.timeout.page\n );\n }\n);\n/**\n * Wait for element property condition", "score": 22.37792554807284 }, { "filename": "src/waits.ts", "retrieved_chunk": "When(\n 'I wait until current url {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const expectedValue = await getValue(value);\n const getValueFn = await ClientFunction(() => window.location.href )\n .with({ boundTestRun: t });\n await wait(getValueFn(), expectedValue, timeout ? timeout : config.browser.timeout.page);\n }\n);", "score": 22.35966036273226 }, { "filename": "src/waits.ts", "retrieved_chunk": " async function (property: string, alias: string, waitType: string, value: string, timeout: number | null) {\n const propertyName = await getValue(property);\n const wait = getValueWait(waitType);\n const element = await getElement(alias);\n const expectedValue = await getValue(value);\n // @ts-ignore\n const getValueFn = element.with({ boundTestRun: t })[propertyName];\n await wait(getValueFn, expectedValue, timeout ? timeout : config.browser.timeout.page);\n }\n);", "score": 21.768792593554863 } ]
typescript
await takeScreenshot(), 'image/png');
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({
url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, });
return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 27.030582679707887 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 21.772222724423578 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 21.363411298224417 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 19.145805258845364 }, { "filename": "src/utils.ts", "retrieved_chunk": " if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;", "score": 19.09125368458794 } ]
typescript
url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, });
import * as path from 'path'; import { Asset, AssetPath, AssetType } from '../Asset'; import { Compiler } from '../Compiler'; import { Emitter } from '../Emitter'; import { Plugin } from '../Plugin'; type Paths = { /** * An array of paths pointing to files that should be processed as `assets`. */ assets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `config`. */ config?: RegExp[]; /** * An array of paths pointing to files that should be processed as `layout`. */ layout?: RegExp[]; /** * An array of paths pointing to files that should be processed as `locales`. */ locales?: RegExp[]; /** * An array of paths pointing to files that should be processed as `sections`. */ sections?: RegExp[]; /** * An array of paths pointing to files that should be processed as `snippets`. */ snippets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `templates`. */ templates?: RegExp[]; }; /** * Path plugin configuration object. */ export type PathsPluginConfig = { /** * A map of Shopify's directory structure and component types. * * @see [Shopify Docs Reference](https://shopify.dev/docs/themes/architecture#directory-structure-and-component-types) */ paths?: Paths | false; }; const defaultPathsPluginConfig: PathsPluginConfig = { paths: { assets: [/assets\/[^\/]*\.*$/], config: [/config\/[^\/]*\.json$/], layout: [/layout\/[^\/]*\.liquid$/], locales: [/locales\/[^\/]*\.json$/], sections: [/sections\/[^\/]*\.liquid$/], snippets: [/snippets\/[^\/]*\.liquid$/], templates: [ /templates\/[^\/]*\.liquid$/, /templates\/[^\/]*\.json$/, /templates\/customers\/[^\/]*\.liquid$/, /templates\/customers\/[^\/]*\.json$/, ], }, }; export class PathsPlugin extends Plugin { config: PathsPluginConfig; constructor(config: PathsPluginConfig) { super(); this.config = config.paths !== false ? { paths: { ...defaultPathsPluginConfig.paths, ...config.paths, }, } : {}; } apply(compiler: Compiler): void { const output = compiler.config.output; if (!output) return; const paths = this.config.paths; if (!paths) return; compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => { emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => { const assetType = this.determineAssetType(paths, asset.source.relative); if (!assetType) return; asset.type = assetType; const assetSourcePathParts = asset.source.relative.split('/'); let assetFilename: string = ''; if (assetSourcePathParts.at(-2) === 'customers') { assetFilename = assetSourcePathParts.slice(-2).join('/'); } else { assetFilename = assetSourcePathParts.at(-1)!; } const assetTargetPath = this.resolveAssetTargetPath( compiler.cwd, output, assetType, assetFilename, ); asset.target = assetTargetPath; }); }); }
private determineAssetType(paths: Paths, assetPath: string): AssetType | null {
const pathEntries = Object.entries(paths); for (let i = 0; i < pathEntries.length; i += 1) { const [name, patterns] = pathEntries[i]; for (let j = 0; j < patterns.length; j++) { if (assetPath.match(patterns[j])) { return name as AssetType; } } } return null; } private resolveAssetTargetPath( cwd: string, output: string, assetType: AssetType, filename: string, ): AssetPath { const relativeAssetTargetPath = path.resolve(output, assetType, filename); const absoluteAssetTargetPath = path.resolve(cwd, relativeAssetTargetPath); return { absolute: absoluteAssetTargetPath, relative: relativeAssetTargetPath, }; } }
src/plugins/PathsPlugin.ts
unshopable-melter-b347450
[ { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 11.513125679864697 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " this.hooks = Object.freeze<CompilationHooks>({\n beforeAddAsset: new SyncHook(['asset']),\n afterAddAsset: new SyncHook(['asset']),\n });\n }\n create() {\n const startTime = performance.now();\n this.assetPaths.forEach((assetPath) => {\n const assetType = 'sections';\n const sourcePath = {", "score": 8.619784318092561 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " case 'update': {\n this.writeFile(asset.target.absolute, asset.content);\n break;\n }\n case 'remove': {\n this.removeFile(asset.target.absolute);\n break;\n }\n // No default.\n }", "score": 7.227137989742742 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " }\n emit() {\n this.compilation.assets.forEach((asset) => {\n this.hooks.beforeAssetAction.call(asset);\n if (typeof asset.target === 'undefined') {\n this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`);\n return;\n }\n switch (asset.action) {\n case 'add':", "score": 6.826677724447855 }, { "filename": "src/Asset.ts", "retrieved_chunk": "export type AssetPath = {\n absolute: string;\n relative: string;\n};\nexport class Asset {\n /**\n * The type of the asset.\n */\n type: AssetType;\n /**", "score": 6.205256901461234 } ]
typescript
private determineAssetType(paths: Paths, assetPath: string): AssetType | null {
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({
url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, });
return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 32.56411641944872 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 29.734605691774256 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 27.339250665167494 }, { "filename": "src/utils.ts", "retrieved_chunk": " url: string;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });", "score": 26.786771875692427 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 26.307526395086494 } ]
typescript
url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, });
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}
${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, });
return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 29.725345071754695 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 25.34078647943461 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 23.438248744230233 }, { "filename": "src/utils.ts", "retrieved_chunk": " url: string;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });", "score": 22.957947645574823 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: response.status,\n message: errorBody.message || 'API request failed',\n };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function patchData({\n url,", "score": 21.363411298224417 } ]
typescript
${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, });
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `
${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 22.99176978730359 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 20.00436282177095 }, { "filename": "src/utils.d.ts", "retrieved_chunk": "export declare const cleanup: (obj: any) => {};\nexport declare function postData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;\n}): Promise<any>;\nexport declare function patchData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;", "score": 16.583760552311066 }, { "filename": "src/utils.ts", "retrieved_chunk": " 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',", "score": 15.802529575491432 }, { "filename": "src/utils.ts", "retrieved_chunk": " method: \"POST\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {", "score": 15.34612854859738 } ]
typescript
${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({
url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 22.99176978730359 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 20.00436282177095 }, { "filename": "src/utils.d.ts", "retrieved_chunk": "export declare const cleanup: (obj: any) => {};\nexport declare function postData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;\n}): Promise<any>;\nexport declare function patchData({ url, body, headers, }: {\n url: string;\n body: any;\n headers?: any;", "score": 16.583760552311066 }, { "filename": "src/utils.ts", "retrieved_chunk": " 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {\n status: response.status,\n message: errorBody.message || 'API request failed',", "score": 15.802529575491432 }, { "filename": "src/utils.ts", "retrieved_chunk": " method: \"POST\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {", "score": 15.34612854859738 } ]
typescript
url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
import { API_URL, API } from './constants'; import { postData, getData, patchData } from './utils'; import { ChargeOptionsType, KeysendOptionsType, ChargeDataResponseType, WalletDataResponseType, BTCUSDDataResponseType, SendPaymentOptionsType, DecodeChargeOptionsType, DecodeChargeResponseType, ProdIPSDataResponseType, StaticChargeOptionsType, KeysendDataResponseType, InternalTransferOptionsType, StaticChargeDataResponseType, WithdrawalRequestOptionsType, SendGamertagPaymentOptionsType, InvoicePaymentDataResponseType, SupportedRegionDataResponseType, InternalTransferDataResponseType, GetWithdrawalRequestDataResponseType, CreateWithdrawalRequestDataResponseType, FetchChargeFromGamertagOptionsType, GamertagTransactionDataResponseType, FetchUserIdByGamertagDataResponseType, FetchGamertagByUserIdDataResponseType, SendLightningAddressPaymentOptionsType, FetchChargeFromGamertagDataResponseType, ValidateLightningAddressDataResponseType, SendLightningAddressPaymentDataResponseType, CreateChargeFromLightningAddressOptionsType, SendGamertagPaymentDataResponseType, FetchChargeFromLightningAddressDataResponseType, } from './types/index'; class zbd { apiBaseUrl: string; apiCoreHeaders: {apikey: string }; constructor(apiKey: string) { this.apiBaseUrl = API_URL; this.apiCoreHeaders = { apikey: apiKey }; } async createCharge(options: ChargeOptionsType) { const { amount, expiresIn, internalId, description, callbackUrl, } = options; const response : ChargeDataResponseType = await postData({ url: `${API_URL}${API.CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, description, callbackUrl, }, }); return response; } async getCharge(chargeId: string) { const response: ChargeDataResponseType = await getData({ url: `${API_URL}${API.CHARGES_ENDPOINT}/${chargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async decodeCharge(options: DecodeChargeOptionsType) { const { invoice } = options; const response: DecodeChargeResponseType = await postData({ url: `${API_URL}${API.DECODE_INVOICE_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { invoice }, }); return response; } async createWithdrawalRequest(options: WithdrawalRequestOptionsType) { const { amount, expiresIn, internalId, callbackUrl, description, } = options; const response : CreateWithdrawalRequestDataResponseType = await postData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, expiresIn, internalId, callbackUrl, description, }, }); return response; } async getWithdrawalRequest(withdrawalRequestId: string) { const response : GetWithdrawalRequestDataResponseType = await getData({ url: `${API_URL}${API.WITHDRAWAL_REQUESTS_ENDPOINT}/${withdrawalRequestId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async validateLightningAddress(lightningAddress: string) { const response : ValidateLightningAddressDataResponseType = await getData({ url: `${API_URL}${API.VALIDATE_LN_ADDRESS_ENDPOINT}/${lightningAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType) { const { amount, comment, lnAddress, internalId, callbackUrl, } = options; const response : SendLightningAddressPaymentDataResponseType = await postData({ url: `${API_URL}${API.SEND_LN_ADDRESS_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, comment, lnAddress, internalId, callbackUrl, }, }); return response; } async createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType) { const { amount, lnaddress, lnAddress, description, } = options; // Addressing issue on ZBD API where it accepts `lnaddress` property // instead of `lnAddress` property as is standardized let lightningAddress = lnaddress || lnAddress; const response: FetchChargeFromLightningAddressDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, description, lnaddress: lightningAddress, }, }); return response; } async getWallet() { const response : WalletDataResponseType = await getData({ url: `${API_URL}${API.WALLET_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async isSupportedRegion(ipAddress: string) { const response : SupportedRegionDataResponseType = await getData({ url: `${API_URL}${API.IS_SUPPORTED_REGION_ENDPOINT}/${ipAddress}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getZBDProdIps() { const response: ProdIPSDataResponseType = await getData({ url: `${API_URL}${API.FETCH_ZBD_PROD_IPS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getBtcUsdExchangeRate() { const response: BTCUSDDataResponseType = await getData({ url: `${API_URL}${API.BTCUSD_PRICE_TICKER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, }); return response; } async internalTransfer(options: InternalTransferOptionsType) { const { amount, receiverWalletId } = options; const response: InternalTransferDataResponseType = await postData({ url: `${API_URL}${API.INTERNAL_TRANSFER_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, receiverWalletId, }, }); return response; } async sendKeysendPayment(options: KeysendOptionsType) { const { amount, pubkey, metadata, tlvRecords, callbackUrl, } = options; const response: KeysendDataResponseType = await postData({ url: `${API_URL}${API.KEYSEND_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, pubkey, metadata, tlvRecords, callbackUrl, }, }); return response; } async sendPayment(options: SendPaymentOptionsType) { const { amount, invoice, internalId, description, callbackUrl, } = options; const response : InvoicePaymentDataResponseType = await postData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, invoice, internalId, description, callbackUrl, }, }); return response; } async getPayment(paymentId: string) { const response = await getData({ url: `${API_URL}${API.PAYMENTS_ENDPOINT}/${paymentId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async sendGamertagPayment(options: SendGamertagPaymentOptionsType) { const { amount, gamertag, description } = options; const response: SendGamertagPaymentDataResponseType = await postData({
url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
amount, gamertag, description, }, }); return response; } async getGamertagTransaction(transactionId: string) { const response: GamertagTransactionDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getUserIdByGamertag(gamertag: string) { const response: FetchUserIdByGamertagDataResponseType = await getData({ url: `${API_URL}${API.GET_USERID_FROM_GAMERTAG_ENDPOINT}/${gamertag}`, headers: { ...this.apiCoreHeaders }, }); return response; } async getGamertagByUserId(userId: string) { const response: FetchGamertagByUserIdDataResponseType = await getData({ url: `${API_URL}${API.GET_GAMERTAG_FROM_USERID_ENDPOINT}/${userId}`, headers: { ...this.apiCoreHeaders }, }); return response; } async createGamertagCharge(options: FetchChargeFromGamertagOptionsType) { const { amount, gamertag, internalId, description, callbackUrl, } = options; const response : FetchChargeFromGamertagDataResponseType = await postData({ url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { amount, gamertag, internalId, description, callbackUrl, }, }); return response; } async createStaticCharge(options: StaticChargeOptionsType) { const { minAmount, maxAmount, internalId, description, callbackUrl, allowedSlots, successMessage, } = options; const response : StaticChargeDataResponseType = await postData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: { minAmount, maxAmount, internalId, callbackUrl, description, allowedSlots, successMessage, }, }); return response; } async updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType) { const response = await patchData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, body: updates, }); return response; } async getStaticCharge(staticChargeId: string) { const response = await getData({ url: `${API_URL}${API.STATIC_CHARGES_ENDPOINT}/${staticChargeId}`, headers: { ...this.apiCoreHeaders }, }); return response; } } export { zbd };
src/zbd.ts
zebedeeio-zbd-node-170d530
[ { "filename": "src/utils.ts", "retrieved_chunk": "export async function postData({\n url,\n body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {", "score": 34.53328706791535 }, { "filename": "src/utils.ts", "retrieved_chunk": " body,\n headers,\n}: {\n url: string;\n body: any;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {", "score": 29.100550202729288 }, { "filename": "src/utils.ts", "retrieved_chunk": " };\n throw error;\n }\n const result = await response.json();\n return result;\n}\nexport async function getData({\n url,\n headers,\n}: {", "score": 27.90282993917545 }, { "filename": "src/utils.ts", "retrieved_chunk": " method: \"POST\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(cleanup(body)),\n });\n if (!response.ok) {\n const errorBody = await response.json();\n const error = {", "score": 24.60924633897227 }, { "filename": "src/utils.ts", "retrieved_chunk": " url: string;\n headers?: any;\n}) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });", "score": 24.202641008852286 } ]
typescript
url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`, headers: { ...this.apiCoreHeaders }, body: {
import * as path from 'path'; import { SyncHook } from 'tapable'; import { Asset } from './Asset'; import { Compiler, CompilerEvent } from './Compiler'; export type CompilationStats = { /** * The compilation time in milliseconds. */ time: number; /** * A list of asset objects. */ assets: Asset[]; /** * A list of warnings. */ warnings: string[]; /** * A list of errors. */ errors: string[]; }; export type CompilationHooks = { beforeAddAsset: SyncHook<[Asset]>; afterAddAsset: SyncHook<[Asset]>; }; export class Compilation { compiler: Compiler; event: CompilerEvent; assetPaths: Set<string>; assets: Set<Asset>; stats: CompilationStats; hooks: Readonly<CompilationHooks>; /** * Creates an instance of `Compilation`. * * @param compiler The compiler which created the compilation. * @param assetPaths A set of paths to assets that should be compiled. */ constructor(compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) { this.compiler = compiler; this.event = event; this.assetPaths = assetPaths; this.assets = new Set<Asset>(); this.stats = { time: 0, assets: [], warnings: [], errors: [], }; this.hooks = Object.freeze<CompilationHooks>({ beforeAddAsset: new SyncHook(['asset']), afterAddAsset: new SyncHook(['asset']), }); } create() { const startTime = performance.now(); this.assetPaths.forEach((assetPath) => { const assetType = 'sections'; const sourcePath = { absolute: path.resolve(this.
compiler.cwd, assetPath), relative: assetPath, };
const asset = new Asset(assetType, sourcePath, new Set(), this.event); this.hooks.beforeAddAsset.call(asset); this.assets.add(asset); this.stats.assets.push(asset); this.hooks.afterAddAsset.call(asset); }); const endTime = performance.now(); this.stats.time = Number((endTime - startTime).toFixed(2)); } addWarning(warning: string) { this.stats.warnings.push(warning); } addError(error: string) { this.stats.errors.push(error); } }
src/Compilation.ts
unshopable-melter-b347450
[ { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " ): AssetPath {\n const relativeAssetTargetPath = path.resolve(output, assetType, filename);\n const absoluteAssetTargetPath = path.resolve(cwd, relativeAssetTargetPath);\n return {\n absolute: absoluteAssetTargetPath,\n relative: relativeAssetTargetPath,\n };\n }\n}", "score": 23.613001304188167 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " });\n });\n }\n private determineAssetType(paths: Paths, assetPath: string): AssetType | null {\n const pathEntries = Object.entries(paths);\n for (let i = 0; i < pathEntries.length; i += 1) {\n const [name, patterns] = pathEntries[i];\n for (let j = 0; j < patterns.length; j++) {\n if (assetPath.match(patterns[j])) {\n return name as AssetType;", "score": 16.735362858920332 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " } else {\n assetFilename = assetSourcePathParts.at(-1)!;\n }\n const assetTargetPath = this.resolveAssetTargetPath(\n compiler.cwd,\n output,\n assetType,\n assetFilename,\n );\n asset.target = assetTargetPath;", "score": 10.637215880795623 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " if (!paths) return;\n compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => {\n emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => {\n const assetType = this.determineAssetType(paths, asset.source.relative);\n if (!assetType) return;\n asset.type = assetType;\n const assetSourcePathParts = asset.source.relative.split('/');\n let assetFilename: string = '';\n if (assetSourcePathParts.at(-2) === 'customers') {\n assetFilename = assetSourcePathParts.slice(-2).join('/');", "score": 10.628517896433008 }, { "filename": "src/Compiler.ts", "retrieved_chunk": " }\n compile(event: CompilerEvent, assetPaths: Set<string>) {\n this.hooks.beforeCompile.call();\n const compilation = new Compilation(this, event, assetPaths);\n this.hooks.compilation.call(compilation);\n compilation.create();\n this.hooks.afterCompile.call(compilation);\n // If no output directory is specified we do not want to emit assets.\n if (this.config.output) {\n this.hooks.beforeEmit.call(compilation);", "score": 9.554312891910882 } ]
typescript
compiler.cwd, assetPath), relative: assetPath, };
import { Controller, Get, Post, Body, Res } from '@nestjs/common'; import { BannerService } from './banner.service'; import { interfaceReturnType } from '../../type/type'; import { Response } from 'express'; @Controller('banner') export class BannerController { constructor(private readonly BannerService: BannerService) {} @Get() async getBannerList(@Res() Res: Response): Promise<interfaceReturnType> { const res = await this.BannerService.listFunc(); Res.status(res.code).json(res); return; } @Post() async postBannerList( @Body() body: any, @Res() Res: Response, ): Promise<interfaceReturnType> { const res = await this.BannerService.addBannerFunc(body); Res.status(res.code).json(res); return; } @Post('update') async updateBannerList( @Body() body: any, @Res() Res: Response, ): Promise<interfaceReturnType> { const res = await this.BannerService.updateBanner(body); Res.status(res.code).json(res); return; } @Post('delete') async deleteBannerList( @Body() body: { id: number }, @Res() Res: Response, ): Promise<interfaceReturnType> {
const res = await this.BannerService.deleteBanner(body);
Res.status(res.code).json(res); return; } // @Post() // async loginFunc(@Body() user: any, @Res() Res: Response): Promise<interfaceReturnType> { // const res = await this.BannerService.listFunc(user); // Res.status(res.code).json(res); // return; // } }
src/api/banner/banner.controller.ts
jiangjin3323-node-nest-api-8cb0076
[ { "filename": "src/api/header/header.controller.ts", "retrieved_chunk": " }\n @Post('delete')\n async deleteHeaderList(\n @Body() body: { id: number },\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.HeaderService.deleteHeader(body);\n Res.status(res.code).json(res);\n return;\n }", "score": 40.60838992286327 }, { "filename": "src/api/product/product.controller.ts", "retrieved_chunk": " return;\n }\n @Post('delete')\n async deleteProductList(\n @Body() body: { id: number },\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.ProductService.deleteProduct(body);\n Res.status(res.code).json(res);\n return;", "score": 40.18639354425979 }, { "filename": "src/api/header/header.controller.ts", "retrieved_chunk": " Res.status(res.code).json(res);\n return;\n }\n @Post()\n async postHeaderList(\n @Body() body: any,\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.HeaderService.addHeaderFunc(body);\n Res.status(res.code).json(res);", "score": 37.0166480731142 }, { "filename": "src/api/product/product.controller.ts", "retrieved_chunk": " Res.status(res.code).json(res);\n return;\n }\n @Post('update')\n async updateProductList(\n @Body() body: any,\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.ProductService.updateProduct(body);\n Res.status(res.code).json(res);", "score": 36.62236733743326 }, { "filename": "src/api/header/header.controller.ts", "retrieved_chunk": " return;\n }\n @Post('update')\n async updateHeaderList(\n @Body() body: any,\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.HeaderService.updateHeader(body);\n Res.status(res.code).json(res);\n return;", "score": 35.4660998628463 } ]
typescript
const res = await this.BannerService.deleteBanner(body);
import { Controller, Get, Post, Body, Res } from '@nestjs/common'; import { HeaderService } from './header.service'; import { interfaceReturnType } from '../../type/type'; import { Response } from 'express'; @Controller('header') export class HeaderController { constructor(private readonly HeaderService: HeaderService) {} @Get() async getHeaderList(@Res() Res: Response): Promise<interfaceReturnType> { const res = await this.HeaderService.listFunc(); Res.status(res.code).json(res); return; } @Post() async postHeaderList( @Body() body: any, @Res() Res: Response, ): Promise<interfaceReturnType> { const res = await this.HeaderService.addHeaderFunc(body); Res.status(res.code).json(res); return; } @Post('update') async updateHeaderList( @Body() body: any, @Res() Res: Response, ): Promise<interfaceReturnType> { const res = await this.HeaderService.updateHeader(body); Res.status(res.code).json(res); return; } @Post('delete') async deleteHeaderList( @Body() body: { id: number }, @Res() Res: Response, ): Promise<interfaceReturnType> {
const res = await this.HeaderService.deleteHeader(body);
Res.status(res.code).json(res); return; } // @Post() // async loginFunc(@Body() user: any, @Res() Res: Response): Promise<interfaceReturnType> { // const res = await this.HeaderService.listFunc(user); // Res.status(res.code).json(res); // return; // } }
src/api/header/header.controller.ts
jiangjin3323-node-nest-api-8cb0076
[ { "filename": "src/api/banner/banner.controller.ts", "retrieved_chunk": " }\n @Post('delete')\n async deleteBannerList(\n @Body() body: { id: number },\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.BannerService.deleteBanner(body);\n Res.status(res.code).json(res);\n return;\n }", "score": 40.60838992286327 }, { "filename": "src/api/product/product.controller.ts", "retrieved_chunk": " return;\n }\n @Post('delete')\n async deleteProductList(\n @Body() body: { id: number },\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.ProductService.deleteProduct(body);\n Res.status(res.code).json(res);\n return;", "score": 40.18639354425979 }, { "filename": "src/api/banner/banner.controller.ts", "retrieved_chunk": " Res.status(res.code).json(res);\n return;\n }\n @Post()\n async postBannerList(\n @Body() body: any,\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.BannerService.addBannerFunc(body);\n Res.status(res.code).json(res);", "score": 37.0166480731142 }, { "filename": "src/api/product/product.controller.ts", "retrieved_chunk": " Res.status(res.code).json(res);\n return;\n }\n @Post('update')\n async updateProductList(\n @Body() body: any,\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.ProductService.updateProduct(body);\n Res.status(res.code).json(res);", "score": 36.62236733743326 }, { "filename": "src/api/banner/banner.controller.ts", "retrieved_chunk": " return;\n }\n @Post('update')\n async updateBannerList(\n @Body() body: any,\n @Res() Res: Response,\n ): Promise<interfaceReturnType> {\n const res = await this.BannerService.updateBanner(body);\n Res.status(res.code).json(res);\n return;", "score": 35.4660998628463 } ]
typescript
const res = await this.HeaderService.deleteHeader(body);
import * as path from 'path'; import { SyncHook } from 'tapable'; import { Asset } from './Asset'; import { Compiler, CompilerEvent } from './Compiler'; export type CompilationStats = { /** * The compilation time in milliseconds. */ time: number; /** * A list of asset objects. */ assets: Asset[]; /** * A list of warnings. */ warnings: string[]; /** * A list of errors. */ errors: string[]; }; export type CompilationHooks = { beforeAddAsset: SyncHook<[Asset]>; afterAddAsset: SyncHook<[Asset]>; }; export class Compilation { compiler: Compiler; event: CompilerEvent; assetPaths: Set<string>; assets: Set<Asset>; stats: CompilationStats; hooks: Readonly<CompilationHooks>; /** * Creates an instance of `Compilation`. * * @param compiler The compiler which created the compilation. * @param assetPaths A set of paths to assets that should be compiled. */ constructor(compiler:
Compiler, event: CompilerEvent, assetPaths: Set<string>) {
this.compiler = compiler; this.event = event; this.assetPaths = assetPaths; this.assets = new Set<Asset>(); this.stats = { time: 0, assets: [], warnings: [], errors: [], }; this.hooks = Object.freeze<CompilationHooks>({ beforeAddAsset: new SyncHook(['asset']), afterAddAsset: new SyncHook(['asset']), }); } create() { const startTime = performance.now(); this.assetPaths.forEach((assetPath) => { const assetType = 'sections'; const sourcePath = { absolute: path.resolve(this.compiler.cwd, assetPath), relative: assetPath, }; const asset = new Asset(assetType, sourcePath, new Set(), this.event); this.hooks.beforeAddAsset.call(asset); this.assets.add(asset); this.stats.assets.push(asset); this.hooks.afterAddAsset.call(asset); }); const endTime = performance.now(); this.stats.time = Number((endTime - startTime).toFixed(2)); } addWarning(warning: string) { this.stats.warnings.push(warning); } addError(error: string) { this.stats.errors.push(error); } }
src/Compilation.ts
unshopable-melter-b347450
[ { "filename": "src/Compiler.ts", "retrieved_chunk": " }\n compile(event: CompilerEvent, assetPaths: Set<string>) {\n this.hooks.beforeCompile.call();\n const compilation = new Compilation(this, event, assetPaths);\n this.hooks.compilation.call(compilation);\n compilation.create();\n this.hooks.afterCompile.call(compilation);\n // If no output directory is specified we do not want to emit assets.\n if (this.config.output) {\n this.hooks.beforeEmit.call(compilation);", "score": 26.813265643409743 }, { "filename": "src/config/index.ts", "retrieved_chunk": " * Where to write the compiled files to. The emitter won't emit any assets if undefined.\n */\n output: string;\n /**\n * A list of additional plugins to add to the compiler.\n */\n plugins: Plugin[];\n};\nexport const defaultBaseCompilerConfig: BaseCompilerConfig = {\n input: 'src',", "score": 22.17647641873888 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " /**\n * An array of paths pointing to files that should be processed as `config`.\n */\n config?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `layout`.\n */\n layout?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `locales`.", "score": 21.2140533250387 }, { "filename": "src/Asset.ts", "retrieved_chunk": " * The absolute and relative path to the asset's file.\n */\n source: AssetPath;\n /**\n * The absolute and relative path to the asset's file.\n */\n target?: AssetPath;\n /**\n * A set of assets the asset is linked with.\n */", "score": 21.068928031930252 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " */\n locales?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `sections`.\n */\n sections?: RegExp[];\n /**\n * An array of paths pointing to files that should be processed as `snippets`.\n */\n snippets?: RegExp[];", "score": 19.707939454996495 } ]
typescript
Compiler, event: CompilerEvent, assetPaths: Set<string>) {
import * as path from 'path'; import { SyncHook } from 'tapable'; import { Asset } from './Asset'; import { Compiler, CompilerEvent } from './Compiler'; export type CompilationStats = { /** * The compilation time in milliseconds. */ time: number; /** * A list of asset objects. */ assets: Asset[]; /** * A list of warnings. */ warnings: string[]; /** * A list of errors. */ errors: string[]; }; export type CompilationHooks = { beforeAddAsset: SyncHook<[Asset]>; afterAddAsset: SyncHook<[Asset]>; }; export class Compilation { compiler: Compiler; event: CompilerEvent; assetPaths: Set<string>; assets: Set<Asset>; stats: CompilationStats; hooks: Readonly<CompilationHooks>; /** * Creates an instance of `Compilation`. * * @param compiler The compiler which created the compilation. * @param assetPaths A set of paths to assets that should be compiled. */ constructor(compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) { this.compiler = compiler; this.event = event; this.assetPaths = assetPaths; this.assets = new Set<Asset>(); this.stats = { time: 0, assets: [], warnings: [], errors: [], }; this.hooks = Object.freeze<CompilationHooks>({ beforeAddAsset: new SyncHook(['asset']), afterAddAsset: new SyncHook(['asset']), }); } create() { const startTime = performance.now(); this.assetPaths.forEach((assetPath) => { const assetType = 'sections'; const sourcePath = { absolute: path.resolve(this.compiler.cwd, assetPath), relative: assetPath, };
const asset = new Asset(assetType, sourcePath, new Set(), this.event);
this.hooks.beforeAddAsset.call(asset); this.assets.add(asset); this.stats.assets.push(asset); this.hooks.afterAddAsset.call(asset); }); const endTime = performance.now(); this.stats.time = Number((endTime - startTime).toFixed(2)); } addWarning(warning: string) { this.stats.warnings.push(warning); } addError(error: string) { this.stats.errors.push(error); } }
src/Compilation.ts
unshopable-melter-b347450
[ { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " ): AssetPath {\n const relativeAssetTargetPath = path.resolve(output, assetType, filename);\n const absoluteAssetTargetPath = path.resolve(cwd, relativeAssetTargetPath);\n return {\n absolute: absoluteAssetTargetPath,\n relative: relativeAssetTargetPath,\n };\n }\n}", "score": 28.074938101437784 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " if (!paths) return;\n compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => {\n emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => {\n const assetType = this.determineAssetType(paths, asset.source.relative);\n if (!assetType) return;\n asset.type = assetType;\n const assetSourcePathParts = asset.source.relative.split('/');\n let assetFilename: string = '';\n if (assetSourcePathParts.at(-2) === 'customers') {\n assetFilename = assetSourcePathParts.slice(-2).join('/');", "score": 19.693675112410133 }, { "filename": "src/Compiler.ts", "retrieved_chunk": " }\n compile(event: CompilerEvent, assetPaths: Set<string>) {\n this.hooks.beforeCompile.call();\n const compilation = new Compilation(this, event, assetPaths);\n this.hooks.compilation.call(compilation);\n compilation.create();\n this.hooks.afterCompile.call(compilation);\n // If no output directory is specified we do not want to emit assets.\n if (this.config.output) {\n this.hooks.beforeEmit.call(compilation);", "score": 18.67492024039027 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " });\n });\n }\n private determineAssetType(paths: Paths, assetPath: string): AssetType | null {\n const pathEntries = Object.entries(paths);\n for (let i = 0; i < pathEntries.length; i += 1) {\n const [name, patterns] = pathEntries[i];\n for (let j = 0; j < patterns.length; j++) {\n if (assetPath.match(patterns[j])) {\n return name as AssetType;", "score": 17.799577348040977 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " } else {\n assetFilename = assetSourcePathParts.at(-1)!;\n }\n const assetTargetPath = this.resolveAssetTargetPath(\n compiler.cwd,\n output,\n assetType,\n assetFilename,\n );\n asset.target = assetTargetPath;", "score": 17.416286197750303 } ]
typescript
const asset = new Asset(assetType, sourcePath, new Set(), this.event);
import { SyncHook } from 'tapable'; import { Compilation, CompilationStats } from './Compilation'; import { Emitter } from './Emitter'; import { Logger } from './Logger'; import { Watcher } from './Watcher'; import { CompilerConfig } from './config'; export type CompilerHooks = { beforeCompile: SyncHook<[]>; compilation: SyncHook<[Compilation]>; afterCompile: SyncHook<[Compilation]>; beforeEmit: SyncHook<[Compilation]>; emitter: SyncHook<[Emitter]>; afterEmit: SyncHook<[Compilation]>; done: SyncHook<[CompilationStats]>; watcherStart: SyncHook<[]>; watcherClose: SyncHook<[]>; }; export type CompilerEvent = 'add' | 'update' | 'remove'; export class Compiler { cwd: Readonly<string>; config: Readonly<CompilerConfig>; hooks: Readonly<CompilerHooks>; watcher: Readonly<Watcher | null>; logger: Readonly<Logger>; constructor(config: CompilerConfig) { this.cwd = process.cwd(); this.config = config; this.hooks = Object.freeze<CompilerHooks>({ beforeCompile: new SyncHook(), compilation: new SyncHook(['compilation']), afterCompile: new SyncHook(['compilation']), beforeEmit: new SyncHook(['compilation']), emitter: new SyncHook(['emitter']), afterEmit: new SyncHook(['compilation']), done: new SyncHook(['stats']), watcherStart: new SyncHook(), watcherClose: new SyncHook(), }); this.watcher = null; this.logger = new Logger(); } build() {
const watcher = new Watcher(this, this.config.input, {
cwd: this.cwd, // Trigger build. ignoreInitial: false, // Do not listen for changes. persistent: false, }); watcher.start(); } watch() { this.watcher = new Watcher(this, this.config.input, { cwd: this.cwd, // Trigger an initial build. ignoreInitial: false, // Continously watch for changes. persistent: true, }); this.watcher.start(); } compile(event: CompilerEvent, assetPaths: Set<string>) { this.hooks.beforeCompile.call(); const compilation = new Compilation(this, event, assetPaths); this.hooks.compilation.call(compilation); compilation.create(); this.hooks.afterCompile.call(compilation); // If no output directory is specified we do not want to emit assets. if (this.config.output) { this.hooks.beforeEmit.call(compilation); const emitter = new Emitter(this, compilation); this.hooks.emitter.call(emitter); emitter.emit(); this.hooks.afterEmit.call(compilation); } this.hooks.done.call(compilation.stats); } close() { if (this.watcher) { // Close active watcher if compiler has one. this.watcher.close(); } process.exit(); } }
src/Compiler.ts
unshopable-melter-b347450
[ { "filename": "src/Emitter.ts", "retrieved_chunk": " compiler: Compiler;\n compilation: Compilation;\n hooks: EmitterHooks;\n constructor(compiler: Compiler, compilation: Compilation) {\n this.compiler = compiler;\n this.compilation = compilation;\n this.hooks = {\n beforeAssetAction: new SyncHook(['asset']),\n afterAssetAction: new SyncHook(['asset']),\n };", "score": 35.07160837220013 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " this.hooks = Object.freeze<CompilationHooks>({\n beforeAddAsset: new SyncHook(['asset']),\n afterAddAsset: new SyncHook(['asset']),\n });\n }\n create() {\n const startTime = performance.now();\n this.assetPaths.forEach((assetPath) => {\n const assetType = 'sections';\n const sourcePath = {", "score": 32.17724315343786 }, { "filename": "src/Watcher.ts", "retrieved_chunk": " }\n this.compiler.compile('add', new Set([path]));\n });\n this.watcher.on('change', (path: string, stats: fs.Stats) => {\n this.compiler.compile('update', new Set([path]));\n });\n this.watcher.on('unlink', (path: string, stats: fs.Stats) => {\n this.compiler.compile('remove', new Set([path]));\n });\n this.watcher.on('ready', () => {", "score": 26.99132933700818 }, { "filename": "src/Watcher.ts", "retrieved_chunk": " initialAssetPaths: Set<string>;\n constructor(compiler: Compiler, watcherPath: string, watchOptions: WatchOptions) {\n this.compiler = compiler;\n this.watcher = null;\n this.watcherPath = watcherPath;\n this.watchOptions = watchOptions;\n this.initial = true;\n this.initialAssetPaths = new Set<string>();\n }\n start() {", "score": 19.265148807159854 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 18.086622611171467 } ]
typescript
const watcher = new Watcher(this, this.config.input, {
import { SyncHook } from 'tapable'; import { Compilation, CompilationStats } from './Compilation'; import { Emitter } from './Emitter'; import { Logger } from './Logger'; import { Watcher } from './Watcher'; import { CompilerConfig } from './config'; export type CompilerHooks = { beforeCompile: SyncHook<[]>; compilation: SyncHook<[Compilation]>; afterCompile: SyncHook<[Compilation]>; beforeEmit: SyncHook<[Compilation]>; emitter: SyncHook<[Emitter]>; afterEmit: SyncHook<[Compilation]>; done: SyncHook<[CompilationStats]>; watcherStart: SyncHook<[]>; watcherClose: SyncHook<[]>; }; export type CompilerEvent = 'add' | 'update' | 'remove'; export class Compiler { cwd: Readonly<string>; config: Readonly<CompilerConfig>; hooks: Readonly<CompilerHooks>; watcher: Readonly<Watcher | null>; logger: Readonly<Logger>; constructor(config: CompilerConfig) { this.cwd = process.cwd(); this.config = config; this.hooks = Object.freeze<CompilerHooks>({ beforeCompile: new SyncHook(), compilation: new SyncHook(['compilation']), afterCompile: new SyncHook(['compilation']), beforeEmit: new SyncHook(['compilation']), emitter: new SyncHook(['emitter']), afterEmit: new SyncHook(['compilation']), done: new SyncHook(['stats']), watcherStart: new SyncHook(), watcherClose: new SyncHook(), }); this.watcher = null; this.logger = new Logger(); } build() { const watcher = new Watcher(this, this.config.input, { cwd: this.cwd, // Trigger build. ignoreInitial: false, // Do not listen for changes. persistent: false, }); watcher.start(); } watch() { this.watcher = new Watcher(this, this.config.input, { cwd: this.cwd, // Trigger an initial build. ignoreInitial: false, // Continously watch for changes. persistent: true, }); this.watcher.start(); } compile(event: CompilerEvent, assetPaths: Set<string>) { this.hooks.beforeCompile.call(); const compilation = new Compilation(this, event, assetPaths); this.hooks.compilation.call(compilation);
compilation.create();
this.hooks.afterCompile.call(compilation); // If no output directory is specified we do not want to emit assets. if (this.config.output) { this.hooks.beforeEmit.call(compilation); const emitter = new Emitter(this, compilation); this.hooks.emitter.call(emitter); emitter.emit(); this.hooks.afterEmit.call(compilation); } this.hooks.done.call(compilation.stats); } close() { if (this.watcher) { // Close active watcher if compiler has one. this.watcher.close(); } process.exit(); } }
src/Compiler.ts
unshopable-melter-b347450
[ { "filename": "src/Emitter.ts", "retrieved_chunk": " compiler: Compiler;\n compilation: Compilation;\n hooks: EmitterHooks;\n constructor(compiler: Compiler, compilation: Compilation) {\n this.compiler = compiler;\n this.compilation = compilation;\n this.hooks = {\n beforeAssetAction: new SyncHook(['asset']),\n afterAssetAction: new SyncHook(['asset']),\n };", "score": 29.249123427177903 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " assets: Set<Asset>;\n stats: CompilationStats;\n hooks: Readonly<CompilationHooks>;\n /**\n * Creates an instance of `Compilation`.\n *\n * @param compiler The compiler which created the compilation.\n * @param assetPaths A set of paths to assets that should be compiled.\n */\n constructor(compiler: Compiler, event: CompilerEvent, assetPaths: Set<string>) {", "score": 26.940933167628792 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " this.compiler = compiler;\n this.event = event;\n this.assetPaths = assetPaths;\n this.assets = new Set<Asset>();\n this.stats = {\n time: 0,\n assets: [],\n warnings: [],\n errors: [],\n };", "score": 23.759894014877258 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " }\n emit() {\n this.compilation.assets.forEach((asset) => {\n this.hooks.beforeAssetAction.call(asset);\n if (typeof asset.target === 'undefined') {\n this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`);\n return;\n }\n switch (asset.action) {\n case 'add':", "score": 22.659266607010604 }, { "filename": "src/Watcher.ts", "retrieved_chunk": " if (this.watchOptions.persistent) {\n // Chokidar is not really watching without `persistent` being `true` so we do not want\n // to call the `watcherStart` hook in this case.\n this.compiler.hooks.watcherStart.call();\n }\n this.watcher = chokidar.watch(this.watcherPath, this.watchOptions);\n this.watcher.on('add', (path: string, stats: fs.Stats) => {\n if (this.initial) {\n this.initialAssetPaths.add(path);\n return;", "score": 22.537719538968673 } ]
typescript
compilation.create();
import { SyncHook } from 'tapable'; import { Compilation, CompilationStats } from './Compilation'; import { Emitter } from './Emitter'; import { Logger } from './Logger'; import { Watcher } from './Watcher'; import { CompilerConfig } from './config'; export type CompilerHooks = { beforeCompile: SyncHook<[]>; compilation: SyncHook<[Compilation]>; afterCompile: SyncHook<[Compilation]>; beforeEmit: SyncHook<[Compilation]>; emitter: SyncHook<[Emitter]>; afterEmit: SyncHook<[Compilation]>; done: SyncHook<[CompilationStats]>; watcherStart: SyncHook<[]>; watcherClose: SyncHook<[]>; }; export type CompilerEvent = 'add' | 'update' | 'remove'; export class Compiler { cwd: Readonly<string>; config: Readonly<CompilerConfig>; hooks: Readonly<CompilerHooks>; watcher: Readonly<Watcher | null>; logger: Readonly<Logger>; constructor(config: CompilerConfig) { this.cwd = process.cwd(); this.config = config; this.hooks = Object.freeze<CompilerHooks>({ beforeCompile: new SyncHook(), compilation: new SyncHook(['compilation']), afterCompile: new SyncHook(['compilation']), beforeEmit: new SyncHook(['compilation']), emitter: new SyncHook(['emitter']), afterEmit: new SyncHook(['compilation']), done: new SyncHook(['stats']), watcherStart: new SyncHook(), watcherClose: new SyncHook(), }); this.watcher = null; this.logger = new Logger(); } build() { const watcher = new Watcher(this, this.config.input, { cwd: this.cwd, // Trigger build. ignoreInitial: false, // Do not listen for changes. persistent: false, }); watcher.start(); } watch() { this.watcher = new Watcher(this, this.config.input, { cwd: this.cwd, // Trigger an initial build. ignoreInitial: false, // Continously watch for changes. persistent: true, }); this.watcher.start(); } compile(event: CompilerEvent, assetPaths: Set<string>) { this.hooks.beforeCompile.call(); const compilation = new Compilation(this, event, assetPaths); this.hooks.compilation.call(compilation); compilation.create(); this.hooks.afterCompile.call(compilation); // If no output directory is specified we do not want to emit assets. if (this.config.output) { this.hooks.beforeEmit.call(compilation); const emitter = new Emitter(this, compilation); this.hooks.emitter.call(emitter); emitter.emit(); this.hooks.afterEmit.call(compilation); } this.hooks.
done.call(compilation.stats);
} close() { if (this.watcher) { // Close active watcher if compiler has one. this.watcher.close(); } process.exit(); } }
src/Compiler.ts
unshopable-melter-b347450
[ { "filename": "src/Emitter.ts", "retrieved_chunk": " }\n emit() {\n this.compilation.assets.forEach((asset) => {\n this.hooks.beforeAssetAction.call(asset);\n if (typeof asset.target === 'undefined') {\n this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`);\n return;\n }\n switch (asset.action) {\n case 'add':", "score": 40.48812535062363 }, { "filename": "src/Watcher.ts", "retrieved_chunk": " if (this.watchOptions.persistent) {\n // Chokidar is not really watching without `persistent` being `true` so we do not want\n // to call the `watcherStart` hook in this case.\n this.compiler.hooks.watcherStart.call();\n }\n this.watcher = chokidar.watch(this.watcherPath, this.watchOptions);\n this.watcher.on('add', (path: string, stats: fs.Stats) => {\n if (this.initial) {\n this.initialAssetPaths.add(path);\n return;", "score": 37.07338894720489 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " compiler: Compiler;\n compilation: Compilation;\n hooks: EmitterHooks;\n constructor(compiler: Compiler, compilation: Compilation) {\n this.compiler = compiler;\n this.compilation = compilation;\n this.hooks = {\n beforeAssetAction: new SyncHook(['asset']),\n afterAssetAction: new SyncHook(['asset']),\n };", "score": 32.61279650807242 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " if (!paths) return;\n compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => {\n emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => {\n const assetType = this.determineAssetType(paths, asset.source.relative);\n if (!assetType) return;\n asset.type = assetType;\n const assetSourcePathParts = asset.source.relative.split('/');\n let assetFilename: string = '';\n if (assetSourcePathParts.at(-2) === 'customers') {\n assetFilename = assetSourcePathParts.slice(-2).join('/');", "score": 31.809650518444723 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 31.414885697339276 } ]
typescript
done.call(compilation.stats);
import { SyncHook } from 'tapable'; import { Compilation, CompilationStats } from './Compilation'; import { Emitter } from './Emitter'; import { Logger } from './Logger'; import { Watcher } from './Watcher'; import { CompilerConfig } from './config'; export type CompilerHooks = { beforeCompile: SyncHook<[]>; compilation: SyncHook<[Compilation]>; afterCompile: SyncHook<[Compilation]>; beforeEmit: SyncHook<[Compilation]>; emitter: SyncHook<[Emitter]>; afterEmit: SyncHook<[Compilation]>; done: SyncHook<[CompilationStats]>; watcherStart: SyncHook<[]>; watcherClose: SyncHook<[]>; }; export type CompilerEvent = 'add' | 'update' | 'remove'; export class Compiler { cwd: Readonly<string>; config: Readonly<CompilerConfig>; hooks: Readonly<CompilerHooks>; watcher: Readonly<Watcher | null>; logger: Readonly<Logger>; constructor(config: CompilerConfig) { this.cwd = process.cwd(); this.config = config; this.hooks = Object.freeze<CompilerHooks>({ beforeCompile: new SyncHook(), compilation: new SyncHook(['compilation']), afterCompile: new SyncHook(['compilation']), beforeEmit: new SyncHook(['compilation']), emitter: new SyncHook(['emitter']), afterEmit: new SyncHook(['compilation']), done: new SyncHook(['stats']), watcherStart: new SyncHook(), watcherClose: new SyncHook(), }); this.watcher = null; this.logger = new Logger(); } build() { const watcher = new Watcher(this, this.config.input, { cwd: this.cwd, // Trigger build. ignoreInitial: false, // Do not listen for changes. persistent: false, }); watcher.start(); } watch() { this.watcher = new Watcher(this, this.config.input, { cwd: this.cwd, // Trigger an initial build. ignoreInitial: false, // Continously watch for changes. persistent: true, }); this.watcher.start(); } compile(event: CompilerEvent, assetPaths: Set<string>) { this.hooks.beforeCompile.call(); const compilation = new Compilation(this, event, assetPaths); this.hooks.compilation.call(compilation); compilation.create(); this.hooks.afterCompile.call(compilation); // If no output directory is specified we do not want to emit assets. if (this.config.output) { this.hooks.beforeEmit.call(compilation); const emitter = new Emitter
(this, compilation);
this.hooks.emitter.call(emitter); emitter.emit(); this.hooks.afterEmit.call(compilation); } this.hooks.done.call(compilation.stats); } close() { if (this.watcher) { // Close active watcher if compiler has one. this.watcher.close(); } process.exit(); } }
src/Compiler.ts
unshopable-melter-b347450
[ { "filename": "src/Emitter.ts", "retrieved_chunk": " compiler: Compiler;\n compilation: Compilation;\n hooks: EmitterHooks;\n constructor(compiler: Compiler, compilation: Compilation) {\n this.compiler = compiler;\n this.compilation = compilation;\n this.hooks = {\n beforeAssetAction: new SyncHook(['asset']),\n afterAssetAction: new SyncHook(['asset']),\n };", "score": 50.76920886204938 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " }\n emit() {\n this.compilation.assets.forEach((asset) => {\n this.hooks.beforeAssetAction.call(asset);\n if (typeof asset.target === 'undefined') {\n this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`);\n return;\n }\n switch (asset.action) {\n case 'add':", "score": 47.25483640811281 }, { "filename": "src/Watcher.ts", "retrieved_chunk": " if (this.watchOptions.persistent) {\n // Chokidar is not really watching without `persistent` being `true` so we do not want\n // to call the `watcherStart` hook in this case.\n this.compiler.hooks.watcherStart.call();\n }\n this.watcher = chokidar.watch(this.watcherPath, this.watchOptions);\n this.watcher.on('add', (path: string, stats: fs.Stats) => {\n if (this.initial) {\n this.initialAssetPaths.add(path);\n return;", "score": 36.76108853628624 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 36.093576314115715 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " this.hooks.afterAssetAction.call(asset);\n });\n }\n private writeFile(targetPath: AssetPath['absolute'], content: Asset['content']) {\n try {\n fs.ensureFileSync(targetPath);\n fs.writeFileSync(targetPath, content);\n } catch (error: any) {\n this.compilation.addError(error.message);\n }", "score": 35.22713290389156 } ]
typescript
(this, compilation);
import { SyncHook } from 'tapable'; import { Compilation, CompilationStats } from './Compilation'; import { Emitter } from './Emitter'; import { Logger } from './Logger'; import { Watcher } from './Watcher'; import { CompilerConfig } from './config'; export type CompilerHooks = { beforeCompile: SyncHook<[]>; compilation: SyncHook<[Compilation]>; afterCompile: SyncHook<[Compilation]>; beforeEmit: SyncHook<[Compilation]>; emitter: SyncHook<[Emitter]>; afterEmit: SyncHook<[Compilation]>; done: SyncHook<[CompilationStats]>; watcherStart: SyncHook<[]>; watcherClose: SyncHook<[]>; }; export type CompilerEvent = 'add' | 'update' | 'remove'; export class Compiler { cwd: Readonly<string>; config: Readonly<CompilerConfig>; hooks: Readonly<CompilerHooks>; watcher: Readonly<Watcher | null>; logger: Readonly<Logger>; constructor(config: CompilerConfig) { this.cwd = process.cwd(); this.config = config; this.hooks = Object.freeze<CompilerHooks>({ beforeCompile: new SyncHook(), compilation: new SyncHook(['compilation']), afterCompile: new SyncHook(['compilation']), beforeEmit: new SyncHook(['compilation']), emitter: new SyncHook(['emitter']), afterEmit: new SyncHook(['compilation']), done: new SyncHook(['stats']), watcherStart: new SyncHook(), watcherClose: new SyncHook(), }); this.watcher = null; this.logger = new Logger(); } build() { const watcher = new Watcher(this, this.config.input, { cwd: this.cwd, // Trigger build. ignoreInitial: false, // Do not listen for changes. persistent: false, }); watcher.start(); } watch() { this.watcher = new Watcher(this, this.config.input, { cwd: this.cwd, // Trigger an initial build. ignoreInitial: false, // Continously watch for changes. persistent: true, }); this.watcher.start(); } compile(event: CompilerEvent, assetPaths: Set<string>) { this.hooks.beforeCompile.call(); const compilation = new Compilation(this, event, assetPaths); this.hooks.compilation.call(compilation); compilation.create(); this.hooks.afterCompile.call(compilation); // If no output directory is specified we do not want to emit assets. if (this.config.output) { this.hooks.beforeEmit.call(compilation); const emitter = new Emitter(this, compilation); this.hooks.emitter.call(emitter);
emitter.emit();
this.hooks.afterEmit.call(compilation); } this.hooks.done.call(compilation.stats); } close() { if (this.watcher) { // Close active watcher if compiler has one. this.watcher.close(); } process.exit(); } }
src/Compiler.ts
unshopable-melter-b347450
[ { "filename": "src/Emitter.ts", "retrieved_chunk": " compiler: Compiler;\n compilation: Compilation;\n hooks: EmitterHooks;\n constructor(compiler: Compiler, compilation: Compilation) {\n this.compiler = compiler;\n this.compilation = compilation;\n this.hooks = {\n beforeAssetAction: new SyncHook(['asset']),\n afterAssetAction: new SyncHook(['asset']),\n };", "score": 50.76920886204939 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " }\n emit() {\n this.compilation.assets.forEach((asset) => {\n this.hooks.beforeAssetAction.call(asset);\n if (typeof asset.target === 'undefined') {\n this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`);\n return;\n }\n switch (asset.action) {\n case 'add':", "score": 50.28573880913099 }, { "filename": "src/Watcher.ts", "retrieved_chunk": " if (this.watchOptions.persistent) {\n // Chokidar is not really watching without `persistent` being `true` so we do not want\n // to call the `watcherStart` hook in this case.\n this.compiler.hooks.watcherStart.call();\n }\n this.watcher = chokidar.watch(this.watcherPath, this.watchOptions);\n this.watcher.on('add', (path: string, stats: fs.Stats) => {\n if (this.initial) {\n this.initialAssetPaths.add(path);\n return;", "score": 36.76108853628624 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 36.09357631411572 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " this.hooks.afterAssetAction.call(asset);\n });\n }\n private writeFile(targetPath: AssetPath['absolute'], content: Asset['content']) {\n try {\n fs.ensureFileSync(targetPath);\n fs.writeFileSync(targetPath, content);\n } catch (error: any) {\n this.compilation.addError(error.message);\n }", "score": 35.22713290389156 } ]
typescript
emitter.emit();
import * as path from 'path'; import { Asset, AssetPath, AssetType } from '../Asset'; import { Compiler } from '../Compiler'; import { Emitter } from '../Emitter'; import { Plugin } from '../Plugin'; type Paths = { /** * An array of paths pointing to files that should be processed as `assets`. */ assets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `config`. */ config?: RegExp[]; /** * An array of paths pointing to files that should be processed as `layout`. */ layout?: RegExp[]; /** * An array of paths pointing to files that should be processed as `locales`. */ locales?: RegExp[]; /** * An array of paths pointing to files that should be processed as `sections`. */ sections?: RegExp[]; /** * An array of paths pointing to files that should be processed as `snippets`. */ snippets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `templates`. */ templates?: RegExp[]; }; /** * Path plugin configuration object. */ export type PathsPluginConfig = { /** * A map of Shopify's directory structure and component types. * * @see [Shopify Docs Reference](https://shopify.dev/docs/themes/architecture#directory-structure-and-component-types) */ paths?: Paths | false; }; const defaultPathsPluginConfig: PathsPluginConfig = { paths: { assets: [/assets\/[^\/]*\.*$/], config: [/config\/[^\/]*\.json$/], layout: [/layout\/[^\/]*\.liquid$/], locales: [/locales\/[^\/]*\.json$/], sections: [/sections\/[^\/]*\.liquid$/], snippets: [/snippets\/[^\/]*\.liquid$/], templates: [ /templates\/[^\/]*\.liquid$/, /templates\/[^\/]*\.json$/, /templates\/customers\/[^\/]*\.liquid$/, /templates\/customers\/[^\/]*\.json$/, ], }, }; export class PathsPlugin extends Plugin { config: PathsPluginConfig; constructor(config: PathsPluginConfig) { super(); this.config = config.paths !== false ? { paths: { ...defaultPathsPluginConfig.paths, ...config.paths, }, } : {}; } apply(compiler: Compiler): void { const output = compiler.config.output; if (!output) return; const paths = this.config.paths; if (!paths) return; compiler.
hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => {
emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => { const assetType = this.determineAssetType(paths, asset.source.relative); if (!assetType) return; asset.type = assetType; const assetSourcePathParts = asset.source.relative.split('/'); let assetFilename: string = ''; if (assetSourcePathParts.at(-2) === 'customers') { assetFilename = assetSourcePathParts.slice(-2).join('/'); } else { assetFilename = assetSourcePathParts.at(-1)!; } const assetTargetPath = this.resolveAssetTargetPath( compiler.cwd, output, assetType, assetFilename, ); asset.target = assetTargetPath; }); }); } private determineAssetType(paths: Paths, assetPath: string): AssetType | null { const pathEntries = Object.entries(paths); for (let i = 0; i < pathEntries.length; i += 1) { const [name, patterns] = pathEntries[i]; for (let j = 0; j < patterns.length; j++) { if (assetPath.match(patterns[j])) { return name as AssetType; } } } return null; } private resolveAssetTargetPath( cwd: string, output: string, assetType: AssetType, filename: string, ): AssetPath { const relativeAssetTargetPath = path.resolve(output, assetType, filename); const absoluteAssetTargetPath = path.resolve(cwd, relativeAssetTargetPath); return { absolute: absoluteAssetTargetPath, relative: relativeAssetTargetPath, }; } }
src/plugins/PathsPlugin.ts
unshopable-melter-b347450
[ { "filename": "src/config/defaults.ts", "retrieved_chunk": " }),\n new PathsPlugin({\n paths: config.paths,\n }),\n ],\n );\n return plugins;\n}\nexport function applyConfigDefaults(config: MelterConfig): CompilerConfig {\n const compilerConfig = {", "score": 26.8654120404371 }, { "filename": "src/Compiler.ts", "retrieved_chunk": " const emitter = new Emitter(this, compilation);\n this.hooks.emitter.call(emitter);\n emitter.emit();\n this.hooks.afterEmit.call(compilation);\n }\n this.hooks.done.call(compilation.stats);\n }\n close() {\n if (this.watcher) {\n // Close active watcher if compiler has one.", "score": 20.744230295041255 }, { "filename": "src/plugins/StatsPlugin.ts", "retrieved_chunk": " this.config = config;\n }\n apply(compiler: Compiler): void {\n if (this.config.stats === false) return;\n compiler.hooks.done.tap('StatsPlugin', (compilationStats: CompilationStats) => {\n if (compilationStats.errors.length > 0) {\n compiler.logger.error('Compilation failed', compilationStats.errors);\n } else if (compilationStats.warnings.length > 0) {\n compiler.logger.warning(\n `Compiled with ${compilationStats.warnings.length} warnings`,", "score": 20.560037603256472 }, { "filename": "src/config/index.ts", "retrieved_chunk": " * Where to write the compiled files to. The emitter won't emit any assets if undefined.\n */\n output: string;\n /**\n * A list of additional plugins to add to the compiler.\n */\n plugins: Plugin[];\n};\nexport const defaultBaseCompilerConfig: BaseCompilerConfig = {\n input: 'src',", "score": 17.949664863352673 }, { "filename": "src/Compiler.ts", "retrieved_chunk": " }\n compile(event: CompilerEvent, assetPaths: Set<string>) {\n this.hooks.beforeCompile.call();\n const compilation = new Compilation(this, event, assetPaths);\n this.hooks.compilation.call(compilation);\n compilation.create();\n this.hooks.afterCompile.call(compilation);\n // If no output directory is specified we do not want to emit assets.\n if (this.config.output) {\n this.hooks.beforeEmit.call(compilation);", "score": 16.186693424697186 } ]
typescript
hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => {
import * as fs from 'fs-extra'; import { SyncHook } from 'tapable'; import { Asset, AssetPath } from './Asset'; import { Compilation } from './Compilation'; import { Compiler } from './Compiler'; export type EmitterHooks = Readonly<{ beforeAssetAction: SyncHook<[Asset]>; afterAssetAction: SyncHook<[Asset]>; }>; export class Emitter { compiler: Compiler; compilation: Compilation; hooks: EmitterHooks; constructor(compiler: Compiler, compilation: Compilation) { this.compiler = compiler; this.compilation = compilation; this.hooks = { beforeAssetAction: new SyncHook(['asset']), afterAssetAction: new SyncHook(['asset']), }; } emit() { this.compilation.assets.forEach((asset) => { this.hooks.beforeAssetAction.call(asset); if (typeof asset.target === 'undefined') { this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`); return; } switch (asset.action) { case 'add': case 'update': { this.writeFile(asset.target.absolute, asset.content); break; } case 'remove': { this.removeFile(asset.target.absolute); break; } // No default. } this.hooks.afterAssetAction.call(asset); }); } private writeFile(targetPath: AssetPath['absolute'], content: Asset['content']) { try { fs.ensureFileSync(targetPath); fs.writeFileSync(targetPath, content); } catch (error: any) {
this.compilation.addError(error.message);
} } private removeFile(targetPath: AssetPath['absolute']) { try { fs.removeSync(targetPath); } catch (error: any) { this.compilation.addError(error.message); } } }
src/Emitter.ts
unshopable-melter-b347450
[ { "filename": "src/Asset.ts", "retrieved_chunk": " this.type = type;\n this.source = source;\n this.links = new Set<Asset>(links);\n this.content = this.getContent();\n this.action = action;\n }\n private getContent() {\n try {\n return fs.readFileSync(this.source.absolute);\n } catch {", "score": 27.006625580303496 }, { "filename": "src/config/load.ts", "retrieved_chunk": "function parseConfigFile(file: string): { config: MelterConfig | null; errors: string[] } {\n if (file.endsWith('json')) {\n const content = fs.readFileSync(file, 'utf8');\n const { data, error } = parseJSON<MelterConfig>(content);\n if (error) {\n return {\n config: null,\n errors: [error],\n };\n }", "score": 22.122767314227236 }, { "filename": "src/Asset.ts", "retrieved_chunk": " links: Set<Asset>;\n /**\n * The asset's content.\n */\n content: Buffer;\n /**\n * The action that created this asset.\n */\n action: CompilerEvent;\n constructor(type: AssetType, source: AssetPath, links: Set<Asset>, action: CompilerEvent) {", "score": 20.904455611950777 }, { "filename": "src/utils/index.ts", "retrieved_chunk": " data: JSON.parse(value),\n };\n } catch (error: any) {\n return {\n data: null,\n error: error.message,\n };\n }\n}", "score": 19.624474500808073 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 13.261346540073921 } ]
typescript
this.compilation.addError(error.message);
import * as fs from 'fs-extra'; import { SyncHook } from 'tapable'; import { Asset, AssetPath } from './Asset'; import { Compilation } from './Compilation'; import { Compiler } from './Compiler'; export type EmitterHooks = Readonly<{ beforeAssetAction: SyncHook<[Asset]>; afterAssetAction: SyncHook<[Asset]>; }>; export class Emitter { compiler: Compiler; compilation: Compilation; hooks: EmitterHooks; constructor(compiler: Compiler, compilation: Compilation) { this.compiler = compiler; this.compilation = compilation; this.hooks = { beforeAssetAction: new SyncHook(['asset']), afterAssetAction: new SyncHook(['asset']), }; } emit() { this.compilation.assets.forEach((asset) => { this.hooks.beforeAssetAction.call(asset); if (typeof asset.target === 'undefined') { this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`); return; } switch (asset.action) { case 'add': case 'update': { this.writeFile(asset.target.absolute, asset.content); break; } case 'remove': { this.removeFile(asset.target.absolute); break; } // No default. } this.hooks.afterAssetAction.call(asset); }); } private writeFile(targetPath: AssetPath['absolute'
], content: Asset['content']) {
try { fs.ensureFileSync(targetPath); fs.writeFileSync(targetPath, content); } catch (error: any) { this.compilation.addError(error.message); } } private removeFile(targetPath: AssetPath['absolute']) { try { fs.removeSync(targetPath); } catch (error: any) { this.compilation.addError(error.message); } } }
src/Emitter.ts
unshopable-melter-b347450
[ { "filename": "src/Asset.ts", "retrieved_chunk": " links: Set<Asset>;\n /**\n * The asset's content.\n */\n content: Buffer;\n /**\n * The action that created this asset.\n */\n action: CompilerEvent;\n constructor(type: AssetType, source: AssetPath, links: Set<Asset>, action: CompilerEvent) {", "score": 19.515795023803495 }, { "filename": "src/Asset.ts", "retrieved_chunk": " * The absolute and relative path to the asset's file.\n */\n source: AssetPath;\n /**\n * The absolute and relative path to the asset's file.\n */\n target?: AssetPath;\n /**\n * A set of assets the asset is linked with.\n */", "score": 19.08393167749984 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 18.695002049332423 }, { "filename": "src/Asset.ts", "retrieved_chunk": " this.type = type;\n this.source = source;\n this.links = new Set<Asset>(links);\n this.content = this.getContent();\n this.action = action;\n }\n private getContent() {\n try {\n return fs.readFileSync(this.source.absolute);\n } catch {", "score": 16.02857835034564 }, { "filename": "src/Asset.ts", "retrieved_chunk": "export type AssetPath = {\n absolute: string;\n relative: string;\n};\nexport class Asset {\n /**\n * The type of the asset.\n */\n type: AssetType;\n /**", "score": 15.41684424477134 } ]
typescript
], content: Asset['content']) {
import * as fs from 'fs-extra'; import { SyncHook } from 'tapable'; import { Asset, AssetPath } from './Asset'; import { Compilation } from './Compilation'; import { Compiler } from './Compiler'; export type EmitterHooks = Readonly<{ beforeAssetAction: SyncHook<[Asset]>; afterAssetAction: SyncHook<[Asset]>; }>; export class Emitter { compiler: Compiler; compilation: Compilation; hooks: EmitterHooks; constructor(compiler: Compiler, compilation: Compilation) { this.compiler = compiler; this.compilation = compilation; this.hooks = { beforeAssetAction: new SyncHook(['asset']), afterAssetAction: new SyncHook(['asset']), }; } emit() { this.compilation.assets.forEach((asset) => { this.hooks.beforeAssetAction.call(asset); if (typeof asset.target === 'undefined') { this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`); return; } switch (asset.action) { case 'add': case 'update': { this.writeFile(asset.target.absolute, asset.content); break; } case 'remove': { this.removeFile(asset.target.absolute); break; } // No default. } this.hooks.afterAssetAction.call(asset); }); } private writeFile(targetPath: AssetPath
['absolute'], content: Asset['content']) {
try { fs.ensureFileSync(targetPath); fs.writeFileSync(targetPath, content); } catch (error: any) { this.compilation.addError(error.message); } } private removeFile(targetPath: AssetPath['absolute']) { try { fs.removeSync(targetPath); } catch (error: any) { this.compilation.addError(error.message); } } }
src/Emitter.ts
unshopable-melter-b347450
[ { "filename": "src/Asset.ts", "retrieved_chunk": " links: Set<Asset>;\n /**\n * The asset's content.\n */\n content: Buffer;\n /**\n * The action that created this asset.\n */\n action: CompilerEvent;\n constructor(type: AssetType, source: AssetPath, links: Set<Asset>, action: CompilerEvent) {", "score": 19.515795023803495 }, { "filename": "src/Asset.ts", "retrieved_chunk": " * The absolute and relative path to the asset's file.\n */\n source: AssetPath;\n /**\n * The absolute and relative path to the asset's file.\n */\n target?: AssetPath;\n /**\n * A set of assets the asset is linked with.\n */", "score": 19.08393167749984 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 18.695002049332423 }, { "filename": "src/Asset.ts", "retrieved_chunk": " this.type = type;\n this.source = source;\n this.links = new Set<Asset>(links);\n this.content = this.getContent();\n this.action = action;\n }\n private getContent() {\n try {\n return fs.readFileSync(this.source.absolute);\n } catch {", "score": 16.02857835034564 }, { "filename": "src/Asset.ts", "retrieved_chunk": "export type AssetPath = {\n absolute: string;\n relative: string;\n};\nexport class Asset {\n /**\n * The type of the asset.\n */\n type: AssetType;\n /**", "score": 15.41684424477134 } ]
typescript
['absolute'], content: Asset['content']) {
import * as path from 'path'; import { Asset, AssetPath, AssetType } from '../Asset'; import { Compiler } from '../Compiler'; import { Emitter } from '../Emitter'; import { Plugin } from '../Plugin'; type Paths = { /** * An array of paths pointing to files that should be processed as `assets`. */ assets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `config`. */ config?: RegExp[]; /** * An array of paths pointing to files that should be processed as `layout`. */ layout?: RegExp[]; /** * An array of paths pointing to files that should be processed as `locales`. */ locales?: RegExp[]; /** * An array of paths pointing to files that should be processed as `sections`. */ sections?: RegExp[]; /** * An array of paths pointing to files that should be processed as `snippets`. */ snippets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `templates`. */ templates?: RegExp[]; }; /** * Path plugin configuration object. */ export type PathsPluginConfig = { /** * A map of Shopify's directory structure and component types. * * @see [Shopify Docs Reference](https://shopify.dev/docs/themes/architecture#directory-structure-and-component-types) */ paths?: Paths | false; }; const defaultPathsPluginConfig: PathsPluginConfig = { paths: { assets: [/assets\/[^\/]*\.*$/], config: [/config\/[^\/]*\.json$/], layout: [/layout\/[^\/]*\.liquid$/], locales: [/locales\/[^\/]*\.json$/], sections: [/sections\/[^\/]*\.liquid$/], snippets: [/snippets\/[^\/]*\.liquid$/], templates: [ /templates\/[^\/]*\.liquid$/, /templates\/[^\/]*\.json$/, /templates\/customers\/[^\/]*\.liquid$/, /templates\/customers\/[^\/]*\.json$/, ], }, }; export class PathsPlugin extends Plugin { config: PathsPluginConfig; constructor(config: PathsPluginConfig) { super(); this.config = config.paths !== false ? { paths: { ...defaultPathsPluginConfig.paths, ...config.paths, }, } : {}; } apply(compiler: Compiler): void { const output = compiler.config.output; if (!output) return; const paths = this.config.paths; if (!paths) return; compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => { emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => { const assetType = this.determineAssetType(paths, asset.source.relative); if (!assetType) return; asset.type = assetType; const assetSourcePathParts = asset.source.relative.split('/'); let assetFilename: string = ''; if (assetSourcePathParts.at(-2) === 'customers') { assetFilename = assetSourcePathParts.slice(-2).join('/'); } else { assetFilename = assetSourcePathParts.at(-1)!; } const assetTargetPath = this.resolveAssetTargetPath(
compiler.cwd, output, assetType, assetFilename, );
asset.target = assetTargetPath; }); }); } private determineAssetType(paths: Paths, assetPath: string): AssetType | null { const pathEntries = Object.entries(paths); for (let i = 0; i < pathEntries.length; i += 1) { const [name, patterns] = pathEntries[i]; for (let j = 0; j < patterns.length; j++) { if (assetPath.match(patterns[j])) { return name as AssetType; } } } return null; } private resolveAssetTargetPath( cwd: string, output: string, assetType: AssetType, filename: string, ): AssetPath { const relativeAssetTargetPath = path.resolve(output, assetType, filename); const absoluteAssetTargetPath = path.resolve(cwd, relativeAssetTargetPath); return { absolute: absoluteAssetTargetPath, relative: relativeAssetTargetPath, }; } }
src/plugins/PathsPlugin.ts
unshopable-melter-b347450
[ { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 6.507224289010152 }, { "filename": "src/utils/index.ts", "retrieved_chunk": "export function getFilenameFromPath(path: string): string {\n return path.split('/').at(-1)!;\n}\n/**\n * Parses provided value and returns data if succeeded. Otherwise the corresponding error\n * will be returned.\n */\nexport function parseJSON<T>(value: string): { data: T | null; error?: string } {\n try {\n return {", "score": 5.729906093140405 }, { "filename": "src/plugins/StatsPlugin.ts", "retrieved_chunk": " compilationStats.warnings,\n );\n } else {\n compiler.logger.success(`Successfully compiled in ${compilationStats.time} ms`);\n }\n });\n }\n}", "score": 5.4741685648771075 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " this.hooks = Object.freeze<CompilationHooks>({\n beforeAddAsset: new SyncHook(['asset']),\n afterAddAsset: new SyncHook(['asset']),\n });\n }\n create() {\n const startTime = performance.now();\n this.assetPaths.forEach((assetPath) => {\n const assetType = 'sections';\n const sourcePath = {", "score": 5.236371469716141 }, { "filename": "src/Logger.ts", "retrieved_chunk": " }\n private formatLogData(type: LoggerDataType, data: string[]) {\n const prefix = this.getPrefix(type);\n return data.map((item) => ` ${prefix} ${item}`).join('\\n');\n }\n private getPrefix(type: LoggerDataType) {\n const prefix = {\n warning: this.formatWarning('⚠'),\n error: this.formatError('✖'),\n };", "score": 5.229519402783576 } ]
typescript
compiler.cwd, output, assetType, assetFilename, );
import * as path from 'path'; import { Asset, AssetPath, AssetType } from '../Asset'; import { Compiler } from '../Compiler'; import { Emitter } from '../Emitter'; import { Plugin } from '../Plugin'; type Paths = { /** * An array of paths pointing to files that should be processed as `assets`. */ assets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `config`. */ config?: RegExp[]; /** * An array of paths pointing to files that should be processed as `layout`. */ layout?: RegExp[]; /** * An array of paths pointing to files that should be processed as `locales`. */ locales?: RegExp[]; /** * An array of paths pointing to files that should be processed as `sections`. */ sections?: RegExp[]; /** * An array of paths pointing to files that should be processed as `snippets`. */ snippets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `templates`. */ templates?: RegExp[]; }; /** * Path plugin configuration object. */ export type PathsPluginConfig = { /** * A map of Shopify's directory structure and component types. * * @see [Shopify Docs Reference](https://shopify.dev/docs/themes/architecture#directory-structure-and-component-types) */ paths?: Paths | false; }; const defaultPathsPluginConfig: PathsPluginConfig = { paths: { assets: [/assets\/[^\/]*\.*$/], config: [/config\/[^\/]*\.json$/], layout: [/layout\/[^\/]*\.liquid$/], locales: [/locales\/[^\/]*\.json$/], sections: [/sections\/[^\/]*\.liquid$/], snippets: [/snippets\/[^\/]*\.liquid$/], templates: [ /templates\/[^\/]*\.liquid$/, /templates\/[^\/]*\.json$/, /templates\/customers\/[^\/]*\.liquid$/, /templates\/customers\/[^\/]*\.json$/, ], }, }; export class PathsPlugin extends Plugin { config: PathsPluginConfig; constructor(config: PathsPluginConfig) { super(); this.config = config.paths !== false ? { paths: { ...defaultPathsPluginConfig.paths, ...config.paths, }, } : {}; } apply(compiler: Compiler): void { const output = compiler.config.output; if (!output) return; const paths = this.config.paths; if (!paths) return; compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => { emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => { const assetType = this.determineAssetType(paths, asset.source.relative); if (!assetType) return; asset.type = assetType; const assetSourcePathParts = asset.source.relative.split('/'); let assetFilename: string = ''; if (assetSourcePathParts.at(-2) === 'customers') { assetFilename = assetSourcePathParts.slice(-2).join('/'); } else { assetFilename = assetSourcePathParts.at(-1)!; } const assetTargetPath = this.resolveAssetTargetPath( compiler.cwd, output, assetType, assetFilename, ); asset.target = assetTargetPath; }); }); } private determineAssetType(paths: Paths, assetPath: string): AssetType | null { const pathEntries = Object.entries(paths); for (let i = 0; i < pathEntries.length; i += 1) { const [name, patterns] = pathEntries[i]; for (let j = 0; j < patterns.length; j++) { if (assetPath.match(patterns[j])) { return name as AssetType; } } } return null; } private resolveAssetTargetPath( cwd: string, output: string, assetType: AssetType, filename: string, ): AssetPath {
const relativeAssetTargetPath = path.resolve(output, assetType, filename);
const absoluteAssetTargetPath = path.resolve(cwd, relativeAssetTargetPath); return { absolute: absoluteAssetTargetPath, relative: relativeAssetTargetPath, }; } }
src/plugins/PathsPlugin.ts
unshopable-melter-b347450
[ { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 12.435655005101701 }, { "filename": "src/Asset.ts", "retrieved_chunk": "export type AssetPath = {\n absolute: string;\n relative: string;\n};\nexport class Asset {\n /**\n * The type of the asset.\n */\n type: AssetType;\n /**", "score": 8.69732079387148 }, { "filename": "src/config/load.ts", "retrieved_chunk": "export function loadConfig(): {\n config: MelterConfig | BaseCompilerConfig | null;\n warnings: string[];\n errors: string[];\n} {\n const configFiles = getConfigFiles(process.cwd());\n if (configFiles.length === 0) {\n return {\n config: defaultBaseCompilerConfig,\n warnings: [", "score": 8.589817122432963 }, { "filename": "src/Logger.ts", "retrieved_chunk": " }\n }\n private formatSuccess(message: string): string {\n return `\\x1b[32m${message}\\x1b[0m`;\n }\n private formatWarning(message: string): string {\n return `\\x1b[33m${message}\\x1b[0m`;\n }\n private formatError(message: string): string {\n return `\\x1b[31m${message}\\x1b[0m`;", "score": 8.300850740401787 }, { "filename": "src/Compiler.ts", "retrieved_chunk": " }\n compile(event: CompilerEvent, assetPaths: Set<string>) {\n this.hooks.beforeCompile.call();\n const compilation = new Compilation(this, event, assetPaths);\n this.hooks.compilation.call(compilation);\n compilation.create();\n this.hooks.afterCompile.call(compilation);\n // If no output directory is specified we do not want to emit assets.\n if (this.config.output) {\n this.hooks.beforeEmit.call(compilation);", "score": 8.259156546216044 } ]
typescript
const relativeAssetTargetPath = path.resolve(output, assetType, filename);
import fg from 'fast-glob'; import * as fs from 'fs-extra'; import * as path from 'path'; import { BaseCompilerConfig, MelterConfig, defaultBaseCompilerConfig } from '.'; import { getFilenameFromPath, parseJSON } from '../utils'; function getConfigFiles(cwd: string): string[] { const configFilePattern = 'melter.config.*'; // flat-glob only supports POSIX path syntax, so we use convertPathToPattern() for windows return fg.sync(fg.convertPathToPattern(cwd) + '/' + configFilePattern); } function parseConfigFile(file: string): { config: MelterConfig | null; errors: string[] } { if (file.endsWith('json')) { const content = fs.readFileSync(file, 'utf8'); const { data, error } = parseJSON<MelterConfig>(content); if (error) { return { config: null, errors: [error], }; } return { config: data, errors: [], }; } return { config: require(file).default || require(file), errors: [], }; } export function loadConfig(): { config: MelterConfig | BaseCompilerConfig | null; warnings: string[]; errors: string[]; } { const configFiles = getConfigFiles(process.cwd()); if (configFiles.length === 0) { return { config: defaultBaseCompilerConfig, warnings: [ 'No config found. Loaded default config. To disable this warning create a custom config.', ], errors: [], }; } const firstConfigFile = configFiles[0]; const warnings: string[] = []; if (configFiles.length > 1) { warnings.push( `Multiple configs found. Loaded '${
getFilenameFromPath( firstConfigFile, )}'. To disable this warning remove unused configs.`, );
} const { config, errors } = parseConfigFile(firstConfigFile); return { config, warnings, errors, }; }
src/config/load.ts
unshopable-melter-b347450
[ { "filename": "src/plugins/StatsPlugin.ts", "retrieved_chunk": " this.config = config;\n }\n apply(compiler: Compiler): void {\n if (this.config.stats === false) return;\n compiler.hooks.done.tap('StatsPlugin', (compilationStats: CompilationStats) => {\n if (compilationStats.errors.length > 0) {\n compiler.logger.error('Compilation failed', compilationStats.errors);\n } else if (compilationStats.warnings.length > 0) {\n compiler.logger.warning(\n `Compiled with ${compilationStats.warnings.length} warnings`,", "score": 17.48516009921522 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " this.stats.time = Number((endTime - startTime).toFixed(2));\n }\n addWarning(warning: string) {\n this.stats.warnings.push(warning);\n }\n addError(error: string) {\n this.stats.errors.push(error);\n }\n}", "score": 14.738617099549316 }, { "filename": "src/plugins/PathsPlugin.ts", "retrieved_chunk": " });\n });\n }\n private determineAssetType(paths: Paths, assetPath: string): AssetType | null {\n const pathEntries = Object.entries(paths);\n for (let i = 0; i < pathEntries.length; i += 1) {\n const [name, patterns] = pathEntries[i];\n for (let j = 0; j < patterns.length; j++) {\n if (assetPath.match(patterns[j])) {\n return name as AssetType;", "score": 12.81498207428356 }, { "filename": "src/Logger.ts", "retrieved_chunk": "export type LoggerDataType = 'warning' | 'error';\nexport class Logger {\n success(message: string) {\n console.log(this.formatSuccess(message));\n console.log('');\n }\n warning(message: string, data: string[]) {\n console.log(this.formatWarning(message));\n if (data.length > 0) {\n console.log('');", "score": 10.58202848314234 }, { "filename": "src/Logger.ts", "retrieved_chunk": " console.log(this.formatLogData('warning', data));\n console.log('');\n }\n }\n error(message: string, data: string[]) {\n console.log(this.formatError(message));\n if (data.length > 0) {\n console.log('');\n console.log(this.formatLogData('error', data));\n console.log('');", "score": 9.682594200517247 } ]
typescript
getFilenameFromPath( firstConfigFile, )}'. To disable this warning remove unused configs.`, );
import * as path from 'path'; import { Asset, AssetPath, AssetType } from '../Asset'; import { Compiler } from '../Compiler'; import { Emitter } from '../Emitter'; import { Plugin } from '../Plugin'; type Paths = { /** * An array of paths pointing to files that should be processed as `assets`. */ assets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `config`. */ config?: RegExp[]; /** * An array of paths pointing to files that should be processed as `layout`. */ layout?: RegExp[]; /** * An array of paths pointing to files that should be processed as `locales`. */ locales?: RegExp[]; /** * An array of paths pointing to files that should be processed as `sections`. */ sections?: RegExp[]; /** * An array of paths pointing to files that should be processed as `snippets`. */ snippets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `templates`. */ templates?: RegExp[]; }; /** * Path plugin configuration object. */ export type PathsPluginConfig = { /** * A map of Shopify's directory structure and component types. * * @see [Shopify Docs Reference](https://shopify.dev/docs/themes/architecture#directory-structure-and-component-types) */ paths?: Paths | false; }; const defaultPathsPluginConfig: PathsPluginConfig = { paths: { assets: [/assets\/[^\/]*\.*$/], config: [/config\/[^\/]*\.json$/], layout: [/layout\/[^\/]*\.liquid$/], locales: [/locales\/[^\/]*\.json$/], sections: [/sections\/[^\/]*\.liquid$/], snippets: [/snippets\/[^\/]*\.liquid$/], templates: [ /templates\/[^\/]*\.liquid$/, /templates\/[^\/]*\.json$/, /templates\/customers\/[^\/]*\.liquid$/, /templates\/customers\/[^\/]*\.json$/, ], }, }; export class PathsPlugin extends Plugin { config: PathsPluginConfig; constructor(config: PathsPluginConfig) { super(); this.config = config.paths !== false ? { paths: { ...defaultPathsPluginConfig.paths, ...config.paths, }, } : {}; } apply(compiler: Compiler): void { const output = compiler.config.output; if (!output) return; const paths = this.config.paths; if (!paths) return; compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => { emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => { const assetType = this.determineAssetType(paths, asset.source.relative); if (!assetType) return; asset.type = assetType; const assetSourcePathParts = asset.source.relative.split('/'); let assetFilename: string = ''; if (assetSourcePathParts.at(-2) === 'customers') { assetFilename = assetSourcePathParts.slice(-2).join('/'); } else { assetFilename = assetSourcePathParts.at(-1)!; } const assetTargetPath = this.resolveAssetTargetPath( compiler.cwd, output, assetType, assetFilename, ); asset
.target = assetTargetPath;
}); }); } private determineAssetType(paths: Paths, assetPath: string): AssetType | null { const pathEntries = Object.entries(paths); for (let i = 0; i < pathEntries.length; i += 1) { const [name, patterns] = pathEntries[i]; for (let j = 0; j < patterns.length; j++) { if (assetPath.match(patterns[j])) { return name as AssetType; } } } return null; } private resolveAssetTargetPath( cwd: string, output: string, assetType: AssetType, filename: string, ): AssetPath { const relativeAssetTargetPath = path.resolve(output, assetType, filename); const absoluteAssetTargetPath = path.resolve(cwd, relativeAssetTargetPath); return { absolute: absoluteAssetTargetPath, relative: relativeAssetTargetPath, }; } }
src/plugins/PathsPlugin.ts
unshopable-melter-b347450
[ { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 9.298721471268456 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " this.hooks = Object.freeze<CompilationHooks>({\n beforeAddAsset: new SyncHook(['asset']),\n afterAddAsset: new SyncHook(['asset']),\n });\n }\n create() {\n const startTime = performance.now();\n this.assetPaths.forEach((assetPath) => {\n const assetType = 'sections';\n const sourcePath = {", "score": 7.50986559414094 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " case 'update': {\n this.writeFile(asset.target.absolute, asset.content);\n break;\n }\n case 'remove': {\n this.removeFile(asset.target.absolute);\n break;\n }\n // No default.\n }", "score": 7.479205213450165 }, { "filename": "src/Emitter.ts", "retrieved_chunk": " }\n emit() {\n this.compilation.assets.forEach((asset) => {\n this.hooks.beforeAssetAction.call(asset);\n if (typeof asset.target === 'undefined') {\n this.compilation.addWarning(`Missing target path: '${asset.source.relative}'`);\n return;\n }\n switch (asset.action) {\n case 'add':", "score": 7.086632791094691 }, { "filename": "src/utils/index.ts", "retrieved_chunk": "export function getFilenameFromPath(path: string): string {\n return path.split('/').at(-1)!;\n}\n/**\n * Parses provided value and returns data if succeeded. Otherwise the corresponding error\n * will be returned.\n */\nexport function parseJSON<T>(value: string): { data: T | null; error?: string } {\n try {\n return {", "score": 5.729906093140405 } ]
typescript
.target = assetTargetPath;
import * as path from 'path'; import { Asset, AssetPath, AssetType } from '../Asset'; import { Compiler } from '../Compiler'; import { Emitter } from '../Emitter'; import { Plugin } from '../Plugin'; type Paths = { /** * An array of paths pointing to files that should be processed as `assets`. */ assets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `config`. */ config?: RegExp[]; /** * An array of paths pointing to files that should be processed as `layout`. */ layout?: RegExp[]; /** * An array of paths pointing to files that should be processed as `locales`. */ locales?: RegExp[]; /** * An array of paths pointing to files that should be processed as `sections`. */ sections?: RegExp[]; /** * An array of paths pointing to files that should be processed as `snippets`. */ snippets?: RegExp[]; /** * An array of paths pointing to files that should be processed as `templates`. */ templates?: RegExp[]; }; /** * Path plugin configuration object. */ export type PathsPluginConfig = { /** * A map of Shopify's directory structure and component types. * * @see [Shopify Docs Reference](https://shopify.dev/docs/themes/architecture#directory-structure-and-component-types) */ paths?: Paths | false; }; const defaultPathsPluginConfig: PathsPluginConfig = { paths: { assets: [/assets\/[^\/]*\.*$/], config: [/config\/[^\/]*\.json$/], layout: [/layout\/[^\/]*\.liquid$/], locales: [/locales\/[^\/]*\.json$/], sections: [/sections\/[^\/]*\.liquid$/], snippets: [/snippets\/[^\/]*\.liquid$/], templates: [ /templates\/[^\/]*\.liquid$/, /templates\/[^\/]*\.json$/, /templates\/customers\/[^\/]*\.liquid$/, /templates\/customers\/[^\/]*\.json$/, ], }, }; export class PathsPlugin extends Plugin { config: PathsPluginConfig; constructor(config: PathsPluginConfig) { super(); this.config = config.paths !== false ? { paths: { ...defaultPathsPluginConfig.paths, ...config.paths, }, } : {}; } apply(compiler: Compiler): void { const output = compiler.config.output; if (!output) return; const paths = this.config.paths; if (!paths) return; compiler.hooks.emitter.tap('PathsPlugin', (emitter: Emitter) => { emitter.hooks.beforeAssetAction.tap('PathsPlugin', (asset: Asset) => {
const assetType = this.determineAssetType(paths, asset.source.relative);
if (!assetType) return; asset.type = assetType; const assetSourcePathParts = asset.source.relative.split('/'); let assetFilename: string = ''; if (assetSourcePathParts.at(-2) === 'customers') { assetFilename = assetSourcePathParts.slice(-2).join('/'); } else { assetFilename = assetSourcePathParts.at(-1)!; } const assetTargetPath = this.resolveAssetTargetPath( compiler.cwd, output, assetType, assetFilename, ); asset.target = assetTargetPath; }); }); } private determineAssetType(paths: Paths, assetPath: string): AssetType | null { const pathEntries = Object.entries(paths); for (let i = 0; i < pathEntries.length; i += 1) { const [name, patterns] = pathEntries[i]; for (let j = 0; j < patterns.length; j++) { if (assetPath.match(patterns[j])) { return name as AssetType; } } } return null; } private resolveAssetTargetPath( cwd: string, output: string, assetType: AssetType, filename: string, ): AssetPath { const relativeAssetTargetPath = path.resolve(output, assetType, filename); const absoluteAssetTargetPath = path.resolve(cwd, relativeAssetTargetPath); return { absolute: absoluteAssetTargetPath, relative: relativeAssetTargetPath, }; } }
src/plugins/PathsPlugin.ts
unshopable-melter-b347450
[ { "filename": "src/config/defaults.ts", "retrieved_chunk": " }),\n new PathsPlugin({\n paths: config.paths,\n }),\n ],\n );\n return plugins;\n}\nexport function applyConfigDefaults(config: MelterConfig): CompilerConfig {\n const compilerConfig = {", "score": 37.048192081410996 }, { "filename": "src/Compiler.ts", "retrieved_chunk": " const emitter = new Emitter(this, compilation);\n this.hooks.emitter.call(emitter);\n emitter.emit();\n this.hooks.afterEmit.call(compilation);\n }\n this.hooks.done.call(compilation.stats);\n }\n close() {\n if (this.watcher) {\n // Close active watcher if compiler has one.", "score": 28.517901716137903 }, { "filename": "src/plugins/StatsPlugin.ts", "retrieved_chunk": " this.config = config;\n }\n apply(compiler: Compiler): void {\n if (this.config.stats === false) return;\n compiler.hooks.done.tap('StatsPlugin', (compilationStats: CompilationStats) => {\n if (compilationStats.errors.length > 0) {\n compiler.logger.error('Compilation failed', compilationStats.errors);\n } else if (compilationStats.warnings.length > 0) {\n compiler.logger.warning(\n `Compiled with ${compilationStats.warnings.length} warnings`,", "score": 24.55724177598857 }, { "filename": "src/Compilation.ts", "retrieved_chunk": " absolute: path.resolve(this.compiler.cwd, assetPath),\n relative: assetPath,\n };\n const asset = new Asset(assetType, sourcePath, new Set(), this.event);\n this.hooks.beforeAddAsset.call(asset);\n this.assets.add(asset);\n this.stats.assets.push(asset);\n this.hooks.afterAddAsset.call(asset);\n });\n const endTime = performance.now();", "score": 21.44453637947177 }, { "filename": "src/config/index.ts", "retrieved_chunk": " * Where to write the compiled files to. The emitter won't emit any assets if undefined.\n */\n output: string;\n /**\n * A list of additional plugins to add to the compiler.\n */\n plugins: Plugin[];\n};\nexport const defaultBaseCompilerConfig: BaseCompilerConfig = {\n input: 'src',", "score": 21.079089438565376 } ]
typescript
const assetType = this.determineAssetType(paths, asset.source.relative);
import { SupportedChainId } from "./types"; export const EVENT_SIGNATURES = { LimitOrderFilled: "0xab614d2b738543c0ea21f56347cf696a3a0c42a7cbec3212a5ca22a4dcff2124", LiquidityProviderSwap: "0x40a6ba9513d09e3488135e0e0d10e2d4382b792720155b144cbea89ac9db6d34", OtcOrderFilled: "0xac75f773e3a92f1a02b12134d65e1f47f8a14eabe4eaf1e24624918e6a8b269f", MetaTransactionExecuted: "0x7f4fe3ff8ae440e1570c558da08440b26f89fb1c1f2910cd91ca6452955f121a", Transfer: "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", TransformedERC20: "0x0f6672f78a59ba8e5e5b5d38df3ebc67f3c792e2c9259b8d97d7f00dd78ba1b3", } as const; export const ERC20_FUNCTION_HASHES = { symbol: "0x95d89b41", decimals: "0x313ce567", } as const; export const EXCHANGE_PROXY_ABI_URL = "https://raw.githubusercontent.com/0xProject/protocol/development/packages/contract-artifacts/artifacts/IZeroEx.json"; const CONONICAL_EXCHANGE_PROXY = "0xdef1c0ded9bec7f1a1670819833240f027b25eff"; export const MULTICALL3 = "0xcA11bde05977b3631167028862bE2a173976CA11"; export const PERMIT_AND_CALL_BY_CHAIN_ID = { 1: "0x1291C02D288de3De7dC25353459489073D11E1Ae", 137: "0x2ddd30fe5c12fc4cd497526f14bf3d1fcd3d5db4", 8453: "0x3CA53031Ad0B86a304845e83644983Be3340895f" } as const export const EXCHANGE_PROXY_BY_CHAIN_ID = { 1: CONONICAL_EXCHANGE_PROXY, 5: "0xf91bb752490473b8342a3e964e855b9f9a2a668e", 10: "0xdef1abe32c034e558cdd535791643c58a13acc10", 56: CONONICAL_EXCHANGE_PROXY, 137: CONONICAL_EXCHANGE_PROXY, 250: "0xdef189deaef76e379df891899eb5a00a94cbc250", 8453: CONONICAL_EXCHANGE_PROXY, 42161: CONONICAL_EXCHANGE_PROXY, 42220: CONONICAL_EXCHANGE_PROXY, 43114: CONONICAL_EXCHANGE_PROXY, } as const export const CONTRACTS = { weth: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", } as const; export const NATIVE_ASSET = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"; export const NATIVE_SYMBOL_BY_CHAIN_ID:
Record<SupportedChainId, string> = {
1: "ETH", // Ethereum 5: "ETH", // Goerli 10: "ETH", // Optimism 56: "BNB", // BNB Chain 137: "MATIC", // Polygon 250: "FTM", // Fantom 8453: "ETH", // Base 42161: "ETH", // Arbitrum One 42220: "CELO", // Celo 43114: "AVAX", // Avalanche } as const;
src/constants.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/utils/index.ts", "retrieved_chunk": "export function convertHexToAddress(hexString: string): string {\n return `0x${hexString.slice(-40)}`;\n}\nexport function isChainIdSupported(\n chainId: number\n): chainId is SupportedChainId {\n return [1, 5, 10, 56, 137, 250, 8453, 42220, 43114, 42161].includes(chainId);\n}\nexport function isPermitAndCallChainId(\n chainId: number", "score": 21.943184954043236 }, { "filename": "src/parsers/index.ts", "retrieved_chunk": " return extractTokenInfo(inputLog, outputLog);\n }\n}\nexport function fillTakerSignedOtcOrderForEth({\n txReceipt,\n}: {\n txReceipt: EnrichedTxReceipt;\n}) {\n const { logs } = txReceipt;\n const inputLog = logs.find((log) => log.address !== CONTRACTS.weth);", "score": 18.57832175588728 }, { "filename": "src/types.ts", "retrieved_chunk": "import { narrow } from \"abitype\";\nimport IZeroEx from \"./abi/IZeroEx.json\";\nimport type {\n Contract,\n BaseContractMethod,\n TransactionReceipt,\n TransactionDescription,\n} from \"ethers\";\nexport type PermitAndCallChainIds = 1 | 137 | 8453;\nexport type SupportedChainId = 1 | 5 | 10 | 56 | 137 | 250 | 8453 | 42220 | 43114 | 42161;", "score": 18.41264085130584 }, { "filename": "src/parsers/index.ts", "retrieved_chunk": " }\n}\nexport function multiplexMultiHopSellTokenForEth({\n txReceipt,\n}: {\n txReceipt: EnrichedTxReceipt;\n}) {\n const { logs, from } = txReceipt;\n const inputLog = logs.find((log) => from.toLowerCase() === log.from);\n const outputLog = logs.find((log) => log.address === CONTRACTS.weth);", "score": 18.126013676808444 }, { "filename": "src/parsers/index.ts", "retrieved_chunk": " txReceipt,\n txDescription,\n}: {\n txReceipt: EnrichedTxReceipt;\n txDescription: TransactionDescription;\n}) {\n const [metaTransaction] = txDescription.args;\n const [from] = metaTransaction as string[];\n const { logs } = txReceipt;\n if (typeof from === \"string\") {", "score": 17.802973174045217 } ]
typescript
Record<SupportedChainId, string> = {
import { Contract, JsonRpcProvider } from "ethers"; import { abi as permitAndCallAbi } from "./abi/PermitAndCall.json"; import multicall3Abi from "./abi/Multicall3.json"; import { MULTICALL3, EXCHANGE_PROXY_ABI_URL, EXCHANGE_PROXY_BY_CHAIN_ID, PERMIT_AND_CALL_BY_CHAIN_ID, } from "./constants"; import { fillLimitOrder, fillOtcOrder, fillOtcOrderForEth, fillOtcOrderWithEth, fillTakerSignedOtcOrder, fillTakerSignedOtcOrderForEth, executeMetaTransaction, multiplexBatchSellTokenForToken, multiplexBatchSellTokenForEth, multiplexBatchSellEthForToken, multiplexMultiHopSellTokenForToken, multiplexMultiHopSellEthForToken, multiplexMultiHopSellTokenForEth, sellToUniswap, sellTokenForEthToUniswapV3, sellEthForTokenToUniswapV3, sellTokenForTokenToUniswapV3, sellToLiquidityProvider, sellToPancakeSwap, transformERC20, } from "./parsers"; import { enrichTxReceipt, isChainIdSupported, isPermitAndCallChainId, } from "./utils"; import { TransactionStatus } from "./types"; import type { Mtx, LogParsers, ParseSwapArgs, ParseGaslessTxArgs, ProcessReceiptArgs, } from "./types"; export * from "./types"; export async function parseSwap({ transactionHash, exchangeProxyAbi, rpcUrl, }: ParseSwapArgs) { if (!rpcUrl) throw new Error("Missing rpcUrl"); if (!transactionHash) throw new Error("Missing transaction hash"); if (!exchangeProxyAbi) throw new Error(`Missing 0x Exchange Proxy ABI: ${EXCHANGE_PROXY_ABI_URL}`); const provider = new JsonRpcProvider(rpcUrl); const [tx, transactionReceipt] = await Promise.all([ provider.getTransaction(transactionHash), provider.getTransactionReceipt(transactionHash), ]); if (tx && transactionReceipt) {
if (transactionReceipt.status === TransactionStatus.REVERTED) return null;
const chainId = Number(tx.chainId); if (!isChainIdSupported(chainId)) { throw new Error(`chainId ${chainId} is unsupported.`); } const exchangeProxyContract = new Contract( EXCHANGE_PROXY_BY_CHAIN_ID[chainId], exchangeProxyAbi ); const permitAndCallAddress = isPermitAndCallChainId(chainId) ? PERMIT_AND_CALL_BY_CHAIN_ID[chainId] : undefined; const permitAndCallContract = permitAndCallAddress ? new Contract(permitAndCallAddress, permitAndCallAbi) : undefined; const transactionDescription = transactionReceipt.to === permitAndCallAddress ? permitAndCallContract?.interface.parseTransaction(tx) : exchangeProxyContract.interface.parseTransaction(tx); if (!transactionDescription) return null; const multicall = new Contract(MULTICALL3, multicall3Abi, provider); const tryBlockAndAggregate = multicall[ "tryBlockAndAggregate(bool requireSuccess, tuple(address target, bytes callData)[] calls)" ]; const logParsers: LogParsers = { fillLimitOrder, fillOtcOrder, fillOtcOrderForEth, fillOtcOrderWithEth, fillTakerSignedOtcOrder, fillTakerSignedOtcOrderForEth, executeMetaTransaction, multiplexBatchSellTokenForToken, multiplexBatchSellTokenForEth, multiplexBatchSellEthForToken, multiplexMultiHopSellTokenForToken, multiplexMultiHopSellEthForToken, multiplexMultiHopSellTokenForEth, sellToUniswap, sellTokenForEthToUniswapV3, sellEthForTokenToUniswapV3, sellTokenForTokenToUniswapV3, sellToLiquidityProvider, sellToPancakeSwap, }; const parser = logParsers[transactionDescription.name]; if (transactionDescription.name === "permitAndCall") { const calldataFromPermitAndCall = transactionDescription.args[7]; const permitAndCallDescription = exchangeProxyContract.interface.parseTransaction({ data: calldataFromPermitAndCall, }); if (permitAndCallDescription) { return parseGaslessTx({ chainId, logParsers, tryBlockAndAggregate, exchangeProxyContract, transactionReceipt, transactionDescription: permitAndCallDescription, }); } } if (transactionDescription.name === "executeMetaTransactionV2") { return parseGaslessTx({ chainId, logParsers, exchangeProxyContract, tryBlockAndAggregate, transactionReceipt, transactionDescription, }); } if (transactionDescription.name === "transformERC20") { return transformERC20({ chainId, transactionReceipt, tryBlockAndAggregate, contract: exchangeProxyContract, }); } const txReceiptEnriched = await enrichTxReceipt({ transactionReceipt, tryBlockAndAggregate, }); return parser({ txDescription: transactionDescription, txReceipt: txReceiptEnriched, }); } } async function parseGaslessTx({ chainId, logParsers, exchangeProxyContract, tryBlockAndAggregate, transactionReceipt, transactionDescription, }: ParseGaslessTxArgs) { const [mtx] = transactionDescription.args; const { 0: signer, 4: data, 6: fees } = mtx as Mtx; const [recipient] = fees[0]; const mtxV2Description = exchangeProxyContract.interface.parseTransaction({ data, }); if (mtxV2Description) { if (mtxV2Description.name === "transformERC20") { return transformERC20({ chainId, transactionReceipt, tryBlockAndAggregate, contract: exchangeProxyContract, }); } else { const parser = logParsers[mtxV2Description.name]; return processReceipt({ signer, parser, recipient, tryBlockAndAggregate, transactionReceipt, transactionDescription: mtxV2Description, }); } } const parser = logParsers[transactionDescription.name]; return processReceipt({ signer, parser, recipient, tryBlockAndAggregate, transactionReceipt, transactionDescription, }); } async function processReceipt({ signer, parser, recipient, tryBlockAndAggregate, transactionReceipt, transactionDescription, }: ProcessReceiptArgs) { const enrichedTxReceipt = await enrichTxReceipt({ transactionReceipt, tryBlockAndAggregate, }); const { logs } = enrichedTxReceipt; const filteredLogs = logs.filter((log) => log.to !== recipient.toLowerCase()); return parser({ txDescription: transactionDescription, txReceipt: { from: signer, logs: filteredLogs }, }); }
src/index.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/tests/index.test.ts", "retrieved_chunk": " } as any);\n }).rejects.toThrowError(\"Missing transaction hash\");\n expect(async () => {\n await parseSwap({\n transactionHash: \"0x…\",\n rpcUrl: ETH_MAINNET_RPC,\n });\n }).rejects.toThrowError(\n `Missing 0x Exchange Proxy ABI: ${EXCHANGE_PROXY_ABI_URL}`\n );", "score": 43.61982349704017 }, { "filename": "src/tests/index.test.ts", "retrieved_chunk": "import { it, expect } from \"vitest\";\nimport { parseSwap } from \"../index\";\nimport EXCHANGE_PROXY_ABI from \"../abi/IZeroEx.json\";\nimport { EXCHANGE_PROXY_ABI_URL } from \"../constants\";\nrequire(\"dotenv\").config();\nconst ETH_MAINNET_RPC = process.env.ETH_MAINNET_RPC;\nif (!ETH_MAINNET_RPC) {\n throw new Error(\"Missing environment variable `ETH_MAINNET_RPC`\");\n}\n// https://etherscan.io/tx/0xe393e03e31ba2b938326ef0527aba08b4e7f2d144ac2a2172c57615990698ee6", "score": 23.345706967373292 }, { "filename": "src/tests/sellTokenForEthToUniswapV3.test.ts", "retrieved_chunk": "import { it, expect, describe } from \"vitest\";\nimport { parseSwap } from \"../index\";\nimport EXCHANGE_PROXY_ABI from \"../abi/IZeroEx.json\";\nrequire(\"dotenv\").config();\nconst ETH_MAINNET_RPC = process.env.ETH_MAINNET_RPC;\nif (!ETH_MAINNET_RPC) {\n throw new Error(\"Missing environment variable `ETH_MAINNET_RPC`\");\n}\ndescribe(\"fillOtcOrder\", () => {\n // https://etherscan.io/tx/0xc9579b9e3cddebd3d48ccb0a719456d7c46869b2c3a536509ea88685c7a5efbb", "score": 20.588087118750877 }, { "filename": "src/tests/permitAndCall.test.ts", "retrieved_chunk": "import { describe, expect, it } from \"vitest\";\nimport { parseSwap } from \"../index\";\nimport EXCHANGE_PROXY_ABI from \"../abi/IZeroEx.json\";\nrequire(\"dotenv\").config();\nconst ETH_MAINNET_RPC = process.env.ETH_MAINNET_RPC;\nif (!ETH_MAINNET_RPC) {\n throw new Error(\"Missing environment variable `ETH_MAINNET_RPC`\");\n}\ndescribe(\"permitAndCall\", () => {\n // https://etherscan.io/tx/0x5eac379185f24ddeba7fcd4414779df77ecfd1102da6ebf6dacf25b01a14b241", "score": 20.588087118750877 }, { "filename": "src/tests/fillOtcOrder.test.ts", "retrieved_chunk": "import { describe, expect, it } from \"vitest\";\nimport { parseSwap } from \"../index\";\nimport EXCHANGE_PROXY_ABI from \"../abi/IZeroEx.json\";\nrequire(\"dotenv\").config();\nconst ETH_MAINNET_RPC = process.env.ETH_MAINNET_RPC;\nif (!ETH_MAINNET_RPC) {\n throw new Error(\"Missing environment variable `ETH_MAINNET_RPC`\");\n}\n// https://etherscan.io/tx/0x822d38c0746b19544cedddd9a1ebaacadd3e5da55dc293738ae135fc595e269b\ndescribe(\"parseSwap\", () => {", "score": 20.588087118750877 } ]
typescript
if (transactionReceipt.status === TransactionStatus.REVERTED) return null;
import { Contract, JsonRpcProvider } from "ethers"; import { abi as permitAndCallAbi } from "./abi/PermitAndCall.json"; import multicall3Abi from "./abi/Multicall3.json"; import { MULTICALL3, EXCHANGE_PROXY_ABI_URL, EXCHANGE_PROXY_BY_CHAIN_ID, PERMIT_AND_CALL_BY_CHAIN_ID, } from "./constants"; import { fillLimitOrder, fillOtcOrder, fillOtcOrderForEth, fillOtcOrderWithEth, fillTakerSignedOtcOrder, fillTakerSignedOtcOrderForEth, executeMetaTransaction, multiplexBatchSellTokenForToken, multiplexBatchSellTokenForEth, multiplexBatchSellEthForToken, multiplexMultiHopSellTokenForToken, multiplexMultiHopSellEthForToken, multiplexMultiHopSellTokenForEth, sellToUniswap, sellTokenForEthToUniswapV3, sellEthForTokenToUniswapV3, sellTokenForTokenToUniswapV3, sellToLiquidityProvider, sellToPancakeSwap, transformERC20, } from "./parsers"; import { enrichTxReceipt, isChainIdSupported, isPermitAndCallChainId, } from "./utils"; import { TransactionStatus } from "./types"; import type { Mtx, LogParsers, ParseSwapArgs, ParseGaslessTxArgs, ProcessReceiptArgs, } from "./types"; export * from "./types"; export async function parseSwap({ transactionHash, exchangeProxyAbi, rpcUrl, }: ParseSwapArgs) { if (!rpcUrl) throw new Error("Missing rpcUrl"); if (!transactionHash) throw new Error("Missing transaction hash"); if (!exchangeProxyAbi) throw new Error(`Missing 0x Exchange Proxy ABI: ${EXCHANGE_PROXY_ABI_URL}`); const provider = new JsonRpcProvider(rpcUrl); const [tx, transactionReceipt] = await Promise.all([ provider.getTransaction(transactionHash), provider.getTransactionReceipt(transactionHash), ]); if (tx && transactionReceipt) { if (transactionReceipt.
status === TransactionStatus.REVERTED) return null;
const chainId = Number(tx.chainId); if (!isChainIdSupported(chainId)) { throw new Error(`chainId ${chainId} is unsupported.`); } const exchangeProxyContract = new Contract( EXCHANGE_PROXY_BY_CHAIN_ID[chainId], exchangeProxyAbi ); const permitAndCallAddress = isPermitAndCallChainId(chainId) ? PERMIT_AND_CALL_BY_CHAIN_ID[chainId] : undefined; const permitAndCallContract = permitAndCallAddress ? new Contract(permitAndCallAddress, permitAndCallAbi) : undefined; const transactionDescription = transactionReceipt.to === permitAndCallAddress ? permitAndCallContract?.interface.parseTransaction(tx) : exchangeProxyContract.interface.parseTransaction(tx); if (!transactionDescription) return null; const multicall = new Contract(MULTICALL3, multicall3Abi, provider); const tryBlockAndAggregate = multicall[ "tryBlockAndAggregate(bool requireSuccess, tuple(address target, bytes callData)[] calls)" ]; const logParsers: LogParsers = { fillLimitOrder, fillOtcOrder, fillOtcOrderForEth, fillOtcOrderWithEth, fillTakerSignedOtcOrder, fillTakerSignedOtcOrderForEth, executeMetaTransaction, multiplexBatchSellTokenForToken, multiplexBatchSellTokenForEth, multiplexBatchSellEthForToken, multiplexMultiHopSellTokenForToken, multiplexMultiHopSellEthForToken, multiplexMultiHopSellTokenForEth, sellToUniswap, sellTokenForEthToUniswapV3, sellEthForTokenToUniswapV3, sellTokenForTokenToUniswapV3, sellToLiquidityProvider, sellToPancakeSwap, }; const parser = logParsers[transactionDescription.name]; if (transactionDescription.name === "permitAndCall") { const calldataFromPermitAndCall = transactionDescription.args[7]; const permitAndCallDescription = exchangeProxyContract.interface.parseTransaction({ data: calldataFromPermitAndCall, }); if (permitAndCallDescription) { return parseGaslessTx({ chainId, logParsers, tryBlockAndAggregate, exchangeProxyContract, transactionReceipt, transactionDescription: permitAndCallDescription, }); } } if (transactionDescription.name === "executeMetaTransactionV2") { return parseGaslessTx({ chainId, logParsers, exchangeProxyContract, tryBlockAndAggregate, transactionReceipt, transactionDescription, }); } if (transactionDescription.name === "transformERC20") { return transformERC20({ chainId, transactionReceipt, tryBlockAndAggregate, contract: exchangeProxyContract, }); } const txReceiptEnriched = await enrichTxReceipt({ transactionReceipt, tryBlockAndAggregate, }); return parser({ txDescription: transactionDescription, txReceipt: txReceiptEnriched, }); } } async function parseGaslessTx({ chainId, logParsers, exchangeProxyContract, tryBlockAndAggregate, transactionReceipt, transactionDescription, }: ParseGaslessTxArgs) { const [mtx] = transactionDescription.args; const { 0: signer, 4: data, 6: fees } = mtx as Mtx; const [recipient] = fees[0]; const mtxV2Description = exchangeProxyContract.interface.parseTransaction({ data, }); if (mtxV2Description) { if (mtxV2Description.name === "transformERC20") { return transformERC20({ chainId, transactionReceipt, tryBlockAndAggregate, contract: exchangeProxyContract, }); } else { const parser = logParsers[mtxV2Description.name]; return processReceipt({ signer, parser, recipient, tryBlockAndAggregate, transactionReceipt, transactionDescription: mtxV2Description, }); } } const parser = logParsers[transactionDescription.name]; return processReceipt({ signer, parser, recipient, tryBlockAndAggregate, transactionReceipt, transactionDescription, }); } async function processReceipt({ signer, parser, recipient, tryBlockAndAggregate, transactionReceipt, transactionDescription, }: ProcessReceiptArgs) { const enrichedTxReceipt = await enrichTxReceipt({ transactionReceipt, tryBlockAndAggregate, }); const { logs } = enrichedTxReceipt; const filteredLogs = logs.filter((log) => log.to !== recipient.toLowerCase()); return parser({ txDescription: transactionDescription, txReceipt: { from: signer, logs: filteredLogs }, }); }
src/index.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/tests/index.test.ts", "retrieved_chunk": " } as any);\n }).rejects.toThrowError(\"Missing transaction hash\");\n expect(async () => {\n await parseSwap({\n transactionHash: \"0x…\",\n rpcUrl: ETH_MAINNET_RPC,\n });\n }).rejects.toThrowError(\n `Missing 0x Exchange Proxy ABI: ${EXCHANGE_PROXY_ABI_URL}`\n );", "score": 31.757194086740252 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface ProcessReceiptArgs {\n signer: string;\n recipient: string;\n parser: ParserFunction;\n transactionReceipt: TransactionReceipt;\n tryBlockAndAggregate: TryBlockAndAggregate;\n transactionDescription: TransactionDescription;\n}\nexport enum TransactionStatus {\n REVERTED = 0,", "score": 19.989244742379697 }, { "filename": "src/tests/index.test.ts", "retrieved_chunk": "import { it, expect } from \"vitest\";\nimport { parseSwap } from \"../index\";\nimport EXCHANGE_PROXY_ABI from \"../abi/IZeroEx.json\";\nimport { EXCHANGE_PROXY_ABI_URL } from \"../constants\";\nrequire(\"dotenv\").config();\nconst ETH_MAINNET_RPC = process.env.ETH_MAINNET_RPC;\nif (!ETH_MAINNET_RPC) {\n throw new Error(\"Missing environment variable `ETH_MAINNET_RPC`\");\n}\n// https://etherscan.io/tx/0xe393e03e31ba2b938326ef0527aba08b4e7f2d144ac2a2172c57615990698ee6", "score": 16.504305105040157 }, { "filename": "src/parsers/index.ts", "retrieved_chunk": "}: {\n contract: Contract;\n chainId: SupportedChainId;\n transactionReceipt: TransactionReceipt;\n tryBlockAndAggregate: TryBlockAndAggregate;\n}) {\n const nativeSymbol = NATIVE_SYMBOL_BY_CHAIN_ID[chainId];\n for (const log of transactionReceipt.logs) {\n const { topics, data } = log;\n const [eventHash] = topics;", "score": 16.075623459930632 }, { "filename": "src/utils/index.ts", "retrieved_chunk": " const { 1: fromHex, 2: toHex } = topics;\n const from = convertHexToAddress(fromHex);\n const to = convertHexToAddress(toHex);\n const amount = formatUnits(data, decimals);\n return { to, from, symbol, amount, address, decimals };\n}\nexport async function enrichTxReceipt({\n transactionReceipt,\n tryBlockAndAggregate,\n}: EnrichedTxReceiptArgs): Promise<EnrichedTxReceipt> {", "score": 15.482403292946994 } ]
typescript
status === TransactionStatus.REVERTED) return null;
import { formatUnits } from "ethers"; import { extractTokenInfo, fetchSymbolAndDecimal } from "../utils"; import { CONTRACTS, NATIVE_ASSET, EVENT_SIGNATURES, NATIVE_SYMBOL_BY_CHAIN_ID, EXCHANGE_PROXY_BY_CHAIN_ID, } from "../constants"; import type { Contract, TransactionReceipt, TransactionDescription, } from "ethers"; import type { SupportedChainId, EnrichedTxReceipt, TryBlockAndAggregate, TransformERC20EventData, } from "../types"; export function sellToLiquidityProvider({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function multiplexMultiHopSellTokenForEth({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => log.address === CONTRACTS.weth); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function multiplexMultiHopSellEthForToken({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => log.address === CONTRACTS.weth); const outputLog = logs.find((log) => log.to === from.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function fillTakerSignedOtcOrder({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [order] = txDescription.args; const { logs } = txReceipt; const { 4: maker, 5: taker } = order as string[]; if (typeof maker === "string" && typeof taker === "string") { const inputLog = logs.find((log) => log.from === taker.toLowerCase()); const outputLog = logs.find((log) => log.from === maker.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } } export function fillOtcOrder({ txReceipt }: { txReceipt: EnrichedTxReceipt }) { const { logs, from } = txReceipt; const fromAddress = from.toLowerCase(); const inputLog = logs.find((log) => log.from === fromAddress); const outputLog = logs.find((log) => log.to === fromAddress); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function fillTakerSignedOtcOrderForEth({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs } = txReceipt; const inputLog = logs.find((log) => log.address !== CONTRACTS.weth); const outputLog = logs.find((log) => log.address === CONTRACTS.weth); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellTokenForEthToUniswapV3({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => log.from === from.toLowerCase()); const outputLog = logs.find((log) => log.from !== from.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellTokenForTokenToUniswapV3({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellEthForTokenToUniswapV3({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() !== log.to); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellToUniswap({ txReceipt }: { txReceipt: EnrichedTxReceipt }) { const [inputLog, outputLog] = txReceipt.logs; return extractTokenInfo(inputLog, outputLog); } export async function transformERC20({ chainId, contract, transactionReceipt, tryBlockAndAggregate, }: { contract: Contract; chainId: SupportedChainId; transactionReceipt: TransactionReceipt; tryBlockAndAggregate: TryBlockAndAggregate; }) { const
nativeSymbol = NATIVE_SYMBOL_BY_CHAIN_ID[chainId];
for (const log of transactionReceipt.logs) { const { topics, data } = log; const [eventHash] = topics; if (eventHash === EVENT_SIGNATURES.TransformedERC20) { const logDescription = contract.interface.parseLog({ data, topics: [...topics], }); const { 1: inputToken, 2: outputToken, 3: inputTokenAmount, 4: outputTokenAmount, } = logDescription!.args as unknown as TransformERC20EventData; let inputSymbol: string; let inputDecimal: number; let outputSymbol: string; let outputDecimal: number; if (inputToken === NATIVE_ASSET) { inputSymbol = nativeSymbol; inputDecimal = 18; } else { [inputSymbol, inputDecimal] = await fetchSymbolAndDecimal( inputToken, tryBlockAndAggregate ); } if (outputToken === NATIVE_ASSET) { outputSymbol = nativeSymbol; outputDecimal = 18; } else { [outputSymbol, outputDecimal] = await fetchSymbolAndDecimal( outputToken, tryBlockAndAggregate ); } const inputAmount = formatUnits(inputTokenAmount, inputDecimal); const outputAmount = formatUnits(outputTokenAmount, outputDecimal); return { tokenIn: { address: inputToken, amount: inputAmount, symbol: inputSymbol, }, tokenOut: { address: outputToken, amount: outputAmount, symbol: outputSymbol, }, }; } } } export function multiplexMultiHopSellTokenForToken({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function multiplexBatchSellTokenForEth({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { from, logs } = txReceipt; const tokenData = { [from.toLowerCase()]: { amount: "0", symbol: "", address: "" }, [CONTRACTS.weth.toLowerCase()]: { amount: "0", symbol: "ETH", address: NATIVE_ASSET, }, }; logs.forEach(({ address, symbol, amount, from }) => { const erc20Address = address.toLowerCase(); if (tokenData[erc20Address]) { tokenData[erc20Address].amount = String( Number(tokenData[erc20Address].amount) + Number(amount) ); } if (tokenData[from]) { tokenData[from].amount = String( Number(tokenData[from].amount) + Number(amount) ); tokenData[from].symbol = symbol; tokenData[from].address = address; } }); return { tokenIn: tokenData[from.toLowerCase()], tokenOut: tokenData[CONTRACTS.weth.toLowerCase()], }; } export function multiplexBatchSellEthForToken({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const { logs } = txReceipt; const { args, value } = txDescription; const { 0: outputToken } = args; const divisor = 1000000000000000000n; // 1e18, for conversion from wei to ether const etherBigInt = value / divisor; const remainderBigInt = value % divisor; const ether = Number(etherBigInt) + Number(remainderBigInt) / Number(divisor); const tokenOutAmount = logs.reduce((total, log) => { return log.address === outputToken ? total + Number(log.amount) : total; }, 0); const inputLog = logs.find((log) => log.address === CONTRACTS.weth); const outputLog = logs.find((log) => log.address === outputToken); if (inputLog && outputLog) { return { tokenIn: { symbol: inputLog.symbol, amount: ether.toString(), address: inputLog.address, }, tokenOut: { symbol: outputLog.symbol, amount: tokenOutAmount.toString(), address: outputLog.address, }, }; } } export function multiplexBatchSellTokenForToken({ txDescription, txReceipt, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [inputContractAddress, outputContractAddress] = txDescription.args; if ( typeof inputContractAddress === "string" && typeof outputContractAddress === "string" ) { const tokenData = { [inputContractAddress]: { amount: "0", symbol: "", address: "" }, [outputContractAddress]: { amount: "0", symbol: "", address: "" }, }; txReceipt.logs.forEach(({ address, symbol, amount }) => { if (address in tokenData) { tokenData[address].address = address; tokenData[address].symbol = symbol; tokenData[address].amount = ( Number(tokenData[address].amount) + Number(amount) ).toString(); } }); return { tokenIn: tokenData[inputContractAddress], tokenOut: tokenData[outputContractAddress], }; } } export function sellToPancakeSwap({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const from = txReceipt.from.toLowerCase(); const { logs } = txReceipt; const exchangeProxy = EXCHANGE_PROXY_BY_CHAIN_ID[56].toLowerCase(); let inputLog = logs.find((log) => log.from === from); let outputLog = logs.find((log) => log.from !== from); if (inputLog === undefined) { inputLog = logs.find((log) => log.from === exchangeProxy); outputLog = logs.find((log) => log.from !== exchangeProxy); } if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function executeMetaTransaction({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [metaTransaction] = txDescription.args; const [from] = metaTransaction as string[]; const { logs } = txReceipt; if (typeof from === "string") { const inputLog = logs.find((log) => log.from === from.toLowerCase()); const outputLog = logs.find((log) => log.to === from.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } } export function fillOtcOrderForEth({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const { logs } = txReceipt; const [order] = txDescription.args; const [makerToken, takerToken] = order as string[]; const inputLog = logs.find((log) => log.address === takerToken); const outputLog = logs.find((log) => log.address === makerToken); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function fillOtcOrderWithEth({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { return fillOtcOrderForEth({ txReceipt, txDescription }); } export function fillLimitOrder({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [order] = txDescription.args; const { 5: maker, 6: taker } = order as string[]; const { logs } = txReceipt; if (typeof maker === "string" && typeof taker === "string") { const inputLog = logs.find((log) => log.from === taker.toLowerCase()); const outputLog = logs.find((log) => log.from === maker.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } }
src/parsers/index.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/types.ts", "retrieved_chunk": "}\nexport type TransformERC20EventData = [string, string, string, bigint, bigint];\nexport interface ParseGaslessTxArgs {\n logParsers: LogParsers;\n chainId: SupportedChainId;\n exchangeProxyContract: Contract;\n tryBlockAndAggregate: TryBlockAndAggregate;\n transactionReceipt: TransactionReceipt;\n transactionDescription: TransactionDescription;\n}", "score": 26.82130579358239 }, { "filename": "src/index.ts", "retrieved_chunk": " transactionReceipt,\n transactionDescription,\n });\n }\n if (transactionDescription.name === \"transformERC20\") {\n return transformERC20({\n chainId,\n transactionReceipt,\n tryBlockAndAggregate,\n contract: exchangeProxyContract,", "score": 22.54061771113801 }, { "filename": "src/types.ts", "retrieved_chunk": " from: string;\n}\nexport type TryBlockAndAggregate = BaseContractMethod<\n [boolean, Call[]],\n AggregateResponse\n>;\nexport interface EnrichedTxReceiptArgs {\n transactionReceipt: TransactionReceipt;\n tryBlockAndAggregate: TryBlockAndAggregate;\n}", "score": 19.23572910685462 }, { "filename": "src/index.ts", "retrieved_chunk": " }\n}\nasync function parseGaslessTx({\n chainId,\n logParsers,\n exchangeProxyContract,\n tryBlockAndAggregate,\n transactionReceipt,\n transactionDescription,\n}: ParseGaslessTxArgs) {", "score": 18.149367176223155 }, { "filename": "src/index.ts", "retrieved_chunk": " if (transactionReceipt.status === TransactionStatus.REVERTED) return null;\n const chainId = Number(tx.chainId);\n if (!isChainIdSupported(chainId)) {\n throw new Error(`chainId ${chainId} is unsupported.`);\n }\n const exchangeProxyContract = new Contract(\n EXCHANGE_PROXY_BY_CHAIN_ID[chainId],\n exchangeProxyAbi\n );\n const permitAndCallAddress = isPermitAndCallChainId(chainId)", "score": 17.522259430291175 } ]
typescript
nativeSymbol = NATIVE_SYMBOL_BY_CHAIN_ID[chainId];
import { formatUnits } from "ethers"; import { extractTokenInfo, fetchSymbolAndDecimal } from "../utils"; import { CONTRACTS, NATIVE_ASSET, EVENT_SIGNATURES, NATIVE_SYMBOL_BY_CHAIN_ID, EXCHANGE_PROXY_BY_CHAIN_ID, } from "../constants"; import type { Contract, TransactionReceipt, TransactionDescription, } from "ethers"; import type { SupportedChainId, EnrichedTxReceipt, TryBlockAndAggregate, TransformERC20EventData, } from "../types"; export function sellToLiquidityProvider({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function multiplexMultiHopSellTokenForEth({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => log.address === CONTRACTS.weth); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function multiplexMultiHopSellEthForToken({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => log.address === CONTRACTS.weth); const outputLog = logs.find((log) => log.to === from.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function fillTakerSignedOtcOrder({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [order] = txDescription.args; const { logs } = txReceipt; const { 4: maker, 5: taker } = order as string[]; if (typeof maker === "string" && typeof taker === "string") { const inputLog = logs.find((log) => log.from === taker.toLowerCase()); const outputLog = logs.find((log) => log.from === maker.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } } export function fillOtcOrder({ txReceipt }: { txReceipt: EnrichedTxReceipt }) { const { logs, from } = txReceipt; const fromAddress = from.toLowerCase(); const inputLog = logs.find((log) => log.from === fromAddress); const outputLog = logs.find((log) => log.to === fromAddress); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function fillTakerSignedOtcOrderForEth({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs } = txReceipt; const inputLog = logs.find((log) => log.address !== CONTRACTS.weth); const outputLog = logs.find((log) => log.address === CONTRACTS.weth); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellTokenForEthToUniswapV3({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => log.from === from.toLowerCase()); const outputLog = logs.find((log) => log.from !== from.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellTokenForTokenToUniswapV3({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellEthForTokenToUniswapV3({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() !== log.to); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellToUniswap({ txReceipt }: { txReceipt: EnrichedTxReceipt }) { const [inputLog, outputLog] = txReceipt.logs; return extractTokenInfo(inputLog, outputLog); } export async function transformERC20({ chainId, contract, transactionReceipt, tryBlockAndAggregate, }: { contract: Contract; chainId: SupportedChainId; transactionReceipt: TransactionReceipt; tryBlockAndAggregate: TryBlockAndAggregate; }) { const nativeSymbol = NATIVE_SYMBOL_BY_CHAIN_ID[chainId]; for (const log of transactionReceipt.logs) { const { topics, data } = log; const [eventHash] = topics; if (eventHash === EVENT_SIGNATURES.TransformedERC20) { const logDescription = contract.interface.parseLog({ data, topics: [...topics], }); const { 1: inputToken, 2: outputToken, 3: inputTokenAmount, 4: outputTokenAmount, } = logDescription!.args as unknown as TransformERC20EventData; let inputSymbol: string; let inputDecimal: number; let outputSymbol: string; let outputDecimal: number; if (inputToken === NATIVE_ASSET) { inputSymbol = nativeSymbol; inputDecimal = 18; } else { [inputSymbol, inputDecimal] =
await fetchSymbolAndDecimal( inputToken, tryBlockAndAggregate );
} if (outputToken === NATIVE_ASSET) { outputSymbol = nativeSymbol; outputDecimal = 18; } else { [outputSymbol, outputDecimal] = await fetchSymbolAndDecimal( outputToken, tryBlockAndAggregate ); } const inputAmount = formatUnits(inputTokenAmount, inputDecimal); const outputAmount = formatUnits(outputTokenAmount, outputDecimal); return { tokenIn: { address: inputToken, amount: inputAmount, symbol: inputSymbol, }, tokenOut: { address: outputToken, amount: outputAmount, symbol: outputSymbol, }, }; } } } export function multiplexMultiHopSellTokenForToken({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function multiplexBatchSellTokenForEth({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { from, logs } = txReceipt; const tokenData = { [from.toLowerCase()]: { amount: "0", symbol: "", address: "" }, [CONTRACTS.weth.toLowerCase()]: { amount: "0", symbol: "ETH", address: NATIVE_ASSET, }, }; logs.forEach(({ address, symbol, amount, from }) => { const erc20Address = address.toLowerCase(); if (tokenData[erc20Address]) { tokenData[erc20Address].amount = String( Number(tokenData[erc20Address].amount) + Number(amount) ); } if (tokenData[from]) { tokenData[from].amount = String( Number(tokenData[from].amount) + Number(amount) ); tokenData[from].symbol = symbol; tokenData[from].address = address; } }); return { tokenIn: tokenData[from.toLowerCase()], tokenOut: tokenData[CONTRACTS.weth.toLowerCase()], }; } export function multiplexBatchSellEthForToken({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const { logs } = txReceipt; const { args, value } = txDescription; const { 0: outputToken } = args; const divisor = 1000000000000000000n; // 1e18, for conversion from wei to ether const etherBigInt = value / divisor; const remainderBigInt = value % divisor; const ether = Number(etherBigInt) + Number(remainderBigInt) / Number(divisor); const tokenOutAmount = logs.reduce((total, log) => { return log.address === outputToken ? total + Number(log.amount) : total; }, 0); const inputLog = logs.find((log) => log.address === CONTRACTS.weth); const outputLog = logs.find((log) => log.address === outputToken); if (inputLog && outputLog) { return { tokenIn: { symbol: inputLog.symbol, amount: ether.toString(), address: inputLog.address, }, tokenOut: { symbol: outputLog.symbol, amount: tokenOutAmount.toString(), address: outputLog.address, }, }; } } export function multiplexBatchSellTokenForToken({ txDescription, txReceipt, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [inputContractAddress, outputContractAddress] = txDescription.args; if ( typeof inputContractAddress === "string" && typeof outputContractAddress === "string" ) { const tokenData = { [inputContractAddress]: { amount: "0", symbol: "", address: "" }, [outputContractAddress]: { amount: "0", symbol: "", address: "" }, }; txReceipt.logs.forEach(({ address, symbol, amount }) => { if (address in tokenData) { tokenData[address].address = address; tokenData[address].symbol = symbol; tokenData[address].amount = ( Number(tokenData[address].amount) + Number(amount) ).toString(); } }); return { tokenIn: tokenData[inputContractAddress], tokenOut: tokenData[outputContractAddress], }; } } export function sellToPancakeSwap({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const from = txReceipt.from.toLowerCase(); const { logs } = txReceipt; const exchangeProxy = EXCHANGE_PROXY_BY_CHAIN_ID[56].toLowerCase(); let inputLog = logs.find((log) => log.from === from); let outputLog = logs.find((log) => log.from !== from); if (inputLog === undefined) { inputLog = logs.find((log) => log.from === exchangeProxy); outputLog = logs.find((log) => log.from !== exchangeProxy); } if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function executeMetaTransaction({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [metaTransaction] = txDescription.args; const [from] = metaTransaction as string[]; const { logs } = txReceipt; if (typeof from === "string") { const inputLog = logs.find((log) => log.from === from.toLowerCase()); const outputLog = logs.find((log) => log.to === from.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } } export function fillOtcOrderForEth({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const { logs } = txReceipt; const [order] = txDescription.args; const [makerToken, takerToken] = order as string[]; const inputLog = logs.find((log) => log.address === takerToken); const outputLog = logs.find((log) => log.address === makerToken); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function fillOtcOrderWithEth({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { return fillOtcOrderForEth({ txReceipt, txDescription }); } export function fillLimitOrder({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [order] = txDescription.args; const { 5: maker, 6: taker } = order as string[]; const { logs } = txReceipt; if (typeof maker === "string" && typeof taker === "string") { const inputLog = logs.find((log) => log.from === taker.toLowerCase()); const outputLog = logs.find((log) => log.from === maker.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } }
src/parsers/index.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/utils/index.ts", "retrieved_chunk": " return formattedFractionalPart.length > 0\n ? `${wholePart}.${formattedFractionalPart}`\n : wholePart.toString();\n}\nexport async function fetchSymbolAndDecimal(\n address: string,\n tryBlockAndAggregate: TryBlockAndAggregate\n): Promise<[string, number]> {\n const calls = [\n { target: address, callData: ERC20_FUNCTION_HASHES.symbol },", "score": 9.42352198415722 }, { "filename": "src/index.ts", "retrieved_chunk": " transactionReceipt,\n tryBlockAndAggregate,\n contract: exchangeProxyContract,\n });\n } else {\n const parser = logParsers[mtxV2Description.name];\n return processReceipt({\n signer,\n parser,\n recipient,", "score": 8.1335600070681 }, { "filename": "src/types.ts", "retrieved_chunk": " SUCCESSFUL = 1,\n}\nexport interface Log {\n transactionIndex: number;\n blockNumber: number;\n transactionHash: string;\n address: string;\n data: string;\n logIndex?: number;\n blockHash: string;", "score": 5.298020635319427 }, { "filename": "src/index.ts", "retrieved_chunk": " transactionDescription: permitAndCallDescription,\n });\n }\n }\n if (transactionDescription.name === \"executeMetaTransactionV2\") {\n return parseGaslessTx({\n chainId,\n logParsers,\n exchangeProxyContract,\n tryBlockAndAggregate,", "score": 4.573820481277901 }, { "filename": "src/index.ts", "retrieved_chunk": " transactionReceipt,\n transactionDescription,\n });\n }\n if (transactionDescription.name === \"transformERC20\") {\n return transformERC20({\n chainId,\n transactionReceipt,\n tryBlockAndAggregate,\n contract: exchangeProxyContract,", "score": 4.4658950610666945 } ]
typescript
await fetchSymbolAndDecimal( inputToken, tryBlockAndAggregate );
import { EVENT_SIGNATURES, ERC20_FUNCTION_HASHES } from "../constants"; import type { ProcessedLog, SupportedChainId, PermitAndCallChainIds, EnrichedTxReceipt, EnrichedTxReceiptArgs, EnrichedLogWithoutAmount, TryBlockAndAggregate, } from "../types"; export function convertHexToAddress(hexString: string): string { return `0x${hexString.slice(-40)}`; } export function isChainIdSupported( chainId: number ): chainId is SupportedChainId { return [1, 5, 10, 56, 137, 250, 8453, 42220, 43114, 42161].includes(chainId); } export function isPermitAndCallChainId( chainId: number ): chainId is PermitAndCallChainIds { return [1, 137, 8453].includes(chainId); } export function parseHexDataToString(hexData: string) { const dataLength = parseInt(hexData.slice(66, 130), 16); const data = hexData.slice(130, 130 + dataLength * 2); const bytes = new Uint8Array( data.match(/.{1,2}/g)?.map((byte: string) => parseInt(byte, 16)) ?? [] ); const textDecoder = new TextDecoder(); const utf8String = textDecoder.decode(bytes); return utf8String; } export function formatUnits(data: string, decimals: number) { const bigIntData = BigInt(data); const bigIntDecimals = BigInt(10 ** decimals); const wholePart = bigIntData / bigIntDecimals; const fractionalPart = bigIntData % bigIntDecimals; const paddedFractionalPart = String(fractionalPart).padStart(decimals, "0"); const formattedFractionalPart = paddedFractionalPart.replace(/0+$/, ""); return formattedFractionalPart.length > 0 ? `${wholePart}.${formattedFractionalPart}` : wholePart.toString(); } export async function fetchSymbolAndDecimal( address: string, tryBlockAndAggregate: TryBlockAndAggregate ): Promise<[string, number]> { const calls = [ { target: address, callData: ERC20_FUNCTION_HASHES.symbol }, { target: address, callData: ERC20_FUNCTION_HASHES.decimals }, ]; const { 2: results } = await tryBlockAndAggregate.staticCall(false, calls); const [symbolResult, decimalsResult] = results; const symbol = parseHexDataToString(symbolResult.returnData); const decimals = Number(BigInt(decimalsResult.returnData)); return [symbol, decimals]; } function processLog(log: EnrichedLogWithoutAmount): ProcessedLog { const { topics, data, decimals, symbol, address } = log; const { 1: fromHex, 2: toHex } = topics; const from = convertHexToAddress(fromHex); const to = convertHexToAddress(toHex); const amount = formatUnits(data, decimals); return { to, from, symbol, amount, address, decimals }; } export async function enrichTxReceipt({ transactionReceipt, tryBlockAndAggregate, }: EnrichedTxReceiptArgs): Promise<EnrichedTxReceipt> { const { from, logs } = transactionReceipt; const filteredLogs = logs.filter( (log) => log.topics[
0] === EVENT_SIGNATURES.Transfer );
const calls = filteredLogs.flatMap((log) => [ { target: log.address, callData: ERC20_FUNCTION_HASHES.symbol }, { target: log.address, callData: ERC20_FUNCTION_HASHES.decimals }, ]); const { 2: results } = await tryBlockAndAggregate.staticCall(false, calls); const enrichedLogs = filteredLogs.map((log, i) => { const symbolResult = results[i * 2]; const decimalsResult = results[i * 2 + 1]; const enrichedLog = { ...log, symbol: parseHexDataToString(symbolResult.returnData), decimals: Number(BigInt(decimalsResult.returnData)), }; return processLog(enrichedLog); }); return { from, logs: enrichedLogs }; } export function extractTokenInfo( inputLog: ProcessedLog, outputLog: ProcessedLog ) { return { tokenIn: { symbol: inputLog.symbol, amount: inputLog.amount, address: inputLog.address, }, tokenOut: { symbol: outputLog.symbol, amount: outputLog.amount, address: outputLog.address, }, }; }
src/utils/index.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/index.ts", "retrieved_chunk": " tryBlockAndAggregate,\n transactionReceipt,\n transactionDescription,\n}: ProcessReceiptArgs) {\n const enrichedTxReceipt = await enrichTxReceipt({\n transactionReceipt,\n tryBlockAndAggregate,\n });\n const { logs } = enrichedTxReceipt;\n const filteredLogs = logs.filter((log) => log.to !== recipient.toLowerCase());", "score": 38.11778274134851 }, { "filename": "src/parsers/index.ts", "retrieved_chunk": "}: {\n contract: Contract;\n chainId: SupportedChainId;\n transactionReceipt: TransactionReceipt;\n tryBlockAndAggregate: TryBlockAndAggregate;\n}) {\n const nativeSymbol = NATIVE_SYMBOL_BY_CHAIN_ID[chainId];\n for (const log of transactionReceipt.logs) {\n const { topics, data } = log;\n const [eventHash] = topics;", "score": 27.096711803300675 }, { "filename": "src/parsers/index.ts", "retrieved_chunk": " }\n}\nexport function multiplexMultiHopSellTokenForEth({\n txReceipt,\n}: {\n txReceipt: EnrichedTxReceipt;\n}) {\n const { logs, from } = txReceipt;\n const inputLog = logs.find((log) => from.toLowerCase() === log.from);\n const outputLog = logs.find((log) => log.address === CONTRACTS.weth);", "score": 22.28641188055544 }, { "filename": "src/parsers/index.ts", "retrieved_chunk": " txReceipt: EnrichedTxReceipt;\n}) {\n const { logs, from } = txReceipt;\n const inputLog = logs.find((log) => from.toLowerCase() === log.from);\n const outputLog = logs.find((log) => from.toLowerCase() === log.to);\n if (inputLog && outputLog) {\n return extractTokenInfo(inputLog, outputLog);\n }\n}\nexport function sellEthForTokenToUniswapV3({", "score": 21.026392525229586 }, { "filename": "src/parsers/index.ts", "retrieved_chunk": "export function sellToLiquidityProvider({\n txReceipt,\n}: {\n txReceipt: EnrichedTxReceipt;\n}) {\n const { logs, from } = txReceipt;\n const inputLog = logs.find((log) => from.toLowerCase() === log.from);\n const outputLog = logs.find((log) => from.toLowerCase() === log.to);\n if (inputLog && outputLog) {\n return extractTokenInfo(inputLog, outputLog);", "score": 20.8150130433926 } ]
typescript
0] === EVENT_SIGNATURES.Transfer );
import { Contract, JsonRpcProvider } from "ethers"; import { abi as permitAndCallAbi } from "./abi/PermitAndCall.json"; import multicall3Abi from "./abi/Multicall3.json"; import { MULTICALL3, EXCHANGE_PROXY_ABI_URL, EXCHANGE_PROXY_BY_CHAIN_ID, PERMIT_AND_CALL_BY_CHAIN_ID, } from "./constants"; import { fillLimitOrder, fillOtcOrder, fillOtcOrderForEth, fillOtcOrderWithEth, fillTakerSignedOtcOrder, fillTakerSignedOtcOrderForEth, executeMetaTransaction, multiplexBatchSellTokenForToken, multiplexBatchSellTokenForEth, multiplexBatchSellEthForToken, multiplexMultiHopSellTokenForToken, multiplexMultiHopSellEthForToken, multiplexMultiHopSellTokenForEth, sellToUniswap, sellTokenForEthToUniswapV3, sellEthForTokenToUniswapV3, sellTokenForTokenToUniswapV3, sellToLiquidityProvider, sellToPancakeSwap, transformERC20, } from "./parsers"; import { enrichTxReceipt, isChainIdSupported, isPermitAndCallChainId, } from "./utils"; import { TransactionStatus } from "./types"; import type { Mtx, LogParsers, ParseSwapArgs, ParseGaslessTxArgs, ProcessReceiptArgs, } from "./types"; export * from "./types"; export async function parseSwap({ transactionHash, exchangeProxyAbi, rpcUrl, }: ParseSwapArgs) { if (!rpcUrl) throw new Error("Missing rpcUrl"); if (!transactionHash) throw new Error("Missing transaction hash"); if (!exchangeProxyAbi) throw new Error(`Missing 0x Exchange Proxy ABI: ${EXCHANGE_PROXY_ABI_URL}`); const provider = new JsonRpcProvider(rpcUrl); const [tx, transactionReceipt] = await Promise.all([ provider.getTransaction(transactionHash), provider.getTransactionReceipt(transactionHash), ]); if (tx && transactionReceipt) { if (transactionReceipt.status === TransactionStatus.REVERTED) return null; const chainId = Number(tx.chainId); if (!isChainIdSupported(chainId)) { throw new Error(`chainId ${chainId} is unsupported.`); } const exchangeProxyContract = new Contract( EXCHANGE_PROXY_BY_CHAIN_ID[chainId], exchangeProxyAbi ); const permitAndCallAddress = isPermitAndCallChainId(chainId) ? PERMIT_AND_CALL_BY_CHAIN_ID[chainId] : undefined; const permitAndCallContract = permitAndCallAddress ? new Contract(permitAndCallAddress, permitAndCallAbi) : undefined; const transactionDescription = transactionReceipt.to === permitAndCallAddress ? permitAndCallContract?.interface.parseTransaction(tx) : exchangeProxyContract.interface.parseTransaction(tx); if (!transactionDescription) return null; const multicall = new Contract
(MULTICALL3, multicall3Abi, provider);
const tryBlockAndAggregate = multicall[ "tryBlockAndAggregate(bool requireSuccess, tuple(address target, bytes callData)[] calls)" ]; const logParsers: LogParsers = { fillLimitOrder, fillOtcOrder, fillOtcOrderForEth, fillOtcOrderWithEth, fillTakerSignedOtcOrder, fillTakerSignedOtcOrderForEth, executeMetaTransaction, multiplexBatchSellTokenForToken, multiplexBatchSellTokenForEth, multiplexBatchSellEthForToken, multiplexMultiHopSellTokenForToken, multiplexMultiHopSellEthForToken, multiplexMultiHopSellTokenForEth, sellToUniswap, sellTokenForEthToUniswapV3, sellEthForTokenToUniswapV3, sellTokenForTokenToUniswapV3, sellToLiquidityProvider, sellToPancakeSwap, }; const parser = logParsers[transactionDescription.name]; if (transactionDescription.name === "permitAndCall") { const calldataFromPermitAndCall = transactionDescription.args[7]; const permitAndCallDescription = exchangeProxyContract.interface.parseTransaction({ data: calldataFromPermitAndCall, }); if (permitAndCallDescription) { return parseGaslessTx({ chainId, logParsers, tryBlockAndAggregate, exchangeProxyContract, transactionReceipt, transactionDescription: permitAndCallDescription, }); } } if (transactionDescription.name === "executeMetaTransactionV2") { return parseGaslessTx({ chainId, logParsers, exchangeProxyContract, tryBlockAndAggregate, transactionReceipt, transactionDescription, }); } if (transactionDescription.name === "transformERC20") { return transformERC20({ chainId, transactionReceipt, tryBlockAndAggregate, contract: exchangeProxyContract, }); } const txReceiptEnriched = await enrichTxReceipt({ transactionReceipt, tryBlockAndAggregate, }); return parser({ txDescription: transactionDescription, txReceipt: txReceiptEnriched, }); } } async function parseGaslessTx({ chainId, logParsers, exchangeProxyContract, tryBlockAndAggregate, transactionReceipt, transactionDescription, }: ParseGaslessTxArgs) { const [mtx] = transactionDescription.args; const { 0: signer, 4: data, 6: fees } = mtx as Mtx; const [recipient] = fees[0]; const mtxV2Description = exchangeProxyContract.interface.parseTransaction({ data, }); if (mtxV2Description) { if (mtxV2Description.name === "transformERC20") { return transformERC20({ chainId, transactionReceipt, tryBlockAndAggregate, contract: exchangeProxyContract, }); } else { const parser = logParsers[mtxV2Description.name]; return processReceipt({ signer, parser, recipient, tryBlockAndAggregate, transactionReceipt, transactionDescription: mtxV2Description, }); } } const parser = logParsers[transactionDescription.name]; return processReceipt({ signer, parser, recipient, tryBlockAndAggregate, transactionReceipt, transactionDescription, }); } async function processReceipt({ signer, parser, recipient, tryBlockAndAggregate, transactionReceipt, transactionDescription, }: ProcessReceiptArgs) { const enrichedTxReceipt = await enrichTxReceipt({ transactionReceipt, tryBlockAndAggregate, }); const { logs } = enrichedTxReceipt; const filteredLogs = logs.filter((log) => log.to !== recipient.toLowerCase()); return parser({ txDescription: transactionDescription, txReceipt: { from: signer, logs: filteredLogs }, }); }
src/index.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/types.ts", "retrieved_chunk": "}\nexport type TransformERC20EventData = [string, string, string, bigint, bigint];\nexport interface ParseGaslessTxArgs {\n logParsers: LogParsers;\n chainId: SupportedChainId;\n exchangeProxyContract: Contract;\n tryBlockAndAggregate: TryBlockAndAggregate;\n transactionReceipt: TransactionReceipt;\n transactionDescription: TransactionDescription;\n}", "score": 29.557003402705345 }, { "filename": "src/tests/transformERC20.test.ts", "retrieved_chunk": "}\ndescribe(\"transformERC20\", () => {\n it(\"returns undefined when TransformedERC20 topic is not found in logs\", async () => {\n const contract = new Contract(\n EXCHANGE_PROXY_BY_CHAIN_ID[1],\n EXCHANGE_PROXY_ABI.compilerOutput.abi\n );\n const transactionReceipt = {\n from: \"0x8C410057a8933d579926dEcCD043921A974A24ee\",\n hash: \"0xee3ffb65f6c8e07b46471cc610cf721affeefed87098c7db30a8147d50eb2a65\",", "score": 19.938763197997538 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface ProcessReceiptArgs {\n signer: string;\n recipient: string;\n parser: ParserFunction;\n transactionReceipt: TransactionReceipt;\n tryBlockAndAggregate: TryBlockAndAggregate;\n transactionDescription: TransactionDescription;\n}\nexport enum TransactionStatus {\n REVERTED = 0,", "score": 18.850436779908797 }, { "filename": "src/parsers/index.ts", "retrieved_chunk": "}: {\n contract: Contract;\n chainId: SupportedChainId;\n transactionReceipt: TransactionReceipt;\n tryBlockAndAggregate: TryBlockAndAggregate;\n}) {\n const nativeSymbol = NATIVE_SYMBOL_BY_CHAIN_ID[chainId];\n for (const log of transactionReceipt.logs) {\n const { topics, data } = log;\n const [eventHash] = topics;", "score": 16.285640621817706 }, { "filename": "src/tests/transformERC20.test.ts", "retrieved_chunk": " logs: [],\n to: \"0xDef1C0ded9bec7F1a1670819833240f027b25EfF\",\n };\n const result = await transformERC20({\n transactionReceipt,\n contract,\n rpcUrl: ETH_MAINNET_RPC,\n } as any);\n expect(result).toBe(undefined);\n });", "score": 14.372115605136818 } ]
typescript
(MULTICALL3, multicall3Abi, provider);
import { HttpModule } from '@nestjs/axios'; import { DynamicModule, Module, Provider, Type } from '@nestjs/common'; import { WatchmanService } from './Watchman.service'; import { WatchmanModuleAsyncOptions, WatchmanModuleFactory, WatchmanModuleOptions, } from './interfaces'; import { STRATEGY_TOKEN, Watchman_OPTIONS } from './constants'; import { BaseStrategy, injectStrategies, strategyDependenciesProviders, strategyProviders, } from './strategies'; @Module({}) export class WatchmanModule { static forRoot(option: WatchmanModuleOptions): DynamicModule { const provider: Provider<any> = { provide: WatchmanService, useFactory: (config: WatchmanModuleOptions, ...args: BaseStrategy[]) => { if (!option.strategy) throw new Error('Please Provide Strategy class'); const loadedStrategy = args.find( (injectedStrategy) => injectedStrategy && injectedStrategy instanceof option.strategy, ); if (!config.strategyConfig) throw new Error('Please set your config in strategyConfig object'); return new WatchmanService(config, loadedStrategy); }, inject: [Watchman_OPTIONS, ...injectStrategies], }; return { providers: [ provider, { provide: Watchman_OPTIONS, useValue: option }, ...strategyDependenciesProviders, ...strategyProviders, ], exports: [provider], module: WatchmanModule, imports: [HttpModule], }; } static forRootAsync(options: WatchmanModuleAsyncOptions): DynamicModule { const provider: Provider = { provide: WatchmanService, useFactory: async ( config: WatchmanModuleOptions, ...args: BaseStrategy[] ) => { const strategy = options.strategy || config.strategy; if (!strategy) throw new Error('Please Provide Strategy class'); const loadedStrategy = args.find( (injectedStrategy) => injectedStrategy && injectedStrategy instanceof strategy, ); if (!options.strategy) { if (!config.strategyConfig) throw new Error('Please set your config in strategyConfig object'); } return new WatchmanService(config, loadedStrategy); }, inject: [ { token: Watchman_OPTIONS, optional: true }, {
token: STRATEGY_TOKEN, optional: true }, ...injectStrategies, ], };
return { module: WatchmanModule, imports: [...(options.imports || []), HttpModule], providers: [ ...this.createAsyncProviders(options), provider, ...strategyProviders, ...strategyDependenciesProviders, { provide: STRATEGY_TOKEN, useClass: options.strategy, }, ], exports: [provider], }; } private static createAsyncProviders( options: WatchmanModuleAsyncOptions, ): Provider[] { if (options.useExisting || options.useFactory) { return [this.createAsyncOptionsProvider(options)]; } const useClass = options.useClass as Type<WatchmanModuleFactory>; if (useClass) return [ this.createAsyncOptionsProvider(options), { provide: useClass, useClass, }, ]; return [ { provide: Watchman_OPTIONS, useValue: null, }, ]; } private static createAsyncOptionsProvider( options: WatchmanModuleAsyncOptions, ): Provider { if (options.useFactory) { return { provide: Watchman_OPTIONS, useFactory: options.useFactory, inject: options.inject || [], }; } const inject = [ (options.useClass || options.useExisting) as Type<WatchmanModuleFactory>, ]; return { provide: Watchman_OPTIONS, useFactory: async (optionsFactory: WatchmanModuleFactory) => await optionsFactory.createWatchmanModuleOptions(), inject, }; } }
src/Watchman.module.ts
dev-codenix-nest-watchman-5b19369
[ { "filename": "src/strategies/discord.strategy.ts", "retrieved_chunk": " name: 'Route',\n value: this.request.path,\n inline: true,\n },\n {\n name: 'Http Method',\n value: this.request.method,\n inline: true,\n },\n {", "score": 9.662891611788476 }, { "filename": "src/constants/provider-names.ts", "retrieved_chunk": "export const Watchman_OPTIONS = 'WatchmanOptions';\nexport const STRATEGY_TOKEN = 'STRATEGY';", "score": 8.953593966796166 }, { "filename": "src/strategies/base.strategy.ts", "retrieved_chunk": " set config(config: StrategyConfig) {\n this.strategyConfig = config;\n }\n private extractErrorFileNameFromPath(path: string): string | null {\n return (\n path\n .slice(path.lastIndexOf('/'))\n .replace('/', '')\n .replace(/\\(|\\)/gi, '') || null\n );", "score": 5.144111099620998 }, { "filename": "src/interfaces/discord.interface.ts", "retrieved_chunk": " */\n avatar_url?: string;\n /**\n * @description true if this is a TTS message\n */\n tts?: boolean;\n /**\n * @description message can be generated in embeds\n * @overview Array of up to 10 embed objects\n * @see {@link https://discord.com/developers/docs/resources/channel#embed-object Embed Object Structure}", "score": 4.9663147057820325 }, { "filename": "src/strategies/base.strategy.ts", "retrieved_chunk": " get filePath(): string {\n return this._filePath;\n }\n get fileName(): string {\n return this._fileName;\n }\n get config(): StrategyConfig {\n if (!this.strategyConfig) return this._options.strategyConfig;\n return this.strategyConfig;\n }", "score": 4.655040180065187 } ]
typescript
token: STRATEGY_TOKEN, optional: true }, ...injectStrategies, ], };
import { EVENT_SIGNATURES, ERC20_FUNCTION_HASHES } from "../constants"; import type { ProcessedLog, SupportedChainId, PermitAndCallChainIds, EnrichedTxReceipt, EnrichedTxReceiptArgs, EnrichedLogWithoutAmount, TryBlockAndAggregate, } from "../types"; export function convertHexToAddress(hexString: string): string { return `0x${hexString.slice(-40)}`; } export function isChainIdSupported( chainId: number ): chainId is SupportedChainId { return [1, 5, 10, 56, 137, 250, 8453, 42220, 43114, 42161].includes(chainId); } export function isPermitAndCallChainId( chainId: number ): chainId is PermitAndCallChainIds { return [1, 137, 8453].includes(chainId); } export function parseHexDataToString(hexData: string) { const dataLength = parseInt(hexData.slice(66, 130), 16); const data = hexData.slice(130, 130 + dataLength * 2); const bytes = new Uint8Array( data.match(/.{1,2}/g)?.map((byte: string) => parseInt(byte, 16)) ?? [] ); const textDecoder = new TextDecoder(); const utf8String = textDecoder.decode(bytes); return utf8String; } export function formatUnits(data: string, decimals: number) { const bigIntData = BigInt(data); const bigIntDecimals = BigInt(10 ** decimals); const wholePart = bigIntData / bigIntDecimals; const fractionalPart = bigIntData % bigIntDecimals; const paddedFractionalPart = String(fractionalPart).padStart(decimals, "0"); const formattedFractionalPart = paddedFractionalPart.replace(/0+$/, ""); return formattedFractionalPart.length > 0 ? `${wholePart}.${formattedFractionalPart}` : wholePart.toString(); } export async function fetchSymbolAndDecimal( address: string, tryBlockAndAggregate: TryBlockAndAggregate ): Promise<[string, number]> { const calls = [
{ target: address, callData: ERC20_FUNCTION_HASHES.symbol }, { target: address, callData: ERC20_FUNCTION_HASHES.decimals }, ];
const { 2: results } = await tryBlockAndAggregate.staticCall(false, calls); const [symbolResult, decimalsResult] = results; const symbol = parseHexDataToString(symbolResult.returnData); const decimals = Number(BigInt(decimalsResult.returnData)); return [symbol, decimals]; } function processLog(log: EnrichedLogWithoutAmount): ProcessedLog { const { topics, data, decimals, symbol, address } = log; const { 1: fromHex, 2: toHex } = topics; const from = convertHexToAddress(fromHex); const to = convertHexToAddress(toHex); const amount = formatUnits(data, decimals); return { to, from, symbol, amount, address, decimals }; } export async function enrichTxReceipt({ transactionReceipt, tryBlockAndAggregate, }: EnrichedTxReceiptArgs): Promise<EnrichedTxReceipt> { const { from, logs } = transactionReceipt; const filteredLogs = logs.filter( (log) => log.topics[0] === EVENT_SIGNATURES.Transfer ); const calls = filteredLogs.flatMap((log) => [ { target: log.address, callData: ERC20_FUNCTION_HASHES.symbol }, { target: log.address, callData: ERC20_FUNCTION_HASHES.decimals }, ]); const { 2: results } = await tryBlockAndAggregate.staticCall(false, calls); const enrichedLogs = filteredLogs.map((log, i) => { const symbolResult = results[i * 2]; const decimalsResult = results[i * 2 + 1]; const enrichedLog = { ...log, symbol: parseHexDataToString(symbolResult.returnData), decimals: Number(BigInt(decimalsResult.returnData)), }; return processLog(enrichedLog); }); return { from, logs: enrichedLogs }; } export function extractTokenInfo( inputLog: ProcessedLog, outputLog: ProcessedLog ) { return { tokenIn: { symbol: inputLog.symbol, amount: inputLog.amount, address: inputLog.address, }, tokenOut: { symbol: outputLog.symbol, amount: outputLog.amount, address: outputLog.address, }, }; }
src/utils/index.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/types.ts", "retrieved_chunk": "export interface CallResult {\n success: boolean;\n returnData: string;\n}\ninterface Call {\n target: string;\n callData: string;\n}\ntype BlockHash = string;\nexport type AggregateResponse = [bigint, BlockHash, CallResult[]];", "score": 27.967520305877397 }, { "filename": "src/index.ts", "retrieved_chunk": " const multicall = new Contract(MULTICALL3, multicall3Abi, provider);\n const tryBlockAndAggregate =\n multicall[\n \"tryBlockAndAggregate(bool requireSuccess, tuple(address target, bytes callData)[] calls)\"\n ];\n const logParsers: LogParsers = {\n fillLimitOrder,\n fillOtcOrder,\n fillOtcOrderForEth,\n fillOtcOrderWithEth,", "score": 27.784451709525154 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface ProcessedLog {\n to: string;\n from: string;\n symbol: string;\n amount: string;\n address: string;\n decimals: number;\n}\nexport interface EnrichedTxReceipt {\n logs: ProcessedLog[];", "score": 21.073371970694815 }, { "filename": "src/constants.ts", "retrieved_chunk": " Transfer:\n \"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\",\n TransformedERC20:\n \"0x0f6672f78a59ba8e5e5b5d38df3ebc67f3c792e2c9259b8d97d7f00dd78ba1b3\",\n} as const;\nexport const ERC20_FUNCTION_HASHES = {\n symbol: \"0x95d89b41\",\n decimals: \"0x313ce567\",\n} as const;\nexport const EXCHANGE_PROXY_ABI_URL =", "score": 19.976265416170595 }, { "filename": "src/types.ts", "retrieved_chunk": " topics: readonly string[];\n}\nexport interface EnrichedLogWithoutAmount extends Log {\n symbol: string;\n decimals: number;\n from?: string;\n}\nexport interface ParseSwapArgs {\n transactionHash: string;\n exchangeProxyAbi?: typeof exchangeProxyAbi;", "score": 18.240516371880425 } ]
typescript
{ target: address, callData: ERC20_FUNCTION_HASHES.symbol }, { target: address, callData: ERC20_FUNCTION_HASHES.decimals }, ];
import { EVENT_SIGNATURES, ERC20_FUNCTION_HASHES } from "../constants"; import type { ProcessedLog, SupportedChainId, PermitAndCallChainIds, EnrichedTxReceipt, EnrichedTxReceiptArgs, EnrichedLogWithoutAmount, TryBlockAndAggregate, } from "../types"; export function convertHexToAddress(hexString: string): string { return `0x${hexString.slice(-40)}`; } export function isChainIdSupported( chainId: number ): chainId is SupportedChainId { return [1, 5, 10, 56, 137, 250, 8453, 42220, 43114, 42161].includes(chainId); } export function isPermitAndCallChainId( chainId: number ): chainId is PermitAndCallChainIds { return [1, 137, 8453].includes(chainId); } export function parseHexDataToString(hexData: string) { const dataLength = parseInt(hexData.slice(66, 130), 16); const data = hexData.slice(130, 130 + dataLength * 2); const bytes = new Uint8Array( data.match(/.{1,2}/g)?.map((byte: string) => parseInt(byte, 16)) ?? [] ); const textDecoder = new TextDecoder(); const utf8String = textDecoder.decode(bytes); return utf8String; } export function formatUnits(data: string, decimals: number) { const bigIntData = BigInt(data); const bigIntDecimals = BigInt(10 ** decimals); const wholePart = bigIntData / bigIntDecimals; const fractionalPart = bigIntData % bigIntDecimals; const paddedFractionalPart = String(fractionalPart).padStart(decimals, "0"); const formattedFractionalPart = paddedFractionalPart.replace(/0+$/, ""); return formattedFractionalPart.length > 0 ? `${wholePart}.${formattedFractionalPart}` : wholePart.toString(); } export async function fetchSymbolAndDecimal( address: string, tryBlockAndAggregate: TryBlockAndAggregate ): Promise<[string, number]> { const calls = [ { target: address, callData
: ERC20_FUNCTION_HASHES.symbol }, { target: address, callData: ERC20_FUNCTION_HASHES.decimals }, ];
const { 2: results } = await tryBlockAndAggregate.staticCall(false, calls); const [symbolResult, decimalsResult] = results; const symbol = parseHexDataToString(symbolResult.returnData); const decimals = Number(BigInt(decimalsResult.returnData)); return [symbol, decimals]; } function processLog(log: EnrichedLogWithoutAmount): ProcessedLog { const { topics, data, decimals, symbol, address } = log; const { 1: fromHex, 2: toHex } = topics; const from = convertHexToAddress(fromHex); const to = convertHexToAddress(toHex); const amount = formatUnits(data, decimals); return { to, from, symbol, amount, address, decimals }; } export async function enrichTxReceipt({ transactionReceipt, tryBlockAndAggregate, }: EnrichedTxReceiptArgs): Promise<EnrichedTxReceipt> { const { from, logs } = transactionReceipt; const filteredLogs = logs.filter( (log) => log.topics[0] === EVENT_SIGNATURES.Transfer ); const calls = filteredLogs.flatMap((log) => [ { target: log.address, callData: ERC20_FUNCTION_HASHES.symbol }, { target: log.address, callData: ERC20_FUNCTION_HASHES.decimals }, ]); const { 2: results } = await tryBlockAndAggregate.staticCall(false, calls); const enrichedLogs = filteredLogs.map((log, i) => { const symbolResult = results[i * 2]; const decimalsResult = results[i * 2 + 1]; const enrichedLog = { ...log, symbol: parseHexDataToString(symbolResult.returnData), decimals: Number(BigInt(decimalsResult.returnData)), }; return processLog(enrichedLog); }); return { from, logs: enrichedLogs }; } export function extractTokenInfo( inputLog: ProcessedLog, outputLog: ProcessedLog ) { return { tokenIn: { symbol: inputLog.symbol, amount: inputLog.amount, address: inputLog.address, }, tokenOut: { symbol: outputLog.symbol, amount: outputLog.amount, address: outputLog.address, }, }; }
src/utils/index.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/types.ts", "retrieved_chunk": "export interface CallResult {\n success: boolean;\n returnData: string;\n}\ninterface Call {\n target: string;\n callData: string;\n}\ntype BlockHash = string;\nexport type AggregateResponse = [bigint, BlockHash, CallResult[]];", "score": 27.967520305877397 }, { "filename": "src/index.ts", "retrieved_chunk": " const multicall = new Contract(MULTICALL3, multicall3Abi, provider);\n const tryBlockAndAggregate =\n multicall[\n \"tryBlockAndAggregate(bool requireSuccess, tuple(address target, bytes callData)[] calls)\"\n ];\n const logParsers: LogParsers = {\n fillLimitOrder,\n fillOtcOrder,\n fillOtcOrderForEth,\n fillOtcOrderWithEth,", "score": 27.784451709525154 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface ProcessedLog {\n to: string;\n from: string;\n symbol: string;\n amount: string;\n address: string;\n decimals: number;\n}\nexport interface EnrichedTxReceipt {\n logs: ProcessedLog[];", "score": 21.073371970694815 }, { "filename": "src/constants.ts", "retrieved_chunk": " Transfer:\n \"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\",\n TransformedERC20:\n \"0x0f6672f78a59ba8e5e5b5d38df3ebc67f3c792e2c9259b8d97d7f00dd78ba1b3\",\n} as const;\nexport const ERC20_FUNCTION_HASHES = {\n symbol: \"0x95d89b41\",\n decimals: \"0x313ce567\",\n} as const;\nexport const EXCHANGE_PROXY_ABI_URL =", "score": 19.976265416170595 }, { "filename": "src/types.ts", "retrieved_chunk": " topics: readonly string[];\n}\nexport interface EnrichedLogWithoutAmount extends Log {\n symbol: string;\n decimals: number;\n from?: string;\n}\nexport interface ParseSwapArgs {\n transactionHash: string;\n exchangeProxyAbi?: typeof exchangeProxyAbi;", "score": 18.240516371880425 } ]
typescript
: ERC20_FUNCTION_HASHES.symbol }, { target: address, callData: ERC20_FUNCTION_HASHES.decimals }, ];
import { formatUnits } from "ethers"; import { extractTokenInfo, fetchSymbolAndDecimal } from "../utils"; import { CONTRACTS, NATIVE_ASSET, EVENT_SIGNATURES, NATIVE_SYMBOL_BY_CHAIN_ID, EXCHANGE_PROXY_BY_CHAIN_ID, } from "../constants"; import type { Contract, TransactionReceipt, TransactionDescription, } from "ethers"; import type { SupportedChainId, EnrichedTxReceipt, TryBlockAndAggregate, TransformERC20EventData, } from "../types"; export function sellToLiquidityProvider({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function multiplexMultiHopSellTokenForEth({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => log.address === CONTRACTS.weth); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function multiplexMultiHopSellEthForToken({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => log.address === CONTRACTS.weth); const outputLog = logs.find((log) => log.to === from.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function fillTakerSignedOtcOrder({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [order] = txDescription.args; const { logs } = txReceipt; const { 4: maker, 5: taker } = order as string[]; if (typeof maker === "string" && typeof taker === "string") { const inputLog = logs.find((log) => log.from === taker.toLowerCase()); const outputLog = logs.find((log) => log.from === maker.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } } export function fillOtcOrder({ txReceipt }: { txReceipt: EnrichedTxReceipt }) { const { logs, from } = txReceipt; const fromAddress = from.toLowerCase(); const inputLog = logs.find((log) => log.from === fromAddress); const outputLog = logs.find((log) => log.to === fromAddress); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function fillTakerSignedOtcOrderForEth({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs } = txReceipt; const inputLog = logs.find((log) => log.address !== CONTRACTS.weth); const outputLog = logs.find((log) => log.address === CONTRACTS.weth); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellTokenForEthToUniswapV3({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => log.from === from.toLowerCase()); const outputLog = logs.find((log) => log.from !== from.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellTokenForTokenToUniswapV3({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellEthForTokenToUniswapV3({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() !== log.to); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function sellToUniswap({ txReceipt }: { txReceipt: EnrichedTxReceipt }) { const [inputLog, outputLog] = txReceipt.logs; return extractTokenInfo(inputLog, outputLog); } export async function transformERC20({ chainId, contract, transactionReceipt, tryBlockAndAggregate, }: { contract: Contract; chainId: SupportedChainId; transactionReceipt: TransactionReceipt; tryBlockAndAggregate: TryBlockAndAggregate; }) { const nativeSymbol = NATIVE_SYMBOL_BY_CHAIN_ID[chainId]; for (const log of transactionReceipt.logs) { const { topics, data } = log; const [eventHash] = topics; if (eventHash === EVENT_SIGNATURES.TransformedERC20) { const logDescription = contract.interface.parseLog({ data, topics: [...topics], }); const { 1: inputToken, 2: outputToken, 3: inputTokenAmount, 4: outputTokenAmount, } = logDescription!.args as unknown as TransformERC20EventData; let inputSymbol: string; let inputDecimal: number; let outputSymbol: string; let outputDecimal: number; if (inputToken === NATIVE_ASSET) { inputSymbol = nativeSymbol; inputDecimal = 18; } else { [inputSymbol, inputDecimal
] = await fetchSymbolAndDecimal( inputToken, tryBlockAndAggregate );
} if (outputToken === NATIVE_ASSET) { outputSymbol = nativeSymbol; outputDecimal = 18; } else { [outputSymbol, outputDecimal] = await fetchSymbolAndDecimal( outputToken, tryBlockAndAggregate ); } const inputAmount = formatUnits(inputTokenAmount, inputDecimal); const outputAmount = formatUnits(outputTokenAmount, outputDecimal); return { tokenIn: { address: inputToken, amount: inputAmount, symbol: inputSymbol, }, tokenOut: { address: outputToken, amount: outputAmount, symbol: outputSymbol, }, }; } } } export function multiplexMultiHopSellTokenForToken({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { logs, from } = txReceipt; const inputLog = logs.find((log) => from.toLowerCase() === log.from); const outputLog = logs.find((log) => from.toLowerCase() === log.to); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function multiplexBatchSellTokenForEth({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const { from, logs } = txReceipt; const tokenData = { [from.toLowerCase()]: { amount: "0", symbol: "", address: "" }, [CONTRACTS.weth.toLowerCase()]: { amount: "0", symbol: "ETH", address: NATIVE_ASSET, }, }; logs.forEach(({ address, symbol, amount, from }) => { const erc20Address = address.toLowerCase(); if (tokenData[erc20Address]) { tokenData[erc20Address].amount = String( Number(tokenData[erc20Address].amount) + Number(amount) ); } if (tokenData[from]) { tokenData[from].amount = String( Number(tokenData[from].amount) + Number(amount) ); tokenData[from].symbol = symbol; tokenData[from].address = address; } }); return { tokenIn: tokenData[from.toLowerCase()], tokenOut: tokenData[CONTRACTS.weth.toLowerCase()], }; } export function multiplexBatchSellEthForToken({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const { logs } = txReceipt; const { args, value } = txDescription; const { 0: outputToken } = args; const divisor = 1000000000000000000n; // 1e18, for conversion from wei to ether const etherBigInt = value / divisor; const remainderBigInt = value % divisor; const ether = Number(etherBigInt) + Number(remainderBigInt) / Number(divisor); const tokenOutAmount = logs.reduce((total, log) => { return log.address === outputToken ? total + Number(log.amount) : total; }, 0); const inputLog = logs.find((log) => log.address === CONTRACTS.weth); const outputLog = logs.find((log) => log.address === outputToken); if (inputLog && outputLog) { return { tokenIn: { symbol: inputLog.symbol, amount: ether.toString(), address: inputLog.address, }, tokenOut: { symbol: outputLog.symbol, amount: tokenOutAmount.toString(), address: outputLog.address, }, }; } } export function multiplexBatchSellTokenForToken({ txDescription, txReceipt, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [inputContractAddress, outputContractAddress] = txDescription.args; if ( typeof inputContractAddress === "string" && typeof outputContractAddress === "string" ) { const tokenData = { [inputContractAddress]: { amount: "0", symbol: "", address: "" }, [outputContractAddress]: { amount: "0", symbol: "", address: "" }, }; txReceipt.logs.forEach(({ address, symbol, amount }) => { if (address in tokenData) { tokenData[address].address = address; tokenData[address].symbol = symbol; tokenData[address].amount = ( Number(tokenData[address].amount) + Number(amount) ).toString(); } }); return { tokenIn: tokenData[inputContractAddress], tokenOut: tokenData[outputContractAddress], }; } } export function sellToPancakeSwap({ txReceipt, }: { txReceipt: EnrichedTxReceipt; }) { const from = txReceipt.from.toLowerCase(); const { logs } = txReceipt; const exchangeProxy = EXCHANGE_PROXY_BY_CHAIN_ID[56].toLowerCase(); let inputLog = logs.find((log) => log.from === from); let outputLog = logs.find((log) => log.from !== from); if (inputLog === undefined) { inputLog = logs.find((log) => log.from === exchangeProxy); outputLog = logs.find((log) => log.from !== exchangeProxy); } if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function executeMetaTransaction({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [metaTransaction] = txDescription.args; const [from] = metaTransaction as string[]; const { logs } = txReceipt; if (typeof from === "string") { const inputLog = logs.find((log) => log.from === from.toLowerCase()); const outputLog = logs.find((log) => log.to === from.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } } export function fillOtcOrderForEth({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const { logs } = txReceipt; const [order] = txDescription.args; const [makerToken, takerToken] = order as string[]; const inputLog = logs.find((log) => log.address === takerToken); const outputLog = logs.find((log) => log.address === makerToken); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } export function fillOtcOrderWithEth({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { return fillOtcOrderForEth({ txReceipt, txDescription }); } export function fillLimitOrder({ txReceipt, txDescription, }: { txReceipt: EnrichedTxReceipt; txDescription: TransactionDescription; }) { const [order] = txDescription.args; const { 5: maker, 6: taker } = order as string[]; const { logs } = txReceipt; if (typeof maker === "string" && typeof taker === "string") { const inputLog = logs.find((log) => log.from === taker.toLowerCase()); const outputLog = logs.find((log) => log.from === maker.toLowerCase()); if (inputLog && outputLog) { return extractTokenInfo(inputLog, outputLog); } } }
src/parsers/index.ts
0xProject-0x-parser-a1dd0bf
[ { "filename": "src/utils/index.ts", "retrieved_chunk": " return formattedFractionalPart.length > 0\n ? `${wholePart}.${formattedFractionalPart}`\n : wholePart.toString();\n}\nexport async function fetchSymbolAndDecimal(\n address: string,\n tryBlockAndAggregate: TryBlockAndAggregate\n): Promise<[string, number]> {\n const calls = [\n { target: address, callData: ERC20_FUNCTION_HASHES.symbol },", "score": 9.42352198415722 }, { "filename": "src/index.ts", "retrieved_chunk": " transactionReceipt,\n tryBlockAndAggregate,\n contract: exchangeProxyContract,\n });\n } else {\n const parser = logParsers[mtxV2Description.name];\n return processReceipt({\n signer,\n parser,\n recipient,", "score": 8.1335600070681 }, { "filename": "src/types.ts", "retrieved_chunk": " SUCCESSFUL = 1,\n}\nexport interface Log {\n transactionIndex: number;\n blockNumber: number;\n transactionHash: string;\n address: string;\n data: string;\n logIndex?: number;\n blockHash: string;", "score": 5.298020635319427 }, { "filename": "src/index.ts", "retrieved_chunk": " transactionDescription: permitAndCallDescription,\n });\n }\n }\n if (transactionDescription.name === \"executeMetaTransactionV2\") {\n return parseGaslessTx({\n chainId,\n logParsers,\n exchangeProxyContract,\n tryBlockAndAggregate,", "score": 4.573820481277901 }, { "filename": "src/index.ts", "retrieved_chunk": " transactionReceipt,\n transactionDescription,\n });\n }\n if (transactionDescription.name === \"transformERC20\") {\n return transformERC20({\n chainId,\n transactionReceipt,\n tryBlockAndAggregate,\n contract: exchangeProxyContract,", "score": 4.4658950610666945 } ]
typescript
] = await fetchSymbolAndDecimal( inputToken, tryBlockAndAggregate );
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { AppRepository } from './app.repository'; import { AppWorkflow } from './app.workflow'; import { Data, Value } from './schemas'; import { Context } from '@vhidvz/wfjs'; @Injectable() export class AppService { constructor( private readonly appWorkflow: AppWorkflow, private readonly appRepository: AppRepository, ) {} /** * This is an asynchronous function that returns the result of finding an item with a specific ID in * the app repository. * * @param {string} id - The `id` parameter is a string that represents the unique identifier of an * entity that we want to find in the database. The `find` method is used to retrieve an entity from * the database based on its `id`. The `async` keyword indicates that the method returns a promise * that resolves to * * @returns The `find` method is being called on the `appRepository` object with the `id` parameter, * and the result of that method call is being returned. The `await` keyword is used to wait for the * `find` method to complete before returning its result. The specific data type of the returned * value is not specified in the code snippet. */ async find(id: string) { return await this.appRepository.find(id); } /** * This function creates a new item in the app repository using data passed in and the context * returned from executing the app workflow. * * @param {string} data - The `data` parameter is a string that is passed as an argument to the * `create` method. It is then used as input to the `execute` method of the `appWorkflow` object. The * `context` object returned from the `execute` method is then used as input to the * * @returns The `create` method is returning the result of calling the `create` method of the * `appRepository` with the `context` object obtained from executing the `appWorkflow` with the * provided `data` parameter. */ async create(data: Data) { // if you have only one start point this is OK const { context } = await this.appWorkflow.execute({ data });
return this.appRepository.create(context.serialize());
} /** * This is an async function that updates an app's context based on a given activity and value. * * @param {string} id - The ID of the app that needs to be updated. * @param {string} activity - The `activity` parameter is a string that represents the name of the * activity that needs to be executed in the workflow. * @param {string} value - The value parameter is a string that represents the input value to be * passed to the appWorkflow.execute() method. It is used to update the context of the app with the * result of the workflow execution. * * @returns The `update` method is returning the updated context after executing the specified * activity on the given id. */ async update(id: string, activity: string, value: Value) { try { const ctx = await this.appRepository.find(id); if (!ctx) throw new HttpException( 'flow with given id dose not exist', HttpStatus.BAD_REQUEST, ); const { context } = await this.appWorkflow.execute({ value, node: { name: activity }, context: Context.deserialize(ctx.toJSON()), }); return this.appRepository.update(id, context.serialize()); } catch (error) { throw new HttpException(error.message, HttpStatus.BAD_REQUEST); } } }
src/app.service.ts
vhidvz-workflow-template-2c2d5fd
[ { "filename": "src/app.repository.ts", "retrieved_chunk": " }\n async create(context: ContextInterface) {\n return this.appModel.create(context);\n }\n async update(id: string, context: ContextInterface) {\n return this.appModel.findByIdAndUpdate(id, context, { new: true });\n }\n}", "score": 47.4594727424374 }, { "filename": "src/app.controller.ts", "retrieved_chunk": " @Get(':id')\n async find(@Param('id') id: string): Promise<App> {\n return this.appService.find(id);\n }\n @Post()\n async create(@Body() data: DataDto): Promise<App> {\n return this.appService.create(data);\n }\n @Patch(':id/:activity')\n async update(", "score": 26.843876849440992 }, { "filename": "src/app.workflow.ts", "retrieved_chunk": " }\n @Node({ name: 'approval_gateway', pause: true })\n async approvalGateway(\n @Data() data: DataFlow,\n @Value() value: ValueFlow,\n @Act() activity: GatewayActivity,\n ) {\n data.global = `${data.global}, ${await this.appProvider.getHello(\n value.local,\n )}`;", "score": 16.547807924545108 }, { "filename": "src/app.workflow.ts", "retrieved_chunk": " return { local: `${value.local} to end event.` };\n }\n @Node({ name: 'end' })\n async end(@Data() data: DataFlow, @Value() value: ValueFlow) {\n data.global = `${data.global}, received a value from previous task(${value.local})`;\n }\n}", "score": 13.470755339737995 }, { "filename": "src/main.ts", "retrieved_chunk": " .setDescription(process.env.npm_package_description)\n .build();\n const document = SwaggerModule.createDocument(app, config);\n SwaggerModule.setup('api', app, document);\n await app.listen(3000);\n console.log(`Swagger UI is running on: ${await app.getUrl()}/api`);\n}\nbootstrap();", "score": 12.96103131727051 } ]
typescript
return this.appRepository.create(context.serialize());
/** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Redux import { RootState } from '../redux/store' import { useAppSelector, useAppDispatch } from '../redux/hooks' import { moveUp, moveDown, moveLeft, moveRight, collectItem, startMission, setIsSavingMission } from '../redux/gameSlice' import { useEffect } from 'react'; import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice'; import { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon } from '@heroicons/react/24/outline' export default function Component() { const { playerPosition, allItemsCollected, mission, isSavingMission } = useAppSelector((state: RootState) => state.game) const { data: user, } = useGetUserQuery(); const playerOnFinalSquare = playerPosition.x === 2 && playerPosition.y === 2; const dispatch = useAppDispatch() const [addCompletedMission] = useAddCompletedMissionMutation() function keyPressHandler({ key, keyCode }: { key: string | undefined, keyCode: number | undefined }) { switch (key) { case 'w': return dispatch(moveUp()) case 'a': return dispatch(moveLeft()) case 's': return dispatch(moveDown()) case 'd': return dispatch(moveRight()) } switch (keyCode) { case 38: // up arrow return dispatch(moveUp()) case 37: // left arrow return dispatch(moveLeft()) case 40: // down arrow return dispatch(moveDown()) case 39: // right arrow return dispatch(moveRight()) case 13: // enter if (allItemsCollected && playerOnFinalSquare && user && !isSavingMission) { dispatch(setIsSavingMission(true)); return addCompletedMission({ mission }).unwrap() .then(() => { dispatch(startMission({ nextMission: true })) }) .catch(error => { console.error('addCompletedMission request did not work.', { error }) }).finally(() => { dispatch(setIsSavingMission(false)); }); } return dispatch
(collectItem()) }
} useEffect(() => { window.addEventListener("keydown", keyPressHandler); return () => { window.removeEventListener("keydown", keyPressHandler); }; }); return ( <section className="hidden sm:block bg-slate-800 rounded-r-xl p-8 col-span-2 space-y-4"> <h2 className='text-slate-100'>Controls</h2> <section className="grid grid-cols-3 gap-3 w-fit"> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player up" onClick={() => dispatch(moveUp())} > <ArrowUpIcon className="block h-6 w-6" aria-hidden="true" /> </button> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player left" onClick={() => dispatch(moveLeft())} > <ArrowLeftIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player down" onClick={() => dispatch(moveDown())} > <ArrowDownIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player right" onClick={() => dispatch(moveRight())} > <ArrowRightIcon className="block h-6 w-6" aria-hidden="true" /> </button> </section> </section > ) }
src/components/game-controls.tsx
GoogleCloudPlatform-developer-journey-app-c20b105
[ { "filename": "src/components/tile.tsx", "retrieved_chunk": " console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {\n dispatch(setIsSavingMission(false));\n });\n }\n }\n if (isError) {\n return <div>{error.toString()}</div>\n }\n if (isSuccess || isLoading) {", "score": 65.24970550151804 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " const tileIsFinalTile = x == 2 && y == 2;\n const tileItem = inventory.find(item => item.position.x === x && item.position.y === y && item.status === 'NOT_COLLECTED');\n const completeMission = async () => {\n if (allItemsCollected && user) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch((error: Error) => {", "score": 28.0342688191743 }, { "filename": "src/redux/apiSlice.ts", "retrieved_chunk": " getUser: builder.query<User, void>({\n // The URL for the request is '/api/user', this is a GET request\n query: () => '/user',\n onCacheEntryAdded: (_, { dispatch }) => { \n dispatch(startMission())\n },\n providesTags: ['User'],\n }),\n addCompletedMission: builder.mutation({\n // The URL for the request is '/api/user', this is a POST request", "score": 17.355999180024863 }, { "filename": "src/components/tile-board.tsx", "retrieved_chunk": " const {\n isLoading,\n isError,\n error\n } = useGetUserQuery();\n const [showUhOh, setShowUhOh] = useState<Boolean>(false);\n const [timeExpired, setTimeExpired] = useState(false);\n useEffect(\n () => {\n if (isLoading) {", "score": 15.300267372311499 }, { "filename": "src/lib/database.ts", "retrieved_chunk": " if (!projectId) {\n const errMessage = \"PROJECT_ID environment variable must be defined.\";\n console.error(errMessage);\n throw new Error(errMessage);\n }\n this.db = new Firestore({\n projectId: projectId,\n });\n }\n }", "score": 14.735699418858479 } ]
typescript
(collectItem()) }
/** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Redux import { RootState } from '../redux/store' import { useAppSelector, useAppDispatch } from '../redux/hooks' import { moveUp, moveDown, moveLeft, moveRight, collectItem, startMission, setIsSavingMission } from '../redux/gameSlice' import { useEffect } from 'react'; import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice'; import { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon } from '@heroicons/react/24/outline' export default function Component() { const { playerPosition, allItemsCollected, mission, isSavingMission } = useAppSelector((state: RootState) => state.game) const { data: user, } = useGetUserQuery(); const playerOnFinalSquare = playerPosition.x === 2 && playerPosition.y === 2; const dispatch = useAppDispatch() const [addCompletedMission] = useAddCompletedMissionMutation() function keyPressHandler({ key, keyCode }: { key: string | undefined, keyCode: number | undefined }) { switch (key) { case 'w': return dispatch(moveUp()) case 'a': return dispatch(moveLeft()) case 's': return dispatch(moveDown()) case 'd': return dispatch(moveRight()) } switch (keyCode) { case 38: // up arrow return dispatch(moveUp()) case 37: // left arrow return dispatch(moveLeft()) case 40: // down arrow return dispatch(moveDown()) case 39: // right arrow return dispatch(moveRight()) case 13: // enter if (allItemsCollected && playerOnFinalSquare && user && !isSavingMission) { dispatch(setIsSavingMission(true)); return addCompletedMission({ mission }).unwrap() .then(() => {
dispatch(startMission({ nextMission: true })) }) .catch(error => {
console.error('addCompletedMission request did not work.', { error }) }).finally(() => { dispatch(setIsSavingMission(false)); }); } return dispatch(collectItem()) } } useEffect(() => { window.addEventListener("keydown", keyPressHandler); return () => { window.removeEventListener("keydown", keyPressHandler); }; }); return ( <section className="hidden sm:block bg-slate-800 rounded-r-xl p-8 col-span-2 space-y-4"> <h2 className='text-slate-100'>Controls</h2> <section className="grid grid-cols-3 gap-3 w-fit"> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player up" onClick={() => dispatch(moveUp())} > <ArrowUpIcon className="block h-6 w-6" aria-hidden="true" /> </button> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player left" onClick={() => dispatch(moveLeft())} > <ArrowLeftIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player down" onClick={() => dispatch(moveDown())} > <ArrowDownIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player right" onClick={() => dispatch(moveRight())} > <ArrowRightIcon className="block h-6 w-6" aria-hidden="true" /> </button> </section> </section > ) }
src/components/game-controls.tsx
GoogleCloudPlatform-developer-journey-app-c20b105
[ { "filename": "src/components/tile.tsx", "retrieved_chunk": " const tileIsFinalTile = x == 2 && y == 2;\n const tileItem = inventory.find(item => item.position.x === x && item.position.y === y && item.status === 'NOT_COLLECTED');\n const completeMission = async () => {\n if (allItemsCollected && user) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch((error: Error) => {", "score": 61.172236376941974 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {\n dispatch(setIsSavingMission(false));\n });\n }\n }\n if (isError) {\n return <div>{error.toString()}</div>\n }\n if (isSuccess || isLoading) {", "score": 30.835900732482937 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " return (\n <section className=\"min-h-full\" onClick={() => {\n if (playerIsLeftOfTile) {\n dispatch(moveRight())\n }\n if (playerIsRightOfTile) {\n dispatch(moveLeft())\n }\n if (playerIsAboveTile) {\n dispatch(moveDown())", "score": 28.91379209859798 }, { "filename": "src/redux/gameSlice.ts", "retrieved_chunk": " },\n setIsSavingMission: (state, action: PayloadAction<boolean>) => {\n state.isSavingMission = action.payload;\n },\n }\n})\n// Action creators are generated for each case reducer function\nexport const { startMission, moveUp, moveDown, moveLeft, moveRight, collectItem, setIsSavingMission } = gameSlice.actions\nexport default gameSlice.reducer", "score": 27.36248322057324 }, { "filename": "src/redux/apiSlice.ts", "retrieved_chunk": " getUser: builder.query<User, void>({\n // The URL for the request is '/api/user', this is a GET request\n query: () => '/user',\n onCacheEntryAdded: (_, { dispatch }) => { \n dispatch(startMission())\n },\n providesTags: ['User'],\n }),\n addCompletedMission: builder.mutation({\n // The URL for the request is '/api/user', this is a POST request", "score": 22.936597898383457 } ]
typescript
dispatch(startMission({ nextMission: true })) }) .catch(error => {
/** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Redux import { RootState } from '../redux/store' import { useAppSelector, useAppDispatch } from '../redux/hooks' import { moveUp, moveDown, moveLeft, moveRight, collectItem, startMission, setIsSavingMission } from '../redux/gameSlice' import { useEffect } from 'react'; import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice'; import { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon } from '@heroicons/react/24/outline' export default function Component() { const { playerPosition, allItemsCollected, mission, isSavingMission } = useAppSelector((state: RootState) => state.game) const { data: user, } = useGetUserQuery(); const playerOnFinalSquare = playerPosition.x === 2 && playerPosition.y === 2; const dispatch = useAppDispatch() const [addCompletedMission] = useAddCompletedMissionMutation() function keyPressHandler({ key, keyCode }: { key: string | undefined, keyCode: number | undefined }) { switch (key) { case 'w': return dispatch(moveUp()) case 'a': return dispatch(moveLeft()) case 's': return dispatch(moveDown()) case 'd': return dispatch(
moveRight()) }
switch (keyCode) { case 38: // up arrow return dispatch(moveUp()) case 37: // left arrow return dispatch(moveLeft()) case 40: // down arrow return dispatch(moveDown()) case 39: // right arrow return dispatch(moveRight()) case 13: // enter if (allItemsCollected && playerOnFinalSquare && user && !isSavingMission) { dispatch(setIsSavingMission(true)); return addCompletedMission({ mission }).unwrap() .then(() => { dispatch(startMission({ nextMission: true })) }) .catch(error => { console.error('addCompletedMission request did not work.', { error }) }).finally(() => { dispatch(setIsSavingMission(false)); }); } return dispatch(collectItem()) } } useEffect(() => { window.addEventListener("keydown", keyPressHandler); return () => { window.removeEventListener("keydown", keyPressHandler); }; }); return ( <section className="hidden sm:block bg-slate-800 rounded-r-xl p-8 col-span-2 space-y-4"> <h2 className='text-slate-100'>Controls</h2> <section className="grid grid-cols-3 gap-3 w-fit"> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player up" onClick={() => dispatch(moveUp())} > <ArrowUpIcon className="block h-6 w-6" aria-hidden="true" /> </button> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player left" onClick={() => dispatch(moveLeft())} > <ArrowLeftIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player down" onClick={() => dispatch(moveDown())} > <ArrowDownIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player right" onClick={() => dispatch(moveRight())} > <ArrowRightIcon className="block h-6 w-6" aria-hidden="true" /> </button> </section> </section > ) }
src/components/game-controls.tsx
GoogleCloudPlatform-developer-journey-app-c20b105
[ { "filename": "src/components/tile.tsx", "retrieved_chunk": " return (\n <section className=\"min-h-full\" onClick={() => {\n if (playerIsLeftOfTile) {\n dispatch(moveRight())\n }\n if (playerIsRightOfTile) {\n dispatch(moveLeft())\n }\n if (playerIsAboveTile) {\n dispatch(moveDown())", "score": 44.38237083034146 }, { "filename": "src/redux/gameSlice.ts", "retrieved_chunk": " },\n setIsSavingMission: (state, action: PayloadAction<boolean>) => {\n state.isSavingMission = action.payload;\n },\n }\n})\n// Action creators are generated for each case reducer function\nexport const { startMission, moveUp, moveDown, moveLeft, moveRight, collectItem, setIsSavingMission } = gameSlice.actions\nexport default gameSlice.reducer", "score": 37.44281258202519 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " const tileIsFinalTile = x == 2 && y == 2;\n const tileItem = inventory.find(item => item.position.x === x && item.position.y === y && item.status === 'NOT_COLLECTED');\n const completeMission = async () => {\n if (allItemsCollected && user) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch((error: Error) => {", "score": 22.115018812133098 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {\n dispatch(setIsSavingMission(false));\n });\n }\n }\n if (isError) {\n return <div>{error.toString()}</div>\n }\n if (isSuccess || isLoading) {", "score": 21.813498204287253 }, { "filename": "src/redux/apiSlice.ts", "retrieved_chunk": " getUser: builder.query<User, void>({\n // The URL for the request is '/api/user', this is a GET request\n query: () => '/user',\n onCacheEntryAdded: (_, { dispatch }) => { \n dispatch(startMission())\n },\n providesTags: ['User'],\n }),\n addCompletedMission: builder.mutation({\n // The URL for the request is '/api/user', this is a POST request", "score": 18.27136974724905 } ]
typescript
moveRight()) }
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { AppRepository } from './app.repository'; import { AppWorkflow } from './app.workflow'; import { Data, Value } from './schemas'; import { Context } from '@vhidvz/wfjs'; @Injectable() export class AppService { constructor( private readonly appWorkflow: AppWorkflow, private readonly appRepository: AppRepository, ) {} /** * This is an asynchronous function that returns the result of finding an item with a specific ID in * the app repository. * * @param {string} id - The `id` parameter is a string that represents the unique identifier of an * entity that we want to find in the database. The `find` method is used to retrieve an entity from * the database based on its `id`. The `async` keyword indicates that the method returns a promise * that resolves to * * @returns The `find` method is being called on the `appRepository` object with the `id` parameter, * and the result of that method call is being returned. The `await` keyword is used to wait for the * `find` method to complete before returning its result. The specific data type of the returned * value is not specified in the code snippet. */ async find(id: string) { return await this.appRepository.find(id); } /** * This function creates a new item in the app repository using data passed in and the context * returned from executing the app workflow. * * @param {string} data - The `data` parameter is a string that is passed as an argument to the * `create` method. It is then used as input to the `execute` method of the `appWorkflow` object. The * `context` object returned from the `execute` method is then used as input to the * * @returns The `create` method is returning the result of calling the `create` method of the * `appRepository` with the `context` object obtained from executing the `appWorkflow` with the * provided `data` parameter. */ async create(
data: Data) {
// if you have only one start point this is OK const { context } = await this.appWorkflow.execute({ data }); return this.appRepository.create(context.serialize()); } /** * This is an async function that updates an app's context based on a given activity and value. * * @param {string} id - The ID of the app that needs to be updated. * @param {string} activity - The `activity` parameter is a string that represents the name of the * activity that needs to be executed in the workflow. * @param {string} value - The value parameter is a string that represents the input value to be * passed to the appWorkflow.execute() method. It is used to update the context of the app with the * result of the workflow execution. * * @returns The `update` method is returning the updated context after executing the specified * activity on the given id. */ async update(id: string, activity: string, value: Value) { try { const ctx = await this.appRepository.find(id); if (!ctx) throw new HttpException( 'flow with given id dose not exist', HttpStatus.BAD_REQUEST, ); const { context } = await this.appWorkflow.execute({ value, node: { name: activity }, context: Context.deserialize(ctx.toJSON()), }); return this.appRepository.update(id, context.serialize()); } catch (error) { throw new HttpException(error.message, HttpStatus.BAD_REQUEST); } } }
src/app.service.ts
vhidvz-workflow-template-2c2d5fd
[ { "filename": "src/app.repository.ts", "retrieved_chunk": " }\n async create(context: ContextInterface) {\n return this.appModel.create(context);\n }\n async update(id: string, context: ContextInterface) {\n return this.appModel.findByIdAndUpdate(id, context, { new: true });\n }\n}", "score": 27.167538207701153 }, { "filename": "src/app.workflow.ts", "retrieved_chunk": " return { local: `${value.local} to end event.` };\n }\n @Node({ name: 'end' })\n async end(@Data() data: DataFlow, @Value() value: ValueFlow) {\n data.global = `${data.global}, received a value from previous task(${value.local})`;\n }\n}", "score": 22.3690937359244 }, { "filename": "src/app.controller.ts", "retrieved_chunk": " @Get(':id')\n async find(@Param('id') id: string): Promise<App> {\n return this.appService.find(id);\n }\n @Post()\n async create(@Body() data: DataDto): Promise<App> {\n return this.appService.create(data);\n }\n @Patch(':id/:activity')\n async update(", "score": 20.964950457914217 }, { "filename": "src/app.workflow.ts", "retrieved_chunk": "import { Act, Data, Node, Process, Value } from '@vhidvz/wfjs/common';\nimport {\n EventActivity,\n GatewayActivity,\n TaskActivity,\n} from '@vhidvz/wfjs/core';\nimport { Data as DataFlow, Value as ValueFlow } from './schemas';\nimport { AppProvider } from './app.provider';\nimport { Injectable } from '@nestjs/common';\nimport { WorkflowJS } from '@vhidvz/wfjs';", "score": 15.446577085959746 }, { "filename": "src/main.ts", "retrieved_chunk": " .setDescription(process.env.npm_package_description)\n .build();\n const document = SwaggerModule.createDocument(app, config);\n SwaggerModule.setup('api', app, document);\n await app.listen(3000);\n console.log(`Swagger UI is running on: ${await app.getUrl()}/api`);\n}\nbootstrap();", "score": 14.32679188764627 } ]
typescript
data: Data) {
/** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Redux import { RootState } from '../redux/store' import { useAppSelector, useAppDispatch } from '../redux/hooks' import { moveUp, moveDown, moveLeft, moveRight, collectItem, startMission, setIsSavingMission } from '../redux/gameSlice' import { useEffect } from 'react'; import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice'; import { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon } from '@heroicons/react/24/outline' export default function Component() { const { playerPosition, allItemsCollected, mission, isSavingMission } = useAppSelector((state: RootState) => state.game) const { data: user, } = useGetUserQuery(); const playerOnFinalSquare = playerPosition.x === 2 && playerPosition.y === 2; const dispatch = useAppDispatch() const [addCompletedMission] = useAddCompletedMissionMutation() function keyPressHandler({ key, keyCode }: { key: string | undefined, keyCode: number | undefined }) { switch (key) { case 'w': return dispatch(moveUp()) case 'a': return dispatch(moveLeft()) case 's': return
dispatch(moveDown()) case 'd': return dispatch(moveRight()) }
switch (keyCode) { case 38: // up arrow return dispatch(moveUp()) case 37: // left arrow return dispatch(moveLeft()) case 40: // down arrow return dispatch(moveDown()) case 39: // right arrow return dispatch(moveRight()) case 13: // enter if (allItemsCollected && playerOnFinalSquare && user && !isSavingMission) { dispatch(setIsSavingMission(true)); return addCompletedMission({ mission }).unwrap() .then(() => { dispatch(startMission({ nextMission: true })) }) .catch(error => { console.error('addCompletedMission request did not work.', { error }) }).finally(() => { dispatch(setIsSavingMission(false)); }); } return dispatch(collectItem()) } } useEffect(() => { window.addEventListener("keydown", keyPressHandler); return () => { window.removeEventListener("keydown", keyPressHandler); }; }); return ( <section className="hidden sm:block bg-slate-800 rounded-r-xl p-8 col-span-2 space-y-4"> <h2 className='text-slate-100'>Controls</h2> <section className="grid grid-cols-3 gap-3 w-fit"> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player up" onClick={() => dispatch(moveUp())} > <ArrowUpIcon className="block h-6 w-6" aria-hidden="true" /> </button> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player left" onClick={() => dispatch(moveLeft())} > <ArrowLeftIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player down" onClick={() => dispatch(moveDown())} > <ArrowDownIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player right" onClick={() => dispatch(moveRight())} > <ArrowRightIcon className="block h-6 w-6" aria-hidden="true" /> </button> </section> </section > ) }
src/components/game-controls.tsx
GoogleCloudPlatform-developer-journey-app-c20b105
[ { "filename": "src/components/tile.tsx", "retrieved_chunk": " return (\n <section className=\"min-h-full\" onClick={() => {\n if (playerIsLeftOfTile) {\n dispatch(moveRight())\n }\n if (playerIsRightOfTile) {\n dispatch(moveLeft())\n }\n if (playerIsAboveTile) {\n dispatch(moveDown())", "score": 44.38237083034146 }, { "filename": "src/redux/gameSlice.ts", "retrieved_chunk": " },\n setIsSavingMission: (state, action: PayloadAction<boolean>) => {\n state.isSavingMission = action.payload;\n },\n }\n})\n// Action creators are generated for each case reducer function\nexport const { startMission, moveUp, moveDown, moveLeft, moveRight, collectItem, setIsSavingMission } = gameSlice.actions\nexport default gameSlice.reducer", "score": 37.44281258202519 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " const tileIsFinalTile = x == 2 && y == 2;\n const tileItem = inventory.find(item => item.position.x === x && item.position.y === y && item.status === 'NOT_COLLECTED');\n const completeMission = async () => {\n if (allItemsCollected && user) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch((error: Error) => {", "score": 22.115018812133098 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {\n dispatch(setIsSavingMission(false));\n });\n }\n }\n if (isError) {\n return <div>{error.toString()}</div>\n }\n if (isSuccess || isLoading) {", "score": 21.813498204287253 }, { "filename": "src/redux/apiSlice.ts", "retrieved_chunk": " getUser: builder.query<User, void>({\n // The URL for the request is '/api/user', this is a GET request\n query: () => '/user',\n onCacheEntryAdded: (_, { dispatch }) => { \n dispatch(startMission())\n },\n providesTags: ['User'],\n }),\n addCompletedMission: builder.mutation({\n // The URL for the request is '/api/user', this is a POST request", "score": 18.27136974724905 } ]
typescript
dispatch(moveDown()) case 'd': return dispatch(moveRight()) }
/** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Redux import { RootState } from '../redux/store' import { useAppSelector, useAppDispatch } from '../redux/hooks' import { moveUp, moveDown, moveLeft, moveRight, collectItem, startMission, setIsSavingMission } from '../redux/gameSlice' import { useEffect } from 'react'; import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice'; import { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon } from '@heroicons/react/24/outline' export default function Component() { const { playerPosition, allItemsCollected, mission, isSavingMission } = useAppSelector((state: RootState) => state.game) const { data: user, } = useGetUserQuery(); const playerOnFinalSquare = playerPosition.x === 2 && playerPosition.y === 2; const dispatch = useAppDispatch() const [addCompletedMission] = useAddCompletedMissionMutation() function keyPressHandler({ key, keyCode }: { key: string | undefined, keyCode: number | undefined }) { switch (key) { case 'w': return dispatch(moveUp()) case 'a': return dispatch(moveLeft()) case 's': return dispatch(moveDown()) case 'd': return
dispatch(moveRight()) }
switch (keyCode) { case 38: // up arrow return dispatch(moveUp()) case 37: // left arrow return dispatch(moveLeft()) case 40: // down arrow return dispatch(moveDown()) case 39: // right arrow return dispatch(moveRight()) case 13: // enter if (allItemsCollected && playerOnFinalSquare && user && !isSavingMission) { dispatch(setIsSavingMission(true)); return addCompletedMission({ mission }).unwrap() .then(() => { dispatch(startMission({ nextMission: true })) }) .catch(error => { console.error('addCompletedMission request did not work.', { error }) }).finally(() => { dispatch(setIsSavingMission(false)); }); } return dispatch(collectItem()) } } useEffect(() => { window.addEventListener("keydown", keyPressHandler); return () => { window.removeEventListener("keydown", keyPressHandler); }; }); return ( <section className="hidden sm:block bg-slate-800 rounded-r-xl p-8 col-span-2 space-y-4"> <h2 className='text-slate-100'>Controls</h2> <section className="grid grid-cols-3 gap-3 w-fit"> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player up" onClick={() => dispatch(moveUp())} > <ArrowUpIcon className="block h-6 w-6" aria-hidden="true" /> </button> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player left" onClick={() => dispatch(moveLeft())} > <ArrowLeftIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player down" onClick={() => dispatch(moveDown())} > <ArrowDownIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player right" onClick={() => dispatch(moveRight())} > <ArrowRightIcon className="block h-6 w-6" aria-hidden="true" /> </button> </section> </section > ) }
src/components/game-controls.tsx
GoogleCloudPlatform-developer-journey-app-c20b105
[ { "filename": "src/components/tile.tsx", "retrieved_chunk": " return (\n <section className=\"min-h-full\" onClick={() => {\n if (playerIsLeftOfTile) {\n dispatch(moveRight())\n }\n if (playerIsRightOfTile) {\n dispatch(moveLeft())\n }\n if (playerIsAboveTile) {\n dispatch(moveDown())", "score": 44.38237083034146 }, { "filename": "src/redux/gameSlice.ts", "retrieved_chunk": " },\n setIsSavingMission: (state, action: PayloadAction<boolean>) => {\n state.isSavingMission = action.payload;\n },\n }\n})\n// Action creators are generated for each case reducer function\nexport const { startMission, moveUp, moveDown, moveLeft, moveRight, collectItem, setIsSavingMission } = gameSlice.actions\nexport default gameSlice.reducer", "score": 37.44281258202519 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " const tileIsFinalTile = x == 2 && y == 2;\n const tileItem = inventory.find(item => item.position.x === x && item.position.y === y && item.status === 'NOT_COLLECTED');\n const completeMission = async () => {\n if (allItemsCollected && user) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch((error: Error) => {", "score": 22.115018812133098 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {\n dispatch(setIsSavingMission(false));\n });\n }\n }\n if (isError) {\n return <div>{error.toString()}</div>\n }\n if (isSuccess || isLoading) {", "score": 21.813498204287253 }, { "filename": "src/redux/apiSlice.ts", "retrieved_chunk": " getUser: builder.query<User, void>({\n // The URL for the request is '/api/user', this is a GET request\n query: () => '/user',\n onCacheEntryAdded: (_, { dispatch }) => { \n dispatch(startMission())\n },\n providesTags: ['User'],\n }),\n addCompletedMission: builder.mutation({\n // The URL for the request is '/api/user', this is a POST request", "score": 18.27136974724905 } ]
typescript
dispatch(moveRight()) }
/** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Redux import { RootState } from '../redux/store' import { useAppSelector, useAppDispatch } from '../redux/hooks' import { moveUp, moveDown, moveLeft, moveRight, collectItem, startMission, setIsSavingMission } from '../redux/gameSlice' import { useEffect } from 'react'; import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice'; import { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon } from '@heroicons/react/24/outline' export default function Component() { const { playerPosition, allItemsCollected, mission, isSavingMission } = useAppSelector((state: RootState) => state.game) const { data: user, } = useGetUserQuery(); const playerOnFinalSquare = playerPosition.x === 2 && playerPosition.y === 2; const dispatch = useAppDispatch() const [addCompletedMission] = useAddCompletedMissionMutation() function keyPressHandler({ key, keyCode }: { key: string | undefined, keyCode: number | undefined }) { switch (key) { case 'w': return dispatch(moveUp()) case 'a': return dispatch(moveLeft()) case 's': return dispatch(
moveDown()) case 'd': return dispatch(moveRight()) }
switch (keyCode) { case 38: // up arrow return dispatch(moveUp()) case 37: // left arrow return dispatch(moveLeft()) case 40: // down arrow return dispatch(moveDown()) case 39: // right arrow return dispatch(moveRight()) case 13: // enter if (allItemsCollected && playerOnFinalSquare && user && !isSavingMission) { dispatch(setIsSavingMission(true)); return addCompletedMission({ mission }).unwrap() .then(() => { dispatch(startMission({ nextMission: true })) }) .catch(error => { console.error('addCompletedMission request did not work.', { error }) }).finally(() => { dispatch(setIsSavingMission(false)); }); } return dispatch(collectItem()) } } useEffect(() => { window.addEventListener("keydown", keyPressHandler); return () => { window.removeEventListener("keydown", keyPressHandler); }; }); return ( <section className="hidden sm:block bg-slate-800 rounded-r-xl p-8 col-span-2 space-y-4"> <h2 className='text-slate-100'>Controls</h2> <section className="grid grid-cols-3 gap-3 w-fit"> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player up" onClick={() => dispatch(moveUp())} > <ArrowUpIcon className="block h-6 w-6" aria-hidden="true" /> </button> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player left" onClick={() => dispatch(moveLeft())} > <ArrowLeftIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player down" onClick={() => dispatch(moveDown())} > <ArrowDownIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player right" onClick={() => dispatch(moveRight())} > <ArrowRightIcon className="block h-6 w-6" aria-hidden="true" /> </button> </section> </section > ) }
src/components/game-controls.tsx
GoogleCloudPlatform-developer-journey-app-c20b105
[ { "filename": "src/components/tile.tsx", "retrieved_chunk": " return (\n <section className=\"min-h-full\" onClick={() => {\n if (playerIsLeftOfTile) {\n dispatch(moveRight())\n }\n if (playerIsRightOfTile) {\n dispatch(moveLeft())\n }\n if (playerIsAboveTile) {\n dispatch(moveDown())", "score": 44.38237083034146 }, { "filename": "src/redux/gameSlice.ts", "retrieved_chunk": " },\n setIsSavingMission: (state, action: PayloadAction<boolean>) => {\n state.isSavingMission = action.payload;\n },\n }\n})\n// Action creators are generated for each case reducer function\nexport const { startMission, moveUp, moveDown, moveLeft, moveRight, collectItem, setIsSavingMission } = gameSlice.actions\nexport default gameSlice.reducer", "score": 37.44281258202519 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " const tileIsFinalTile = x == 2 && y == 2;\n const tileItem = inventory.find(item => item.position.x === x && item.position.y === y && item.status === 'NOT_COLLECTED');\n const completeMission = async () => {\n if (allItemsCollected && user) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch((error: Error) => {", "score": 22.115018812133098 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {\n dispatch(setIsSavingMission(false));\n });\n }\n }\n if (isError) {\n return <div>{error.toString()}</div>\n }\n if (isSuccess || isLoading) {", "score": 21.813498204287253 }, { "filename": "src/redux/apiSlice.ts", "retrieved_chunk": " getUser: builder.query<User, void>({\n // The URL for the request is '/api/user', this is a GET request\n query: () => '/user',\n onCacheEntryAdded: (_, { dispatch }) => { \n dispatch(startMission())\n },\n providesTags: ['User'],\n }),\n addCompletedMission: builder.mutation({\n // The URL for the request is '/api/user', this is a POST request", "score": 18.27136974724905 } ]
typescript
moveDown()) case 'd': return dispatch(moveRight()) }
import { SuiTransactionBlockResponse, SuiTransactionBlockResponseOptions, JsonRpcProvider, Connection, getObjectDisplay, getObjectFields, getObjectId, getObjectType, getObjectVersion, getSharedObjectInitialVersion, } from '@mysten/sui.js'; import { ObjectData } from 'src/types'; import { SuiOwnedObject, SuiSharedObject } from '../suiModel'; import { delay } from './util'; /** * `SuiTransactionSender` is used to send transaction with a given gas coin. * It always uses the gas coin to pay for the gas, * and update the gas coin after the transaction. */ export class SuiInteractor { public readonly providers: JsonRpcProvider[]; public currentProvider: JsonRpcProvider; constructor(fullNodeUrls: string[]) { if (fullNodeUrls.length === 0) throw new Error('fullNodeUrls must not be empty'); this.providers = fullNodeUrls.map( (url) => new JsonRpcProvider(new Connection({ fullnode: url })) ); this.currentProvider = this.providers[0]; } switchToNextProvider() { const currentProviderIdx = this.providers.indexOf(this.currentProvider); this.currentProvider = this.providers[(currentProviderIdx + 1) % this.providers.length]; } async sendTx( transactionBlock: Uint8Array | string, signature: string | string[] ): Promise<SuiTransactionBlockResponse> { const txResOptions: SuiTransactionBlockResponseOptions = { showEvents: true, showEffects: true, showObjectChanges: true, showBalanceChanges: true, }; // const currentProviderIdx = this.providers.indexOf(this.currentProvider); // const providers = [ // ...this.providers.slice(currentProviderIdx, this.providers.length), // ...this.providers.slice(0, currentProviderIdx), // ] for (const provider of this.providers) { try { const res = await provider.executeTransactionBlock({ transactionBlock, signature, options: txResOptions, }); return res; } catch (err) { console.warn( `Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}` ); await delay(2000); } } throw new Error('Failed to send transaction with all fullnodes'); } async getObjects(ids: string[]) { const options = { showContent: true, showDisplay: true, showType: true, showOwner: true, }; // const currentProviderIdx = this.providers.indexOf(this.currentProvider); // const providers = [ // ...this.providers.slice(currentProviderIdx, this.providers.length), // ...this.providers.slice(0, currentProviderIdx), // ] for (const provider of this.providers) { try { const objects = await provider.multiGetObjects({ ids, options }); const parsedObjects = objects.map((object) => { const objectId = getObjectId(object); const objectType = getObjectType(object); const objectVersion = getObjectVersion(object); const objectDigest = object.data ? object.data.digest : undefined; const initialSharedVersion = getSharedObjectInitialVersion(object); const objectFields = getObjectFields(object); const objectDisplay = getObjectDisplay(object); return { objectId, objectType, objectVersion, objectDigest, objectFields, objectDisplay, initialSharedVersion, }; }); return parsedObjects as ObjectData[]; } catch (err) { await delay(2000); console.warn( `Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}` ); } } throw new Error('Failed to get objects with all fullnodes'); } async getObject(id: string) { const objects = await this.getObjects([id]); return objects[0]; } /** * @description Update objects in a batch * @param suiObjects */
async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {
const objectIds = suiObjects.map((obj) => obj.objectId); const objects = await this.getObjects(objectIds); for (const object of objects) { const suiObject = suiObjects.find( (obj) => obj.objectId === object.objectId ); if (suiObject instanceof SuiSharedObject) { suiObject.initialSharedVersion = object.initialSharedVersion; } else if (suiObject instanceof SuiOwnedObject) { suiObject.version = object.objectVersion; suiObject.digest = object.objectDigest; } } } /** * @description Select coins that add up to the given amount. * @param addr the address of the owner * @param amount the amount that is needed for the coin * @param coinType the coin type, default is '0x2::SUI::SUI' */ async selectCoins( addr: string, amount: number, coinType: string = '0x2::SUI::SUI' ) { const selectedCoins: { objectId: string; digest: string; version: string; }[] = []; let totalAmount = 0; let hasNext = true, nextCursor: string | null = null; while (hasNext && totalAmount < amount) { const coins = await this.currentProvider.getCoins({ owner: addr, coinType: coinType, cursor: nextCursor, }); // Sort the coins by balance in descending order coins.data.sort((a, b) => parseInt(b.balance) - parseInt(a.balance)); for (const coinData of coins.data) { selectedCoins.push({ objectId: coinData.coinObjectId, digest: coinData.digest, version: coinData.version, }); totalAmount = totalAmount + parseInt(coinData.balance); if (totalAmount >= amount) { break; } } nextCursor = coins.nextCursor; hasNext = coins.hasNextPage; } if (!selectedCoins.length) { throw new Error('No valid coins found for the transaction.'); } return selectedCoins; } }
src/libs/suiInteractor/suiInteractor.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/suiKit.ts", "retrieved_chunk": " }\n /**\n * @description Update objects in a batch\n * @param suiObjects\n */\n async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) {\n return this.suiInteractor.updateObjects(suiObjects);\n }\n async signTxn(\n tx: Uint8Array | TransactionBlock | SuiTxBlock,", "score": 62.00211285648311 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " ) {\n return this.transferCoinToMany(\n [recipient],\n [amount],\n coinType,\n derivePathParams\n );\n }\n async transferObjects(\n objects: string[],", "score": 18.454326740690448 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " recipient: string,\n derivePathParams?: DerivePathParams\n ) {\n const tx = new SuiTxBlock();\n tx.transferObjects(objects, recipient);\n return this.signAndSendTxn(tx, derivePathParams);\n }\n async moveCall(callParams: {\n target: string;\n arguments?: (SuiTxArg | SuiVecTxArg)[];", "score": 14.87244701026014 }, { "filename": "src/libs/suiTxBuilder/util.ts", "retrieved_chunk": " const objects = args.map((arg) =>\n typeof arg === 'string'\n ? txBlock.object(normalizeSuiObjectId(arg))\n : (arg as any)\n );\n return txBlock.makeMoveVec({ objects });\n } else {\n const vecType = type || defaultSuiType;\n return txBlock.pure(args, `vector<${vecType}>`);\n }", "score": 13.588575936072552 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " }\n provider() {\n return this.suiInteractor.currentProvider;\n }\n async getBalance(coinType?: string, derivePathParams?: DerivePathParams) {\n const owner = this.accountManager.getAddress(derivePathParams);\n return this.suiInteractor.currentProvider.getBalance({ owner, coinType });\n }\n async getObjects(objectIds: string[]) {\n return this.suiInteractor.getObjects(objectIds);", "score": 13.54230231436034 } ]
typescript
async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }: SuiKitParams = {}) { // Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider
fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];
this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) { return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/types/index.ts", "retrieved_chunk": " mnemonics?: string;\n secretKey?: string;\n fullnodeUrls?: string[];\n faucetUrl?: string;\n networkType?: NetworkType;\n};\nexport type ObjectData = {\n objectId: string;\n objectType: string;\n objectVersion: number;", "score": 34.34129128645495 }, { "filename": "src/libs/suiAccountManager/index.ts", "retrieved_chunk": " // If the mnemonics or secretKey is provided, use it\n // Otherwise, generate a random mnemonics with 24 words\n this.mnemonics = mnemonics || '';\n this.secretKey = secretKey || '';\n if (!this.mnemonics && !this.secretKey) {\n this.mnemonics = generateMnemonic(24);\n }\n // Init the current account\n this.currentKeyPair = this.secretKey\n ? Ed25519Keypair.fromSecretKey(", "score": 29.270634414316515 }, { "filename": "src/libs/suiInteractor/defaultConfig.ts", "retrieved_chunk": "/**\n * @description Get the default fullnode url and faucet url for the given network type\n * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'\n * @returns { fullNode: string, websocket: string, faucet?: string }\n */\nexport const getDefaultConnection = (\n networkType: NetworkType = 'devnet'\n): Connection => {\n switch (networkType) {\n case 'localnet':", "score": 19.467370161625052 }, { "filename": "src/libs/suiAccountManager/index.ts", "retrieved_chunk": " /**\n * Support the following ways to init the SuiToolkit:\n * 1. mnemonics\n * 2. secretKey (base64 or hex)\n * If none of them is provided, will generate a random mnemonics with 24 words.\n *\n * @param mnemonics, 12 or 24 mnemonics words, separated by space\n * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored\n */\n constructor({ mnemonics, secretKey }: AccountMangerParams = {}) {", "score": 18.95392200276798 }, { "filename": "src/libs/suiAccountManager/index.ts", "retrieved_chunk": " if (!derivePathParams || !this.mnemonics) return this.currentAddress;\n return getKeyPair(this.mnemonics, derivePathParams)\n .getPublicKey()\n .toSuiAddress();\n }\n /**\n * Switch the current account with the given derivePathParams.\n * This is only useful when the mnemonics is provided. For secretKey mode, it will always use the same account.\n */\n switchAccount(derivePathParams: DerivePathParams) {", "score": 17.81294166947616 } ]
typescript
fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];
/** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Import the RTK Query methods from the React-specific entry point import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' import { Mission } from 'src/models/Mission' import { User } from 'src/models/User' import { startMission } from './gameSlice'; // Define our single API slice object export const apiSlice = createApi({ // The cache reducer expects to be added at `state.api` (already default - this is optional) reducerPath: 'api', // All of our requests will have URLs starting with '/api' baseQuery: fetchBaseQuery({ baseUrl: '/api' }), tagTypes: ['User'], // The "endpoints" represent operations and requests for this server endpoints: builder => ({ // The `getUser` endpoint is a "query" operation that returns data getUser: builder.query<User, void>({ // The URL for the request is '/api/user', this is a GET request query: () => '/user', onCacheEntryAdded: (_, { dispatch }) => { dispatch(
startMission()) }, providesTags: ['User'], }), addCompletedMission: builder.mutation({
// The URL for the request is '/api/user', this is a POST request query: ({mission}: {mission: Mission}) => ({ url: '/user', method: 'POST', // Include the entire post object as the body of the request body: mission, }), invalidatesTags: ['User'] }), }) }) // Export the auto-generated hook for the `getUser` query endpoint export const { useGetUserQuery, useAddCompletedMissionMutation } = apiSlice
src/redux/apiSlice.ts
GoogleCloudPlatform-developer-journey-app-c20b105
[ { "filename": "src/components/game-controls.tsx", "retrieved_chunk": " case 13: // enter\n if (allItemsCollected && playerOnFinalSquare && user && !isSavingMission) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch(error => {\n console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {", "score": 29.076704168439658 }, { "filename": "src/pages/api/auth/[...nextauth].ts", "retrieved_chunk": " const user = { id: username, name: username };\n if (user) {\n return user;\n } else {\n // Display an error will be displayed advising the user to check\n // their details.\n return null;\n // Or reject this callback with an Error to send the user to the error\n // page with the error message as a query parameter\n }", "score": 20.169236487778655 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {\n dispatch(setIsSavingMission(false));\n });\n }\n }\n if (isError) {\n return <div>{error.toString()}</div>\n }\n if (isSuccess || isLoading) {", "score": 18.555052587152446 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " const tileIsFinalTile = x == 2 && y == 2;\n const tileItem = inventory.find(item => item.position.x === x && item.position.y === y && item.status === 'NOT_COLLECTED');\n const completeMission = async () => {\n if (allItemsCollected && user) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch((error: Error) => {", "score": 17.72528780918808 }, { "filename": "src/pages/api/user.ts", "retrieved_chunk": " const missionId = req.body.id;\n await fs.addCompletedMission({ username, missionId })\n }\n const user = await fs.getUser({ username });\n res.status(200).json(user)\n}", "score": 16.281199805793385 } ]
typescript
startMission()) }, providesTags: ['User'], }), addCompletedMission: builder.mutation({
import { SuiTransactionBlockResponse, SuiTransactionBlockResponseOptions, JsonRpcProvider, Connection, getObjectDisplay, getObjectFields, getObjectId, getObjectType, getObjectVersion, getSharedObjectInitialVersion, } from '@mysten/sui.js'; import { ObjectData } from 'src/types'; import { SuiOwnedObject, SuiSharedObject } from '../suiModel'; import { delay } from './util'; /** * `SuiTransactionSender` is used to send transaction with a given gas coin. * It always uses the gas coin to pay for the gas, * and update the gas coin after the transaction. */ export class SuiInteractor { public readonly providers: JsonRpcProvider[]; public currentProvider: JsonRpcProvider; constructor(fullNodeUrls: string[]) { if (fullNodeUrls.length === 0) throw new Error('fullNodeUrls must not be empty'); this.providers = fullNodeUrls.map( (url) => new JsonRpcProvider(new Connection({ fullnode: url })) ); this.currentProvider = this.providers[0]; } switchToNextProvider() { const currentProviderIdx = this.providers.indexOf(this.currentProvider); this.currentProvider = this.providers[(currentProviderIdx + 1) % this.providers.length]; } async sendTx( transactionBlock: Uint8Array | string, signature: string | string[] ): Promise<SuiTransactionBlockResponse> { const txResOptions: SuiTransactionBlockResponseOptions = { showEvents: true, showEffects: true, showObjectChanges: true, showBalanceChanges: true, }; // const currentProviderIdx = this.providers.indexOf(this.currentProvider); // const providers = [ // ...this.providers.slice(currentProviderIdx, this.providers.length), // ...this.providers.slice(0, currentProviderIdx), // ] for (const provider of this.providers) { try { const res = await provider.executeTransactionBlock({ transactionBlock, signature, options: txResOptions, }); return res; } catch (err) { console.warn( `Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}` ); await delay(2000); } } throw new Error('Failed to send transaction with all fullnodes'); } async getObjects(ids: string[]) { const options = { showContent: true, showDisplay: true, showType: true, showOwner: true, }; // const currentProviderIdx = this.providers.indexOf(this.currentProvider); // const providers = [ // ...this.providers.slice(currentProviderIdx, this.providers.length), // ...this.providers.slice(0, currentProviderIdx), // ] for (const provider of this.providers) { try { const objects = await provider.multiGetObjects({ ids, options }); const parsedObjects = objects.map((object) => { const objectId = getObjectId(object); const objectType = getObjectType(object); const objectVersion = getObjectVersion(object); const objectDigest = object.data ? object.data.digest : undefined; const initialSharedVersion = getSharedObjectInitialVersion(object); const objectFields = getObjectFields(object); const objectDisplay = getObjectDisplay(object); return { objectId, objectType, objectVersion, objectDigest, objectFields, objectDisplay, initialSharedVersion, }; }); return parsedObjects as ObjectData[]; } catch (err) { await delay(2000); console.warn( `Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}` ); } } throw new Error('Failed to get objects with all fullnodes'); } async getObject(id: string) { const objects = await this.getObjects([id]); return objects[0]; } /** * @description Update objects in a batch * @param suiObjects */ async
updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {
const objectIds = suiObjects.map((obj) => obj.objectId); const objects = await this.getObjects(objectIds); for (const object of objects) { const suiObject = suiObjects.find( (obj) => obj.objectId === object.objectId ); if (suiObject instanceof SuiSharedObject) { suiObject.initialSharedVersion = object.initialSharedVersion; } else if (suiObject instanceof SuiOwnedObject) { suiObject.version = object.objectVersion; suiObject.digest = object.objectDigest; } } } /** * @description Select coins that add up to the given amount. * @param addr the address of the owner * @param amount the amount that is needed for the coin * @param coinType the coin type, default is '0x2::SUI::SUI' */ async selectCoins( addr: string, amount: number, coinType: string = '0x2::SUI::SUI' ) { const selectedCoins: { objectId: string; digest: string; version: string; }[] = []; let totalAmount = 0; let hasNext = true, nextCursor: string | null = null; while (hasNext && totalAmount < amount) { const coins = await this.currentProvider.getCoins({ owner: addr, coinType: coinType, cursor: nextCursor, }); // Sort the coins by balance in descending order coins.data.sort((a, b) => parseInt(b.balance) - parseInt(a.balance)); for (const coinData of coins.data) { selectedCoins.push({ objectId: coinData.coinObjectId, digest: coinData.digest, version: coinData.version, }); totalAmount = totalAmount + parseInt(coinData.balance); if (totalAmount >= amount) { break; } } nextCursor = coins.nextCursor; hasNext = coins.hasNextPage; } if (!selectedCoins.length) { throw new Error('No valid coins found for the transaction.'); } return selectedCoins; } }
src/libs/suiInteractor/suiInteractor.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/suiKit.ts", "retrieved_chunk": " }\n /**\n * @description Update objects in a batch\n * @param suiObjects\n */\n async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) {\n return this.suiInteractor.updateObjects(suiObjects);\n }\n async signTxn(\n tx: Uint8Array | TransactionBlock | SuiTxBlock,", "score": 62.00211285648311 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " ) {\n return this.transferCoinToMany(\n [recipient],\n [amount],\n coinType,\n derivePathParams\n );\n }\n async transferObjects(\n objects: string[],", "score": 18.454326740690448 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " recipient: string,\n derivePathParams?: DerivePathParams\n ) {\n const tx = new SuiTxBlock();\n tx.transferObjects(objects, recipient);\n return this.signAndSendTxn(tx, derivePathParams);\n }\n async moveCall(callParams: {\n target: string;\n arguments?: (SuiTxArg | SuiVecTxArg)[];", "score": 14.87244701026014 }, { "filename": "src/libs/suiTxBuilder/util.ts", "retrieved_chunk": " const objects = args.map((arg) =>\n typeof arg === 'string'\n ? txBlock.object(normalizeSuiObjectId(arg))\n : (arg as any)\n );\n return txBlock.makeMoveVec({ objects });\n } else {\n const vecType = type || defaultSuiType;\n return txBlock.pure(args, `vector<${vecType}>`);\n }", "score": 13.588575936072552 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " }\n provider() {\n return this.suiInteractor.currentProvider;\n }\n async getBalance(coinType?: string, derivePathParams?: DerivePathParams) {\n const owner = this.accountManager.getAddress(derivePathParams);\n return this.suiInteractor.currentProvider.getBalance({ owner, coinType });\n }\n async getObjects(objectIds: string[]) {\n return this.suiInteractor.getObjects(objectIds);", "score": 13.54230231436034 } ]
typescript
updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {
import { SuiTransactionBlockResponse, SuiTransactionBlockResponseOptions, JsonRpcProvider, Connection, getObjectDisplay, getObjectFields, getObjectId, getObjectType, getObjectVersion, getSharedObjectInitialVersion, } from '@mysten/sui.js'; import { ObjectData } from 'src/types'; import { SuiOwnedObject, SuiSharedObject } from '../suiModel'; import { delay } from './util'; /** * `SuiTransactionSender` is used to send transaction with a given gas coin. * It always uses the gas coin to pay for the gas, * and update the gas coin after the transaction. */ export class SuiInteractor { public readonly providers: JsonRpcProvider[]; public currentProvider: JsonRpcProvider; constructor(fullNodeUrls: string[]) { if (fullNodeUrls.length === 0) throw new Error('fullNodeUrls must not be empty'); this.providers = fullNodeUrls.map( (url) => new JsonRpcProvider(new Connection({ fullnode: url })) ); this.currentProvider = this.providers[0]; } switchToNextProvider() { const currentProviderIdx = this.providers.indexOf(this.currentProvider); this.currentProvider = this.providers[(currentProviderIdx + 1) % this.providers.length]; } async sendTx( transactionBlock: Uint8Array | string, signature: string | string[] ): Promise<SuiTransactionBlockResponse> { const txResOptions: SuiTransactionBlockResponseOptions = { showEvents: true, showEffects: true, showObjectChanges: true, showBalanceChanges: true, }; // const currentProviderIdx = this.providers.indexOf(this.currentProvider); // const providers = [ // ...this.providers.slice(currentProviderIdx, this.providers.length), // ...this.providers.slice(0, currentProviderIdx), // ] for (const provider of this.providers) { try { const res = await provider.executeTransactionBlock({ transactionBlock, signature, options: txResOptions, }); return res; } catch (err) { console.warn( `Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}` ); await
delay(2000);
} } throw new Error('Failed to send transaction with all fullnodes'); } async getObjects(ids: string[]) { const options = { showContent: true, showDisplay: true, showType: true, showOwner: true, }; // const currentProviderIdx = this.providers.indexOf(this.currentProvider); // const providers = [ // ...this.providers.slice(currentProviderIdx, this.providers.length), // ...this.providers.slice(0, currentProviderIdx), // ] for (const provider of this.providers) { try { const objects = await provider.multiGetObjects({ ids, options }); const parsedObjects = objects.map((object) => { const objectId = getObjectId(object); const objectType = getObjectType(object); const objectVersion = getObjectVersion(object); const objectDigest = object.data ? object.data.digest : undefined; const initialSharedVersion = getSharedObjectInitialVersion(object); const objectFields = getObjectFields(object); const objectDisplay = getObjectDisplay(object); return { objectId, objectType, objectVersion, objectDigest, objectFields, objectDisplay, initialSharedVersion, }; }); return parsedObjects as ObjectData[]; } catch (err) { await delay(2000); console.warn( `Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}` ); } } throw new Error('Failed to get objects with all fullnodes'); } async getObject(id: string) { const objects = await this.getObjects([id]); return objects[0]; } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) { const objectIds = suiObjects.map((obj) => obj.objectId); const objects = await this.getObjects(objectIds); for (const object of objects) { const suiObject = suiObjects.find( (obj) => obj.objectId === object.objectId ); if (suiObject instanceof SuiSharedObject) { suiObject.initialSharedVersion = object.initialSharedVersion; } else if (suiObject instanceof SuiOwnedObject) { suiObject.version = object.objectVersion; suiObject.digest = object.objectDigest; } } } /** * @description Select coins that add up to the given amount. * @param addr the address of the owner * @param amount the amount that is needed for the coin * @param coinType the coin type, default is '0x2::SUI::SUI' */ async selectCoins( addr: string, amount: number, coinType: string = '0x2::SUI::SUI' ) { const selectedCoins: { objectId: string; digest: string; version: string; }[] = []; let totalAmount = 0; let hasNext = true, nextCursor: string | null = null; while (hasNext && totalAmount < amount) { const coins = await this.currentProvider.getCoins({ owner: addr, coinType: coinType, cursor: nextCursor, }); // Sort the coins by balance in descending order coins.data.sort((a, b) => parseInt(b.balance) - parseInt(a.balance)); for (const coinData of coins.data) { selectedCoins.push({ objectId: coinData.coinObjectId, digest: coinData.digest, version: coinData.version, }); totalAmount = totalAmount + parseInt(coinData.balance); if (totalAmount >= amount) { break; } } nextCursor = coins.nextCursor; hasNext = coins.hasNextPage; } if (!selectedCoins.length) { throw new Error('No valid coins found for the transaction.'); } return selectedCoins; } }
src/libs/suiInteractor/suiInteractor.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/suiKit.ts", "retrieved_chunk": " const { transactionBlockBytes, signature } = await this.signTxn(\n tx,\n derivePathParams\n );\n return this.suiInteractor.sendTx(transactionBlockBytes, signature);\n }\n /**\n * Transfer the given amount of SUI to the recipient\n * @param recipient\n * @param amount", "score": 12.230959942624219 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " // Init the rpc provider\n fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];\n this.suiInteractor = new SuiInteractor(fullnodeUrls);\n }\n /**\n * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner.\n * else:\n * it will generate signer from the mnemonic with the given derivePathParams.\n * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard\n */", "score": 9.441311393103279 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type\n */\n constructor({\n mnemonics,\n secretKey,\n networkType,\n fullnodeUrls,\n }: SuiKitParams = {}) {\n // Init the account manager\n this.accountManager = new SuiAccountManager({ mnemonics, secretKey });", "score": 8.747966172664656 }, { "filename": "src/libs/suiTxBuilder/index.ts", "retrieved_chunk": " }\n build(\n params: {\n provider?: JsonRpcProvider;\n onlyTransactionKind?: boolean;\n } = {}\n ) {\n return this.txBlock.build(params);\n }\n getDigest({ provider }: { provider?: JsonRpcProvider } = {}) {", "score": 7.022446630356589 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " tx.stakeSui(amount, validatorAddr);\n return this.signAndSendTxn(tx, derivePathParams);\n }\n /**\n * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction.\n * Since the transaction is not submitted, its gas cost is not charged.\n * @param tx the transaction to execute\n * @param derivePathParams the derive path params\n * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted.\n */", "score": 6.779528494751942 } ]
typescript
delay(2000);
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls,
}: SuiKitParams = {}) {
// Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) { return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiInteractor/defaultConfig.ts", "retrieved_chunk": "/**\n * @description Get the default fullnode url and faucet url for the given network type\n * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'\n * @returns { fullNode: string, websocket: string, faucet?: string }\n */\nexport const getDefaultConnection = (\n networkType: NetworkType = 'devnet'\n): Connection => {\n switch (networkType) {\n case 'localnet':", "score": 73.40323288598293 }, { "filename": "src/libs/suiAccountManager/index.ts", "retrieved_chunk": " /**\n * Support the following ways to init the SuiToolkit:\n * 1. mnemonics\n * 2. secretKey (base64 or hex)\n * If none of them is provided, will generate a random mnemonics with 24 words.\n *\n * @param mnemonics, 12 or 24 mnemonics words, separated by space\n * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored\n */\n constructor({ mnemonics, secretKey }: AccountMangerParams = {}) {", "score": 58.43921768925004 }, { "filename": "src/types/index.ts", "retrieved_chunk": " mnemonics?: string;\n secretKey?: string;\n};\nexport type DerivePathParams = {\n accountIndex?: number;\n isExternal?: boolean;\n addressIndex?: number;\n};\nexport type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';\nexport type SuiKitParams = {", "score": 38.63281018457062 }, { "filename": "src/libs/suiAccountManager/index.ts", "retrieved_chunk": " // If the mnemonics or secretKey is provided, use it\n // Otherwise, generate a random mnemonics with 24 words\n this.mnemonics = mnemonics || '';\n this.secretKey = secretKey || '';\n if (!this.mnemonics && !this.secretKey) {\n this.mnemonics = generateMnemonic(24);\n }\n // Init the current account\n this.currentKeyPair = this.secretKey\n ? Ed25519Keypair.fromSecretKey(", "score": 33.06484937106853 }, { "filename": "src/libs/suiAccountManager/index.ts", "retrieved_chunk": " normalizePrivateKey(hexOrBase64ToUint8Array(this.secretKey))\n )\n : getKeyPair(this.mnemonics);\n this.currentAddress = this.currentKeyPair.getPublicKey().toSuiAddress();\n }\n /**\n * if derivePathParams is not provided or mnemonics is empty, it will return the currentKeyPair.\n * else:\n * it will generate keyPair from the mnemonic with the given derivePathParams.\n */", "score": 32.785848605274914 } ]
typescript
}: SuiKitParams = {}) {
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }: SuiKitParams = {}) { // Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects: (
SuiSharedObject | SuiOwnedObject)[]) {
return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " }\n async getObject(id: string) {\n const objects = await this.getObjects([id]);\n return objects[0];\n }\n /**\n * @description Update objects in a batch\n * @param suiObjects\n */\n async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {", "score": 59.64749914761954 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " const objectIds = suiObjects.map((obj) => obj.objectId);\n const objects = await this.getObjects(objectIds);\n for (const object of objects) {\n const suiObject = suiObjects.find(\n (obj) => obj.objectId === object.objectId\n );\n if (suiObject instanceof SuiSharedObject) {\n suiObject.initialSharedVersion = object.initialSharedVersion;\n } else if (suiObject instanceof SuiOwnedObject) {\n suiObject.version = object.objectVersion;", "score": 32.95021440030828 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " console.warn(\n `Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}`\n );\n await delay(2000);\n }\n }\n throw new Error('Failed to send transaction with all fullnodes');\n }\n async getObjects(ids: string[]) {\n const options = {", "score": 12.782256795456341 }, { "filename": "src/libs/suiModel/index.ts", "retrieved_chunk": "export { SuiOwnedObject } from './suiOwnedObject';\nexport { SuiSharedObject } from './suiSharedObject';", "score": 8.298551002433621 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " async selectCoins(\n addr: string,\n amount: number,\n coinType: string = '0x2::SUI::SUI'\n ) {\n const selectedCoins: {\n objectId: string;\n digest: string;\n version: string;\n }[] = [];", "score": 7.817557033940283 } ]
typescript
SuiSharedObject | SuiOwnedObject)[]) {
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }: SuiKitParams = {}) { // Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */
async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) {
return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " }\n async getObject(id: string) {\n const objects = await this.getObjects([id]);\n return objects[0];\n }\n /**\n * @description Update objects in a batch\n * @param suiObjects\n */\n async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {", "score": 60.12210856951323 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " const objectIds = suiObjects.map((obj) => obj.objectId);\n const objects = await this.getObjects(objectIds);\n for (const object of objects) {\n const suiObject = suiObjects.find(\n (obj) => obj.objectId === object.objectId\n );\n if (suiObject instanceof SuiSharedObject) {\n suiObject.initialSharedVersion = object.initialSharedVersion;\n } else if (suiObject instanceof SuiOwnedObject) {\n suiObject.version = object.objectVersion;", "score": 33.19186575577262 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " let totalAmount = 0;\n let hasNext = true,\n nextCursor: string | null = null;\n while (hasNext && totalAmount < amount) {\n const coins = await this.currentProvider.getCoins({\n owner: addr,\n coinType: coinType,\n cursor: nextCursor,\n });\n // Sort the coins by balance in descending order", "score": 13.348279021400735 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " console.warn(\n `Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}`\n );\n await delay(2000);\n }\n }\n throw new Error('Failed to send transaction with all fullnodes');\n }\n async getObjects(ids: string[]) {\n const options = {", "score": 12.782256795456341 }, { "filename": "src/libs/suiInteractor/index.ts", "retrieved_chunk": "export { SuiInteractor } from './suiInteractor';\nexport { getDefaultConnection } from './defaultConfig';", "score": 12.347807236514933 } ]
typescript
async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) {
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }: SuiKitParams = {}) { // Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects:
(SuiSharedObject | SuiOwnedObject)[]) {
return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " }\n async getObject(id: string) {\n const objects = await this.getObjects([id]);\n return objects[0];\n }\n /**\n * @description Update objects in a batch\n * @param suiObjects\n */\n async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {", "score": 59.64749914761954 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " const objectIds = suiObjects.map((obj) => obj.objectId);\n const objects = await this.getObjects(objectIds);\n for (const object of objects) {\n const suiObject = suiObjects.find(\n (obj) => obj.objectId === object.objectId\n );\n if (suiObject instanceof SuiSharedObject) {\n suiObject.initialSharedVersion = object.initialSharedVersion;\n } else if (suiObject instanceof SuiOwnedObject) {\n suiObject.version = object.objectVersion;", "score": 32.95021440030828 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " console.warn(\n `Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}`\n );\n await delay(2000);\n }\n }\n throw new Error('Failed to send transaction with all fullnodes');\n }\n async getObjects(ids: string[]) {\n const options = {", "score": 12.782256795456341 }, { "filename": "src/libs/suiModel/index.ts", "retrieved_chunk": "export { SuiOwnedObject } from './suiOwnedObject';\nexport { SuiSharedObject } from './suiSharedObject';", "score": 8.298551002433621 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " async selectCoins(\n addr: string,\n amount: number,\n coinType: string = '0x2::SUI::SUI'\n ) {\n const selectedCoins: {\n objectId: string;\n digest: string;\n version: string;\n }[] = [];", "score": 7.817557033940283 } ]
typescript
(SuiSharedObject | SuiOwnedObject)[]) {
import { TransactionBlock, SUI_SYSTEM_STATE_OBJECT_ID, TransactionExpiration, SuiObjectRef, SharedObjectRef, JsonRpcProvider, TransactionType, Transactions, ObjectCallArg, } from '@mysten/sui.js'; import { convertArgs } from './util'; import type { SuiTxArg, SuiObjectArg, SuiVecTxArg } from 'src/types'; export class SuiTxBlock { public txBlock: TransactionBlock; constructor(transaction?: TransactionBlock) { this.txBlock = new TransactionBlock(transaction); } //======== override methods of TransactionBlock ============ address(value: string) { return this.txBlock.pure(value, 'address'); } pure(value: unknown, type?: string) { return this.txBlock.pure(value, type); } object(value: string | ObjectCallArg) { return this.txBlock.object(value); } objectRef(ref: SuiObjectRef) { return this.txBlock.objectRef(ref); } sharedObjectRef(ref: SharedObjectRef) { return this.txBlock.sharedObjectRef(ref); } setSender(sender: string) { return this.txBlock.setSender(sender); } setSenderIfNotSet(sender: string) { return this.txBlock.setSenderIfNotSet(sender); } setExpiration(expiration?: TransactionExpiration) { return this.txBlock.setExpiration(expiration); } setGasPrice(price: number | bigint) { return this.txBlock.setGasPrice(price); } setGasBudget(budget: number | bigint) { return this.txBlock.setGasBudget(budget); } setGasOwner(owner: string) { return this.txBlock.setGasOwner(owner); } setGasPayment(payments: SuiObjectRef[]) { return this.txBlock.setGasPayment(payments); } add(transaction: TransactionType) { return this.txBlock.add(transaction); } serialize() { return this.txBlock.serialize(); } build( params: { provider?: JsonRpcProvider; onlyTransactionKind?: boolean; } = {} ) { return this.txBlock.build(params); } getDigest({ provider }: { provider?: JsonRpcProvider } = {}) { return this.txBlock.getDigest({ provider }); } get gas() { return this.txBlock.gas; } get blockData() { return this.txBlock.blockData; } transferObjects(objects: SuiObjectArg[], recipient: string) { const tx = this.txBlock;
tx.transferObjects(convertArgs(this.txBlock, objects), tx.pure(recipient));
return this; } splitCoins(coin: SuiObjectArg, amounts: number[]) { const tx = this.txBlock; const coinObject = convertArgs(this.txBlock, [coin])[0]; const res = tx.splitCoins( coinObject, amounts.map((m) => tx.pure(m)) ); return amounts.map((_, i) => res[i]); } mergeCoins(destination: SuiObjectArg, sources: SuiObjectArg[]) { const destinationObject = convertArgs(this.txBlock, [destination])[0]; const sourceObjects = convertArgs(this.txBlock, sources); return this.txBlock.mergeCoins(destinationObject, sourceObjects); } publish(...args: Parameters<(typeof Transactions)['Publish']>) { return this.txBlock.publish(...args); } upgrade(...args: Parameters<(typeof Transactions)['Upgrade']>) { return this.txBlock.upgrade(...args); } makeMoveVec(...args: Parameters<(typeof Transactions)['MakeMoveVec']>) { return this.txBlock.makeMoveVec(...args); } /** * @description Move call * @param target `${string}::${string}::${string}`, e.g. `0x3::sui_system::request_add_stake` * @param args the arguments of the move call, such as `['0x1', '0x2']` * @param typeArgs the type arguments of the move call, such as `['0x2::sui::SUI']` */ moveCall( target: string, args: (SuiTxArg | SuiVecTxArg)[] = [], typeArgs: string[] = [] ) { // a regex for pattern `${string}::${string}::${string}` const regex = /(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/; const match = target.match(regex); if (match === null) throw new Error( 'Invalid target format. Expected `${string}::${string}::${string}`' ); const convertedArgs = convertArgs(this.txBlock, args); const tx = this.txBlock; return tx.moveCall({ target: target as `${string}::${string}::${string}`, arguments: convertedArgs, typeArguments: typeArgs, }); } //======== enhance methods ============ transferSuiToMany(recipients: string[], amounts: number[]) { // require recipients.length === amounts.length if (recipients.length !== amounts.length) { throw new Error( 'transferSuiToMany: recipients.length !== amounts.length' ); } const tx = this.txBlock; const coins = tx.splitCoins( tx.gas, amounts.map((amount) => tx.pure(amount)) ); recipients.forEach((recipient, index) => { tx.transferObjects([coins[index]], tx.pure(recipient)); }); return this; } transferSui(recipient: string, amount: number) { return this.transferSuiToMany([recipient], [amount]); } takeAmountFromCoins(coins: SuiObjectArg[], amount: number) { const tx = this.txBlock; const coinObjects = convertArgs(this.txBlock, coins); const mergedCoin = coinObjects[0]; if (coins.length > 1) { tx.mergeCoins(mergedCoin, coinObjects.slice(1)); } const [sendCoin] = tx.splitCoins(mergedCoin, [tx.pure(amount)]); return [sendCoin, mergedCoin]; } splitSUIFromGas(amounts: number[]) { const tx = this.txBlock; return tx.splitCoins( tx.gas, amounts.map((m) => tx.pure(m)) ); } splitMultiCoins(coins: SuiObjectArg[], amounts: number[]) { const tx = this.txBlock; const coinObjects = convertArgs(this.txBlock, coins); const mergedCoin = coinObjects[0]; if (coins.length > 1) { tx.mergeCoins(mergedCoin, coinObjects.slice(1)); } const splitedCoins = tx.splitCoins( mergedCoin, amounts.map((m) => tx.pure(m)) ); return { splitedCoins, mergedCoin }; } transferCoinToMany( inputCoins: SuiObjectArg[], sender: string, recipients: string[], amounts: number[] ) { // require recipients.length === amounts.length if (recipients.length !== amounts.length) { throw new Error( 'transferSuiToMany: recipients.length !== amounts.length' ); } const tx = this.txBlock; const { splitedCoins, mergedCoin } = this.splitMultiCoins( inputCoins, amounts ); recipients.forEach((recipient, index) => { tx.transferObjects([splitedCoins[index]], tx.pure(recipient)); }); tx.transferObjects([mergedCoin], tx.pure(sender)); return this; } transferCoin( inputCoins: SuiObjectArg[], sender: string, recipient: string, amount: number ) { return this.transferCoinToMany(inputCoins, sender, [recipient], [amount]); } stakeSui(amount: number, validatorAddr: string) { const tx = this.txBlock; const [stakeCoin] = tx.splitCoins(tx.gas, [tx.pure(amount)]); tx.moveCall({ target: '0x3::sui_system::request_add_stake', arguments: [ tx.object(SUI_SYSTEM_STATE_OBJECT_ID), stakeCoin, tx.pure(validatorAddr), ], }); return tx; } }
src/libs/suiTxBuilder/index.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/suiKit.ts", "retrieved_chunk": " recipient: string,\n derivePathParams?: DerivePathParams\n ) {\n const tx = new SuiTxBlock();\n tx.transferObjects(objects, recipient);\n return this.signAndSendTxn(tx, derivePathParams);\n }\n async moveCall(callParams: {\n target: string;\n arguments?: (SuiTxArg | SuiVecTxArg)[];", "score": 32.63134242558247 }, { "filename": "src/libs/suiTxBuilder/util.ts", "retrieved_chunk": " const objects = args.map((arg) =>\n typeof arg === 'string'\n ? txBlock.object(normalizeSuiObjectId(arg))\n : (arg as any)\n );\n return txBlock.makeMoveVec({ objects });\n } else {\n const vecType = type || defaultSuiType;\n return txBlock.pure(args, `vector<${vecType}>`);\n }", "score": 28.533461511989014 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " ) {\n return this.transferCoinToMany(\n [recipient],\n [amount],\n coinType,\n derivePathParams\n );\n }\n async transferObjects(\n objects: string[],", "score": 26.94004122476988 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " async inspectTxn(\n tx: Uint8Array | TransactionBlock | SuiTxBlock,\n derivePathParams?: DerivePathParams\n ): Promise<DevInspectResults> {\n tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;\n return this.suiInteractor.currentProvider.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: this.getAddress(derivePathParams),\n });\n }", "score": 23.35469222295437 }, { "filename": "src/suiKit.ts", "retrieved_chunk": " derivePathParams?: DerivePathParams\n ) {\n tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;\n const signer = this.getSigner(derivePathParams);\n return signer.signTransactionBlock({ transactionBlock: tx });\n }\n async signAndSendTxn(\n tx: Uint8Array | TransactionBlock | SuiTxBlock,\n derivePathParams?: DerivePathParams\n ): Promise<SuiTransactionBlockResponse> {", "score": 22.73315143811588 } ]
typescript
tx.transferObjects(convertArgs(this.txBlock, objects), tx.pure(recipient));
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }: SuiKitParams = {}) { // Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(
suiObjects: (SuiSharedObject | SuiOwnedObject)[]) {
return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " }\n async getObject(id: string) {\n const objects = await this.getObjects([id]);\n return objects[0];\n }\n /**\n * @description Update objects in a batch\n * @param suiObjects\n */\n async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {", "score": 59.64749914761954 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " const objectIds = suiObjects.map((obj) => obj.objectId);\n const objects = await this.getObjects(objectIds);\n for (const object of objects) {\n const suiObject = suiObjects.find(\n (obj) => obj.objectId === object.objectId\n );\n if (suiObject instanceof SuiSharedObject) {\n suiObject.initialSharedVersion = object.initialSharedVersion;\n } else if (suiObject instanceof SuiOwnedObject) {\n suiObject.version = object.objectVersion;", "score": 32.95021440030828 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " console.warn(\n `Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}`\n );\n await delay(2000);\n }\n }\n throw new Error('Failed to send transaction with all fullnodes');\n }\n async getObjects(ids: string[]) {\n const options = {", "score": 12.782256795456341 }, { "filename": "src/libs/suiModel/index.ts", "retrieved_chunk": "export { SuiOwnedObject } from './suiOwnedObject';\nexport { SuiSharedObject } from './suiSharedObject';", "score": 8.298551002433621 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " async selectCoins(\n addr: string,\n amount: number,\n coinType: string = '0x2::SUI::SUI'\n ) {\n const selectedCoins: {\n objectId: string;\n digest: string;\n version: string;\n }[] = [];", "score": 7.817557033940283 } ]
typescript
suiObjects: (SuiSharedObject | SuiOwnedObject)[]) {
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }: SuiKitParams = {}) { // Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) { return this.suiInteractor.updateObjects(suiObjects); } async signTxn(
tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) {
tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " }\n async getObject(id: string) {\n const objects = await this.getObjects([id]);\n return objects[0];\n }\n /**\n * @description Update objects in a batch\n * @param suiObjects\n */\n async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {", "score": 62.192811742639655 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " const objectIds = suiObjects.map((obj) => obj.objectId);\n const objects = await this.getObjects(objectIds);\n for (const object of objects) {\n const suiObject = suiObjects.find(\n (obj) => obj.objectId === object.objectId\n );\n if (suiObject instanceof SuiSharedObject) {\n suiObject.initialSharedVersion = object.initialSharedVersion;\n } else if (suiObject instanceof SuiOwnedObject) {\n suiObject.version = object.objectVersion;", "score": 21.6028210665562 }, { "filename": "src/libs/suiAccountManager/keypair.ts", "retrieved_chunk": "import { Ed25519Keypair } from '@mysten/sui.js';\nimport type { DerivePathParams } from 'src/types';\n/**\n * @description Get ed25519 derive path for SUI\n * @param derivePathParams\n */\nexport const getDerivePathForSUI = (\n derivePathParams: DerivePathParams = {}\n) => {\n const {", "score": 11.434428657038886 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " }\n switchToNextProvider() {\n const currentProviderIdx = this.providers.indexOf(this.currentProvider);\n this.currentProvider =\n this.providers[(currentProviderIdx + 1) % this.providers.length];\n }\n async sendTx(\n transactionBlock: Uint8Array | string,\n signature: string | string[]\n ): Promise<SuiTransactionBlockResponse> {", "score": 9.856089176806874 }, { "filename": "src/libs/suiAccountManager/util.ts", "retrieved_chunk": " * @param str\n */\nexport const isBase64 = (str: string) => /^[a-zA-Z0-9+/]+={0,2}$/g.test(str);\n/**\n * Convert a hex string to Uint8Array\n * @param hexStr\n */\nexport const fromHEX = (hexStr: string): Uint8Array => {\n if (!hexStr) {\n throw new Error('cannot parse empty string to Uint8Array');", "score": 8.691939468992423 } ]
typescript
tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) {
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }
: SuiKitParams = {}) {
// Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) { return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiInteractor/defaultConfig.ts", "retrieved_chunk": "/**\n * @description Get the default fullnode url and faucet url for the given network type\n * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'\n * @returns { fullNode: string, websocket: string, faucet?: string }\n */\nexport const getDefaultConnection = (\n networkType: NetworkType = 'devnet'\n): Connection => {\n switch (networkType) {\n case 'localnet':", "score": 70.27820953437858 }, { "filename": "src/types/index.ts", "retrieved_chunk": " mnemonics?: string;\n secretKey?: string;\n};\nexport type DerivePathParams = {\n accountIndex?: number;\n isExternal?: boolean;\n addressIndex?: number;\n};\nexport type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';\nexport type SuiKitParams = {", "score": 30.453996679215514 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " suiObject.digest = object.objectDigest;\n }\n }\n }\n /**\n * @description Select coins that add up to the given amount.\n * @param addr the address of the owner\n * @param amount the amount that is needed for the coin\n * @param coinType the coin type, default is '0x2::SUI::SUI'\n */", "score": 24.154973241129095 }, { "filename": "src/libs/suiAccountManager/keypair.ts", "retrieved_chunk": " *\n * isExternal is the type of the address, default is false. Usually, the external address is used to receive coins. The internal address is used to change coins.\n *\n * addressIndex is the index of the address, default is 0. It's used to generate multiple addresses for one account.\n *\n * @description Get keypair from mnemonics and derive path\n * @param mnemonics\n * @param derivePathParams\n */\nexport const getKeyPair = (", "score": 23.530252291856655 }, { "filename": "src/libs/suiInteractor/defaultConfig.ts", "retrieved_chunk": " return localnetConnection;\n case 'devnet':\n return devnetConnection;\n case 'testnet':\n return testnetConnection;\n case 'mainnet':\n return mainnetConnection;\n default:\n return devnetConnection;\n }", "score": 22.80990385356604 } ]
typescript
: SuiKitParams = {}) {
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }: SuiKitParams = {}) { // Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) { return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock |
SuiTxBlock, derivePathParams?: DerivePathParams ) {
tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " }\n async getObject(id: string) {\n const objects = await this.getObjects([id]);\n return objects[0];\n }\n /**\n * @description Update objects in a batch\n * @param suiObjects\n */\n async updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]) {", "score": 42.34199873411556 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " const objectIds = suiObjects.map((obj) => obj.objectId);\n const objects = await this.getObjects(objectIds);\n for (const object of objects) {\n const suiObject = suiObjects.find(\n (obj) => obj.objectId === object.objectId\n );\n if (suiObject instanceof SuiSharedObject) {\n suiObject.initialSharedVersion = object.initialSharedVersion;\n } else if (suiObject instanceof SuiOwnedObject) {\n suiObject.version = object.objectVersion;", "score": 18.532074109824258 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " }\n switchToNextProvider() {\n const currentProviderIdx = this.providers.indexOf(this.currentProvider);\n this.currentProvider =\n this.providers[(currentProviderIdx + 1) % this.providers.length];\n }\n async sendTx(\n transactionBlock: Uint8Array | string,\n signature: string | string[]\n ): Promise<SuiTransactionBlockResponse> {", "score": 9.856089176806874 }, { "filename": "src/libs/suiAccountManager/keypair.ts", "retrieved_chunk": "import { Ed25519Keypair } from '@mysten/sui.js';\nimport type { DerivePathParams } from 'src/types';\n/**\n * @description Get ed25519 derive path for SUI\n * @param derivePathParams\n */\nexport const getDerivePathForSUI = (\n derivePathParams: DerivePathParams = {}\n) => {\n const {", "score": 8.990749481866567 }, { "filename": "src/libs/suiModel/index.ts", "retrieved_chunk": "export { SuiOwnedObject } from './suiOwnedObject';\nexport { SuiSharedObject } from './suiSharedObject';", "score": 8.298551002433621 } ]
typescript
SuiTxBlock, derivePathParams?: DerivePathParams ) {
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }: SuiKitParams = {}) { // Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) { return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany(
coins.map((c) => c.objectId), owner, recipients, amounts );
return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string; arguments?: (SuiTxArg | SuiVecTxArg)[]; typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " let totalAmount = 0;\n let hasNext = true,\n nextCursor: string | null = null;\n while (hasNext && totalAmount < amount) {\n const coins = await this.currentProvider.getCoins({\n owner: addr,\n coinType: coinType,\n cursor: nextCursor,\n });\n // Sort the coins by balance in descending order", "score": 18.410647329348446 }, { "filename": "src/libs/suiTxBuilder/index.ts", "retrieved_chunk": " amounts.map((m) => tx.pure(m))\n );\n return { splitedCoins, mergedCoin };\n }\n transferCoinToMany(\n inputCoins: SuiObjectArg[],\n sender: string,\n recipients: string[],\n amounts: number[]\n ) {", "score": 16.344194966750806 }, { "filename": "src/libs/suiTxBuilder/index.ts", "retrieved_chunk": " }\n const tx = this.txBlock;\n const coins = tx.splitCoins(\n tx.gas,\n amounts.map((amount) => tx.pure(amount))\n );\n recipients.forEach((recipient, index) => {\n tx.transferObjects([coins[index]], tx.pure(recipient));\n });\n return this;", "score": 14.347800122813613 }, { "filename": "src/libs/suiTxBuilder/index.ts", "retrieved_chunk": " // require recipients.length === amounts.length\n if (recipients.length !== amounts.length) {\n throw new Error(\n 'transferSuiToMany: recipients.length !== amounts.length'\n );\n }\n const tx = this.txBlock;\n const { splitedCoins, mergedCoin } = this.splitMultiCoins(\n inputCoins,\n amounts", "score": 10.831769977752028 }, { "filename": "src/libs/suiInteractor/suiInteractor.ts", "retrieved_chunk": " coins.data.sort((a, b) => parseInt(b.balance) - parseInt(a.balance));\n for (const coinData of coins.data) {\n selectedCoins.push({\n objectId: coinData.coinObjectId,\n digest: coinData.digest,\n version: coinData.version,\n });\n totalAmount = totalAmount + parseInt(coinData.balance);\n if (totalAmount >= amount) {\n break;", "score": 10.365042114268164 } ]
typescript
coins.map((c) => c.objectId), owner, recipients, amounts );
/** * @description This file is used to aggregate the tools that used to interact with SUI network. */ import { RawSigner, TransactionBlock, DevInspectResults, SuiTransactionBlockResponse, } from '@mysten/sui.js'; import { SuiAccountManager } from './libs/suiAccountManager'; import { SuiTxBlock } from './libs/suiTxBuilder'; import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor'; import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel'; import { SuiKitParams, DerivePathParams, SuiTxArg, SuiVecTxArg } from './types'; /** * @class SuiKit * @description This class is used to aggregate the tools that used to interact with SUI network. */ export class SuiKit { public accountManager: SuiAccountManager; public suiInteractor: SuiInteractor; /** * Support the following ways to init the SuiToolkit: * 1. mnemonics * 2. secretKey (base64 or hex) * If none of them is provided, will generate a random mnemonics with 24 words. * * @param mnemonics, 12 or 24 mnemonics words, separated by space * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet' * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type */ constructor({ mnemonics, secretKey, networkType, fullnodeUrls, }: SuiKitParams = {}) { // Init the account manager this.accountManager = new SuiAccountManager({ mnemonics, secretKey }); // Init the rpc provider fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode]; this.suiInteractor = new SuiInteractor(fullnodeUrls); } /** * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner. * else: * it will generate signer from the mnemonic with the given derivePathParams. * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getSigner(derivePathParams?: DerivePathParams) { const keyPair = this.accountManager.getKeyPair(derivePathParams); return new RawSigner(keyPair, this.suiInteractor.currentProvider); } /** * @description Switch the current account with the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ switchAccount(derivePathParams: DerivePathParams) { this.accountManager.switchAccount(derivePathParams); } /** * @description Get the address of the account for the given derivePathParams * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard */ getAddress(derivePathParams?: DerivePathParams) { return this.accountManager.getAddress(derivePathParams); } currentAddress() { return this.accountManager.currentAddress; } provider() { return this.suiInteractor.currentProvider; } async getBalance(coinType?: string, derivePathParams?: DerivePathParams) { const owner = this.accountManager.getAddress(derivePathParams); return this.suiInteractor.currentProvider.getBalance({ owner, coinType }); } async getObjects(objectIds: string[]) { return this.suiInteractor.getObjects(objectIds); } /** * @description Update objects in a batch * @param suiObjects */ async updateObjects(suiObjects: (SuiSharedObject | SuiOwnedObject)[]) { return this.suiInteractor.updateObjects(suiObjects); } async signTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ) { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; const signer = this.getSigner(derivePathParams); return signer.signTransactionBlock({ transactionBlock: tx }); } async signAndSendTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<SuiTransactionBlockResponse> { const { transactionBlockBytes, signature } = await this.signTxn( tx, derivePathParams ); return this.suiInteractor.sendTx(transactionBlockBytes, signature); } /** * Transfer the given amount of SUI to the recipient * @param recipient * @param amount * @param derivePathParams */ async transferSui( recipient: string, amount: number, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSui(recipient, amount); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer to mutliple recipients * @param recipients the recipients addresses * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients * @param derivePathParams */ async transferSuiToMany( recipients: string[], amounts: number[], derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferSuiToMany(recipients, amounts); return this.signAndSendTxn(tx, derivePathParams); } /** * Transfer the given amounts of coin to multiple recipients * @param recipients the list of recipient address * @param amounts the amounts to transfer for each recipient * @param coinType any custom coin type but not SUI * @param derivePathParams the derive path params for the current signer */ async transferCoinToMany( recipients: string[], amounts: number[], coinType: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); const owner = this.accountManager.getAddress(derivePathParams); const totalAmount = amounts.reduce((a, b) => a + b, 0); const coins = await this.suiInteractor.selectCoins( owner, totalAmount, coinType ); tx.transferCoinToMany( coins.map((c) => c.objectId), owner, recipients, amounts ); return this.signAndSendTxn(tx, derivePathParams); } async transferCoin( recipient: string, amount: number, coinType: string, derivePathParams?: DerivePathParams ) { return this.transferCoinToMany( [recipient], [amount], coinType, derivePathParams ); } async transferObjects( objects: string[], recipient: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.transferObjects(objects, recipient); return this.signAndSendTxn(tx, derivePathParams); } async moveCall(callParams: { target: string;
arguments?: (SuiTxArg | SuiVecTxArg)[];
typeArguments?: string[]; derivePathParams?: DerivePathParams; }) { const { target, arguments: args = [], typeArguments = [], derivePathParams, } = callParams; const tx = new SuiTxBlock(); tx.moveCall(target, args, typeArguments); return this.signAndSendTxn(tx, derivePathParams); } /** * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount * @param amount * @param coinType * @param owner */ async selectCoinsWithAmount( amount: number, coinType: string, owner?: string ) { owner = owner || this.accountManager.currentAddress; const coins = await this.suiInteractor.selectCoins(owner, amount, coinType); return coins.map((c) => c.objectId); } /** * stake the given amount of SUI to the validator * @param amount the amount of SUI to stake * @param validatorAddr the validator address * @param derivePathParams the derive path params for the current signer */ async stakeSui( amount: number, validatorAddr: string, derivePathParams?: DerivePathParams ) { const tx = new SuiTxBlock(); tx.stakeSui(amount, validatorAddr); return this.signAndSendTxn(tx, derivePathParams); } /** * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction. * Since the transaction is not submitted, its gas cost is not charged. * @param tx the transaction to execute * @param derivePathParams the derive path params * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted. */ async inspectTxn( tx: Uint8Array | TransactionBlock | SuiTxBlock, derivePathParams?: DerivePathParams ): Promise<DevInspectResults> { tx = tx instanceof SuiTxBlock ? tx.txBlock : tx; return this.suiInteractor.currentProvider.devInspectTransactionBlock({ transactionBlock: tx, sender: this.getAddress(derivePathParams), }); } }
src/suiKit.ts
scallop-io-sui-kit-bea8b42
[ { "filename": "src/libs/suiTxBuilder/index.ts", "retrieved_chunk": " recipient: string,\n amount: number\n ) {\n return this.transferCoinToMany(inputCoins, sender, [recipient], [amount]);\n }\n stakeSui(amount: number, validatorAddr: string) {\n const tx = this.txBlock;\n const [stakeCoin] = tx.splitCoins(tx.gas, [tx.pure(amount)]);\n tx.moveCall({\n target: '0x3::sui_system::request_add_stake',", "score": 25.030425587208892 }, { "filename": "src/libs/suiTxBuilder/index.ts", "retrieved_chunk": " );\n recipients.forEach((recipient, index) => {\n tx.transferObjects([splitedCoins[index]], tx.pure(recipient));\n });\n tx.transferObjects([mergedCoin], tx.pure(sender));\n return this;\n }\n transferCoin(\n inputCoins: SuiObjectArg[],\n sender: string,", "score": 24.307796703971963 }, { "filename": "src/libs/suiTxBuilder/index.ts", "retrieved_chunk": " }\n const tx = this.txBlock;\n const coins = tx.splitCoins(\n tx.gas,\n amounts.map((amount) => tx.pure(amount))\n );\n recipients.forEach((recipient, index) => {\n tx.transferObjects([coins[index]], tx.pure(recipient));\n });\n return this;", "score": 22.675299036504082 }, { "filename": "src/libs/suiTxBuilder/index.ts", "retrieved_chunk": " const match = target.match(regex);\n if (match === null)\n throw new Error(\n 'Invalid target format. Expected `${string}::${string}::${string}`'\n );\n const convertedArgs = convertArgs(this.txBlock, args);\n const tx = this.txBlock;\n return tx.moveCall({\n target: target as `${string}::${string}::${string}`,\n arguments: convertedArgs,", "score": 21.350800434391182 }, { "filename": "src/libs/suiTxBuilder/index.ts", "retrieved_chunk": " tx.transferObjects(convertArgs(this.txBlock, objects), tx.pure(recipient));\n return this;\n }\n splitCoins(coin: SuiObjectArg, amounts: number[]) {\n const tx = this.txBlock;\n const coinObject = convertArgs(this.txBlock, [coin])[0];\n const res = tx.splitCoins(\n coinObject,\n amounts.map((m) => tx.pure(m))\n );", "score": 20.84340362949284 } ]
typescript
arguments?: (SuiTxArg | SuiVecTxArg)[];
/** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Redux import { RootState } from '../redux/store' import { useAppSelector, useAppDispatch } from '../redux/hooks' import { moveUp, moveDown, moveLeft, moveRight, collectItem, startMission, setIsSavingMission } from '../redux/gameSlice' import { useEffect } from 'react'; import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice'; import { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon } from '@heroicons/react/24/outline' export default function Component() { const { playerPosition, allItemsCollected, mission, isSavingMission } = useAppSelector((state: RootState) => state.game) const { data: user, } = useGetUserQuery(); const playerOnFinalSquare = playerPosition.x === 2 && playerPosition.y === 2; const dispatch = useAppDispatch() const [addCompletedMission] = useAddCompletedMissionMutation() function keyPressHandler({ key, keyCode }: { key: string | undefined, keyCode: number | undefined }) { switch (key) { case 'w': return dispatch(moveUp()) case 'a': return dispatch(moveLeft()) case 's': return dispatch(moveDown()) case 'd': return dispatch(moveRight()) } switch (keyCode) { case 38: // up arrow return dispatch(moveUp()) case 37: // left arrow return dispatch(moveLeft()) case 40: // down arrow return dispatch(moveDown()) case 39: // right arrow return dispatch(moveRight()) case 13: // enter if (allItemsCollected && playerOnFinalSquare && user && !isSavingMission) {
dispatch(setIsSavingMission(true));
return addCompletedMission({ mission }).unwrap() .then(() => { dispatch(startMission({ nextMission: true })) }) .catch(error => { console.error('addCompletedMission request did not work.', { error }) }).finally(() => { dispatch(setIsSavingMission(false)); }); } return dispatch(collectItem()) } } useEffect(() => { window.addEventListener("keydown", keyPressHandler); return () => { window.removeEventListener("keydown", keyPressHandler); }; }); return ( <section className="hidden sm:block bg-slate-800 rounded-r-xl p-8 col-span-2 space-y-4"> <h2 className='text-slate-100'>Controls</h2> <section className="grid grid-cols-3 gap-3 w-fit"> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player up" onClick={() => dispatch(moveUp())} > <ArrowUpIcon className="block h-6 w-6" aria-hidden="true" /> </button> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player left" onClick={() => dispatch(moveLeft())} > <ArrowLeftIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player down" onClick={() => dispatch(moveDown())} > <ArrowDownIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player right" onClick={() => dispatch(moveRight())} > <ArrowRightIcon className="block h-6 w-6" aria-hidden="true" /> </button> </section> </section > ) }
src/components/game-controls.tsx
GoogleCloudPlatform-developer-journey-app-c20b105
[ { "filename": "src/components/tile.tsx", "retrieved_chunk": " return (\n <section className=\"min-h-full\" onClick={() => {\n if (playerIsLeftOfTile) {\n dispatch(moveRight())\n }\n if (playerIsRightOfTile) {\n dispatch(moveLeft())\n }\n if (playerIsAboveTile) {\n dispatch(moveDown())", "score": 53.52777136434578 }, { "filename": "src/redux/gameSlice.ts", "retrieved_chunk": " },\n setIsSavingMission: (state, action: PayloadAction<boolean>) => {\n state.isSavingMission = action.payload;\n },\n }\n})\n// Action creators are generated for each case reducer function\nexport const { startMission, moveUp, moveDown, moveLeft, moveRight, collectItem, setIsSavingMission } = gameSlice.actions\nexport default gameSlice.reducer", "score": 46.508900681953776 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " const tileIsFinalTile = x == 2 && y == 2;\n const tileItem = inventory.find(item => item.position.x === x && item.position.y === y && item.status === 'NOT_COLLECTED');\n const completeMission = async () => {\n if (allItemsCollected && user) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch((error: Error) => {", "score": 40.716012383729655 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {\n dispatch(setIsSavingMission(false));\n });\n }\n }\n if (isError) {\n return <div>{error.toString()}</div>\n }\n if (isSuccess || isLoading) {", "score": 33.24662504310139 }, { "filename": "src/redux/apiSlice.ts", "retrieved_chunk": " getUser: builder.query<User, void>({\n // The URL for the request is '/api/user', this is a GET request\n query: () => '/user',\n onCacheEntryAdded: (_, { dispatch }) => { \n dispatch(startMission())\n },\n providesTags: ['User'],\n }),\n addCompletedMission: builder.mutation({\n // The URL for the request is '/api/user', this is a POST request", "score": 25.19539241575072 } ]
typescript
dispatch(setIsSavingMission(true));
/** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Redux import { RootState } from '../redux/store' import { useAppSelector, useAppDispatch } from '../redux/hooks' import { moveUp, moveDown, moveLeft, moveRight, collectItem, startMission, setIsSavingMission } from '../redux/gameSlice' import { useEffect } from 'react'; import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice'; import { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon } from '@heroicons/react/24/outline' export default function Component() { const { playerPosition, allItemsCollected, mission, isSavingMission } = useAppSelector((state: RootState) => state.game) const { data: user, } = useGetUserQuery(); const playerOnFinalSquare = playerPosition.x === 2 && playerPosition.y === 2; const dispatch = useAppDispatch() const [addCompletedMission] = useAddCompletedMissionMutation() function keyPressHandler({ key, keyCode }: { key: string | undefined, keyCode: number | undefined }) { switch (key) { case 'w': return dispatch(moveUp()) case 'a': return dispatch(moveLeft()) case 's': return dispatch(moveDown()) case 'd': return dispatch(moveRight()) } switch (keyCode) { case 38: // up arrow return dispatch(moveUp()) case 37: // left arrow return dispatch(moveLeft()) case 40: // down arrow return dispatch(moveDown()) case 39: // right arrow return dispatch(moveRight()) case 13: // enter if (allItemsCollected && playerOnFinalSquare && user && !isSavingMission) { dispatch(setIsSavingMission(true)); return addCompletedMission({ mission }).unwrap() .then(() => { dispatch(startMission({ nextMission: true })) }) .catch(error => { console.error('addCompletedMission request did not work.', { error }) }).finally(() => { dispatch(setIsSavingMission(false)); }); }
return dispatch(collectItem()) }
} useEffect(() => { window.addEventListener("keydown", keyPressHandler); return () => { window.removeEventListener("keydown", keyPressHandler); }; }); return ( <section className="hidden sm:block bg-slate-800 rounded-r-xl p-8 col-span-2 space-y-4"> <h2 className='text-slate-100'>Controls</h2> <section className="grid grid-cols-3 gap-3 w-fit"> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player up" onClick={() => dispatch(moveUp())} > <ArrowUpIcon className="block h-6 w-6" aria-hidden="true" /> </button> <div /> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player left" onClick={() => dispatch(moveLeft())} > <ArrowLeftIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player down" onClick={() => dispatch(moveDown())} > <ArrowDownIcon className="block h-6 w-6" aria-hidden="true" /> </button> <button className='text-slate-900 bg-slate-100 hover:bg-slate-200 py-2 px-4 rounded' aria-label="Move player right" onClick={() => dispatch(moveRight())} > <ArrowRightIcon className="block h-6 w-6" aria-hidden="true" /> </button> </section> </section > ) }
src/components/game-controls.tsx
GoogleCloudPlatform-developer-journey-app-c20b105
[ { "filename": "src/components/tile.tsx", "retrieved_chunk": " console.error('addCompletedMission request did not work.', { error })\n }).finally(() => {\n dispatch(setIsSavingMission(false));\n });\n }\n }\n if (isError) {\n return <div>{error.toString()}</div>\n }\n if (isSuccess || isLoading) {", "score": 69.0537302108982 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " const tileIsFinalTile = x == 2 && y == 2;\n const tileItem = inventory.find(item => item.position.x === x && item.position.y === y && item.status === 'NOT_COLLECTED');\n const completeMission = async () => {\n if (allItemsCollected && user) {\n dispatch(setIsSavingMission(true));\n return addCompletedMission({ mission }).unwrap()\n .then(() => {\n dispatch(startMission({ nextMission: true }))\n })\n .catch((error: Error) => {", "score": 43.337998376988075 }, { "filename": "src/redux/apiSlice.ts", "retrieved_chunk": " getUser: builder.query<User, void>({\n // The URL for the request is '/api/user', this is a GET request\n query: () => '/user',\n onCacheEntryAdded: (_, { dispatch }) => { \n dispatch(startMission())\n },\n providesTags: ['User'],\n }),\n addCompletedMission: builder.mutation({\n // The URL for the request is '/api/user', this is a POST request", "score": 24.848542519928554 }, { "filename": "src/components/tile.tsx", "retrieved_chunk": " return (\n <section className=\"min-h-full\" onClick={() => {\n if (playerIsLeftOfTile) {\n dispatch(moveRight())\n }\n if (playerIsRightOfTile) {\n dispatch(moveLeft())\n }\n if (playerIsAboveTile) {\n dispatch(moveDown())", "score": 18.947808260684432 }, { "filename": "src/components/tile-board.tsx", "retrieved_chunk": " const {\n isLoading,\n isError,\n error\n } = useGetUserQuery();\n const [showUhOh, setShowUhOh] = useState<Boolean>(false);\n const [timeExpired, setTimeExpired] = useState(false);\n useEffect(\n () => {\n if (isLoading) {", "score": 15.300267372311499 } ]
typescript
return dispatch(collectItem()) }