### Run Swap Example with pnpm Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/examples/README.md Execute the swap example after installing dependencies. This command starts the basic swap flow demonstration. ```bash pnpm start:swap ``` -------------------------------- ### Configuration Guide Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt A comprehensive guide to SDK configuration, covering quick start, OpenAPI options, token setup, and security best practices. ```APIDOC ## Configuration Guide ### Description A complete guide to configuring the SDK, including a quick start, detailed explanations of all OpenAPI options with examples, static and dynamic token setup, token refresh patterns, and recommendations for environment variables. Also covers browser and Node.js examples, testing configuration, and security best practices. ### Configuration Options - **BASE**: API URL. - **TOKEN**: Authentication token. - **HEADERS**: Custom headers. - **USERNAME/PASSWORD**: Basic authentication credentials. - **WITH_CREDENTIALS**: CORS credential setting. - **CREDENTIALS**: Credential mode. - **ENCODE_PATH**: Path encoding flag. - **VERSION**: API version. ``` -------------------------------- ### Complete OpenAPI Configuration Example Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/api-reference/open-api-config.md Demonstrates a full configuration setup for the OpenAPI client, including setting the base URL, static or dynamic JWT tokens, custom headers, and cross-origin request credentials. This configuration is applied before making API calls. ```typescript import { OpenAPI, OneClickService, UserAuthService } from '@defuse-protocol/one-click-sdk-typescript'; // Configure base URL OpenAPI.BASE = 'https://1click.chaindefuser.com'; // Set static JWT token const JWT_TOKEN = 'your-jwt-token-here'; OpenAPI.TOKEN = JWT_TOKEN; // Or set dynamic token provider with refresh OpenAPI.TOKEN = async () => { // Check if token is expired if (isTokenExpired()) { // Refresh the token const response = await UserAuthService.refresh({ refreshToken: getSavedRefreshToken() }); return response.accessToken; } return getSavedAccessToken(); }; // Optionally set custom headers OpenAPI.HEADERS = { 'X-Client-Version': '1.0.0' }; // Configure credentials for cross-origin requests OpenAPI.WITH_CREDENTIALS = true; OpenAPI.CREDENTIALS = 'include'; // Now all API calls will use this configuration const tokens = await OneClickService.getTokens(); ``` -------------------------------- ### Install SDK with npm, yarn, or pnpm Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/README.md Install the SDK using your preferred package manager. ```bash # Using npm npm install @defuse-protocol/one-click-sdk-typescript # Using yarn yarn add @defuse-protocol/one-click-sdk-typescript # Using pnpm pnpm add @defuse-protocol/one-click-sdk-typescript ``` -------------------------------- ### Install SDK Dependencies and Build Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/README.md Commands for SDK developers to install dependencies, generate the SDK from the API spec, build the project, and clean build artifacts. ```bash # Install dependencies pnpm install # Generate fresh SDK from latest API spec pnpm generate:fresh # Build the SDK pnpm build # Clean build artifacts pnpm clean ``` -------------------------------- ### Install One-Click SDK TypeScript Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/README.md Install the SDK using npm, yarn, or pnpm. This command adds the necessary package to your project dependencies. ```bash npm install @defuse-protocol/one-click-sdk-typescript yarn add @defuse-protocol/one-click-sdk-typescript pnpm add @defuse-protocol/one-click-sdk-typescript ``` -------------------------------- ### Complete Quote Verification and Usage Example Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/api-reference/quote-signature.md Demonstrates the end-to-end process of obtaining a quote, verifying its signature using the default key, and then proceeding with the swap if the signature is valid. Includes setup for API endpoints and tokens. ```typescript import { OneClickService, OpenAPI, QuoteRequest, buildSignedQuoteRequest, buildSignedQuote, hashQuote, verifyQuoteSignature, quoteHash } from '@defuse-protocol/one-click-sdk-typescript'; // Setup OpenAPI.BASE = 'https://1click.chaindefuser.com'; OpenAPI.TOKEN = 'your-jwt-token'; // Get a quote const quoteRequest: QuoteRequest = { dry: false, swapType: QuoteRequest.swapType.EXACT_INPUT, slippageTolerance: 100, originAsset: 'nep141:arb-0xaf88d065e77c8cc2239327c5edb3a432268e5831.omft.near', depositType: QuoteRequest.depositType.ORIGIN_CHAIN, destinationAsset: 'nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near', amount: '1000000', refundTo: '0x2527D02599Ba641c19FEa793cD0F167589a0f10D', refundType: QuoteRequest.refundType.ORIGIN_CHAIN, recipient: '13QkxhNMrTPxoCkRdYdJ65tFuwXPhL5gLS2Z5Nr6gjRK', recipientType: QuoteRequest.recipientType.DESTINATION_CHAIN, deadline: '2025-08-06T14:15:22Z' }; const quoteResponse = await OneClickService.getQuote(quoteRequest); // Verify the signature const isSignatureValid = verifyQuoteSignature(quoteResponse); console.log('Signature valid:', isSignatureValid); // If signature is valid, safely use the quote if (isSignatureValid) { // Get hash for manual verification or logging const hash = quoteHash(quoteResponse); console.log('Verified quote hash:', hash); // Proceed with swap console.log('Deposit address:', quoteResponse.quote.depositAddress); console.log('Expected output:', quoteResponse.quote.amountOutFormatted); } else { console.error('Quote signature verification failed'); // Do not proceed with swap } ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/examples/README.md Use this command to install project dependencies. Ensure Node.js and pnpm are installed. ```bash pnpm install ``` -------------------------------- ### Initialize SDK and Get Quote Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/README.md Initialize the API client with the base URL and JWT, then create a quote request object to get a swap quote. Set `dry: true` for testing. ```typescript import { OpenAPI, QuoteRequest, OneClickService } from '@defuse-protocol/one-click-sdk-typescript'; // Initialize the API client OpenAPI.BASE = 'https://1click.chaindefuser.com'; // Configure your JSON Web Token (JWT) - required for most endpoints // Request one here: // https://docs.google.com/forms/d/e/1FAIpQLSdrSrqSkKOMb_a8XhwF0f7N5xZ0Y5CYgyzxiAuoC2g4a2N68g/viewform OpenAPI.TOKEN = "your-JSON-Web-Token"; // Create a quote request // See docs for more info: // https://docs.near-intents.org/near-intents/integration/distribution-channels/1click-api#post-v0-quote const quoteRequest: QuoteRequest = { dry: true, // set to true for testing / false to get `depositAddress` and execute swap swapType: QuoteRequest.swapType.EXACT_INPUT, slippageTolerance: 100, // 1% originAsset: 'nep141:arb-0xaf88d065e77c8cc2239327c5edb3a432268e5831.omft.near', // USDC on Arbitrum depositType: QuoteRequest.depositType.ORIGIN_CHAIN, destinationAsset: 'nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near', // USDC on Solana amount: '1000000', // 1 USDC (in smallest units) refundTo: '0x2527D02599Ba641c19FEa793cD0F167589a0f10D', // Valid Arbitrum address refundType: QuoteRequest.refundType.ORIGIN_CHAIN, recipient: '13QkxhNMrTPxoCkRdYdJ65tFuwXPhL5gLS2Z5Nr6gjRK', // Valid Solana Address recipientType: QuoteRequest.recipientType.DESTINATION_CHAIN, deadline: "2025-08-06T14:15:22Z" }; // Get quote const quote = await OneClickService.getQuote(quoteRequest); ``` -------------------------------- ### Quick Start Configuration Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/configuration.md Initialize the SDK by setting the API base URL and your JWT authentication token. This is required before using most SDK services. ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; // Set the API base URL (default is production) OpenAPI.BASE = 'https://1click.chaindefuser.com'; // Set your JWT authentication token (required for most endpoints) OpenAPI.TOKEN = 'your-jwt-token-here'; // Now you can use all the services import { OneClickService } from '@defuse-protocol/one-click-sdk-typescript'; const tokens = await OneClickService.getTokens(); ``` -------------------------------- ### Example Response for Supported Tokens Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md This is an example of the JSON response structure when retrieving supported tokens. It includes details like asset ID, decimals, blockchain, symbol, price, and contract address. ```json [ { "assetId": "nep141:usdc.near", "decimals": 6, "blockchain": "near", "symbol": "USDC", "price": 1.0, "priceUpdatedAt": "2025-06-16T10:30:00Z", "contractAddress": null }, { "assetId": "nep141:eth.near", "decimals": 18, "blockchain": "near", "symbol": "ETH", "price": 3500.50, "priceUpdatedAt": "2025-06-16T10:30:00Z", "contractAddress": null } ] ``` -------------------------------- ### Minimal SDK Configuration Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/configuration.md Basic setup for the SDK, including setting the authentication token. The production base URL is used by default. ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.TOKEN = 'your-jwt-token'; ``` -------------------------------- ### Example Configuration from Environment Variables Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/configuration.md Configure the SDK using environment variables for base URL, authentication token, and custom headers. Ensure sensitive information is not hardcoded. ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.BASE = process.env.API_BASE_URL || 'https://1click.chaindefuser.com'; OpenAPI.TOKEN = process.env.JWT_TOKEN; OpenAPI.HEADERS = { 'X-Client-ID': process.env.CLIENT_ID, 'X-Client-Version': process.env.CLIENT_VERSION, 'X-Client-Platform': process.env.CLIENT_PLATFORM }; ``` -------------------------------- ### cURL Example: Authenticate User Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md Example of how to authenticate a user using a wallet signature via cURL. It specifies the endpoint and includes the signed data in the JSON payload. ```bash curl -X POST "https://1click.chaindefuser.com/v0/auth/authenticate" \ -H "Content-Type: application/json" \ -d '{ "signedData": { /* signed payload from wallet */ } }' ``` -------------------------------- ### cURL Example: Generate Intent Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md Example of how to generate an unsigned intent payload using cURL. It includes the necessary endpoint, JWT token, and JSON payload. ```bash curl -X POST "https://1click.chaindefuser.com/v0/generate-intent" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "type": "swap_transfer", "standard": "nep413", "signerId": "user.near", "depositAddress": "0xabcd1234" }' ``` -------------------------------- ### Retrieve Supported Tokens Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md Use this endpoint to get a list of all tokens supported by the SDK for swapping. No authentication is required. ```bash curl -X GET "https://1click.chaindefuser.com/v0/tokens" ``` -------------------------------- ### OpenAPIConfig Interface Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the OpenAPIConfig interface, explaining its configuration properties and providing examples for token and configuration patterns. ```APIDOC ## OpenAPIConfig Interface ### Description Documentation for the `OpenAPIConfig` interface, detailing its 8 configuration properties. Includes examples for static and dynamic tokens, and various configuration scenarios. ### Properties - **BASE**: API base URL. - **TOKEN**: Authentication token. - **HEADERS**: Custom headers. - **USERNAME/PASSWORD**: Basic authentication credentials. - **WITH_CREDENTIALS**: CORS credential setting. - **CREDENTIALS**: Credential mode. - **ENCODE_PATH**: Path encoding flag. - **VERSION**: API version. ``` -------------------------------- ### cURL Example: Submit Intent Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md Example of how to submit a signed intent using cURL. It includes the endpoint, JWT token, and a JSON payload with the signed data. ```bash curl -X POST "https://1click.chaindefuser.com/v0/submit-intent" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "type": "swap_transfer", "signedData": { /* signed payload from wallet */ } }' ``` -------------------------------- ### GET /v0/tokens Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md Retrieves a list of all supported tokens for swapping, including their details and current pricing. ```APIDOC ## GET /v0/tokens ### Description Retrieve all supported tokens for swapping. ### Method GET ### Endpoint /v0/tokens ### Parameters #### Query Parameters None ### Request Example ```bash curl -X GET "https://1click.chaindefuser.com/v0/tokens" ``` ### Response #### Success Response (200) Returns an array of `TokenResponse` objects. **TokenResponse Fields:** - **assetId** (string) - Unique token identifier - **decimals** (number) - Token decimal places - **blockchain** (string) - Blockchain enum (near, eth, sol, etc.) - **symbol** (string) - Token symbol (BTC, ETH, USDC, etc.) - **price** (number) - Current price in USD - **priceUpdatedAt** (string) - ISO 8601 timestamp of last price update - **contractAddress** (string | null) - Smart contract address if applicable #### Response Example ```json [ { "assetId": "nep141:usdc.near", "decimals": 6, "blockchain": "near", "symbol": "USDC", "price": 1.0, "priceUpdatedAt": "2025-06-16T10:30:00Z", "contractAddress": null } ] ``` ``` -------------------------------- ### UserAuthService Methods Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the `authenticate()` and `refresh()` methods in the UserAuthService class, covering token management and session examples. ```APIDOC ## UserAuthService Methods ### Description Documentation for the `authenticate()` and `refresh()` methods of the `UserAuthService` class. This section covers token management patterns and provides code examples for session management. ### Methods - **authenticate()**: Authenticates a user. - **refresh()**: Refreshes authentication tokens. ``` -------------------------------- ### AccountService Method Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the `getBalances()` method in the AccountService class, including parameter and response details, and code examples. ```APIDOC ## AccountService Method ### Description Documentation for the `getBalances()` method within the `AccountService` class. This includes details on its parameters, the structure of the response, and illustrative code examples. ### Method - **getBalances()**: Retrieves account balances. ``` -------------------------------- ### Production Configuration with Token Refresh Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/configuration.md Set up the SDK for production, including dynamic token retrieval and automatic refresh logic. This example demonstrates authenticating a user and configuring the SDK to use a JWT with a refresh mechanism. ```typescript import { OpenAPI, UserAuthService } from '@defuse-protocol/one-click-sdk-typescript'; let accessToken = ''; let refreshToken = ''; let tokenExpiration = 0; async function initializeSDK() { // Authenticate user const authResponse = await UserAuthService.authenticate({ signedData: userSignedMessage }); accessToken = authResponse.accessToken; refreshToken = authResponse.refreshToken; tokenExpiration = Date.now() + authResponse.expiresIn * 1000; // Configure OpenAPI with token refresh OpenAPI.BASE = 'https://1click.chaindefuser.com'; OpenAPI.TOKEN = async () => { // Refresh if expiring soon if (Date.now() > tokenExpiration - 60000) { const refreshResponse = await UserAuthService.refresh({ refreshToken }); accessToken = refreshResponse.accessToken; tokenExpiration = Date.now() + refreshResponse.expiresIn * 1000; } return accessToken; }; } initializeSDK(); ``` -------------------------------- ### GET /v0/status Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md Check the execution status of a swap using the deposit address and optional memo. ```APIDOC ## GET /v0/status ### Description Check the execution status of a swap. ### Method GET ### Endpoint /v0/status ### Parameters #### Query Parameters - **depositAddress** (string) - Required - Deposit address from quote response - **depositMemo** (string) - Optional - Memo if deposit requires one ### Response #### Success Response (200) - **correlationId** (string) - Unique request tracing ID - **quoteResponse** (QuoteResponse) - Original quote response - **status** (enum) - KNOWN_DEPOSIT_TX, PENDING_DEPOSIT, INCOMPLETE_DEPOSIT, PROCESSING, SUCCESS, REFUNDED, or FAILED - **updatedAt** (string) - ISO 8601 timestamp of last status update - **swapDetails** (SwapDetails) - Transaction hashes and swap details ### Request Example ```bash curl -X GET "https://1click.chaindefuser.com/v0/status?depositAddress=0xabcd1234" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` ``` -------------------------------- ### OneClickService Methods Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the public methods available in the OneClickService class, including their signatures, parameters, return types, and examples. ```APIDOC ## OneClickService Methods ### Description This section details the public methods of the `OneClickService` class, providing full signatures, parameter descriptions, return types, and error information. ### Methods - **getTokens()**: Retrieves available tokens. - **getQuote()**: Fetches a quote for a transaction. - **getExecutionStatus()**: Gets the status of a transaction execution. - **submitDepositTx()**: Submits a deposit transaction. - **generateIntent()**: Generates a transaction intent. - **submitIntent()**: Submits a transaction intent. - **getAnyInputQuoteWithdrawals()**: Retrieves withdrawal quotes for any input. ``` -------------------------------- ### cURL Example: Refresh Token Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md Example of how to refresh an access token using a refresh token via cURL. It includes the endpoint and the refresh token in the JSON payload. ```bash curl -X POST "https://1click.chaindefuser.com/v0/auth/refresh" \ -H "Content-Type: application/json" \ -d '{ "refreshToken": "eyJhbGciOiJIUzI1NiIs..." }' ``` -------------------------------- ### Get All Non-Zero Balances Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/api-reference/account-service.md Retrieve all non-zero token balances for the authenticated user. Ensure the SDK is configured with a valid session token. ```typescript import { AccountService } from '@defuse-protocol/one-click-sdk-typescript'; const response = await AccountService.getBalances(); console.log('User balances:'); response.balances.forEach(entry => { console.log(`${entry.tokenId}: ${entry.available} (source: ${entry.source})`); }); ``` -------------------------------- ### Get User Token Balances Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md Retrieves a user's token balances. If no token IDs are provided, it returns all non-zero balances. Requires an authenticated session token. ```bash curl -X GET "https://1click.chaindefuser.com/v0/account/balances?tokenIds=nep141:usdc.near&tokenIds=nep141:eth.near" \ -H "Authorization: Bearer YOUR_SESSION_TOKEN" ``` -------------------------------- ### Implement Custom Rate Limiting Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/configuration.md Implement a custom rate limiting mechanism to manage outgoing requests. This example enforces a limit of 100 requests per minute and includes logic for waiting if the limit is reached. ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; let requestCount = 0; let lastResetTime = Date.now(); const RATE_LIMIT = 100; // requests per minute async function enforceRateLimit() { const now = Date.now(); if (now - lastResetTime > 60000) { requestCount = 0; lastResetTime = now; } if (requestCount >= RATE_LIMIT) { const waitTime = 60000 - (now - lastResetTime); await new Promise(resolve => setTimeout(resolve, waitTime)); return enforceRateLimit(); } requestCount++; } ``` -------------------------------- ### REST Endpoint Specifications Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Specifications for 8 REST endpoints, including authentication, parameters, response schemas, status codes, and cURL examples. ```bash GET /v0/tokens POST /v0/quote GET /v0/status GET /v0/any-input/withdrawals POST /v0/deposit/submit POST /v0/generate-intent POST /v0/submit-intent POST/v0/auth/* endpoints GET /v0/account/balances ``` -------------------------------- ### GET /v0/status/{depositAddress} Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/README.md Retrieves the execution status of a swap transaction using the deposit address. This endpoint requires JWT authentication. ```APIDOC ## GET /v0/status/{depositAddress} ### Description Fetches the current status of a cross-chain swap transaction identified by its deposit address. This allows tracking the progress of the swap. ### Method GET ### Endpoint /v0/status/{depositAddress} ### Parameters #### Path Parameters - **depositAddress** (string) - Required - The address where the origin asset was deposited. ### Response #### Success Response (200) - **status** (string) - The current status of the swap (e.g., 'PENDING', 'COMPLETED', 'FAILED'). - **transactionHash** (string) - The transaction hash on the destination chain if the swap has been completed. - **estimatedCompletionTime** (string) - An estimated time for swap completion. #### Response Example ```json { "status": "COMPLETED", "transactionHash": "0xdef456...", "estimatedCompletionTime": "2025-08-06T14:30:00Z" } ``` ``` -------------------------------- ### API Reference File Structure Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Details the expected content and structure of individual API reference files, including function signatures, parameter tables, return types, error conditions, and usage examples. ```APIDOC ## API Reference File Structure Each API Reference File Contains: 1. Function/Class signature in code block 2. Parameters table (name | type | required | description) 3. Return type explanation 4. Throws/Errors section 5. Usage examples (realistic code) 6. Authentication notes (if applicable) 7. Related functions reference Each Type Definition Contains: 1. TypeScript code block with exact definition 2. Field table for objects (name | type | required | description) 3. Enum values for enum types 4. Functions that use this type 5. Related types cross-reference Each Endpoint Contains: 1. HTTP method and path 2. Authentication requirement 3. Query/body parameters table 4. Response schema table 5. Status codes with meanings 6. cURL example 7. Example JSON responses ``` -------------------------------- ### Get a Swap Quote Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/README.md Use this snippet to request a quote for a swap. Ensure you have set the OpenAPI token and provide all required parameters for origin and destination assets, amounts, and recipient details. ```typescript import { OneClickService, OpenAPI, QuoteRequest } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.TOKEN = 'your-jwt-token'; const quote = await OneClickService.getQuote({ dry: false, swapType: QuoteRequest.swapType.EXACT_INPUT, slippageTolerance: 100, originAsset: 'nep141:arb-0xaf88d065e77c8cc2239327c5edb3a432268e5831.omft.near', depositType: QuoteRequest.depositType.ORIGIN_CHAIN, destinationAsset: 'nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near', amount: '1000000', refundTo: '0x2527D02599Ba641c19FEa793cD0F167589a0f10D', refundType: QuoteRequest.refundType.ORIGIN_CHAIN, recipient: '13QkxhNMrTPxoCkRdYdJ65tFuwXPhL5gLS2Z5Nr6gjRK', recipientType: QuoteRequest.recipientType.DESTINATION_CHAIN, deadline: '2025-08-06T14:15:22Z' }); console.log('Deposit to:', quote.quote.depositAddress); console.log('Expected output:', quote.quote.amountOutFormatted); ``` -------------------------------- ### Configuration Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/README.md Explains how to configure the SDK, including setting the base URL for API requests, adding custom headers, and managing credentials. ```APIDOC ## Configuration ### Base URL ```typescript OpenAPI.BASE = 'https://1click.chaindefuser.com'; // Production (default) OpenAPI.BASE = 'https://staging.api.com'; // Staging ``` ### Custom Headers ```typescript OpenAPI.HEADERS = { 'X-Client-ID': 'my-app', 'X-Client-Version': '1.0.0' }; ``` ### Credentials ```typescript OpenAPI.WITH_CREDENTIALS = true; // Include cookies OpenAPI.CREDENTIALS = 'include'; // Credential mode ``` See [Configuration Guide](configuration.md) for complete options. ``` -------------------------------- ### Configuration Options Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Details the 8 configuration options available for the SDK, including BASE, TOKEN, HEADERS, USERNAME/PASSWORD, WITH_CREDENTIALS, CREDENTIALS, ENCODE_PATH, and VERSION. ```plaintext BASE (API URL) TOKEN (Authentication) HEADERS (Custom headers) USERNAME/PASSWORD (Basic auth) WITH_CREDENTIALS (CORS) CREDENTIALS (Credential mode) ENCODE_PATH (Path encoding) VERSION (API version) ``` -------------------------------- ### Typical Swap Flow Steps Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/README.md Outlines the sequence of operations for a typical cross-chain token swap using the SDK. ```text 1. **Get Tokens** → `OneClickService.getTokens()` (no auth needed) 2. **Request Quote** → `OneClickService.getQuote(quoteRequest)` (JWT required) 3. **Verify Quote** → `verifyQuoteSignature(quoteResponse)` (optional but recommended) 4. **Get Deposit Address** → From `quoteResponse.quote.depositAddress` 5. **Send Deposit** → User sends assets to deposit address 6. **Submit Deposit** → `OneClickService.submitDepositTx(txRequest)` (JWT required) 7. **Check Status** → `OneClickService.getExecutionStatus(depositAddress)` (JWT required) 8. **Verify Success** → Poll status until `SUCCESS` or `REFUNDED` ``` -------------------------------- ### Get Quote from SDK Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/README.md Call the `getQuote` method on the `OneClickService` with a configured `quoteRequest` object. ```typescript const quote = await OneClickService.getQuote(quoteRequest); ``` -------------------------------- ### Get Execution Status Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/README.md Retrieve the status of a cross-chain swap execution using the `depositAddress` obtained from a quote. ```typescript const status = await OneClickService.getExecutionStatus(depositAddress); ``` -------------------------------- ### Development Configuration Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/configuration.md Configure the SDK for a development environment, specifying a local base URL, a development token, enabling credentials, and adding custom headers. ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.BASE = 'http://localhost:3000'; OpenAPI.TOKEN = 'dev-token'; OpenAPI.WITH_CREDENTIALS = true; OpenAPI.HEADERS = { 'X-Environment': 'development' }; ``` -------------------------------- ### User Authentication Flow Steps Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/README.md Details the steps involved in the user authentication process using the SDK. ```text 1. **Sign Message** → User signs auth message with wallet 2. **Authenticate** → `UserAuthService.authenticate(signedPayload)` 3. **Get Tokens** → Receive `accessToken` and `refreshToken` 4. **Set Token** → `OpenAPI.TOKEN = accessToken` 5. **Use Services** → Access authenticated endpoints 6. **Refresh Token** → `UserAuthService.refresh(refreshToken)` when expired 7. **Query Balances** → `AccountService.getBalances()` ``` -------------------------------- ### GET /v0/any-input/withdrawals Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md Retrieve withdrawals for ANY_INPUT quote type with pagination, filtering by deposit address, memo, and timestamp. ```APIDOC ## GET /v0/any-input/withdrawals ### Description Retrieve withdrawals for ANY_INPUT quote type with pagination. ### Method GET ### Endpoint /v0/any-input/withdrawals ### Parameters #### Query Parameters - **depositAddress** (string) - Required - Deposit address from quote - **depositMemo** (string) - Optional - Memo if required - **timestampFrom** (string) - Optional - ISO 8601 timestamp to filter from - **page** (number) - Optional - Page number for pagination (default: 1) - **limit** (number) - Optional - Results per page (max 50, default: 50) - **sortOrder** (enum) - Optional - 'asc' or 'desc' for sorting ### Response #### Success Response (200) - **asset** (string) - Destination asset ID - **recipient** (string) - Recipient address - **affiliateRecipient** (string) - Affiliate recipient address - **withdrawals** (AnyInputQuoteWithdrawal) - Withdrawal details ### Request Example ```bash curl -X GET "https://1click.chaindefuser.com/v0/any-input/withdrawals?depositAddress=0xabcd1234&page=1&limit=10" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` ``` -------------------------------- ### Server Application (Node.js) Configuration Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/configuration.md Configure the SDK for a Node.js server environment, using environment variables for the base URL and token. Custom headers and disabling credentials are also demonstrated. ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; // Configure for server environment OpenAPI.BASE = process.env.API_BASE_URL || 'https://1click.chaindefuser.com'; // Load token from environment or secure storage const JWT_TOKEN = process.env.JWT_TOKEN; if (!JWT_TOKEN) { throw new Error('JWT_TOKEN environment variable is required'); } OpenAPI.TOKEN = JWT_TOKEN; // Add custom headers for server requests OpenAPI.HEADERS = { 'X-Client-ID': process.env.CLIENT_ID, 'X-Server-Version': process.env.APP_VERSION, 'User-Agent': `MyApp-Server/1.0 (Node.js ${process.version})` }; // Disable credentials if not needed OpenAPI.WITH_CREDENTIALS = false; OpenAPI.CREDENTIALS = 'omit'; ``` -------------------------------- ### Testing Configuration Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/configuration.md Set up the SDK for testing purposes, pointing to a staging API URL and using a test JWT. Custom headers for test modes are also included. ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; // Use test/staging API OpenAPI.BASE = process.env.TEST_API_URL || 'https://staging.1click.api.com'; // Use test JWT OpenAPI.TOKEN = process.env.TEST_JWT_TOKEN || 'test-token'; // Add test headers OpenAPI.HEADERS = { 'X-Test-Mode': 'true', 'X-Test-ID': process.env.TEST_RUN_ID }; ``` -------------------------------- ### Browser Application Configuration Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/configuration.md Configure the SDK for a browser environment, setting the production base URL, retrieving tokens from local storage, and optionally implementing dynamic token refresh. Custom headers and credentials for cross-origin requests can also be configured. ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; // Use production API OpenAPI.BASE = 'https://1click.chaindefuser.com'; // Get token from localStorage or secure storage const token = localStorage.getItem('jwt_token'); if (token) { OpenAPI.TOKEN = token; } // Or use dynamic token with refresh OpenAPI.TOKEN = async () => { let token = localStorage.getItem('jwt_token'); const expiration = parseInt(localStorage.getItem('jwt_expires') || '0'); if (Date.now() > expiration - 60000) { // Token expired, refresh it const refreshToken = localStorage.getItem('refresh_token'); const response = await UserAuthService.refresh({ refreshToken }); localStorage.setItem('jwt_token', response.accessToken); localStorage.setItem('jwt_expires', Date.now() + response.expiresIn * 1000); token = response.accessToken; } return token; }; // Add custom headers for browser requests OpenAPI.HEADERS = { 'X-Client-Platform': 'browser', 'X-Client-Version': '1.0.0' }; // Enable credentials for cross-origin requests if needed OpenAPI.WITH_CREDENTIALS = true; ``` -------------------------------- ### Get Supported Tokens Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/api-reference/one-click-service.md Retrieves a list of all tokens supported by the 1Click API for swaps. This endpoint does not require authentication. ```typescript import { OneClickService, TokenResponse } from '@defuse-protocol/one-click-sdk-typescript'; const tokens = await OneClickService.getTokens(); console.log(tokens.map((t: TokenResponse) => ({ symbol: t.symbol, blockchain: t.blockchain, price: t.price, decimals: t.decimals }))); ``` -------------------------------- ### Error Response Format Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md All error responses from the API follow a standard JSON format. This example shows the structure of a typical error response. ```json { "message": "Error description", "details": "Additional error details if available" } ``` -------------------------------- ### authenticate() Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/api-reference/user-auth-service.md Verifies a wallet signature and issues JWT session tokens (access and refresh tokens). This is the initial authentication step for user-specific endpoints. ```APIDOC ## POST /authenticate ### Description Verifies a wallet signature and issues JWT session tokens (access and refresh tokens). This is the initial authentication step for user-specific endpoints. ### Method POST ### Endpoint /authenticate ### Parameters #### Request Body - **requestBody** (AuthenticateRequestDto) - Required - Request containing signed wallet data - **signedData** (MultiPayload) - Required - Wallet signature and signing metadata ### Request Example ```typescript import { UserAuthService, AuthenticateRequestDto } from '@defuse-protocol/one-click-sdk-typescript'; // Assume signedPayload is obtained from user's wallet after signing a message const authRequest: AuthenticateRequestDto = { signedData: signedPayload }; const authResponse = await UserAuthService.authenticate(authRequest); console.log('Access token expires in:', authResponse.expiresIn, 'seconds'); console.log('Refresh token expires in:', authResponse.refreshExpiresIn, 'seconds'); // Set the access token for subsequent API calls import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.TOKEN = authResponse.accessToken; // Save refresh token for later use const savedRefreshToken = authResponse.refreshToken; ``` ### Response #### Success Response (200) - **accessToken** (string) - JWT access token for API calls (use with `OpenAPI.TOKEN`) - **refreshToken** (string) - JWT refresh token for obtaining new access tokens - **expiresIn** (number) - Access token expiration time in seconds - **refreshExpiresIn** (number) - Refresh token expiration time in seconds #### Response Example ```json { "accessToken": "eyJ...", "refreshToken": "eyJ...", "expiresIn": 3600, "refreshExpiresIn": 86400 } ``` ### Error Handling - Status 400: Invalid signed data - Status 401: Signature verification failed ### Authentication No JWT token required for this endpoint; uses wallet signature verification instead. ``` -------------------------------- ### REST Endpoint Specifications Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Specifications for 9 REST endpoints, including authentication, parameters, response schemas, status codes, and cURL examples. ```APIDOC ## REST Endpoint Specifications ### Description Specifications for 9 REST endpoints, detailing authentication requirements, query/body parameters with types, response schema tables, HTTP status codes, and cURL request examples. ### Endpoints - **GET /v0/tokens** (public) - **POST /v0/quote** (protected) - **GET /v0/status** (protected) - **GET /v0/any-input/withdrawals** (protected) - **POST /v0/deposit/submit** (protected) - **POST /v0/generate-intent** (protected) - **POST /v0/submit-intent** (protected) - **POST /v0/auth/*** (public) - **GET /v0/account/balances** (protected) ``` -------------------------------- ### Get Swap Quote Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/api-reference/one-click-service.md Generates a swap quote based on provided parameters, including assets, amounts, and slippage. Requires JWT authentication. ```typescript import { OneClickService, QuoteRequest } from '@defuse-protocol/one-click-sdk-typescript'; const quoteRequest: QuoteRequest = { dry: false, swapType: QuoteRequest.swapType.EXACT_INPUT, slippageTolerance: 100, // 1% originAsset: 'nep141:arb-0xaf88d065e77c8cc2239327c5edb3a432268e5831.omft.near', depositType: QuoteRequest.depositType.ORIGIN_CHAIN, destinationAsset: 'nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near', amount: '1000000', refundTo: '0x2527D02599Ba641c19FEa793cD0F167589a0f10D', refundType: QuoteRequest.refundType.ORIGIN_CHAIN, recipient: '13QkxhNMrTPxoCkRdYdJ65tFuwXPhL5gLS2Z5Nr6gjRK', recipientType: QuoteRequest.recipientType.DESTINATION_CHAIN, deadline: '2025-08-06T14:15:22Z' }; const quote = await OneClickService.getQuote(quoteRequest); console.log('Deposit to:', quote.quote.depositAddress); console.log('Expected output:', quote.quote.amountOut); console.log('Min output:', quote.quote.minAmountOut); ``` -------------------------------- ### API Reference File Structure Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt This details the expected file structure for API reference documentation, including main service files and specialized references for errors, signatures, configuration, authentication, and accounts. ```text /workspace/home/output/ ├── README.md (Master index, 421 lines) ├── types.md (Type reference, 626 lines) ├── endpoints.md (REST API spec, 600 lines) ├── configuration.md (Config guide, 563 lines) └── api-reference/ ├── one-click-service.md (Main service, 358 lines) ├── error-handling.md (Error reference, 375 lines) ├── quote-signature.md (Signatures, 341 lines) ├── open-api-config.md (Config, 272 lines) ├── user-auth-service.md (Auth, 154 lines) └── account-service.md (Account, 66 lines) ``` -------------------------------- ### AccountService Method Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the AccountService class covers the getBalances() method, including parameter and response details. ```typescript getBalances() ``` -------------------------------- ### Authentication Header Format Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/endpoints.md All protected endpoints require the JWT token in the Authorization header. This example shows how to format the header using a static token. ```typescript const headers = { 'Authorization': `Bearer ${OpenAPI.TOKEN}` }; ``` -------------------------------- ### OpenAPI Configuration Properties Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/api-reference/open-api-config.md Configure global settings for SDK requests, such as base URL, authentication, and custom headers. ```APIDOC ## OpenAPI Configuration This section details the properties available for configuring the global OpenAPI settings. ### BASE The base URL for all API requests. - **Type:** `string` - **Default:** `'https://1click.chaindefuser.com'` - **Example:** ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.BASE = 'https://staging.1click.api.local'; ``` ### VERSION The API version string. - **Type:** `string` - **Default:** `'0.1.10'` - **Note:** Read-only, set by the SDK. ### WITH_CREDENTIALS Determines whether to include credentials (cookies, authorization headers) in cross-origin requests. - **Type:** `boolean` - **Default:** `false` - **Example:** ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.WITH_CREDENTIALS = true; ``` ### CREDENTIALS Credential mode for cross-origin requests. - **Type:** `'include' | 'omit' | 'same-origin'` - **Default:** `'include'` - **Values:** - `'include'`: Always send credentials. - `'omit'`: Never send credentials. - `'same-origin'`: Send credentials only for same-origin requests. - **Example:** ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.CREDENTIALS = 'omit'; ``` ### TOKEN JWT authentication token for protected endpoints. Can be a static string or a function that returns a fresh token. - **Type:** `string | Resolver | undefined` - **Default:** `undefined` - **Usage - Static Token:** ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; const JWT_TOKEN = '...'; OpenAPI.TOKEN = JWT_TOKEN; ``` - **Usage - Dynamic Token Provider:** ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.TOKEN = async () => { const response = await fetch('...'); const data = await response.json(); return data.accessToken; }; ``` - **Protected Endpoints Requiring TOKEN:** - `OneClickService.getQuote()` - `OneClickService.submitDepositTx()` - `OneClickService.getExecutionStatus()` - `OneClickService.generateIntent()` - `OneClickService.submitIntent()` - `OneClickService.getAnyInputQuoteWithdrawals()` - `AccountService.getBalances()` ### USERNAME Username for HTTP Basic Authentication. - **Type:** `string | Resolver | undefined` - **Default:** `undefined` - **Note:** Not typically used with 1Click API. ### PASSWORD Password for HTTP Basic Authentication. - **Type:** `string | Resolver | undefined` - **Default:** `undefined` - **Note:** Not typically used with 1Click API. ### HEADERS Custom HTTP headers to include in all requests. - **Type:** `Record | Resolver> | undefined` - **Default:** `undefined` - **Example - Static Headers:** ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.HEADERS = { 'X-Custom-Header': 'value' }; ``` - **Example - Dynamic Headers:** ```typescript import { OpenAPI } from '@defuse-protocol/one-click-sdk-typescript'; OpenAPI.HEADERS = () => ({ 'X-Timestamp': new Date().toISOString() }); ``` ``` -------------------------------- ### Get Specific Token Balances Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/api-reference/account-service.md Retrieve balances for a specified list of token IDs for the authenticated user. Requires a valid session token to be set in the SDK. ```typescript import { AccountService } from '@defuse-protocol/one-click-sdk-typescript'; const tokenIds = [ 'nep141:usdc.near', 'nep141:usdt.near', 'nep141:wnear.near' ]; const response = await AccountService.getBalances(tokenIds); console.log('USDC Balance:', response.balances[0].available); console.log('USDT Balance:', response.balances[1].available); console.log('wNEAR Balance:', response.balances[2].available); ``` -------------------------------- ### UserAuthService Methods Source: https://github.com/defuse-protocol/one-click-sdk-typescript/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the UserAuthService class details the authenticate() and refresh() methods, along with token and session management patterns. ```typescript authenticate() refresh() ```