@settlemint/sdk-portal 2.2.0-prdfa9d68b → 2.2.1-maina13447c3

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 CHANGED
@@ -28,14 +28,18 @@
28
28
 
29
29
  - [About](#about)
30
30
  - [Examples](#examples)
31
+ - [Deploy contract](#deploy-contract)
31
32
  - [Get pending transactions](#get-pending-transactions)
32
- - [Hd wallet](#hd-wallet)
33
+ - [Send transaction using hd wallet](#send-transaction-using-hd-wallet)
33
34
  - [API Reference](#api-reference)
34
35
  - [Functions](#functions)
35
36
  - [createPortalClient()](#createportalclient)
36
37
  - [handleWalletVerificationChallenge()](#handlewalletverificationchallenge)
38
+ - [waitForTransactionReceipt()](#waitfortransactionreceipt)
37
39
  - [Interfaces](#interfaces)
38
40
  - [HandleWalletVerificationChallengeOptions\<Setup\>](#handlewalletverificationchallengeoptionssetup)
41
+ - [Transaction](#transaction)
42
+ - [WaitForTransactionReceiptOptions](#waitfortransactionreceiptoptions)
39
43
  - [Type Aliases](#type-aliases)
40
44
  - [ClientOptions](#clientoptions)
41
45
  - [RequestConfig](#requestconfig)
@@ -51,9 +55,131 @@ The SettleMint Smart Contract Portal SDK provides a seamless way to interact wit
51
55
  The SDK offers a type-safe interface for all Portal API operations, with comprehensive error handling and validation. It integrates smoothly with modern TypeScript applications while providing a simple and intuitive developer experience.
52
56
  ## Examples
53
57
 
58
+ ### Deploy contract
59
+
60
+ ```ts
61
+ /**
62
+ * This example demonstrates how to deploy a contract.
63
+ *
64
+ * The process involves:
65
+ * 1. Creating a portal client
66
+ * 2. Deploying a forwarder contract
67
+ * 3. Waiting for the forwarder contract deployment to be finalized
68
+ * 4. Deploying a stablecoin factory contract
69
+ * 5. Getting all contracts and filtering by ABI name
70
+ *
71
+ * This pattern is useful for applications that need to deploy smart contracts
72
+ * in the SettleMint Portal, providing a way to track the progress of blockchain operations.
73
+ */
74
+ import { loadEnv } from "@settlemint/sdk-utils/environment";
75
+ import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
76
+ import { getAddress } from "viem";
77
+ import { createPortalClient } from "../portal.js"; // Replace this path with "@settlemint/sdk-portal"
78
+ import { waitForTransactionReceipt } from "../utils/wait-for-transaction-receipt.js"; // Replace this path with "@settlemint/sdk-portal"
79
+ import type { introspection } from "./schemas/portal-env.d.ts"; // Replace this path with the generated introspection type
80
+
81
+ const env = await loadEnv(false, false);
82
+ const logger = createLogger();
83
+
84
+ const { client: portalClient, graphql: portalGraphql } = createPortalClient<{
85
+ introspection: introspection;
86
+ disableMasking: true;
87
+ scalars: {
88
+ // Change unknown to the type you are using to store metadata
89
+ JSON: unknown;
90
+ };
91
+ }>(
92
+ {
93
+ instance: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,
94
+ accessToken: env.SETTLEMINT_ACCESS_TOKEN!,
95
+ },
96
+ {
97
+ fetch: requestLogger(logger, "portal", fetch) as typeof fetch,
98
+ },
99
+ );
100
+
101
+ // Replace with the address of your private key which you use to deploy smart contracts
102
+ const FROM = getAddress("0x4B03331cF2db1497ec58CAa4AFD8b93611906960");
103
+
104
+ /**
105
+ * Deploy a forwarder contract
106
+ */
107
+ const deployForwarder = await portalClient.request(
108
+ portalGraphql(`
109
+ mutation DeployContractForwarder($from: String!) {
110
+ DeployContractForwarder(from: $from, gasLimit: "0x3d0900") {
111
+ transactionHash
112
+ }
113
+ }
114
+ `),
115
+ {
116
+ from: FROM,
117
+ },
118
+ );
119
+
120
+ /**
121
+ * Wait for the forwarder contract deployment to be finalized
122
+ */
123
+ const transaction = await waitForTransactionReceipt(deployForwarder.DeployContractForwarder?.transactionHash!, {
124
+ portalGraphqlEndpoint: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,
125
+ accessToken: env.SETTLEMINT_ACCESS_TOKEN!,
126
+ });
127
+
128
+ /**
129
+ * Deploy a stablecoin factory contract
130
+ */
131
+ const deployStableCoinFactory = await portalClient.request(
132
+ portalGraphql(`
133
+ mutation DeployContractStableCoinFactory($from: String!, $constructorArguments: DeployContractStableCoinFactoryInput!) {
134
+ DeployContractStableCoinFactory(from: $from, constructorArguments: $constructorArguments, gasLimit: "0x3d0900") {
135
+ transactionHash
136
+ }
137
+ }
138
+ `),
139
+ {
140
+ from: FROM,
141
+ constructorArguments: {
142
+ forwarder: getAddress(transaction?.receipt.contractAddress!),
143
+ },
144
+ },
145
+ );
146
+
147
+ console.log(deployStableCoinFactory?.DeployContractStableCoinFactory?.transactionHash);
148
+
149
+ const contractAddresses = await portalClient.request(
150
+ portalGraphql(`
151
+ query GetContracts {
152
+ getContracts {
153
+ count
154
+ records {
155
+ address
156
+ abiName
157
+ createdAt
158
+ }
159
+ }
160
+ }
161
+ `),
162
+ );
163
+ // Print total count
164
+ console.log(`Total contracts: ${contractAddresses.getContracts?.count}`);
165
+
166
+ // Contracts for StableCoinFactory
167
+ console.log(contractAddresses.getContracts?.records.filter((record) => record.abiName === "StableCoinFactory"));
168
+
169
+ ```
54
170
  ### Get pending transactions
55
171
 
56
172
  ```ts
173
+ /**
174
+ * This example demonstrates how to get the number of pending transactions.
175
+ *
176
+ * The process involves:
177
+ * 1. Creating a portal client
178
+ * 2. Making a GraphQL query to get the number of pending transactions
179
+ *
180
+ * This pattern is useful for applications that need to monitor the status of pending transactions
181
+ * in the SettleMint Portal, providing a way to track the progress of blockchain operations.
182
+ */
57
183
  import { loadEnv } from "@settlemint/sdk-utils/environment";
58
184
  import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
59
185
  import { createPortalClient } from "../portal.js"; // Replace this path with "@settlemint/sdk-portal"
@@ -92,15 +218,28 @@ const result = await portalClient.request(query);
92
218
  console.log(`There are ${result.getPendingTransactions?.count} pending transactions`);
93
219
 
94
220
  ```
95
- ### Hd wallet
221
+ ### Send transaction using hd wallet
96
222
 
97
223
  ```ts
224
+ /**
225
+ * This example demonstrates how to send a transaction using an HD wallet.
226
+ *
227
+ * The process involves:
228
+ * 1. Creating a wallet for a user using the HD private key
229
+ * 2. Setting up a pincode for wallet verification
230
+ * 3. Handling the wallet verification challenge
231
+ * 4. Sending a transaction to the blockchain
232
+ *
233
+ * This pattern is useful for applications that need to manage multiple user wallets
234
+ * derived from a single HD wallet, providing a secure and scalable approach to
235
+ * blockchain interactions in enterprise applications.
236
+ */
98
237
  import { loadEnv } from "@settlemint/sdk-utils/environment";
99
238
  import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
100
239
  import type { Address } from "viem";
101
240
  import { createPortalClient } from "../portal.js"; // Replace this path with "@settlemint/sdk-portal"
102
- import { handleWalletVerificationChallenge } from "../wallet-verification-challenge.js"; // Replace this path with "@settlemint/sdk-portal"
103
- import type { introspection } from "./schemas/portal-env.d.ts"; // Replace this path with the generated introspection type
241
+ import { handleWalletVerificationChallenge } from "../utils/wallet-verification-challenge.js"; // Replace this path with "@settlemint/sdk-portal"
242
+ import type { introspection } from "./schemas/portal-env.js"; // Replace this path with the generated introspection type
104
243
 
105
244
  const env = await loadEnv(false, false);
106
245
  const logger = createLogger();
@@ -176,19 +315,20 @@ const challengeResponse = await handleWalletVerificationChallenge({
176
315
 
177
316
  /**
178
317
  * Send a transaction to the chain
179
- * This is a sample of how to send a transaction to the chain using the portal client and the asset tokenization keyVaultId
318
+ * This is a sample of how to send a transaction to the chain using the portal client and the asset tokenization kit
319
+ * The challenge response is generated using the handleWalletVerificationChallenge function, this is used to verifiy wallet access
180
320
  * @see https://github.com/settlemint/asset-tokenization-kit
181
321
  */
182
322
  const result = await portalClient.request(
183
323
  portalGraphql(`
184
- mutation BondMint(
185
- $challengeResponse: String!,
186
- $verificationId: String,
187
- $address: String!,
188
- $from: String!,
189
- $input: BondMintInput!
324
+ mutation StableCoinFactoryCreate(
325
+ $challengeResponse: String!
326
+ $verificationId: String
327
+ $address: String!
328
+ $from: String!
329
+ $input: StableCoinFactoryCreateInput!
190
330
  ) {
191
- BondMint(
331
+ StableCoinFactoryCreate(
192
332
  challengeResponse: $challengeResponse
193
333
  verificationId: $verificationId
194
334
  address: $address
@@ -202,17 +342,19 @@ const result = await portalClient.request(
202
342
  {
203
343
  challengeResponse: challengeResponse.challengeResponse,
204
344
  verificationId: pincodeVerification.createWalletVerification?.id!,
205
- address: wallet.createWallet?.address!,
345
+ address: "0x5e771e1417100000000000000000000000000004",
206
346
  from: wallet.createWallet?.address!,
207
347
  input: {
208
- to: "0x0000000000000000000000000000000000000000",
209
- amount: "1000000000000000000",
348
+ name: "Test Coin",
349
+ symbol: "TEST",
350
+ decimals: 18,
351
+ collateralLivenessSeconds: 3_600,
210
352
  },
211
353
  },
212
354
  );
213
355
 
214
356
  // Log the transaction hash
215
- console.log("Transaction hash:", result.BondMint?.transactionHash);
357
+ console.log("Transaction hash:", result.StableCoinFactoryCreate?.transactionHash);
216
358
 
217
359
  ```
218
360
 
@@ -224,7 +366,7 @@ console.log("Transaction hash:", result.BondMint?.transactionHash);
224
366
 
225
367
  > **createPortalClient**\<`Setup`\>(`options`, `clientOptions?`): `object`
226
368
 
227
- Defined in: [sdk/portal/src/portal.ts:37](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/portal.ts#L37)
369
+ Defined in: [sdk/portal/src/portal.ts:71](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/portal.ts#L71)
228
370
 
229
371
  Creates a Portal GraphQL client with the provided configuration.
230
372
 
@@ -252,8 +394,8 @@ An object containing the configured GraphQL client and graphql helper function
252
394
 
253
395
  | Name | Type | Defined in |
254
396
  | ------ | ------ | ------ |
255
- | `client` | `GraphQLClient` | [sdk/portal/src/portal.ts:41](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/portal.ts#L41) |
256
- | `graphql` | `initGraphQLTada`\<`Setup`\> | [sdk/portal/src/portal.ts:42](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/portal.ts#L42) |
397
+ | `client` | `GraphQLClient` | [sdk/portal/src/portal.ts:75](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/portal.ts#L75) |
398
+ | `graphql` | `initGraphQLTada`\<`Setup`\> | [sdk/portal/src/portal.ts:76](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/portal.ts#L76) |
257
399
 
258
400
  ##### Throws
259
401
 
@@ -265,7 +407,8 @@ If the provided options fail validation
265
407
  import { createPortalClient } from "@settlemint/sdk-portal";
266
408
  import { loadEnv } from "@settlemint/sdk-utils/environment";
267
409
  import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
268
- import type { introspection } from "./test-app/portal-env";
410
+ import type { introspection } from "@schemas/portal-env";
411
+
269
412
  const env = await loadEnv(false, false);
270
413
  const logger = createLogger();
271
414
 
@@ -304,7 +447,7 @@ const result = await portalClient.request(query);
304
447
 
305
448
  > **handleWalletVerificationChallenge**\<`Setup`\>(`options`): `Promise`\<\{ `challengeResponse`: `string`; `verificationId?`: `string`; \}\>
306
449
 
307
- Defined in: [sdk/portal/src/wallet-verification-challenge.ts:106](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/wallet-verification-challenge.ts#L106)
450
+ Defined in: [sdk/portal/src/utils/wallet-verification-challenge.ts:106](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/utils/wallet-verification-challenge.ts#L106)
308
451
 
309
452
  Handles a wallet verification challenge by generating an appropriate response
310
453
 
@@ -332,6 +475,7 @@ If the challenge cannot be created or is invalid
332
475
 
333
476
  ##### Example
334
477
 
478
+ ```ts
335
479
  import { createPortalClient } from "@settlemint/sdk-portal";
336
480
  import { handleWalletVerificationChallenge } from "@settlemint/sdk-portal";
337
481
 
@@ -348,12 +492,53 @@ const result = await handleWalletVerificationChallenge({
348
492
  code: "123456",
349
493
  verificationType: "otp"
350
494
  });
495
+ ```
496
+
497
+ ***
498
+
499
+ #### waitForTransactionReceipt()
500
+
501
+ > **waitForTransactionReceipt**(`transactionHash`, `options`): `Promise`\<[`Transaction`](#transaction)\>
502
+
503
+ Defined in: [sdk/portal/src/utils/wait-for-transaction-receipt.ts:82](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/utils/wait-for-transaction-receipt.ts#L82)
504
+
505
+ Waits for a blockchain transaction receipt by subscribing to transaction updates via GraphQL.
506
+ This function polls until the transaction is confirmed or the timeout is reached.
507
+
508
+ ##### Parameters
509
+
510
+ | Parameter | Type | Description |
511
+ | ------ | ------ | ------ |
512
+ | `transactionHash` | `string` | The hash of the transaction to wait for |
513
+ | `options` | [`WaitForTransactionReceiptOptions`](#waitfortransactionreceiptoptions) | Configuration options for the waiting process |
514
+
515
+ ##### Returns
516
+
517
+ `Promise`\<[`Transaction`](#transaction)\>
518
+
519
+ The transaction details including receipt information when the transaction is confirmed
520
+
521
+ ##### Throws
522
+
523
+ Error if the transaction receipt cannot be retrieved within the specified timeout
524
+
525
+ ##### Example
526
+
527
+ ```ts
528
+ import { waitForTransactionReceipt } from "@settlemint/sdk-portal";
529
+
530
+ const transaction = await waitForTransactionReceipt("0x123...", {
531
+ portalGraphqlEndpoint: "https://example.settlemint.com/graphql",
532
+ accessToken: "your-access-token",
533
+ timeout: 30000 // 30 seconds timeout
534
+ });
535
+ ```
351
536
 
352
537
  ### Interfaces
353
538
 
354
539
  #### HandleWalletVerificationChallengeOptions\<Setup\>
355
540
 
356
- Defined in: [sdk/portal/src/wallet-verification-challenge.ts:73](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/wallet-verification-challenge.ts#L73)
541
+ Defined in: [sdk/portal/src/utils/wallet-verification-challenge.ts:73](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/utils/wallet-verification-challenge.ts#L73)
357
542
 
358
543
  Options for handling a wallet verification challenge
359
544
 
@@ -363,13 +548,29 @@ Options for handling a wallet verification challenge
363
548
  | ------ | ------ |
364
549
  | `Setup` *extends* `AbstractSetupSchema` | The GraphQL schema setup type |
365
550
 
551
+ ***
552
+
553
+ #### Transaction
554
+
555
+ Defined in: [sdk/portal/src/utils/wait-for-transaction-receipt.ts:25](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/utils/wait-for-transaction-receipt.ts#L25)
556
+
557
+ Represents the structure of a blockchain transaction with its receipt
558
+
559
+ ***
560
+
561
+ #### WaitForTransactionReceiptOptions
562
+
563
+ Defined in: [sdk/portal/src/utils/wait-for-transaction-receipt.ts:58](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/utils/wait-for-transaction-receipt.ts#L58)
564
+
565
+ Options for waiting for a transaction receipt
566
+
366
567
  ### Type Aliases
367
568
 
368
569
  #### ClientOptions
369
570
 
370
571
  > **ClientOptions** = `object`
371
572
 
372
- Defined in: [sdk/portal/src/portal.ts:24](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/portal.ts#L24)
573
+ Defined in: [sdk/portal/src/portal.ts:24](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/portal.ts#L24)
373
574
 
374
575
  Type representing the validated client options.
375
576
 
@@ -377,9 +578,9 @@ Type representing the validated client options.
377
578
 
378
579
  | Name | Type | Default value | Defined in |
379
580
  | ------ | ------ | ------ | ------ |
380
- | <a id="accesstoken"></a> `accessToken` | `string` | `ApplicationAccessTokenSchema` | [sdk/portal/src/portal.ts:17](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/portal.ts#L17) |
381
- | <a id="cache"></a> `cache?` | `"default"` \| `"force-cache"` \| `"no-cache"` \| `"no-store"` \| `"only-if-cached"` \| `"reload"` | - | [sdk/portal/src/portal.ts:18](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/portal.ts#L18) |
382
- | <a id="instance"></a> `instance` | `string` | `UrlOrPathSchema` | [sdk/portal/src/portal.ts:16](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/portal.ts#L16) |
581
+ | <a id="accesstoken"></a> `accessToken` | `string` | `ApplicationAccessTokenSchema` | [sdk/portal/src/portal.ts:17](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/portal.ts#L17) |
582
+ | <a id="cache"></a> `cache?` | `"default"` \| `"force-cache"` \| `"no-cache"` \| `"no-store"` \| `"only-if-cached"` \| `"reload"` | - | [sdk/portal/src/portal.ts:18](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/portal.ts#L18) |
583
+ | <a id="instance"></a> `instance` | `string` | `UrlOrPathSchema` | [sdk/portal/src/portal.ts:16](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/portal.ts#L16) |
383
584
 
384
585
  ***
385
586
 
@@ -387,7 +588,7 @@ Type representing the validated client options.
387
588
 
388
589
  > **RequestConfig** = `ConstructorParameters`\<*typeof* `GraphQLClient`\>\[`1`\]
389
590
 
390
- Defined in: [sdk/portal/src/portal.ts:10](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/portal.ts#L10)
591
+ Defined in: [sdk/portal/src/portal.ts:10](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/portal.ts#L10)
391
592
 
392
593
  Configuration options for the GraphQL client, excluding 'url' and 'exchanges'.
393
594
 
@@ -397,7 +598,7 @@ Configuration options for the GraphQL client, excluding 'url' and 'exchanges'.
397
598
 
398
599
  > `const` **ClientOptionsSchema**: `ZodObject`\<[`ClientOptions`](#clientoptions)\>
399
600
 
400
- Defined in: [sdk/portal/src/portal.ts:15](https://github.com/settlemint/sdk/blob/v2.2.0/sdk/portal/src/portal.ts#L15)
601
+ Defined in: [sdk/portal/src/portal.ts:15](https://github.com/settlemint/sdk/blob/v2.2.1/sdk/portal/src/portal.ts#L15)
401
602
 
402
603
  Schema for validating Portal client configuration options.
403
604
 
package/dist/portal.cjs CHANGED
@@ -112,37 +112,54 @@ async function handleWalletVerificationChallenge({
112
112
  }
113
113
 
114
114
  // src/utils/wait-for-transaction-receipt.ts
115
- async function waitForTransactionReceipt(wsClient, transactionHash) {
115
+ var import_graphql_ws = require("graphql-ws");
116
+ async function waitForTransactionReceipt(transactionHash, options) {
117
+ const wsClient = (0, import_graphql_ws.createClient)({
118
+ url: options.portalGraphqlEndpoint.toLowerCase().replace("/graphql", `/${options.accessToken}/graphql`)
119
+ });
116
120
  const subscription = wsClient.iterate({
117
121
  query: `subscription getTransaction($transactionHash: String!) {
118
- getTransaction(transactionHash: $transactionHash) {
119
- receipt {
120
- transactionHash
121
- to
122
- status
123
- from
124
- type
125
- revertReason
126
- revertReasonDecoded
127
- logs
128
- events
129
- contractAddress
130
- }
131
- transactionHash
132
- from
133
- createdAt
134
- address
135
- functionName
136
- isContract
137
- }
138
- }`,
122
+ getTransaction(transactionHash: $transactionHash) {
123
+ receipt {
124
+ transactionHash
125
+ to
126
+ status
127
+ from
128
+ type
129
+ revertReason
130
+ revertReasonDecoded
131
+ logs
132
+ events
133
+ contractAddress
134
+ }
135
+ transactionHash
136
+ from
137
+ createdAt
138
+ address
139
+ functionName
140
+ isContract
141
+ }
142
+ }`,
139
143
  variables: { transactionHash }
140
144
  });
145
+ const promises = [getTransactionFromSubscription(subscription)];
146
+ if (options.timeout) {
147
+ promises.push(createTimeoutPromise(options.timeout));
148
+ }
149
+ return Promise.race(promises);
150
+ }
151
+ function createTimeoutPromise(timeout) {
152
+ return new Promise((_, reject) => {
153
+ setTimeout(() => reject(new Error("Transaction receipt not found")), timeout);
154
+ });
155
+ }
156
+ async function getTransactionFromSubscription(subscription) {
141
157
  for await (const result of subscription) {
142
158
  if (result?.data?.getTransaction?.receipt) {
143
159
  return result.data.getTransaction;
144
160
  }
145
161
  }
162
+ throw new Error("No transaction found");
146
163
  }
147
164
 
148
165
  // src/portal.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/portal.ts","../src/utils/wallet-verification-challenge.ts","../src/utils/wait-for-transaction-receipt.ts"],"sourcesContent":["import {} from \"@settlemint/sdk-utils/logging\";\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\";\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 { waitForTransactionReceipt, type Transaction } from \"./utils/wait-for-transaction-receipt.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 { Address } from \"viem\";\nimport type { createPortalClient } from \"../portal.js\";\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 {ReturnType<typeof createPortalClient>[\"client\"]} 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: ReturnType<typeof createPortalClient>[\"client\"];\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 type { Client } from \"graphql-ws\";\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 * Wait for the transaction receipt\n * @param wsClient websocket client\n * @param transactionHash transaction hash\n * @returns receipt\n */\nexport async function waitForTransactionReceipt(wsClient: Client, transactionHash: string) {\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\n for await (const result of subscription) {\n if (result?.data?.getTransaction?.receipt) {\n return result.data.getTransaction;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,qBAA6B;AAC7B,wBAAwE;AACxE,iBAA0D;AAC1D,6BAA8B;AAC9B,iBAAkB;;;ACLlB,yBAA2B;AAQpB,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EAET,YAAY,SAAiB,MAAc;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AA4BA,SAAS,YAAY,SAAiB,MAAsB;AAC1D,aAAO,+B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,EACF,SAAS,OAAO;AACd,QAAI,iBAAiB,gBAAgB;AACnC,YAAM;AAAA,IACR;AACA,UAAM,IAAI,eAAe,mDAAmD,4BAA4B;AAAA,EAC1G;AACF;;;ACvHA,eAAsB,0BAA0B,UAAkB,iBAAyB;AACzF,QAAM,eAAe,SAAS,QAAgC;AAAA,IAC5D,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAsBP,WAAW,EAAE,gBAAgB;AAAA,EAC/B,CAAC;AAED,mBAAiB,UAAU,cAAc;AACvC,QAAI,QAAQ,MAAM,gBAAgB,SAAS;AACzC,aAAO,OAAO,KAAK;AAAA,IACrB;AAAA,EACF;AACF;;;AFUA,IAAAA,cAA6B;AAlFtB,IAAM,sBAAsB,aAAE,OAAO;AAAA,EAC1C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,OAAO,aAAE,KAAK,CAAC,WAAW,eAAe,YAAY,YAAY,kBAAkB,QAAQ,CAAC,EAAE,SAAS;AACzG,CAAC;AAoDM,SAAS,mBACd,SACA,eAIA;AACA,mCAAa;AACb,QAAM,uBAAmB,4BAAS,qBAAqB,OAAO;AAC9D,QAAM,cAAU,4BAAuB;AACvC,QAAM,UAAU,IAAI,IAAI,iBAAiB,QAAQ,EAAE,SAAS;AAE5D,SAAO;AAAA,IACL,QAAQ,IAAI,qCAAc,SAAS;AAAA,MACjC,GAAG;AAAA,MACH,SAAS,EAAE,GAAI,eAAe,WAAW,CAAC,GAAI,gBAAgB,iBAAiB,YAAY;AAAA,IAC7F,CAAC;AAAA,IACD;AAAA,EACF;AACF;","names":["import_gql"]}
1
+ {"version":3,"sources":["../src/portal.ts","../src/utils/wallet-verification-challenge.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\";\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 { 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 { type FormattedExecutionResult, createClient } from \"graphql-ws\";\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 {string} portalGraphqlEndpoint - The GraphQL endpoint URL for the Portal API\n * @property {string} accessToken - The access token for authentication with the Portal API\n * @property {number} [timeout] - Optional timeout in milliseconds before the operation fails\n */\nexport interface WaitForTransactionReceiptOptions {\n portalGraphqlEndpoint: string;\n accessToken: string;\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 = createClient({\n url: options.portalGraphqlEndpoint.toLowerCase().replace(\"/graphql\", `/${options.accessToken}/graphql`),\n });\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;AAAA,qBAA6B;AAC7B,wBAAwE;AACxE,iBAA0D;AAC1D,6BAA8B;AAC9B,iBAAkB;;;ACJlB,yBAA2B;AAQpB,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EAET,YAAY,SAAiB,MAAc;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AA4BA,SAAS,YAAY,SAAiB,MAAsB;AAC1D,aAAO,+BAAW,QAAQ,EAAE,OAAO,GAAG,IAAI,GAAG,OAAO,EAAE,EAAE,OAAO,KAAK;AACtE;AASA,SAAS,iBAAiB,SAAiB,MAAc,WAA2B;AAClF,QAAM,gBAAgB,YAAY,SAAS,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iBAAiB,QAAQ,EAAE,SAAS;AAE5D,SAAO;AAAA,IACL,QAAQ,IAAI,qCAAc,SAAS;AAAA,MACjC,GAAG;AAAA,MACH,SAAS,EAAE,GAAI,eAAe,WAAW,CAAC,GAAI,gBAAgB,iBAAiB,YAAY;AAAA,IAC7F,CAAC;AAAA,IACD;AAAA,EACF;AACF;","names":["import_gql"]}
package/dist/portal.d.cts CHANGED
@@ -3,14 +3,13 @@ export { FragmentOf, ResultOf, VariablesOf, readFragment } from 'gql.tada';
3
3
  import { GraphQLClient } from 'graphql-request';
4
4
  import { z } from 'zod';
5
5
  import { Address } from 'viem';
6
- import { Client } from 'graphql-ws';
7
6
 
8
7
  /**
9
8
  * Options for handling a wallet verification challenge
10
9
  *
11
10
  * @typedef {Object} HandleWalletVerificationChallengeOptions
12
11
  * @template {AbstractSetupSchema} Setup - The GraphQL schema setup type
13
- * @property {ReturnType<typeof createPortalClient>["client"]} portalClient - The portal client instance
12
+ * @property {GraphQLClient} portalClient - The portal client instance
14
13
  * @property {initGraphQLTada<Setup>} portalGraphql - The GraphQL query builder
15
14
  * @property {string} verificationId - The ID of the verification challenge
16
15
  * @property {Address} userWalletAddress - The wallet address to verify
@@ -18,7 +17,7 @@ import { Client } from 'graphql-ws';
18
17
  * @property {"otp" | "secret-code" | "pincode"} verificationType - The type of verification being performed
19
18
  */
20
19
  interface HandleWalletVerificationChallengeOptions<Setup extends AbstractSetupSchema> {
21
- portalClient: ReturnType<typeof createPortalClient>["client"];
20
+ portalClient: GraphQLClient;
22
21
  portalGraphql: initGraphQLTada<Setup>;
23
22
  verificationId: string;
24
23
  userWalletAddress: Address;
@@ -97,12 +96,37 @@ interface Transaction {
97
96
  isContract: boolean;
98
97
  }
99
98
  /**
100
- * Wait for the transaction receipt
101
- * @param wsClient websocket client
102
- * @param transactionHash transaction hash
103
- * @returns receipt
99
+ * Options for waiting for a transaction receipt
100
+ *
101
+ * @typedef {Object} WaitForTransactionReceiptOptions
102
+ * @property {string} portalGraphqlEndpoint - The GraphQL endpoint URL for the Portal API
103
+ * @property {string} accessToken - The access token for authentication with the Portal API
104
+ * @property {number} [timeout] - Optional timeout in milliseconds before the operation fails
105
+ */
106
+ interface WaitForTransactionReceiptOptions {
107
+ portalGraphqlEndpoint: string;
108
+ accessToken: string;
109
+ timeout?: number;
110
+ }
111
+ /**
112
+ * Waits for a blockchain transaction receipt by subscribing to transaction updates via GraphQL.
113
+ * This function polls until the transaction is confirmed or the timeout is reached.
114
+ *
115
+ * @param transactionHash - The hash of the transaction to wait for
116
+ * @param options - Configuration options for the waiting process
117
+ * @returns The transaction details including receipt information when the transaction is confirmed
118
+ * @throws Error if the transaction receipt cannot be retrieved within the specified timeout
119
+ *
120
+ * @example
121
+ * import { waitForTransactionReceipt } from "@settlemint/sdk-portal";
122
+ *
123
+ * const transaction = await waitForTransactionReceipt("0x123...", {
124
+ * portalGraphqlEndpoint: "https://example.settlemint.com/graphql",
125
+ * accessToken: "your-access-token",
126
+ * timeout: 30000 // 30 seconds timeout
127
+ * });
104
128
  */
105
- declare function waitForTransactionReceipt(wsClient: Client, transactionHash: string): Promise<Transaction | undefined>;
129
+ declare function waitForTransactionReceipt(transactionHash: string, options: WaitForTransactionReceiptOptions): Promise<Transaction>;
106
130
 
107
131
  /**
108
132
  * Configuration options for the GraphQL client, excluding 'url' and 'exchanges'.
@@ -178,4 +202,4 @@ declare function createPortalClient<const Setup extends AbstractSetupSchema>(opt
178
202
  graphql: initGraphQLTada<Setup>;
179
203
  };
180
204
 
181
- export { type ClientOptions, ClientOptionsSchema, type HandleWalletVerificationChallengeOptions, type RequestConfig, type Transaction, createPortalClient, handleWalletVerificationChallenge, waitForTransactionReceipt };
205
+ export { type ClientOptions, ClientOptionsSchema, type HandleWalletVerificationChallengeOptions, type RequestConfig, type Transaction, type WaitForTransactionReceiptOptions, createPortalClient, handleWalletVerificationChallenge, waitForTransactionReceipt };
package/dist/portal.d.ts CHANGED
@@ -3,14 +3,13 @@ export { FragmentOf, ResultOf, VariablesOf, readFragment } from 'gql.tada';
3
3
  import { GraphQLClient } from 'graphql-request';
4
4
  import { z } from 'zod';
5
5
  import { Address } from 'viem';
6
- import { Client } from 'graphql-ws';
7
6
 
8
7
  /**
9
8
  * Options for handling a wallet verification challenge
10
9
  *
11
10
  * @typedef {Object} HandleWalletVerificationChallengeOptions
12
11
  * @template {AbstractSetupSchema} Setup - The GraphQL schema setup type
13
- * @property {ReturnType<typeof createPortalClient>["client"]} portalClient - The portal client instance
12
+ * @property {GraphQLClient} portalClient - The portal client instance
14
13
  * @property {initGraphQLTada<Setup>} portalGraphql - The GraphQL query builder
15
14
  * @property {string} verificationId - The ID of the verification challenge
16
15
  * @property {Address} userWalletAddress - The wallet address to verify
@@ -18,7 +17,7 @@ import { Client } from 'graphql-ws';
18
17
  * @property {"otp" | "secret-code" | "pincode"} verificationType - The type of verification being performed
19
18
  */
20
19
  interface HandleWalletVerificationChallengeOptions<Setup extends AbstractSetupSchema> {
21
- portalClient: ReturnType<typeof createPortalClient>["client"];
20
+ portalClient: GraphQLClient;
22
21
  portalGraphql: initGraphQLTada<Setup>;
23
22
  verificationId: string;
24
23
  userWalletAddress: Address;
@@ -97,12 +96,37 @@ interface Transaction {
97
96
  isContract: boolean;
98
97
  }
99
98
  /**
100
- * Wait for the transaction receipt
101
- * @param wsClient websocket client
102
- * @param transactionHash transaction hash
103
- * @returns receipt
99
+ * Options for waiting for a transaction receipt
100
+ *
101
+ * @typedef {Object} WaitForTransactionReceiptOptions
102
+ * @property {string} portalGraphqlEndpoint - The GraphQL endpoint URL for the Portal API
103
+ * @property {string} accessToken - The access token for authentication with the Portal API
104
+ * @property {number} [timeout] - Optional timeout in milliseconds before the operation fails
105
+ */
106
+ interface WaitForTransactionReceiptOptions {
107
+ portalGraphqlEndpoint: string;
108
+ accessToken: string;
109
+ timeout?: number;
110
+ }
111
+ /**
112
+ * Waits for a blockchain transaction receipt by subscribing to transaction updates via GraphQL.
113
+ * This function polls until the transaction is confirmed or the timeout is reached.
114
+ *
115
+ * @param transactionHash - The hash of the transaction to wait for
116
+ * @param options - Configuration options for the waiting process
117
+ * @returns The transaction details including receipt information when the transaction is confirmed
118
+ * @throws Error if the transaction receipt cannot be retrieved within the specified timeout
119
+ *
120
+ * @example
121
+ * import { waitForTransactionReceipt } from "@settlemint/sdk-portal";
122
+ *
123
+ * const transaction = await waitForTransactionReceipt("0x123...", {
124
+ * portalGraphqlEndpoint: "https://example.settlemint.com/graphql",
125
+ * accessToken: "your-access-token",
126
+ * timeout: 30000 // 30 seconds timeout
127
+ * });
104
128
  */
105
- declare function waitForTransactionReceipt(wsClient: Client, transactionHash: string): Promise<Transaction | undefined>;
129
+ declare function waitForTransactionReceipt(transactionHash: string, options: WaitForTransactionReceiptOptions): Promise<Transaction>;
106
130
 
107
131
  /**
108
132
  * Configuration options for the GraphQL client, excluding 'url' and 'exchanges'.
@@ -178,4 +202,4 @@ declare function createPortalClient<const Setup extends AbstractSetupSchema>(opt
178
202
  graphql: initGraphQLTada<Setup>;
179
203
  };
180
204
 
181
- export { type ClientOptions, ClientOptionsSchema, type HandleWalletVerificationChallengeOptions, type RequestConfig, type Transaction, createPortalClient, handleWalletVerificationChallenge, waitForTransactionReceipt };
205
+ export { type ClientOptions, ClientOptionsSchema, type HandleWalletVerificationChallengeOptions, type RequestConfig, type Transaction, type WaitForTransactionReceiptOptions, createPortalClient, handleWalletVerificationChallenge, waitForTransactionReceipt };
package/dist/portal.mjs CHANGED
@@ -84,37 +84,54 @@ async function handleWalletVerificationChallenge({
84
84
  }
85
85
 
86
86
  // src/utils/wait-for-transaction-receipt.ts
87
- async function waitForTransactionReceipt(wsClient, transactionHash) {
87
+ import { createClient } from "graphql-ws";
88
+ async function waitForTransactionReceipt(transactionHash, options) {
89
+ const wsClient = createClient({
90
+ url: options.portalGraphqlEndpoint.toLowerCase().replace("/graphql", `/${options.accessToken}/graphql`)
91
+ });
88
92
  const subscription = wsClient.iterate({
89
93
  query: `subscription getTransaction($transactionHash: String!) {
90
- getTransaction(transactionHash: $transactionHash) {
91
- receipt {
92
- transactionHash
93
- to
94
- status
95
- from
96
- type
97
- revertReason
98
- revertReasonDecoded
99
- logs
100
- events
101
- contractAddress
102
- }
103
- transactionHash
104
- from
105
- createdAt
106
- address
107
- functionName
108
- isContract
109
- }
110
- }`,
94
+ getTransaction(transactionHash: $transactionHash) {
95
+ receipt {
96
+ transactionHash
97
+ to
98
+ status
99
+ from
100
+ type
101
+ revertReason
102
+ revertReasonDecoded
103
+ logs
104
+ events
105
+ contractAddress
106
+ }
107
+ transactionHash
108
+ from
109
+ createdAt
110
+ address
111
+ functionName
112
+ isContract
113
+ }
114
+ }`,
111
115
  variables: { transactionHash }
112
116
  });
117
+ const promises = [getTransactionFromSubscription(subscription)];
118
+ if (options.timeout) {
119
+ promises.push(createTimeoutPromise(options.timeout));
120
+ }
121
+ return Promise.race(promises);
122
+ }
123
+ function createTimeoutPromise(timeout) {
124
+ return new Promise((_, reject) => {
125
+ setTimeout(() => reject(new Error("Transaction receipt not found")), timeout);
126
+ });
127
+ }
128
+ async function getTransactionFromSubscription(subscription) {
113
129
  for await (const result of subscription) {
114
130
  if (result?.data?.getTransaction?.receipt) {
115
131
  return result.data.getTransaction;
116
132
  }
117
133
  }
134
+ throw new Error("No transaction found");
118
135
  }
119
136
 
120
137
  // src/portal.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/portal.ts","../src/utils/wallet-verification-challenge.ts","../src/utils/wait-for-transaction-receipt.ts"],"sourcesContent":["import {} from \"@settlemint/sdk-utils/logging\";\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\";\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 { waitForTransactionReceipt, type Transaction } from \"./utils/wait-for-transaction-receipt.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 { Address } from \"viem\";\nimport type { createPortalClient } from \"../portal.js\";\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 {ReturnType<typeof createPortalClient>[\"client\"]} 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: ReturnType<typeof createPortalClient>[\"client\"];\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 type { Client } from \"graphql-ws\";\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 * Wait for the transaction receipt\n * @param wsClient websocket client\n * @param transactionHash transaction hash\n * @returns receipt\n */\nexport async function waitForTransactionReceipt(wsClient: Client, transactionHash: string) {\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\n for await (const result of subscription) {\n if (result?.data?.getTransaction?.receipt) {\n return result.data.getTransaction;\n }\n }\n}\n"],"mappings":";AACA,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B,iBAAiB,gBAAgB;AACxE,SAAmC,uBAAuB;AAC1D,SAAS,qBAAqB;AAC9B,SAAS,SAAS;;;ACLlB,SAAS,kBAAkB;AAQpB,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EAET,YAAY,SAAiB,MAAc;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AA4BA,SAAS,YAAY,SAAiB,MAAsB;AAC1D,SAAO,WAAW,QAAQ,EAAE,OAAO,GAAG,IAAI,GAAG,OAAO,EAAE,EAAE,OAAO,KAAK;AACtE;AASA,SAAS,iBAAiB,SAAiB,MAAc,WAA2B;AAClF,QAAM,gBAAgB,Y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B,0BAA0B,UAAkB,iBAAyB;AACzF,QAAM,eAAe,SAAS,QAAgC;AAAA,IAC5D,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAsBP,WAAW,EAAE,gBAAgB;AAAA,EAC/B,CAAC;AAED,mBAAiB,UAAU,cAAc;AACvC,QAAI,QAAQ,MAAM,gBAAgB,SAAS;AACzC,aAAO,OAAO,KAAK;AAAA,IACrB;AAAA,EACF;AACF;;;AFUA,SAAS,oBAAoB;AAlFtB,IAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,OAAO,EAAE,KAAK,CAAC,WAAW,eAAe,YAAY,YAAY,kBAAkB,QAAQ,CAAC,EAAE,SAAS;AACzG,CAAC;AAoDM,SAAS,mBACd,SACA,eAIA;AACA,eAAa;AACb,QAAM,mBAAmB,SAAS,qBAAqB,OAAO;AAC9D,QAAM,UAAU,gBAAuB;AACvC,QAAM,UAAU,IAAI,IAAI,iBAAiB,QAAQ,EAAE,SAAS;AAE5D,SAAO;AAAA,IACL,QAAQ,IAAI,cAAc,SAAS;AAAA,MACjC,GAAG;AAAA,MACH,SAAS,EAAE,GAAI,eAAe,WAAW,CAAC,GAAI,gBAAgB,iBAAiB,YAAY;AAAA,IAC7F,CAAC;AAAA,IACD;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/portal.ts","../src/utils/wallet-verification-challenge.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\";\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 { 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 { type FormattedExecutionResult, createClient } from \"graphql-ws\";\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 {string} portalGraphqlEndpoint - The GraphQL endpoint URL for the Portal API\n * @property {string} accessToken - The access token for authentication with the Portal API\n * @property {number} [timeout] - Optional timeout in milliseconds before the operation fails\n */\nexport interface WaitForTransactionReceiptOptions {\n portalGraphqlEndpoint: string;\n accessToken: string;\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 = createClient({\n url: options.portalGraphqlEndpoint.toLowerCase().replace(\"/graphql\", `/${options.accessToken}/graphql`),\n });\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,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B,iBAAiB,gBAAgB;AACxE,SAAmC,uBAAuB;AAC1D,SAAS,qBAAqB;AAC9B,SAAS,SAAS;;;ACJlB,SAAS,kBAAkB;AAQpB,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EAET,YAAY,SAAiB,MAAc;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AA4BA,SAAS,YAAY,SAAiB,MAAsB;AAC1D,SAAO,WAAW,QAAQ,EAAE,OAAO,GAAG,IAAI,GAAG,OAAO,EAAE,EAAE,OAAO,KAAK;AACtE;AASA,SAAS,iBAAiB,SAAiB,MAAc,WAA2B;AAClF,QAAM,gBAAgB,YAAY,SAAS,IAAI;AAC/C,SAAO,WAAW,QAAQ,EAAE,OAAO,GAAG,aAAa,IAAI,SAAS,EAAE,EAAE,OAAO,KAAK;AAClF;AA+CA,eAAsB,kCAA2E;AAAA,EAC/F;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA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A,IAC7F,CAAC;AAAA,IACD;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@settlemint/sdk-portal",
3
3
  "description": "Portal API client module for SettleMint SDK, providing access to smart contract portal services and APIs",
4
- "version": "2.2.0-prdfa9d68b",
4
+ "version": "2.2.1-maina13447c3",
5
5
  "type": "module",
6
6
  "private": false,
7
7
  "license": "FSL-1.1-MIT",
@@ -50,10 +50,13 @@
50
50
  "codegen": "gql-tada generate-output",
51
51
  "docs": "typedoc --options '../../typedoc.config.mjs' --entryPoints src/portal.ts --out ./docs"
52
52
  },
53
- "devDependencies": {},
53
+ "devDependencies": {
54
+ "viem": "^2"
55
+ },
54
56
  "dependencies": {
55
57
  "gql.tada": "^1",
56
- "@settlemint/sdk-utils": "2.2.0-prdfa9d68b",
58
+ "graphql-ws": "^6",
59
+ "@settlemint/sdk-utils": "2.2.1-maina13447c3",
57
60
  "graphql-request": "^7",
58
61
  "zod": "^3"
59
62
  },