UNPKG

@settlemint/sdk-portal

Version:

Portal API client module for SettleMint SDK, providing access to smart contract portal services and APIs

327 lines (321 loc) • 11.5 kB
//#region rolldown:runtime var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); //#endregion const __settlemint_sdk_utils_http = __toESM(require("@settlemint/sdk-utils/http")); const __settlemint_sdk_utils_runtime = __toESM(require("@settlemint/sdk-utils/runtime")); const __settlemint_sdk_utils_validation = __toESM(require("@settlemint/sdk-utils/validation")); const gql_tada = __toESM(require("gql.tada")); const graphql_request = __toESM(require("graphql-request")); const zod_v4 = __toESM(require("zod/v4")); const graphql_ws = __toESM(require("graphql-ws")); const node_crypto = __toESM(require("node:crypto")); //#region src/utils/websocket-client.ts /** * Creates a GraphQL WebSocket client for the Portal API * * @param {WebsocketClientOptions} options - The options for the client * @returns {Client} The GraphQL WebSocket client * @example * import { getWebsocketClient } from "@settlemint/sdk-portal"; * * const client = getWebsocketClient({ * portalGraphqlEndpoint: "https://portal.settlemint.com/graphql", * accessToken: "your-access-token", * }); */ function getWebsocketClient({ portalGraphqlEndpoint, accessToken }) { if (!portalGraphqlEndpoint) { throw new Error("portalGraphqlEndpoint is required"); } const graphqlEndpoint = setWsProtocol(new URL(portalGraphqlEndpoint)); return (0, graphql_ws.createClient)({ url: accessToken ? `${graphqlEndpoint.protocol}//${graphqlEndpoint.host}/${accessToken}${graphqlEndpoint.pathname}${graphqlEndpoint.search}` : graphqlEndpoint.toString() }); } function setWsProtocol(url) { if (url.protocol === "ws:" || url.protocol === "wss:") { return url; } if (url.protocol === "http:") { url.protocol = "ws:"; } else { url.protocol = "wss:"; } return url; } //#endregion //#region src/utils/wait-for-transaction-receipt.ts /** * Waits for a blockchain transaction receipt by subscribing to transaction updates via GraphQL. * This function polls until the transaction is confirmed or the timeout is reached. * * @param transactionHash - The hash of the transaction to wait for * @param options - Configuration options for the waiting process * @returns The transaction details including receipt information when the transaction is confirmed * @throws Error if the transaction receipt cannot be retrieved within the specified timeout * * @example * import { waitForTransactionReceipt } from "@settlemint/sdk-portal"; * * const transaction = await waitForTransactionReceipt("0x123...", { * portalGraphqlEndpoint: "https://example.settlemint.com/graphql", * accessToken: "your-access-token", * timeout: 30000 // 30 seconds timeout * }); */ async function waitForTransactionReceipt(transactionHash, options) { const wsClient = getWebsocketClient(options); const subscription = wsClient.iterate({ query: `subscription getTransaction($transactionHash: String!) { getTransaction(transactionHash: $transactionHash) { receipt { transactionHash to status from type revertReason revertReasonDecoded logs events contractAddress } transactionHash from createdAt address functionName isContract } }`, variables: { transactionHash } }); const promises = [getTransactionFromSubscription(subscription)]; if (options.timeout) { promises.push(createTimeoutPromise(options.timeout)); } return Promise.race(promises); } function createTimeoutPromise(timeout) { return new Promise((_, reject) => { setTimeout(() => reject(new Error("Transaction receipt not found")), timeout); }); } async function getTransactionFromSubscription(subscription) { for await (const result of subscription) { if (result?.data?.getTransaction?.receipt) { return result.data.getTransaction; } } throw new Error("No transaction found"); } //#endregion //#region src/utils/wallet-verification-challenge.ts /** * Custom error class for challenge-related errors */ var ChallengeError = class extends Error { code; constructor(message, code) { super(message); this.name = "ChallengeError"; this.code = code; } }; /** * Hashes a pincode with a salt using SHA-256 * @param pincode - The pincode to hash * @param salt - The salt to use in hashing * @returns The hashed pincode as a hex string */ function hashPincode(pincode, salt) { return (0, node_crypto.createHash)("sha256").update(`${salt}${pincode}`).digest("hex"); } /** * Generates a challenge response by combining a hashed pincode with a challenge * @param pincode - The user's pincode * @param salt - The salt provided in the challenge * @param challenge - The challenge secret * @returns The challenge response as a hex string */ function generateResponse(pincode, salt, challenge) { const hashedPincode = hashPincode(pincode, salt); return (0, node_crypto.createHash)("sha256").update(`${hashedPincode}_${challenge}`).digest("hex"); } /** * Handles a wallet verification challenge by generating an appropriate response * * @param options - The options for handling the wallet verification challenge * @returns Promise resolving to an object containing the challenge response and optionally the verification ID * @throws {ChallengeError} If the challenge cannot be created or is invalid * @example * import { createPortalClient } from "@settlemint/sdk-portal"; * import { handleWalletVerificationChallenge } from "@settlemint/sdk-portal"; * * const { client, graphql } = createPortalClient({ * instance: "https://portal.example.com/graphql", * accessToken: "your-access-token" * }); * * const result = await handleWalletVerificationChallenge({ * portalClient: client, * portalGraphql: graphql, * verificationId: "verification-123", * userWalletAddress: "0x123...", * code: "123456", * verificationType: "otp" * }); */ async function handleWalletVerificationChallenge({ portalClient, portalGraphql, verificationId, userWalletAddress, code, verificationType }) { try { if (verificationType === "otp") { return { challengeResponse: code.toString(), verificationId }; } if (verificationType === "secret-code") { const formattedCode = code.toString().replace(/(.{5})(?=.)/, "$1-"); return { challengeResponse: formattedCode, verificationId }; } const verificationChallenges = await portalClient.request(portalGraphql(` mutation CreateWalletVerificationChallenges($userWalletAddress: String!, $verificationId: String!) { createWalletVerificationChallenges(userWalletAddress: $userWalletAddress, verificationId: $verificationId) { challenge id name verificationType } } `), { userWalletAddress, verificationId }); if (!verificationChallenges.createWalletVerificationChallenges?.length) { throw new ChallengeError("No verification challenges received", "NO_CHALLENGES"); } const walletVerificationChallenge = verificationChallenges.createWalletVerificationChallenges.find((challenge) => challenge.id === verificationId); if (!walletVerificationChallenge?.challenge?.secret || !walletVerificationChallenge?.challenge?.salt) { throw new ChallengeError("Invalid challenge format", "INVALID_CHALLENGE"); } const { secret, salt } = walletVerificationChallenge.challenge; const challengeResponse = generateResponse(code.toString(), salt, secret); return { challengeResponse, verificationId }; } catch (error) { if (error instanceof ChallengeError) { throw error; } throw new ChallengeError("Failed to process wallet verification challenge", "CHALLENGE_PROCESSING_ERROR"); } } //#endregion //#region src/portal.ts /** * Schema for validating Portal client configuration options. */ const ClientOptionsSchema = zod_v4.z.object({ instance: __settlemint_sdk_utils_validation.UrlOrPathSchema, accessToken: __settlemint_sdk_utils_validation.ApplicationAccessTokenSchema.optional(), cache: zod_v4.z.enum([ "default", "force-cache", "no-cache", "no-store", "only-if-cached", "reload" ]).optional() }); /** * Creates a Portal GraphQL client with the provided configuration. * * @param options - Configuration options for the Portal client * @param clientOptions - Additional GraphQL client configuration options * @returns An object containing the configured GraphQL client and graphql helper function * @throws If the provided options fail validation * * @example * import { createPortalClient } from "@settlemint/sdk-portal"; * import { loadEnv } from "@settlemint/sdk-utils/environment"; * import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging"; * import type { introspection } from "@schemas/portal-env"; * * const env = await loadEnv(false, false); * const logger = createLogger(); * * const { client: portalClient, graphql: portalGraphql } = createPortalClient<{ * introspection: introspection; * disableMasking: true; * scalars: { * // Change unknown to the type you are using to store metadata * JSON: unknown; * }; * }>( * { * instance: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!, * accessToken: env.SETTLEMINT_ACCESS_TOKEN!, * }, * { * fetch: requestLogger(logger, "portal", fetch) as typeof fetch, * }, * ); * * // Making GraphQL queries * const query = portalGraphql(` * query GetPendingTransactions { * getPendingTransactions { * count * } * } * `); * * const result = await portalClient.request(query); */ function createPortalClient(options, clientOptions) { (0, __settlemint_sdk_utils_runtime.ensureServer)(); const validatedOptions = (0, __settlemint_sdk_utils_validation.validate)(ClientOptionsSchema, options); const graphql = (0, gql_tada.initGraphQLTada)(); const fullUrl = new URL(validatedOptions.instance).toString(); return { client: new graphql_request.GraphQLClient(fullUrl, { ...clientOptions, headers: (0, __settlemint_sdk_utils_http.appendHeaders)(clientOptions?.headers, { "x-auth-token": validatedOptions.accessToken }) }), graphql }; } //#endregion exports.ClientOptionsSchema = ClientOptionsSchema; exports.createPortalClient = createPortalClient; exports.getWebsocketClient = getWebsocketClient; exports.handleWalletVerificationChallenge = handleWalletVerificationChallenge; Object.defineProperty(exports, 'readFragment', { enumerable: true, get: function () { return gql_tada.readFragment; } }); exports.waitForTransactionReceipt = waitForTransactionReceipt; //# sourceMappingURL=portal.cjs.map