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 { 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/types/lightning.ts",
"retrieved_chunk": "}\nexport interface CreateChargeFromLightningAddressOptionsType {\n amount: string\n lnaddress: string\n lnAddress?: string\n description: string\n}",
"score": 0.87754225730896
},
{
"filename": "src/types/lightning.d.ts",
"retrieved_chunk": "}\nexport interface CreateChargeFromLightningAddressOptionsType {\n amount: string;\n lnaddress: string;\n lnAddress?: string;\n description: string;\n}\n//# sourceMappingURL=lightning.d.ts.map",
"score": 0.8467779159545898
},
{
"filename": "src/types/lightning.d.ts",
"retrieved_chunk": " };\n success: boolean;\n message: string;\n}\nexport interface SendLightningAddressPaymentOptionsType {\n lnAddress: string;\n amount: string;\n comment: string;\n callbackUrl: string;\n internalId: string;",
"score": 0.842625081539154
},
{
"filename": "src/types/lightning.ts",
"retrieved_chunk": " }\n success: boolean;\n message: string;\n}\nexport interface SendLightningAddressPaymentOptionsType {\n lnAddress: string;\n amount: string;\n comment: string;\n callbackUrl: string;\n internalId: string;",
"score": 0.841202974319458
},
{
"filename": "src/types/lightning.ts",
"retrieved_chunk": " }\n success: boolean;\n}\nexport interface FetchChargeFromLightningAddressDataResponseType {\n data: {\n lnaddress: string;\n amount: string;\n invoice: {\n uri: string;\n request: string;",
"score": 0.8340312242507935
}
] |
typescript
|
: `${API_URL}${API.CREATE_CHARGE_FROM_LN_ADDRESS_ENDPOINT}`,
headers: { ...this.apiCoreHeaders },
body: {
|
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": 0.8728252649307251
},
{
"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": 0.8727484941482544
},
{
"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": 0.8638174533843994
},
{
"filename": "src/adapter/__tests__/FetchAdapter.test.ts",
"retrieved_chunk": " method: 'POST',\n headers: new Headers(),\n })\n })\n it('should add abortSignal when given ctx with `abort` field', () => {\n const spy = vi.spyOn(global, 'fetch').mockImplementation(toAny(vi.fn()))\n const abort = new TimeoutAbortController(0)\n new FetchAdapter()\n .request(\n toAny({",
"score": 0.8521628379821777
},
{
"filename": "src/core/AbortController.ts",
"retrieved_chunk": "export class TimeoutAbortController {\n static readonly supported = typeof AbortController !== 'undefined'\n private controller: AbortController\n private timeoutId: ReturnType<typeof setTimeout> | null = null\n constructor(timeout: number) {\n if (!TimeoutAbortController.supported)\n throw new ReferenceError(\n 'Not support AbortController in current environment.'\n )\n this.controller = new AbortController()",
"score": 0.8513287305831909
}
] |
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/types/charges.ts",
"retrieved_chunk": "export interface ChargeDataResponseType {\n data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;",
"score": 0.861592710018158
},
{
"filename": "src/types/charges.d.ts",
"retrieved_chunk": "export interface ChargeDataResponseType {\n data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;",
"score": 0.8614141941070557
},
{
"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": 0.8295347690582275
},
{
"filename": "src/types/static-charges.d.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": 0.8287636637687683
},
{
"filename": "src/types/charges.ts",
"retrieved_chunk": "export interface DecodeChargeResponseType {\n data: {\n unit: string;\n status: string;\n amount: string;\n createdAt: string;\n internalId: string;\n callbackUrl: string;\n description: string;\n invoiceRequest: string;",
"score": 0.8222149014472961
}
] |
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/types/charges.d.ts",
"retrieved_chunk": "export interface ChargeOptionsType {\n expiresIn: number;\n amount: string;\n description: string;\n internalId: string;\n callbackUrl: string;\n}\nexport interface DecodeChargeOptionsType {\n invoice: string;\n}",
"score": 0.8678807020187378
},
{
"filename": "src/types/charges.ts",
"retrieved_chunk": "export interface ChargeOptionsType {\n expiresIn: number;\n amount: string;\n description: string;\n internalId: string;\n callbackUrl: string;\n}\nexport interface DecodeChargeOptionsType {\n invoice: string;\n}",
"score": 0.8671219944953918
},
{
"filename": "src/types/charges.ts",
"retrieved_chunk": "export interface ChargeDataResponseType {\n data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;",
"score": 0.8591603636741638
},
{
"filename": "src/types/charges.d.ts",
"retrieved_chunk": "export interface ChargeDataResponseType {\n data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;",
"score": 0.8583288788795471
},
{
"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": 0.8455355763435364
}
] |
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/zbd.d.ts",
"retrieved_chunk": " createWithdrawalRequest(options: WithdrawalRequestOptionsType): Promise<CreateWithdrawalRequestDataResponseType>;\n getWithdrawalRequest(withdrawalRequestId: string): Promise<GetWithdrawalRequestDataResponseType>;\n validateLightningAddress(lightningAddress: string): Promise<ValidateLightningAddressDataResponseType>;\n sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType): Promise<SendLightningAddressPaymentDataResponseType>;\n createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType): Promise<FetchChargeFromLightningAddressDataResponseType>;\n getWallet(): Promise<WalletDataResponseType>;\n isSupportedRegion(ipAddress: string): Promise<SupportedRegionDataResponseType>;\n getZBDProdIps(): Promise<ProdIPSDataResponseType>;\n getBtcUsdExchangeRate(): Promise<BTCUSDDataResponseType>;\n internalTransfer(options: InternalTransferOptionsType): Promise<InternalTransferDataResponseType>;",
"score": 0.8527396321296692
},
{
"filename": "src/types/lightning.ts",
"retrieved_chunk": " }\n success: boolean;\n}\nexport interface FetchChargeFromLightningAddressDataResponseType {\n data: {\n lnaddress: string;\n amount: string;\n invoice: {\n uri: string;\n request: string;",
"score": 0.8395859599113464
},
{
"filename": "src/types/lightning.d.ts",
"retrieved_chunk": "export interface ValidateLightningAddressDataResponseType {\n data: {\n valid: boolean;\n metadata: {\n minSendable: number;\n maxSendable: number;\n commentAllowed: number;\n tag: string;\n metadata: string;\n callback: string;",
"score": 0.8371446132659912
},
{
"filename": "src/types/lightning.ts",
"retrieved_chunk": "export interface ValidateLightningAddressDataResponseType {\n data: {\n valid: boolean;\n metadata: {\n minSendable: number;\n maxSendable: number;\n commentAllowed: number;\n tag: string;\n metadata: string;\n callback: string;",
"score": 0.8370208144187927
},
{
"filename": "src/types/lightning.d.ts",
"retrieved_chunk": " };\n success: boolean;\n}\nexport interface FetchChargeFromLightningAddressDataResponseType {\n data: {\n lnaddress: string;\n amount: string;\n invoice: {\n uri: string;\n request: string;",
"score": 0.8368525505065918
}
] |
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/types/charges.d.ts",
"retrieved_chunk": "export interface ChargeOptionsType {\n expiresIn: number;\n amount: string;\n description: string;\n internalId: string;\n callbackUrl: string;\n}\nexport interface DecodeChargeOptionsType {\n invoice: string;\n}",
"score": 0.8633572459220886
},
{
"filename": "src/types/charges.ts",
"retrieved_chunk": "export interface ChargeOptionsType {\n expiresIn: number;\n amount: string;\n description: string;\n internalId: string;\n callbackUrl: string;\n}\nexport interface DecodeChargeOptionsType {\n invoice: string;\n}",
"score": 0.8621190190315247
},
{
"filename": "src/types/charges.d.ts",
"retrieved_chunk": "export interface ChargeDataResponseType {\n data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;",
"score": 0.8597453832626343
},
{
"filename": "src/types/charges.ts",
"retrieved_chunk": "export interface ChargeDataResponseType {\n data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;",
"score": 0.8588330149650574
},
{
"filename": "src/types/withdrawal.ts",
"retrieved_chunk": " data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;\n confirmedAt: string;",
"score": 0.848261296749115
}
] |
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/types/withdrawal.d.ts",
"retrieved_chunk": "export interface WithdrawalRequestOptionsType {\n amount: string;\n expiresIn: number;\n description: string;\n internalId: string;\n callbackUrl: string;\n}\nexport interface GetWithdrawalRequestDataResponseType {\n data: {\n id: string;",
"score": 0.8958083391189575
},
{
"filename": "src/types/withdrawal.ts",
"retrieved_chunk": "export interface WithdrawalRequestOptionsType {\n amount: string;\n expiresIn: number;\n description: string;\n internalId: string;\n callbackUrl: string;\n}\nexport interface GetWithdrawalRequestDataResponseType {\n data: {\n id: string;",
"score": 0.8950890302658081
},
{
"filename": "src/types/withdrawal.ts",
"retrieved_chunk": " data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;\n confirmedAt: string;",
"score": 0.83957839012146
},
{
"filename": "src/types/withdrawal.d.ts",
"retrieved_chunk": " data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;\n confirmedAt: string;",
"score": 0.8334327936172485
},
{
"filename": "src/zbd.d.ts",
"retrieved_chunk": " createWithdrawalRequest(options: WithdrawalRequestOptionsType): Promise<CreateWithdrawalRequestDataResponseType>;\n getWithdrawalRequest(withdrawalRequestId: string): Promise<GetWithdrawalRequestDataResponseType>;\n validateLightningAddress(lightningAddress: string): Promise<ValidateLightningAddressDataResponseType>;\n sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType): Promise<SendLightningAddressPaymentDataResponseType>;\n createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType): Promise<FetchChargeFromLightningAddressDataResponseType>;\n getWallet(): Promise<WalletDataResponseType>;\n isSupportedRegion(ipAddress: string): Promise<SupportedRegionDataResponseType>;\n getZBDProdIps(): Promise<ProdIPSDataResponseType>;\n getBtcUsdExchangeRate(): Promise<BTCUSDDataResponseType>;\n internalTransfer(options: InternalTransferOptionsType): Promise<InternalTransferDataResponseType>;",
"score": 0.8260222673416138
}
] |
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/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": 0.8695640563964844
},
{
"filename": "src/types/static-charges.d.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": 0.8695231080055237
},
{
"filename": "src/types/static-charges.ts",
"retrieved_chunk": " data: {\n id: string;\n unit: string;\n slots: string;\n minAmount: string;\n maxAmount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;",
"score": 0.822900652885437
},
{
"filename": "src/types/charges.ts",
"retrieved_chunk": "export interface ChargeDataResponseType {\n data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;",
"score": 0.8188245892524719
},
{
"filename": "src/types/charges.d.ts",
"retrieved_chunk": "export interface ChargeDataResponseType {\n data: {\n id: string;\n unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;",
"score": 0.8186154365539551
}
] |
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/types/misc.ts",
"retrieved_chunk": " ipAddress: string;\n isSupported: boolean;\n ipCountry: string;\n ipRegion: string;\n }\n success: boolean;\n}\nexport interface ProdIPSDataResponseType {\n data: {\n ips: [string];",
"score": 0.835344672203064
},
{
"filename": "src/types/misc.d.ts",
"retrieved_chunk": " ipAddress: string;\n isSupported: boolean;\n ipCountry: string;\n ipRegion: string;\n };\n success: boolean;\n}\nexport interface ProdIPSDataResponseType {\n data: {\n ips: [string];",
"score": 0.8326830267906189
},
{
"filename": "src/types/misc.ts",
"retrieved_chunk": "export interface BTCUSDDataResponseType {\n data: {\n btcUsdPrice: string;\n btcUsdTimestamp: string;\n }\n message: string;\n success: boolean;\n}\nexport interface SupportedRegionDataResponseType {\n data: {",
"score": 0.7976251840591431
},
{
"filename": "src/types/misc.d.ts",
"retrieved_chunk": "export interface BTCUSDDataResponseType {\n data: {\n btcUsdPrice: string;\n btcUsdTimestamp: string;\n };\n message: string;\n success: boolean;\n}\nexport interface SupportedRegionDataResponseType {\n data: {",
"score": 0.7941016554832458
},
{
"filename": "src/zbd.d.ts",
"retrieved_chunk": " createWithdrawalRequest(options: WithdrawalRequestOptionsType): Promise<CreateWithdrawalRequestDataResponseType>;\n getWithdrawalRequest(withdrawalRequestId: string): Promise<GetWithdrawalRequestDataResponseType>;\n validateLightningAddress(lightningAddress: string): Promise<ValidateLightningAddressDataResponseType>;\n sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType): Promise<SendLightningAddressPaymentDataResponseType>;\n createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType): Promise<FetchChargeFromLightningAddressDataResponseType>;\n getWallet(): Promise<WalletDataResponseType>;\n isSupportedRegion(ipAddress: string): Promise<SupportedRegionDataResponseType>;\n getZBDProdIps(): Promise<ProdIPSDataResponseType>;\n getBtcUsdExchangeRate(): Promise<BTCUSDDataResponseType>;\n internalTransfer(options: InternalTransferOptionsType): Promise<InternalTransferDataResponseType>;",
"score": 0.788323700428009
}
] |
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": 0.8401659727096558
},
{
"filename": "src/types/misc.d.ts",
"retrieved_chunk": "export interface BTCUSDDataResponseType {\n data: {\n btcUsdPrice: string;\n btcUsdTimestamp: string;\n };\n message: string;\n success: boolean;\n}\nexport interface SupportedRegionDataResponseType {\n data: {",
"score": 0.830945611000061
},
{
"filename": "src/types/misc.ts",
"retrieved_chunk": "export interface BTCUSDDataResponseType {\n data: {\n btcUsdPrice: string;\n btcUsdTimestamp: string;\n }\n message: string;\n success: boolean;\n}\nexport interface SupportedRegionDataResponseType {\n data: {",
"score": 0.8304698467254639
},
{
"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": 0.8298002481460571
},
{
"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": 0.8044095635414124
}
] |
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/types/wallet.ts",
"retrieved_chunk": "export interface WalletDataResponseType {\n data: {\n balance: string;\n unit: string;\n }\n message: string;\n}",
"score": 0.8584826588630676
},
{
"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": 0.8310610055923462
},
{
"filename": "src/types/wallet.d.ts",
"retrieved_chunk": "export interface WalletDataResponseType {\n data: {\n balance: string;\n unit: string;\n };\n message: string;\n}\n//# sourceMappingURL=wallet.d.ts.map",
"score": 0.8285650610923767
},
{
"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": 0.8105623126029968
},
{
"filename": "src/zbd.d.ts",
"retrieved_chunk": " createWithdrawalRequest(options: WithdrawalRequestOptionsType): Promise<CreateWithdrawalRequestDataResponseType>;\n getWithdrawalRequest(withdrawalRequestId: string): Promise<GetWithdrawalRequestDataResponseType>;\n validateLightningAddress(lightningAddress: string): Promise<ValidateLightningAddressDataResponseType>;\n sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType): Promise<SendLightningAddressPaymentDataResponseType>;\n createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType): Promise<FetchChargeFromLightningAddressDataResponseType>;\n getWallet(): Promise<WalletDataResponseType>;\n isSupportedRegion(ipAddress: string): Promise<SupportedRegionDataResponseType>;\n getZBDProdIps(): Promise<ProdIPSDataResponseType>;\n getBtcUsdExchangeRate(): Promise<BTCUSDDataResponseType>;\n internalTransfer(options: InternalTransferOptionsType): Promise<InternalTransferDataResponseType>;",
"score": 0.807371199131012
}
] |
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": 0.8302121758460999
},
{
"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": 0.8166850805282593
},
{
"filename": "src/types/misc.ts",
"retrieved_chunk": " ipAddress: string;\n isSupported: boolean;\n ipCountry: string;\n ipRegion: string;\n }\n success: boolean;\n}\nexport interface ProdIPSDataResponseType {\n data: {\n ips: [string];",
"score": 0.8128550052642822
},
{
"filename": "src/types/misc.d.ts",
"retrieved_chunk": " ipAddress: string;\n isSupported: boolean;\n ipCountry: string;\n ipRegion: string;\n };\n success: boolean;\n}\nexport interface ProdIPSDataResponseType {\n data: {\n ips: [string];",
"score": 0.8080410957336426
},
{
"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": 0.7938091158866882
}
] |
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/types/internal-transfers.d.ts",
"retrieved_chunk": " createdAt: string;\n updatedAt: string;\n };\n message: string;\n success: boolean;\n}\nexport interface InternalTransferOptionsType {\n amount: string;\n receiverWalletId: string;\n}",
"score": 0.8734022974967957
},
{
"filename": "src/types/internal-transfers.ts",
"retrieved_chunk": " createdAt: string;\n updatedAt: string;\n }\n message: string;\n success: boolean;\n}\nexport interface InternalTransferOptionsType {\n amount: string;\n receiverWalletId: string;\n}",
"score": 0.8725401163101196
},
{
"filename": "src/types/internal-transfers.ts",
"retrieved_chunk": "export interface InternalTransferDataResponseType {\n data: {\n id: string;\n senderWalletId: string;\n receivedWalletId: string;\n userId: string;\n sendTxId: string;\n receiveTxId: string;\n status: string;\n amount: string;",
"score": 0.8563547134399414
},
{
"filename": "src/types/internal-transfers.d.ts",
"retrieved_chunk": "export interface InternalTransferDataResponseType {\n data: {\n id: string;\n senderWalletId: string;\n receivedWalletId: string;\n userId: string;\n sendTxId: string;\n receiveTxId: string;\n status: string;\n amount: string;",
"score": 0.8554624915122986
},
{
"filename": "src/zbd.d.ts",
"retrieved_chunk": " createWithdrawalRequest(options: WithdrawalRequestOptionsType): Promise<CreateWithdrawalRequestDataResponseType>;\n getWithdrawalRequest(withdrawalRequestId: string): Promise<GetWithdrawalRequestDataResponseType>;\n validateLightningAddress(lightningAddress: string): Promise<ValidateLightningAddressDataResponseType>;\n sendLightningAddressPayment(options: SendLightningAddressPaymentOptionsType): Promise<SendLightningAddressPaymentDataResponseType>;\n createChargeFromLightningAddress(options: CreateChargeFromLightningAddressOptionsType): Promise<FetchChargeFromLightningAddressDataResponseType>;\n getWallet(): Promise<WalletDataResponseType>;\n isSupportedRegion(ipAddress: string): Promise<SupportedRegionDataResponseType>;\n getZBDProdIps(): Promise<ProdIPSDataResponseType>;\n getBtcUsdExchangeRate(): Promise<BTCUSDDataResponseType>;\n internalTransfer(options: InternalTransferOptionsType): Promise<InternalTransferDataResponseType>;",
"score": 0.8386337757110596
}
] |
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/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": 0.8789870738983154
},
{
"filename": "src/sections/posts/usePostForm.ts",
"retrieved_chunk": "\t\ttry {\n\t\t\tconst postCreated = await createPost(\n\t\t\t\tpostRepository,\n\t\t\t\tuserRepository,\n\t\t\t)({ title, body, userId }).catch(() => {\n\t\t\t\tthrow new Error('Error creating post');\n\t\t\t});\n\t\t\tsetPostCreated(postCreated);\n\t\t\tsetFormStatus(FormStatus.SUCCESS);\n\t\t} catch (error) {",
"score": 0.8753867745399475
},
{
"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": 0.8731036186218262
},
{
"filename": "src/modules/posts/application/create/createPost.ts",
"retrieved_chunk": "import { UserRepository } from \"@/src/modules/users/domain/UserRepository\";\nimport { PostRepository } from \"../../domain/PostRepository\";\nimport { Post } from \"../../domain/Post\";\nimport { PostDataCreate } from \"../../domain/PostDataCreate\";\nimport { PostDataResponse } from \"../../domain/PostDataResponse\";\nexport function createPost(\n\tpostRepository: PostRepository,\n\tuserRepository: UserRepository,\n): (post: PostDataCreate) => Promise<Post> {\n\treturn async (post: PostDataCreate): Promise<Post> => {",
"score": 0.8719457387924194
},
{
"filename": "src/modules/posts/domain/PostDataCreate.ts",
"retrieved_chunk": "export interface PostDataCreate {\n\ttitle: string;\n\tbody: string;\n\tuserId: number;\n};\n// TODO: add validation function\n// ensurePostIsValid",
"score": 0.8541655540466309
}
] |
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": 0.8961909413337708
},
{
"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": 0.8844634294509888
},
{
"filename": "src/modules/posts/application/get-all/getAllPostsByUser.ts",
"retrieved_chunk": "import { Post } from '../../domain/Post';\nimport { PostRepository } from '../../domain/PostRepository';\nexport function getAllPostsByUser(\n\tpostRepository: PostRepository,\n): (userId: number) => Promise<Post[]> {\n\treturn async (userId: number): Promise<Post[]> => {\n\t\treturn await postRepository.getByUser(userId);\n\t};\n}",
"score": 0.8832187652587891
},
{
"filename": "src/modules/posts/application/get-all/getPaginatedPosts.ts",
"retrieved_chunk": "\tlimit: number,\n\tpage: number,\n): () => Promise<Post[]> {\n\treturn async (): Promise<Post[]> => {\n\t\tconst [posts, users, comments] = await Promise.all([\n\t\t\tpostRepository.getAllWithPagination(limit, page),\n\t\t\tuserRepository.getAll(),\n\t\t\tcommentRepository.getAll(),\n\t\t]);\n\t\tconst userMap = postMapper.createUserMap(users);",
"score": 0.8533508777618408
},
{
"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": 0.8504147529602051
}
] |
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/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": 0.8795574903488159
},
{
"filename": "src/modules/posts/application/create/createPost.ts",
"retrieved_chunk": "import { UserRepository } from \"@/src/modules/users/domain/UserRepository\";\nimport { PostRepository } from \"../../domain/PostRepository\";\nimport { Post } from \"../../domain/Post\";\nimport { PostDataCreate } from \"../../domain/PostDataCreate\";\nimport { PostDataResponse } from \"../../domain/PostDataResponse\";\nexport function createPost(\n\tpostRepository: PostRepository,\n\tuserRepository: UserRepository,\n): (post: PostDataCreate) => Promise<Post> {\n\treturn async (post: PostDataCreate): Promise<Post> => {",
"score": 0.8759160041809082
},
{
"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": 0.8699884414672852
},
{
"filename": "src/sections/posts/usePostForm.ts",
"retrieved_chunk": "\t\ttry {\n\t\t\tconst postCreated = await createPost(\n\t\t\t\tpostRepository,\n\t\t\t\tuserRepository,\n\t\t\t)({ title, body, userId }).catch(() => {\n\t\t\t\tthrow new Error('Error creating post');\n\t\t\t});\n\t\t\tsetPostCreated(postCreated);\n\t\t\tsetFormStatus(FormStatus.SUCCESS);\n\t\t} catch (error) {",
"score": 0.8615489602088928
},
{
"filename": "src/modules/posts/application/get-all/getAllPostsByUser.ts",
"retrieved_chunk": "import { Post } from '../../domain/Post';\nimport { PostRepository } from '../../domain/PostRepository';\nexport function getAllPostsByUser(\n\tpostRepository: PostRepository,\n): (userId: number) => Promise<Post[]> {\n\treturn async (userId: number): Promise<Post[]> => {\n\t\treturn await postRepository.getByUser(userId);\n\t};\n}",
"score": 0.8488459587097168
}
] |
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/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": 0.873225212097168
},
{
"filename": "src/modules/posts/application/create/createPost.ts",
"retrieved_chunk": "import { UserRepository } from \"@/src/modules/users/domain/UserRepository\";\nimport { PostRepository } from \"../../domain/PostRepository\";\nimport { Post } from \"../../domain/Post\";\nimport { PostDataCreate } from \"../../domain/PostDataCreate\";\nimport { PostDataResponse } from \"../../domain/PostDataResponse\";\nexport function createPost(\n\tpostRepository: PostRepository,\n\tuserRepository: UserRepository,\n): (post: PostDataCreate) => Promise<Post> {\n\treturn async (post: PostDataCreate): Promise<Post> => {",
"score": 0.8713515400886536
},
{
"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": 0.8621468544006348
},
{
"filename": "src/sections/posts/usePostForm.ts",
"retrieved_chunk": "\t\ttry {\n\t\t\tconst postCreated = await createPost(\n\t\t\t\tpostRepository,\n\t\t\t\tuserRepository,\n\t\t\t)({ title, body, userId }).catch(() => {\n\t\t\t\tthrow new Error('Error creating post');\n\t\t\t});\n\t\t\tsetPostCreated(postCreated);\n\t\t\tsetFormStatus(FormStatus.SUCCESS);\n\t\t} catch (error) {",
"score": 0.8603619337081909
},
{
"filename": "src/modules/posts/application/get-all/getAllPostsByUser.ts",
"retrieved_chunk": "import { Post } from '../../domain/Post';\nimport { PostRepository } from '../../domain/PostRepository';\nexport function getAllPostsByUser(\n\tpostRepository: PostRepository,\n): (userId: number) => Promise<Post[]> {\n\treturn async (userId: number): Promise<Post[]> => {\n\t\treturn await postRepository.getByUser(userId);\n\t};\n}",
"score": 0.8561452627182007
}
] |
typescript
|
async function create(post: PostDataCreate): Promise<PostDataResponse> {
|
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/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": 0.8308141231536865
},
{
"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": 0.8198529481887817
},
{
"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": 0.8179047107696533
},
{
"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": 0.8167083263397217
},
{
"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": 0.806069016456604
}
] |
typescript
|
: AssetPath['absolute'], content: Asset['content']) {
|
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/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": 0.8826791048049927
},
{
"filename": "src/sections/posts/usePostForm.ts",
"retrieved_chunk": "\t\ttry {\n\t\t\tconst postCreated = await createPost(\n\t\t\t\tpostRepository,\n\t\t\t\tuserRepository,\n\t\t\t)({ title, body, userId }).catch(() => {\n\t\t\t\tthrow new Error('Error creating post');\n\t\t\t});\n\t\t\tsetPostCreated(postCreated);\n\t\t\tsetFormStatus(FormStatus.SUCCESS);\n\t\t} catch (error) {",
"score": 0.8753372430801392
},
{
"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": 0.8750781416893005
},
{
"filename": "src/modules/posts/application/create/createPost.ts",
"retrieved_chunk": "import { UserRepository } from \"@/src/modules/users/domain/UserRepository\";\nimport { PostRepository } from \"../../domain/PostRepository\";\nimport { Post } from \"../../domain/Post\";\nimport { PostDataCreate } from \"../../domain/PostDataCreate\";\nimport { PostDataResponse } from \"../../domain/PostDataResponse\";\nexport function createPost(\n\tpostRepository: PostRepository,\n\tuserRepository: UserRepository,\n): (post: PostDataCreate) => Promise<Post> {\n\treturn async (post: PostDataCreate): Promise<Post> => {",
"score": 0.8734561204910278
},
{
"filename": "src/modules/posts/domain/PostDataCreate.ts",
"retrieved_chunk": "export interface PostDataCreate {\n\ttitle: string;\n\tbody: string;\n\tuserId: number;\n};\n// TODO: add validation function\n// ensurePostIsValid",
"score": 0.8565305471420288
}
] |
typescript
|
userId } = post;
|
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": 0.8642771244049072
},
{
"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": 0.8448962569236755
},
{
"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": 0.8436519503593445
},
{
"filename": "src/Compilation.ts",
"retrieved_chunk": " errors: string[];\n};\nexport type CompilationHooks = {\n beforeAddAsset: SyncHook<[Asset]>;\n afterAddAsset: SyncHook<[Asset]>;\n};\nexport class Compilation {\n compiler: Compiler;\n event: CompilerEvent;\n assetPaths: Set<string>;",
"score": 0.8221608400344849
},
{
"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": 0.8150654435157776
}
] |
typescript
|
source: AssetPath, links: Set<Asset>, action: CompilerEvent) {
|
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/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": 0.8746136426925659
},
{
"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": 0.8741213083267212
},
{
"filename": "src/sections/posts/usePostForm.ts",
"retrieved_chunk": "\t\ttry {\n\t\t\tconst postCreated = await createPost(\n\t\t\t\tpostRepository,\n\t\t\t\tuserRepository,\n\t\t\t)({ title, body, userId }).catch(() => {\n\t\t\t\tthrow new Error('Error creating post');\n\t\t\t});\n\t\t\tsetPostCreated(postCreated);\n\t\t\tsetFormStatus(FormStatus.SUCCESS);\n\t\t} catch (error) {",
"score": 0.8709589242935181
},
{
"filename": "src/modules/posts/application/create/createPost.ts",
"retrieved_chunk": "import { UserRepository } from \"@/src/modules/users/domain/UserRepository\";\nimport { PostRepository } from \"../../domain/PostRepository\";\nimport { Post } from \"../../domain/Post\";\nimport { PostDataCreate } from \"../../domain/PostDataCreate\";\nimport { PostDataResponse } from \"../../domain/PostDataResponse\";\nexport function createPost(\n\tpostRepository: PostRepository,\n\tuserRepository: UserRepository,\n): (post: PostDataCreate) => Promise<Post> {\n\treturn async (post: PostDataCreate): Promise<Post> => {",
"score": 0.867601752281189
},
{
"filename": "src/modules/posts/application/get/getPostById.ts",
"retrieved_chunk": "\t\tconst post = await postRepository.get(postId);\n\t\tif (!post) {\n\t\t\tthrow new Error(`Post with id ${postId} not found`);\n\t\t}\n\t\tconst [author, comments] = await Promise.all([\n\t\t\tuserRepository.get(post.userId),\n\t\t\tcommentRepository.getAllByPost(postId),\n\t\t]);\n\t\tconst postWithAuthorAndCommentCount = {\n\t\t\t...post,",
"score": 0.8524755835533142
}
] |
typescript
|
{ title, body, userId } = post;
|
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": " errors: string[];\n};\nexport type CompilationHooks = {\n beforeAddAsset: SyncHook<[Asset]>;\n afterAddAsset: SyncHook<[Asset]>;\n};\nexport class Compilation {\n compiler: Compiler;\n event: CompilerEvent;\n assetPaths: Set<string>;",
"score": 0.858625054359436
},
{
"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": 0.8536813855171204
},
{
"filename": "src/Compilation.ts",
"retrieved_chunk": " * A list of asset objects.\n */\n assets: Asset[];\n /**\n * A list of warnings.\n */\n warnings: string[];\n /**\n * A list of errors.\n */",
"score": 0.8443185687065125
},
{
"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": 0.839267373085022
},
{
"filename": "src/plugins/PathsPlugin.ts",
"retrieved_chunk": "import * as path from 'path';\nimport { Asset, AssetPath, AssetType } from '../Asset';\nimport { Compiler } from '../Compiler';\nimport { Emitter } from '../Emitter';\nimport { Plugin } from '../Plugin';\ntype Paths = {\n /**\n * An array of paths pointing to files that should be processed as `assets`.\n */\n assets?: RegExp[];",
"score": 0.8342169523239136
}
] |
typescript
|
action: CompilerEvent;
|
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": "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": 0.8172020316123962
},
{
"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": 0.8150030970573425
},
{
"filename": "src/memory.ts",
"retrieved_chunk": " memory.setValue(key, title);\n});\n/**\n * Save page screenshot into memory\n * @param {string} key - key to store value\n * @example I save screenshot as 'screenshot'\n */\nWhen('I save screenshot as {string}', async function(key: string) {\n const screenshot = await t.takeScreenshot();\n memory.setValue(key, screenshot);",
"score": 0.8022952675819397
},
{
"filename": "src/waits.ts",
"retrieved_chunk": "When(\n 'I wait until {string} attribute of {string} {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (attribute: string, alias: string, waitType: string, value: string, timeout: number | null) {\n const attributeName = await getValue(attribute);\n const wait = getValueWait(waitType);\n const element = await getElement(alias);\n const expectedValue = await getValue(value);\n const getValueFn = element.with({ boundTestRun: t }).getAttribute(attributeName);\n await wait(getValueFn, expectedValue, timeout ? timeout : config.browser.timeout.page);\n }",
"score": 0.7963314652442932
},
{
"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": 0.7946947813034058
}
] |
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/types/payments.ts",
"retrieved_chunk": " invoice: string;\n callbackUrl: string;\n amount: string;\n}",
"score": 0.8502215147018433
},
{
"filename": "src/types/withdrawal.d.ts",
"retrieved_chunk": " unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;\n confirmedAt: string;\n status: string;\n invoice: {",
"score": 0.8415011763572693
},
{
"filename": "src/types/withdrawal.ts",
"retrieved_chunk": " unit: string;\n amount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;\n expiresAt: string;\n confirmedAt: string;\n status: string;\n invoice: {",
"score": 0.8398206830024719
},
{
"filename": "src/types/payments.d.ts",
"retrieved_chunk": " confirmedAt: string;\n description: string;\n status: string;\n };\n success: boolean;\n message: string;\n}\nexport interface SendPaymentOptionsType {\n description: string;\n internalId: string;",
"score": 0.8378860950469971
},
{
"filename": "src/types/lightning.d.ts",
"retrieved_chunk": " };\n success: boolean;\n message: string;\n}\nexport interface SendLightningAddressPaymentOptionsType {\n lnAddress: string;\n amount: string;\n comment: string;\n callbackUrl: string;\n internalId: string;",
"score": 0.8362104296684265
}
] |
typescript
|
url: `${API_URL}${API.PAYMENTS_ENDPOINT}`,
headers: { ...this.apiCoreHeaders },
body: {
|
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/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": 0.8095727562904358
},
{
"filename": "src/plugins/PathsPlugin.ts",
"retrieved_chunk": " ...defaultPathsPluginConfig.paths,\n ...config.paths,\n },\n }\n : {};\n }\n apply(compiler: Compiler): void {\n const output = compiler.config.output;\n if (!output) return;\n const paths = this.config.paths;",
"score": 0.7934466004371643
},
{
"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": 0.7887470126152039
},
{
"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": 0.7821105718612671
},
{
"filename": "src/config/defaults.ts",
"retrieved_chunk": "import { CompilerConfig, MelterConfig, defaultBaseCompilerConfig } from '.';\nimport { Plugin } from '../Plugin';\nimport { PathsPlugin } from '../plugins/PathsPlugin';\nimport { StatsPlugin } from '../plugins/StatsPlugin';\nfunction applyDefaultPlugins(config: CompilerConfig): Plugin[] {\n const plugins = [];\n plugins.push(\n ...[\n new StatsPlugin({\n stats: config.stats,",
"score": 0.7772347331047058
}
] |
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": "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": 0.8810939788818359
},
{
"filename": "src/memory.ts",
"retrieved_chunk": " memory.setValue(key, title);\n});\n/**\n * Save page screenshot into memory\n * @param {string} key - key to store value\n * @example I save screenshot as 'screenshot'\n */\nWhen('I save screenshot as {string}', async function(key: string) {\n const screenshot = await t.takeScreenshot();\n memory.setValue(key, screenshot);",
"score": 0.8284749388694763
},
{
"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": 0.8210939168930054
},
{
"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": 0.8198709487915039
},
{
"filename": "src/utils/screenshotEvent.ts",
"retrieved_chunk": "export enum ScreenshotEvent {\n ON_FAIL = 'onFail',\n BEFORE_STEP = 'beforeStep',\n AFTER_STEP = 'afterStep'\n}",
"score": 0.8037714958190918
}
] |
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/execute.ts",
"retrieved_chunk": " * @param {string} functionKey - memory key of function\n * @param {string} alias - alias of target element\n * @example I execute '$fn' function on 'Component > Element' // fn is function reference\n * @example I execute 'target.scrollIntoView()' function on 'Component > Element'\n */\nWhen('I execute {string} function on {string}', async function (functionKey, alias) {\n const fnDef = await getValue(functionKey);\n const element = await getElement(alias);\n const clientFunction = ClientFunction(resolveFunction(fnDef), {\n dependencies: { target: element }",
"score": 0.7996909618377686
},
{
"filename": "src/waits.ts",
"retrieved_chunk": ");\n/**\n * Wait\n * @param {number} ms - milliseconds\n * @example I wait 1000 ms\n */\nWhen('I wait {int} ms', async function (ms) {\n await new Promise((resolve: Function): void => {\n setTimeout(() => resolve(), ms)\n });",
"score": 0.798100471496582
},
{
"filename": "src/waits.ts",
"retrieved_chunk": " */\nWhen(\n 'I wait until text of {string} {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (alias: string, waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const element = await getElement(alias);\n const expectedValue = await getValue(value);\n await wait(\n element.with({ boundTestRun: t }).innerText,\n expectedValue,",
"score": 0.7936716079711914
},
{
"filename": "src/waits.ts",
"retrieved_chunk": "When(\n 'I wait until {string} attribute of {string} {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (attribute: string, alias: string, waitType: string, value: string, timeout: number | null) {\n const attributeName = await getValue(attribute);\n const wait = getValueWait(waitType);\n const element = await getElement(alias);\n const expectedValue = await getValue(value);\n const getValueFn = element.with({ boundTestRun: t }).getAttribute(attributeName);\n await wait(getValueFn, expectedValue, timeout ? timeout : config.browser.timeout.page);\n }",
"score": 0.7904810905456543
},
{
"filename": "src/waits.ts",
"retrieved_chunk": " * @example I wait until number of elements in 'Search Results' collection to be equal '50'\n * @example I wait until number of elements in 'Search Results' collection to be above '49'\n * @example I wait until number of elements in 'Search Results' collection to be below '51'\n * @example I wait until number of elements in 'Search Results' collection to be below '51' (timeout: 3000)\n */\nWhen(\n 'I wait until number of elements in {string} collection {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (alias: string, waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const collection = await getElement(alias);",
"score": 0.7822626233100891
}
] |
typescript
|
= parseCoords(await getValue(offset));
|
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": "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": 0.8800441026687622
},
{
"filename": "src/memory.ts",
"retrieved_chunk": " memory.setValue(key, title);\n});\n/**\n * Save page screenshot into memory\n * @param {string} key - key to store value\n * @example I save screenshot as 'screenshot'\n */\nWhen('I save screenshot as {string}', async function(key: string) {\n const screenshot = await t.takeScreenshot();\n memory.setValue(key, screenshot);",
"score": 0.8300390839576721
},
{
"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": 0.8223098516464233
},
{
"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": 0.8214543461799622
},
{
"filename": "src/utils/screenshotEvent.ts",
"retrieved_chunk": "export enum ScreenshotEvent {\n ON_FAIL = 'onFail',\n BEFORE_STEP = 'beforeStep',\n AFTER_STEP = 'afterStep'\n}",
"score": 0.8066298961639404
}
] |
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": " * @param {string} validationType - validation\n * @param {string} value - expected result\n * @example I expect text of '#1 of Search Results' equals to 'google'\n * @example I expect text of '#2 of Search Results' does not contain 'yandex'\n */\nThen(\n 'I expect text of {string} {testcafeValidation} {string}',\n async function (alias: string, validationType: string, value: any) {\n const expectedValue = await getValue(value);\n const element = await getElement(alias);",
"score": 0.898330807685852
},
{
"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": 0.8762848377227783
},
{
"filename": "src/actions.ts",
"retrieved_chunk": " const urlValue = await getValue(url);\n await t.navigateTo(urlValue);\n});\n/**\n * Type text to element\n * @param {string} alias - element to type\n * @param {string} value - value to type\n * @example I type 'wikipedia' to 'Google Input'\n */\nWhen('I type {string} to {string}', async function (value: string, alias: string) {",
"score": 0.8634642362594604
},
{
"filename": "src/validations.ts",
"retrieved_chunk": " * @example I expect 'color' css property of 'Search Input' to be equal 'rgb(42, 42, 42)'\n * @example I expect 'font-family' css property of 'Label' to contain 'Fira'\n */\nThen(\n 'I expect {string} css property of {string} {testcafeValidation} {string}',\n async function (property: string, alias: string, validationType: string, value: string) {\n const propertyName = await getValue(property);\n const expectedValue = await getValue(value);\n const element = await getElement(alias);\n const validation = getValidation(validationType);",
"score": 0.8568715453147888
},
{
"filename": "src/validations.ts",
"retrieved_chunk": " async function (alias: string, validationType: string, value: string) {\n const expectedValue = await getValue(value);\n const collection = await getElement(alias);\n const validation = getValidation(validationType);\n const count = await collection.with({ boundTestRun: t }).count;\n for (let i = 0; i < count; i++) {\n const text = await collection.nth(i).with({ boundTestRun: t }).innerText;\n validation(text, expectedValue);\n }\n }",
"score": 0.85237056016922
}
] |
typescript
|
const wait = getValueWait(waitType);
|
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/types/keysend.ts",
"retrieved_chunk": " amount: string;\n pubkey: string;\n tlvRecords: string;\n metadata: string;\n callbackUrl: string;\n}",
"score": 0.8433067202568054
},
{
"filename": "src/zbd.d.ts",
"retrieved_chunk": " sendKeysendPayment(options: KeysendOptionsType): Promise<KeysendDataResponseType>;\n sendPayment(options: SendPaymentOptionsType): Promise<InvoicePaymentDataResponseType>;\n getPayment(paymentId: string): Promise<any>;\n sendGamertagPayment(options: SendGamertagPaymentOptionsType): Promise<SendGamertagPaymentDataResponseType>;\n getGamertagTransaction(transactionId: string): Promise<GamertagTransactionDataResponseType>;\n getUserIdByGamertag(gamertag: string): Promise<FetchUserIdByGamertagDataResponseType>;\n getGamertagByUserId(userId: string): Promise<FetchGamertagByUserIdDataResponseType>;\n createGamertagCharge(options: FetchChargeFromGamertagOptionsType): Promise<FetchChargeFromGamertagDataResponseType>;\n createStaticCharge(options: StaticChargeOptionsType): Promise<StaticChargeDataResponseType>;\n updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType): Promise<any>;",
"score": 0.8314336538314819
},
{
"filename": "src/types/keysend.d.ts",
"retrieved_chunk": "export interface KeysendDataResponseType {\n data: {\n keysendId: string;\n paymentId: string;\n transaction: {\n id: string;\n walletId: string;\n type: string;\n totalAmount: string;\n fee: string;",
"score": 0.8295935988426208
},
{
"filename": "src/types/keysend.ts",
"retrieved_chunk": "export interface KeysendDataResponseType {\n data: {\n keysendId: string;\n paymentId: string;\n transaction: {\n id: string;\n walletId: string;\n type: string;\n totalAmount: string;\n fee: string;",
"score": 0.829477846622467
},
{
"filename": "src/types/keysend.ts",
"retrieved_chunk": " amount: string;\n description: string;\n status: string;\n confirmedAt: string;\n }\n }\n message: string;\n success: boolean;\n}\nexport interface KeysendOptionsType {",
"score": 0.8277188539505005
}
] |
typescript
|
}${API.KEYSEND_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/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": 0.8977251648902893
},
{
"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": 0.8752712607383728
},
{
"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": 0.8678826093673706
},
{
"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": 0.8649328947067261
},
{
"filename": "src/Compiler.ts",
"retrieved_chunk": " config: Readonly<CompilerConfig>;\n hooks: Readonly<CompilerHooks>;\n watcher: Readonly<Watcher | null>;\n logger: Readonly<Logger>;\n constructor(config: CompilerConfig) {\n this.cwd = process.cwd();\n this.config = config;\n this.hooks = Object.freeze<CompilerHooks>({\n beforeCompile: new SyncHook(),\n compilation: new SyncHook(['compilation']),",
"score": 0.8420511484146118
}
] |
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": 0.8885973691940308
},
{
"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": 0.8481860756874084
},
{
"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": 0.8465162515640259
},
{
"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": 0.8416704535484314
},
{
"filename": "src/plugins/PathsPlugin.ts",
"retrieved_chunk": "import * as path from 'path';\nimport { Asset, AssetPath, AssetType } from '../Asset';\nimport { Compiler } from '../Compiler';\nimport { Emitter } from '../Emitter';\nimport { Plugin } from '../Plugin';\ntype Paths = {\n /**\n * An array of paths pointing to files that should be processed as `assets`.\n */\n assets?: RegExp[];",
"score": 0.8337106704711914
}
] |
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/execute.ts",
"retrieved_chunk": " * @param {string} functionKey - memory key of function\n * @param {string} alias - alias of target element\n * @example I execute '$fn' function on 'Component > Element' // fn is function reference\n * @example I execute 'target.scrollIntoView()' function on 'Component > Element'\n */\nWhen('I execute {string} function on {string}', async function (functionKey, alias) {\n const fnDef = await getValue(functionKey);\n const element = await getElement(alias);\n const clientFunction = ClientFunction(resolveFunction(fnDef), {\n dependencies: { target: element }",
"score": 0.8008131980895996
},
{
"filename": "src/waits.ts",
"retrieved_chunk": ");\n/**\n * Wait\n * @param {number} ms - milliseconds\n * @example I wait 1000 ms\n */\nWhen('I wait {int} ms', async function (ms) {\n await new Promise((resolve: Function): void => {\n setTimeout(() => resolve(), ms)\n });",
"score": 0.7996764779090881
},
{
"filename": "src/waits.ts",
"retrieved_chunk": " */\nWhen(\n 'I wait until text of {string} {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (alias: string, waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const element = await getElement(alias);\n const expectedValue = await getValue(value);\n await wait(\n element.with({ boundTestRun: t }).innerText,\n expectedValue,",
"score": 0.7945852279663086
},
{
"filename": "src/waits.ts",
"retrieved_chunk": "When(\n 'I wait until {string} attribute of {string} {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (attribute: string, alias: string, waitType: string, value: string, timeout: number | null) {\n const attributeName = await getValue(attribute);\n const wait = getValueWait(waitType);\n const element = await getElement(alias);\n const expectedValue = await getValue(value);\n const getValueFn = element.with({ boundTestRun: t }).getAttribute(attributeName);\n await wait(getValueFn, expectedValue, timeout ? timeout : config.browser.timeout.page);\n }",
"score": 0.7917205095291138
},
{
"filename": "src/waits.ts",
"retrieved_chunk": " * @example I wait until number of elements in 'Search Results' collection to be equal '50'\n * @example I wait until number of elements in 'Search Results' collection to be above '49'\n * @example I wait until number of elements in 'Search Results' collection to be below '51'\n * @example I wait until number of elements in 'Search Results' collection to be below '51' (timeout: 3000)\n */\nWhen(\n 'I wait until number of elements in {string} collection {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (alias: string, waitType: string, value: string, timeout: number | null) {\n const wait = getValueWait(waitType);\n const collection = await getElement(alias);",
"score": 0.7853702306747437
}
] |
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": 0.8706023097038269
},
{
"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": 0.8610415458679199
},
{
"filename": "src/config/index.ts",
"retrieved_chunk": "import { Plugin } from '../Plugin';\nimport { PathsPluginConfig } from '../plugins/PathsPlugin';\nimport { StatsPluginConfig } from '../plugins/StatsPlugin';\nexport * from './load';\nexport type BaseCompilerConfig = {\n /**\n * Where to look for files to compile.\n */\n input: string;\n /**",
"score": 0.8537003993988037
},
{
"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": 0.8495818376541138
},
{
"filename": "src/config/defaults.ts",
"retrieved_chunk": "import { CompilerConfig, MelterConfig, defaultBaseCompilerConfig } from '.';\nimport { Plugin } from '../Plugin';\nimport { PathsPlugin } from '../plugins/PathsPlugin';\nimport { StatsPlugin } from '../plugins/StatsPlugin';\nfunction applyDefaultPlugins(config: CompilerConfig): Plugin[] {\n const plugins = [];\n plugins.push(\n ...[\n new StatsPlugin({\n stats: config.stats,",
"score": 0.8477516770362854
}
] |
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": "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": 0.8187976479530334
},
{
"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": 0.8154467344284058
},
{
"filename": "src/memory.ts",
"retrieved_chunk": " memory.setValue(key, title);\n});\n/**\n * Save page screenshot into memory\n * @param {string} key - key to store value\n * @example I save screenshot as 'screenshot'\n */\nWhen('I save screenshot as {string}', async function(key: string) {\n const screenshot = await t.takeScreenshot();\n memory.setValue(key, screenshot);",
"score": 0.7996997833251953
},
{
"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": 0.79579097032547
},
{
"filename": "src/waits.ts",
"retrieved_chunk": "When(\n 'I wait until {string} attribute of {string} {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (attribute: string, alias: string, waitType: string, value: string, timeout: number | null) {\n const attributeName = await getValue(attribute);\n const wait = getValueWait(waitType);\n const element = await getElement(alias);\n const expectedValue = await getValue(value);\n const getValueFn = element.with({ boundTestRun: t }).getAttribute(attributeName);\n await wait(getValueFn, expectedValue, timeout ? timeout : config.browser.timeout.page);\n }",
"score": 0.7912003993988037
}
] |
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": 0.8979511260986328
},
{
"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": 0.8814095258712769
},
{
"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": 0.8633450269699097
},
{
"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": 0.8614239692687988
},
{
"filename": "src/Compiler.ts",
"retrieved_chunk": " config: Readonly<CompilerConfig>;\n hooks: Readonly<CompilerHooks>;\n watcher: Readonly<Watcher | null>;\n logger: Readonly<Logger>;\n constructor(config: CompilerConfig) {\n this.cwd = process.cwd();\n this.config = config;\n this.hooks = Object.freeze<CompilerHooks>({\n beforeCompile: new SyncHook(),\n compilation: new SyncHook(['compilation']),",
"score": 0.8478865623474121
}
] |
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": "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": 0.8174264430999756
},
{
"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": 0.8157336115837097
},
{
"filename": "src/memory.ts",
"retrieved_chunk": " memory.setValue(key, title);\n});\n/**\n * Save page screenshot into memory\n * @param {string} key - key to store value\n * @example I save screenshot as 'screenshot'\n */\nWhen('I save screenshot as {string}', async function(key: string) {\n const screenshot = await t.takeScreenshot();\n memory.setValue(key, screenshot);",
"score": 0.803544819355011
},
{
"filename": "src/waits.ts",
"retrieved_chunk": "When(\n 'I wait until {string} attribute of {string} {testcafeValueWait} {string}( ){testcafeTimeout}',\n async function (attribute: string, alias: string, waitType: string, value: string, timeout: number | null) {\n const attributeName = await getValue(attribute);\n const wait = getValueWait(waitType);\n const element = await getElement(alias);\n const expectedValue = await getValue(value);\n const getValueFn = element.with({ boundTestRun: t }).getAttribute(attributeName);\n await wait(getValueFn, expectedValue, timeout ? timeout : config.browser.timeout.page);\n }",
"score": 0.7967191338539124
},
{
"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": 0.7962450385093689
}
] |
typescript
|
await takeScreenshot(), 'image/png');
|
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/Asset.ts",
"retrieved_chunk": "import * as fs from 'fs-extra';\nimport { CompilerEvent } from './Compiler';\nexport type AssetType =\n | 'assets'\n | 'config'\n | 'layout'\n | 'locales'\n | 'sections'\n | 'snippets'\n | 'templates';",
"score": 0.8302826285362244
},
{
"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": 0.8214418292045593
},
{
"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": 0.8209372758865356
},
{
"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": 0.8139350414276123
},
{
"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": 0.8117903470993042
}
] |
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/types/gamertag.ts",
"retrieved_chunk": " gamertag: string;\n }\n}\nexport interface GamertagTransactionDataResponseType {\n data: {\n id: string;\n receivedId: string;\n amount: string;\n fee: string;\n unit: string;",
"score": 0.8589436411857605
},
{
"filename": "src/types/gamertag.d.ts",
"retrieved_chunk": " gamertag: string;\n };\n}\nexport interface GamertagTransactionDataResponseType {\n data: {\n id: string;\n receivedId: string;\n amount: string;\n fee: string;\n unit: string;",
"score": 0.8585554361343384
},
{
"filename": "src/zbd.d.ts",
"retrieved_chunk": " sendKeysendPayment(options: KeysendOptionsType): Promise<KeysendDataResponseType>;\n sendPayment(options: SendPaymentOptionsType): Promise<InvoicePaymentDataResponseType>;\n getPayment(paymentId: string): Promise<any>;\n sendGamertagPayment(options: SendGamertagPaymentOptionsType): Promise<SendGamertagPaymentDataResponseType>;\n getGamertagTransaction(transactionId: string): Promise<GamertagTransactionDataResponseType>;\n getUserIdByGamertag(gamertag: string): Promise<FetchUserIdByGamertagDataResponseType>;\n getGamertagByUserId(userId: string): Promise<FetchGamertagByUserIdDataResponseType>;\n createGamertagCharge(options: FetchChargeFromGamertagOptionsType): Promise<FetchChargeFromGamertagDataResponseType>;\n createStaticCharge(options: StaticChargeOptionsType): Promise<StaticChargeDataResponseType>;\n updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType): Promise<any>;",
"score": 0.8439436554908752
},
{
"filename": "src/types/gamertag.ts",
"retrieved_chunk": " receiverId: string;\n transactionId: string;\n amount: string;\n comment: string;\n }\n success: boolean;\n message: string;\n}\nexport interface SendGamertagPaymentOptionsType {\n gamertag: string;",
"score": 0.8380985856056213
},
{
"filename": "src/types/gamertag.d.ts",
"retrieved_chunk": " receiverId: string;\n transactionId: string;\n amount: string;\n comment: string;\n };\n success: boolean;\n message: string;\n}\nexport interface SendGamertagPaymentOptionsType {\n gamertag: string;",
"score": 0.8359964489936829
}
] |
typescript
|
url: `${API_URL}${API.GET_GAMERTAG_PAYMENT_ENDPOINT}/${transactionId}`,
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/types/gamertag.d.ts",
"retrieved_chunk": "export interface FetchUserIdByGamertagDataResponseType {\n success: boolean;\n data: {\n id: string;\n };\n}\nexport interface FetchGamertagByUserIdDataResponseType {\n success: boolean;\n message: string;\n data: {",
"score": 0.8628455996513367
},
{
"filename": "src/types/gamertag.ts",
"retrieved_chunk": "export interface FetchUserIdByGamertagDataResponseType {\n success: boolean;\n data: {\n id: string;\n }\n}\nexport interface FetchGamertagByUserIdDataResponseType {\n success: boolean;\n message: string;\n data: {",
"score": 0.8626646995544434
},
{
"filename": "src/zbd.d.ts",
"retrieved_chunk": " sendKeysendPayment(options: KeysendOptionsType): Promise<KeysendDataResponseType>;\n sendPayment(options: SendPaymentOptionsType): Promise<InvoicePaymentDataResponseType>;\n getPayment(paymentId: string): Promise<any>;\n sendGamertagPayment(options: SendGamertagPaymentOptionsType): Promise<SendGamertagPaymentDataResponseType>;\n getGamertagTransaction(transactionId: string): Promise<GamertagTransactionDataResponseType>;\n getUserIdByGamertag(gamertag: string): Promise<FetchUserIdByGamertagDataResponseType>;\n getGamertagByUserId(userId: string): Promise<FetchGamertagByUserIdDataResponseType>;\n createGamertagCharge(options: FetchChargeFromGamertagOptionsType): Promise<FetchChargeFromGamertagDataResponseType>;\n createStaticCharge(options: StaticChargeOptionsType): Promise<StaticChargeDataResponseType>;\n updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType): Promise<any>;",
"score": 0.8473515510559082
},
{
"filename": "src/types/gamertag.d.ts",
"retrieved_chunk": " gamertag: string;\n };\n}\nexport interface GamertagTransactionDataResponseType {\n data: {\n id: string;\n receivedId: string;\n amount: string;\n fee: string;\n unit: string;",
"score": 0.8309299349784851
},
{
"filename": "src/types/gamertag.ts",
"retrieved_chunk": " gamertag: string;\n }\n}\nexport interface GamertagTransactionDataResponseType {\n data: {\n id: string;\n receivedId: string;\n amount: string;\n fee: string;\n unit: string;",
"score": 0.829695999622345
}
] |
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/types/gamertag.d.ts",
"retrieved_chunk": "export interface FetchUserIdByGamertagDataResponseType {\n success: boolean;\n data: {\n id: string;\n };\n}\nexport interface FetchGamertagByUserIdDataResponseType {\n success: boolean;\n message: string;\n data: {",
"score": 0.8781188726425171
},
{
"filename": "src/types/gamertag.ts",
"retrieved_chunk": "export interface FetchUserIdByGamertagDataResponseType {\n success: boolean;\n data: {\n id: string;\n }\n}\nexport interface FetchGamertagByUserIdDataResponseType {\n success: boolean;\n message: string;\n data: {",
"score": 0.8778970241546631
},
{
"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": 0.8197054862976074
},
{
"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": 0.8181250095367432
},
{
"filename": "src/zbd.d.ts",
"retrieved_chunk": " sendKeysendPayment(options: KeysendOptionsType): Promise<KeysendDataResponseType>;\n sendPayment(options: SendPaymentOptionsType): Promise<InvoicePaymentDataResponseType>;\n getPayment(paymentId: string): Promise<any>;\n sendGamertagPayment(options: SendGamertagPaymentOptionsType): Promise<SendGamertagPaymentDataResponseType>;\n getGamertagTransaction(transactionId: string): Promise<GamertagTransactionDataResponseType>;\n getUserIdByGamertag(gamertag: string): Promise<FetchUserIdByGamertagDataResponseType>;\n getGamertagByUserId(userId: string): Promise<FetchGamertagByUserIdDataResponseType>;\n createGamertagCharge(options: FetchChargeFromGamertagOptionsType): Promise<FetchChargeFromGamertagDataResponseType>;\n createStaticCharge(options: StaticChargeOptionsType): Promise<StaticChargeDataResponseType>;\n updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType): Promise<any>;",
"score": 0.7950966358184814
}
] |
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/types/static-charges.d.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": 0.8851335048675537
},
{
"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": 0.8841007947921753
},
{
"filename": "src/types/static-charges.ts",
"retrieved_chunk": " data: {\n id: string;\n unit: string;\n slots: string;\n minAmount: string;\n maxAmount: string;\n createdAt: string;\n callbackUrl: string;\n internalId: string;\n description: string;",
"score": 0.8204839825630188
},
{
"filename": "src/types/gamertag.d.ts",
"retrieved_chunk": " callbackUrl: string;\n description: string;\n invoiceRequest: string;\n invoiceExpiresAt: string;\n invoiceDescriptionHash: string | null;\n };\n success: boolean;\n}\nexport interface FetchChargeFromGamertagOptionsType {\n amount: string;",
"score": 0.819696307182312
},
{
"filename": "src/types/gamertag.ts",
"retrieved_chunk": " callbackUrl: string;\n description: string;\n invoiceRequest: string;\n invoiceExpiresAt: string;\n invoiceDescriptionHash: string | null;\n }\n success: boolean;\n}\nexport interface FetchChargeFromGamertagOptionsType {\n amount: string;",
"score": 0.818960428237915
}
] |
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/types/gamertag.d.ts",
"retrieved_chunk": " callbackUrl: string;\n description: string;\n invoiceRequest: string;\n invoiceExpiresAt: string;\n invoiceDescriptionHash: string | null;\n };\n success: boolean;\n}\nexport interface FetchChargeFromGamertagOptionsType {\n amount: string;",
"score": 0.8743494749069214
},
{
"filename": "src/types/gamertag.ts",
"retrieved_chunk": " callbackUrl: string;\n description: string;\n invoiceRequest: string;\n invoiceExpiresAt: string;\n invoiceDescriptionHash: string | null;\n }\n success: boolean;\n}\nexport interface FetchChargeFromGamertagOptionsType {\n amount: string;",
"score": 0.8732484579086304
},
{
"filename": "src/types/gamertag.ts",
"retrieved_chunk": " amount: string;\n description: string;\n}\nexport interface FetchChargeFromGamertagDataResponseType {\n data: {\n unit: string;\n status: string;\n amount: string;\n createdAt: string;\n internalId: string;",
"score": 0.8633558750152588
},
{
"filename": "src/types/gamertag.d.ts",
"retrieved_chunk": " amount: string;\n description: string;\n}\nexport interface FetchChargeFromGamertagDataResponseType {\n data: {\n unit: string;\n status: string;\n amount: string;\n createdAt: string;\n internalId: string;",
"score": 0.8615149855613708
},
{
"filename": "src/types/gamertag.d.ts",
"retrieved_chunk": " receiverId: string;\n transactionId: string;\n amount: string;\n comment: string;\n };\n success: boolean;\n message: string;\n}\nexport interface SendGamertagPaymentOptionsType {\n gamertag: string;",
"score": 0.8366686701774597
}
] |
typescript
|
url: `${API_URL}${API.CREATE_CHARGE_FROM_GAMERTAG_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/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": 0.8683621883392334
},
{
"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": 0.8652037978172302
},
{
"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": 0.8432400822639465
},
{
"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": 0.8376014828681946
},
{
"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": 0.830793023109436
}
] |
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/banner/banner.service.ts",
"retrieved_chunk": " msg: 'ok',\n data: null,\n code: HttpStatus.OK,\n };\n }\n async deleteBanner(banner: { id: number }): Promise<interfaceReturnType> {\n if (!banner.id) throw new BadRequestException('id为必填项~');\n await this.bannerList.delete(banner.id);\n return {\n msg: 'ok',",
"score": 0.9132025837898254
},
{
"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": 0.9107198119163513
},
{
"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": 0.9027794003486633
},
{
"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": 0.9008175134658813
},
{
"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": 0.8979520201683044
}
] |
typescript
|
const res = await this.BannerService.deleteBanner(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/zbd.d.ts",
"retrieved_chunk": " sendKeysendPayment(options: KeysendOptionsType): Promise<KeysendDataResponseType>;\n sendPayment(options: SendPaymentOptionsType): Promise<InvoicePaymentDataResponseType>;\n getPayment(paymentId: string): Promise<any>;\n sendGamertagPayment(options: SendGamertagPaymentOptionsType): Promise<SendGamertagPaymentDataResponseType>;\n getGamertagTransaction(transactionId: string): Promise<GamertagTransactionDataResponseType>;\n getUserIdByGamertag(gamertag: string): Promise<FetchUserIdByGamertagDataResponseType>;\n getGamertagByUserId(userId: string): Promise<FetchGamertagByUserIdDataResponseType>;\n createGamertagCharge(options: FetchChargeFromGamertagOptionsType): Promise<FetchChargeFromGamertagDataResponseType>;\n createStaticCharge(options: StaticChargeOptionsType): Promise<StaticChargeDataResponseType>;\n updateStaticCharge(staticChargeId: string, updates: StaticChargeOptionsType): Promise<any>;",
"score": 0.8674750924110413
},
{
"filename": "src/types/gamertag.ts",
"retrieved_chunk": " receiverId: string;\n transactionId: string;\n amount: string;\n comment: string;\n }\n success: boolean;\n message: string;\n}\nexport interface SendGamertagPaymentOptionsType {\n gamertag: string;",
"score": 0.8641248345375061
},
{
"filename": "src/types/gamertag.d.ts",
"retrieved_chunk": " receiverId: string;\n transactionId: string;\n amount: string;\n comment: string;\n };\n success: boolean;\n message: string;\n}\nexport interface SendGamertagPaymentOptionsType {\n gamertag: string;",
"score": 0.8639796376228333
},
{
"filename": "src/types/gamertag.ts",
"retrieved_chunk": " callbackUrl: string;\n description: string;\n invoiceRequest: string;\n invoiceExpiresAt: string;\n invoiceDescriptionHash: string | null;\n }\n success: boolean;\n}\nexport interface FetchChargeFromGamertagOptionsType {\n amount: string;",
"score": 0.8408677577972412
},
{
"filename": "src/types/gamertag.d.ts",
"retrieved_chunk": " callbackUrl: string;\n description: string;\n invoiceRequest: string;\n invoiceExpiresAt: string;\n invoiceDescriptionHash: string | null;\n };\n success: boolean;\n}\nexport interface FetchChargeFromGamertagOptionsType {\n amount: string;",
"score": 0.8398380279541016
}
] |
typescript
|
url: `${API_URL}${API.SEND_GAMERTAG_PAYMENT_ENDPOINT}`,
headers: { ...this.apiCoreHeaders },
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": 0.9217891097068787
},
{
"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": 0.9022365808486938
},
{
"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": 0.9002429842948914
},
{
"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": 0.8987329602241516
},
{
"filename": "src/api/header/header.service.ts",
"retrieved_chunk": " msg: 'ok',\n data: null,\n code: HttpStatus.OK,\n };\n }\n async deleteHeader(item: { id: number }): Promise<interfaceReturnType> {\n if (!item.id) throw new BadRequestException('id为必填项~');\n await this.headerList.delete(item.id);\n return {\n msg: 'ok',",
"score": 0.890865683555603
}
] |
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": 0.8959368467330933
},
{
"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": 0.878224790096283
},
{
"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": 0.8627806901931763
},
{
"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": 0.860151469707489
},
{
"filename": "src/Emitter.ts",
"retrieved_chunk": "import * as fs from 'fs-extra';\nimport { SyncHook } from 'tapable';\nimport { Asset, AssetPath } from './Asset';\nimport { Compilation } from './Compilation';\nimport { Compiler } from './Compiler';\nexport type EmitterHooks = Readonly<{\n beforeAssetAction: SyncHook<[Asset]>;\n afterAssetAction: SyncHook<[Asset]>;\n}>;\nexport class Emitter {",
"score": 0.8446626663208008
}
] |
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/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": 0.8883573412895203
},
{
"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": 0.8629393577575684
},
{
"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": 0.847723662853241
},
{
"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": 0.836755096912384
},
{
"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": 0.833969235420227
}
] |
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": 0.8595494627952576
},
{
"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": 0.854311466217041
},
{
"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": 0.8520083427429199
},
{
"filename": "src/Watcher.ts",
"retrieved_chunk": " this.initial = false;\n this.compiler.compile('add', this.initialAssetPaths);\n });\n }\n async close() {\n if (this.watcher) {\n await this.watcher.close();\n this.compiler.hooks.watcherClose.call();\n }\n }",
"score": 0.8515110611915588
},
{
"filename": "src/Watcher.ts",
"retrieved_chunk": "import * as chokidar from 'chokidar';\nimport * as fs from 'fs';\nimport { Compiler } from './Compiler';\ninterface WatchOptions extends chokidar.WatchOptions {}\nexport class Watcher {\n compiler: Compiler;\n watcher: chokidar.FSWatcher | null;\n watcherPath: string;\n watchOptions: WatchOptions;\n initial: boolean;",
"score": 0.8458408713340759
}
] |
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/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": 0.9014056324958801
},
{
"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": 0.8940551280975342
},
{
"filename": "src/Watcher.ts",
"retrieved_chunk": " this.initial = false;\n this.compiler.compile('add', this.initialAssetPaths);\n });\n }\n async close() {\n if (this.watcher) {\n await this.watcher.close();\n this.compiler.hooks.watcherClose.call();\n }\n }",
"score": 0.8857517242431641
},
{
"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": 0.8757892847061157
},
{
"filename": "src/Compilation.ts",
"retrieved_chunk": " errors: string[];\n};\nexport type CompilationHooks = {\n beforeAddAsset: SyncHook<[Asset]>;\n afterAddAsset: SyncHook<[Asset]>;\n};\nexport class Compilation {\n compiler: Compiler;\n event: CompilerEvent;\n assetPaths: Set<string>;",
"score": 0.874752938747406
}
] |
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": 0.8760223984718323
},
{
"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": 0.8523331880569458
},
{
"filename": "src/Watcher.ts",
"retrieved_chunk": " this.initial = false;\n this.compiler.compile('add', this.initialAssetPaths);\n });\n }\n async close() {\n if (this.watcher) {\n await this.watcher.close();\n this.compiler.hooks.watcherClose.call();\n }\n }",
"score": 0.8485503792762756
},
{
"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": 0.8408379554748535
},
{
"filename": "src/Emitter.ts",
"retrieved_chunk": "import * as fs from 'fs-extra';\nimport { SyncHook } from 'tapable';\nimport { Asset, AssetPath } from './Asset';\nimport { Compilation } from './Compilation';\nimport { Compiler } from './Compiler';\nexport type EmitterHooks = Readonly<{\n beforeAssetAction: SyncHook<[Asset]>;\n afterAssetAction: SyncHook<[Asset]>;\n}>;\nexport class Emitter {",
"score": 0.8386243581771851
}
] |
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": 0.8857011795043945
},
{
"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": 0.8795185089111328
},
{
"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": 0.8783563375473022
},
{
"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": 0.8755983114242554
},
{
"filename": "src/Compilation.ts",
"retrieved_chunk": " errors: string[];\n};\nexport type CompilationHooks = {\n beforeAddAsset: SyncHook<[Asset]>;\n afterAddAsset: SyncHook<[Asset]>;\n};\nexport class Compilation {\n compiler: Compiler;\n event: CompilerEvent;\n assetPaths: Set<string>;",
"score": 0.8752444982528687
}
] |
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": " }\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": 0.8872462511062622
},
{
"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": 0.8723364472389221
},
{
"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": 0.8705099821090698
},
{
"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": 0.8653587102890015
},
{
"filename": "src/Compilation.ts",
"retrieved_chunk": " errors: string[];\n};\nexport type CompilationHooks = {\n beforeAddAsset: SyncHook<[Asset]>;\n afterAddAsset: SyncHook<[Asset]>;\n};\nexport class Compilation {\n compiler: Compiler;\n event: CompilerEvent;\n assetPaths: Set<string>;",
"score": 0.8603701591491699
}
] |
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": 0.8679907321929932
},
{
"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": 0.853147029876709
},
{
"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": 0.8478103876113892
},
{
"filename": "src/config/index.ts",
"retrieved_chunk": "import { Plugin } from '../Plugin';\nimport { PathsPluginConfig } from '../plugins/PathsPlugin';\nimport { StatsPluginConfig } from '../plugins/StatsPlugin';\nexport * from './load';\nexport type BaseCompilerConfig = {\n /**\n * Where to look for files to compile.\n */\n input: string;\n /**",
"score": 0.8470149040222168
},
{
"filename": "src/config/defaults.ts",
"retrieved_chunk": "import { CompilerConfig, MelterConfig, defaultBaseCompilerConfig } from '.';\nimport { Plugin } from '../Plugin';\nimport { PathsPlugin } from '../plugins/PathsPlugin';\nimport { StatsPlugin } from '../plugins/StatsPlugin';\nfunction applyDefaultPlugins(config: CompilerConfig): Plugin[] {\n const plugins = [];\n plugins.push(\n ...[\n new StatsPlugin({\n stats: config.stats,",
"score": 0.8423401713371277
}
] |
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/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": 0.8567385077476501
},
{
"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": 0.8471860885620117
},
{
"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": 0.831134021282196
},
{
"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": 0.8276379108428955
},
{
"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": 0.8273621797561646
}
] |
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/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": 0.8325763940811157
},
{
"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": 0.8208536505699158
},
{
"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": 0.8173569440841675
},
{
"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": 0.8128469586372375
},
{
"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": 0.8064761161804199
}
] |
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/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": 0.832572340965271
},
{
"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": 0.8219931721687317
},
{
"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": 0.8178942203521729
},
{
"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": 0.8130483627319336
},
{
"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": 0.8058990240097046
}
] |
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": 0.8254992961883545
},
{
"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": 0.8180614113807678
},
{
"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": 0.8142400979995728
},
{
"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": 0.8084878921508789
},
{
"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": 0.8037790060043335
}
] |
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/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": 0.8250579833984375
},
{
"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": 0.8087009191513062
},
{
"filename": "src/Emitter.ts",
"retrieved_chunk": " }\n private removeFile(targetPath: AssetPath['absolute']) {\n try {\n fs.removeSync(targetPath);\n } catch (error: any) {\n this.compilation.addError(error.message);\n }\n }\n}",
"score": 0.8050453662872314
},
{
"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": 0.8033834099769592
},
{
"filename": "src/Asset.ts",
"retrieved_chunk": "import * as fs from 'fs-extra';\nimport { CompilerEvent } from './Compiler';\nexport type AssetType =\n | 'assets'\n | 'config'\n | 'layout'\n | 'locales'\n | 'sections'\n | 'snippets'\n | 'templates';",
"score": 0.7980436086654663
}
] |
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/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": 0.8061702847480774
},
{
"filename": "src/plugins/PathsPlugin.ts",
"retrieved_chunk": " ...defaultPathsPluginConfig.paths,\n ...config.paths,\n },\n }\n : {};\n }\n apply(compiler: Compiler): void {\n const output = compiler.config.output;\n if (!output) return;\n const paths = this.config.paths;",
"score": 0.7854668498039246
},
{
"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": 0.784951388835907
},
{
"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": 0.7845683097839355
},
{
"filename": "src/config/defaults.ts",
"retrieved_chunk": "import { CompilerConfig, MelterConfig, defaultBaseCompilerConfig } from '.';\nimport { Plugin } from '../Plugin';\nimport { PathsPlugin } from '../plugins/PathsPlugin';\nimport { StatsPlugin } from '../plugins/StatsPlugin';\nfunction applyDefaultPlugins(config: CompilerConfig): Plugin[] {\n const plugins = [];\n plugins.push(\n ...[\n new StatsPlugin({\n stats: config.stats,",
"score": 0.7736297845840454
}
] |
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/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": 0.8325806260108948
},
{
"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": 0.8276197910308838
},
{
"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": 0.8186156749725342
},
{
"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": 0.8178176879882812
},
{
"filename": "src/Emitter.ts",
"retrieved_chunk": " }\n private removeFile(targetPath: AssetPath['absolute']) {\n try {\n fs.removeSync(targetPath);\n } catch (error: any) {\n this.compilation.addError(error.message);\n }\n }\n}",
"score": 0.8101760745048523
}
] |
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/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": 0.8817286491394043
},
{
"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": 0.8777549266815186
},
{
"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": 0.8635119795799255
},
{
"filename": "src/Compilation.ts",
"retrieved_chunk": " errors: string[];\n};\nexport type CompilationHooks = {\n beforeAddAsset: SyncHook<[Asset]>;\n afterAddAsset: SyncHook<[Asset]>;\n};\nexport class Compilation {\n compiler: Compiler;\n event: CompilerEvent;\n assetPaths: Set<string>;",
"score": 0.8589968681335449
},
{
"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": 0.8573806881904602
}
] |
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/parsers/index.ts",
"retrieved_chunk": "import { formatUnits } from \"ethers\";\nimport { extractTokenInfo, fetchSymbolAndDecimal } from \"../utils\";\nimport {\n CONTRACTS,\n NATIVE_ASSET,\n EVENT_SIGNATURES,\n NATIVE_SYMBOL_BY_CHAIN_ID,\n EXCHANGE_PROXY_BY_CHAIN_ID,\n} from \"../constants\";\nimport type {",
"score": 0.8637924194335938
},
{
"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": 0.8440953493118286
},
{
"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": 0.8360384702682495
},
{
"filename": "src/index.ts",
"retrieved_chunk": "import { Contract, JsonRpcProvider } from \"ethers\";\nimport { abi as permitAndCallAbi } from \"./abi/PermitAndCall.json\";\nimport multicall3Abi from \"./abi/Multicall3.json\";\nimport {\n MULTICALL3,\n EXCHANGE_PROXY_ABI_URL,\n EXCHANGE_PROXY_BY_CHAIN_ID,\n PERMIT_AND_CALL_BY_CHAIN_ID,\n} from \"./constants\";\nimport {",
"score": 0.8304983377456665
},
{
"filename": "src/parsers/index.ts",
"retrieved_chunk": " Contract,\n TransactionReceipt,\n TransactionDescription,\n} from \"ethers\";\nimport type {\n SupportedChainId,\n EnrichedTxReceipt,\n TryBlockAndAggregate,\n TransformERC20EventData,\n} from \"../types\";",
"score": 0.8302032351493835
}
] |
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": 0.8638889789581299
},
{
"filename": "src/tests/index.test.ts",
"retrieved_chunk": "it(\"returns null when the transaction reverted\", async () => {\n const data = await parseSwap({\n transactionHash:\n \"0x335b2a3faf4a15cd6f67f1ec7ed26ee04ea7cc248f5cd052967e6ae672af8d35\",\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n rpcUrl: ETH_MAINNET_RPC,\n });\n expect(data).toBe(null);\n});\nit(\"throws an error when required arguments are not passed\", () => {",
"score": 0.8553218841552734
},
{
"filename": "src/tests/index.test.ts",
"retrieved_chunk": " expect(async () => {\n await parseSwap({\n transactionHash: \"0x…\",\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n } as any);\n }).rejects.toThrowError(\"Missing rpcUrl\");\n expect(async () => {\n await parseSwap({\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n rpcUrl: ETH_MAINNET_RPC,",
"score": 0.852362334728241
},
{
"filename": "src/tests/multiplexMultiHopSellEthForToken.test.ts",
"retrieved_chunk": " const data = await parseSwap({\n transactionHash: \"0x00b191d47269265cfbbc94c77a114281ee939463b7a922e8bfbf7de8bc150c5c\",\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n rpcUrl: ETH_MAINNET_RPC,\n });\n expect(data).toEqual({\n tokenIn: {\n symbol: \"WETH\",\n amount: \"3\",\n address: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\",",
"score": 0.8489691019058228
},
{
"filename": "src/tests/sellEthForTokenToUniswapV3.test.ts",
"retrieved_chunk": " const data = await parseSwap({\n transactionHash: '0xc552e83ef96c5d523f69494ae61b7235a6304ab439e127eb0121d33bbcdaa1ff',\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n rpcUrl: ETH_MAINNET_RPC,\n });\n expect(data).toEqual({\n tokenIn: {\n symbol: \"WETH\",\n amount: \"2.749441612813630418\",\n address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',",
"score": 0.8436706066131592
}
] |
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": 0.8670564889907837
},
{
"filename": "src/tests/index.test.ts",
"retrieved_chunk": " expect(async () => {\n await parseSwap({\n transactionHash: \"0x…\",\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n } as any);\n }).rejects.toThrowError(\"Missing rpcUrl\");\n expect(async () => {\n await parseSwap({\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n rpcUrl: ETH_MAINNET_RPC,",
"score": 0.8598898649215698
},
{
"filename": "src/tests/index.test.ts",
"retrieved_chunk": "it(\"returns null when the transaction reverted\", async () => {\n const data = await parseSwap({\n transactionHash:\n \"0x335b2a3faf4a15cd6f67f1ec7ed26ee04ea7cc248f5cd052967e6ae672af8d35\",\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n rpcUrl: ETH_MAINNET_RPC,\n });\n expect(data).toBe(null);\n});\nit(\"throws an error when required arguments are not passed\", () => {",
"score": 0.858196496963501
},
{
"filename": "src/tests/multiplexMultiHopSellEthForToken.test.ts",
"retrieved_chunk": " const data = await parseSwap({\n transactionHash: \"0x00b191d47269265cfbbc94c77a114281ee939463b7a922e8bfbf7de8bc150c5c\",\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n rpcUrl: ETH_MAINNET_RPC,\n });\n expect(data).toEqual({\n tokenIn: {\n symbol: \"WETH\",\n amount: \"3\",\n address: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\",",
"score": 0.8536486029624939
},
{
"filename": "src/tests/sellEthForTokenToUniswapV3.test.ts",
"retrieved_chunk": " const data = await parseSwap({\n transactionHash: '0xc552e83ef96c5d523f69494ae61b7235a6304ab439e127eb0121d33bbcdaa1ff',\n exchangeProxyAbi: EXCHANGE_PROXY_ABI.compilerOutput.abi,\n rpcUrl: ETH_MAINNET_RPC,\n });\n expect(data).toEqual({\n tokenIn: {\n symbol: \"WETH\",\n amount: \"2.749441612813630418\",\n address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',",
"score": 0.8500574827194214
}
] |
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": " from: string;\n}\nexport type TryBlockAndAggregate = BaseContractMethod<\n [boolean, Call[]],\n AggregateResponse\n>;\nexport interface EnrichedTxReceiptArgs {\n transactionReceipt: TransactionReceipt;\n tryBlockAndAggregate: TryBlockAndAggregate;\n}",
"score": 0.8656265735626221
},
{
"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": 0.8565512895584106
},
{
"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": 0.8443213105201721
},
{
"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": 0.8369641304016113
},
{
"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": 0.8361236453056335
}
] |
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": 0.8513478636741638
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": " { target: address, callData: ERC20_FUNCTION_HASHES.decimals },\n ];\n const { 2: results } = await tryBlockAndAggregate.staticCall(false, calls);\n const [symbolResult, decimalsResult] = results;\n const symbol = parseHexDataToString(symbolResult.returnData);\n const decimals = Number(BigInt(decimalsResult.returnData));\n return [symbol, decimals];\n}\nfunction processLog(log: EnrichedLogWithoutAmount): ProcessedLog {\n const { topics, data, decimals, symbol, address } = log;",
"score": 0.8182644248008728
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": "}\nexport function extractTokenInfo(\n inputLog: ProcessedLog,\n outputLog: ProcessedLog\n) {\n return {\n tokenIn: {\n symbol: inputLog.symbol,\n amount: inputLog.amount,\n address: inputLog.address,",
"score": 0.8084928393363953
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": " },\n tokenOut: {\n symbol: outputLog.symbol,\n amount: outputLog.amount,\n address: outputLog.address,\n },\n };\n}",
"score": 0.8012433648109436
},
{
"filename": "src/tests/transformERC20.test.ts",
"retrieved_chunk": " });\n expect(data).toEqual({\n tokenIn: {\n symbol: \"USDT\",\n amount: \"275.0\",\n address: \"0xdAC17F958D2ee523a2206206994597C13D831ec7\",\n },\n tokenOut: {\n symbol: \"MUTE\",\n amount: \"183.067612917791449241\",",
"score": 0.7977942228317261
}
] |
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": 0.9125967025756836
},
{
"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": 0.8992955684661865
},
{
"filename": "src/index.ts",
"retrieved_chunk": " });\n }\n const txReceiptEnriched = await enrichTxReceipt({\n transactionReceipt,\n tryBlockAndAggregate,\n });\n return parser({\n txDescription: transactionDescription,\n txReceipt: txReceiptEnriched,\n });",
"score": 0.8790875673294067
},
{
"filename": "src/parsers/index.ts",
"retrieved_chunk": "}\nexport function sellToUniswap({ txReceipt }: { txReceipt: EnrichedTxReceipt }) {\n const [inputLog, outputLog] = txReceipt.logs;\n return extractTokenInfo(inputLog, outputLog);\n}\nexport async function transformERC20({\n chainId,\n contract,\n transactionReceipt,\n tryBlockAndAggregate,",
"score": 0.8654178380966187
},
{
"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": 0.862310528755188
}
] |
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/constants.ts",
"retrieved_chunk": " \"https://raw.githubusercontent.com/0xProject/protocol/development/packages/contract-artifacts/artifacts/IZeroEx.json\";\nconst CONONICAL_EXCHANGE_PROXY = \"0xdef1c0ded9bec7f1a1670819833240f027b25eff\";\nexport const MULTICALL3 = \"0xcA11bde05977b3631167028862bE2a173976CA11\";\nexport const PERMIT_AND_CALL_BY_CHAIN_ID = {\n 1: \"0x1291C02D288de3De7dC25353459489073D11E1Ae\",\n 137: \"0x2ddd30fe5c12fc4cd497526f14bf3d1fcd3d5db4\",\n 8453: \"0x3CA53031Ad0B86a304845e83644983Be3340895f\"\n} as const\nexport const EXCHANGE_PROXY_BY_CHAIN_ID = {\n 1: CONONICAL_EXCHANGE_PROXY,",
"score": 0.8419824242591858
},
{
"filename": "src/parsers/index.ts",
"retrieved_chunk": " txReceipt: EnrichedTxReceipt;\n txDescription: TransactionDescription;\n}) {\n const [order] = txDescription.args;\n const { logs } = txReceipt;\n const { 4: maker, 5: taker } = order as string[];\n if (typeof maker === \"string\" && typeof taker === \"string\") {\n const inputLog = logs.find((log) => log.from === taker.toLowerCase());\n const outputLog = logs.find((log) => log.from === maker.toLowerCase());\n if (inputLog && outputLog) {",
"score": 0.8288495540618896
},
{
"filename": "src/parsers/index.ts",
"retrieved_chunk": " });\n return {\n tokenIn: tokenData[from.toLowerCase()],\n tokenOut: tokenData[CONTRACTS.weth.toLowerCase()],\n };\n}\nexport function multiplexBatchSellEthForToken({\n txReceipt,\n txDescription,\n}: {",
"score": 0.8268898725509644
},
{
"filename": "src/parsers/index.ts",
"retrieved_chunk": " const { logs, from } = txReceipt;\n const inputLog = logs.find((log) => log.from === from.toLowerCase());\n const outputLog = logs.find((log) => log.from !== from.toLowerCase());\n if (inputLog && outputLog) {\n return extractTokenInfo(inputLog, outputLog);\n }\n}\nexport function sellTokenForTokenToUniswapV3({\n txReceipt,\n}: {",
"score": 0.8260584473609924
},
{
"filename": "src/parsers/index.ts",
"retrieved_chunk": "}: {\n txReceipt: EnrichedTxReceipt;\n txDescription: TransactionDescription;\n}) {\n const { logs } = txReceipt;\n const [order] = txDescription.args;\n const [makerToken, takerToken] = order as string[];\n const inputLog = logs.find((log) => log.address === takerToken);\n const outputLog = logs.find((log) => log.address === makerToken);\n if (inputLog && outputLog) {",
"score": 0.8258123397827148
}
] |
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/constants/provider-names.ts",
"retrieved_chunk": "export const Watchman_OPTIONS = 'WatchmanOptions';\nexport const STRATEGY_TOKEN = 'STRATEGY';",
"score": 0.8639061450958252
},
{
"filename": "src/index.ts",
"retrieved_chunk": "export * from './Watchman.module';\nexport * from './Watchman.service';\nexport * from './strategies/export.strategy';\nexport * from './interfaces';\nexport * from './constants';",
"score": 0.8434015512466431
},
{
"filename": "src/Watchman.service.ts",
"retrieved_chunk": "export class WatchmanService {\n constructor(\n private options: Partial<WatchmanModuleOptions>,\n private strategy: BaseStrategy,\n ) {}\n public setStrategy(strategy: BaseStrategy) {\n this.strategy = strategy;\n }\n public watch(exception: IException, data: WatchData): void {\n const { host, trackUUID, metaData } = data;",
"score": 0.8417961001396179
},
{
"filename": "src/strategies/base.strategy.ts",
"retrieved_chunk": "import { Request, Response } from 'express';\nimport { Inject } from '@nestjs/common';\nimport { Watchman_OPTIONS } from '../constants';\nimport {\n DiscordConfig,\n IException,\n WatchmanModuleOptions,\n WatchMetaData,\n} from '../interfaces';\ntype StrategyConfig = WatchmanModuleOptions['strategyConfig'];",
"score": 0.841664731502533
},
{
"filename": "src/interfaces/module.interface.ts",
"retrieved_chunk": " ...args: any[]\n ) => Promise<WatchmanModuleOptions> | WatchmanModuleOptions;\n}\nexport interface WatchmanModuleOptions {\n /**\n * @default false\n * */\n catchOnlyInternalExceptions?: boolean;\n strategy?: any;\n strategyConfig?: DiscordConfig;",
"score": 0.8323040008544922
}
] |
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/parsers/index.ts",
"retrieved_chunk": " inputToken,\n tryBlockAndAggregate\n );\n }\n if (outputToken === NATIVE_ASSET) {\n outputSymbol = nativeSymbol;\n outputDecimal = 18;\n } else {\n [outputSymbol, outputDecimal] = await fetchSymbolAndDecimal(\n outputToken,",
"score": 0.8469526171684265
},
{
"filename": "src/parsers/index.ts",
"retrieved_chunk": " tryBlockAndAggregate\n );\n }\n const inputAmount = formatUnits(inputTokenAmount, inputDecimal);\n const outputAmount = formatUnits(outputTokenAmount, outputDecimal);\n return {\n tokenIn: {\n address: inputToken,\n amount: inputAmount,\n symbol: inputSymbol,",
"score": 0.8243488073348999
},
{
"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": 0.8071707487106323
},
{
"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": 0.8047155141830444
},
{
"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": 0.8042142391204834
}
] |
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/parsers/index.ts",
"retrieved_chunk": " inputToken,\n tryBlockAndAggregate\n );\n }\n if (outputToken === NATIVE_ASSET) {\n outputSymbol = nativeSymbol;\n outputDecimal = 18;\n } else {\n [outputSymbol, outputDecimal] = await fetchSymbolAndDecimal(\n outputToken,",
"score": 0.847194492816925
},
{
"filename": "src/parsers/index.ts",
"retrieved_chunk": " tryBlockAndAggregate\n );\n }\n const inputAmount = formatUnits(inputTokenAmount, inputDecimal);\n const outputAmount = formatUnits(outputTokenAmount, outputDecimal);\n return {\n tokenIn: {\n address: inputToken,\n amount: inputAmount,\n symbol: inputSymbol,",
"score": 0.8230284452438354
},
{
"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": 0.8181685209274292
},
{
"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": 0.8098695278167725
},
{
"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": 0.8066736459732056
}
] |
typescript
|
: ERC20_FUNCTION_HASHES.symbol },
{ target: address, callData: ERC20_FUNCTION_HASHES.decimals },
];
|
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": 0.8304898738861084
},
{
"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": 0.7938175797462463
},
{
"filename": "src/app.workflow.ts",
"retrieved_chunk": "import { join } from 'path';\n@Injectable()\n@Process({ name: 'Simple Workflow', path: join(__dirname, 'app.flow.bpmn') })\nexport class AppWorkflow extends WorkflowJS {\n constructor(private readonly appProvider: AppProvider) {\n super();\n }\n @Node({ name: 'start' })\n async start(@Act() activity: EventActivity) {\n activity.takeOutgoing();",
"score": 0.792475700378418
},
{
"filename": "src/app.repository.ts",
"retrieved_chunk": "import { ContextInterface } from '@vhidvz/wfjs';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { Injectable } from '@nestjs/common';\nimport { Model } from 'mongoose';\nimport { App } from './schemas';\n@Injectable()\nexport class AppRepository {\n constructor(@InjectModel(App.name) private appModel: Model<App>) {}\n async find(id: string) {\n return this.appModel.findById(id);",
"score": 0.783112645149231
},
{
"filename": "src/app.controller.ts",
"retrieved_chunk": "import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { DataDto, ValueDto } from './dto';\nimport { ActivityPipe } from './pipes';\nimport { App } from './schemas';\nimport { ApiTags } from '@nestjs/swagger';\n@ApiTags('workflows')\n@Controller('flow')\nexport class AppController {\n constructor(private readonly appService: AppService) {}",
"score": 0.7671964168548584
}
] |
typescript
|
return this.appRepository.create(context.serialize());
|
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": 0.852439284324646
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": " { target: address, callData: ERC20_FUNCTION_HASHES.decimals },\n ];\n const { 2: results } = await tryBlockAndAggregate.staticCall(false, calls);\n const [symbolResult, decimalsResult] = results;\n const symbol = parseHexDataToString(symbolResult.returnData);\n const decimals = Number(BigInt(decimalsResult.returnData));\n return [symbol, decimals];\n}\nfunction processLog(log: EnrichedLogWithoutAmount): ProcessedLog {\n const { topics, data, decimals, symbol, address } = log;",
"score": 0.822437047958374
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": "}\nexport function extractTokenInfo(\n inputLog: ProcessedLog,\n outputLog: ProcessedLog\n) {\n return {\n tokenIn: {\n symbol: inputLog.symbol,\n amount: inputLog.amount,\n address: inputLog.address,",
"score": 0.810930609703064
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": " },\n tokenOut: {\n symbol: outputLog.symbol,\n amount: outputLog.amount,\n address: outputLog.address,\n },\n };\n}",
"score": 0.8063062429428101
},
{
"filename": "src/tests/executeMetaTransactionV2.test.ts",
"retrieved_chunk": " tokenIn: {\n amount: \"399.98912868386398826\",\n symbol: \"cbETH\",\n address: \"0xBe9895146f7AF43049ca1c1AE358B0541Ea49704\",\n },\n tokenOut: {\n amount: \"410.723904828710787856\",\n symbol: \"ETH\",\n address: \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\",\n },",
"score": 0.801396906375885
}
] |
typescript
|
] = await fetchSymbolAndDecimal(
inputToken,
tryBlockAndAggregate
);
|
/**
* 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": 0.891235888004303
},
{
"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": 0.8799184560775757
},
{
"filename": "src/lib/database.ts",
"retrieved_chunk": " const completedMissions = snapshot.data()?.completedMissions || [];\n return { username, completedMissions }\n }\n async addCompletedMission({ username, missionId }: { username: string, missionId: string }): Promise<any> {\n const { completedMissions } = await this.getUser({ username });\n const updatedMissions = [...completedMissions, missionId]\n return this.setUser({\n username,\n completedMissions: updatedMissions,\n });",
"score": 0.8373682498931885
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " </button>\n )}\n {allItemsCollected && tileIsFinalTile && playerIsOnTile && (\n <button\n className='bg-blue-500 hover:bg-blue-700 text-white p-2 rounded disabled:bg-slate-50 disabled:text-slate-500'\n disabled={!playerIsOnTile || isSavingMission} onClick={completeMission}\n >\n {isSavingMission ? 'Saving...' : 'Complete'}\n </button>\n )}",
"score": 0.8246713280677795
},
{
"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": 0.8215847015380859
}
] |
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": 0.8788670301437378
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " if (state.playerPosition.y > 0 && !state.isSavingMission) state.playerPosition.y -= 1\n },\n moveLeft: state => {\n if (state.playerPosition.x > 0 && !state.isSavingMission) state.playerPosition.x -= 1\n },\n moveRight: state => {\n if (state.playerPosition.x < 2 && !state.isSavingMission) state.playerPosition.x += 1\n },\n collectItem: (state) => {\n const itemIndex = state.inventory.findIndex(item => {",
"score": 0.8445667028427124
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " playerPosition,\n inventory,\n allItemsCollected: false,\n isSavingMission: false,\n }\n },\n moveUp: state => {\n if (state.playerPosition.y < 2 && !state.isSavingMission) state.playerPosition.y += 1\n },\n moveDown: state => {",
"score": 0.8408182263374329
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " </button>\n )}\n {allItemsCollected && tileIsFinalTile && playerIsOnTile && (\n <button\n className='bg-blue-500 hover:bg-blue-700 text-white p-2 rounded disabled:bg-slate-50 disabled:text-slate-500'\n disabled={!playerIsOnTile || isSavingMission} onClick={completeMission}\n >\n {isSavingMission ? 'Saving...' : 'Complete'}\n </button>\n )}",
"score": 0.8394341468811035
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " const [addCompletedMission] = useAddCompletedMissionMutation()\n const dispatch = useAppDispatch()\n const { playerPosition, mission, inventory, allItemsCollected, isSavingMission } = useAppSelector((state: RootState) => state.game)\n const playerIsOnTile = playerPosition.x === x && playerPosition.y === y;\n const playerIsOnStartingTile = playerPosition.x === 0 && playerPosition.y === 0;\n const playerIsLeftOfTile = playerPosition.x + 1 === x && playerPosition.y === y;\n const playerIsRightOfTile = playerPosition.x - 1 === x && playerPosition.y === y;\n const playerIsAboveTile = playerPosition.x === x && playerPosition.y - 1 === y;\n const playerIsBelowTile = playerPosition.x === x && playerPosition.y + 1 === y;\n const playerIsOnAdjacentTile = playerIsLeftOfTile || playerIsRightOfTile || playerIsAboveTile || playerIsBelowTile;",
"score": 0.8392147421836853
}
] |
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": 0.8426973819732666
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " playerPosition,\n inventory,\n allItemsCollected: false,\n isSavingMission: false,\n }\n },\n moveUp: state => {\n if (state.playerPosition.y < 2 && !state.isSavingMission) state.playerPosition.y += 1\n },\n moveDown: state => {",
"score": 0.8205722570419312
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " if (state.playerPosition.y > 0 && !state.isSavingMission) state.playerPosition.y -= 1\n },\n moveLeft: state => {\n if (state.playerPosition.x > 0 && !state.isSavingMission) state.playerPosition.x -= 1\n },\n moveRight: state => {\n if (state.playerPosition.x < 2 && !state.isSavingMission) state.playerPosition.x += 1\n },\n collectItem: (state) => {\n const itemIndex = state.inventory.findIndex(item => {",
"score": 0.8051661252975464
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " }\n if (playerIsBelowTile) {\n dispatch(moveUp())\n }\n }}>\n <figure className=\"bg-slate-200 rounded-xl p-3 w-full\">\n <div className=\"h-8 md:h-12 lg:h-20 flex justify-between\">\n {playerIsOnTile ? (\n <UserCircleIcon className=\"block h-8 md:h-12 lg:h-20\" data-testid=\"usericon\" aria-hidden=\"true\" />\n ) : <div />}",
"score": 0.7962406277656555
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport Image from 'next/image'\nimport { RootState } from '../redux/store'\nimport { useAppDispatch, useAppSelector } from '../redux/hooks'\nimport { GridPosition } from 'src/models/GridPosition';\nimport { collectItem, moveDown, moveLeft, moveRight, moveUp, setIsSavingMission, startMission } from 'src/redux/gameSlice';",
"score": 0.7861047387123108
}
] |
typescript
|
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": 0.8421192169189453
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " playerPosition,\n inventory,\n allItemsCollected: false,\n isSavingMission: false,\n }\n },\n moveUp: state => {\n if (state.playerPosition.y < 2 && !state.isSavingMission) state.playerPosition.y += 1\n },\n moveDown: state => {",
"score": 0.8260757327079773
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " if (state.playerPosition.y > 0 && !state.isSavingMission) state.playerPosition.y -= 1\n },\n moveLeft: state => {\n if (state.playerPosition.x > 0 && !state.isSavingMission) state.playerPosition.x -= 1\n },\n moveRight: state => {\n if (state.playerPosition.x < 2 && !state.isSavingMission) state.playerPosition.x += 1\n },\n collectItem: (state) => {\n const itemIndex = state.inventory.findIndex(item => {",
"score": 0.8096389174461365
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " }\n if (playerIsBelowTile) {\n dispatch(moveUp())\n }\n }}>\n <figure className=\"bg-slate-200 rounded-xl p-3 w-full\">\n <div className=\"h-8 md:h-12 lg:h-20 flex justify-between\">\n {playerIsOnTile ? (\n <UserCircleIcon className=\"block h-8 md:h-12 lg:h-20\" data-testid=\"usericon\" aria-hidden=\"true\" />\n ) : <div />}",
"score": 0.8008163571357727
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport Image from 'next/image'\nimport { RootState } from '../redux/store'\nimport { useAppDispatch, useAppSelector } from '../redux/hooks'\nimport { GridPosition } from 'src/models/GridPosition';\nimport { collectItem, moveDown, moveLeft, moveRight, moveUp, setIsSavingMission, startMission } from 'src/redux/gameSlice';",
"score": 0.7866239547729492
}
] |
typescript
|
dispatch(moveDown())
case 'd':
return dispatch(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": 0.8074748516082764
},
{
"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": 0.7856108546257019
},
{
"filename": "src/app.workflow.ts",
"retrieved_chunk": "import { join } from 'path';\n@Injectable()\n@Process({ name: 'Simple Workflow', path: join(__dirname, 'app.flow.bpmn') })\nexport class AppWorkflow extends WorkflowJS {\n constructor(private readonly appProvider: AppProvider) {\n super();\n }\n @Node({ name: 'start' })\n async start(@Act() activity: EventActivity) {\n activity.takeOutgoing();",
"score": 0.769497811794281
},
{
"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": 0.764419436454773
},
{
"filename": "src/schemas/app.schema.ts",
"retrieved_chunk": "import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Token, TokenSchema } from './token.schema';\nimport { ContextInterface } from '@vhidvz/wfjs';\nimport { ApiProperty } from '@nestjs/swagger';\nimport { HydratedDocument } from 'mongoose';\nimport { Data } from './data.schema';\nimport { Status } from 'src/enums';\n@Schema()\nexport class App implements ContextInterface {\n @ApiProperty()",
"score": 0.757185697555542
}
] |
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": 0.8403159379959106
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " playerPosition,\n inventory,\n allItemsCollected: false,\n isSavingMission: false,\n }\n },\n moveUp: state => {\n if (state.playerPosition.y < 2 && !state.isSavingMission) state.playerPosition.y += 1\n },\n moveDown: state => {",
"score": 0.8240876197814941
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " if (state.playerPosition.y > 0 && !state.isSavingMission) state.playerPosition.y -= 1\n },\n moveLeft: state => {\n if (state.playerPosition.x > 0 && !state.isSavingMission) state.playerPosition.x -= 1\n },\n moveRight: state => {\n if (state.playerPosition.x < 2 && !state.isSavingMission) state.playerPosition.x += 1\n },\n collectItem: (state) => {\n const itemIndex = state.inventory.findIndex(item => {",
"score": 0.8089783191680908
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " }\n if (playerIsBelowTile) {\n dispatch(moveUp())\n }\n }}>\n <figure className=\"bg-slate-200 rounded-xl p-3 w-full\">\n <div className=\"h-8 md:h-12 lg:h-20 flex justify-between\">\n {playerIsOnTile ? (\n <UserCircleIcon className=\"block h-8 md:h-12 lg:h-20\" data-testid=\"usericon\" aria-hidden=\"true\" />\n ) : <div />}",
"score": 0.7979140877723694
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport Image from 'next/image'\nimport { RootState } from '../redux/store'\nimport { useAppDispatch, useAppSelector } from '../redux/hooks'\nimport { GridPosition } from 'src/models/GridPosition';\nimport { collectItem, moveDown, moveLeft, moveRight, moveUp, setIsSavingMission, startMission } from 'src/redux/gameSlice';",
"score": 0.7834216356277466
}
] |
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": 0.8418393135070801
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " playerPosition,\n inventory,\n allItemsCollected: false,\n isSavingMission: false,\n }\n },\n moveUp: state => {\n if (state.playerPosition.y < 2 && !state.isSavingMission) state.playerPosition.y += 1\n },\n moveDown: state => {",
"score": 0.8185421228408813
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " if (state.playerPosition.y > 0 && !state.isSavingMission) state.playerPosition.y -= 1\n },\n moveLeft: state => {\n if (state.playerPosition.x > 0 && !state.isSavingMission) state.playerPosition.x -= 1\n },\n moveRight: state => {\n if (state.playerPosition.x < 2 && !state.isSavingMission) state.playerPosition.x += 1\n },\n collectItem: (state) => {\n const itemIndex = state.inventory.findIndex(item => {",
"score": 0.8044582605361938
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " }\n if (playerIsBelowTile) {\n dispatch(moveUp())\n }\n }}>\n <figure className=\"bg-slate-200 rounded-xl p-3 w-full\">\n <div className=\"h-8 md:h-12 lg:h-20 flex justify-between\">\n {playerIsOnTile ? (\n <UserCircleIcon className=\"block h-8 md:h-12 lg:h-20\" data-testid=\"usericon\" aria-hidden=\"true\" />\n ) : <div />}",
"score": 0.7946728467941284
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport Image from 'next/image'\nimport { RootState } from '../redux/store'\nimport { useAppDispatch, useAppSelector } from '../redux/hooks'\nimport { GridPosition } from 'src/models/GridPosition';\nimport { collectItem, moveDown, moveLeft, moveRight, moveUp, setIsSavingMission, startMission } from 'src/redux/gameSlice';",
"score": 0.7852777242660522
}
] |
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": 0.9103599190711975
},
{
"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": 0.82255619764328
},
{
"filename": "src/libs/suiModel/suiOwnedObject.ts",
"retrieved_chunk": "import { Infer } from 'superstruct';\nimport {\n getObjectChanges,\n SuiTransactionBlockResponse,\n ObjectCallArg,\n ObjectId,\n} from '@mysten/sui.js';\nexport class SuiOwnedObject {\n public readonly objectId: string;\n public version?: number | string;",
"score": 0.8151096105575562
},
{
"filename": "src/libs/suiModel/index.ts",
"retrieved_chunk": "export { SuiOwnedObject } from './suiOwnedObject';\nexport { SuiSharedObject } from './suiSharedObject';",
"score": 0.8098389506340027
},
{
"filename": "src/libs/suiModel/suiSharedObject.ts",
"retrieved_chunk": "import { Infer } from 'superstruct';\nimport { ObjectCallArg, ObjectId } from '@mysten/sui.js';\nexport class SuiSharedObject {\n public readonly objectId: string;\n public initialSharedVersion?: number | string;\n constructor(param: {\n objectId: string;\n initialSharedVersion?: number;\n mutable?: boolean;\n }) {",
"score": 0.799409031867981
}
] |
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/libs/suiAccountManager/index.ts",
"retrieved_chunk": "import { Ed25519Keypair } from '@mysten/sui.js';\nimport { getKeyPair } from './keypair';\nimport { hexOrBase64ToUint8Array, normalizePrivateKey } from './util';\nimport { generateMnemonic } from './crypto';\nimport type { AccountMangerParams, DerivePathParams } from 'src/types';\nexport class SuiAccountManager {\n private mnemonics: string;\n private secretKey: string;\n public currentKeyPair: Ed25519Keypair;\n public currentAddress: string;",
"score": 0.8868436813354492
},
{
"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": 0.8792407512664795
},
{
"filename": "src/libs/suiInteractor/suiInteractor.ts",
"retrieved_chunk": "export class SuiInteractor {\n public readonly providers: JsonRpcProvider[];\n public currentProvider: JsonRpcProvider;\n constructor(fullNodeUrls: string[]) {\n if (fullNodeUrls.length === 0)\n throw new Error('fullNodeUrls must not be empty');\n this.providers = fullNodeUrls.map(\n (url) => new JsonRpcProvider(new Connection({ fullnode: url }))\n );\n this.currentProvider = this.providers[0];",
"score": 0.8684058785438538
},
{
"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": 0.8637877702713013
},
{
"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": 0.8344194889068604
}
] |
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": "import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice';\nimport { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon } from '@heroicons/react/24/outline'\nexport default function Component() {\n const { playerPosition, allItemsCollected, mission, isSavingMission } = useAppSelector((state: RootState) => state.game)\n const {\n data: user,\n } = useGetUserQuery();\n const playerOnFinalSquare = playerPosition.x === 2 && playerPosition.y === 2;\n const dispatch = useAppDispatch()\n const [addCompletedMission] = useAddCompletedMissionMutation()",
"score": 0.8329103589057922
},
{
"filename": "src/components/mission-history.tsx",
"retrieved_chunk": "export default function MissionHistory() {\n const {\n data: user,\n isLoading,\n isSuccess,\n isError,\n error\n } = useGetUserQuery();\n if (isSuccess || isLoading) {\n return (",
"score": 0.8317230939865112
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": "import { useAddCompletedMissionMutation, useGetUserQuery } from 'src/redux/apiSlice'\nimport { UserCircleIcon } from '@heroicons/react/24/outline'\nexport default function Component({ x, y }: GridPosition) {\n const {\n data: user,\n isLoading,\n isSuccess,\n isError,\n error\n } = useGetUserQuery();",
"score": 0.8267641067504883
},
{
"filename": "src/lib/__test__/database.test.ts",
"retrieved_chunk": " expect(user).toEqual({ username: \"Bob\", completedMissions: [] });\n });\n it(\"should add completed missions\", async () => {\n await fs.setUser({username: 'Bob'});\n await fs.addCompletedMission({username: 'Bob', missionId: 'Mission0001aweifjwek'});\n const firstUserResponse = await fs.getUser({username: 'Bob'});\n expect(firstUserResponse).toEqual({\n \"username\": \"Bob\",\n completedMissions: ['Mission0001aweifjwek']\n });",
"score": 0.8261824250221252
},
{
"filename": "src/lib/database.ts",
"retrieved_chunk": " const completedMissions = snapshot.data()?.completedMissions || [];\n return { username, completedMissions }\n }\n async addCompletedMission({ username, missionId }: { username: string, missionId: string }): Promise<any> {\n const { completedMissions } = await this.getUser({ username });\n const updatedMissions = [...completedMissions, missionId]\n return this.setUser({\n username,\n completedMissions: updatedMissions,\n });",
"score": 0.8259354829788208
}
] |
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": 0.9057180285453796
},
{
"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": 0.8150423169136047
},
{
"filename": "src/libs/suiModel/suiOwnedObject.ts",
"retrieved_chunk": "import { Infer } from 'superstruct';\nimport {\n getObjectChanges,\n SuiTransactionBlockResponse,\n ObjectCallArg,\n ObjectId,\n} from '@mysten/sui.js';\nexport class SuiOwnedObject {\n public readonly objectId: string;\n public version?: number | string;",
"score": 0.8097106218338013
},
{
"filename": "src/libs/suiModel/index.ts",
"retrieved_chunk": "export { SuiOwnedObject } from './suiOwnedObject';\nexport { SuiSharedObject } from './suiSharedObject';",
"score": 0.8042099475860596
},
{
"filename": "src/libs/suiModel/suiSharedObject.ts",
"retrieved_chunk": "import { Infer } from 'superstruct';\nimport { ObjectCallArg, ObjectId } from '@mysten/sui.js';\nexport class SuiSharedObject {\n public readonly objectId: string;\n public initialSharedVersion?: number | string;\n constructor(param: {\n objectId: string;\n initialSharedVersion?: number;\n mutable?: boolean;\n }) {",
"score": 0.7940456867218018
}
] |
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": " 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": 0.8049834370613098
},
{
"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": 0.7680557370185852
},
{
"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": 0.7666555643081665
},
{
"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": 0.7647216320037842
},
{
"filename": "src/suiKit.ts",
"retrieved_chunk": " recipients,\n amounts\n );\n return this.signAndSendTxn(tx, derivePathParams);\n }\n async transferCoin(\n recipient: string,\n amount: number,\n coinType: string,\n derivePathParams?: DerivePathParams",
"score": 0.7645779848098755
}
] |
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/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": 0.8763760328292847
},
{
"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": 0.8631308078765869
},
{
"filename": "src/libs/suiAccountManager/index.ts",
"retrieved_chunk": "import { Ed25519Keypair } from '@mysten/sui.js';\nimport { getKeyPair } from './keypair';\nimport { hexOrBase64ToUint8Array, normalizePrivateKey } from './util';\nimport { generateMnemonic } from './crypto';\nimport type { AccountMangerParams, DerivePathParams } from 'src/types';\nexport class SuiAccountManager {\n private mnemonics: string;\n private secretKey: string;\n public currentKeyPair: Ed25519Keypair;\n public currentAddress: string;",
"score": 0.8448559045791626
},
{
"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": 0.8119083642959595
},
{
"filename": "src/libs/suiInteractor/suiInteractor.ts",
"retrieved_chunk": "export class SuiInteractor {\n public readonly providers: JsonRpcProvider[];\n public currentProvider: JsonRpcProvider;\n constructor(fullNodeUrls: string[]) {\n if (fullNodeUrls.length === 0)\n throw new Error('fullNodeUrls must not be empty');\n this.providers = fullNodeUrls.map(\n (url) => new JsonRpcProvider(new Connection({ fullnode: url }))\n );\n this.currentProvider = this.providers[0];",
"score": 0.8108282685279846
}
] |
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": 0.9670401811599731
},
{
"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": 0.8862841129302979
},
{
"filename": "src/libs/suiModel/suiOwnedObject.ts",
"retrieved_chunk": "import { Infer } from 'superstruct';\nimport {\n getObjectChanges,\n SuiTransactionBlockResponse,\n ObjectCallArg,\n ObjectId,\n} from '@mysten/sui.js';\nexport class SuiOwnedObject {\n public readonly objectId: string;\n public version?: number | string;",
"score": 0.8130831718444824
},
{
"filename": "src/libs/suiInteractor/suiInteractor.ts",
"retrieved_chunk": " for (const provider of this.providers) {\n try {\n const objects = await provider.multiGetObjects({ ids, options });\n const parsedObjects = objects.map((object) => {\n const objectId = getObjectId(object);\n const objectType = getObjectType(object);\n const objectVersion = getObjectVersion(object);\n const objectDigest = object.data ? object.data.digest : undefined;\n const initialSharedVersion = getSharedObjectInitialVersion(object);\n const objectFields = getObjectFields(object);",
"score": 0.805509626865387
},
{
"filename": "src/libs/suiModel/index.ts",
"retrieved_chunk": "export { SuiOwnedObject } from './suiOwnedObject';\nexport { SuiSharedObject } from './suiSharedObject';",
"score": 0.8008818030357361
}
] |
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": 0.9454087018966675
},
{
"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": 0.8696964979171753
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": " }\n transferSui(recipient: string, amount: number) {\n return this.transferSuiToMany([recipient], [amount]);\n }\n takeAmountFromCoins(coins: SuiObjectArg[], amount: number) {\n const tx = this.txBlock;\n const coinObjects = convertArgs(this.txBlock, coins);\n const mergedCoin = coinObjects[0];\n if (coins.length > 1) {\n tx.mergeCoins(mergedCoin, coinObjects.slice(1));",
"score": 0.8387060761451721
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": " return this.txBlock.getDigest({ provider });\n }\n get gas() {\n return this.txBlock.gas;\n }\n get blockData() {\n return this.txBlock.blockData;\n }\n transferObjects(objects: SuiObjectArg[], recipient: string) {\n const tx = this.txBlock;",
"score": 0.838455855846405
},
{
"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": 0.8347324132919312
}
] |
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": 0.9674447774887085
},
{
"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": 0.884861946105957
},
{
"filename": "src/libs/suiModel/suiOwnedObject.ts",
"retrieved_chunk": "import { Infer } from 'superstruct';\nimport {\n getObjectChanges,\n SuiTransactionBlockResponse,\n ObjectCallArg,\n ObjectId,\n} from '@mysten/sui.js';\nexport class SuiOwnedObject {\n public readonly objectId: string;\n public version?: number | string;",
"score": 0.8096622228622437
},
{
"filename": "src/libs/suiInteractor/suiInteractor.ts",
"retrieved_chunk": " for (const provider of this.providers) {\n try {\n const objects = await provider.multiGetObjects({ ids, options });\n const parsedObjects = objects.map((object) => {\n const objectId = getObjectId(object);\n const objectType = getObjectType(object);\n const objectVersion = getObjectVersion(object);\n const objectDigest = object.data ? object.data.digest : undefined;\n const initialSharedVersion = getSharedObjectInitialVersion(object);\n const objectFields = getObjectFields(object);",
"score": 0.8030749559402466
},
{
"filename": "src/libs/suiModel/index.ts",
"retrieved_chunk": "export { SuiOwnedObject } from './suiOwnedObject';\nexport { SuiSharedObject } from './suiSharedObject';",
"score": 0.798023521900177
}
] |
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": 0.876013994216919
},
{
"filename": "src/suiKit.ts",
"retrieved_chunk": " * @param derivePathParams\n */\n async transferSui(\n recipient: string,\n amount: number,\n derivePathParams?: DerivePathParams\n ) {\n const tx = new SuiTxBlock();\n tx.transferSui(recipient, amount);\n return this.signAndSendTxn(tx, derivePathParams);",
"score": 0.8581010103225708
},
{
"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": 0.8578504323959351
},
{
"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": 0.8555287718772888
},
{
"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": 0.8455464243888855
}
] |
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": 0.9686396718025208
},
{
"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": 0.8878381252288818
},
{
"filename": "src/libs/suiModel/suiOwnedObject.ts",
"retrieved_chunk": "import { Infer } from 'superstruct';\nimport {\n getObjectChanges,\n SuiTransactionBlockResponse,\n ObjectCallArg,\n ObjectId,\n} from '@mysten/sui.js';\nexport class SuiOwnedObject {\n public readonly objectId: string;\n public version?: number | string;",
"score": 0.8150985240936279
},
{
"filename": "src/libs/suiInteractor/suiInteractor.ts",
"retrieved_chunk": " for (const provider of this.providers) {\n try {\n const objects = await provider.multiGetObjects({ ids, options });\n const parsedObjects = objects.map((object) => {\n const objectId = getObjectId(object);\n const objectType = getObjectType(object);\n const objectVersion = getObjectVersion(object);\n const objectDigest = object.data ? object.data.digest : undefined;\n const initialSharedVersion = getSharedObjectInitialVersion(object);\n const objectFields = getObjectFields(object);",
"score": 0.8066691160202026
},
{
"filename": "src/libs/suiModel/index.ts",
"retrieved_chunk": "export { SuiOwnedObject } from './suiOwnedObject';\nexport { SuiSharedObject } from './suiSharedObject';",
"score": 0.8048611879348755
}
] |
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": 0.9200422763824463
},
{
"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": 0.852832019329071
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": " return this.txBlock.getDigest({ provider });\n }\n get gas() {\n return this.txBlock.gas;\n }\n get blockData() {\n return this.txBlock.blockData;\n }\n transferObjects(objects: SuiObjectArg[], recipient: string) {\n const tx = this.txBlock;",
"score": 0.8340634107589722
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": " }\n transferSui(recipient: string, amount: number) {\n return this.transferSuiToMany([recipient], [amount]);\n }\n takeAmountFromCoins(coins: SuiObjectArg[], amount: number) {\n const tx = this.txBlock;\n const coinObjects = convertArgs(this.txBlock, coins);\n const mergedCoin = coinObjects[0];\n if (coins.length > 1) {\n tx.mergeCoins(mergedCoin, coinObjects.slice(1));",
"score": 0.8288043141365051
},
{
"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": 0.8248004913330078
}
] |
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/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": 0.8675570487976074
},
{
"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": 0.8466514945030212
},
{
"filename": "src/libs/suiAccountManager/index.ts",
"retrieved_chunk": "import { Ed25519Keypair } from '@mysten/sui.js';\nimport { getKeyPair } from './keypair';\nimport { hexOrBase64ToUint8Array, normalizePrivateKey } from './util';\nimport { generateMnemonic } from './crypto';\nimport type { AccountMangerParams, DerivePathParams } from 'src/types';\nexport class SuiAccountManager {\n private mnemonics: string;\n private secretKey: string;\n public currentKeyPair: Ed25519Keypair;\n public currentAddress: string;",
"score": 0.8365378379821777
},
{
"filename": "src/libs/suiInteractor/suiInteractor.ts",
"retrieved_chunk": "export class SuiInteractor {\n public readonly providers: JsonRpcProvider[];\n public currentProvider: JsonRpcProvider;\n constructor(fullNodeUrls: string[]) {\n if (fullNodeUrls.length === 0)\n throw new Error('fullNodeUrls must not be empty');\n this.providers = fullNodeUrls.map(\n (url) => new JsonRpcProvider(new Connection({ fullnode: url }))\n );\n this.currentProvider = this.providers[0];",
"score": 0.8249219655990601
},
{
"filename": "src/libs/suiAccountManager/keypair.ts",
"retrieved_chunk": " mnemonics: string,\n derivePathParams: DerivePathParams = {}\n) => {\n const derivePath = getDerivePathForSUI(derivePathParams);\n return Ed25519Keypair.deriveKeypair(mnemonics, derivePath);\n};",
"score": 0.80414879322052
}
] |
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": 0.8990994095802307
},
{
"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": 0.855622410774231
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": " return this.txBlock.getDigest({ provider });\n }\n get gas() {\n return this.txBlock.gas;\n }\n get blockData() {\n return this.txBlock.blockData;\n }\n transferObjects(objects: SuiObjectArg[], recipient: string) {\n const tx = this.txBlock;",
"score": 0.8419862985610962
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": " }\n transferSui(recipient: string, amount: number) {\n return this.transferSuiToMany([recipient], [amount]);\n }\n takeAmountFromCoins(coins: SuiObjectArg[], amount: number) {\n const tx = this.txBlock;\n const coinObjects = convertArgs(this.txBlock, coins);\n const mergedCoin = coinObjects[0];\n if (coins.length > 1) {\n tx.mergeCoins(mergedCoin, coinObjects.slice(1));",
"score": 0.833857536315918
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": "import {\n TransactionBlock,\n SUI_SYSTEM_STATE_OBJECT_ID,\n TransactionExpiration,\n SuiObjectRef,\n SharedObjectRef,\n JsonRpcProvider,\n TransactionType,\n Transactions,\n ObjectCallArg,",
"score": 0.8323851823806763
}
] |
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/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": 0.896683931350708
},
{
"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": 0.8806005716323853
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": " }\n transferSui(recipient: string, amount: number) {\n return this.transferSuiToMany([recipient], [amount]);\n }\n takeAmountFromCoins(coins: SuiObjectArg[], amount: number) {\n const tx = this.txBlock;\n const coinObjects = convertArgs(this.txBlock, coins);\n const mergedCoin = coinObjects[0];\n if (coins.length > 1) {\n tx.mergeCoins(mergedCoin, coinObjects.slice(1));",
"score": 0.8797106146812439
},
{
"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": 0.8766146898269653
},
{
"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": 0.8756183385848999
}
] |
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": " * @param typeArgs the type arguments of the move call, such as `['0x2::sui::SUI']`\n */\n moveCall(\n target: string,\n args: (SuiTxArg | SuiVecTxArg)[] = [],\n typeArgs: string[] = []\n ) {\n // a regex for pattern `${string}::${string}::${string}`\n const regex =\n /(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/;",
"score": 0.8570213317871094
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": " }\n transferSui(recipient: string, amount: number) {\n return this.transferSuiToMany([recipient], [amount]);\n }\n takeAmountFromCoins(coins: SuiObjectArg[], amount: number) {\n const tx = this.txBlock;\n const coinObjects = convertArgs(this.txBlock, coins);\n const mergedCoin = coinObjects[0];\n if (coins.length > 1) {\n tx.mergeCoins(mergedCoin, coinObjects.slice(1));",
"score": 0.856277585029602
},
{
"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": 0.8537874221801758
},
{
"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": 0.8516921997070312
},
{
"filename": "src/libs/suiTxBuilder/index.ts",
"retrieved_chunk": " upgrade(...args: Parameters<(typeof Transactions)['Upgrade']>) {\n return this.txBlock.upgrade(...args);\n }\n makeMoveVec(...args: Parameters<(typeof Transactions)['MakeMoveVec']>) {\n return this.txBlock.makeMoveVec(...args);\n }\n /**\n * @description Move call\n * @param target `${string}::${string}::${string}`, e.g. `0x3::sui_system::request_add_stake`\n * @param args the arguments of the move call, such as `['0x1', '0x2']`",
"score": 0.8489792346954346
}
] |
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/redux/gameSlice.ts",
"retrieved_chunk": " playerPosition,\n inventory,\n allItemsCollected: false,\n isSavingMission: false,\n }\n },\n moveUp: state => {\n if (state.playerPosition.y < 2 && !state.isSavingMission) state.playerPosition.y += 1\n },\n moveDown: state => {",
"score": 0.8632587194442749
},
{
"filename": "src/redux/gameSlice.ts",
"retrieved_chunk": " if (state.playerPosition.y > 0 && !state.isSavingMission) state.playerPosition.y -= 1\n },\n moveLeft: state => {\n if (state.playerPosition.x > 0 && !state.isSavingMission) state.playerPosition.x -= 1\n },\n moveRight: state => {\n if (state.playerPosition.x < 2 && !state.isSavingMission) state.playerPosition.x += 1\n },\n collectItem: (state) => {\n const itemIndex = state.inventory.findIndex(item => {",
"score": 0.8601014614105225
},
{
"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": 0.8482965230941772
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " const [addCompletedMission] = useAddCompletedMissionMutation()\n const dispatch = useAppDispatch()\n const { playerPosition, mission, inventory, allItemsCollected, isSavingMission } = useAppSelector((state: RootState) => state.game)\n const playerIsOnTile = playerPosition.x === x && playerPosition.y === y;\n const playerIsOnStartingTile = playerPosition.x === 0 && playerPosition.y === 0;\n const playerIsLeftOfTile = playerPosition.x + 1 === x && playerPosition.y === y;\n const playerIsRightOfTile = playerPosition.x - 1 === x && playerPosition.y === y;\n const playerIsAboveTile = playerPosition.x === x && playerPosition.y - 1 === y;\n const playerIsBelowTile = playerPosition.x === x && playerPosition.y + 1 === y;\n const playerIsOnAdjacentTile = playerIsLeftOfTile || playerIsRightOfTile || playerIsAboveTile || playerIsBelowTile;",
"score": 0.8313912153244019
},
{
"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": 0.8270387649536133
}
] |
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": " 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": 0.8869340419769287
},
{
"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": 0.8826268911361694
},
{
"filename": "src/lib/database.ts",
"retrieved_chunk": " const completedMissions = snapshot.data()?.completedMissions || [];\n return { username, completedMissions }\n }\n async addCompletedMission({ username, missionId }: { username: string, missionId: string }): Promise<any> {\n const { completedMissions } = await this.getUser({ username });\n const updatedMissions = [...completedMissions, missionId]\n return this.setUser({\n username,\n completedMissions: updatedMissions,\n });",
"score": 0.8427404761314392
},
{
"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": 0.826087474822998
},
{
"filename": "src/components/tile.tsx",
"retrieved_chunk": " </button>\n )}\n {allItemsCollected && tileIsFinalTile && playerIsOnTile && (\n <button\n className='bg-blue-500 hover:bg-blue-700 text-white p-2 rounded disabled:bg-slate-50 disabled:text-slate-500'\n disabled={!playerIsOnTile || isSavingMission} onClick={completeMission}\n >\n {isSavingMission ? 'Saving...' : 'Complete'}\n </button>\n )}",
"score": 0.8247157335281372
}
] |
typescript
|
return dispatch(collectItem())
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.