{"_id":"@darklakefi/ts-sdk-on-chain","name":"@darklakefi/ts-sdk-on-chain","dist-tags":{"latest":"0.2.0"},"versions":{"0.2.0":{"name":"@darklakefi/ts-sdk-on-chain","version":"0.2.0","description":"Darklake DEX TypeScript SDK - A standalone SDK for interacting directly with Darklake AMM pools","main":"dist/index.js","types":"dist/index.d.ts","engines":{"node":">=22"},"keywords":["darklake","dex","amm","solana","typescript","sdk"],"author":{"name":"Darklake Team"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/darklakefi/ts-sdk-on-chain.git"},"homepage":"https://github.com/darklakefi/ts-sdk-on-chain","dependencies":{"@coral-xyz/anchor":"=0.30.1","@solana/spl-token":"^0.4.1","@solana/web3.js":"^1.87.6","bn.js":"^5.2.1","circomlibjs":"^0.1.7","decimal.js":"^10.6.0","ffjavascript":"^0.3.0","snarkjs":"^0.7.5"},"devDependencies":{"@types/bn.js":"^5.1.5","@types/node":"^20.10.0","@typescript-eslint/eslint-plugin":"^6.13.0","@typescript-eslint/parser":"^6.13.0","eslint":"^8.54.0","husky":"^9.1.7","jest":"^29.7.0","lint-staged":"^16.2.3","prettier":"^3.6.2","typescript":"^5.3.0","shx":"^0.3.4","rimraf":"^6.0.1"},"lint-staged":{"*.{js,ts,json,md}":["prettier --check"]},"scripts":{"build":"tsc && shx mkdir -p dist/zk && shx cp -r src/zk/circuits dist/zk/","dev":"tsc --watch","test":"jest","lint":"eslint src/**/*.ts","clean":"rimraf dist","format":"prettier --write .","format:check":"prettier --check ."},"_id":"@darklakefi/ts-sdk-on-chain@0.2.0","bugs":{"url":"https://github.com/darklakefi/ts-sdk-on-chain/issues"},"_integrity":"sha512-jnfKFklxq4F342pGpnWeVp1S4HV0aRUw57kFxKGiE/HUSCi5h9S7+z5ykFAS1GiHl+UVnRMrSQA+Jrh3yDyTDQ==","_resolved":"/tmp/03a64f0669b0b9ebc6d90c1052237800/darklakefi-ts-sdk-on-chain-0.2.0.tgz","_from":"file:darklakefi-ts-sdk-on-chain-0.2.0.tgz","_nodeVersion":"22.12.0","_npmVersion":"11.0.0","dist":{"integrity":"sha512-jnfKFklxq4F342pGpnWeVp1S4HV0aRUw57kFxKGiE/HUSCi5h9S7+z5ykFAS1GiHl+UVnRMrSQA+Jrh3yDyTDQ==","shasum":"ecdbf439b25d23e925bc25dd716c76a5ec756f53","tarball":"https://registry.npmjs.org/@darklakefi/ts-sdk-on-chain/-/ts-sdk-on-chain-0.2.0.tgz","fileCount":55,"unpackedSize":4481537,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQChrpZYmId6WKBixrrchsJxie+eENJihkimURmQpWAhvAIgX6ssHdnUsHCVviWnFDYcv4CJ/zQak43eQPrIBco1HUA="}]},"_npmUser":{"name":"darklake-bot","email":"online-services@darklake.fi"},"directories":{},"maintainers":[{"name":"jsondoge","email":"matas@darklake.fi"},{"name":"darklake-bot","email":"online-services@darklake.fi"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/ts-sdk-on-chain_0.2.0_1759329295228_0.36309537091392374"},"_hasShrinkwrap":false}},"time":{"created":"2025-10-01T14:34:55.157Z","0.2.0":"2025-10-01T14:34:55.527Z","modified":"2025-10-01T14:34:55.786Z"},"maintainers":[{"name":"jsondoge","email":"matas@darklake.fi"},{"name":"darklake-bot","email":"online-services@darklake.fi"}],"description":"Darklake DEX TypeScript SDK - A standalone SDK for interacting directly with Darklake AMM pools","homepage":"https://github.com/darklakefi/ts-sdk-on-chain","keywords":["darklake","dex","amm","solana","typescript","sdk"],"repository":{"type":"git","url":"git+https://github.com/darklakefi/ts-sdk-on-chain.git"},"author":{"name":"Darklake Team"},"bugs":{"url":"https://github.com/darklakefi/ts-sdk-on-chain/issues"},"license":"MIT","readme":"# Darklake DEX TypeScript SDK\n\nA TypeScript client SDK for interacting with Darklake AMM pools on Solana. This SDK provides a clean interface for trading, liquidity provision, and pool management on the Darklake DEX.\n\n## Features\n\n- **Trading**: Swap tokens with automatic SOL/WSOL handling\n- **Liquidity Management**: Add and remove liquidity from pools\n- **Pool Management**: Initialize new pools\n- **Order Management**: Handle swap orders with settlement and cancellation\n- **TypeScript Support**: Full TypeScript support with comprehensive type definitions\n\n## Installation\n\n```bash\npnpm install @darklakefi/ts-sdk-on-chain\n```\n\n## Quick Start\n\n### Basic Setup\n\n```typescript\nimport { DarklakeSDK, BN } from '@darklakefi/ts-sdk-on-chain';\n\n// Initialize the SDK\nconst sdk = new DarklakeSDK(\n  'https://api.devnet.solana.com', // RPC endpoint\n  CommitmentLevel.Confirmed, // Commitment level\n  true, // isDevnet\n  'my-app', // label (optional, max 10 chars)\n  'ref123', // ref code (optional, max 20 chars)\n);\n```\n\n## Transaction Functions (ending with 'tx')\n\nThese functions return complete `VersionedTransaction` objects ready to be signed and sent. They automatically handle SOL/WSOL wrapping and include all necessary instructions. This includes `loadPool` and `updateAccounts` calls internally.\n\n### `swapTx(tokenIn, tokenOut, amountIn, minAmountOut, tokenOwner)`\n\nCreates a complete swap transaction.\n\n```typescript\nconst { tx, orderKey, minOut, salt } = await sdk.swapTx(\n  tokenIn, // PublicKey - input token mint\n  tokenOut, // PublicKey - output token mint\n  amountIn, // BN - input amount\n  minAmountOut, // BN - minimum output amount\n  tokenOwner, // PublicKey - token owner\n);\n```\n\n### `finalizeTx(orderKey, unwrapWsol, minOut, salt, settleSigner?)`\n\nFinalizes a swap order by settling, canceling, or slashing it.\n\n```typescript\nconst { tx } = await sdk.finalizeTx(\n  orderKey, // PublicKey - order key from swapTx\n  true, // boolean - unwrap WSOL to SOL\n  minOut, // BN - minimum output amount\n  salt, // Uint8Array - salt from swapTx\n  settleSigner, // PublicKey - optional settle signer\n);\n```\n\n### `addLiquidityTx(tokenX, tokenY, maxAmountX, maxAmountY, amountLp, user)`\n\nAdds liquidity to a pool.\n\n```typescript\nconst { tx } = await sdk.addLiquidityTx(\n  tokenX, // PublicKey - first token mint\n  tokenY, // PublicKey - second token mint\n  maxAmountX, // BN - maximum amount of token X\n  maxAmountY, // BN - maximum amount of token Y\n  amountLp, // BN - LP tokens to mint\n  user, // PublicKey - user public key\n);\n```\n\n### `removeLiquidityTx(tokenX, tokenY, minAmountX, minAmountY, amountLp, user)`\n\nRemoves liquidity from a pool.\n\n```typescript\nconst { tx } = await sdk.removeLiquidityTx(\n  tokenX, // PublicKey - first token mint\n  tokenY, // PublicKey - second token mint\n  minAmountX, // BN - minimum amount of token X to receive\n  minAmountY, // BN - minimum amount of token Y to receive\n  amountLp, // BN - LP tokens to burn\n  user, // PublicKey - user public key\n);\n```\n\n### `initializePoolTx(tokenX, tokenY, amountX, amountY, user)`\n\nInitializes a new liquidity pool.\n\n```typescript\nconst { tx } = await sdk.initializePoolTx(\n  tokenX, // PublicKey - first token mint\n  tokenY, // PublicKey - second token mint\n  amountX, // BN - initial amount of token X\n  amountY, // BN - initial amount of token Y\n  user, // PublicKey - user public key\n);\n```\n\n## Instruction Functions (ending with 'ix')\n\nThese functions return `TransactionInstruction` objects for manual transaction building. **Important**: When using instruction functions, you are responsible for calling `loadPool` and `updateAccounts` before starting pool usage, and `updateAccounts` before each further call.\n\n### Prerequisites for Instruction Functions\n\n```typescript\n// Before using any instruction function, you MUST:\n// 1. Load the pool data\nawait sdk.loadPool(tokenMintX, tokenMintY);\n\n// 2. Update accounts with latest chain data\nawait sdk.updateAccounts();\n\n// 3. For each subsequent ix calls, update accounts again\nawait sdk.updateAccounts();\n```\n\n### `swapIx(swapParamsIx)`\n\nCreates a swap instruction.\n\n```typescript\nconst swapParamsIx: SwapParamsIx = {\n  sourceMint: tokenIn, // PublicKey\n  destinationMint: tokenOut, // PublicKey\n  tokenTransferAuthority: user, // PublicKey\n  inAmount: amountIn, // BN\n  swapMode: SwapMode.ExactIn, // SwapMode\n  minOut: minAmountOut, // BN\n  salt: generateRandomSalt(), // Uint8Array\n};\n\nconst swapInstruction = await sdk.swapIx(swapParamsIx);\n```\n\n### `finalizeIx(finalizeParamsIx)`\n\nCreates a finalize instruction (settle, cancel, or slash).\n\n```typescript\nconst finalizeParamsIx: FinalizeParamsIx = {\n  settleSigner: settleSigner, // PublicKey\n  orderOwner: orderOwner, // PublicKey\n  unwrapWsol: true, // boolean\n  minOut: minOut, // BN\n  salt: salt, // Uint8Array\n  output: output, // BN\n  commitment: commitment, // BN\n  deadline: deadline, // BN\n  currentSlot: currentSlot, // BN\n};\n\nconst finalizeInstruction = await sdk.finalizeIx(finalizeParamsIx);\n```\n\n### `addLiquidityIx(addLiquidityParamsIx)`\n\nCreates an add liquidity instruction.\n\n```typescript\nconst addLiquidityParamsIx: AddLiquidityParamsIx = {\n  user: user, // PublicKey\n  amountLp: amountLp, // BN\n  maxAmountX: maxAmountX, // BN\n  maxAmountY: maxAmountY, // BN\n};\n\nconst addLiquidityInstruction = await sdk.addLiquidityIx(addLiquidityParamsIx);\n```\n\n### `removeLiquidityIx(removeLiquidityParamsIx)`\n\nCreates a remove liquidity instruction.\n\n```typescript\nconst removeLiquidityParamsIx: RemoveLiquidityParamsIx = {\n  user: user, // PublicKey\n  amountLp: amountLp, // BN\n  minAmountX: minAmountX, // BN\n  minAmountY: minAmountY, // BN\n};\n\nconst removeLiquidityInstruction = await sdk.removeLiquidityIx(\n  removeLiquidityParamsIx,\n);\n```\n\n### `initializePoolIx(initializePoolParamsIx)`\n\nCreates an initialize pool instruction.\n\n```typescript\nconst initializePoolParamsIx: InitializePoolParamsIx = {\n  user: user, // PublicKey\n  amountX: amountX, // BN\n  amountY: amountY, // BN\n  tokenX: tokenX, // PublicKey\n  tokenXProgram: tokenXProgram, // PublicKey\n  tokenY: tokenY, // PublicKey\n  tokenYProgram: tokenYProgram, // PublicKey\n};\n\nconst initializePoolInstruction = await sdk.initializePoolIx(\n  initializePoolParamsIx,\n);\n```\n\n## Utility Functions\n\n### `getOrder(orderOwner)`\n\nGets a parsed order or null if not found. This function does not use internal state and pings directly the on-chain data.\n\n```typescript\nconst order: Order | null = await sdk.getOrder(orderOwner);\nif (order) {\n  console.log('Order found:', order);\n} else {\n  console.log('No order found for this user');\n}\n```\n\n### `sortTokens(tokenMintX, tokenMintY)`\n\nGets the order of tokens used by the DEX. Returns tokens in the correct order for pool operations.\n\n```typescript\nconst [orderedTokenX, orderedTokenY] = sdk.sortTokens(tokenMintX, tokenMintY);\n```\n\n## State Management Functions\n\n### `loadPool(tokenMintX, tokenMintY)`\n\nLoads pool data for internal state tracking. **Required** before using instruction functions call when using `...ix()` functions.\n\n```typescript\nconst [poolKey, orderedTokenMintX, orderedTokenMintY] = await sdk.loadPool(\n  tokenMintX,\n  tokenMintY,\n);\n```\n\n### `updateAccounts()`\n\nUpdates internal state with latest chain data. **Required** before each instruction function call when using `...ix()` functions.\n\n```typescript\nawait sdk.updateAccounts();\n```\n\n## Complete Trading Example\n\n```typescript\nimport { DarklakeSDK, PublicKey, BN } from '@darklakefi/ts-sdk-on-chain';\nimport { Connection, Keypair } from '@solana/web3.js';\n\n// Initialize SDK\nconst sdk = new DarklakeSDK(\n  'https://api.devnet.solana.com',\n  'confirmed',\n  true,\n  'my-app',\n  'ref123',\n);\n\n// Setup\nconst connection = new Connection('https://api.devnet.solana.com');\nconst wallet = Keypair.generate();\nconst tokenIn = new PublicKey('So11111111111111111111111111111111111111111'); // SOL\nconst tokenOut = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC\nconst amountIn = new BN(1000000000); // 1 SOL\n\n// Get quote\nconst quote = await sdk.quote(tokenIn, tokenOut, amountIn);\nconsole.log(`Expected output: ${quote.outAmount.toString()}`);\n\n// Create swap transaction\nconst { tx, orderKey, minOut, salt } = await sdk.swapTx(\n  tokenIn,\n  tokenOut,\n  amountIn,\n  new BN(quote.outAmount.muln(0.95)), // 5% slippage\n  wallet.publicKey,\n);\n\n// Sign and send\nconst signedTx = await wallet.signTransaction(tx);\nconst signature = await connection.sendTransaction(signedTx);\nconsole.log('Swap transaction sent:', signature);\n\n// Wait for confirmation, then finalize\nawait connection.confirmTransaction(signature);\n\nconst { tx: finalizeTx } = await sdk.finalizeTx(\n  orderKey,\n  true, // unwrap WSOL\n  minOut,\n  salt,\n);\n\nconst signedFinalizeTx = await wallet.signTransaction(finalizeTx);\nconst finalizeSignature = await connection.sendTransaction(signedFinalizeTx);\nconsole.log('Finalize transaction sent:', finalizeSignature);\n```\n\n## Important Notes\n\n### Quote Return Structure\n\nThe `quote()` function returns a `Quote` object with the following structure:\n\n```typescript\ninterface Quote {\n  inAmount: BN; // Amount that the exchange will use to trade, calculated by subtracting ALL fees from the user input. So it's NOT the user input value.\n  outAmount: BN; // The output amount from the exchange EXCLUDING any transfer fees imposed by the token itself (if it does so)\n  feeAmount: BN; // The total amount of fees deducted by the exchange NOT including any fees imposed by tokens\n  feeMint: PublicKey; // Pubkey address of a token in which the fees are charged\n  feePct: BN; // The current total fee rate of the trade in percentage. Max value 1000000 = 100%\n}\n```\n\n**Key Points:**\n\n- `inAmount` is the actual amount used for trading after all exchange fees are deducted (both dex and token transfer fees if any)\n- `outAmount` dex output, excludes any token-level transfer fees (e.g., USDC transfer fees)\n- `feeAmount` only includes exchange fees, not token transfer fees\n- `feePct` same feeAmount in basis points where 1000000 = 100%\n\n### State Management Responsibility\n\nWhen using instruction functions (ending with 'ix'), you are responsible for:\n\n1. **Before starting pool usage**: Call `loadPool(tokenMintX, tokenMintY)`\n2. **Before each instruction call**: Call `updateAccounts()`\n\nThis ensures the SDK has the latest pool and account data for accurate calculations.\n\n### SOL/WSOL Handling\n\nThe Darklake DEX does not support direct SOL pairs - only WSOL (Wrapped SOL) pairs are supported:\n\n- **Transaction Functions**: Automatically handle SOL/WSOL conversion\n- **Instruction Functions**: Require manual handling of SOL/WSOL wrapping\n\n### Versioned Transactions\n\nThe SDK uses Versioned Transactions by default for better performance and reduced transaction size.\n\n### Address Lookup Tables\n\nThe SDK includes pre-configured address lookup tables for devnet and mainnet usage to optimize transaction size.\n\n## Error Handling\n\nThe SDK throws descriptive errors for common issues:\n\n```typescript\ntry {\n  const quote = await sdk.quote(tokenIn, tokenOut, amountIn);\n} catch (error) {\n  if (error.message.includes('Pool not found')) {\n    // Handle pool not found\n  } else if (error.message.includes('Order not found')) {\n    // Handle order not found\n  }\n  // Handle other errors\n}\n```\n\n## Development\n\n### Building\n\n```bash\npnpm run build\n```\n\n### Linting\n\n```bash\npnpm run lint\n```\n\n### Formatting\n\n```bash\npnpm run format\n```\n\n## License\n\nMIT License - see LICENSE file for details.\n\n## Support\n\nFor issues and questions:\n\n- Check the examples in the repository\n- Review the SDK source code\n- Open an issue on the repository\n\n---\n\n**Note**: This SDK is for interacting with the Darklake DEX on Solana. Always test thoroughly on devnet before using on mainnet.\n","readmeFilename":"README.md","_rev":"1-d02da9b12eb8ba22be4b25215752f490"}