@settlemint/sdk-portal 2.3.2 → 2.3.3
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 +337 -19
- package/dist/browser/portal.d.ts +252 -0
- package/dist/browser/portal.js +294 -0
- package/dist/browser/portal.js.map +1 -0
- package/dist/portal.cjs +281 -172
- package/dist/portal.cjs.map +1 -1
- package/dist/portal.d.cts +145 -115
- package/dist/portal.d.ts +145 -115
- package/dist/portal.js +294 -0
- package/dist/portal.js.map +1 -0
- package/package.json +6 -6
- package/dist/portal.mjs +0 -188
- package/dist/portal.mjs.map +0 -1
package/dist/portal.cjs
CHANGED
|
@@ -1,148 +1,92 @@
|
|
|
1
|
-
|
|
1
|
+
//#region rolldown:runtime
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
8
|
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
+
key = keys[i];
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
+
get: ((k) => from[k]).bind(null, key),
|
|
13
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
17
|
};
|
|
18
|
-
var
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
value: mod,
|
|
20
|
+
enumerable: true
|
|
21
|
+
}) : target, mod));
|
|
19
22
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
});
|
|
30
|
-
module.exports = __toCommonJS(portal_exports);
|
|
31
|
-
var import_runtime = require("@settlemint/sdk-utils/runtime");
|
|
32
|
-
var import_validation = require("@settlemint/sdk-utils/validation");
|
|
33
|
-
var import_gql = require("gql.tada");
|
|
34
|
-
var import_graphql_request = require("graphql-request");
|
|
35
|
-
var import_v4 = require("zod/v4");
|
|
23
|
+
//#endregion
|
|
24
|
+
const __settlemint_sdk_utils_http = __toESM(require("@settlemint/sdk-utils/http"));
|
|
25
|
+
const __settlemint_sdk_utils_runtime = __toESM(require("@settlemint/sdk-utils/runtime"));
|
|
26
|
+
const __settlemint_sdk_utils_validation = __toESM(require("@settlemint/sdk-utils/validation"));
|
|
27
|
+
const gql_tada = __toESM(require("gql.tada"));
|
|
28
|
+
const graphql_request = __toESM(require("graphql-request"));
|
|
29
|
+
const zod_v4 = __toESM(require("zod/v4"));
|
|
30
|
+
const graphql_ws = __toESM(require("graphql-ws"));
|
|
31
|
+
const node_crypto = __toESM(require("node:crypto"));
|
|
36
32
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const hashedPincode = hashPincode(pincode, salt);
|
|
52
|
-
return (0, import_node_crypto.createHash)("sha256").update(`${hashedPincode}_${challenge}`).digest("hex");
|
|
53
|
-
}
|
|
54
|
-
async function handleWalletVerificationChallenge({
|
|
55
|
-
portalClient,
|
|
56
|
-
portalGraphql,
|
|
57
|
-
verificationId,
|
|
58
|
-
userWalletAddress,
|
|
59
|
-
code,
|
|
60
|
-
verificationType
|
|
61
|
-
}) {
|
|
62
|
-
try {
|
|
63
|
-
if (verificationType === "otp") {
|
|
64
|
-
return {
|
|
65
|
-
challengeResponse: code.toString(),
|
|
66
|
-
verificationId
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
if (verificationType === "secret-code") {
|
|
70
|
-
const formattedCode = code.toString().replace(/(.{5})(?=.)/, "$1-");
|
|
71
|
-
return {
|
|
72
|
-
challengeResponse: formattedCode,
|
|
73
|
-
verificationId
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
const verificationChallenges = await portalClient.request(
|
|
77
|
-
portalGraphql(`
|
|
78
|
-
mutation CreateWalletVerificationChallenges($userWalletAddress: String!, $verificationId: String!) {
|
|
79
|
-
createWalletVerificationChallenges(userWalletAddress: $userWalletAddress, verificationId: $verificationId) {
|
|
80
|
-
challenge
|
|
81
|
-
id
|
|
82
|
-
name
|
|
83
|
-
verificationType
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
`),
|
|
87
|
-
{
|
|
88
|
-
userWalletAddress,
|
|
89
|
-
verificationId
|
|
90
|
-
}
|
|
91
|
-
);
|
|
92
|
-
if (!verificationChallenges.createWalletVerificationChallenges?.length) {
|
|
93
|
-
throw new ChallengeError("No verification challenges received", "NO_CHALLENGES");
|
|
94
|
-
}
|
|
95
|
-
const walletVerificationChallenge = verificationChallenges.createWalletVerificationChallenges.find(
|
|
96
|
-
(challenge) => challenge.id === verificationId
|
|
97
|
-
);
|
|
98
|
-
if (!walletVerificationChallenge?.challenge?.secret || !walletVerificationChallenge?.challenge?.salt) {
|
|
99
|
-
throw new ChallengeError("Invalid challenge format", "INVALID_CHALLENGE");
|
|
100
|
-
}
|
|
101
|
-
const { secret, salt } = walletVerificationChallenge.challenge;
|
|
102
|
-
const challengeResponse = generateResponse(code.toString(), salt, secret);
|
|
103
|
-
return {
|
|
104
|
-
challengeResponse,
|
|
105
|
-
verificationId
|
|
106
|
-
};
|
|
107
|
-
} catch (error) {
|
|
108
|
-
if (error instanceof ChallengeError) {
|
|
109
|
-
throw error;
|
|
110
|
-
}
|
|
111
|
-
throw new ChallengeError("Failed to process wallet verification challenge", "CHALLENGE_PROCESSING_ERROR");
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// src/utils/websocket-client.ts
|
|
116
|
-
var import_graphql_ws = require("graphql-ws");
|
|
33
|
+
//#region src/utils/websocket-client.ts
|
|
34
|
+
/**
|
|
35
|
+
* Creates a GraphQL WebSocket client for the Portal API
|
|
36
|
+
*
|
|
37
|
+
* @param {WebsocketClientOptions} options - The options for the client
|
|
38
|
+
* @returns {Client} The GraphQL WebSocket client
|
|
39
|
+
* @example
|
|
40
|
+
* import { getWebsocketClient } from "@settlemint/sdk-portal";
|
|
41
|
+
*
|
|
42
|
+
* const client = getWebsocketClient({
|
|
43
|
+
* portalGraphqlEndpoint: "https://portal.settlemint.com/graphql",
|
|
44
|
+
* accessToken: "your-access-token",
|
|
45
|
+
* });
|
|
46
|
+
*/
|
|
117
47
|
function getWebsocketClient({ portalGraphqlEndpoint, accessToken }) {
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
const graphqlEndpoint = setWsProtocol(new URL(portalGraphqlEndpoint));
|
|
125
|
-
return (0, import_graphql_ws.createClient)({
|
|
126
|
-
url: `${graphqlEndpoint.protocol}//${graphqlEndpoint.host}/${accessToken}${graphqlEndpoint.pathname}${graphqlEndpoint.search}`
|
|
127
|
-
});
|
|
48
|
+
if (!portalGraphqlEndpoint) {
|
|
49
|
+
throw new Error("portalGraphqlEndpoint is required");
|
|
50
|
+
}
|
|
51
|
+
const graphqlEndpoint = setWsProtocol(new URL(portalGraphqlEndpoint));
|
|
52
|
+
return (0, graphql_ws.createClient)({ url: `${graphqlEndpoint.protocol}//${graphqlEndpoint.host}/${accessToken}${graphqlEndpoint.pathname}${graphqlEndpoint.search}` });
|
|
128
53
|
}
|
|
129
54
|
function setWsProtocol(url) {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
55
|
+
if (url.protocol === "ws:" || url.protocol === "wss:") {
|
|
56
|
+
return url;
|
|
57
|
+
}
|
|
58
|
+
if (url.protocol === "http:") {
|
|
59
|
+
url.protocol = "ws:";
|
|
60
|
+
} else {
|
|
61
|
+
url.protocol = "wss:";
|
|
62
|
+
}
|
|
63
|
+
return url;
|
|
139
64
|
}
|
|
140
65
|
|
|
141
|
-
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region src/utils/wait-for-transaction-receipt.ts
|
|
68
|
+
/**
|
|
69
|
+
* Waits for a blockchain transaction receipt by subscribing to transaction updates via GraphQL.
|
|
70
|
+
* This function polls until the transaction is confirmed or the timeout is reached.
|
|
71
|
+
*
|
|
72
|
+
* @param transactionHash - The hash of the transaction to wait for
|
|
73
|
+
* @param options - Configuration options for the waiting process
|
|
74
|
+
* @returns The transaction details including receipt information when the transaction is confirmed
|
|
75
|
+
* @throws Error if the transaction receipt cannot be retrieved within the specified timeout
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* import { waitForTransactionReceipt } from "@settlemint/sdk-portal";
|
|
79
|
+
*
|
|
80
|
+
* const transaction = await waitForTransactionReceipt("0x123...", {
|
|
81
|
+
* portalGraphqlEndpoint: "https://example.settlemint.com/graphql",
|
|
82
|
+
* accessToken: "your-access-token",
|
|
83
|
+
* timeout: 30000 // 30 seconds timeout
|
|
84
|
+
* });
|
|
85
|
+
*/
|
|
142
86
|
async function waitForTransactionReceipt(transactionHash, options) {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
87
|
+
const wsClient = getWebsocketClient(options);
|
|
88
|
+
const subscription = wsClient.iterate({
|
|
89
|
+
query: `subscription getTransaction($transactionHash: String!) {
|
|
146
90
|
getTransaction(transactionHash: $transactionHash) {
|
|
147
91
|
receipt {
|
|
148
92
|
transactionHash
|
|
@@ -164,55 +108,220 @@ async function waitForTransactionReceipt(transactionHash, options) {
|
|
|
164
108
|
isContract
|
|
165
109
|
}
|
|
166
110
|
}`,
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
111
|
+
variables: { transactionHash }
|
|
112
|
+
});
|
|
113
|
+
const promises = [getTransactionFromSubscription(subscription)];
|
|
114
|
+
if (options.timeout) {
|
|
115
|
+
promises.push(createTimeoutPromise(options.timeout));
|
|
116
|
+
}
|
|
117
|
+
return Promise.race(promises);
|
|
174
118
|
}
|
|
175
119
|
function createTimeoutPromise(timeout) {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
120
|
+
return new Promise((_, reject) => {
|
|
121
|
+
setTimeout(() => reject(new Error("Transaction receipt not found")), timeout);
|
|
122
|
+
});
|
|
179
123
|
}
|
|
180
124
|
async function getTransactionFromSubscription(subscription) {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
125
|
+
for await (const result of subscription) {
|
|
126
|
+
if (result?.data?.getTransaction?.receipt) {
|
|
127
|
+
return result.data.getTransaction;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
throw new Error("No transaction found");
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
//#endregion
|
|
134
|
+
//#region src/utils/wallet-verification-challenge.ts
|
|
135
|
+
/**
|
|
136
|
+
* Custom error class for challenge-related errors
|
|
137
|
+
*/
|
|
138
|
+
var ChallengeError = class extends Error {
|
|
139
|
+
code;
|
|
140
|
+
constructor(message, code) {
|
|
141
|
+
super(message);
|
|
142
|
+
this.name = "ChallengeError";
|
|
143
|
+
this.code = code;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* Hashes a pincode with a salt using SHA-256
|
|
148
|
+
* @param pincode - The pincode to hash
|
|
149
|
+
* @param salt - The salt to use in hashing
|
|
150
|
+
* @returns The hashed pincode as a hex string
|
|
151
|
+
*/
|
|
152
|
+
function hashPincode(pincode, salt) {
|
|
153
|
+
return (0, node_crypto.createHash)("sha256").update(`${salt}${pincode}`).digest("hex");
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Generates a challenge response by combining a hashed pincode with a challenge
|
|
157
|
+
* @param pincode - The user's pincode
|
|
158
|
+
* @param salt - The salt provided in the challenge
|
|
159
|
+
* @param challenge - The challenge secret
|
|
160
|
+
* @returns The challenge response as a hex string
|
|
161
|
+
*/
|
|
162
|
+
function generateResponse(pincode, salt, challenge) {
|
|
163
|
+
const hashedPincode = hashPincode(pincode, salt);
|
|
164
|
+
return (0, node_crypto.createHash)("sha256").update(`${hashedPincode}_${challenge}`).digest("hex");
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Handles a wallet verification challenge by generating an appropriate response
|
|
168
|
+
*
|
|
169
|
+
* @param options - The options for handling the wallet verification challenge
|
|
170
|
+
* @returns Promise resolving to an object containing the challenge response and optionally the verification ID
|
|
171
|
+
* @throws {ChallengeError} If the challenge cannot be created or is invalid
|
|
172
|
+
* @example
|
|
173
|
+
* import { createPortalClient } from "@settlemint/sdk-portal";
|
|
174
|
+
* import { handleWalletVerificationChallenge } from "@settlemint/sdk-portal";
|
|
175
|
+
*
|
|
176
|
+
* const { client, graphql } = createPortalClient({
|
|
177
|
+
* instance: "https://portal.example.com/graphql",
|
|
178
|
+
* accessToken: "your-access-token"
|
|
179
|
+
* });
|
|
180
|
+
*
|
|
181
|
+
* const result = await handleWalletVerificationChallenge({
|
|
182
|
+
* portalClient: client,
|
|
183
|
+
* portalGraphql: graphql,
|
|
184
|
+
* verificationId: "verification-123",
|
|
185
|
+
* userWalletAddress: "0x123...",
|
|
186
|
+
* code: "123456",
|
|
187
|
+
* verificationType: "otp"
|
|
188
|
+
* });
|
|
189
|
+
*/
|
|
190
|
+
async function handleWalletVerificationChallenge({ portalClient, portalGraphql, verificationId, userWalletAddress, code, verificationType }) {
|
|
191
|
+
try {
|
|
192
|
+
if (verificationType === "otp") {
|
|
193
|
+
return {
|
|
194
|
+
challengeResponse: code.toString(),
|
|
195
|
+
verificationId
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
if (verificationType === "secret-code") {
|
|
199
|
+
const formattedCode = code.toString().replace(/(.{5})(?=.)/, "$1-");
|
|
200
|
+
return {
|
|
201
|
+
challengeResponse: formattedCode,
|
|
202
|
+
verificationId
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
const verificationChallenges = await portalClient.request(portalGraphql(`
|
|
206
|
+
mutation CreateWalletVerificationChallenges($userWalletAddress: String!, $verificationId: String!) {
|
|
207
|
+
createWalletVerificationChallenges(userWalletAddress: $userWalletAddress, verificationId: $verificationId) {
|
|
208
|
+
challenge
|
|
209
|
+
id
|
|
210
|
+
name
|
|
211
|
+
verificationType
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
`), {
|
|
215
|
+
userWalletAddress,
|
|
216
|
+
verificationId
|
|
217
|
+
});
|
|
218
|
+
if (!verificationChallenges.createWalletVerificationChallenges?.length) {
|
|
219
|
+
throw new ChallengeError("No verification challenges received", "NO_CHALLENGES");
|
|
220
|
+
}
|
|
221
|
+
const walletVerificationChallenge = verificationChallenges.createWalletVerificationChallenges.find((challenge) => challenge.id === verificationId);
|
|
222
|
+
if (!walletVerificationChallenge?.challenge?.secret || !walletVerificationChallenge?.challenge?.salt) {
|
|
223
|
+
throw new ChallengeError("Invalid challenge format", "INVALID_CHALLENGE");
|
|
224
|
+
}
|
|
225
|
+
const { secret, salt } = walletVerificationChallenge.challenge;
|
|
226
|
+
const challengeResponse = generateResponse(code.toString(), salt, secret);
|
|
227
|
+
return {
|
|
228
|
+
challengeResponse,
|
|
229
|
+
verificationId
|
|
230
|
+
};
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (error instanceof ChallengeError) {
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
throw new ChallengeError("Failed to process wallet verification challenge", "CHALLENGE_PROCESSING_ERROR");
|
|
236
|
+
}
|
|
187
237
|
}
|
|
188
238
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region src/portal.ts
|
|
241
|
+
/**
|
|
242
|
+
* Schema for validating Portal client configuration options.
|
|
243
|
+
*/
|
|
244
|
+
const ClientOptionsSchema = zod_v4.z.object({
|
|
245
|
+
instance: __settlemint_sdk_utils_validation.UrlOrPathSchema,
|
|
246
|
+
accessToken: __settlemint_sdk_utils_validation.ApplicationAccessTokenSchema.optional(),
|
|
247
|
+
cache: zod_v4.z.enum([
|
|
248
|
+
"default",
|
|
249
|
+
"force-cache",
|
|
250
|
+
"no-cache",
|
|
251
|
+
"no-store",
|
|
252
|
+
"only-if-cached",
|
|
253
|
+
"reload"
|
|
254
|
+
]).optional()
|
|
195
255
|
});
|
|
256
|
+
/**
|
|
257
|
+
* Creates a Portal GraphQL client with the provided configuration.
|
|
258
|
+
*
|
|
259
|
+
* @param options - Configuration options for the Portal client
|
|
260
|
+
* @param clientOptions - Additional GraphQL client configuration options
|
|
261
|
+
* @returns An object containing the configured GraphQL client and graphql helper function
|
|
262
|
+
* @throws If the provided options fail validation
|
|
263
|
+
*
|
|
264
|
+
* @example
|
|
265
|
+
* import { createPortalClient } from "@settlemint/sdk-portal";
|
|
266
|
+
* import { loadEnv } from "@settlemint/sdk-utils/environment";
|
|
267
|
+
* import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
|
|
268
|
+
* import type { introspection } from "@schemas/portal-env";
|
|
269
|
+
*
|
|
270
|
+
* const env = await loadEnv(false, false);
|
|
271
|
+
* const logger = createLogger();
|
|
272
|
+
*
|
|
273
|
+
* const { client: portalClient, graphql: portalGraphql } = createPortalClient<{
|
|
274
|
+
* introspection: introspection;
|
|
275
|
+
* disableMasking: true;
|
|
276
|
+
* scalars: {
|
|
277
|
+
* // Change unknown to the type you are using to store metadata
|
|
278
|
+
* JSON: unknown;
|
|
279
|
+
* };
|
|
280
|
+
* }>(
|
|
281
|
+
* {
|
|
282
|
+
* instance: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,
|
|
283
|
+
* accessToken: env.SETTLEMINT_ACCESS_TOKEN!,
|
|
284
|
+
* },
|
|
285
|
+
* {
|
|
286
|
+
* fetch: requestLogger(logger, "portal", fetch) as typeof fetch,
|
|
287
|
+
* },
|
|
288
|
+
* );
|
|
289
|
+
*
|
|
290
|
+
* // Making GraphQL queries
|
|
291
|
+
* const query = portalGraphql(`
|
|
292
|
+
* query GetPendingTransactions {
|
|
293
|
+
* getPendingTransactions {
|
|
294
|
+
* count
|
|
295
|
+
* }
|
|
296
|
+
* }
|
|
297
|
+
* `);
|
|
298
|
+
*
|
|
299
|
+
* const result = await portalClient.request(query);
|
|
300
|
+
*/
|
|
196
301
|
function createPortalClient(options, clientOptions) {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
302
|
+
(0, __settlemint_sdk_utils_runtime.ensureServer)();
|
|
303
|
+
const validatedOptions = (0, __settlemint_sdk_utils_validation.validate)(ClientOptionsSchema, options);
|
|
304
|
+
const graphql = (0, gql_tada.initGraphQLTada)();
|
|
305
|
+
const fullUrl = new URL(validatedOptions.instance).toString();
|
|
306
|
+
return {
|
|
307
|
+
client: new graphql_request.GraphQLClient(fullUrl, {
|
|
308
|
+
...clientOptions,
|
|
309
|
+
headers: (0, __settlemint_sdk_utils_http.appendHeaders)(clientOptions?.headers, { "x-auth-token": validatedOptions.accessToken })
|
|
310
|
+
}),
|
|
311
|
+
graphql
|
|
312
|
+
};
|
|
208
313
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
314
|
+
|
|
315
|
+
//#endregion
|
|
316
|
+
exports.ClientOptionsSchema = ClientOptionsSchema;
|
|
317
|
+
exports.createPortalClient = createPortalClient;
|
|
318
|
+
exports.getWebsocketClient = getWebsocketClient;
|
|
319
|
+
exports.handleWalletVerificationChallenge = handleWalletVerificationChallenge;
|
|
320
|
+
Object.defineProperty(exports, 'readFragment', {
|
|
321
|
+
enumerable: true,
|
|
322
|
+
get: function () {
|
|
323
|
+
return gql_tada.readFragment;
|
|
324
|
+
}
|
|
217
325
|
});
|
|
326
|
+
exports.waitForTransactionReceipt = waitForTransactionReceipt;
|
|
218
327
|
//# sourceMappingURL=portal.cjs.map
|
package/dist/portal.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/portal.ts","../src/utils/wallet-verification-challenge.ts","../src/utils/websocket-client.ts","../src/utils/wait-for-transaction-receipt.ts"],"sourcesContent":["import { ensureServer } from \"@settlemint/sdk-utils/runtime\";\nimport { ApplicationAccessTokenSchema, UrlOrPathSchema, validate } from \"@settlemint/sdk-utils/validation\";\nimport { type AbstractSetupSchema, initGraphQLTada } from \"gql.tada\";\nimport { GraphQLClient } from \"graphql-request\";\nimport { z } from \"zod/v4\";\n\n/**\n * Configuration options for the GraphQL client, excluding 'url' and 'exchanges'.\n */\nexport type RequestConfig = ConstructorParameters<typeof GraphQLClient>[1];\n\n/**\n * Schema for validating Portal client configuration options.\n */\nexport const ClientOptionsSchema = z.object({\n instance: UrlOrPathSchema,\n accessToken: ApplicationAccessTokenSchema,\n cache: z.enum([\"default\", \"force-cache\", \"no-cache\", \"no-store\", \"only-if-cached\", \"reload\"]).optional(),\n});\n\n/**\n * Type representing the validated client options.\n */\nexport type ClientOptions = z.infer<typeof ClientOptionsSchema>;\n\n/**\n * Creates a Portal GraphQL client with the provided configuration.\n *\n * @param options - Configuration options for the Portal client\n * @param clientOptions - Additional GraphQL client configuration options\n * @returns An object containing the configured GraphQL client and graphql helper function\n * @throws If the provided options fail validation\n *\n * @example\n * import { createPortalClient } from \"@settlemint/sdk-portal\";\n * import { loadEnv } from \"@settlemint/sdk-utils/environment\";\n * import { createLogger, requestLogger } from \"@settlemint/sdk-utils/logging\";\n * import type { introspection } from \"@schemas/portal-env\";\n *\n * const env = await loadEnv(false, false);\n * const logger = createLogger();\n *\n * const { client: portalClient, graphql: portalGraphql } = createPortalClient<{\n * introspection: introspection;\n * disableMasking: true;\n * scalars: {\n * // Change unknown to the type you are using to store metadata\n * JSON: unknown;\n * };\n * }>(\n * {\n * instance: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,\n * accessToken: env.SETTLEMINT_ACCESS_TOKEN!,\n * },\n * {\n * fetch: requestLogger(logger, \"portal\", fetch) as typeof fetch,\n * },\n * );\n *\n * // Making GraphQL queries\n * const query = portalGraphql(`\n * query GetPendingTransactions {\n * getPendingTransactions {\n * count\n * }\n * }\n * `);\n *\n * const result = await portalClient.request(query);\n */\nexport function createPortalClient<const Setup extends AbstractSetupSchema>(\n options: ClientOptions,\n clientOptions?: RequestConfig,\n): {\n client: GraphQLClient;\n graphql: initGraphQLTada<Setup>;\n} {\n ensureServer();\n const validatedOptions = validate(ClientOptionsSchema, options);\n const graphql = initGraphQLTada<Setup>();\n const fullUrl = new URL(validatedOptions.instance).toString();\n\n return {\n client: new GraphQLClient(fullUrl, {\n ...clientOptions,\n headers: { ...(clientOptions?.headers ?? {}), \"x-auth-token\": validatedOptions.accessToken },\n }),\n graphql,\n };\n}\n\nexport {\n handleWalletVerificationChallenge,\n type HandleWalletVerificationChallengeOptions,\n} from \"./utils/wallet-verification-challenge.js\";\nexport {\n waitForTransactionReceipt,\n type Transaction,\n type WaitForTransactionReceiptOptions,\n} from \"./utils/wait-for-transaction-receipt.js\";\nexport { getWebsocketClient, type WebsocketClientOptions } from \"./utils/websocket-client.js\";\nexport { readFragment } from \"gql.tada\";\nexport type { FragmentOf, ResultOf, VariablesOf } from \"gql.tada\";\n","import { createHash } from \"node:crypto\";\nimport type { AbstractSetupSchema, initGraphQLTada } from \"gql.tada\";\nimport type { GraphQLClient } from \"graphql-request\";\nimport type { Address } from \"viem\";\n\n/**\n * Custom error class for challenge-related errors\n */\nexport class ChallengeError extends Error {\n readonly code: string;\n\n constructor(message: string, code: string) {\n super(message);\n this.name = \"ChallengeError\";\n this.code = code;\n }\n}\n\n/**\n * Represents the structure of a wallet verification challenge\n */\ninterface WalletVerificationChallenge {\n challenge: {\n secret: string;\n salt: string;\n };\n id: string;\n name: string;\n verificationType: string;\n}\n\n/**\n * Response type for the CreateWalletVerificationChallenges mutation\n */\ninterface CreateWalletVerificationChallengesResponse {\n createWalletVerificationChallenges: WalletVerificationChallenge[];\n}\n\n/**\n * Hashes a pincode with a salt using SHA-256\n * @param pincode - The pincode to hash\n * @param salt - The salt to use in hashing\n * @returns The hashed pincode as a hex string\n */\nfunction hashPincode(pincode: string, salt: string): string {\n return createHash(\"sha256\").update(`${salt}${pincode}`).digest(\"hex\");\n}\n\n/**\n * Generates a challenge response by combining a hashed pincode with a challenge\n * @param pincode - The user's pincode\n * @param salt - The salt provided in the challenge\n * @param challenge - The challenge secret\n * @returns The challenge response as a hex string\n */\nfunction generateResponse(pincode: string, salt: string, challenge: string): string {\n const hashedPincode = hashPincode(pincode, salt);\n return createHash(\"sha256\").update(`${hashedPincode}_${challenge}`).digest(\"hex\");\n}\n\n/**\n * Options for handling a wallet verification challenge\n *\n * @typedef {Object} HandleWalletVerificationChallengeOptions\n * @template {AbstractSetupSchema} Setup - The GraphQL schema setup type\n * @property {GraphQLClient} portalClient - The portal client instance\n * @property {initGraphQLTada<Setup>} portalGraphql - The GraphQL query builder\n * @property {string} verificationId - The ID of the verification challenge\n * @property {Address} userWalletAddress - The wallet address to verify\n * @property {string | number} code - The verification code provided by the user\n * @property {\"otp\" | \"secret-code\" | \"pincode\"} verificationType - The type of verification being performed\n */\nexport interface HandleWalletVerificationChallengeOptions<Setup extends AbstractSetupSchema> {\n portalClient: GraphQLClient;\n portalGraphql: initGraphQLTada<Setup>;\n verificationId: string;\n userWalletAddress: Address;\n code: string | number;\n verificationType: \"otp\" | \"secret-code\" | \"pincode\";\n}\n\n/**\n * Handles a wallet verification challenge by generating an appropriate response\n *\n * @param options - The options for handling the wallet verification challenge\n * @returns Promise resolving to an object containing the challenge response and optionally the verification ID\n * @throws {ChallengeError} If the challenge cannot be created or is invalid\n * @example\n * import { createPortalClient } from \"@settlemint/sdk-portal\";\n * import { handleWalletVerificationChallenge } from \"@settlemint/sdk-portal\";\n *\n * const { client, graphql } = createPortalClient({\n * instance: \"https://portal.example.com/graphql\",\n * accessToken: \"your-access-token\"\n * });\n *\n * const result = await handleWalletVerificationChallenge({\n * portalClient: client,\n * portalGraphql: graphql,\n * verificationId: \"verification-123\",\n * userWalletAddress: \"0x123...\",\n * code: \"123456\",\n * verificationType: \"otp\"\n * });\n */\nexport async function handleWalletVerificationChallenge<const Setup extends AbstractSetupSchema>({\n portalClient,\n portalGraphql,\n verificationId,\n userWalletAddress,\n code,\n verificationType,\n}: HandleWalletVerificationChallengeOptions<Setup>): Promise<{\n challengeResponse: string;\n verificationId?: string;\n}> {\n try {\n if (verificationType === \"otp\") {\n return {\n challengeResponse: code.toString(),\n verificationId,\n };\n }\n\n if (verificationType === \"secret-code\") {\n // Add - separator to the code\n const formattedCode = code.toString().replace(/(.{5})(?=.)/, \"$1-\");\n return {\n challengeResponse: formattedCode,\n verificationId,\n };\n }\n\n const verificationChallenges = await portalClient.request<CreateWalletVerificationChallengesResponse>(\n portalGraphql(`\n mutation CreateWalletVerificationChallenges($userWalletAddress: String!, $verificationId: String!) {\n createWalletVerificationChallenges(userWalletAddress: $userWalletAddress, verificationId: $verificationId) {\n challenge\n id\n name\n verificationType\n }\n }\n `),\n {\n userWalletAddress,\n verificationId,\n },\n );\n\n if (!verificationChallenges.createWalletVerificationChallenges?.length) {\n throw new ChallengeError(\"No verification challenges received\", \"NO_CHALLENGES\");\n }\n\n const walletVerificationChallenge = verificationChallenges.createWalletVerificationChallenges.find(\n (challenge) => challenge.id === verificationId,\n );\n\n if (!walletVerificationChallenge?.challenge?.secret || !walletVerificationChallenge?.challenge?.salt) {\n throw new ChallengeError(\"Invalid challenge format\", \"INVALID_CHALLENGE\");\n }\n\n const { secret, salt } = walletVerificationChallenge.challenge;\n const challengeResponse = generateResponse(code.toString(), salt, secret);\n return {\n challengeResponse,\n verificationId,\n };\n } catch (error) {\n if (error instanceof ChallengeError) {\n throw error;\n }\n throw new ChallengeError(\"Failed to process wallet verification challenge\", \"CHALLENGE_PROCESSING_ERROR\");\n }\n}\n","import { createClient } from \"graphql-ws\";\n\n/**\n * Options for the GraphQL WebSocket client\n *\n * @typedef {Object} WebsocketClientOptions\n * @property {string} portalGraphqlEndpoint - The GraphQL endpoint URL for the Portal API\n * @property {string} accessToken - The access token for authentication with the Portal API\n */\nexport interface WebsocketClientOptions {\n portalGraphqlEndpoint: string;\n accessToken: string;\n}\n\n/**\n * Creates a GraphQL WebSocket client for the Portal API\n *\n * @param {WebsocketClientOptions} options - The options for the client\n * @param {string} options.portalGraphqlEndpoint - The GraphQL endpoint URL for the Portal API\n * @param {string} options.accessToken - The access token for authentication with the Portal API\n * @returns {Client} The GraphQL WebSocket client\n */\nexport function getWebsocketClient({ portalGraphqlEndpoint, accessToken }: WebsocketClientOptions) {\n if (!portalGraphqlEndpoint) {\n throw new Error(\"portalGraphqlEndpoint is required\");\n }\n if (!accessToken) {\n throw new Error(\"accessToken is required\");\n }\n const graphqlEndpoint = setWsProtocol(new URL(portalGraphqlEndpoint));\n return createClient({\n url: `${graphqlEndpoint.protocol}//${graphqlEndpoint.host}/${accessToken}${graphqlEndpoint.pathname}${graphqlEndpoint.search}`,\n });\n}\n\nfunction setWsProtocol(url: URL) {\n if (url.protocol === \"ws:\" || url.protocol === \"wss:\") {\n return url;\n }\n if (url.protocol === \"http:\") {\n url.protocol = \"ws:\";\n } else {\n url.protocol = \"wss:\";\n }\n return url;\n}\n","import type { FormattedExecutionResult } from \"graphql-ws\";\nimport { type WebsocketClientOptions, getWebsocketClient } from \"./websocket-client.js\";\n\n/**\n * Represents the structure of a blockchain transaction with its receipt\n *\n * @typedef {Object} Transaction\n * @property {Object} receipt - The transaction receipt details\n * @property {string} receipt.transactionHash - The hash of the transaction\n * @property {string} receipt.to - The recipient address of the transaction\n * @property {string} receipt.status - The status of the transaction (success/failure)\n * @property {string} receipt.from - The sender address of the transaction\n * @property {string} receipt.type - The type of the transaction\n * @property {string} receipt.revertReason - The reason for transaction reversion, if applicable\n * @property {string} receipt.revertReasonDecoded - Human-readable version of the revert reason\n * @property {string} receipt.contractAddress - The address of the contract deployed in the transaction\n * @property {string[]} receipt.logs - Array of log entries generated by the transaction\n * @property {string[]} receipt.events - Array of events emitted during the transaction\n * @property {string} transactionHash - The hash of the transaction (duplicate of receipt.transactionHash)\n * @property {string} from - The sender address (duplicate of receipt.from)\n * @property {string} createdAt - Timestamp when the transaction was created\n * @property {string} address - The contract address involved in the transaction\n * @property {string} functionName - The name of the function called in the transaction\n * @property {boolean} isContract - Whether the transaction is a contract deployment\n */\nexport interface Transaction {\n receipt: {\n transactionHash: string;\n to: string;\n status: string;\n from: string;\n type: string;\n revertReason: string;\n revertReasonDecoded: string;\n logs: string[];\n events: string[];\n contractAddress: string;\n };\n transactionHash: string;\n from: string;\n createdAt: string;\n address: string;\n functionName: string;\n isContract: boolean;\n}\n\ninterface GetTransactionResponse {\n getTransaction: Transaction;\n}\n\n/**\n * Options for waiting for a transaction receipt\n *\n * @typedef {Object} WaitForTransactionReceiptOptions\n * @property {number} [timeout] - Optional timeout in milliseconds before the operation fails\n */\nexport interface WaitForTransactionReceiptOptions extends WebsocketClientOptions {\n timeout?: number;\n}\n\n/**\n * Waits for a blockchain transaction receipt by subscribing to transaction updates via GraphQL.\n * This function polls until the transaction is confirmed or the timeout is reached.\n *\n * @param transactionHash - The hash of the transaction to wait for\n * @param options - Configuration options for the waiting process\n * @returns The transaction details including receipt information when the transaction is confirmed\n * @throws Error if the transaction receipt cannot be retrieved within the specified timeout\n *\n * @example\n * import { waitForTransactionReceipt } from \"@settlemint/sdk-portal\";\n *\n * const transaction = await waitForTransactionReceipt(\"0x123...\", {\n * portalGraphqlEndpoint: \"https://example.settlemint.com/graphql\",\n * accessToken: \"your-access-token\",\n * timeout: 30000 // 30 seconds timeout\n * });\n */\nexport async function waitForTransactionReceipt(transactionHash: string, options: WaitForTransactionReceiptOptions) {\n const wsClient = getWebsocketClient(options);\n const subscription = wsClient.iterate<GetTransactionResponse>({\n query: `subscription getTransaction($transactionHash: String!) {\n getTransaction(transactionHash: $transactionHash) {\n receipt {\n transactionHash\n to\n status\n from\n type\n revertReason\n revertReasonDecoded\n logs\n events\n contractAddress\n }\n transactionHash\n from\n createdAt\n address\n functionName\n isContract\n }\n }`,\n variables: { transactionHash },\n });\n const promises = [getTransactionFromSubscription(subscription)];\n if (options.timeout) {\n promises.push(createTimeoutPromise(options.timeout));\n }\n\n return Promise.race(promises);\n}\n\nfunction createTimeoutPromise(timeout: number): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => reject(new Error(\"Transaction receipt not found\")), timeout);\n });\n}\n\nasync function getTransactionFromSubscription(\n subscription: AsyncIterableIterator<FormattedExecutionResult<GetTransactionResponse, unknown>>,\n): Promise<Transaction> {\n for await (const result of subscription) {\n if (result?.data?.getTransaction?.receipt) {\n return result.data.getTransaction;\n }\n }\n throw new Error(\"No transaction found\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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transactionHash: string","options: WaitForTransactionReceiptOptions","timeout: number","subscription: AsyncIterableIterator<FormattedExecutionResult<GetTransactionResponse, unknown>>","message: string","code: string","pincode: string","salt: string","challenge: string","UrlOrPathSchema","options: ClientOptions","clientOptions?: RequestConfig","GraphQLClient"],"sources":["../src/utils/websocket-client.ts","../src/utils/wait-for-transaction-receipt.ts","../src/utils/wallet-verification-challenge.ts","../src/portal.ts"],"sourcesContent":["import { createClient } from \"graphql-ws\";\n\n/**\n * Options for the GraphQL WebSocket client\n */\nexport interface WebsocketClientOptions {\n /**\n * The GraphQL endpoint URL for the Portal API\n */\n portalGraphqlEndpoint: string;\n /**\n * The access token for authentication with the Portal API\n */\n accessToken?: string;\n}\n\n/**\n * Creates a GraphQL WebSocket client for the Portal API\n *\n * @param {WebsocketClientOptions} options - The options for the client\n * @returns {Client} The GraphQL WebSocket client\n * @example\n * import { getWebsocketClient } from \"@settlemint/sdk-portal\";\n *\n * const client = getWebsocketClient({\n * portalGraphqlEndpoint: \"https://portal.settlemint.com/graphql\",\n * accessToken: \"your-access-token\",\n * });\n */\nexport function getWebsocketClient({ portalGraphqlEndpoint, accessToken }: WebsocketClientOptions) {\n if (!portalGraphqlEndpoint) {\n throw new Error(\"portalGraphqlEndpoint is required\");\n }\n const graphqlEndpoint = setWsProtocol(new URL(portalGraphqlEndpoint));\n return createClient({\n url: `${graphqlEndpoint.protocol}//${graphqlEndpoint.host}/${accessToken}${graphqlEndpoint.pathname}${graphqlEndpoint.search}`,\n });\n}\n\nfunction setWsProtocol(url: URL) {\n if (url.protocol === \"ws:\" || url.protocol === \"wss:\") {\n return url;\n }\n if (url.protocol === \"http:\") {\n url.protocol = \"ws:\";\n } else {\n url.protocol = \"wss:\";\n }\n return url;\n}\n","import type { FormattedExecutionResult } from \"graphql-ws\";\nimport type { Address, Hex, TransactionReceipt as TransactionReceiptViem } from \"viem\";\nimport { type WebsocketClientOptions, getWebsocketClient } from \"./websocket-client.js\";\n\n/**\n * Represents an event emitted during a transaction execution\n */\nexport interface TransactionEvent {\n /** The name of the event that was emitted */\n eventName: string;\n /** The arguments emitted by the event */\n args: Record<string, unknown>;\n /** Indexed event parameters used for filtering and searching */\n topics: Hex[];\n}\n\n/**\n * Represents the structure of a blockchain transaction receipt\n */\nexport interface TransactionReceipt extends TransactionReceiptViem<string, number, \"Success\" | \"Reverted\"> {\n /** The raw reason for transaction reversion, if applicable */\n revertReason: string;\n /** Human-readable version of the revert reason */\n revertReasonDecoded: string;\n /** Array of events emitted during the transaction */\n events: TransactionEvent[];\n /** The address of the contract deployed in the transaction */\n contractAddress: Address;\n}\n\n/**\n * Represents the structure of a blockchain transaction with its receipt\n */\nexport interface Transaction {\n receipt: TransactionReceipt;\n /** The hash of the transaction (duplicate of receipt.transactionHash) */\n transactionHash: string;\n /** The sender address (duplicate of receipt.from) */\n from: string;\n /** Timestamp when the transaction was created */\n createdAt: string;\n /** The contract address involved in the transaction */\n address: string;\n /** The name of the function called in the transaction */\n functionName: string;\n /** Whether the transaction is a contract deployment */\n isContract: boolean;\n}\n\ninterface GetTransactionResponse {\n getTransaction: Transaction;\n}\n\n/**\n * Options for waiting for a transaction receipt\n */\nexport interface WaitForTransactionReceiptOptions extends WebsocketClientOptions {\n /** Optional timeout in milliseconds before the operation fails */\n timeout?: number;\n}\n\n/**\n * Waits for a blockchain transaction receipt by subscribing to transaction updates via GraphQL.\n * This function polls until the transaction is confirmed or the timeout is reached.\n *\n * @param transactionHash - The hash of the transaction to wait for\n * @param options - Configuration options for the waiting process\n * @returns The transaction details including receipt information when the transaction is confirmed\n * @throws Error if the transaction receipt cannot be retrieved within the specified timeout\n *\n * @example\n * import { waitForTransactionReceipt } from \"@settlemint/sdk-portal\";\n *\n * const transaction = await waitForTransactionReceipt(\"0x123...\", {\n * portalGraphqlEndpoint: \"https://example.settlemint.com/graphql\",\n * accessToken: \"your-access-token\",\n * timeout: 30000 // 30 seconds timeout\n * });\n */\nexport async function waitForTransactionReceipt(transactionHash: string, options: WaitForTransactionReceiptOptions) {\n const wsClient = getWebsocketClient(options);\n const subscription = wsClient.iterate<GetTransactionResponse>({\n query: `subscription getTransaction($transactionHash: String!) {\n getTransaction(transactionHash: $transactionHash) {\n receipt {\n transactionHash\n to\n status\n from\n type\n revertReason\n revertReasonDecoded\n logs\n events\n contractAddress\n }\n transactionHash\n from\n createdAt\n address\n functionName\n isContract\n }\n }`,\n variables: { transactionHash },\n });\n const promises = [getTransactionFromSubscription(subscription)];\n if (options.timeout) {\n promises.push(createTimeoutPromise(options.timeout));\n }\n\n return Promise.race(promises);\n}\n\nfunction createTimeoutPromise(timeout: number): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => reject(new Error(\"Transaction receipt not found\")), timeout);\n });\n}\n\nasync function getTransactionFromSubscription(\n subscription: AsyncIterableIterator<FormattedExecutionResult<GetTransactionResponse, unknown>>,\n): Promise<Transaction> {\n for await (const result of subscription) {\n if (result?.data?.getTransaction?.receipt) {\n return result.data.getTransaction;\n }\n }\n throw new Error(\"No transaction found\");\n}\n","import { createHash } from \"node:crypto\";\nimport type { AbstractSetupSchema, initGraphQLTada } from \"gql.tada\";\nimport type { GraphQLClient } from \"graphql-request\";\nimport type { Address } from \"viem\";\n\n/**\n * Custom error class for challenge-related errors\n */\nexport class ChallengeError extends Error {\n readonly code: string;\n\n constructor(message: string, code: string) {\n super(message);\n this.name = \"ChallengeError\";\n this.code = code;\n }\n}\n\n/**\n * Represents the structure of a wallet verification challenge\n */\ninterface WalletVerificationChallenge {\n challenge: {\n secret: string;\n salt: string;\n };\n id: string;\n name: string;\n verificationType: string;\n}\n\n/**\n * Response type for the CreateWalletVerificationChallenges mutation\n */\ninterface CreateWalletVerificationChallengesResponse {\n createWalletVerificationChallenges: WalletVerificationChallenge[];\n}\n\n/**\n * Hashes a pincode with a salt using SHA-256\n * @param pincode - The pincode to hash\n * @param salt - The salt to use in hashing\n * @returns The hashed pincode as a hex string\n */\nfunction hashPincode(pincode: string, salt: string): string {\n return createHash(\"sha256\").update(`${salt}${pincode}`).digest(\"hex\");\n}\n\n/**\n * Generates a challenge response by combining a hashed pincode with a challenge\n * @param pincode - The user's pincode\n * @param salt - The salt provided in the challenge\n * @param challenge - The challenge secret\n * @returns The challenge response as a hex string\n */\nfunction generateResponse(pincode: string, salt: string, challenge: string): string {\n const hashedPincode = hashPincode(pincode, salt);\n return createHash(\"sha256\").update(`${hashedPincode}_${challenge}`).digest(\"hex\");\n}\n\n/**\n * Options for handling a wallet verification challenge\n */\nexport interface HandleWalletVerificationChallengeOptions<Setup extends AbstractSetupSchema> {\n /** The portal client instance */\n portalClient: GraphQLClient;\n /** The GraphQL query builder */\n portalGraphql: initGraphQLTada<Setup>;\n /** The ID of the verification challenge */\n verificationId: string;\n /** The wallet address to verify */\n userWalletAddress: Address;\n /** The verification code provided by the user */\n code: string | number;\n /** The type of verification being performed */\n verificationType: \"otp\" | \"secret-code\" | \"pincode\";\n}\n\n/**\n * Handles a wallet verification challenge by generating an appropriate response\n *\n * @param options - The options for handling the wallet verification challenge\n * @returns Promise resolving to an object containing the challenge response and optionally the verification ID\n * @throws {ChallengeError} If the challenge cannot be created or is invalid\n * @example\n * import { createPortalClient } from \"@settlemint/sdk-portal\";\n * import { handleWalletVerificationChallenge } from \"@settlemint/sdk-portal\";\n *\n * const { client, graphql } = createPortalClient({\n * instance: \"https://portal.example.com/graphql\",\n * accessToken: \"your-access-token\"\n * });\n *\n * const result = await handleWalletVerificationChallenge({\n * portalClient: client,\n * portalGraphql: graphql,\n * verificationId: \"verification-123\",\n * userWalletAddress: \"0x123...\",\n * code: \"123456\",\n * verificationType: \"otp\"\n * });\n */\nexport async function handleWalletVerificationChallenge<const Setup extends AbstractSetupSchema>({\n portalClient,\n portalGraphql,\n verificationId,\n userWalletAddress,\n code,\n verificationType,\n}: HandleWalletVerificationChallengeOptions<Setup>): Promise<{\n challengeResponse: string;\n verificationId?: string;\n}> {\n try {\n if (verificationType === \"otp\") {\n return {\n challengeResponse: code.toString(),\n verificationId,\n };\n }\n\n if (verificationType === \"secret-code\") {\n // Add - separator to the code\n const formattedCode = code.toString().replace(/(.{5})(?=.)/, \"$1-\");\n return {\n challengeResponse: formattedCode,\n verificationId,\n };\n }\n\n const verificationChallenges = await portalClient.request<CreateWalletVerificationChallengesResponse>(\n portalGraphql(`\n mutation CreateWalletVerificationChallenges($userWalletAddress: String!, $verificationId: String!) {\n createWalletVerificationChallenges(userWalletAddress: $userWalletAddress, verificationId: $verificationId) {\n challenge\n id\n name\n verificationType\n }\n }\n `),\n {\n userWalletAddress,\n verificationId,\n },\n );\n\n if (!verificationChallenges.createWalletVerificationChallenges?.length) {\n throw new ChallengeError(\"No verification challenges received\", \"NO_CHALLENGES\");\n }\n\n const walletVerificationChallenge = verificationChallenges.createWalletVerificationChallenges.find(\n (challenge) => challenge.id === verificationId,\n );\n\n if (!walletVerificationChallenge?.challenge?.secret || !walletVerificationChallenge?.challenge?.salt) {\n throw new ChallengeError(\"Invalid challenge format\", \"INVALID_CHALLENGE\");\n }\n\n const { secret, salt } = walletVerificationChallenge.challenge;\n const challengeResponse = generateResponse(code.toString(), salt, secret);\n return {\n challengeResponse,\n verificationId,\n };\n } catch (error) {\n if (error instanceof ChallengeError) {\n throw error;\n }\n throw new ChallengeError(\"Failed to process wallet verification challenge\", \"CHALLENGE_PROCESSING_ERROR\");\n }\n}\n","import { appendHeaders } from \"@settlemint/sdk-utils/http\";\nimport { ensureServer } from \"@settlemint/sdk-utils/runtime\";\nimport { ApplicationAccessTokenSchema, UrlOrPathSchema, validate } from \"@settlemint/sdk-utils/validation\";\nimport { type AbstractSetupSchema, initGraphQLTada } from \"gql.tada\";\nimport { GraphQLClient } from \"graphql-request\";\nimport { z } from \"zod/v4\";\n\n/**\n * Configuration options for the GraphQL client, excluding 'url' and 'exchanges'.\n */\nexport type RequestConfig = ConstructorParameters<typeof GraphQLClient>[1];\n\n/**\n * Schema for validating Portal client configuration options.\n */\nexport const ClientOptionsSchema = z.object({\n instance: UrlOrPathSchema,\n accessToken: ApplicationAccessTokenSchema.optional(),\n cache: z.enum([\"default\", \"force-cache\", \"no-cache\", \"no-store\", \"only-if-cached\", \"reload\"]).optional(),\n});\n\n/**\n * Type representing the validated client options.\n */\nexport type ClientOptions = z.infer<typeof ClientOptionsSchema>;\n\n/**\n * Creates a Portal GraphQL client with the provided configuration.\n *\n * @param options - Configuration options for the Portal client\n * @param clientOptions - Additional GraphQL client configuration options\n * @returns An object containing the configured GraphQL client and graphql helper function\n * @throws If the provided options fail validation\n *\n * @example\n * import { createPortalClient } from \"@settlemint/sdk-portal\";\n * import { loadEnv } from \"@settlemint/sdk-utils/environment\";\n * import { createLogger, requestLogger } from \"@settlemint/sdk-utils/logging\";\n * import type { introspection } from \"@schemas/portal-env\";\n *\n * const env = await loadEnv(false, false);\n * const logger = createLogger();\n *\n * const { client: portalClient, graphql: portalGraphql } = createPortalClient<{\n * introspection: introspection;\n * disableMasking: true;\n * scalars: {\n * // Change unknown to the type you are using to store metadata\n * JSON: unknown;\n * };\n * }>(\n * {\n * instance: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,\n * accessToken: env.SETTLEMINT_ACCESS_TOKEN!,\n * },\n * {\n * fetch: requestLogger(logger, \"portal\", fetch) as typeof fetch,\n * },\n * );\n *\n * // Making GraphQL queries\n * const query = portalGraphql(`\n * query GetPendingTransactions {\n * getPendingTransactions {\n * count\n * }\n * }\n * `);\n *\n * const result = await portalClient.request(query);\n */\nexport function createPortalClient<const Setup extends AbstractSetupSchema>(\n options: ClientOptions,\n clientOptions?: RequestConfig,\n): {\n client: GraphQLClient;\n graphql: initGraphQLTada<Setup>;\n} {\n ensureServer();\n const validatedOptions = validate(ClientOptionsSchema, options);\n const graphql = initGraphQLTada<Setup>();\n const fullUrl = new URL(validatedOptions.instance).toString();\n\n return {\n client: new GraphQLClient(fullUrl, {\n ...clientOptions,\n headers: appendHeaders(clientOptions?.headers, { \"x-auth-token\": validatedOptions.accessToken }),\n }),\n graphql,\n };\n}\n\nexport { readFragment } from \"gql.tada\";\nexport type { FragmentOf, ResultOf, VariablesOf } from \"gql.tada\";\nexport {\n waitForTransactionReceipt,\n type Transaction,\n type TransactionEvent,\n type TransactionReceipt,\n type WaitForTransactionReceiptOptions,\n} from \"./utils/wait-for-transaction-receipt.js\";\nexport {\n handleWalletVerificationChallenge,\n type HandleWalletVerificationChallengeOptions,\n} from \"./utils/wallet-verification-challenge.js\";\nexport { getWebsocketClient, type WebsocketClientOptions } from \"./utils/websocket-client.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,mBAAmB,EAAE,uBAAuB,aAAqC,EAAE;AACjG,MAAK,uBAAuB;AAC1B,QAAM,IAAI,MAAM;CACjB;CACD,MAAM,kBAAkB,cAAc,IAAI,IAAI,uBAAuB;AACrE,QAAO,6BAAa,EAClB,MAAM,EAAE,gBAAgB,SAAS,IAAI,gBAAgB,KAAK,GAAG,YAAY,EAAE,gBAAgB,SAAS,EAAE,gBAAgB,OAAO,EAC9H,EAAC;AACH;AAED,SAAS,cAAcA,KAAU;AAC/B,KAAI,IAAI,aAAa,SAAS,IAAI,aAAa,QAAQ;AACrD,SAAO;CACR;AACD,KAAI,IAAI,aAAa,SAAS;AAC5B,MAAI,WAAW;CAChB,OAAM;AACL,MAAI,WAAW;CAChB;AACD,QAAO;AACR;;;;;;;;;;;;;;;;;;;;;;AC8BD,eAAsB,0BAA0BC,iBAAyBC,SAA2C;CAClH,MAAM,WAAW,mBAAmB,QAAQ;CAC5C,MAAM,eAAe,SAAS,QAAgC;EAC5D,QAAQ;;;;;;;;;;;;;;;;;;;;;;EAsBR,WAAW,EAAE,gBAAiB;CAC/B,EAAC;CACF,MAAM,WAAW,CAAC,+BAA+B,aAAa,AAAC;AAC/D,KAAI,QAAQ,SAAS;AACnB,WAAS,KAAK,qBAAqB,QAAQ,QAAQ,CAAC;CACrD;AAED,QAAO,QAAQ,KAAK,SAAS;AAC9B;AA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