### Install SIP Protocol SDK using npm, pnpm, or yarn Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Installs the SIP Protocol SDK package. It requires Node.js 18+ and TypeScript 5.0+ (recommended). Users can choose their preferred package manager for installation. ```bash # npm npm install @sip-protocol/sdk # pnpm (recommended) pnpm add @sip-protocol/sdk # yarn yarn add @sip-protocol/sdk ``` -------------------------------- ### Create a Transparent Intent Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Example of creating a transparent intent with the SIP SDK. This is a standard cross-chain swap without any privacy features, prioritizing speed. ```typescript const intent = await sip .intent() .input('near', 'NEAR', 100n) .output('ethereum', 'ETH') .privacy(PrivacyLevel.TRANSPARENT) .build() ``` -------------------------------- ### Install and Run SIP Docs Dev Server (Bash) Source: https://github.com/sip-protocol/docs-sip/blob/main/CLAUDE.md Commands to install project dependencies and start the development server for the SIP documentation website. This allows for local testing and previewing changes before deployment. ```bash npm install npm run dev ``` -------------------------------- ### Create and Verify Pedersen Commitments Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Illustrates the use of Pedersen commitments for privacy. Includes functions for creating a commitment with a blinding factor, verifying a commitment, and performing homomorphic addition on commitments. ```typescript import { commit, verifyOpening, addCommitments } from '@sip-protocol/sdk' // Create a commitment const amount = 1000n const { commitment, blinding } = commit(amount) // Verify commitment const isValid = verifyOpening(commitment, amount, blinding) // true // Commitments are homomorphic const c1 = commit(100n) const c2 = commit(200n) const sum = addCommitments(c1.commitment, c2.commitment) // sum commits to 300n ``` -------------------------------- ### Generate and Use Viewing Keys Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Demonstrates the functionality of viewing keys for privacy and compliance. Shows how to generate master and derived viewing keys, encrypt data for a specific viewing key holder, and decrypt that data. ```typescript import { generateViewingKey, deriveViewingKey, encryptForViewing, decryptWithViewing } from '@sip-protocol/sdk' // Generate master viewing key const masterKey = generateViewingKey('/m/44/501/0') // Derive child keys const auditKey = deriveViewingKey(masterKey, '/audit/2024') // Encrypt data for viewing key holder const encrypted = encryptForViewing(txData, auditKey) // Decrypt with key const decrypted = decryptWithViewing(encrypted, auditKey) ``` -------------------------------- ### Create a Compliant Intent with Viewing Key Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Example of creating a compliant intent for institutional use. It includes a viewing key for selective disclosure, allowing regulatory compliance while maintaining a degree of privacy. ```typescript const viewingKey = sip.generateViewingKey('/m/44/501/0/audit') const intent = await sip .intent() .input('solana', 'SOL', 5_000_000_000n) .output('near', 'NEAR') .privacy(PrivacyLevel.COMPLIANT) .viewingKey(viewingKey) .build() ``` -------------------------------- ### Configure tsconfig.json for SIP SDK Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Recommended TypeScript configuration for the SIP SDK. Ensures proper module resolution and strict type checking. No additional @types packages are needed as the SDK includes full type definitions. ```json { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "strict": true, "esModuleInterop": true } } ``` -------------------------------- ### Handle SIP SDK Errors Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Provides an example of error handling within the SIP SDK. It shows how to catch potential errors, identify them as SIP errors, and check for specific error codes like INVALID_CHAIN or INVALID_AMOUNT. ```typescript import { SIPError, ValidationError, ErrorCode, isSIPError, hasErrorCode } from '@sip-protocol/sdk' try { const intent = await sip.intent()...build() } catch (error) { if (isSIPError(error)) { if (hasErrorCode(error, ErrorCode.INVALID_CHAIN)) { console.error('Invalid chain specified') } else if (hasErrorCode(error, ErrorCode.INVALID_AMOUNT)) { console.error('Invalid amount') } } throw error } ``` -------------------------------- ### Create a Shielded Intent with ETH to ZEC Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Demonstrates creating a fully shielded intent for high-privacy transactions. This example shows swapping ETH for ZEC with hidden sender, amount, and recipient. ```typescript const intent = await sip .intent() .input('ethereum', 'ETH', 1_000_000_000_000_000_000n) // 1 ETH .output('zcash', 'ZEC') .privacy(PrivacyLevel.SHIELDED) .build() ``` -------------------------------- ### Create and Execute a Shielded Intent Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Demonstrates creating a shielded cross-chain intent using the SIP SDK. It initializes the SDK, builds an intent with hidden inputs/outputs and privacy, fetches quotes from solvers, and executes the transaction with the best quote. ```typescript import { SIP, PrivacyLevel } from '@sip-protocol/sdk' // 1. Initialize the SDK const sip = new SIP({ network: 'testnet' }) // 2. Create a shielded intent using the builder pattern const intent = await sip .intent() .input('solana', 'SOL', 1_000_000_000n) // 1 SOL (in lamports) .output('ethereum', 'ETH') // Receive ETH .privacy(PrivacyLevel.SHIELDED) // Enable privacy .build() // 3. Get quotes from solvers const quotes = await sip.getQuotes(intent.intent) // 4. Execute with best quote if (quotes.length > 0) { const result = await sip.execute(intent, quotes[0]) console.log('Transaction:', result.txHash) } ``` -------------------------------- ### SIP Solver Implementation Interface and Example Source: https://context7.com/sip-protocol/docs-sip/llms.txt Defines the `SIPSolver` interface for implementing SIP-compatible solvers and provides an example implementation, `MySolver`. This interface outlines methods for handling intents, generating quotes, and fulfilling transactions, including optional methods for cancellation and status checks. The example demonstrates how to implement these methods, including checking chain support, expiry, liquidity, generating quotes with fees, and fulfilling intents with ZK proof verification. ```typescript interface SIPSolver { readonly info: Solver readonly capabilities: SolverCapabilities canHandle(intent: SolverVisibleIntent): Promise generateQuote(intent: SolverVisibleIntent): Promise fulfill(intent: ShieldedIntent, quote: SolverQuote): Promise cancel?(intentId: string): Promise getStatus?(intentId: string): Promise } // Example implementation class MySolver implements SIPSolver { async canHandle(intent: SolverVisibleIntent): Promise { // Check chain support if (!this.capabilities.outputChains.includes(intent.outputAsset.chain)) { return false } // Check expiry if (intent.expiry < Date.now() / 1000) { return false } // Check liquidity const liquidity = await this.getLiquidity(intent.outputAsset) return liquidity >= intent.minOutputAmount } async generateQuote(intent: SolverVisibleIntent): Promise { if (!await this.canHandle(intent)) { return null } const price = await this.getPrice(intent.outputAsset) const baseOutput = intent.minOutputAmount const spread = 50 // 0.5% const outputWithSpread = baseOutput + (baseOutput * BigInt(spread)) / 10000n const fee = (outputWithSpread * BigInt(30)) / 10000n // 0.3% fee return { quoteId: generateQuoteId(), intentId: intent.intentId, solverId: this.info.id, outputAmount: outputWithSpread, estimatedTime: 30, expiry: Math.floor(Date.now() / 1000) + 60, fee, signature: await this.signQuote(quoteId, outputWithSpread), } } async fulfill( intent: ShieldedIntent, quote: SolverQuote, ): Promise { try { // Verify quote validity if (quote.expiry < Date.now() / 1000) { throw new Error('Quote expired') } // Verify ZK proofs await this.verifyProofs(intent) // Execute swap - send to stealth address const txHash = await this.executeSwap( intent.outputAsset, quote.outputAmount, intent.recipientStealth.address, // One-time address ) // Generate fulfillment proof const proof = await this.generateFulfillmentProof(intent, quote, txHash) return { intentId: intent.intentId, status: IntentStatus.FULFILLED, outputAmount: quote.outputAmount, fulfillmentProof: proof, } } catch (error) { return { intentId: intent.intentId, status: IntentStatus.FAILED, error: error.message, } } } } // Define solver capabilities const capabilities: SolverCapabilities = { inputChains: ['near', 'ethereum', 'solana'], outputChains: ['near', 'ethereum', 'solana', 'zcash'], supportedPairs: new Map([ ['near', ['ethereum', 'solana']], ['ethereum', ['near', 'zcash']], ]), supportsShielded: true, supportsCompliant: true, avgFulfillmentTime: 30, } ``` -------------------------------- ### Install SIP Protocol SDK Source: https://context7.com/sip-protocol/docs-sip/llms.txt Command to install the SIP Protocol SDK using npm. This is the first step to integrating privacy-preserving cross-chain transactions into your application. ```bash # Install the SDK npm install @sip-protocol/sdk ``` -------------------------------- ### Implementing fulfill Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/solver-integration.md Outlines the `fulfill` method, responsible for verifying quote validity, proofs, executing the swap to a stealth address, and generating a fulfillment proof. ```APIDOC ## Implementing `fulfill` ### Description The `fulfill` method is the core execution logic. It verifies the provided quote and proofs, executes the swap by sending assets to the recipient's stealth address, and generates a proof of fulfillment. ### Method `fulfill(intent: ShieldedIntent, quote: SolverQuote): Promise` ### Parameters #### Request Body - **intent** (ShieldedIntent) - The shielded intent containing hidden details. - **recipientStealth** (StealthAddress) - The one-time stealth address for the recipient. - **address** (string) - The stealth address. - **quote** (SolverQuote) - The quote generated by the solver for this intent. ### Logic 1. **Verify Quote Expiry**: Checks if `quote.expiry` is in the future. 2. **Verify Proofs**: Calls `verifyProofs(intent)` to validate necessary cryptographic proofs. 3. **Execute Swap**: Interacts with the blockchain to send `quote.outputAmount` of `intent.outputAsset` to `intent.recipientStealth.address`. 4. **Generate Fulfillment Proof**: Creates a cryptographic proof confirming the successful execution of the swap. ### Returns - **`FulfillmentResult`** object: - **`intentId`** (string): The ID of the intent. - **`status`** (IntentStatus): The status of the fulfillment (e.g., `FULFILLED`, `FAILED`). - **`outputAmount`** (BigInt): The actual amount of output asset transferred. - **`fulfillmentProof`** (string): The proof of successful fulfillment. - **`error`** (string, optional): An error message if the fulfillment failed. ### Response Example (FulfillmentResult - Success) ```json { "intentId": "someIntentId", "status": "FULFILLED", "outputAmount": "1000000000000000000", "fulfillmentProof": "0xabc..." } ``` ### Response Example (FulfillmentResult - Failure) ```json { "intentId": "someIntentId", "status": "FAILED", "error": "Quote expired" } ``` ``` -------------------------------- ### SolanaWalletAdapter Implementation Example (TypeScript) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/specs/wallet-adapter-spec.md Shows an example of using the Solana wallet adapter from '@sip-protocol/sdk' for Phantom, Solflare, and other Solana wallets. It includes connecting, signing messages, and signing multiple transactions. ```typescript import { createSolanaAdapter, getSolanaProvider } from '@sip-protocol/sdk' const provider = getSolanaProvider() const adapter = createSolanaAdapter(provider) await adapter.connect() console.log('Connected:', adapter.address) // Sign message const signature = await adapter.signMessage(message) // Sign all transactions (Solana-specific) const signedTxs = await adapter.signAllTransactions(transactions) ``` -------------------------------- ### Generate and Use Stealth Addresses Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/getting-started.md Code snippet for working with stealth addresses, a core privacy primitive. It covers generating a public meta-address, creating a one-time stealth address for sending, and deriving the private key for receiving. ```typescript import { generateStealthMetaAddress, generateStealthAddress, deriveStealthPrivateKey } from '@sip-protocol/sdk' // Recipient: Generate meta-address (share publicly) const metaAddress = generateStealthMetaAddress('ethereum') // Sender: Generate one-time stealth address const { stealthAddress, ephemeralPublicKey } = generateStealthAddress(metaAddress) // Recipient: Derive private key to spend funds const privateKey = deriveStealthPrivateKey( stealthAddress, ephemeralPublicKey, metaAddress.spendingKey, metaAddress.viewingKey ) ``` -------------------------------- ### Example: Full Swap Flow Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/integrations/near-intents.md This example demonstrates a complete private swap flow using the SIP Protocol SDK. It covers initializing the SIP client, connecting a wallet, creating a shielded intent, fetching quotes, and executing the swap. ```APIDOC ## Example: Full Swap Flow This example illustrates a comprehensive private swap using the SIP SDK, including intent creation, quote retrieval, and execution. ### Method N/A (SDK Function) ### Endpoint N/A (SDK Function) ### Parameters N/A ### Request Example ```typescript import { SIP, PrivacyLevel, createEthereumAdapter } from '@sip-protocol/sdk' async function privateSwap() { // Initialize const sip = new SIP({ network: 'testnet' }) // Connect wallet const adapter = createEthereumAdapter(window.ethereum) await adapter.connect() sip.connect(adapter) // Create shielded intent const intent = await sip .intent() .input('ethereum', 'ETH', 1_000_000_000_000_000_000n) .output('solana', 'SOL') .privacy(PrivacyLevel.SHIELDED) .slippage(0.5) .expiry(30) // 30 minutes .build() // Get quotes (via NEAR Intents) const quotes = await sip.getQuotes(intent.intent) // Execute best quote const result = await sip.execute(intent, quotes[0]) console.log('Swap complete:', result.txHash) } ``` ### Response #### Success Response - **txHash** (string) - The transaction hash of the completed swap. ``` -------------------------------- ### Mock Solver Testing with TypeScript Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/solver-integration.md Demonstrates how to create and use a mock solver for testing purposes. It shows the instantiation of a `MockSolver` with specific configurations and how to generate and assert quote amounts against a visible intent. Requires '@sip-protocol/sdk'. ```typescript import { MockSolver, createMockSolver } from '@sip-protocol/sdk' const solver = createMockSolver({ name: 'Test Solver', supportedChains: ['near', 'ethereum'], feePercent: 0.005, executionDelay: 100, failureRate: 0, }) const quote = await solver.generateQuote(visibleIntent) expect(quote.outputAmount).toBeGreaterThan(visibleIntent.minOutputAmount) ``` -------------------------------- ### Implementing canHandle Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/solver-integration.md Demonstrates the logic for the `canHandle` method, which checks if a solver is capable of fulfilling a given intent based on chain support, expiry, minimum amount, and liquidity. ```APIDOC ## Implementing `canHandle` ### Description This function checks if the solver can handle the provided `SolverVisibleIntent`. It verifies chain compatibility, ensures the intent has not expired, checks if the minimum output amount meets the solver's threshold, and confirms sufficient liquidity for the output asset. ### Method `canHandle(intent: SolverVisibleIntent): Promise` ### Parameters #### Request Body - **intent** (SolverVisibleIntent) - The visible part of the intent that the solver can process. - **intent.outputAsset** (Asset) - The asset to be received. - **chain** (string) - The chain of the output asset. - **intent.expiry** (number) - The Unix timestamp when the intent expires. - **intent.minOutputAmount** (BigInt) - The minimum amount of the output asset required. ### Logic 1. Checks if the `intent.outputAsset.chain` is supported by the solver's capabilities. 2. Verifies that the `intent.expiry` is in the future. 3. Confirms that `intent.minOutputAmount` is greater than or equal to the solver's `info.minOrderSize`. 4. Assesses if the solver has enough liquidity for the `intent.minOutputAmount` of the `intent.outputAsset`. ### Returns - `true` if the solver can handle the intent, `false` otherwise. ``` -------------------------------- ### Implementing generateQuote Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/solver-integration.md Details the process of generating a quote for a solvable intent, calculating output amounts, fees, and creating a signed quote object. ```APIDOC ## Implementing `generateQuote` ### Description This method generates a price quote for a given `SolverVisibleIntent` after confirming it can be handled. It calculates the output amount considering a spread, determines the fee, and constructs a signed `SolverQuote` object. ### Method `generateQuote(intent: SolverVisibleIntent): Promise` ### Parameters #### Request Body - **intent** (SolverVisibleIntent) - The visible part of the intent. ### Logic 1. Calls `canHandle` to ensure the intent is processable. 2. Fetches the current price for the `intent.outputAsset`. 3. Calculates `outputWithSpread` by adding a spread percentage to the `intent.minOutputAmount`. 4. Computes the `fee` based on a `feePercent`. 5. Generates a unique `quoteId`. 6. Sets the quote `expiry` (e.g., 60 seconds from now). 7. Signs the quote details to create a `signature`. ### Returns - A `SolverQuote` object containing the quote details if successful. - `null` if the intent cannot be handled. ### Response Example (SolverQuote) ```json { "quoteId": "someQuoteId", "intentId": "someIntentId", "solverId": "solver123", "outputAmount": "1000000000000000000", "estimatedTime": 30, "expiry": 1678886400, "fee": "10000000000000000", "signature": "0x..." } ``` ``` -------------------------------- ### EthereumWalletAdapter Implementation Example (TypeScript) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/specs/wallet-adapter-spec.md Demonstrates how to create and use an Ethereum wallet adapter using the '@sip-protocol/sdk'. It covers connecting, signing messages, and signing transactions for Ethereum-compatible wallets. ```typescript import { createEthereumAdapter, getEthereumProvider } from '@sip-protocol/sdk' const provider = getEthereumProvider() const adapter = createEthereumAdapter(provider) await adapter.connect() console.log('Connected:', adapter.address) // Sign message const signature = await adapter.signMessage( new TextEncoder().encode('Hello SIP') ) // Sign transaction const signedTx = await adapter.signTransaction({ to: '0x...', value: '0x...', data: '0x...' }) ``` -------------------------------- ### ESLint Installation Command (Shell) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/security/internal-review.md This shell command installs ESLint, a popular linter for JavaScript and TypeScript. Installing ESLint is recommended to enforce code quality standards, identify potential issues early, and maintain consistency across the codebase. This addresses the CODE-1 finding regarding the absence of ESLint in the project root. ```shell npm install eslint --save-dev # or yarn add eslint --dev # or pnpm add eslint --save-dev ``` -------------------------------- ### Install SIP SDK using npm Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/index.mdx Installs the Shielded Intents Protocol SDK package from npm. This package provides the necessary tools to integrate SIP's privacy features into your applications. ```bash npm install @sip-protocol/sdk ``` -------------------------------- ### Initialize SIP Client and Build Intent (TypeScript) Source: https://context7.com/sip-protocol/docs-sip/llms.txt Demonstrates initializing the SIP client and building a shielded cross-chain intent. It shows how to specify input and output assets, set the privacy level, get quotes from solvers, and execute the transaction. ```typescript import { SIP, PrivacyLevel } from '@sip-protocol/sdk' // Initialize the SIP client const sip = new SIP({ network: 'testnet' }) // Create a shielded cross-chain intent const intent = await sip .intent() .input('solana', 'SOL', 1_000_000_000n) // 1 SOL in lamports .output('ethereum', 'ETH') // Receive ETH .privacy(PrivacyLevel.SHIELDED) // Enable privacy .build() // Get quotes from solvers const quotes = await sip.getQuotes(intent.intent) // Execute with best quote if (quotes.length > 0) { const result = await sip.execute(intent, quotes[0]) console.log('Transaction:', result.txHash) } ``` -------------------------------- ### Running Migration Tests Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/api-migration.md This snippet shows commands for running tests and type checking during the API migration process. It includes options for running the full test suite, specific integration tests, and performing type checks. ```bash # Run full test suite pnpm test -- --run # Run specific tests pnpm test -- tests/integration --run # Type check pnpm typecheck ``` -------------------------------- ### Pedersen Commitments: verifyCommitment() -> verifyOpening() Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/api-migration.md Update your commitment verification logic from the deprecated `verifyCommitment()` to the new `verifyOpening()` function. The new function requires separate parameters for commitment, value, and blinding factor, and has a different import path. ```APIDOC ## POST /api/commitments/verify ### Description Verifies if a given commitment matches the provided value and blinding factor. ### Method POST ### Endpoint /api/commitments/verify ### Parameters #### Request Body - **commitment** (HexString) - Required - The commitment value to verify. - **value** (bigint) - Required - The original value. - **blinding** (HexString) - Required - The blinding factor. ### Request Example ```json { "commitment": "0x...", "value": 1000n, "blinding": "0x..." } ``` ### Response #### Success Response (200) - **isValid** (boolean) - True if the commitment is valid, false otherwise. #### Response Example ```json { "isValid": true } ``` ``` -------------------------------- ### SIP Solver Interface Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/solver-integration.md The core interface that SIP solvers must implement to interact with the SIP network. It defines methods for checking intent feasibility, generating quotes, and fulfilling intents. ```APIDOC ## SIP Solver Interface ### Description This interface outlines the essential methods a SIP solver needs to implement to participate in fulfilling shielded intents. It includes methods for providing solver information, checking capabilities, determining if an intent can be handled, generating price quotes, and executing the fulfillment of an intent. ### Methods - **`info`**: (readonly Solver) - Provides static information about the solver. - **`capabilities`**: (readonly SolverCapabilities) - Describes the network and asset capabilities of the solver. - **`canHandle(intent: SolverVisibleIntent)`**: (Promise) - Determines if the solver can process the given intent. - **`generateQuote(intent: SolverVisibleIntent)`**: (Promise) - Generates a price quote for a given intent if it can be handled. - **`fulfill(intent: ShieldedIntent, quote: SolverQuote)`**: (Promise) - Executes the swap and fulfills the intent based on the provided quote. - **`cancel?(intentId: string)`**: (Promise) - Optional method to cancel a previously accepted intent. - **`getStatus?(intentId: string)`**: (Promise) - Optional method to retrieve the status of a fulfillment. ``` -------------------------------- ### Troubleshooting Test Coverage Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/deployment.md Details how to check test coverage locally for the SIP Protocol SDK. This command, executed within the SDK package directory, allows developers to review test coverage and ensure it meets project standards before triggering CI. ```bash # Check coverage locally cd packages/sdk pnpm test:coverage ``` -------------------------------- ### Migrate Pedersen Commitment Verification: verifyCommitment() to verifyOpening() Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/api-migration.md This snippet demonstrates migrating from the deprecated `verifyCommitment()` to the new `verifyOpening()` function for verifying Pedersen commitments. The new API requires separate parameters for commitment, value, and blinding, and changes the import path. ```typescript import { verifyCommitment } from '@sip-protocol/sdk' const isValid = verifyCommitment(commitment, 1000n) // commitment is { value: HexString, blindingFactor: HexString } ``` ```typescript import { verifyOpening } from '@sip-protocol/sdk/commitment' const isValid = verifyOpening(commitment, 1000n, blinding) // commitment is HexString, blinding is HexString ``` ```typescript // Before import { verifyCommitment } from '@sip-protocol/sdk' const isValid = verifyCommitment(commitmentObj, 1000n) // After import { verifyOpening } from '@sip-protocol/sdk/commitment' const isValid = verifyOpening( commitmentObj.value, 1000n, commitmentObj.blindingFactor ) ``` -------------------------------- ### Implement `generateQuote` Method for SIP Solver Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/solver-integration.md Demonstrates the TypeScript implementation of the `generateQuote` method for a SIP solver. It first validates the intent using `canHandle`, then calculates the output amount considering spread and fees, and finally returns a signed quote object. ```typescript async generateQuote(intent: SolverVisibleIntent): Promise { if (!await this.canHandle(intent)) { return null } const price = await this.getPrice(intent.outputAsset) const baseOutput = intent.minOutputAmount const outputWithSpread = baseOutput + (baseOutput * BigInt(spread)) / 10000n const fee = (outputWithSpread * BigInt(feePercent)) / 10000n return { quoteId: generateQuoteId(), intentId: intent.intentId, solverId: this.info.id, outputAmount: outputWithSpread, estimatedTime: 30, expiry: Math.floor(Date.now() / 1000) + 60, fee, signature: await this.signQuote(quoteId, outputWithSpread), } } ``` -------------------------------- ### Implement `fulfill` Method for SIP Solver Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/solver-integration.md Shows the TypeScript implementation of the `fulfill` method for a SIP solver. This method handles the execution of a swap, including verifying quote validity, proofs, executing the transaction to a stealth address, and generating a fulfillment proof. ```typescript async fulfill( intent: ShieldedIntent, quote: SolverQuote, ): Promise { try { // Verify quote validity if (quote.expiry < Date.now() / 1000) { throw new Error('Quote expired') } // Verify proofs await this.verifyProofs(intent) // Execute swap - send to stealth address const txHash = await this.executeSwap( intent.outputAsset, quote.outputAmount, intent.recipientStealth.address, // One-time address ) // Generate fulfillment proof const proof = await this.generateFulfillmentProof(intent, quote, txHash) return { intentId: intent.intentId, status: IntentStatus.FULFILLED, outputAmount: quote.outputAmount, fulfillmentProof: proof, } } catch (error) { return { intentId: intent.intentId, status: IntentStatus.FAILED, error: error.message, } } } ``` -------------------------------- ### Implement `canHandle` Method for SIP Solver Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/solver-integration.md Provides a TypeScript implementation for the `canHandle` method within a SIP solver. It checks for chain support, intent expiry, minimum output amount, and sufficient liquidity to determine if the solver can fulfill a given intent. ```typescript async canHandle(intent: SolverVisibleIntent): Promise { // Check chain support if (!this.capabilities.outputChains.includes(intent.outputAsset.chain)) { return false } // Check expiry if (intent.expiry < Date.now() / 1000) { return false } // Check minimum amount if (intent.minOutputAmount < this.info.minOrderSize) { return false } // Check liquidity const liquidity = await this.getLiquidity(intent.outputAsset) return liquidity >= intent.minOutputAmount } ``` -------------------------------- ### Manual npm Package Publishing Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/deployment.md Provides instructions for manually building and publishing SIP Protocol packages to the npm registry. This involves building all packages, then sequentially publishing the `@sip-protocol/types` and `@sip-protocol/sdk` packages. Ensure you navigate to the correct package directory before publishing. ```bash # Build all packages pnpm build # Publish types first (sdk depends on it) cd packages/types npm publish --access public # Publish SDK cd ../sdk npm publish --access public ``` -------------------------------- ### Build and Preview SIP Docs (Bash) Source: https://github.com/sip-protocol/docs-sip/blob/main/CLAUDE.md Commands to build the SIP documentation website for production and preview the built output. This is useful for testing the production build locally. ```bash npm run build npm run preview ``` -------------------------------- ### Generate and Use SIP Stealth Addresses (TypeScript) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/concepts/stealth-address.md Demonstrates the complete lifecycle of a SIP stealth address in TypeScript, from recipient setup and address sharing to sender payment creation and recipient claiming. It utilizes functions from the '@sip-protocol/sdk' package. This example covers generating meta-addresses, encoding them for sharing, creating stealth addresses for specific payments, checking ownership, and deriving the private key for claiming funds. ```typescript import { generateStealthMetaAddress, generateStealthAddress, checkStealthAddress, deriveStealthPrivateKey, encodeStealthMetaAddress, decodeStealthMetaAddress } from '@sip-protocol/sdk' // Recipient setup (one-time) const meta = generateStealthMetaAddress('ethereum') const encoded = encodeStealthMetaAddress(meta.metaAddress) // Share `encoded` publicly // Sender creates payment const decoded = decodeStealthMetaAddress(encoded) const { stealthAddress, ephemeralPublicKey } = generateStealthAddress(decoded) // Recipient scans const isMine = checkStealthAddress( stealthAddress, meta.spendingPrivateKey, meta.viewingPrivateKey ) // Recipient claims if (isMine) { const pk = deriveStealthPrivateKey( stealthAddress, ephemeralPublicKey, meta.spendingPrivateKey, meta.viewingPrivateKey ) // Use pk to spend from stealthAddress } ``` -------------------------------- ### TypeScript MockProofProvider Initialization Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/specs/zk-architecture.md Demonstrates how to initialize the SIP SDK with a MockProofProvider in TypeScript. This is useful for testing and development purposes, allowing for the generation of mock proofs without the need for a full ZK circuit compilation and execution environment. The example shows passing a new instance of MockProofProvider to the SIP constructor. ```typescript const sip = new SIP({ network: 'testnet', proofProvider: new MockProofProvider() }) ``` -------------------------------- ### Solver Capabilities Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/solver-integration.md Defines the capabilities of a SIP solver, including supported chains, asset pairs, and whether it supports shielded or compliant transactions. ```APIDOC ## Solver Capabilities ### Description This structure defines the capabilities of a SIP solver, outlining the blockchain networks and asset pairs it supports, and its support for specific transaction types like shielded and compliant swaps. ### Fields - **`inputChains`** (string[]) - An array of blockchain network identifiers from which the solver can accept inputs. - **`outputChains`** (string[]) - An array of blockchain network identifiers to which the solver can send outputs. - **`supportedPairs`** (Map) - A map where keys are input chain identifiers and values are arrays of output chain identifiers supported for swaps between those chains. - **`supportsShielded`** (boolean) - Indicates if the solver supports fulfilling shielded intents. - **`supportsCompliant`** (boolean) - Indicates if the solver supports fulfilling compliant intents. - **`avgFulfillmentTime`** (number) - The average time in seconds the solver takes to fulfill an intent. ### Example ```json { "inputChains": ["near", "ethereum", "solana"], "outputChains": ["near", "ethereum", "solana", "zcash"], "supportedPairs": { "near": ["ethereum", "solana"], "ethereum": ["near", "zcash"] }, "supportsShielded": true, "supportsCompliant": true, "avgFulfillmentTime": 30 } ``` ``` -------------------------------- ### Meta-Address Encoding Format (Example) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/specs/sip-spec.md Illustrates the standard URI format for encoding a meta-address, including the chain, spending public key, and viewing public key, separated by colons. ```plaintext sip::: Example: sip:ethereum:0x02abc...def:0x03123...456 Where: - chain ∈ {ethereum, solana, near, zcash, polygon, ...} - spendingKey: 33-byte compressed public key (hex) - viewingKey: 33-byte compressed public key (hex) ``` -------------------------------- ### Manual Swap Steps using Low-Level API (TypeScript) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/integrations/near-integration-design.md Illustrates advanced control over swap operations using the Low-Level API, involving manual steps for intent creation, quoting, and deposit. This approach requires more setup, including instantiating NEARIntentsAdapter and OneClickClient, and handling each stage of the swap process separately. ```typescript import { NEARIntentsAdapter, OneClickClient } from '@sip-protocol/sdk' const oneClick = new OneClickClient({ baseUrl: '...' }) const adapter = new NEARIntentsAdapter({ oneClick }) // Manual control over each step const intent = await createShieldedIntent({ ... }) // Assuming createShieldedIntent is defined elsewhere const quote = await adapter.getQuote( await adapter.prepareQuote(intent) ) // Deposit separately const depositTx = await wallet.send(quote.depositAddress, quote.amountIn) // Assuming wallet is defined elsewhere // Track status const status = await adapter.getStatus(quote.depositAddress) ``` -------------------------------- ### GET /v0/tokens Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/integrations/near-1click-api.md Retrieves a list of supported tokens with their metadata, including blockchain, address, symbol, decimals, and current USD price. ```APIDOC ## GET /v0/tokens ### Description Returns available tokens with metadata. ### Method GET ### Endpoint /v0/tokens ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **defuse_asset_id** (string) - Unique identifier for the asset. - **blockchain** (string) - The blockchain network the token is on. - **address** (string) - The contract address of the token. - **symbol** (string) - The trading symbol of the token. - **decimals** (integer) - The number of decimal places for the token. - **priceUsd** (string) - The current price of the token in USD. #### Response Example ```json [ { "defuse_asset_id": "near:mainnet:wrap.near", "blockchain": "near", "address": "wrap.near", "symbol": "wNEAR", "decimals": 24, "priceUsd": "3.45" } ] ``` ``` -------------------------------- ### Initialize SIP with NoirProofProvider (TypeScript) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/specs/zk-architecture.md This snippet demonstrates how to initialize the SIP client using the NoirProofProvider. It specifies the network and the paths for the WASM and circuit files required by the NoirProofProvider. This is intended for production environments. ```typescript const sip = new SIP({ network: 'mainnet', proofProvider: new NoirProofProvider({ wasmPath: '/circuits/funding.wasm', circuitPath: '/circuits/' }) }) ``` -------------------------------- ### Pedersen Commitments: createCommitment() -> commit() Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/guides/api-migration.md Migrate from the deprecated `createCommitment()` function to the new `commit()` function for generating Pedersen commitments. The new function offers clearer property names and a different import path. ```APIDOC ## POST /api/commitments ### Description Generates a Pedersen commitment and its blinding factor. ### Method POST ### Endpoint /api/commitments ### Parameters #### Request Body - **value** (bigint) - Required - The value to commit. ### Request Example ```json { "value": 1000n } ``` ### Response #### Success Response (200) - **commitment** (HexString) - The generated commitment value. - **blinding** (HexString) - The generated blinding factor. #### Response Example ```json { "commitment": "0x...", "blinding": "0x..." } ``` ``` -------------------------------- ### TypeScript SDK for Generating Funding Proof Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/specs/funding-proof.md This TypeScript code demonstrates how to use the SIP Protocol SDK to generate a Funding Proof. It requires initializing a proof provider and providing parameters such as commitment hash, minimum amount, actual balance, and blinding factor. The generated proof is returned if valid. ```typescript import { MockProofProvider, FundingProofParams } from '@sip-protocol/sdk' const proofProvider = new MockProofProvider() const params: FundingProofParams = { commitmentHash: '0x...', minimumAmount: 500n, actualBalance: 1000n, blindingFactor: '0x...' } const result = await proofProvider.generateFundingProof(params) if (result.valid) { console.log('Proof:', result.proof) } ``` -------------------------------- ### Client-Side Proof Generation with NoirJS (TypeScript) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/specs/zk-architecture.md This code example shows how to perform client-side proof generation in a browser environment using NoirJS. It includes steps for compiling a Noir circuit, creating a prover, and generating a proof with specific input parameters. Ensure necessary imports are available. ```typescript import { compile, createProver } from '@noir-lang/noir_js' // Load circuit const circuit = await compile('/circuits/funding.nr') const prover = await createProver(circuit) // Generate proof in browser const proof = await prover.prove({ actual_balance: 1000n, blinding_factor: randomField(), commitment_hash: commitmentHash, minimum_amount: 500n }) ``` -------------------------------- ### Integrating Wallet Adapter with SIP Protocol (TypeScript) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/specs/wallet-adapter-spec.md Demonstrates how to integrate a connected wallet adapter with the SIP protocol. This example shows connecting an Ethereum adapter and then attaching it to a SIP instance to enable wallet-signed intents. ```typescript import { SIP, createEthereumAdapter, getEthereumProvider } from '@sip-protocol/sdk' const sip = new SIP({ network: 'testnet' }) // Connect wallet const provider = getEthereumProvider() const adapter = createEthereumAdapter(provider) await adapter.connect() // Attach to SIP sip.connect(adapter) // Now SIP can sign intents const intent = await sip .intent() .input('ethereum', 'ETH', 1_000_000_000_000_000_000n) .output('solana', 'SOL') .build() // Will sign with connected wallet ``` -------------------------------- ### Solver Relay API - Get Status (JSON-RPC) Source: https://github.com/sip-protocol/docs-sip/blob/main/src/content/docs/integrations/near-1click-api.md Retrieves the execution status of an intent identified by its quote hash. Possible statuses include PENDING, TX_BROADCASTED, SETTLED, and NOT_FOUND_OR_NOT_VALID. ```JSON { "jsonrpc": "2.0", "method": "get_status", "params": { "quote_hash": "0x..." }, "id": 3 } ```