@ton-pay/api 0.1.0

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.
package/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # @ton-pay/api
2
+
3
+ Core API functions for TonPay SDK - create transfers, check status, and verify webhooks.
4
+
5
+ ## Documentation
6
+
7
+ Full documentation: https://docs.tonpay.tech
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @ton-pay/api
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```typescript
18
+ import {
19
+ createTonPayTransfer,
20
+ getTonPayTransferByReference,
21
+ getTonPayTransferByBodyHash,
22
+ verifySignature,
23
+ TON,
24
+ USDT,
25
+ } from "@ton-pay/api";
26
+
27
+ // Create a TonPay transfer
28
+ const transfer = await createTonPayTransfer(
29
+ {
30
+ amount: 10.5,
31
+ asset: TON,
32
+ recipientAddr: "EQC...",
33
+ senderAddr: "EQC...",
34
+ commentToSender: "Payment for order #123",
35
+ commentToRecipient: "Thank you!",
36
+ },
37
+ {
38
+ chain: "mainnet",
39
+ apiKey: "your-api-key",
40
+ }
41
+ );
42
+
43
+ // Get transfer status by reference
44
+ const transferInfo = await getTonPayTransferByReference(transfer.reference, {
45
+ chain: "mainnet",
46
+ apiKey: "your-api-key",
47
+ });
48
+
49
+ // Verify webhook signature
50
+ const isValid = verifySignature(webhookPayload, signature, apiSecret);
51
+ ```
52
+
53
+ ## API
54
+
55
+ ### Transfer Functions
56
+
57
+ - `createTonPayTransfer(params, options)` - Create a new TON Pay transfer
58
+ - `getTonPayTransferByReference(reference, options)` - Get transfer info by reference
59
+ - `getTonPayTransferByBodyHash(bodyHash, options)` - Get transfer info by body hash
60
+
61
+ ### Webhook Utils
62
+
63
+ - `verifySignature(payload, signature, apiSecret)` - Verify webhook signature
64
+
65
+ ### Constants
66
+
67
+ - `TON` - TON coin identifier
68
+ - `USDT` - USDT jetton identifier
69
+
70
+ ## License
71
+
72
+ Apache License 2.0
@@ -0,0 +1,202 @@
1
+ type Chain = "mainnet" | "testnet";
2
+
3
+ type APIOptions = {
4
+ chain?: Chain;
5
+ apiKey?: string;
6
+ };
7
+
8
+ /**
9
+ * @param amount - in human readable format, 10.5 for example
10
+ * @param asset - jetton master address or TON coin address for TON transfer
11
+ * @param recipientAddr - recipient wallet address. Optional if API key is provided - defaults to the merchant's wallet address from the admin panel
12
+ * @param senderAddr - payer wallet address
13
+ * @param queryId - only for Jetton
14
+ * @param commentToSender - a comment that will be displayed in the user's wallet when signing a transaction
15
+ * @param commentToRecipient - a comment that will be displayed in the recipient's wallet when receiving a transaction
16
+ */
17
+ type CreateTonPayTransferParams = {
18
+ amount: number;
19
+ asset: string;
20
+ recipientAddr?: string;
21
+ senderAddr: string;
22
+ queryId?: number;
23
+ commentToSender?: string;
24
+ commentToRecipient?: string;
25
+ };
26
+ /**
27
+ * @param message - a built message that will be sent to the recipient's wallet
28
+ * @param bodyBase64Hash - a hash of the transaction message content in Base64 format
29
+ * @param reference - a reference ID for the transaction, used for tracking the transaction
30
+ */
31
+ type CreateTonPayTransferResponse = {
32
+ message: {
33
+ address: string;
34
+ amount: string;
35
+ payload: string;
36
+ };
37
+ bodyBase64Hash: string;
38
+ reference: string;
39
+ };
40
+
41
+ /**
42
+ * Creates a message for TON Pay transfer
43
+ * @param params - the parameters for the transfer
44
+ * @param options - the options for the transfer
45
+ * @returns the message for the transfer and data for tracking the transfer
46
+ */
47
+ declare const createTonPayTransfer: (params: CreateTonPayTransferParams, options?: APIOptions) => Promise<CreateTonPayTransferResponse>;
48
+
49
+ /**
50
+ * @param amount - the amount of the transfer in human readable format
51
+ * @param rawAmount - the amount of the transfer in base units
52
+ * @param senderAddr - the address of the sender wallet
53
+ * @param recipientAddr - the address of the recipient wallet
54
+ * @param asset - the address of the asset
55
+ * @param assetTicker - the ticker of the asset (e.g. "USDT")
56
+ * @param status - the status of the transfer ("success" or "failed")
57
+ * @param reference - the reference of the transfer
58
+ * @param bodyBase64Hash - the hash of the body of the transfer in Base64 format
59
+ * @param txHash - the hash of the transaction
60
+ * @param traceId - the id of the trace
61
+ * @param commentToSender - the comment to the sender wallet
62
+ * @param commentToRecipient - the comment to the recipient wallet
63
+ * @param date - the date of the transfer
64
+ * @param errorCode - the error code of the transfer
65
+ * @param errorMessage - the error message of the transfer
66
+ */
67
+ type CompletedTonPayTransferInfo = {
68
+ amount: string;
69
+ rawAmount: string;
70
+ senderAddr: string;
71
+ recipientAddr: string;
72
+ asset: string;
73
+ assetTicker?: string;
74
+ status: string;
75
+ reference: string;
76
+ bodyBase64Hash: string;
77
+ txHash: string;
78
+ traceId: string;
79
+ commentToSender?: string;
80
+ commentToRecipient?: string;
81
+ date: string;
82
+ errorCode?: number;
83
+ errorMessage?: string;
84
+ };
85
+
86
+ /**
87
+ * Gets a TON Pay transfer by reference
88
+ * @param reference - the reference of the transfer
89
+ * @param options - the options for the transfer
90
+ * @returns the transfer information
91
+ */
92
+ declare const getTonPayTransferByBodyHash: (bodyHash: string, options?: APIOptions) => Promise<CompletedTonPayTransferInfo>;
93
+
94
+ /**
95
+ * Gets a TON Pay transfer by reference
96
+ * @param reference - the reference of the transfer
97
+ * @param options - the options for the transfer
98
+ * @returns the transfer information
99
+ */
100
+ declare const getTonPayTransferByReference: (reference: string, options?: APIOptions) => Promise<CompletedTonPayTransferInfo>;
101
+
102
+ /**
103
+ * @param bodyHash - the hash of the transaction message content
104
+ */
105
+ type GetTonPayTransferByBodyHashParams = {
106
+ bodyHash: string;
107
+ };
108
+
109
+ /**
110
+ * @param reference - the reference of the transfer
111
+ */
112
+ type GetTonPayTransferByReferenceParams = {
113
+ reference: string;
114
+ };
115
+
116
+ /**
117
+ * Webhook event types
118
+ *
119
+ * @remarks
120
+ * - `transfer.completed` - Transfer completed (check `data.status` for success/failed)
121
+ * - `transfer.refunded` - Transfer was refunded (Coming Soon)
122
+ */
123
+ type WebhookEventType = "transfer.completed" | "transfer.refunded";
124
+
125
+ /**
126
+ * Base webhook payload structure
127
+ */
128
+ interface BaseWebhookPayload {
129
+ event: WebhookEventType;
130
+ timestamp: string;
131
+ }
132
+ /**
133
+ * Webhook payload for transfer.completed event
134
+ *
135
+ * @remarks
136
+ * Sent when a transfer is completed on the blockchain.
137
+ * Check `data.status` field to determine if transfer was "success" or "failed".
138
+ */
139
+ interface TransferCompletedWebhookPayload extends BaseWebhookPayload {
140
+ event: "transfer.completed";
141
+ data: CompletedTonPayTransferInfo;
142
+ }
143
+ /**
144
+ * Webhook payload for transfer.refunded event
145
+ *
146
+ * @remarks
147
+ * Coming Soon - Sent when a transfer is refunded
148
+ */
149
+ interface TransferRefundedWebhookPayload extends BaseWebhookPayload {
150
+ event: "transfer.refunded";
151
+ data: unknown;
152
+ }
153
+ /**
154
+ * Union type for all webhook payloads
155
+ *
156
+ * @remarks
157
+ * Currently only transfer.completed is supported.
158
+ * Additional events will be added in future updates.
159
+ */
160
+ type WebhookPayload = TransferCompletedWebhookPayload | TransferRefundedWebhookPayload;
161
+
162
+ declare const USDT = "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs";
163
+ declare const TON = "TON";
164
+
165
+ /**
166
+ * Verifies the HMAC-SHA256 signature of a payload
167
+ * @param payload - Raw JSON string or object to verify
168
+ * @param signature - The signature from X-TonPay-Signature header
169
+ * @param apiSecret - Your TON Pay webhook API secret
170
+ * @returns true if signature is valid, false otherwise
171
+ *
172
+ * @example
173
+ * ```typescript
174
+ * import { verifySignature } from "@ton-pay/api";
175
+ *
176
+ * // With raw string
177
+ * app.post("/webhook", (req, res) => {
178
+ * const signature = req.headers["x-tonpay-signature"] as string;
179
+ * const payload = JSON.stringify(req.body);
180
+ *
181
+ * if (!verifySignature(payload, signature, YOUR_API_SECRET)) {
182
+ * return res.status(401).json({ error: "Invalid signature" });
183
+ * }
184
+ *
185
+ * res.status(200).json({ received: true });
186
+ * });
187
+ *
188
+ * // With object (will be stringified automatically)
189
+ * app.post("/webhook", (req, res) => {
190
+ * const signature = req.headers["x-tonpay-signature"] as string;
191
+ *
192
+ * if (!verifySignature(req.body, signature, YOUR_API_SECRET)) {
193
+ * return res.status(401).json({ error: "Invalid signature" });
194
+ * }
195
+ *
196
+ * res.status(200).json({ received: true });
197
+ * });
198
+ * ```
199
+ */
200
+ declare function verifySignature(payload: string | object, signature: string, apiSecret: string): boolean;
201
+
202
+ export { type APIOptions, type Chain, type CompletedTonPayTransferInfo, type CreateTonPayTransferParams, type CreateTonPayTransferResponse, type GetTonPayTransferByBodyHashParams, type GetTonPayTransferByReferenceParams, TON, type TransferCompletedWebhookPayload, type TransferRefundedWebhookPayload, USDT, type WebhookEventType, type WebhookPayload, createTonPayTransfer, getTonPayTransferByBodyHash, getTonPayTransferByReference, verifySignature };
@@ -0,0 +1,202 @@
1
+ type Chain = "mainnet" | "testnet";
2
+
3
+ type APIOptions = {
4
+ chain?: Chain;
5
+ apiKey?: string;
6
+ };
7
+
8
+ /**
9
+ * @param amount - in human readable format, 10.5 for example
10
+ * @param asset - jetton master address or TON coin address for TON transfer
11
+ * @param recipientAddr - recipient wallet address. Optional if API key is provided - defaults to the merchant's wallet address from the admin panel
12
+ * @param senderAddr - payer wallet address
13
+ * @param queryId - only for Jetton
14
+ * @param commentToSender - a comment that will be displayed in the user's wallet when signing a transaction
15
+ * @param commentToRecipient - a comment that will be displayed in the recipient's wallet when receiving a transaction
16
+ */
17
+ type CreateTonPayTransferParams = {
18
+ amount: number;
19
+ asset: string;
20
+ recipientAddr?: string;
21
+ senderAddr: string;
22
+ queryId?: number;
23
+ commentToSender?: string;
24
+ commentToRecipient?: string;
25
+ };
26
+ /**
27
+ * @param message - a built message that will be sent to the recipient's wallet
28
+ * @param bodyBase64Hash - a hash of the transaction message content in Base64 format
29
+ * @param reference - a reference ID for the transaction, used for tracking the transaction
30
+ */
31
+ type CreateTonPayTransferResponse = {
32
+ message: {
33
+ address: string;
34
+ amount: string;
35
+ payload: string;
36
+ };
37
+ bodyBase64Hash: string;
38
+ reference: string;
39
+ };
40
+
41
+ /**
42
+ * Creates a message for TON Pay transfer
43
+ * @param params - the parameters for the transfer
44
+ * @param options - the options for the transfer
45
+ * @returns the message for the transfer and data for tracking the transfer
46
+ */
47
+ declare const createTonPayTransfer: (params: CreateTonPayTransferParams, options?: APIOptions) => Promise<CreateTonPayTransferResponse>;
48
+
49
+ /**
50
+ * @param amount - the amount of the transfer in human readable format
51
+ * @param rawAmount - the amount of the transfer in base units
52
+ * @param senderAddr - the address of the sender wallet
53
+ * @param recipientAddr - the address of the recipient wallet
54
+ * @param asset - the address of the asset
55
+ * @param assetTicker - the ticker of the asset (e.g. "USDT")
56
+ * @param status - the status of the transfer ("success" or "failed")
57
+ * @param reference - the reference of the transfer
58
+ * @param bodyBase64Hash - the hash of the body of the transfer in Base64 format
59
+ * @param txHash - the hash of the transaction
60
+ * @param traceId - the id of the trace
61
+ * @param commentToSender - the comment to the sender wallet
62
+ * @param commentToRecipient - the comment to the recipient wallet
63
+ * @param date - the date of the transfer
64
+ * @param errorCode - the error code of the transfer
65
+ * @param errorMessage - the error message of the transfer
66
+ */
67
+ type CompletedTonPayTransferInfo = {
68
+ amount: string;
69
+ rawAmount: string;
70
+ senderAddr: string;
71
+ recipientAddr: string;
72
+ asset: string;
73
+ assetTicker?: string;
74
+ status: string;
75
+ reference: string;
76
+ bodyBase64Hash: string;
77
+ txHash: string;
78
+ traceId: string;
79
+ commentToSender?: string;
80
+ commentToRecipient?: string;
81
+ date: string;
82
+ errorCode?: number;
83
+ errorMessage?: string;
84
+ };
85
+
86
+ /**
87
+ * Gets a TON Pay transfer by reference
88
+ * @param reference - the reference of the transfer
89
+ * @param options - the options for the transfer
90
+ * @returns the transfer information
91
+ */
92
+ declare const getTonPayTransferByBodyHash: (bodyHash: string, options?: APIOptions) => Promise<CompletedTonPayTransferInfo>;
93
+
94
+ /**
95
+ * Gets a TON Pay transfer by reference
96
+ * @param reference - the reference of the transfer
97
+ * @param options - the options for the transfer
98
+ * @returns the transfer information
99
+ */
100
+ declare const getTonPayTransferByReference: (reference: string, options?: APIOptions) => Promise<CompletedTonPayTransferInfo>;
101
+
102
+ /**
103
+ * @param bodyHash - the hash of the transaction message content
104
+ */
105
+ type GetTonPayTransferByBodyHashParams = {
106
+ bodyHash: string;
107
+ };
108
+
109
+ /**
110
+ * @param reference - the reference of the transfer
111
+ */
112
+ type GetTonPayTransferByReferenceParams = {
113
+ reference: string;
114
+ };
115
+
116
+ /**
117
+ * Webhook event types
118
+ *
119
+ * @remarks
120
+ * - `transfer.completed` - Transfer completed (check `data.status` for success/failed)
121
+ * - `transfer.refunded` - Transfer was refunded (Coming Soon)
122
+ */
123
+ type WebhookEventType = "transfer.completed" | "transfer.refunded";
124
+
125
+ /**
126
+ * Base webhook payload structure
127
+ */
128
+ interface BaseWebhookPayload {
129
+ event: WebhookEventType;
130
+ timestamp: string;
131
+ }
132
+ /**
133
+ * Webhook payload for transfer.completed event
134
+ *
135
+ * @remarks
136
+ * Sent when a transfer is completed on the blockchain.
137
+ * Check `data.status` field to determine if transfer was "success" or "failed".
138
+ */
139
+ interface TransferCompletedWebhookPayload extends BaseWebhookPayload {
140
+ event: "transfer.completed";
141
+ data: CompletedTonPayTransferInfo;
142
+ }
143
+ /**
144
+ * Webhook payload for transfer.refunded event
145
+ *
146
+ * @remarks
147
+ * Coming Soon - Sent when a transfer is refunded
148
+ */
149
+ interface TransferRefundedWebhookPayload extends BaseWebhookPayload {
150
+ event: "transfer.refunded";
151
+ data: unknown;
152
+ }
153
+ /**
154
+ * Union type for all webhook payloads
155
+ *
156
+ * @remarks
157
+ * Currently only transfer.completed is supported.
158
+ * Additional events will be added in future updates.
159
+ */
160
+ type WebhookPayload = TransferCompletedWebhookPayload | TransferRefundedWebhookPayload;
161
+
162
+ declare const USDT = "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs";
163
+ declare const TON = "TON";
164
+
165
+ /**
166
+ * Verifies the HMAC-SHA256 signature of a payload
167
+ * @param payload - Raw JSON string or object to verify
168
+ * @param signature - The signature from X-TonPay-Signature header
169
+ * @param apiSecret - Your TON Pay webhook API secret
170
+ * @returns true if signature is valid, false otherwise
171
+ *
172
+ * @example
173
+ * ```typescript
174
+ * import { verifySignature } from "@ton-pay/api";
175
+ *
176
+ * // With raw string
177
+ * app.post("/webhook", (req, res) => {
178
+ * const signature = req.headers["x-tonpay-signature"] as string;
179
+ * const payload = JSON.stringify(req.body);
180
+ *
181
+ * if (!verifySignature(payload, signature, YOUR_API_SECRET)) {
182
+ * return res.status(401).json({ error: "Invalid signature" });
183
+ * }
184
+ *
185
+ * res.status(200).json({ received: true });
186
+ * });
187
+ *
188
+ * // With object (will be stringified automatically)
189
+ * app.post("/webhook", (req, res) => {
190
+ * const signature = req.headers["x-tonpay-signature"] as string;
191
+ *
192
+ * if (!verifySignature(req.body, signature, YOUR_API_SECRET)) {
193
+ * return res.status(401).json({ error: "Invalid signature" });
194
+ * }
195
+ *
196
+ * res.status(200).json({ received: true });
197
+ * });
198
+ * ```
199
+ */
200
+ declare function verifySignature(payload: string | object, signature: string, apiSecret: string): boolean;
201
+
202
+ export { type APIOptions, type Chain, type CompletedTonPayTransferInfo, type CreateTonPayTransferParams, type CreateTonPayTransferResponse, type GetTonPayTransferByBodyHashParams, type GetTonPayTransferByReferenceParams, TON, type TransferCompletedWebhookPayload, type TransferRefundedWebhookPayload, USDT, type WebhookEventType, type WebhookPayload, createTonPayTransfer, getTonPayTransferByBodyHash, getTonPayTransferByReference, verifySignature };
package/dist/index.js ADDED
@@ -0,0 +1,91 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/common/const.ts
2
+ var BASE_URL = "https://tonpay.tech";
3
+ var TESTNET_BASE_URL = "https://testnet.tonpay.tech";
4
+
5
+ // src/common/get-base-url.ts
6
+ var getBaseUrl = (chain) => {
7
+ if (process.env.TONPAY_BASE_URL) {
8
+ return process.env.TONPAY_BASE_URL;
9
+ }
10
+ if (!chain || chain === "mainnet") {
11
+ return BASE_URL;
12
+ }
13
+ return TESTNET_BASE_URL;
14
+ };
15
+
16
+ // src/create-ton-pay-transfer/create-ton-pay-transfer.ts
17
+ var createTonPayTransfer = async (params, options) => {
18
+ const baseUrl = getBaseUrl(_optionalChain([options, 'optionalAccess', _ => _.chain]));
19
+ const headers = {
20
+ "Content-Type": "application/json",
21
+ ..._optionalChain([options, 'optionalAccess', _2 => _2.apiKey]) ? { "x-api-key": options.apiKey } : {}
22
+ };
23
+ const response = await fetch(`${baseUrl}/api/merchant/v1/create-transfer`, {
24
+ method: "POST",
25
+ body: JSON.stringify(params),
26
+ headers
27
+ });
28
+ if (!response.ok) {
29
+ throw new Error("Failed to create TON Pay transfer", {
30
+ cause: response.statusText
31
+ });
32
+ }
33
+ return response.json();
34
+ };
35
+
36
+ // src/get-ton-pay-transfer/get-ton-pay-transfer-by-body-hash.ts
37
+ var getTonPayTransferByBodyHash = async (bodyHash, options) => {
38
+ const baseUrl = getBaseUrl(_optionalChain([options, 'optionalAccess', _3 => _3.chain]));
39
+ const response = await fetch(
40
+ `${baseUrl}/api/merchant/v1/transfer?bodyHash=${bodyHash}`,
41
+ {
42
+ method: "GET"
43
+ }
44
+ );
45
+ if (!response.ok) {
46
+ throw new Error("Failed to get TON Pay transfer by body hash", {
47
+ cause: response.statusText
48
+ });
49
+ }
50
+ return response.json();
51
+ };
52
+
53
+ // src/get-ton-pay-transfer/get-ton-pay-transfer-by-reference.ts
54
+ var getTonPayTransferByReference = async (reference, options) => {
55
+ const baseUrl = getBaseUrl(_optionalChain([options, 'optionalAccess', _4 => _4.chain]));
56
+ const response = await fetch(
57
+ `${baseUrl}/api/merchant/v1/transfer?reference=${reference}`,
58
+ {
59
+ method: "GET"
60
+ }
61
+ );
62
+ if (!response.ok) {
63
+ throw new Error("Failed to get TON Pay transfer by reference", {
64
+ cause: response.statusText
65
+ });
66
+ }
67
+ return response.json();
68
+ };
69
+
70
+ // src/common/assets.ts
71
+ var USDT = "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs";
72
+ var TON = "TON";
73
+
74
+ // src/utils/verify-signature.ts
75
+ var _crypto = require('crypto');
76
+ function verifySignature(payload, signature, apiSecret) {
77
+ const payloadString = typeof payload === "string" ? payload : JSON.stringify(payload);
78
+ const hmac = _crypto.createHmac.call(void 0, "sha256", apiSecret);
79
+ hmac.update(payloadString);
80
+ const expectedSignature = `sha256=${hmac.digest("hex")}`;
81
+ return signature === expectedSignature;
82
+ }
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+ exports.TON = TON; exports.USDT = USDT; exports.createTonPayTransfer = createTonPayTransfer; exports.getTonPayTransferByBodyHash = getTonPayTransferByBodyHash; exports.getTonPayTransferByReference = getTonPayTransferByReference; exports.verifySignature = verifySignature;
91
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/ilya/work/tpn/ton-pay/packages/api/dist/index.js","../src/common/const.ts","../src/common/get-base-url.ts","../src/create-ton-pay-transfer/create-ton-pay-transfer.ts","../src/get-ton-pay-transfer/get-ton-pay-transfer-by-body-hash.ts","../src/get-ton-pay-transfer/get-ton-pay-transfer-by-reference.ts","../src/common/assets.ts","../src/utils/verify-signature.ts"],"names":[],"mappings":"AAAA;ACAO,IAAM,SAAA,EAAW,qBAAA;AACjB,IAAM,iBAAA,EAAmB,6BAAA;ADEhC;AACA;AEDO,IAAM,WAAA,EAAa,CAAC,KAAA,EAAA,GAAkB;AAE3C,EAAA,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,eAAA,EAAiB;AAC/B,IAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,eAAA;AAAA,EACrB;AACA,EAAA,GAAA,CAAI,CAAC,MAAA,GAAS,MAAA,IAAU,SAAA,EAAW;AACjC,IAAA,OAAO,QAAA;AAAA,EACT;AACA,EAAA,OAAO,gBAAA;AACT,CAAA;AFEA;AACA;AGHO,IAAM,qBAAA,EAAuB,MAAA,CAClC,MAAA,EACA,OAAA,EAAA,GAC0C;AAC1C,EAAA,MAAM,QAAA,EAAU,UAAA,iBAAW,OAAA,2BAAS,OAAK,CAAA;AACzC,EAAA,MAAM,QAAA,EAAU;AAAA,IACd,cAAA,EAAgB,kBAAA;AAAA,IAChB,mBAAI,OAAA,6BAAS,SAAA,EAAS,EAAE,WAAA,EAAa,OAAA,CAAQ,OAAO,EAAA,EAAI,CAAC;AAAA,EAC3D,CAAA;AACA,EAAA,MAAM,SAAA,EAAW,MAAM,KAAA,CAAM,CAAA,EAAA;AACnB,IAAA;AACmB,IAAA;AAC3B,IAAA;AACD,EAAA;AACiB,EAAA;AACA,IAAA;AACE,MAAA;AACjB,IAAA;AACH,EAAA;AACqB,EAAA;AACvB;AHEgC;AACA;AIxBnB;AAIgB,EAAA;AACJ,EAAA;AACX,IAAA;AACV,IAAA;AACU,MAAA;AACV,IAAA;AACF,EAAA;AACkB,EAAA;AACA,IAAA;AACE,MAAA;AACjB,IAAA;AACH,EAAA;AACqB,EAAA;AACvB;AJuBgC;AACA;AKzCnB;AAIgB,EAAA;AACJ,EAAA;AACX,IAAA;AACV,IAAA;AACU,MAAA;AACV,IAAA;AACF,EAAA;AACkB,EAAA;AACA,IAAA;AACE,MAAA;AACjB,IAAA;AACH,EAAA;AACqB,EAAA;AACvB;ALwCgC;AACA;AMrEZ;AACD;ANuEa;AACA;AOzEL;AAsCzB;AAKS,EAAA;AAEe,EAAA;AACC,EAAA;AACC,EAAA;AAEL,EAAA;AACvB;APgCgC;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/ilya/work/tpn/ton-pay/packages/api/dist/index.js","sourcesContent":[null,"export const BASE_URL = \"https://tonpay.tech\";\nexport const TESTNET_BASE_URL = \"https://testnet.tonpay.tech\";\n","import type { Chain } from \"../types/chain\";\nimport { BASE_URL, TESTNET_BASE_URL } from \"./const\";\n\nexport const getBaseUrl = (chain?: Chain) => {\n // only for testing. do not use in production. do not use in docs\n if (process.env.TONPAY_BASE_URL) {\n return process.env.TONPAY_BASE_URL;\n }\n if (!chain || chain === \"mainnet\") {\n return BASE_URL;\n }\n return TESTNET_BASE_URL;\n};\n","import { getBaseUrl } from \"../common/get-base-url\";\nimport type { APIOptions } from \"../types/api-options\";\nimport type { CreateTonPayTransferParams } from \"../types/create-ton-pay-transfer\";\nimport type { CreateTonPayTransferResponse } from \"../types/create-ton-pay-transfer\";\n\n/**\n * Creates a message for TON Pay transfer\n * @param params - the parameters for the transfer\n * @param options - the options for the transfer\n * @returns the message for the transfer and data for tracking the transfer\n */\n\nexport const createTonPayTransfer = async (\n params: CreateTonPayTransferParams,\n options?: APIOptions\n): Promise<CreateTonPayTransferResponse> => {\n const baseUrl = getBaseUrl(options?.chain);\n const headers = {\n \"Content-Type\": \"application/json\",\n ...(options?.apiKey ? { \"x-api-key\": options.apiKey } : {}),\n };\n const response = await fetch(`${baseUrl}/api/merchant/v1/create-transfer`, {\n method: \"POST\",\n body: JSON.stringify(params),\n headers,\n });\n if (!response.ok) {\n throw new Error(\"Failed to create TON Pay transfer\", {\n cause: response.statusText,\n });\n }\n return response.json();\n};\n","import { getBaseUrl } from \"../common/get-base-url\";\nimport type { APIOptions } from \"../types/api-options\";\nimport type { CompletedTonPayTransferInfo } from \"../types/completed-ton-pay-transfer-info\";\n\n/**\n * Gets a TON Pay transfer by reference\n * @param reference - the reference of the transfer\n * @param options - the options for the transfer\n * @returns the transfer information\n */\n\nexport const getTonPayTransferByBodyHash = async (\n bodyHash: string,\n options?: APIOptions\n): Promise<CompletedTonPayTransferInfo> => {\n const baseUrl = getBaseUrl(options?.chain);\n const response = await fetch(\n `${baseUrl}/api/merchant/v1/transfer?bodyHash=${bodyHash}`,\n {\n method: \"GET\",\n }\n );\n if (!response.ok) {\n throw new Error(\"Failed to get TON Pay transfer by body hash\", {\n cause: response.statusText,\n });\n }\n return response.json();\n};\n","import { getBaseUrl } from \"../common/get-base-url\";\nimport type { APIOptions } from \"../types/api-options\";\nimport type { CompletedTonPayTransferInfo } from \"../types/completed-ton-pay-transfer-info\";\n\n/**\n * Gets a TON Pay transfer by reference\n * @param reference - the reference of the transfer\n * @param options - the options for the transfer\n * @returns the transfer information\n */\n\nexport const getTonPayTransferByReference = async (\n reference: string,\n options?: APIOptions\n): Promise<CompletedTonPayTransferInfo> => {\n const baseUrl = getBaseUrl(options?.chain);\n const response = await fetch(\n `${baseUrl}/api/merchant/v1/transfer?reference=${reference}`,\n {\n method: \"GET\",\n }\n );\n if (!response.ok) {\n throw new Error(\"Failed to get TON Pay transfer by reference\", {\n cause: response.statusText,\n });\n }\n return response.json();\n};\n","export const USDT = \"EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs\";\nexport const TON = \"TON\";\n","import { createHmac } from \"crypto\";\n\n/**\n * Verifies the HMAC-SHA256 signature of a payload\n * @param payload - Raw JSON string or object to verify\n * @param signature - The signature from X-TonPay-Signature header\n * @param apiSecret - Your TON Pay webhook API secret\n * @returns true if signature is valid, false otherwise\n *\n * @example\n * ```typescript\n * import { verifySignature } from \"@ton-pay/api\";\n *\n * // With raw string\n * app.post(\"/webhook\", (req, res) => {\n * const signature = req.headers[\"x-tonpay-signature\"] as string;\n * const payload = JSON.stringify(req.body);\n *\n * if (!verifySignature(payload, signature, YOUR_API_SECRET)) {\n * return res.status(401).json({ error: \"Invalid signature\" });\n * }\n *\n * res.status(200).json({ received: true });\n * });\n *\n * // With object (will be stringified automatically)\n * app.post(\"/webhook\", (req, res) => {\n * const signature = req.headers[\"x-tonpay-signature\"] as string;\n *\n * if (!verifySignature(req.body, signature, YOUR_API_SECRET)) {\n * return res.status(401).json({ error: \"Invalid signature\" });\n * }\n *\n * res.status(200).json({ received: true });\n * });\n * ```\n */\nexport function verifySignature(\n payload: string | object,\n signature: string,\n apiSecret: string\n): boolean {\n const payloadString =\n typeof payload === \"string\" ? payload : JSON.stringify(payload);\n\n const hmac = createHmac(\"sha256\", apiSecret);\n hmac.update(payloadString);\n const expectedSignature = `sha256=${hmac.digest(\"hex\")}`;\n\n return signature === expectedSignature;\n}\n"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,91 @@
1
+ // src/common/const.ts
2
+ var BASE_URL = "https://tonpay.tech";
3
+ var TESTNET_BASE_URL = "https://testnet.tonpay.tech";
4
+
5
+ // src/common/get-base-url.ts
6
+ var getBaseUrl = (chain) => {
7
+ if (process.env.TONPAY_BASE_URL) {
8
+ return process.env.TONPAY_BASE_URL;
9
+ }
10
+ if (!chain || chain === "mainnet") {
11
+ return BASE_URL;
12
+ }
13
+ return TESTNET_BASE_URL;
14
+ };
15
+
16
+ // src/create-ton-pay-transfer/create-ton-pay-transfer.ts
17
+ var createTonPayTransfer = async (params, options) => {
18
+ const baseUrl = getBaseUrl(options?.chain);
19
+ const headers = {
20
+ "Content-Type": "application/json",
21
+ ...options?.apiKey ? { "x-api-key": options.apiKey } : {}
22
+ };
23
+ const response = await fetch(`${baseUrl}/api/merchant/v1/create-transfer`, {
24
+ method: "POST",
25
+ body: JSON.stringify(params),
26
+ headers
27
+ });
28
+ if (!response.ok) {
29
+ throw new Error("Failed to create TON Pay transfer", {
30
+ cause: response.statusText
31
+ });
32
+ }
33
+ return response.json();
34
+ };
35
+
36
+ // src/get-ton-pay-transfer/get-ton-pay-transfer-by-body-hash.ts
37
+ var getTonPayTransferByBodyHash = async (bodyHash, options) => {
38
+ const baseUrl = getBaseUrl(options?.chain);
39
+ const response = await fetch(
40
+ `${baseUrl}/api/merchant/v1/transfer?bodyHash=${bodyHash}`,
41
+ {
42
+ method: "GET"
43
+ }
44
+ );
45
+ if (!response.ok) {
46
+ throw new Error("Failed to get TON Pay transfer by body hash", {
47
+ cause: response.statusText
48
+ });
49
+ }
50
+ return response.json();
51
+ };
52
+
53
+ // src/get-ton-pay-transfer/get-ton-pay-transfer-by-reference.ts
54
+ var getTonPayTransferByReference = async (reference, options) => {
55
+ const baseUrl = getBaseUrl(options?.chain);
56
+ const response = await fetch(
57
+ `${baseUrl}/api/merchant/v1/transfer?reference=${reference}`,
58
+ {
59
+ method: "GET"
60
+ }
61
+ );
62
+ if (!response.ok) {
63
+ throw new Error("Failed to get TON Pay transfer by reference", {
64
+ cause: response.statusText
65
+ });
66
+ }
67
+ return response.json();
68
+ };
69
+
70
+ // src/common/assets.ts
71
+ var USDT = "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs";
72
+ var TON = "TON";
73
+
74
+ // src/utils/verify-signature.ts
75
+ import { createHmac } from "crypto";
76
+ function verifySignature(payload, signature, apiSecret) {
77
+ const payloadString = typeof payload === "string" ? payload : JSON.stringify(payload);
78
+ const hmac = createHmac("sha256", apiSecret);
79
+ hmac.update(payloadString);
80
+ const expectedSignature = `sha256=${hmac.digest("hex")}`;
81
+ return signature === expectedSignature;
82
+ }
83
+ export {
84
+ TON,
85
+ USDT,
86
+ createTonPayTransfer,
87
+ getTonPayTransferByBodyHash,
88
+ getTonPayTransferByReference,
89
+ verifySignature
90
+ };
91
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/common/const.ts","../src/common/get-base-url.ts","../src/create-ton-pay-transfer/create-ton-pay-transfer.ts","../src/get-ton-pay-transfer/get-ton-pay-transfer-by-body-hash.ts","../src/get-ton-pay-transfer/get-ton-pay-transfer-by-reference.ts","../src/common/assets.ts","../src/utils/verify-signature.ts"],"sourcesContent":["export const BASE_URL = \"https://tonpay.tech\";\nexport const TESTNET_BASE_URL = \"https://testnet.tonpay.tech\";\n","import type { Chain } from \"../types/chain\";\nimport { BASE_URL, TESTNET_BASE_URL } from \"./const\";\n\nexport const getBaseUrl = (chain?: Chain) => {\n // only for testing. do not use in production. do not use in docs\n if (process.env.TONPAY_BASE_URL) {\n return process.env.TONPAY_BASE_URL;\n }\n if (!chain || chain === \"mainnet\") {\n return BASE_URL;\n }\n return TESTNET_BASE_URL;\n};\n","import { getBaseUrl } from \"../common/get-base-url\";\nimport type { APIOptions } from \"../types/api-options\";\nimport type { CreateTonPayTransferParams } from \"../types/create-ton-pay-transfer\";\nimport type { CreateTonPayTransferResponse } from \"../types/create-ton-pay-transfer\";\n\n/**\n * Creates a message for TON Pay transfer\n * @param params - the parameters for the transfer\n * @param options - the options for the transfer\n * @returns the message for the transfer and data for tracking the transfer\n */\n\nexport const createTonPayTransfer = async (\n params: CreateTonPayTransferParams,\n options?: APIOptions\n): Promise<CreateTonPayTransferResponse> => {\n const baseUrl = getBaseUrl(options?.chain);\n const headers = {\n \"Content-Type\": \"application/json\",\n ...(options?.apiKey ? { \"x-api-key\": options.apiKey } : {}),\n };\n const response = await fetch(`${baseUrl}/api/merchant/v1/create-transfer`, {\n method: \"POST\",\n body: JSON.stringify(params),\n headers,\n });\n if (!response.ok) {\n throw new Error(\"Failed to create TON Pay transfer\", {\n cause: response.statusText,\n });\n }\n return response.json();\n};\n","import { getBaseUrl } from \"../common/get-base-url\";\nimport type { APIOptions } from \"../types/api-options\";\nimport type { CompletedTonPayTransferInfo } from \"../types/completed-ton-pay-transfer-info\";\n\n/**\n * Gets a TON Pay transfer by reference\n * @param reference - the reference of the transfer\n * @param options - the options for the transfer\n * @returns the transfer information\n */\n\nexport const getTonPayTransferByBodyHash = async (\n bodyHash: string,\n options?: APIOptions\n): Promise<CompletedTonPayTransferInfo> => {\n const baseUrl = getBaseUrl(options?.chain);\n const response = await fetch(\n `${baseUrl}/api/merchant/v1/transfer?bodyHash=${bodyHash}`,\n {\n method: \"GET\",\n }\n );\n if (!response.ok) {\n throw new Error(\"Failed to get TON Pay transfer by body hash\", {\n cause: response.statusText,\n });\n }\n return response.json();\n};\n","import { getBaseUrl } from \"../common/get-base-url\";\nimport type { APIOptions } from \"../types/api-options\";\nimport type { CompletedTonPayTransferInfo } from \"../types/completed-ton-pay-transfer-info\";\n\n/**\n * Gets a TON Pay transfer by reference\n * @param reference - the reference of the transfer\n * @param options - the options for the transfer\n * @returns the transfer information\n */\n\nexport const getTonPayTransferByReference = async (\n reference: string,\n options?: APIOptions\n): Promise<CompletedTonPayTransferInfo> => {\n const baseUrl = getBaseUrl(options?.chain);\n const response = await fetch(\n `${baseUrl}/api/merchant/v1/transfer?reference=${reference}`,\n {\n method: \"GET\",\n }\n );\n if (!response.ok) {\n throw new Error(\"Failed to get TON Pay transfer by reference\", {\n cause: response.statusText,\n });\n }\n return response.json();\n};\n","export const USDT = \"EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs\";\nexport const TON = \"TON\";\n","import { createHmac } from \"crypto\";\n\n/**\n * Verifies the HMAC-SHA256 signature of a payload\n * @param payload - Raw JSON string or object to verify\n * @param signature - The signature from X-TonPay-Signature header\n * @param apiSecret - Your TON Pay webhook API secret\n * @returns true if signature is valid, false otherwise\n *\n * @example\n * ```typescript\n * import { verifySignature } from \"@ton-pay/api\";\n *\n * // With raw string\n * app.post(\"/webhook\", (req, res) => {\n * const signature = req.headers[\"x-tonpay-signature\"] as string;\n * const payload = JSON.stringify(req.body);\n *\n * if (!verifySignature(payload, signature, YOUR_API_SECRET)) {\n * return res.status(401).json({ error: \"Invalid signature\" });\n * }\n *\n * res.status(200).json({ received: true });\n * });\n *\n * // With object (will be stringified automatically)\n * app.post(\"/webhook\", (req, res) => {\n * const signature = req.headers[\"x-tonpay-signature\"] as string;\n *\n * if (!verifySignature(req.body, signature, YOUR_API_SECRET)) {\n * return res.status(401).json({ error: \"Invalid signature\" });\n * }\n *\n * res.status(200).json({ received: true });\n * });\n * ```\n */\nexport function verifySignature(\n payload: string | object,\n signature: string,\n apiSecret: string\n): boolean {\n const payloadString =\n typeof payload === \"string\" ? payload : JSON.stringify(payload);\n\n const hmac = createHmac(\"sha256\", apiSecret);\n hmac.update(payloadString);\n const expectedSignature = `sha256=${hmac.digest(\"hex\")}`;\n\n return signature === expectedSignature;\n}\n"],"mappings":";AAAO,IAAM,WAAW;AACjB,IAAM,mBAAmB;;;ACEzB,IAAM,aAAa,CAAC,UAAkB;AAE3C,MAAI,QAAQ,IAAI,iBAAiB;AAC/B,WAAO,QAAQ,IAAI;AAAA,EACrB;AACA,MAAI,CAAC,SAAS,UAAU,WAAW;AACjC,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;ACAO,IAAM,uBAAuB,OAClC,QACA,YAC0C;AAC1C,QAAM,UAAU,WAAW,SAAS,KAAK;AACzC,QAAM,UAAU;AAAA,IACd,gBAAgB;AAAA,IAChB,GAAI,SAAS,SAAS,EAAE,aAAa,QAAQ,OAAO,IAAI,CAAC;AAAA,EAC3D;AACA,QAAM,WAAW,MAAM,MAAM,GAAG,OAAO,oCAAoC;AAAA,IACzE,QAAQ;AAAA,IACR,MAAM,KAAK,UAAU,MAAM;AAAA,IAC3B;AAAA,EACF,CAAC;AACD,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI,MAAM,qCAAqC;AAAA,MACnD,OAAO,SAAS;AAAA,IAClB,CAAC;AAAA,EACH;AACA,SAAO,SAAS,KAAK;AACvB;;;ACrBO,IAAM,8BAA8B,OACzC,UACA,YACyC;AACzC,QAAM,UAAU,WAAW,SAAS,KAAK;AACzC,QAAM,WAAW,MAAM;AAAA,IACrB,GAAG,OAAO,sCAAsC,QAAQ;AAAA,IACxD;AAAA,MACE,QAAQ;AAAA,IACV;AAAA,EACF;AACA,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI,MAAM,+CAA+C;AAAA,MAC7D,OAAO,SAAS;AAAA,IAClB,CAAC;AAAA,EACH;AACA,SAAO,SAAS,KAAK;AACvB;;;ACjBO,IAAM,+BAA+B,OAC1C,WACA,YACyC;AACzC,QAAM,UAAU,WAAW,SAAS,KAAK;AACzC,QAAM,WAAW,MAAM;AAAA,IACrB,GAAG,OAAO,uCAAuC,SAAS;AAAA,IAC1D;AAAA,MACE,QAAQ;AAAA,IACV;AAAA,EACF;AACA,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI,MAAM,+CAA+C;AAAA,MAC7D,OAAO,SAAS;AAAA,IAClB,CAAC;AAAA,EACH;AACA,SAAO,SAAS,KAAK;AACvB;;;AC5BO,IAAM,OAAO;AACb,IAAM,MAAM;;;ACDnB,SAAS,kBAAkB;AAqCpB,SAAS,gBACd,SACA,WACA,WACS;AACT,QAAM,gBACJ,OAAO,YAAY,WAAW,UAAU,KAAK,UAAU,OAAO;AAEhE,QAAM,OAAO,WAAW,UAAU,SAAS;AAC3C,OAAK,OAAO,aAAa;AACzB,QAAM,oBAAoB,UAAU,KAAK,OAAO,KAAK,CAAC;AAEtD,SAAO,cAAc;AACvB;","names":[]}
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@ton-pay/api",
3
+ "version": "0.1.0",
4
+ "description": "API functions for TonPay SDK",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "build": "tsup",
17
+ "dev": "tsup --watch",
18
+ "clean": "rm -rf dist",
19
+ "typecheck": "tsc --noEmit",
20
+ "test": "bun test",
21
+ "prepublishOnly": "npm run clean && npm run build"
22
+ },
23
+ "tsup": {
24
+ "entry": [
25
+ "src/index.ts"
26
+ ],
27
+ "format": [
28
+ "cjs",
29
+ "esm"
30
+ ],
31
+ "dts": true,
32
+ "splitting": true,
33
+ "sourcemap": true,
34
+ "clean": true
35
+ },
36
+ "dependencies": {},
37
+ "peerDependencies": {},
38
+ "keywords": [
39
+ "ton",
40
+ "tonpay",
41
+ "blockchain",
42
+ "transfer",
43
+ "api"
44
+ ],
45
+ "author": "RSquad Blockchain Lab",
46
+ "license": "Apache-2.0",
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "https://github.com/RSquad/ton-pay.git",
50
+ "directory": "packages/api"
51
+ },
52
+ "homepage": "https://docs.tonpay.tech",
53
+ "bugs": {
54
+ "url": "https://github.com/RSquad/ton-pay/issues"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public"
58
+ },
59
+ "files": [
60
+ "dist",
61
+ "README.md"
62
+ ]
63
+ }