@coin-voyage/shared 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,179 @@
1
+ import { CurrencyWithBalance, PayOrder } from "../common/index";
2
+ import { DepositPayOrderParams, PaymentDetails, PaymentDetailsParams, PayOrderQuoteParams, SalePayOrderParams } from "../types/api";
3
+ import { APIEnvironment } from "./config";
4
+ export declare class ApiClient {
5
+ private readonly apiKey;
6
+ private readonly environment?;
7
+ private readonly sessionId?;
8
+ private readonly version?;
9
+ constructor({ apiKey, sessionId, environment: env, version }: {
10
+ apiKey: string;
11
+ sessionId?: string;
12
+ environment?: APIEnvironment;
13
+ version?: string;
14
+ });
15
+ private request;
16
+ /**
17
+ * Fetches a PayOrder by its ID.
18
+ *
19
+ * Retrieves a PayOrder object from the API using the provided payOrderId.
20
+ * This function requires an API key for authentication.
21
+ *
22
+ * @param {string} payOrderId - The unique identifier of the PayOrder.
23
+ * @returns {Promise<PayOrder | undefined>} - The PayOrder object if the request is successful.
24
+ *
25
+ * @example
26
+ * const payOrder = await getPayOrder('123456');
27
+ */
28
+ getPayOrder(payOrderId: string): Promise<PayOrder | undefined>;
29
+ /**
30
+ * Creates a `DEPOSIT` type PayOrder.
31
+ *
32
+ * Generates a PayOrder of type `DEPOSIT` with the provided parameters.
33
+ * This function ensures the request parameters are valid using a schema validation.
34
+ *
35
+ * @param {DepositPayOrderParams} params - Parameters required to create a deposit PayOrder.
36
+ * @param {boolean} [throwOnFailure] - Whether to throw an error if the request fails.
37
+ * @returns {Promise<PayOrder | undefined>} - The PayOrder object if the request is successful.
38
+ *
39
+ * @example
40
+ * const apiKey = 'yourApiKey';
41
+ * const depositOrderParams = {
42
+ * amount: 1000,
43
+ * currency: 'USD',
44
+ * metadata: { description: 'Deposit for account' }
45
+ * };
46
+ * const depositPayOrder = await createDepositPayOrder(depositOrderParams);
47
+ */
48
+ createDepositPayOrder(params: DepositPayOrderParams, throwOnFailure?: boolean): Promise<PayOrder | undefined>;
49
+ /**
50
+ * Generates a `sale` type PayOrder.
51
+ *
52
+ * Creates a `sale` type PayOrder with a fixed valueOut `destination_value_usd`.
53
+ * This function should be executed
54
+ *
55
+ * and a SHA-512 hash signature of the concatenated API key, secret, and timestamp.
56
+ *
57
+ * @param {SalePayOrderParams} params - destination_value_usd and metadata for this payOrder.
58
+ * @param {string} signature - signature generated by the `generateAuthorizationSignature` function.
59
+ * @returns {PayOrder | undefined} - A PayOrder object if the request was successful.
60
+ *
61
+ * @example
62
+ * const apiKey = 'yourApiKey';
63
+ * const apiSecret = 'yourApiSecret';
64
+ * const authSignature = generateAuthorizationSignature(apiKey, apiSecret);
65
+ * const payOrder = await createSalePayOrder(
66
+ * createSalePayOrder({
67
+ * destination_value_usd: 200,
68
+ * metadata: {
69
+ * items: [
70
+ * {
71
+ * name: "t-shirt",
72
+ * description: "a nice t-shirt",
73
+ * image: "https://example.com/tshirt.jpg",
74
+ * quantity: 1,
75
+ * unit_price: 200,
76
+ * currency: "USD"
77
+ * }
78
+ * ]
79
+ * }}, authSignature)
80
+ */
81
+ createSalePayOrder(params: SalePayOrderParams, signature: string): Promise<PayOrder | undefined>;
82
+ /**
83
+ * Generates a PayOrder Quote.
84
+ *
85
+ * Creates a PayOrder Quote for an existing PayOrder by providing wallet information and chain details.
86
+ * This function requires an API key for authentication.
87
+ *
88
+ * @param {string} orderId - The unique identifier of the PayOrder for which the quote is requested.
89
+ * @param {PayOrderQuoteParams} quoteParams - Contains `wallet_address`, `chain_type`, chain_id`.
90
+ * @returns {CurrencyWithBalance[] | undefined} - An array of PayTokens if the request was successful.
91
+ *
92
+ * @example
93
+ * const orderId = 'existingOrderId';
94
+ * const apiKey = 'yourApiKey';
95
+ * const quoteParams = {
96
+ * wallet_address: '0x1234...abcd',
97
+ * chain_type: ChainType.EVM,
98
+ * chain_id: 1 // Ethereum Mainnet
99
+ * };
100
+ *
101
+ * const payOrderQuote = await payOrderQuote(orderId, quoteParams, apiKey);
102
+
103
+ */
104
+ payOrderQuote(orderId: string, quoteParams: PayOrderQuoteParams): Promise<CurrencyWithBalance[] | undefined>;
105
+ /**
106
+ * Retrieves payment details for a specific PayOrder.
107
+ *
108
+ * This function fetches payment details associated with a specific PayOrder ID.
109
+ * It allows specifying the token and blockchain network (via `outTokenAddress` and `outChainId`)
110
+ * to retrieve source currency information, as well as a refund address for the transaction.
111
+ *
112
+ * The request is authenticated using the provided API key in the headers.
113
+ *
114
+ * @param {PaymentDetailsParams} params - Parameters to retrieve the payment details.
115
+ * @param {string} params.payOrderId - The unique identifier of the PayOrder for which payment details are fetched.
116
+ * @param {string} [params.outTokenAddress] - (Optional) The token address of the source currency.
117
+ * @param {ChainId} params.outChainId - The blockchain network ID where the token resides.
118
+ * @param {string} params.refundAddress - The address where funds will be refunded in case of a failed transaction.
119
+ *
120
+ * @returns {Promise<PaymentDetails | undefined>} - The payment details object if the request is successful.
121
+ *
122
+ * @example
123
+ * const paymentDetails = await payOrderPaymentDetails({
124
+ * payOrderId: '12345',
125
+ * outTokenAddress: '0x1234567890abcdef1234567890abcdef12345678',
126
+ * outChainId: 1,
127
+ * refundAddress: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
128
+ * });
129
+ *
130
+ * console.log(paymentDetails);
131
+ */
132
+ payOrderPaymentDetails(params: PaymentDetailsParams): Promise<PaymentDetails | undefined>;
133
+ /**
134
+ * Processes a PayOrder transaction.
135
+ *
136
+ * This function triggers the processing of a PayOrder by providing the transaction hash
137
+ * that represents the payment on the blockchain. The request is authenticated using an API key.
138
+ *
139
+ * @param {Object} params - Parameters required to process the PayOrder.
140
+ * @param {string} params.payOrderId - The unique identifier of the PayOrder to be processed.
141
+ * @param {string} params.sourceTransactionHash - The transaction hash representing the payment on the blockchain.
142
+ *
143
+ * @returns {Promise<void>}
144
+ *
145
+ * @example
146
+ * const processedPayment = await processPayOrder({
147
+ * payOrderId: '12345',
148
+ * sourceTransactionHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
149
+ * });
150
+ *
151
+ * console.log(processedPayment);
152
+ */
153
+ processPayOrder(payOrderId: string, sourceTransactionHash: string): Promise<void>;
154
+ /**
155
+ * Generates an authorization signature for API requests.
156
+ *
157
+ * ⚠️ **Warning:** This function should only be run on the server.
158
+ * It uses the API secret, which must remain confidential. Running this
159
+ * code in a client-side environment risks exposing sensitive information
160
+ * to end users or malicious actors.
161
+ *
162
+ * This function creates a signed authorization string using the provided API key and secret.
163
+ * The generated string includes the API key, a timestamp (in seconds since epoch),
164
+ * and a SHA-512 hash signature of the concatenated API key, secret, and timestamp.
165
+ *
166
+ * @param {string} apiSecret - The API secret used to generate the signature.
167
+ * @returns {string} - A formatted authorization string in the format:
168
+ * `APIKey=<apiKey>,signature=<signature>,timestamp=<timestamp>`.
169
+ *
170
+ * @example
171
+ * const apiKey = 'yourApiKey';
172
+ * const apiSecret = 'yourApiSecret';
173
+ * const authSignature = generateAuthorizationSignature(apiKey, apiSecret);
174
+ * console.log(authSignature);
175
+ * // Example output:
176
+ * // APIKey=yourApiKey,signature=2ee76043a90a...,timestamp=1737106896
177
+ */
178
+ generateAuthorizationSignature(apiSecret: string): string;
179
+ }
@@ -0,0 +1,266 @@
1
+ import { createHash } from "crypto";
2
+ import { z } from "zod";
3
+ import { PayOrderMode, zDepositPayOrder, zPayOrderMetadata } from "../common/index";
4
+ import { API_URL } from "./config";
5
+ import { fetchApi } from "./fetcher";
6
+ export class ApiClient {
7
+ constructor({ apiKey, sessionId, environment: env = "production", version }) {
8
+ this.apiKey = apiKey;
9
+ this.environment = env;
10
+ this.sessionId = sessionId;
11
+ this.version = version;
12
+ }
13
+ async request(args) {
14
+ const baseUrl = API_URL[this.environment ?? "production"];
15
+ return fetchApi({
16
+ ...args,
17
+ path: `${baseUrl}/${args.path}`,
18
+ options: {
19
+ ...args.options,
20
+ headers: {
21
+ ...args.options?.headers,
22
+ "X-API-KEY": this.apiKey,
23
+ ...this.sessionId ? { "X-Session-ID": this.sessionId } : {},
24
+ ...this.version ? { "X-Client-Version": this.version } : {},
25
+ },
26
+ },
27
+ throwOnFailure: args.throwOnFailure,
28
+ });
29
+ }
30
+ /**
31
+ * Fetches a PayOrder by its ID.
32
+ *
33
+ * Retrieves a PayOrder object from the API using the provided payOrderId.
34
+ * This function requires an API key for authentication.
35
+ *
36
+ * @param {string} payOrderId - The unique identifier of the PayOrder.
37
+ * @returns {Promise<PayOrder | undefined>} - The PayOrder object if the request is successful.
38
+ *
39
+ * @example
40
+ * const payOrder = await getPayOrder('123456');
41
+ */
42
+ async getPayOrder(payOrderId) {
43
+ return this.request({ path: `pay-orders/${payOrderId}` });
44
+ }
45
+ /**
46
+ * Creates a `DEPOSIT` type PayOrder.
47
+ *
48
+ * Generates a PayOrder of type `DEPOSIT` with the provided parameters.
49
+ * This function ensures the request parameters are valid using a schema validation.
50
+ *
51
+ * @param {DepositPayOrderParams} params - Parameters required to create a deposit PayOrder.
52
+ * @param {boolean} [throwOnFailure] - Whether to throw an error if the request fails.
53
+ * @returns {Promise<PayOrder | undefined>} - The PayOrder object if the request is successful.
54
+ *
55
+ * @example
56
+ * const apiKey = 'yourApiKey';
57
+ * const depositOrderParams = {
58
+ * amount: 1000,
59
+ * currency: 'USD',
60
+ * metadata: { description: 'Deposit for account' }
61
+ * };
62
+ * const depositPayOrder = await createDepositPayOrder(depositOrderParams);
63
+ */
64
+ async createDepositPayOrder(params, throwOnFailure) {
65
+ const result = zDepositPayOrder.safeParse(params);
66
+ if (!result.success)
67
+ return;
68
+ return this.request({
69
+ path: `pay-orders`,
70
+ options: {
71
+ method: "POST",
72
+ body: JSON.stringify({ mode: PayOrderMode.DEPOSIT, ...params }),
73
+ },
74
+ throwOnFailure: throwOnFailure,
75
+ });
76
+ }
77
+ /**
78
+ * Generates a `sale` type PayOrder.
79
+ *
80
+ * Creates a `sale` type PayOrder with a fixed valueOut `destination_value_usd`.
81
+ * This function should be executed
82
+ *
83
+ * and a SHA-512 hash signature of the concatenated API key, secret, and timestamp.
84
+ *
85
+ * @param {SalePayOrderParams} params - destination_value_usd and metadata for this payOrder.
86
+ * @param {string} signature - signature generated by the `generateAuthorizationSignature` function.
87
+ * @returns {PayOrder | undefined} - A PayOrder object if the request was successful.
88
+ *
89
+ * @example
90
+ * const apiKey = 'yourApiKey';
91
+ * const apiSecret = 'yourApiSecret';
92
+ * const authSignature = generateAuthorizationSignature(apiKey, apiSecret);
93
+ * const payOrder = await createSalePayOrder(
94
+ * createSalePayOrder({
95
+ * destination_value_usd: 200,
96
+ * metadata: {
97
+ * items: [
98
+ * {
99
+ * name: "t-shirt",
100
+ * description: "a nice t-shirt",
101
+ * image: "https://example.com/tshirt.jpg",
102
+ * quantity: 1,
103
+ * unit_price: 200,
104
+ * currency: "USD"
105
+ * }
106
+ * ]
107
+ * }}, authSignature)
108
+ */
109
+ async createSalePayOrder(params, signature) {
110
+ try {
111
+ if (params.metadata)
112
+ zPayOrderMetadata.parse(params.metadata);
113
+ return this.request({
114
+ path: "pay-orders", options: {
115
+ method: "POST",
116
+ body: JSON.stringify({ mode: PayOrderMode.SALE, ...params }),
117
+ headers: { Authorization: signature },
118
+ },
119
+ }); // Ensure the API key is set in the headers
120
+ }
121
+ catch (err) {
122
+ if (err instanceof z.ZodError) {
123
+ throw new Error(err.errors.map(e => e.message).join(", "));
124
+ }
125
+ throw err;
126
+ }
127
+ }
128
+ /**
129
+ * Generates a PayOrder Quote.
130
+ *
131
+ * Creates a PayOrder Quote for an existing PayOrder by providing wallet information and chain details.
132
+ * This function requires an API key for authentication.
133
+ *
134
+ * @param {string} orderId - The unique identifier of the PayOrder for which the quote is requested.
135
+ * @param {PayOrderQuoteParams} quoteParams - Contains `wallet_address`, `chain_type`, chain_id`.
136
+ * @returns {CurrencyWithBalance[] | undefined} - An array of PayTokens if the request was successful.
137
+ *
138
+ * @example
139
+ * const orderId = 'existingOrderId';
140
+ * const apiKey = 'yourApiKey';
141
+ * const quoteParams = {
142
+ * wallet_address: '0x1234...abcd',
143
+ * chain_type: ChainType.EVM,
144
+ * chain_id: 1 // Ethereum Mainnet
145
+ * };
146
+ *
147
+ * const payOrderQuote = await payOrderQuote(orderId, quoteParams, apiKey);
148
+
149
+ */
150
+ async payOrderQuote(orderId, quoteParams) {
151
+ return this.request({
152
+ path: `pay-orders/${orderId}/quote`,
153
+ options: {
154
+ method: "POST",
155
+ body: JSON.stringify(quoteParams),
156
+ },
157
+ });
158
+ }
159
+ /**
160
+ * Retrieves payment details for a specific PayOrder.
161
+ *
162
+ * This function fetches payment details associated with a specific PayOrder ID.
163
+ * It allows specifying the token and blockchain network (via `outTokenAddress` and `outChainId`)
164
+ * to retrieve source currency information, as well as a refund address for the transaction.
165
+ *
166
+ * The request is authenticated using the provided API key in the headers.
167
+ *
168
+ * @param {PaymentDetailsParams} params - Parameters to retrieve the payment details.
169
+ * @param {string} params.payOrderId - The unique identifier of the PayOrder for which payment details are fetched.
170
+ * @param {string} [params.outTokenAddress] - (Optional) The token address of the source currency.
171
+ * @param {ChainId} params.outChainId - The blockchain network ID where the token resides.
172
+ * @param {string} params.refundAddress - The address where funds will be refunded in case of a failed transaction.
173
+ *
174
+ * @returns {Promise<PaymentDetails | undefined>} - The payment details object if the request is successful.
175
+ *
176
+ * @example
177
+ * const paymentDetails = await payOrderPaymentDetails({
178
+ * payOrderId: '12345',
179
+ * outTokenAddress: '0x1234567890abcdef1234567890abcdef12345678',
180
+ * outChainId: 1,
181
+ * refundAddress: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
182
+ * });
183
+ *
184
+ * console.log(paymentDetails);
185
+ */
186
+ async payOrderPaymentDetails(params) {
187
+ const { payOrderId, outTokenAddress, outChainId, refundAddress } = params;
188
+ return this.request({
189
+ path: `pay-orders/${payOrderId}/payment-details`,
190
+ options: {
191
+ method: "POST",
192
+ body: JSON.stringify({
193
+ source_currency: {
194
+ address: outTokenAddress,
195
+ chain_id: outChainId,
196
+ },
197
+ refund_address: refundAddress,
198
+ }),
199
+ },
200
+ });
201
+ }
202
+ /**
203
+ * Processes a PayOrder transaction.
204
+ *
205
+ * This function triggers the processing of a PayOrder by providing the transaction hash
206
+ * that represents the payment on the blockchain. The request is authenticated using an API key.
207
+ *
208
+ * @param {Object} params - Parameters required to process the PayOrder.
209
+ * @param {string} params.payOrderId - The unique identifier of the PayOrder to be processed.
210
+ * @param {string} params.sourceTransactionHash - The transaction hash representing the payment on the blockchain.
211
+ *
212
+ * @returns {Promise<void>}
213
+ *
214
+ * @example
215
+ * const processedPayment = await processPayOrder({
216
+ * payOrderId: '12345',
217
+ * sourceTransactionHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
218
+ * });
219
+ *
220
+ * console.log(processedPayment);
221
+ */
222
+ async processPayOrder(payOrderId, sourceTransactionHash) {
223
+ return this.request({
224
+ path: `pay-orders/${payOrderId}/process?tx_hash=${sourceTransactionHash}`,
225
+ options: { method: "GET" },
226
+ });
227
+ }
228
+ /**
229
+ * Generates an authorization signature for API requests.
230
+ *
231
+ * ⚠️ **Warning:** This function should only be run on the server.
232
+ * It uses the API secret, which must remain confidential. Running this
233
+ * code in a client-side environment risks exposing sensitive information
234
+ * to end users or malicious actors.
235
+ *
236
+ * This function creates a signed authorization string using the provided API key and secret.
237
+ * The generated string includes the API key, a timestamp (in seconds since epoch),
238
+ * and a SHA-512 hash signature of the concatenated API key, secret, and timestamp.
239
+ *
240
+ * @param {string} apiSecret - The API secret used to generate the signature.
241
+ * @returns {string} - A formatted authorization string in the format:
242
+ * `APIKey=<apiKey>,signature=<signature>,timestamp=<timestamp>`.
243
+ *
244
+ * @example
245
+ * const apiKey = 'yourApiKey';
246
+ * const apiSecret = 'yourApiSecret';
247
+ * const authSignature = generateAuthorizationSignature(apiKey, apiSecret);
248
+ * console.log(authSignature);
249
+ * // Example output:
250
+ * // APIKey=yourApiKey,signature=2ee76043a90a...,timestamp=1737106896
251
+ */
252
+ generateAuthorizationSignature(apiSecret) {
253
+ // Get the current timestamp as a string
254
+ const timestamp = Math.floor(Date.now() / 1000).toString();
255
+ // Create the data string
256
+ const data = this.apiKey + apiSecret + timestamp;
257
+ // Create a SHA-512 hash of the data
258
+ const hash = createHash('sha512');
259
+ hash.update(data);
260
+ // Encode the hash as a hexadecimal string
261
+ const signature = hash.digest('hex');
262
+ // Format the final string
263
+ return `APIKey=${this.apiKey},signature=${signature},timestamp=${timestamp}`;
264
+ }
265
+ }
266
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAiC,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEnH,OAAO,EAAE,OAAO,EAAkB,MAAM,UAAU,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,MAAM,OAAO,SAAS;IAMpB,YAAY,EACV,MAAM,EACN,SAAS,EACT,WAAW,EAAE,GAAG,GAAG,YAAY,EAC/B,OAAO,EAMR;QACC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,WAAW,GAAG,GAAG,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAEO,KAAK,CAAC,OAAO,CAAI,IAAuC;QAC9D,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,WAAW,IAAI,YAAY,CAAC,CAAC;QAC1D,OAAO,QAAQ,CAAI;YACjB,GAAG,IAAI;YACP,IAAI,EAAE,GAAG,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE;YAC/B,OAAO,EAAE;gBACP,GAAG,IAAI,CAAC,OAAO;gBACf,OAAO,EAAE;oBACP,GAAG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ACnB,eAAe,EAAE;wBACf,OAAO,EAAE,eAAe;wBACxB,QAAQ,EAAE,UAAU;qBACrB;oBACD,cAAc,EAAE,aAAa;iBAC9B,CAAC;aACH;SACF,CAAC,CAAC;IACL,CAAC;IAGD;;;;;;;;;;;;;;;;;;;MAmBE;IACF,KAAK,CAAC,eAAe,CAAC,UAAkB,EAAE,qBAA6B;QACrE,OAAO,IAAI,CAAC,OAAO,CAAO;YACxB,IAAI,EAAE,cAAc,UAAU,oBAAoB,qBAAqB,EAAE;YACzE,OAAO,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE;SAC3B,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,8BAA8B,CAAC,SAAiB;QAC9C,wCAAwC;QACxC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC;QAE3D,yBAAyB;QACzB,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,GAAG,SAAS,GAAG,SAAS,CAAC;QAEjD,oCAAoC;QACpC,MAAM,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;QAClC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAElB,0CAA0C;QAC1C,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAErC,0BAA0B;QAC1B,OAAO,UAAU,IAAI,CAAC,MAAM,cAAc,SAAS,cAAc,SAAS,EAAE,CAAC;IAC/E,CAAC;CACF"}
@@ -1 +1,2 @@
1
- export declare const API_URL = "https://api.coinvoyage.io";
1
+ export declare const API_URL: Record<string, string>;
2
+ export type APIEnvironment = keyof typeof API_URL;
@@ -1,2 +1,5 @@
1
- export const API_URL = "https://api.coinvoyage.io";
1
+ export const API_URL = {
2
+ "development": "https://acc-api.coinvoyage.io",
3
+ "production": "https://api.coinvoyage.io"
4
+ };
2
5
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/api/config.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,2BAA2B,CAAA"}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/api/config.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAA2B;IAC3C,aAAa,EAAE,+BAA+B;IAC9C,YAAY,EAAE,2BAA2B;CAC5C,CAAA"}
@@ -1,7 +1,6 @@
1
- import { API_URL } from "./config";
2
1
  export async function fetchApi(opts) {
3
2
  try {
4
- const response = await fetch(`${API_URL}/${opts.path}`, {
3
+ const response = await fetch(opts.path, {
5
4
  ...opts.options,
6
5
  headers: {
7
6
  ...opts.options?.headers,
@@ -1 +1 @@
1
- {"version":3,"file":"fetcher.js","sourceRoot":"","sources":["../../src/api/fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAQnC,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAI,IAAqB;IACnD,IAAI,CAAC;QACD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,EAAE;YACpD,GAAG,IAAI,CAAC,OAAO;YACf,OAAO,EAAE;gBACL,GAAG,IAAI,CAAC,OAAO,EAAE,OAAO;gBACxB,cAAc,EAAE,kBAAkB;gBAClC,iBAAiB,EAAE,mBAAmB;aACzC;SACJ,CAAC,CAAC;QACH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACf,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;YACnC,OAAO,CAAC,KAAK,CACT,IAAI,CAAC,SAAS,CAAC;gBACX,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,MAAM,EAAE,QAAQ,CAAC,MAAM;gBACvB,UAAU,EAAE,QAAQ,CAA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AI,cAAc,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC/D,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACtB,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;AACL,CAAC"}
@@ -1,3 +1,3 @@
1
+ export * from "./client";
1
2
  export * from "./config";
2
3
  export * from "./fetcher";
3
- export * from "./pay-order";
package/dist/api/index.js CHANGED
@@ -1,4 +1,4 @@
1
+ export * from "./client";
1
2
  export * from "./config";
2
3
  export * from "./fetcher";
3
- export * from "./pay-order";
4
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,aAAa,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA;AACxB,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA"}
@@ -0,0 +1,82 @@
1
+ import { PayOrderMetadata, CurrencyBase, ChainType, ChainId, PayOrderStatus, CurrencyWithAmount, CurrencyAmount } from "../common";
2
+ /** PayOrder parameters. The payOrder is created only after user taps pay. */
3
+ export interface DepositPayOrderParams {
4
+ /**
5
+ * Metadata to attach to the payOrder.
6
+ */
7
+ metadata?: PayOrderMetadata;
8
+ /**
9
+ * Value in USD received from the Deposit.
10
+ */
11
+ destination_value_usd?: number;
12
+ /**
13
+ * Desired output token + chain.
14
+ */
15
+ destination_currency: CurrencyBase;
16
+ /**
17
+ * Output amount to deposit in human readable format (e.g. "10" for 10 tokens).
18
+ */
19
+ destination_amount?: string;
20
+ /**
21
+ * Receiving address for the deposit.
22
+ */
23
+ receiving_address: string;
24
+ }
25
+ export type SalePayOrderParams = {
26
+ /**
27
+ * Metadata to attach to the payOrder.
28
+ */
29
+ metadata?: PayOrderMetadata;
30
+ /**
31
+ * Expected value in USD to be received from the Sale.
32
+ */
33
+ destination_value_usd: number;
34
+ /**
35
+ * Expected token on what chain to receive the value from the Sale.
36
+ */
37
+ destination_currency?: CurrencyBase;
38
+ /**
39
+ * Expected receiving address to receive the value from the Sale.
40
+ */
41
+ receiving_address?: string;
42
+ } | {
43
+ /**
44
+ * Metadata to attach to the payOrder.
45
+ */
46
+ metadata?: PayOrderMetadata;
47
+ /**
48
+ * Expected token on what chain to receive the value from the Sale.
49
+ */
50
+ destination_currency: CurrencyBase;
51
+ /**
52
+ * Expected amount to be received from the Sale.
53
+ */
54
+ destination_amount: string;
55
+ /**
56
+ * Expected receiving address to receive the value from the Sale.
57
+ */
58
+ receiving_address?: string;
59
+ };
60
+ export type PayOrderQuoteParams = {
61
+ wallet_address: string;
62
+ chain_type: ChainType;
63
+ chain_id?: ChainId;
64
+ };
65
+ export type PaymentDetailsParams = {
66
+ payOrderId: string;
67
+ outTokenAddress?: string;
68
+ outChainId: ChainId;
69
+ refundAddress: string;
70
+ };
71
+ export type PaymentDetails = {
72
+ payorder_id: string;
73
+ status: PayOrderStatus;
74
+ expires_at: Date;
75
+ refund_address: string;
76
+ deposit_address: string;
77
+ receiving_address?: string;
78
+ source_currency: CurrencyWithAmount;
79
+ source_amount: CurrencyAmount;
80
+ destination_currency?: CurrencyWithAmount;
81
+ destination_amount?: CurrencyAmount;
82
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/types/api.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@coin-voyage/shared",
3
3
  "description": "Shared utilities for Coin Voyage",
4
- "version": "0.0.10",
4
+ "version": "0.0.12",
5
5
  "private": false,
6
6
  "sideEffects": false,
7
7
  "exports": {
@@ -1,233 +0,0 @@
1
- import { ChainId, ChainType, CurrencyAmount, CurrencyBase, CurrencyWithAmount, CurrencyWithBalance, PayOrder, PayOrderMetadata, PayOrderStatus } from "../common/index";
2
- /**
3
- * Fetches a PayOrder by its ID.
4
- *
5
- * Retrieves a PayOrder object from the API using the provided payOrderId.
6
- * This function requires an API key for authentication.
7
- *
8
- * @param {string} payOrderId - The unique identifier of the PayOrder.
9
- * @param {string} apiKey - The API key required for authentication.
10
- * @returns {Promise<PayOrder | undefined>} - The PayOrder object if the request is successful.
11
- *
12
- * @example
13
- * const apiKey = 'yourApiKey';
14
- * const payOrder = await getPayOrder('123456', apiKey);
15
- */
16
- export declare function getPayOrder(payOrderId: string, apiKey: string): Promise<PayOrder | undefined>;
17
- /** PayOrder parameters. The payOrder is created only after user taps pay. */
18
- export interface DepositPayOrderParams {
19
- /**
20
- * Metadata to attach to the payOrder.
21
- */
22
- metadata?: PayOrderMetadata;
23
- /**
24
- * Value in USD received from the Deposit.
25
- */
26
- destination_value_usd?: number;
27
- /**
28
- * Desired output token + chain.
29
- */
30
- destination_currency: CurrencyBase;
31
- /**
32
- * Output amount to deposit in human readable format (e.g. "10" for 10 tokens).
33
- */
34
- destination_amount?: string;
35
- /**
36
- * Receiving address for the deposit.
37
- */
38
- receiving_address: string;
39
- }
40
- /**
41
- * Creates a `DEPOSIT` type PayOrder.
42
- *
43
- * Generates a PayOrder of type `DEPOSIT` with the provided parameters.
44
- * This function ensures the request parameters are valid using a schema validation.
45
- *
46
- * @param {DepositPayOrderParams} createOrderParams - Parameters required to create a deposit PayOrder.
47
- * @param {string} apiKey - The API key required for authentication.
48
- * @param {boolean} [throwOnFailure] - Whether to throw an error if the request fails.
49
- * @returns {Promise<PayOrder | undefined>} - The PayOrder object if the request is successful.
50
- *
51
- * @example
52
- * const apiKey = 'yourApiKey';
53
- * const depositOrderParams = {
54
- * amount: 1000,
55
- * currency: 'USD',
56
- * metadata: { description: 'Deposit for account' }
57
- * };
58
- * const depositPayOrder = await createDepositPayOrder(depositOrderParams, apiKey);
59
- */
60
- export declare function createDepositPayOrder(createOrderParams: DepositPayOrderParams, apiKey: string, throwOnFailure?: boolean): Promise<PayOrder | undefined>;
61
- export type SalePayOrderParams = {
62
- /**
63
- * Metadata to attach to the payOrder.
64
- */
65
- metadata?: PayOrderMetadata;
66
- /**
67
- * Expected value in USD to be received from the Sale.
68
- */
69
- destination_value_usd: number;
70
- /**
71
- * Expected token on what chain to receive the value from the Sale.
72
- */
73
- destination_currency?: CurrencyBase;
74
- /**
75
- * Expected receiving address to receive the value from the Sale.
76
- */
77
- receiving_address?: string;
78
- } | {
79
- /**
80
- * Metadata to attach to the payOrder.
81
- */
82
- metadata?: PayOrderMetadata;
83
- /**
84
- * Expected token on what chain to receive the value from the Sale.
85
- */
86
- destination_currency: CurrencyBase;
87
- /**
88
- * Expected amount to be received from the Sale.
89
- */
90
- destination_amount: string;
91
- /**
92
- * Expected receiving address to receive the value from the Sale.
93
- */
94
- receiving_address?: string;
95
- };
96
- /**
97
- * Generates a `sale` type PayOrder.
98
- *
99
- * Creates a `sale` type PayOrder with a fixed valueOut `destination_value_usd`.
100
- * This function should be executed
101
- *
102
- * and a SHA-512 hash signature of the concatenated API key, secret, and timestamp.
103
- *
104
- * @param {SalePayOrderParams} payOrderParams - destination_value_usd and metadata for this payOrder.
105
- * @param {string} signature - signature generated by the `generateAuthorizationSignature` function.
106
- * @returns {PayOrder | undefined} - A PayOrder object if the request was successful.
107
- *
108
- * @example
109
- * const apiKey = 'yourApiKey';
110
- * const apiSecret = 'yourApiSecret';
111
- * const authSignature = generateAuthorizationSignature(apiKey, apiSecret);
112
- * const payOrder = await createSalePayOrder(
113
- * createSalePayOrder({
114
- * destination_value_usd: 200,
115
- * metadata: {
116
- * items: [
117
- * {
118
- * name: "t-shirt",
119
- * description: "a nice t-shirt",
120
- * image: "https://example.com/tshirt.jpg",
121
- * quantity: 1,
122
- * unit_price: 200,
123
- * currency: "USD"
124
- * }
125
- * ]
126
- * }}, authSignature)
127
- */
128
- export declare function createSalePayOrder(createOrderParams: SalePayOrderParams, signature: string): Promise<PayOrder | undefined>;
129
- export type PayOrderQuoteParams = {
130
- wallet_address: string;
131
- chain_type: ChainType;
132
- chain_id?: ChainId;
133
- };
134
- /**
135
- * Generates a PayOrder Quote.
136
- *
137
- * Creates a PayOrder Quote for an existing PayOrder by providing wallet information and chain details.
138
- * This function requires an API key for authentication.
139
- *
140
- * @param {string} orderId - The unique identifier of the PayOrder for which the quote is requested.
141
- * @param {PayOrderQuoteParams} quoteParams - Contains `wallet_address`, `chain_type`, chain_id`.
142
- * @param {string} apiKey - The API key for authorization.
143
- * @returns {CurrencyWithBalance[] | undefined} - An array of PayTokens if the request was successful.
144
- *
145
- * @example
146
- * const orderId = 'existingOrderId';
147
- * const apiKey = 'yourApiKey';
148
- * const quoteParams = {
149
- * wallet_address: '0x1234...abcd',
150
- * chain_type: ChainType.EVM,
151
- * chain_id: 1 // Ethereum Mainnet
152
- * };
153
- *
154
- * const payOrderQuote = await payOrderQuote(orderId, quoteParams, apiKey);
155
-
156
- */
157
- export declare function payOrderQuote(orderId: string, quoteParams: PayOrderQuoteParams, apiKey: string): Promise<CurrencyWithBalance[] | undefined>;
158
- export type PaymentDetailsParams = {
159
- payOrderId: string;
160
- outTokenAddress?: string;
161
- outChainId: ChainId;
162
- refundAddress: string;
163
- apiKey: string;
164
- };
165
- export type PaymentDetails = {
166
- payorder_id: string;
167
- status: PayOrderStatus;
168
- expires_at: Date;
169
- refund_address: string;
170
- deposit_address: string;
171
- receiving_address?: string;
172
- source_currency: CurrencyWithAmount;
173
- source_amount: CurrencyAmount;
174
- destination_currency?: CurrencyWithAmount;
175
- destination_amount?: CurrencyAmount;
176
- };
177
- /**
178
- * Retrieves payment details for a specific PayOrder.
179
- *
180
- * This function fetches payment details associated with a specific PayOrder ID.
181
- * It allows specifying the token and blockchain network (via `outTokenAddress` and `outChainId`)
182
- * to retrieve source currency information, as well as a refund address for the transaction.
183
- *
184
- * The request is authenticated using the provided API key in the headers.
185
- *
186
- * @param {PaymentDetailsParams} params - Parameters to retrieve the payment details.
187
- * @param {string} params.payOrderId - The unique identifier of the PayOrder for which payment details are fetched.
188
- * @param {string} [params.outTokenAddress] - (Optional) The token address of the source currency.
189
- * @param {ChainId} params.outChainId - The blockchain network ID where the token resides.
190
- * @param {string} params.refundAddress - The address where funds will be refunded in case of a failed transaction.
191
- * @param {string} params.apiKey - The API key used to authenticate the request.
192
- *
193
- * @returns {Promise<PaymentDetails | undefined>} - The payment details object if the request is successful.
194
- *
195
- * @example
196
- * const paymentDetails = await payOrderPaymentDetails({
197
- * payOrderId: '12345',
198
- * outTokenAddress: '0x1234567890abcdef1234567890abcdef12345678',
199
- * outChainId: 1,
200
- * refundAddress: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
201
- * apiKey: 'yourApiKey'
202
- * });
203
- *
204
- * console.log(paymentDetails);
205
- */
206
- export declare function payOrderPaymentDetails({ payOrderId, outTokenAddress, outChainId, refundAddress, apiKey }: PaymentDetailsParams): Promise<PaymentDetails | undefined>;
207
- /**
208
- * Processes a PayOrder transaction.
209
- *
210
- * This function triggers the processing of a PayOrder by providing the transaction hash
211
- * that represents the payment on the blockchain. The request is authenticated using an API key.
212
- *
213
- * @param {Object} params - Parameters required to process the PayOrder.
214
- * @param {string} params.payOrderId - The unique identifier of the PayOrder to be processed.
215
- * @param {string} params.sourceTransactionHash - The transaction hash representing the payment on the blockchain.
216
- * @param {string} params.apiKey - The API key used to authenticate the request.
217
- *
218
- * @returns {Promise<void>}
219
- *
220
- * @example
221
- * const processedPayment = await processPayOrder({
222
- * payOrderId: '12345',
223
- * sourceTransactionHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
224
- * apiKey: 'yourApiKey'
225
- * });
226
- *
227
- * console.log(processedPayment);
228
- */
229
- export declare function processPayOrder({ payOrderId, sourceTransactionHash, apiKey }: {
230
- payOrderId: string;
231
- sourceTransactionHash: string;
232
- apiKey: string;
233
- }): Promise<void>;
@@ -1,238 +0,0 @@
1
- import { z } from "zod";
2
- import { PayOrderMode, zDepositPayOrder, zPayOrderMetadata } from "../common/index";
3
- import { fetchApi } from "./fetcher";
4
- /**
5
- * Fetches a PayOrder by its ID.
6
- *
7
- * Retrieves a PayOrder object from the API using the provided payOrderId.
8
- * This function requires an API key for authentication.
9
- *
10
- * @param {string} payOrderId - The unique identifier of the PayOrder.
11
- * @param {string} apiKey - The API key required for authentication.
12
- * @returns {Promise<PayOrder | undefined>} - The PayOrder object if the request is successful.
13
- *
14
- * @example
15
- * const apiKey = 'yourApiKey';
16
- * const payOrder = await getPayOrder('123456', apiKey);
17
- */
18
- export async function getPayOrder(payOrderId, apiKey) {
19
- return fetchApi({
20
- path: `pay-orders/${payOrderId}`,
21
- options: {
22
- headers: {
23
- "X-API-KEY": apiKey
24
- }
25
- }
26
- });
27
- }
28
- /**
29
- * Creates a `DEPOSIT` type PayOrder.
30
- *
31
- * Generates a PayOrder of type `DEPOSIT` with the provided parameters.
32
- * This function ensures the request parameters are valid using a schema validation.
33
- *
34
- * @param {DepositPayOrderParams} createOrderParams - Parameters required to create a deposit PayOrder.
35
- * @param {string} apiKey - The API key required for authentication.
36
- * @param {boolean} [throwOnFailure] - Whether to throw an error if the request fails.
37
- * @returns {Promise<PayOrder | undefined>} - The PayOrder object if the request is successful.
38
- *
39
- * @example
40
- * const apiKey = 'yourApiKey';
41
- * const depositOrderParams = {
42
- * amount: 1000,
43
- * currency: 'USD',
44
- * metadata: { description: 'Deposit for account' }
45
- * };
46
- * const depositPayOrder = await createDepositPayOrder(depositOrderParams, apiKey);
47
- */
48
- export async function createDepositPayOrder(createOrderParams, apiKey, throwOnFailure) {
49
- const result = zDepositPayOrder.safeParse(createOrderParams);
50
- if (result.error) {
51
- return;
52
- }
53
- return fetchApi({
54
- path: `pay-orders`, options: {
55
- method: "POST",
56
- body: JSON.stringify({
57
- mode: PayOrderMode.DEPOSIT,
58
- ...createOrderParams
59
- }),
60
- headers: {
61
- "X-API-KEY": apiKey
62
- }
63
- },
64
- throwOnFailure: throwOnFailure
65
- });
66
- }
67
- /**
68
- * Generates a `sale` type PayOrder.
69
- *
70
- * Creates a `sale` type PayOrder with a fixed valueOut `destination_value_usd`.
71
- * This function should be executed
72
- *
73
- * and a SHA-512 hash signature of the concatenated API key, secret, and timestamp.
74
- *
75
- * @param {SalePayOrderParams} payOrderParams - destination_value_usd and metadata for this payOrder.
76
- * @param {string} signature - signature generated by the `generateAuthorizationSignature` function.
77
- * @returns {PayOrder | undefined} - A PayOrder object if the request was successful.
78
- *
79
- * @example
80
- * const apiKey = 'yourApiKey';
81
- * const apiSecret = 'yourApiSecret';
82
- * const authSignature = generateAuthorizationSignature(apiKey, apiSecret);
83
- * const payOrder = await createSalePayOrder(
84
- * createSalePayOrder({
85
- * destination_value_usd: 200,
86
- * metadata: {
87
- * items: [
88
- * {
89
- * name: "t-shirt",
90
- * description: "a nice t-shirt",
91
- * image: "https://example.com/tshirt.jpg",
92
- * quantity: 1,
93
- * unit_price: 200,
94
- * currency: "USD"
95
- * }
96
- * ]
97
- * }}, authSignature)
98
- */
99
- export async function createSalePayOrder(createOrderParams, signature) {
100
- try {
101
- if (createOrderParams?.metadata) {
102
- zPayOrderMetadata.parse(createOrderParams.metadata);
103
- }
104
- return fetchApi({
105
- path: `pay-orders`, options: {
106
- method: "POST",
107
- body: JSON.stringify({
108
- mode: PayOrderMode.SALE,
109
- ...createOrderParams
110
- }),
111
- headers: {
112
- "Authorization": signature
113
- }
114
- }
115
- });
116
- }
117
- catch (err) {
118
- if (err instanceof z.ZodError) {
119
- throw new Error(err.errors.map(e => e.message).join(", "));
120
- }
121
- throw err;
122
- }
123
- }
124
- /**
125
- * Generates a PayOrder Quote.
126
- *
127
- * Creates a PayOrder Quote for an existing PayOrder by providing wallet information and chain details.
128
- * This function requires an API key for authentication.
129
- *
130
- * @param {string} orderId - The unique identifier of the PayOrder for which the quote is requested.
131
- * @param {PayOrderQuoteParams} quoteParams - Contains `wallet_address`, `chain_type`, chain_id`.
132
- * @param {string} apiKey - The API key for authorization.
133
- * @returns {CurrencyWithBalance[] | undefined} - An array of PayTokens if the request was successful.
134
- *
135
- * @example
136
- * const orderId = 'existingOrderId';
137
- * const apiKey = 'yourApiKey';
138
- * const quoteParams = {
139
- * wallet_address: '0x1234...abcd',
140
- * chain_type: ChainType.EVM,
141
- * chain_id: 1 // Ethereum Mainnet
142
- * };
143
- *
144
- * const payOrderQuote = await payOrderQuote(orderId, quoteParams, apiKey);
145
-
146
- */
147
- export async function payOrderQuote(orderId, quoteParams, apiKey) {
148
- return fetchApi({
149
- path: `pay-orders/${orderId}/quote`, options: {
150
- method: "POST",
151
- body: JSON.stringify({
152
- ...quoteParams
153
- }),
154
- headers: {
155
- "X-API-KEY": apiKey
156
- },
157
- }
158
- });
159
- }
160
- /**
161
- * Retrieves payment details for a specific PayOrder.
162
- *
163
- * This function fetches payment details associated with a specific PayOrder ID.
164
- * It allows specifying the token and blockchain network (via `outTokenAddress` and `outChainId`)
165
- * to retrieve source currency information, as well as a refund address for the transaction.
166
- *
167
- * The request is authenticated using the provided API key in the headers.
168
- *
169
- * @param {PaymentDetailsParams} params - Parameters to retrieve the payment details.
170
- * @param {string} params.payOrderId - The unique identifier of the PayOrder for which payment details are fetched.
171
- * @param {string} [params.outTokenAddress] - (Optional) The token address of the source currency.
172
- * @param {ChainId} params.outChainId - The blockchain network ID where the token resides.
173
- * @param {string} params.refundAddress - The address where funds will be refunded in case of a failed transaction.
174
- * @param {string} params.apiKey - The API key used to authenticate the request.
175
- *
176
- * @returns {Promise<PaymentDetails | undefined>} - The payment details object if the request is successful.
177
- *
178
- * @example
179
- * const paymentDetails = await payOrderPaymentDetails({
180
- * payOrderId: '12345',
181
- * outTokenAddress: '0x1234567890abcdef1234567890abcdef12345678',
182
- * outChainId: 1,
183
- * refundAddress: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
184
- * apiKey: 'yourApiKey'
185
- * });
186
- *
187
- * console.log(paymentDetails);
188
- */
189
- export async function payOrderPaymentDetails({ payOrderId, outTokenAddress, outChainId, refundAddress, apiKey }) {
190
- return fetchApi({
191
- path: `pay-orders/${payOrderId}/payment-details`, options: {
192
- method: "POST",
193
- body: JSON.stringify({
194
- source_currency: {
195
- address: outTokenAddress,
196
- chain_id: outChainId
197
- },
198
- refund_address: refundAddress
199
- }),
200
- headers: {
201
- "X-API-KEY": apiKey
202
- },
203
- }
204
- });
205
- }
206
- /**
207
- * Processes a PayOrder transaction.
208
- *
209
- * This function triggers the processing of a PayOrder by providing the transaction hash
210
- * that represents the payment on the blockchain. The request is authenticated using an API key.
211
- *
212
- * @param {Object} params - Parameters required to process the PayOrder.
213
- * @param {string} params.payOrderId - The unique identifier of the PayOrder to be processed.
214
- * @param {string} params.sourceTransactionHash - The transaction hash representing the payment on the blockchain.
215
- * @param {string} params.apiKey - The API key used to authenticate the request.
216
- *
217
- * @returns {Promise<void>}
218
- *
219
- * @example
220
- * const processedPayment = await processPayOrder({
221
- * payOrderId: '12345',
222
- * sourceTransactionHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
223
- * apiKey: 'yourApiKey'
224
- * });
225
- *
226
- * console.log(processedPayment);
227
- */
228
- export async function processPayOrder({ payOrderId, sourceTransactionHash, apiKey }) {
229
- return fetchApi({
230
- path: `pay-orders/${payOrderId}/process?tx_hash=${sourceTransactionHash}`, options: {
231
- method: "GET",
232
- headers: {
233
- "X-API-KEY": apiKey
234
- },
235
- }
236
- });
237
- }
238
- //# sourceMappingURL=pay-order.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pay-order.js","sourceRoot":"","sources":["../../src/api/pay-order.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAyH,YAAY,EAAkB,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC3N,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAA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