@paxoslabs/amplify-sdk 0.1.1 → 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +0 -2
  2. package/README.md +42 -0
  3. package/dist/{chunk-REKEQLQA.mjs → chunk-4ORV7PFT.mjs} +3 -3
  4. package/dist/{chunk-REKEQLQA.mjs.map → chunk-4ORV7PFT.mjs.map} +1 -1
  5. package/dist/{chunk-GS7TDQXA.js → chunk-76SRRIGW.js} +8 -8
  6. package/dist/{chunk-GS7TDQXA.js.map → chunk-76SRRIGW.js.map} +1 -1
  7. package/dist/{chunk-XXHRCCZS.mjs → chunk-AQFFMJX7.mjs} +3 -3
  8. package/dist/chunk-AQFFMJX7.mjs.map +1 -0
  9. package/dist/{chunk-B2QCI6ET.js → chunk-EWJDKRSY.js} +308 -30
  10. package/dist/chunk-EWJDKRSY.js.map +1 -0
  11. package/dist/{chunk-HI44AMLC.mjs → chunk-LJPJWJ2Y.mjs} +24 -19
  12. package/dist/chunk-LJPJWJ2Y.mjs.map +1 -0
  13. package/dist/{chunk-ITB7FXG4.js → chunk-OJOKPBK7.js} +3 -3
  14. package/dist/chunk-OJOKPBK7.js.map +1 -0
  15. package/dist/{chunk-KYR6BFAE.js → chunk-SMIA4ULA.js} +38 -33
  16. package/dist/chunk-SMIA4ULA.js.map +1 -0
  17. package/dist/{chunk-DTFLXAZJ.js → chunk-TF3S7T6P.js} +147 -5
  18. package/dist/chunk-TF3S7T6P.js.map +1 -0
  19. package/dist/{chunk-VIULRHK6.mjs → chunk-UURNMLRT.mjs} +3 -3
  20. package/dist/{chunk-VIULRHK6.mjs.map → chunk-UURNMLRT.mjs.map} +1 -1
  21. package/dist/{chunk-LSNRG5Z2.js → chunk-WWTNCRXX.js} +4 -4
  22. package/dist/{chunk-LSNRG5Z2.js.map → chunk-WWTNCRXX.js.map} +1 -1
  23. package/dist/{chunk-ZILA73XN.mjs → chunk-Y3QNUDV6.mjs} +144 -4
  24. package/dist/chunk-Y3QNUDV6.mjs.map +1 -0
  25. package/dist/{chunk-CUGK4ZBJ.mjs → chunk-YDMFT2R7.mjs} +304 -30
  26. package/dist/chunk-YDMFT2R7.mjs.map +1 -0
  27. package/dist/core.js +16 -16
  28. package/dist/core.js.map +1 -1
  29. package/dist/core.mjs +6 -6
  30. package/dist/core.mjs.map +1 -1
  31. package/dist/display.d.mts +1 -1
  32. package/dist/display.d.ts +1 -1
  33. package/dist/display.js +12 -12
  34. package/dist/display.mjs +4 -4
  35. package/dist/{exchange-rate-BfPH_fQt.d.mts → exchange-rate-DCB2CY9v.d.mts} +5 -0
  36. package/dist/{exchange-rate-Cp1ddpw4.d.ts → exchange-rate-DOmoqut9.d.ts} +5 -0
  37. package/dist/index.d.mts +456 -8
  38. package/dist/index.d.ts +456 -8
  39. package/dist/index.js +402 -215
  40. package/dist/index.js.map +1 -1
  41. package/dist/index.mjs +292 -123
  42. package/dist/index.mjs.map +1 -1
  43. package/dist/utils.js +5 -5
  44. package/dist/utils.mjs +2 -2
  45. package/package.json +2 -1
  46. package/dist/chunk-B2QCI6ET.js.map +0 -1
  47. package/dist/chunk-CUGK4ZBJ.mjs.map +0 -1
  48. package/dist/chunk-DTFLXAZJ.js.map +0 -1
  49. package/dist/chunk-HI44AMLC.mjs.map +0 -1
  50. package/dist/chunk-ITB7FXG4.js.map +0 -1
  51. package/dist/chunk-KYR6BFAE.js.map +0 -1
  52. package/dist/chunk-XXHRCCZS.mjs.map +0 -1
  53. package/dist/chunk-ZILA73XN.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vaults/deposit/approve-deposit.ts","../src/abi/community-code-depositor-abi.ts","../src/vaults/deposit/utils.ts","../src/vaults/deposit/deposit.ts","../src/abi/erc2612-abi.ts","../src/vaults/deposit/deposit-with-permit.ts","../src/vaults/withdraw/approve-withdraw.ts","../src/vaults/withdraw/utils.ts","../src/vaults/withdraw/bulk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,EAAO,OACpC,CAAA,CAAA;AAAA,QACA;AAAA,UACE,QAAA,EAAU,gCAAA;AAAA,UACV,KAAA,EACE,iBAAA,EAAmB,KAAA,IACnB,uBAAA,EAAyB,SACzB,yBAAA,EAA2B;AAAA;AAC/B,OACF;AAAA,IACF;AAGA,IAAA,MAAM,WAAA,GAAc,oBAAA;AAAA,MAClB,iBAAA,CAAkB,MAAA;AAAA;AAAA,MAClB,uBAAA,CAAwB,MAAA;AAAA;AAAA,MACxB;AAAA,KACF;AAGA,IAAA,MAAM,oBAAA,GAAuBA,UAAAA;AAAA,MAC3B,WAAA;AAAA,MACA,yBAAA,CAA0B;AAAA,KAC5B;AAEA,IAAA,MAAM,WAAA,GAAc,kBAAA;AAAA,MAClB,oBAAA;AAAA,MACA,WAAA;AAAA,MACA;AAAA,KACF;AAEA,IAAA,OAAO;AAAA,MACL,GAAA,EAAK,cAAA;AAAA,MACL,OAAA,EAAS,6BAAA;AAAA,MACT,YAAA,EAAc,qBAAA;AAAA,MACd,IAAA,EAAM,CAAC,kBAAA,EAAoB,gBAAA,EAAkB,WAAW,CAAA;AAAA,MACxD,OAAA,EAAS;AAAA,KACX;AAAA,EACF,SAAS,KAAA,EAAO;AAEd,IAAA,IAAI,iBAAiB,QAAA,EAAU;AAC7B,MAAA,MAAM,KAAA;AAAA,IACR;AAGA,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,6CACE,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CACvD,CAAA,CAAA;AAAA,MACA;AAAA,QACE,QAAA,EAAU,gCAAA;AAAA,QACV,KAAA,EAAO;AAAA;AACT,KACF;AAAA,EACF;AACF","file":"index.mjs","sourcesContent":["/**\n * @file Approve Asset for deposit functionality for Paxos Labs vaults\n * @module vaults/deposit\n */\n\nimport { type Address, erc20Abi, parseUnits } from \"viem\";\nimport {\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport { DEFAULT_APPROVAL_AMOUNT } from \"../../constants\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\n\n/**\n * Parameters required for preparing an approval transaction\n * @interface PrepareApproveDepositTokenTxParams\n * @property {Address} depositToken - Token contract address to approve\n * @property {Address} boringVaultAddress - Address of the BoringVault to approve spending\n * @property {string} [approvalAmount] - Optional amount to approve (defaults to maximum approval)\n * @property {number | string} chainId - ID of the chain where the approval will occur\n */\ninterface PrepareApproveDepositTokenTxParams {\n yieldType: YieldType;\n depositToken: Address;\n approvalAmount?: string;\n chainId: ChainId;\n}\n\n/**\n * Result object containing transaction data for an ERC20 approval operation\n * @interface ApproveDepositTokenTxData\n * @property {typeof erc20Abi} abi - ABI for the ERC20 token contract\n * @property {Address} address - Address of the ERC20 token being approved\n * @property {'approve'} functionName - Name of the function to call\n * @property {[Address, bigint]} args - Arguments for the approve function:\n * [spender (boringVault address), amount]\n */\ninterface ApproveDepositTokenTxData {\n abi: typeof erc20Abi;\n address: Address;\n functionName: \"approve\";\n args: [Address, bigint];\n}\n\n/**\n * Prepares the transaction data needed to approve a deposit token for the vault\n *\n * This function prepares an ERC20 approval transaction that allows the vault's\n * BoringVault contract to spend the user's deposit tokens.\n *\n * @example\n * ```typescript\n * const approveData = await prepareApproveDepositToken({\n * depositToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * boringVaultAddress: '0x1234...',\n * approvalAmount: \"1000.0\", // Approve 1000 USDC\n * chainId: 1,\n * });\n * ```\n *\n * @param {PrepareApproveDepositTokenTxParams} params - Parameters for the approval operation\n * @returns {Promise<ApproveDepositTokenTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If parameters are invalid\n */\nexport async function prepareApproveDepositTokenTxData({\n yieldType,\n depositToken,\n approvalAmount,\n chainId,\n}: PrepareApproveDepositTokenTxParams): Promise<ApproveDepositTokenTxData> {\n const normalizedChainId = toChainId(chainId);\n\n try {\n const config = await findVaultByConfig({\n assetAddress: depositToken,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n if (!config) {\n throw new APIError(\n `No vault found for token address ${depositToken} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n const boringVaultAddress = config.vault.boringVaultAddress;\n if (!boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n\n // Get asset decimals for amount calculation\n const assets = await getAssetsFromCache({ address: depositToken });\n if (assets.length === 0) {\n throw new APIError(\n `Asset metadata not found for token ${depositToken} on chain ${normalizedChainId}`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n\n const decimals = assets[0].decimals;\n const amount = approvalAmount\n ? parseUnits(approvalAmount, decimals)\n : DEFAULT_APPROVAL_AMOUNT;\n return {\n abi: erc20Abi,\n address: depositToken,\n functionName: \"approve\",\n args: [boringVaultAddress, amount],\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare approval transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareApproveDepositToken\",\n cause: error,\n }\n );\n }\n}\n\nexport type { ApproveDepositTokenTxData, PrepareApproveDepositTokenTxParams };\n","export const CommunityCodeDepositorAbi = [\n {\n inputs: [\n {\n internalType: \"contract TellerWithMultiAssetSupport\",\n name: \"_teller\",\n type: \"address\",\n },\n {\n internalType: \"contract INativeWrapper\",\n name: \"_nativeWrapper\",\n type: \"address\",\n },\n {\n internalType: \"contract Authority\",\n name: \"_rolesAuthority\",\n type: \"address\",\n },\n { internalType: \"bool\", name: \"_isNativeDepositSupported\", type: \"bool\" },\n { internalType: \"address\", name: \"_owner\", type: \"address\" },\n ],\n stateMutability: \"nonpayable\",\n type: \"constructor\",\n },\n { inputs: [], name: \"IncorrectNativeDepositAmount\", type: \"error\" },\n { inputs: [], name: \"NativeDepositNotSupported\", type: \"error\" },\n {\n inputs: [],\n name: \"NativeWrapperAccountantDecimalsMismatch\",\n type: \"error\",\n },\n { inputs: [], name: \"PermitFailedAndAllowanceTooLow\", type: \"error\" },\n { inputs: [], name: \"ZeroAddress\", type: \"error\" },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: \"address\", name: \"user\", type: \"address\" },\n {\n indexed: true,\n internalType: \"contract Authority\",\n name: \"newAuthority\",\n type: \"address\",\n },\n ],\n name: \"AuthorityUpdated\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"address\",\n name: \"depositor\",\n type: \"address\",\n },\n {\n indexed: true,\n internalType: \"contract ERC20\",\n name: \"depositAsset\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"uint256\",\n name: \"depositAmount\",\n type: \"uint256\",\n },\n {\n indexed: false,\n internalType: \"uint256\",\n name: \"minimumMint\",\n type: \"uint256\",\n },\n { indexed: false, internalType: \"address\", name: \"to\", type: \"address\" },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"depositHash\",\n type: \"bytes32\",\n },\n {\n indexed: true,\n internalType: \"bytes\",\n name: \"distributorCode\",\n type: \"bytes\",\n },\n ],\n name: \"DepositWithDistributorCode\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: \"address\", name: \"user\", type: \"address\" },\n {\n indexed: true,\n internalType: \"address\",\n name: \"newOwner\",\n type: \"address\",\n },\n ],\n name: \"OwnershipTransferred\",\n type: \"event\",\n },\n {\n inputs: [],\n name: \"authority\",\n outputs: [\n { internalType: \"contract Authority\", name: \"\", type: \"address\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"boringVault\",\n outputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"contract ERC20\", name: \"depositAsset\", type: \"address\" },\n { internalType: \"uint256\", name: \"depositAmount\", type: \"uint256\" },\n { internalType: \"uint256\", name: \"minimumMint\", type: \"uint256\" },\n { internalType: \"address\", name: \"to\", type: \"address\" },\n { internalType: \"bytes\", name: \"distributorCode\", type: \"bytes\" },\n ],\n name: \"deposit\",\n outputs: [{ internalType: \"uint256\", name: \"shares\", type: \"uint256\" }],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"uint256\", name: \"depositAmount\", type: \"uint256\" },\n { internalType: \"uint256\", name: \"minimumMint\", type: \"uint256\" },\n { internalType: \"address\", name: \"to\", type: \"address\" },\n { internalType: \"bytes\", name: \"distributorCode\", type: \"bytes\" },\n ],\n name: \"depositNative\",\n outputs: [{ internalType: \"uint256\", name: \"shares\", type: \"uint256\" }],\n stateMutability: \"payable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"depositNonce\",\n outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"contract ERC20\", name: \"depositAsset\", type: \"address\" },\n { internalType: \"uint256\", name: \"depositAmount\", type: \"uint256\" },\n { internalType: \"uint256\", name: \"minimumMint\", type: \"uint256\" },\n { internalType: \"address\", name: \"to\", type: \"address\" },\n { internalType: \"bytes\", name: \"distributorCode\", type: \"bytes\" },\n { internalType: \"uint256\", name: \"deadline\", type: \"uint256\" },\n { internalType: \"uint8\", name: \"v\", type: \"uint8\" },\n { internalType: \"bytes32\", name: \"r\", type: \"bytes32\" },\n { internalType: \"bytes32\", name: \"s\", type: \"bytes32\" },\n ],\n name: \"depositWithPermit\",\n outputs: [{ internalType: \"uint256\", name: \"shares\", type: \"uint256\" }],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"isNativeDepositSupported\",\n outputs: [{ internalType: \"bool\", name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"nativeWrapper\",\n outputs: [\n { internalType: \"contract INativeWrapper\", name: \"\", type: \"address\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"owner\",\n outputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract Authority\",\n name: \"newAuthority\",\n type: \"address\",\n },\n ],\n name: \"setAuthority\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"teller\",\n outputs: [\n {\n internalType: \"contract TellerWithMultiAssetSupport\",\n name: \"\",\n type: \"address\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"address\", name: \"newOwner\", type: \"address\" }],\n name: \"transferOwnership\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n] as const;\n","import { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport { WAD } from \"../../utils/bigint\";\n\n/**\n * Calculates the minimum amount of tokens to mint based on deposit amount, rate, and slippage\n * @param depositAmount The amount being deposited (in base units)\n * @param rate The current exchange rate between deposit and mint tokens\n * @param vaultTokenDecimals The number of precision decimals of the vault token\n * @param slippage The maximum acceptable slippage as a decimal (e.g., 0.01 for 1%)\n * @returns The minimum amount of tokens that should be minted accounting for slippage in vault token precision decimals\n */\nconst calculateMinimumMint = (\n depositAmount: bigint, // In deposit token decimals\n rate: bigint, // In deposit token decimals\n vaultTokenDecimals: number, // The number of precision decimals of the vault token\n slippage?: number // In bps (e.g., 50 for 0.5%) = 50 / 10000 = 0.005 = 0.5%\n): bigint => {\n const slippageValue = slippage ?? DEFAULT_SLIPPAGE_BPS;\n // Convert bps to WAD format (multiply by WAD/10000)\n const slippageAsBigInt = (BigInt(slippageValue) * WAD.bigint) / BigInt(10000);\n\n // Calculate ideal mint amount without slippage\n const minimumMint = (depositAmount * WAD.bigint) / rate;\n\n // Calculate the amount to subtract for slippage tolerance\n const slippageAmount = (minimumMint * slippageAsBigInt) / WAD.bigint;\n\n // Return mint amount minus slippage buffer\n if (vaultTokenDecimals > 18) {\n return (\n (minimumMint - slippageAmount) *\n BigInt(10) ** (BigInt(vaultTokenDecimals) - BigInt(18))\n );\n }\n return (\n (minimumMint - slippageAmount) /\n BigInt(10) ** (BigInt(18) - BigInt(vaultTokenDecimals))\n );\n};\n\nexport { calculateMinimumMint };\n","/**\n * @file Deposit functionality for Nucleus vaults\n * @module vaults/deposit\n */\n\nimport { type Address, type Hex, parseUnits, stringToHex } from \"viem\";\nimport { CommunityCodeDepositorAbi } from \"../../abi/community-code-depositor-abi\";\nimport { getRateInQuoteWithAssetDecimals } from \"../../api/accountant\";\nimport {\n fetchSupportedAssets,\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport type {\n AmplifyVault,\n SupportedAsset,\n YieldType,\n} from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { calculateMinimumMint } from \"./utils\";\n\n/**\n * Result object containing transaction data for a deposit operation\n * @interface DepositTxData\n * @property {typeof CommunityCodeDepositorAbi} abi - ABI for the CommunityCodeDepositor contract\n * @property {Address} address - Address of the CommunityCodeDepositor contract\n * @property {'deposit'} functionName - Name of the function to call\n * @property {readonly [depositAsset: Address, depositAmount: bigint, minimumMint: bigint, to: Address, distributorCode: Hex]} args - Arguments for the deposit function:\n * [depositAsset, depositAmount, minimumMint, recipientAddress, distributorCode]\n * @property {number} chainId - ID of the chain where the transaction should be executed\n */\ninterface DepositTxData {\n abi: typeof CommunityCodeDepositorAbi;\n address: Address;\n functionName: \"deposit\";\n args: readonly [\n depositAsset: Address,\n depositAmount: bigint,\n minimumMint: bigint,\n to: Address,\n distributorCode: Hex\n ];\n chainId: number;\n}\n/**\n * Parameters for prepareDepositTransactionData()\n * Accepts yieldType, recipientAddress, depositToken, and chainId for automatic vault resolution\n * @interface PrepareDepositTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (e.g., \"PRIME\", \"TBILL\", \"LENDING\")\n * @property {Address} recipientAddress - Ethereum address of the user (recipient of vault shares)\n * @property {Address} depositToken - Token contract address to deposit (matches vault's baseTokenAddress)\n * @property {string} depositAmount - Amount of assets to deposit as a decimal string (e.g., \"1.5\")\n * @property {number | string} chainId - ID of the chain where the deposit will occur\n * @property {number} [slippage] - Maximum acceptable slippage in basis points (e.g., 100 for 1%)\n */\ninterface PrepareDepositTxDataParams {\n yieldType: YieldType;\n recipientAddress: Address;\n depositToken: Address;\n depositAmount: string;\n chainId: ChainId;\n slippage?: number;\n partnerCode?: string;\n}\n\n/**\n * Prepares the transaction data needed to deposit assets into a vault\n *\n * This function calculates the minimum amount of vault tokens to be minted based on\n * the current exchange rate and the specified slippage tolerance. It automatically\n * resolves the vault from yieldType, depositToken, and chainId parameters.\n *\n * ```typescript\n * const depositData = await prepareDepositTransactionData({\n * yieldType: 'PRIME',\n * recipientAddress: '0x1234...',\n * depositToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * depositAmount: \"1.0\",\n * chainId: 1,\n * slippage: 100, // 1% slippage (100 bps)\n * });\n * ```\n *\n * @param {PrepareDepositTransactionDataParams} params - Parameters for the deposit operation\n * @returns {Promise<DepositTransactionData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If vault cannot be resolved, asset not found, or contracts not configured\n */\nexport async function prepareDepositTxData(\n params: PrepareDepositTxDataParams\n): Promise<DepositTxData> {\n const {\n yieldType,\n depositToken,\n depositAmount,\n chainId,\n slippage = DEFAULT_SLIPPAGE_BPS,\n recipientAddress,\n partnerCode,\n } = params;\n\n try {\n const normalizedChainId = toChainId(chainId);\n\n // Implement vault resolution using findVaultByConfig\n let vault: AmplifyVault | null;\n try {\n vault = await findVaultByConfig({\n assetAddress: depositToken,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositToken} with yield type ${yieldType} on chain ${normalizedChainId}: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositTransactionData\",\n cause: error,\n }\n );\n }\n\n // Check if vault was found\n if (!vault) {\n throw new APIError(\n `No vault found for token address ${depositToken} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n {\n endpoint: \"prepareDepositTransactionData\",\n }\n );\n }\n\n // Fetch the asset metadata for the deposit token\n let asset: SupportedAsset | null = null;\n const assets = await getAssetsFromCache({ address: depositToken });\n if (assets.length > 0) {\n // Find the asset for the correct chain\n asset =\n assets.find((a) => a.chains.includes(normalizedChainId)) ||\n assets[0] ||\n null;\n }\n\n if (!asset) {\n throw new APIError(\n `Asset metadata not found for token ${depositToken} on chain ${normalizedChainId}`,\n {\n endpoint: \"prepareDepositTransactionData\",\n }\n );\n }\n\n // Verify transaction data includes correct vault contract addresses\n const communityCodeDepositorAddress = vault.vault\n .communityCodeDepositorAddress as Address;\n const accountantAddress = vault.vault.accountantAddress as Address;\n const depositAssetAddress = asset.address as Address;\n\n // Get exchange rate from accountant (returns tuple from multicall)\n const [depositAssetDecimalsResult, rateInQuoteResult] =\n await getRateInQuoteWithAssetDecimals({\n assetAddress: depositAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n\n // Check decimals call result\n if (depositAssetDecimalsResult.status === \"failure\") {\n throw new APIError(\n `Failed to get asset decimals: ${\n depositAssetDecimalsResult.error?.message || \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositTransactionData\",\n cause: depositAssetDecimalsResult.error,\n }\n );\n }\n\n // Check rate call result\n if (rateInQuoteResult.status === \"failure\") {\n throw new APIError(\n `Failed to get exchange rate: ${\n rateInQuoteResult.error?.message || \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositTransactionData\",\n cause: rateInQuoteResult.error,\n }\n );\n }\n\n // Use decimals from API instead of on-chain call\n const depositAmountAsBigInt = parseUnits(\n depositAmount,\n depositAssetDecimalsResult.result\n );\n\n // Get vault shares asset decimals for minimum mint calculation\n const vaultSharesAssets = await fetchSupportedAssets({\n address: vault.vault.boringVaultAddress,\n });\n\n if (vaultSharesAssets.length === 0) {\n throw new APIError(\n `Vault shares token not found in supported assets: ${vault.vault.boringVaultAddress}`,\n { endpoint: \"prepareDepositTransactionData\" }\n );\n }\n\n const minimumMint = calculateMinimumMint(\n depositAmountAsBigInt,\n rateInQuoteResult.result,\n depositAssetDecimalsResult.result,\n slippage\n );\n\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `CommunityCodeDepositor contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositTransactionData\" }\n );\n }\n\n return {\n abi: CommunityCodeDepositorAbi,\n address: communityCodeDepositorAddress,\n functionName: \"deposit\",\n args: [\n depositAssetAddress,\n depositAmountAsBigInt,\n minimumMint,\n recipientAddress,\n stringToHex(partnerCode || \"\"),\n ],\n chainId: normalizedChainId,\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors with context\n throw new APIError(\n `Failed to prepare deposit transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareDepositTransactionData\",\n cause: error,\n }\n );\n }\n}\n\nexport type { DepositTxData, PrepareDepositTxDataParams };\n","/**\n * ERC2612 Permit ABI\n *\n * Standard ERC20 + ERC2612 permit extension interface.\n * Enables off-chain signed approval (permit) to combine approval + transfer in single transaction.\n *\n * Reference: https://eips.ethereum.org/EIPS/eip-2612\n */\n\nexport const erc2612Abi = [\n // Standard ERC20 functions (subset needed for permit flow)\n {\n constant: true,\n inputs: [{ name: \"_owner\", type: \"address\" }],\n name: \"nonces\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n {\n constant: true,\n inputs: [],\n name: \"DOMAIN_SEPARATOR\",\n outputs: [{ name: \"\", type: \"bytes32\" }],\n type: \"function\",\n },\n {\n constant: false,\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"v\", type: \"uint8\" },\n { name: \"r\", type: \"bytes32\" },\n { name: \"s\", type: \"bytes32\" },\n ],\n name: \"permit\",\n outputs: [],\n type: \"function\",\n },\n {\n constant: true,\n inputs: [],\n name: \"name\",\n outputs: [{ name: \"\", type: \"string\" }],\n type: \"function\",\n },\n {\n constant: true,\n inputs: [],\n name: \"version\",\n outputs: [{ name: \"\", type: \"string\" }],\n type: \"function\",\n },\n] as const;\n\n/**\n * Standard ERC20 ABI (subset for basic token operations)\n */\nexport const erc20Abi = [\n {\n constant: true,\n inputs: [{ name: \"_owner\", type: \"address\" }],\n name: \"balanceOf\",\n outputs: [{ name: \"balance\", type: \"uint256\" }],\n type: \"function\",\n },\n {\n constant: true,\n inputs: [\n { name: \"_owner\", type: \"address\" },\n { name: \"_spender\", type: \"address\" },\n ],\n name: \"allowance\",\n outputs: [{ name: \"remaining\", type: \"uint256\" }],\n type: \"function\",\n },\n {\n constant: false,\n inputs: [\n { name: \"_spender\", type: \"address\" },\n { name: \"_value\", type: \"uint256\" },\n ],\n name: \"approve\",\n outputs: [{ name: \"\", type: \"bool\" }],\n type: \"function\",\n },\n {\n constant: false,\n inputs: [\n { name: \"_to\", type: \"address\" },\n { name: \"_value\", type: \"uint256\" },\n ],\n name: \"transfer\",\n outputs: [{ name: \"\", type: \"bool\" }],\n type: \"function\",\n },\n {\n constant: false,\n inputs: [\n { name: \"_from\", type: \"address\" },\n { name: \"_to\", type: \"address\" },\n { name: \"_value\", type: \"uint256\" },\n ],\n name: \"transferFrom\",\n outputs: [{ name: \"\", type: \"bool\" }],\n type: \"function\",\n },\n {\n constant: true,\n inputs: [],\n name: \"decimals\",\n outputs: [{ name: \"\", type: \"uint8\" }],\n type: \"function\",\n },\n {\n constant: true,\n inputs: [],\n name: \"symbol\",\n outputs: [{ name: \"\", type: \"string\" }],\n type: \"function\",\n },\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\n/**\n * Permit-capable ERC20 ABI (combined ERC20 + ERC2612)\n */\nexport const permitCapableErc20Abi = [\n ...erc20Abi,\n // Add permit-specific functions\n {\n constant: true,\n inputs: [{ name: \"_owner\", type: \"address\" }],\n name: \"nonces\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n {\n constant: true,\n inputs: [],\n name: \"DOMAIN_SEPARATOR\",\n outputs: [{ name: \"\", type: \"bytes32\" }],\n type: \"function\",\n },\n {\n constant: false,\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"v\", type: \"uint8\" },\n { name: \"r\", type: \"bytes32\" },\n { name: \"s\", type: \"bytes32\" },\n ],\n name: \"permit\",\n outputs: [],\n type: \"function\",\n },\n] as const;\n","/**\n * @file Deposit with permit functionality for Nucleus vaults\n * @module vaults/deposit/deposit-with-permit\n */\n\nimport {\n type Address,\n type Hex,\n hexToSignature,\n parseUnits,\n stringToHex,\n} from \"viem\";\nimport { CommunityCodeDepositorAbi } from \"../../abi/community-code-depositor-abi\";\nimport { erc2612Abi } from \"../../abi/erc2612-abi\";\nimport { getRateInQuoteWithAssetDecimals } from \"../../api/accountant\";\nimport {\n fetchSupportedAssets,\n findVaultByConfig,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport { getClient } from \"../../lib/viem/client\";\nimport type {\n AmplifyVault,\n SupportedAsset,\n YieldType,\n} from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { calculateMinimumMint } from \"./utils\";\n\n/**\n * EIP-712 domain separator conforming to the EIP-712 TypedData JSON schema\n * Compatible with standard EIP-712 signing libraries (Privy, wagmi, ethers)\n *\n * This interface matches the domain type from SignTypedDataParams as defined in\n * the EIP-712 specification and implemented by signing libraries.\n *\n * @see {@link https://eips.ethereum.org/EIPS/eip-712#specification-of-the-eth_signtypeddata-json-rpc EIP-712 Specification}\n *\n * @property name - Human-readable name of the signing domain\n * @property version - Version of the signing domain\n * @property chainId - Ethereum chain ID as a number (not bigint)\n * @property verifyingContract - Address of the contract that will verify the signature\n * @property salt - Optional salt for disambiguation\n */\nexport interface EIP712Domain {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n salt?: ArrayBuffer;\n}\n\n/**\n * T008: EIP-2612 Permit type definition\n * Standard structure for permit typed data per EIP-2612 specification\n */\nexport const PERMIT_TYPES = {\n Permit: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n ],\n};\n\n/**\n * T009: Complete EIP-712 typed data for permit signature\n * Returned by prepareDepositPermitSignature() ready for wallet signing\n *\n * @property domain - EIP-712 domain separator with numeric chainId\n * @property types - EIP-2612 Permit type structure (mutable for compatibility)\n * @property message - Permit message fields\n * @property primaryType - Always \"Permit\" for EIP-2612\n */\nexport interface PermitSignatureData {\n domain: EIP712Domain;\n types: {\n Permit: Array<{ name: string; type: string }>;\n };\n message: {\n owner: Address;\n spender: Address;\n value: bigint;\n nonce: bigint;\n deadline: bigint;\n };\n primaryType: \"Permit\";\n}\n\n/**\n * T009: Parsed permit signature components\n * Returned by parsePermitSignature() after converting hex signature\n *\n * @property v - Recovery ID (27 or 28)\n * @property r - First 32 bytes of signature\n * @property s - Second 32 bytes of signature\n */\nexport interface ParsedPermitSignature {\n v: number;\n r: Hex;\n s: Hex;\n}\n\n/**\n * T009: Parameters for prepareDepositPermitSignature\n * Input parameters for generating permit typed data\n *\n * @property yieldType - Vault yield strategy\n * @property depositToken - Token contract address to deposit\n * @property depositAmount - Deposit amount as decimal string\n * @property recipientAddress - User address (permit owner)\n * @property chainId - Blockchain network ID\n * @property deadline - Optional permit expiration (defaults to 1 hour)\n */\nexport interface PrepareDepositPermitSignatureParams {\n yieldType: YieldType;\n depositToken: Address;\n depositAmount: string;\n recipientAddress: Address;\n chainId: number;\n deadline?: bigint;\n}\n\n/**\n * T009: Encoded transaction data for permit deposit\n * Returned by updated prepareDepositWithPermitTransactionData()\n *\n * @property abi - Contract ABI\n * @property functionName - Function name to call\n * @property {readonly [depositAsset: Address, depositAmount: bigint, minimumMint: bigint, to: Address, distributorCode: Hex, deadline: bigint, v: number, r: Hex, s: Hex]} args - Function arguments\n * @property address - Teller contract address\n * @property chainId - Chain ID for transaction\n */\n\nexport interface DepositWithPermitData {\n abi: typeof CommunityCodeDepositorAbi;\n functionName: \"depositWithPermit\";\n args: readonly [\n depositAsset: Address,\n depositAmount: bigint,\n minimumMint: bigint,\n to: Address,\n distributorCode: Hex,\n deadline: bigint,\n v: number,\n r: Hex,\n s: Hex\n ];\n}\n\nexport interface UnencodedDepositWithPermitData {\n data: DepositWithPermitData;\n address: Address;\n chainId: number;\n}\n\n/**\n * T018-T030: Prepare complete EIP-712 typed data for permit signature\n *\n * Reads token metadata (name, version, nonce) from the blockchain and\n * constructs the complete EIP-712 structure for wallet signing.\n *\n * @param params - Permit signature parameters\n * @returns Complete EIP-712 typed data ready for signing\n * @throws {APIError} If token doesn't support EIP-2612, vault not found, or chain unsupported\n *\n * @example\n * ```typescript\n * const permitData = await prepareDepositPermitSignature({\n * yieldType: 'PRIME',\n * depositToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * depositAmount: '1000.0',\n * recipientAddress: recipientAddress,\n * chainId: 1,\n * deadline: BigInt(Math.floor(Date.now() / 1000) + 3600),\n * });\n *\n * // Sign with wallet\n * const signature = await signTypedData(permitData);\n * ```\n */\nexport async function prepareDepositPermitSignature(\n params: PrepareDepositPermitSignatureParams\n): Promise<PermitSignatureData> {\n const {\n yieldType,\n depositToken,\n depositAmount,\n recipientAddress,\n chainId,\n deadline,\n } = params;\n\n try {\n const normalizedChainId = toChainId(chainId);\n\n // T019: Implement vault resolution using findVaultByConfig\n let vault: AmplifyVault | null;\n try {\n vault = await findVaultByConfig({\n assetAddress: depositToken,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositToken} with yield type ${yieldType} on chain ${normalizedChainId}: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n cause: error,\n }\n );\n }\n\n // T028: Check if vault was found\n if (!vault) {\n throw new APIError(\n `No vault found for token address ${depositToken} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n }\n );\n }\n\n // T029: Validate chainId is supported\n const communityCodeDepositorAddress =\n vault.vault.communityCodeDepositorAddress;\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `CommunityCodeDepositor contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositPermitSignature\" }\n );\n }\n\n // T020: Create PublicClient from chainId\n const client = await getClient(normalizedChainId);\n\n // T021: Read token metadata (name, version, nonces) in parallel\n let tokenName: string;\n let tokenVersion: string;\n let nonce: bigint;\n\n try {\n // Attempt to read all three values\n const [nameResult, versionResult, nonceResult] = await Promise.allSettled(\n [\n client.readContract({\n address: depositToken,\n abi: erc2612Abi,\n functionName: \"name\",\n }),\n client.readContract({\n address: depositToken,\n abi: erc2612Abi,\n functionName: \"version\",\n }),\n client.readContract({\n address: depositToken,\n abi: erc2612Abi,\n functionName: \"nonces\",\n args: [recipientAddress],\n }),\n ]\n );\n\n // Extract name\n if (nameResult.status === \"fulfilled\") {\n tokenName = nameResult.value as string;\n } else {\n throw new APIError(`Failed to read token name from ${depositToken}`, {\n endpoint: \"prepareDepositPermitSignature\",\n cause: nameResult.reason,\n });\n }\n\n // T022: Extract version with fallback to \"1\"\n if (versionResult.status === \"fulfilled\") {\n tokenVersion = versionResult.value as string;\n } else {\n // Gracefully default to \"1\" when version() is not implemented\n tokenVersion = \"1\";\n }\n\n // T027: Extract nonce - this MUST succeed for EIP-2612 support\n if (nonceResult.status === \"fulfilled\") {\n nonce = nonceResult.value as bigint;\n } else {\n throw new APIError(\n `Token ${depositToken} does not support EIP-2612 permit. Missing required function: nonces()`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n cause: nonceResult.reason,\n }\n );\n }\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n throw new APIError(\n `Failed to read token metadata: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n cause: error,\n }\n );\n }\n\n // T023: Calculate deadline (default: current time + 3600 seconds)\n const permitDeadline =\n deadline ?? BigInt(Math.floor(Date.now() / 1000) + 3600);\n\n // Convert depositAmount to bigint\n // Get token decimals for conversion\n const assets = await fetchSupportedAssets({ address: depositToken });\n if (assets.length === 0) {\n throw new APIError(`Asset metadata not found for token ${depositToken}`, {\n endpoint: \"prepareDepositPermitSignature\",\n });\n }\n const asset = assets[0];\n const value = parseUnits(depositAmount, asset.decimals);\n\n // T024: Build EIP-712 domain\n const domain: EIP712Domain = {\n name: tokenName,\n version: tokenVersion,\n chainId: normalizedChainId,\n verifyingContract: depositToken,\n };\n\n // T025: Build permit message\n const message = {\n owner: recipientAddress,\n spender: communityCodeDepositorAddress,\n value,\n nonce,\n deadline: permitDeadline,\n };\n\n // T026: Return PermitSignatureData\n return {\n domain,\n message,\n primaryType: \"Permit\",\n types: PERMIT_TYPES,\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare permit signature: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n cause: error,\n }\n );\n }\n}\n\n/**\n * T036-T040: Parse raw hex signature into v, r, s components\n *\n * Handles both v-based and yParity-based signature formats.\n * Converts yParity to v by adding 27 if needed.\n *\n * @param signature - Raw hex signature from wallet\n * @returns Parsed signature components (v, r, s)\n * @throws {APIError} If signature format is invalid\n *\n * @example\n * ```typescript\n * const signature = await signTypedData(permitData);\n * const { v, r, s } = parsePermitSignature(signature);\n * // Use v, r, s in smart contract call\n * ```\n */\nexport function parsePermitSignature(signature: Hex): ParsedPermitSignature {\n try {\n // T037: Use viem's hexToSignature for robust parsing\n const parsed = hexToSignature(signature);\n\n // T038: Calculate v from yParity if present, otherwise use v\n // Modern wallets may return yParity (0 or 1) instead of v (27 or 28)\n let v: number;\n if (parsed.v !== undefined) {\n // v-based signature (legacy format)\n v = Number(parsed.v);\n } else if (parsed.yParity !== undefined) {\n // yParity-based signature (modern format) - convert to v\n v = parsed.yParity + 27;\n } else {\n // Default to 27 if neither present\n v = 27;\n }\n\n // T039: Return ParsedPermitSignature object\n return {\n v,\n r: parsed.r,\n s: parsed.s,\n };\n } catch (error) {\n // T040: Throw APIError with clear message when parsing fails\n throw new APIError(\n `Invalid permit signature format. Expected hex string but received: ${signature}. ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"parsePermitSignature\",\n cause: error,\n }\n );\n }\n}\n\n/**\n * T048: Updated parameters for prepareDepositWithPermitTransactionData()\n * Now accepts raw signature and deadline for complete transaction encoding\n *\n * @interface PrepareDepositWithPermitTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (e.g., \"PRIME\", \"TBILL\")\n * @property {Address} recipientAddress - Ethereum address of the user (recipient of vault shares)\n * @property {Address} depositToken - Token contract address to deposit (matches vault's baseTokenAddress)\n * @property {string} depositAmount - Amount of assets to deposit as a decimal string (e.g., \"100.25\")\n * @property {number | ChainId} chainId - ID of the chain where the deposit will occur\n * @property {Hex} signature - Raw hex signature from wallet signing\n * @property {bigint} deadline - Deadline timestamp (must match permit signature deadline)\n * @property {number} [slippage] - Maximum acceptable slippage in basis points (default: 100 for 1%)\n *\n * @example\n * ```typescript\n * const permitData = await prepareDepositPermitSignature({ ... });\n * const signature = await signTypedData(permitData);\n *\n * const params: PrepareDepositWithPermitTransactionDataParams = {\n * yieldType: \"PRIME\",\n * recipientAddress: \"0x1234567890123456789012345678901234567890\",\n * depositToken: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * depositAmount: \"100.25\",\n * chainId: 1,\n * signature,\n * deadline: permitData.message.deadline,\n * slippage: 100, // 1%\n * };\n * ```\n */\nexport interface PrepareDepositWithPermitTxDataParams {\n yieldType: YieldType;\n recipientAddress: Address;\n depositToken: Address;\n depositAmount: string;\n chainId: number | ChainId;\n signature: Hex;\n deadline: bigint;\n slippage?: number;\n partnerCode?: string;\n}\n\n/**\n * T048-T057: Prepare complete deposit transaction with permit signature\n *\n * Accepts raw signature and deadline, parses signature internally,\n * resolves vault, calculates minimum mint with slippage, and\n * encodes the complete depositWithPermit function call.\n *\n * @param {PrepareDepositWithPermitTransactionDataParams} params - Deposit parameters including signature and deadline\n * @returns {Promise<UnencodedDepositWithPermitData>} Encoded transaction data ready for submission\n * @throws {APIError} If vault not found, invalid signature, or parameter validation fails\n *\n * // Submit transaction\n * await sendTransaction({\n * to: txData.address,\n * data: txData.data,\n * });\n * ```\n */\nexport async function prepareDepositWithPermitTxData(\n params: PrepareDepositWithPermitTxDataParams\n): Promise<UnencodedDepositWithPermitData> {\n const {\n yieldType,\n depositToken,\n depositAmount,\n chainId,\n signature,\n deadline,\n slippage = DEFAULT_SLIPPAGE_BPS,\n recipientAddress,\n partnerCode,\n } = params;\n\n try {\n // T049: Parse signature internally using parsePermitSignature\n const { v, r, s } = parsePermitSignature(signature);\n\n // T050: Validate slippage parameter is within acceptable range (0-10000 bps)\n if (slippage < 0 || slippage > 10000) {\n throw new APIError(\n `Invalid slippage value: ${slippage}. Slippage must be between 0 and 10000 basis points.`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n }\n );\n }\n\n const normalizedChainId = toChainId(chainId);\n\n // T008: Implement vault resolution using findVaultByConfig\n let vault: AmplifyVault | null;\n try {\n vault = await findVaultByConfig({\n assetAddress: depositToken,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositToken} with yield type ${yieldType} on chain ${normalizedChainId}: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n cause: error,\n }\n );\n }\n\n // Check if vault was found\n if (!vault) {\n throw new APIError(\n `No vault found for token address ${depositToken} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n }\n );\n }\n\n // T009: Fetch deposit token metadata using fetchSupportedAssets\n let asset: SupportedAsset | null = null;\n const assets = await fetchSupportedAssets({ address: depositToken });\n if (assets.length > 0) {\n // Find the asset for the correct chain\n asset =\n assets.find((a) => a.chains.includes(normalizedChainId)) ||\n assets[0] ||\n null;\n }\n\n if (!asset) {\n throw new APIError(\n `Asset metadata not found for token ${depositToken} on chain ${normalizedChainId}`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n }\n );\n }\n\n // T035: Implement chainId validation against SupportedAsset.chains\n // T036: Throw APIError with descriptive message when chainId not in supportedChains\n if (!asset.chains || !asset.chains.includes(normalizedChainId)) {\n throw new APIError(\n `Token ${\n asset.symbol || depositToken\n } not supported on chain ${normalizedChainId}`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n }\n );\n }\n\n // Verify transaction data includes correct vault contract addresses\n const communityCodeDepositorAddress =\n vault.vault.communityCodeDepositorAddress;\n const accountantAddress = vault.vault.accountantAddress;\n const depositAssetAddress = asset.address;\n\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `CommunityCodeDepositor contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositWithPermitTxData\" }\n );\n }\n\n // T010: Call getRateInQuoteWithAssetDecimals for exchange rate\n const [depositAssetDecimalsResult, rateInQuoteResult] =\n await getRateInQuoteWithAssetDecimals({\n assetAddress: depositAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n\n // Check decimals call result\n if (depositAssetDecimalsResult.status === \"failure\") {\n throw new APIError(\n `Failed to get asset decimals: ${\n depositAssetDecimalsResult.error?.message || \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n cause: depositAssetDecimalsResult.error,\n }\n );\n }\n\n // Check rate call result\n if (rateInQuoteResult.status === \"failure\") {\n throw new APIError(\n `Failed to get exchange rate: ${\n rateInQuoteResult.error?.message || \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n cause: rateInQuoteResult.error,\n }\n );\n }\n\n // T012: Convert depositAmount from decimal string to bigint\n const depositAmountAsBigInt = parseUnits(depositAmount, asset.decimals);\n\n // Get vault shares asset decimals for minimum mint calculation\n const vaultSharesAssets = await fetchSupportedAssets({\n address: vault.vault.boringVaultAddress,\n });\n\n if (vaultSharesAssets.length === 0) {\n throw new APIError(\n `Vault shares token not found in supported assets: ${vault.vault.boringVaultAddress}`,\n { endpoint: \"prepareDepositWithPermitTxData\" }\n );\n }\n\n // T051: Calculate minimumMint using calculateMinimumMint utility\n const minimumMint = calculateMinimumMint(\n depositAmountAsBigInt,\n rateInQuoteResult.result,\n vaultSharesAssets[0].decimals,\n slippage\n );\n\n return {\n data: {\n abi: CommunityCodeDepositorAbi,\n functionName: \"depositWithPermit\",\n args: [\n depositAssetAddress,\n depositAmountAsBigInt,\n minimumMint,\n recipientAddress,\n stringToHex(partnerCode || \"\"),\n deadline,\n v,\n r,\n s,\n ],\n },\n address: communityCodeDepositorAddress,\n chainId: normalizedChainId,\n };\n } catch (error) {\n // T057: Implement error handling\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors with context\n throw new APIError(\n `Failed to prepare deposit with permit transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n cause: error,\n }\n );\n }\n}\n","import { type Address, parseUnits } from \"viem\";\nimport { BoringVaultAbi } from \"../../abi/boring-vault-abi\";\nimport {\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport {\n ATOMIC_QUEUE_CONTRACT_ADDRESS,\n DEFAULT_APPROVAL_AMOUNT,\n} from \"../../constants\";\nimport { APIError, type YieldType } from \"../../types/amplify-sdk-api\";\n/**\n * Parameters required for preparing an approval transaction (NEW AmplifyVault schema)\n * @interface PrepareApproveWithdrawTokenTxParams\n * @property {YieldType} yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @property {Address} wantAssetAddress - Address of the want token\n * @property {string} [withdrawAmount] - Optional amount to approve (defaults to maximum approval)\n * @property {ChainId} chainId - ID of the chain where the approval will occur\n */\ninterface PrepareApproveWithdrawTokenTxParams {\n yieldType: YieldType;\n wantAssetAddress: Address;\n withdrawAmount?: string;\n chainId: ChainId;\n}\n\n/**\n * Result object containing transaction data for a vault shares approval operation\n * @interface ApproveWithdrawTokenTxData\n * @property {typeof BoringVaultAbi} abi - ABI for the BoringVault contract\n * @property {Address} address - Address of the BoringVault (shares token)\n * @property {'approve'} functionName - Name of the function to call\n * @property {[Address, bigint]} args - Arguments for the approve function:\n * [spender (AtomicQueue address), amount]\n */\ninterface ApproveWithdrawTokenTxData {\n abi: typeof BoringVaultAbi;\n address: Address;\n functionName: \"approve\";\n args: [Address, bigint];\n}\n\n/**\n * Prepares the transaction data needed to approve vault shares for the AtomicQueue contract\n *\n * This function prepares an ERC20 approval transaction that allows the AtomicQueue\n * contract to spend the user's vault shares. It uses the new AmplifyVault schema\n * with asset decimals from the API (no on-chain calls).\n *\n * @example\n * ```typescript\n * const vaults = await fetchVaults({ chainId: 1 });\n * const approveData = await prepareApproveWithdrawToken({\n * yieldType: 'PRIME',\n * wantAssetAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * withdrawAmount: \"10.0\", // Approve 10 vault shares\n * chainId: 1,\n * });\n * ```\n *\n * @param {PrepareApproveWithdrawTokenTxParams} params - Parameters for the approval operation\n * @param {YieldType} params.yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @param {Address} params.wantAssetAddress - Address of the want token\n * @param {string} [params.withdrawAmount] - Optional amount to approve as a decimal string (defaults to maximum approval)\n * @param {number | string} params.chainId - ID of the chain where the approval will occur\n *\n * @returns {Promise<ApproveWithdrawTokenTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not on the correct chain or contracts not configured\n */\nexport async function prepareApproveWithdrawTxData({\n yieldType,\n wantAssetAddress,\n withdrawAmount,\n chainId,\n}: PrepareApproveWithdrawTokenTxParams): Promise<ApproveWithdrawTokenTxData> {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n assetAddress: wantAssetAddress,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n\n // Validation: Ensure vault is on the correct chain\n if (!config || config.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${config?.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareApproveWithdrawToken\" }\n );\n }\n\n // Validation: Ensure boringVault address is configured\n if (!config.vault.boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareApproveWithdrawToken\" }\n );\n }\n\n const boringVaultAddress = config.vault.boringVaultAddress;\n\n // Get vault shares asset decimals for parsing withdraw amount\n const vaultSharesAssets = await getAssetsFromCache({\n address: boringVaultAddress,\n });\n\n if (vaultSharesAssets.length === 0) {\n throw new APIError(\n `Vault shares token not found in supported assets: ${boringVaultAddress}`,\n { endpoint: \"prepareApproveWithdrawToken\" }\n );\n }\n\n // Use decimals from API instead of on-chain call\n const withdrawAmountAsBigInt = withdrawAmount\n ? parseUnits(withdrawAmount, vaultSharesAssets[0].decimals)\n : DEFAULT_APPROVAL_AMOUNT;\n\n return {\n abi: BoringVaultAbi,\n address: boringVaultAddress,\n functionName: \"approve\",\n args: [ATOMIC_QUEUE_CONTRACT_ADDRESS, withdrawAmountAsBigInt],\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare approval transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareApproveWithdrawToken\",\n cause: error,\n }\n );\n }\n}\n\nexport type { ApproveWithdrawTokenTxData, PrepareApproveWithdrawTokenTxParams };\n","import { WithdrawError } from \"../../types/amplify-sdk-api\";\nimport { isValidAddress } from \"../../utils/address\";\nimport { calculateDeadline } from \"../../utils/time\";\nimport type { UserRequest } from \"./withdraw\";\n\n/**\n * Prepares a withdrawal request with the specified parameters\n * @param redeemAmount The amount of tokens to be redeemed\n * @param atomicPrice The current atomic price for the withdrawal\n * @param deadline Optional timestamp for when the request expires\n * @returns UserRequest object with withdrawal parameters\n */\nconst prepareUserRequest = (\n offerAmount: bigint,\n atomicPrice: bigint,\n deadline: number\n): UserRequest => {\n const deadlineTimeStamp = calculateDeadline(deadline);\n return {\n deadline: deadlineTimeStamp,\n atomicPrice: atomicPrice,\n offerAmount: offerAmount,\n inSolve: false,\n };\n};\n\n/**\n * Calculates the final redeem amount accounting for exchange rate and slippage\n * @param amount The initial amount to be redeemed\n * @param exchangeRate The current exchange rate between tokens\n * @param slippage The slippage tolerance as a decimal (e.g., 0.01 for 1%)\n * @returns The final redeem amount after applying exchange rate and slippage\n */\n// ! Deprecated - marked for removal\n// const calculateWantAssetReceiveAmount = (\n// amount: bigint,\n// amountDecimals: number,\n// exchangeRate: bigint,\n// exchangeRateDecimals: number,\n// slippage: number\n// ): bigint => {\n// if (exchangeRate === BigInt(0)) {\n// return BigInt(0);\n// }\n// if (amountDecimals === exchangeRateDecimals) {\n// // all good\n// }\n\n// if (amountDecimals > exchangeRateDecimals) {\n// // normalize to larger decimals\n// }\n// // Convert amount to the target token using exchange rate\n// // Multiply by WAD (10^18) for precision and divide by exchange rate\n// const baseAmount = (amount * WAD.bigint) / exchangeRate;\n\n// // Convert slippage percentage to WAD format for calculation\n// const slippageAsBigInt = BigInt((slippage * WAD.number).toString());\n\n// // Calculate the amount to be subtracted due to slippage\n// const slippageAmount = (baseAmount * slippageAsBigInt) / WAD.bigint;\n\n// // Return the final amount after subtracting slippage\n// return baseAmount - slippageAmount;\n// };\n\n/**\n *\n * @param rateInQuote in want asset decimals\n * @param wantAssetDecimals in want asset decimals\n * @param slippage in bps (e.g., 20 for 0.2%) 20 in 4 decimals = 20 / 10000 = 0.002 = 0.2%\n * @returns atomic price in want asset decimals\n */\nconst calculateAtomicPrice = (\n rateInQuote: bigint, // e.g., 1200000 (1.2 USDC) or 120000000 (1.2 WBTC)\n wantAssetDecimals: number, // 6 for USDC, 8 for WBTC - the \"want\" asset decimals\n slippage: number // In bps (e.g., 20 for 0.2%)\n): bigint => {\n // Step 1: Create precision multiplier for want asset\n const wantPrecision = BigInt(10 ** wantAssetDecimals);\n\n // Step 2: Convert bps to decimal for calculation (bps / 10000)\n const slippageAsBigInt = (BigInt(slippage) * wantPrecision) / BigInt(10000);\n\n // Step 3: Apply formula: atomicPrice = rateInQuote * (1 - slippage)\n return (rateInQuote * (wantPrecision - slippageAsBigInt)) / wantPrecision;\n};\n\nexport { calculateAtomicPrice, prepareUserRequest };\n\n/**\n * Validates withdrawal transaction parameters\n *\n * Performs comprehensive validation of all user-supplied parameters:\n * - yieldType is non-empty string\n * - recipientAddress is valid Ethereum address (not zero address)\n * - wantToken is valid Ethereum address (not zero address)\n * - shareAmount is convertible to positive number\n * - chainId is positive integer\n * - slippage (if provided) is valid basis point value\n *\n * @param yieldType Yield strategy type to validate\n * @param recipientAddress Wallet address to receive withdrawn assets\n * @param wantToken Token address to withdraw\n * @param shareAmount Amount of shares to redeem (decimal string)\n * @param chainId Blockchain network ID\n * @param slippage Optional slippage in basis points\n * @throws WithdrawError if any parameter is invalid\n *\n * @example\n * ```typescript\n * validateWithdrawParams(\n * \"PRIME\",\n * \"0x1234...\",\n * \"0xA0b86991...\",\n * \"1.5\",\n * 1,\n * 100\n * );\n * ```\n */\nexport function validateWithdrawParams(\n yieldType: string,\n recipientAddress: string,\n wantToken: string,\n shareAmount: string,\n chainId: number,\n slippage?: number\n): void {\n // Validate yieldType\n if (!yieldType || typeof yieldType !== \"string\") {\n throw new WithdrawError(\"Invalid yield type\", {\n code: \"INVALID_YIELD_TYPE\",\n });\n }\n\n // Validate recipientAddress\n if (!isValidAddress(recipientAddress)) {\n throw new WithdrawError(\"Invalid recipient address\", {\n code: \"INVALID_RECIPIENT_ADDRESS\",\n });\n }\n\n if (recipientAddress === \"0x0000000000000000000000000000000000000000\") {\n throw new WithdrawError(\"Cannot withdraw to zero address\", {\n code: \"ZERO_ADDRESS\",\n });\n }\n\n // Validate wantToken\n if (!isValidAddress(wantToken)) {\n throw new WithdrawError(\"Invalid token address\", {\n code: \"INVALID_TOKEN_ADDRESS\",\n });\n }\n\n if (wantToken === \"0x0000000000000000000000000000000000000000\") {\n throw new WithdrawError(\"Invalid token address (zero address)\", {\n code: \"INVALID_TOKEN_ADDRESS\",\n });\n }\n\n // Validate shareAmount\n if (!shareAmount || typeof shareAmount !== \"string\") {\n throw new WithdrawError(\"Share amount must be a string\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n const shareAmountNum = Number.parseFloat(shareAmount);\n if (Number.isNaN(shareAmountNum) || shareAmountNum <= 0) {\n throw new WithdrawError(\"Share amount must be greater than zero\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n // Validate chainId\n if (\n typeof chainId !== \"number\" ||\n !Number.isInteger(chainId) ||\n chainId <= 0\n ) {\n throw new WithdrawError(\"Invalid chain ID\", { code: \"INVALID_CHAIN_ID\" });\n }\n\n // Validate slippage if provided\n if (slippage !== undefined) {\n if (typeof slippage !== \"number\" || !Number.isInteger(slippage)) {\n throw new WithdrawError(\"Slippage must be an integer\", {\n code: \"INVALID_SLIPPAGE\",\n });\n }\n\n if (slippage < 0 || slippage > 10000) {\n throw new WithdrawError(\n \"Slippage must be between 0 and 10000 basis points\",\n {\n code: \"INVALID_SLIPPAGE\",\n }\n );\n }\n }\n}\n\n/**\n * Calculates the minimum acceptable asset amount after applying slippage protection\n *\n * Uses the formula: minimumAssets = shareAmount * (10000 - slippage) / 10000\n *\n * This ensures the transaction will revert if the actual output falls below\n * the minimum acceptable amount due to price movements.\n *\n * @param shareAmount Amount of shares to redeem (as bigint in smallest units)\n * @param slippage Acceptable slippage in basis points (100 = 1%, defaults to 100)\n * @returns The minimum acceptable asset amount\n *\n * @example\n * ```typescript\n * const shareAmount = 1000n;\n * const slippage = 100; // 1%\n * const minimumAssets = calculateMinimumAssets(shareAmount, slippage);\n * // Result: 990n (allows 1% slippage)\n * ```\n */\nexport function calculateMinimumAssets(\n shareAmount: bigint,\n slippage: number = 100\n): bigint {\n const basisPoints = BigInt(10000);\n const slippageAmount = BigInt(slippage);\n return (shareAmount * (basisPoints - slippageAmount)) / basisPoints;\n}\n\n/**\n * Converts share amount from decimal string to BigInt\n *\n * Handles conversion of user-supplied decimal amount to blockchain-compatible BigInt.\n * Assumes 18 decimal places (standard for most ERC20 tokens).\n *\n * @param amount Decimal string amount (e.g., \"1.5\", \"100\", \"0.001\")\n * @param decimals Number of decimal places for the token (default: 18)\n * @returns BigInt representation in smallest units\n * @throws WithdrawError if amount cannot be parsed or results in zero\n *\n * @example\n * ```typescript\n * const shareAmountBigInt = parseShareAmount(\"1.5\");\n * // Result: 1500000000000000000n\n *\n * const usdcAmount = parseShareAmount(\"100\", 6);\n * // Result: 100000000n\n * ```\n */\nexport function parseShareAmount(\n amount: string,\n decimals: number = 18\n): bigint {\n if (!amount || typeof amount !== \"string\") {\n throw new WithdrawError(\"Share amount must be a valid string\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n const numAmount = Number.parseFloat(amount);\n if (Number.isNaN(numAmount) || numAmount < 0) {\n throw new WithdrawError(\"Share amount must be a valid positive number\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n const bigIntAmount = BigInt(Math.floor(numAmount * 10 ** decimals));\n\n if (bigIntAmount === BigInt(0) && numAmount > 0) {\n throw new WithdrawError(\n \"Share amount is too small for the specified decimals\",\n {\n code: \"INVALID_SHARE_AMOUNT\",\n }\n );\n }\n\n if (bigIntAmount < BigInt(0)) {\n throw new WithdrawError(\"Share amount must be greater than zero\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n return bigIntAmount;\n}\n\n/**\n * Finds a vault by configuration criteria from a vault array (test helper)\n *\n * @param vaults - Array of AmplifyVault objects to search\n * @param yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @param wantToken - Token address\n * @param chainId - Blockchain network ID\n * @returns Matching vault or undefined\n */\nexport function findVaultByConfig(\n vaults: Array<{\n yieldType: string;\n chainId: number;\n vault: {\n baseTokenAddress: string;\n };\n }>,\n yieldType: string,\n wantToken: string,\n chainId: number\n) {\n const normalizedToken = wantToken.toLowerCase();\n return vaults.find((vault) => {\n const vaultToken = (vault.vault.baseTokenAddress || \"\").toLowerCase();\n return (\n vault.yieldType === yieldType &&\n vault.chainId === chainId &&\n vaultToken === normalizedToken\n );\n });\n}\n","import { type Address, parseUnits } from \"viem\";\nimport { TellerAbi } from \"../../abi/teller-abi\";\nimport { getRateInQuoteAndSharesAndWantAssetDecimals } from \"../../api/accountant\";\nimport {\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport { DEFAULT_SLIPPAGE_BPS, type YieldType } from \"../../constants/config\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { calculateAtomicPrice } from \"./utils\";\n\ninterface BulkWithdrawTxData {\n abi: typeof TellerAbi;\n address: Address;\n functionName: \"bulkWithdraw\";\n args: [\n withdrawAsset: Address,\n shareAmount: bigint,\n minimumAssets: bigint,\n to: Address\n ];\n chainId: number;\n}\n\ninterface PrepareBulkWithdrawTxDataParams {\n yieldType: YieldType;\n shareAmount: string;\n wantAssetAddress: Address;\n chainId: ChainId;\n slippage?: number;\n recipientAddress: Address;\n}\n\n/**\n * Prepares the transaction data needed to withdraw assets from a vault\n *\n * This function calculates the appropriate exchange rate with slippage protection\n * and prepares a user request for the AtomicQueue contract. It uses the new\n * AmplifyVault schema with asset decimals from the API (no on-chain calls).\n *\n * @example\n * ```typescript\n * const vaults = await fetchVaults({ chainId: 1 });\n * const wantAssets = await fetchSupportedAssets({ symbol: 'WETH' });\n * const withdrawData = await prepareBulkWithdrawTransactionData({\n * vault: vaults[0],\n * wantAsset: wantAssets[0],\n * chainId: 1,\n * recipientAddress: '0x1234...',\n * offerAmount: \"1.0\", // 1 vault share\n * deadline: Math.floor(Date.now() / 1000) + 3600, // 1 hour from now\n * slippage: 100, // 1% slippage (100 bps)\n * });\n * ```\n *\n * @param {PrepareBulkWithdrawTxDataParams} params - Parameters for the withdraw operation\n * @param {AmplifyVault} params.vault - Vault configuration from fetchVaults()\n * @param {SupportedAsset} params.wantAsset - Asset metadata from fetchSupportedAssets()\n * @param {ChainId} params.chainId - ID of the chain where the withdrawal will occur\n * @param {Address} params.recipientAddress - Ethereum address of the user making the withdrawal\n * @param {string} params.offerAmount - Amount of vault shares to withdraw as a decimal string\n * @param {number} [params.deadline] - Unix timestamp when the request expires\n * @param {number} [params.slippage] - Maximum acceptable slippage in basis points\n *\n * @returns {Promise<BulkWithdrawTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not on the correct chain, asset not supported, or contracts not configured\n */\nexport async function prepareBulkWithdrawTxData(\n params: PrepareBulkWithdrawTxDataParams\n): Promise<BulkWithdrawTxData> {\n const {\n yieldType,\n wantAssetAddress,\n shareAmount,\n chainId,\n slippage = DEFAULT_SLIPPAGE_BPS,\n recipientAddress,\n } = params;\n try {\n const normalizedChainId = toChainId(chainId);\n\n const vault = await findVaultByConfig({\n assetAddress: wantAssetAddress,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n\n // Validation: Ensure vault is on the correct chain\n if (vault && vault.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${vault.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareBulkWithdrawTransactionData\" }\n );\n }\n\n // Validation: Ensure required contract addresses are present\n if (!vault || !vault.vault.boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${vault?.vault.boringVaultAddress}`,\n { endpoint: \"prepareBulkWithdrawTransactionData\" }\n );\n }\n const boringVaultAddress = vault.vault.boringVaultAddress;\n const accountantAddress = vault.vault.accountantAddress;\n\n // Get vault shares asset decimals for parsing offer amount\n const wantAsset = await getAssetsFromCache({\n address: wantAssetAddress,\n });\n\n if (wantAsset.length === 0) {\n throw new APIError(\n `Vault shares token not found in supported assets: ${boringVaultAddress}`,\n { endpoint: \"prepareBulkWithdrawTransactionData\" }\n );\n }\n\n // Get exchange rate from accountant\n const [\n wantAssetDecimalsResult,\n sharesAssetDecimalsResult,\n rateInQuoteResult,\n ] = await getRateInQuoteAndSharesAndWantAssetDecimals({\n sharesAssetAddress: boringVaultAddress,\n wantAssetAddress: wantAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n\n // Validate rate results\n if (\n rateInQuoteResult.status === \"failure\" ||\n wantAssetDecimalsResult.status === \"failure\" ||\n sharesAssetDecimalsResult.status === \"failure\"\n ) {\n throw new APIError(\n `Failed to get exchange rate: ${\n rateInQuoteResult?.error?.message ||\n wantAssetDecimalsResult?.error?.message ||\n sharesAssetDecimalsResult?.error?.message\n }`,\n {\n endpoint: \"prepareBulkWithdrawTransactionData\",\n cause:\n rateInQuoteResult?.error ||\n wantAssetDecimalsResult?.error ||\n sharesAssetDecimalsResult?.error,\n }\n );\n }\n\n // Parse offer amount using vault shares decimals from API\n const offerAmountAsBigInt = parseUnits(\n shareAmount,\n sharesAssetDecimalsResult.result\n );\n\n // Calculate atomic price using want asset decimals from API\n const atomicPrice = calculateAtomicPrice(\n rateInQuoteResult.result, // rateInQuote bigint\n wantAssetDecimalsResult.result, // Want asset decimals from API\n slippage\n );\n\n const minimumAssets =\n (atomicPrice * offerAmountAsBigInt) /\n BigInt(10 ** sharesAssetDecimalsResult.result);\n\n return {\n abi: TellerAbi,\n address: vault.vault.tellerAddress as Address,\n functionName: \"bulkWithdraw\",\n args: [\n wantAssetAddress,\n offerAmountAsBigInt,\n minimumAssets,\n recipientAddress,\n ],\n chainId: normalizedChainId,\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare withdrawal transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareBulkWithdrawTransactionData\",\n cause: error,\n }\n );\n }\n}\n\nexport type { BulkWithdrawTxData, PrepareBulkWithdrawTxDataParams };\n","export const AtomicQueueAbi = [\n {\n type: \"function\",\n name: \"getUserAtomicRequest\",\n inputs: [\n { name: \"user\", type: \"address\", internalType: \"address\" },\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"want\", type: \"address\", internalType: \"contract ERC20\" },\n ],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n internalType: \"struct AtomicQueue.AtomicRequest\",\n components: [\n { name: \"deadline\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"atomicPrice\", type: \"uint88\", internalType: \"uint88\" },\n { name: \"offerAmount\", type: \"uint96\", internalType: \"uint96\" },\n { name: \"inSolve\", type: \"bool\", internalType: \"bool\" },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAtomicRequestValid\",\n inputs: [\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"user\", type: \"address\", internalType: \"address\" },\n {\n name: \"userRequest\",\n type: \"tuple\",\n internalType: \"struct AtomicQueue.AtomicRequest\",\n components: [\n { name: \"deadline\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"atomicPrice\", type: \"uint88\", internalType: \"uint88\" },\n { name: \"offerAmount\", type: \"uint96\", internalType: \"uint96\" },\n { name: \"inSolve\", type: \"bool\", internalType: \"bool\" },\n ],\n },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"solve\",\n inputs: [\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"want\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"users\", type: \"address[]\", internalType: \"address[]\" },\n { name: \"runData\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"solver\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"updateAtomicRequest\",\n inputs: [\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"want\", type: \"address\", internalType: \"contract ERC20\" },\n {\n name: \"userRequest\",\n type: \"tuple\",\n internalType: \"struct AtomicQueue.AtomicRequest\",\n components: [\n { name: \"deadline\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"atomicPrice\", type: \"uint88\", internalType: \"uint88\" },\n { name: \"offerAmount\", type: \"uint96\", internalType: \"uint96\" },\n { name: \"inSolve\", type: \"bool\", internalType: \"bool\" },\n ],\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"userAtomicRequest\",\n inputs: [\n { name: \"\", type: \"address\", internalType: \"address\" },\n { name: \"\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"\", type: \"address\", internalType: \"contract ERC20\" },\n ],\n outputs: [\n { name: \"deadline\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"atomicPrice\", type: \"uint88\", internalType: \"uint88\" },\n { name: \"offerAmount\", type: \"uint96\", internalType: \"uint96\" },\n { name: \"inSolve\", type: \"bool\", internalType: \"bool\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"viewSolveMetaData\",\n inputs: [\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"want\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"users\", type: \"address[]\", internalType: \"address[]\" },\n ],\n outputs: [\n {\n name: \"metaData\",\n type: \"tuple[]\",\n internalType: \"struct AtomicQueue.SolveMetaData[]\",\n components: [\n { name: \"user\", type: \"address\", internalType: \"address\" },\n { name: \"flags\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"assetsToOffer\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"assetsForWant\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"totalAssetsForWant\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"totalAssetsToOffer\", type: \"uint256\", internalType: \"uint256\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"event\",\n name: \"AtomicRequestFulfilled\",\n inputs: [\n {\n name: \"user\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"offerToken\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"wantToken\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"offerAmountSpent\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"wantAmountReceived\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"timestamp\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n ],\n anonymous: false,\n },\n {\n type: \"event\",\n name: \"AtomicRequestUpdated\",\n inputs: [\n {\n name: \"user\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"offerToken\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"wantToken\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"amount\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"deadline\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"minPrice\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"timestamp\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n ],\n anonymous: false,\n },\n {\n type: \"error\",\n name: \"AtomicQueue__RequestDeadlineExceeded\",\n inputs: [{ name: \"user\", type: \"address\", internalType: \"address\" }],\n },\n {\n type: \"error\",\n name: \"AtomicQueue__UserNotInSolve\",\n inputs: [{ name: \"user\", type: \"address\", internalType: \"address\" }],\n },\n {\n type: \"error\",\n name: \"AtomicQueue__UserRepeated\",\n inputs: [{ name: \"user\", type: \"address\", internalType: \"address\" }],\n },\n {\n type: \"error\",\n name: \"AtomicQueue__ZeroOfferAmount\",\n inputs: [{ name: \"user\", type: \"address\", internalType: \"address\" }],\n },\n] as const;\n","/**\n * @file Withdraw functionality for Paxos Labs vaults\n * @module vaults/withdraw\n */\n\nimport { type Address, parseUnits } from \"viem\";\nimport { AtomicQueueAbi } from \"../../abi/atomic-queue-abi\";\nimport { getRateInQuoteAndSharesAndWantAssetDecimals } from \"../../api/accountant\";\nimport { findVaultByConfig } from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport {\n ATOMIC_QUEUE_CONTRACT_ADDRESS,\n DEFAULT_DEADLINE,\n} from \"../../constants\";\nimport { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { calculateAtomicPrice, prepareUserRequest } from \"./utils\";\n\n/**\n * Arguments for an atomic request to the AtomicQueue contract\n * @typedef {Object} AtomicRequestArgs\n * @property {Address} offer - Address of the token being offered (shares token address)\n * @property {Address} want - Address of the token being requested (want token address)\n * @property {UserRequest} userRequest - User request details\n */\nexport type AtomicRequestArgs = {\n offer: Address; // sharesTokenAddress\n want: Address; // wantTokenAddress\n userRequest: UserRequest; // userRequest\n};\n\n/**\n * Options for an atomic request\n * @typedef {Object} AtomicRequestOptions\n * @property {Address} atomicQueueContractAddress - Address of the AtomicQueue contract\n * @property {number} chainId - ID of the destination chain\n */\nexport type AtomicRequestOptions = {\n atomicQueueContractAddress: Address; // atomicQueueContractAddress\n chainId: ChainId; // destinationChainId\n};\n\n/**\n * User request details for an atomic swap\n * @typedef {Object} UserRequest\n * @property {number} deadline - Unix timestamp when the request expires\n * @property {bigint} atomicPrice - Rate in quote with fee applied\n * @property {bigint} offerAmount - Amount of shares token to redeem\n * @property {boolean} inSolve - Whether the request is in solve mode (always false for new requests)\n */\nexport type UserRequest = {\n deadline: bigint; // deadline\n atomicPrice: bigint; // rateInQuoteWithFee\n offerAmount: bigint; // redeemAmount\n inSolve: boolean; // false\n};\n\n/**\n * Parameters for preparing a withdrawal transaction from a vault (NEW AmplifyVault schema)\n * @interface PrepareWithdrawTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @property {Address} wantAssetAddress - Address of the want token\n * @property {ChainId} chainId - ID of the chain where the withdrawal will occur\n * @property {string} offerAmount - Amount of vault shares to withdraw as a decimal string\n * @property {number} [deadline] - Unix timestamp when the request expires (optional)\n * @property {number} [slippage] - Maximum acceptable slippage in basis points (optional, default: 100 for 1%)\n *\n * **Slippage Protection**:\n * The slippage parameter protects users from unfavorable price movements during the withdrawal.\n * It defines the maximum acceptable loss as a percentage of the initial share amount.\n *\n * - Default: 100 basis points (1% slippage tolerance)\n * - Range: 0-10000 basis points (0-100%)\n * - Formula: minimumAssets = shareAmount * (10000 - slippage) / 10000\n *\n * @example\n * ```typescript\n * // 1% slippage (default) - allows price to move 1% unfavorably\n * { slippage: 100 }\n *\n * // 0.5% slippage - conservative, tighter protection\n * { slippage: 50 }\n *\n * // 5% slippage - aggressive, more lenient\n * { slippage: 500 }\n *\n * // No slippage tolerance - transaction reverts if price changes at all\n * { slippage: 0 }\n * ```\n */\ninterface PrepareWithdrawTxDataParams {\n yieldType: YieldType;\n wantAssetAddress: Address;\n chainId: ChainId;\n offerAmount: string;\n deadline?: number;\n slippage?: number;\n}\n\n/**\n * Result object containing transaction data for a withdrawal operation\n * @interface WithdrawTxData\n * @property {typeof AtomicQueueAbi} abi - ABI for the AtomicQueue contract\n * @property {Address} address - Address of the AtomicQueue contract\n * @property {'updateAtomicRequest'} functionName - Name of the function to call\n * @property {[Address, Address, UserRequest]} args - Arguments for the updateAtomicRequest function:\n * [offer (vault shares address), want (want asset address), userRequest]\n * @property {number} chainId - ID of the chain where the transaction should be executed\n */\ninterface WithdrawTxData {\n abi: typeof AtomicQueueAbi;\n address: Address;\n functionName: \"updateAtomicRequest\";\n args: [offer: Address, want: Address, userRequest: UserRequest];\n chainId: number;\n}\n\n/**\n * Prepares the transaction data needed to withdraw assets from a vault\n *\n * This function calculates the appropriate exchange rate with slippage protection\n * and prepares a user request for the AtomicQueue contract. It uses the new\n * AmplifyVault schema with asset decimals from the API (no on-chain calls).\n *\n * @example\n * ```typescript\n * const withdrawData = await prepareWithdrawTransactionData({\n * yieldType: 'PRIME',\n * wantAssetAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * chainId: 1,\n * offerAmount: \"1.0\", // 1 vault share\n * deadline: Math.floor(Date.now() / 1000) + 3600, // Optional: Defaults to 3 days from now\n * slippage: 100, // Optional: Defaults to 0.5% slippage (50 bps)\n * });\n * ```\n *\n * @param {PrepareWithdrawTxDataParams} params - Parameters for the withdraw operation\n * @param {YieldType} params.yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @param {Address} params.wantAssetAddress - Address of the want token\n * @param {ChainId} params.chainId - ID of the chain where the withdrawal will occur\n * @param {Address} params.recipientAddress - Ethereum address of the user making the withdrawal\n * @param {string} params.offerAmount - Amount of vault shares to withdraw as a decimal string\n * @param {number} [params.deadline] - Unix timestamp when the request expires\n * @param {number} [params.slippage] - Maximum acceptable slippage in basis points\n *\n * @returns {Promise<WithdrawTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not on the correct chain, asset not supported, or contracts not configured\n */\nconst prepareWithdrawTxData = async ({\n yieldType,\n wantAssetAddress,\n chainId,\n offerAmount,\n deadline = DEFAULT_DEADLINE,\n slippage = DEFAULT_SLIPPAGE_BPS,\n}: PrepareWithdrawTxDataParams): Promise<WithdrawTxData> => {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n assetAddress: wantAssetAddress,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n\n // Validation: Ensure vault is on the correct chain\n if (config && config.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${config.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareWithdrawTransactionData\" }\n );\n }\n\n // Validation: Ensure required contract addresses are present\n if (!config || !config.vault.boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config?.id}`,\n { endpoint: \"prepareWithdrawTransactionData\" }\n );\n }\n\n if (!config.vault.accountantAddress) {\n throw new APIError(\n `Accountant contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareWithdrawTransactionData\" }\n );\n }\n\n const boringVaultAddress = config.vault.boringVaultAddress;\n const accountantAddress = config.vault.accountantAddress;\n\n // Get exchange rate from accountant\n const [\n wantAssetDecimalsResult,\n sharesAssetDecimalsResult,\n rateInQuoteResult,\n ] = await getRateInQuoteAndSharesAndWantAssetDecimals({\n sharesAssetAddress: boringVaultAddress,\n wantAssetAddress: wantAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n\n // Validate rate results\n if (\n rateInQuoteResult?.status === \"failure\" ||\n wantAssetDecimalsResult?.status === \"failure\" ||\n sharesAssetDecimalsResult?.status === \"failure\"\n ) {\n throw new APIError(\n `Failed to get exchange rate: ${\n rateInQuoteResult?.error?.message ||\n wantAssetDecimalsResult?.error?.message ||\n sharesAssetDecimalsResult?.error?.message\n }`,\n {\n endpoint: \"prepareWithdrawTransactionData\",\n cause:\n rateInQuoteResult?.error ||\n wantAssetDecimalsResult?.error ||\n sharesAssetDecimalsResult?.error,\n }\n );\n }\n\n // Calculate atomic price using want asset decimals from API\n const atomicPrice = calculateAtomicPrice(\n rateInQuoteResult.result, // rateInQuote bigint\n wantAssetDecimalsResult.result, // Want asset decimals from API\n slippage\n );\n\n // Parse offer amount using vault shares decimals from API\n const formattedOfferAmount = parseUnits(\n offerAmount,\n sharesAssetDecimalsResult.result\n );\n\n const userRequest = prepareUserRequest(\n formattedOfferAmount,\n atomicPrice,\n deadline\n );\n\n return {\n abi: AtomicQueueAbi,\n address: ATOMIC_QUEUE_CONTRACT_ADDRESS,\n functionName: \"updateAtomicRequest\",\n args: [boringVaultAddress, wantAssetAddress, userRequest],\n chainId: normalizedChainId,\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare withdrawal transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareWithdrawTransactionData\",\n cause: error,\n }\n );\n }\n};\n\nexport { prepareWithdrawTxData };\n\nexport type { PrepareWithdrawTxDataParams, WithdrawTxData };\n"]}
1
+ {"version":3,"sources":["../src/vaults/deposit/approve-deposit.ts","../src/abi/community-code-depositor-abi.ts","../src/vaults/deposit/utils.ts","../src/vaults/deposit/deposit.ts","../src/vaults/deposit/deposit-with-permit.ts","../src/vaults/deposit/index.ts","../src/vaults/withdraw/approve-withdraw.ts","../src/vaults/withdraw/utils.ts","../src/vaults/withdraw/bulk-withdraw.ts","../src/abi/atomic-queue-abi.ts","../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AAA,EAAO;AAEd,IAAA,IAAI,iBAAiB,QAAA,EAAU;AAC7B,MAAA,MAAM,KAAA;AAAA,IACR;AAGA,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,6CACE,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CACvD,CAAA,CAAA;AAAA,MACA;AAAA,QACE,QAAA,EAAU,gCAAA;AAAA,QACV,KAAA,EAAO;AAAA;AACT,KACF;AAAA,EACF;AACF","file":"index.mjs","sourcesContent":["/**\n * @file Approve Asset for deposit functionality for Paxos Labs vaults\n * @module vaults/deposit\n */\n\nimport { type Address, erc20Abi, parseUnits } from \"viem\";\nimport {\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport { DEFAULT_APPROVAL_AMOUNT } from \"../../constants\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\n\n/**\n * Parameters required for preparing an approval transaction\n * @interface PrepareApproveDepositTokenTxParams\n * @property {Address} depositToken - Token contract address to approve\n * @property {Address} boringVaultAddress - Address of the BoringVault to approve spending\n * @property {string} [approvalAmount] - Optional amount to approve (defaults to maximum approval)\n * @property {number | string} chainId - ID of the chain where the approval will occur\n */\ninterface PrepareApproveDepositTokenTxParams {\n yieldType: YieldType;\n depositToken: Address;\n approvalAmount?: string;\n chainId: ChainId;\n}\n\n/**\n * Result object containing transaction data for an ERC20 approval operation\n * @interface ApproveDepositTokenTxData\n * @property {typeof erc20Abi} abi - ABI for the ERC20 token contract\n * @property {Address} address - Address of the ERC20 token being approved\n * @property {'approve'} functionName - Name of the function to call\n * @property {[Address, bigint]} args - Arguments for the approve function:\n * [spender (boringVault address), amount]\n */\ninterface ApproveDepositTokenTxData {\n abi: typeof erc20Abi;\n address: Address;\n functionName: \"approve\";\n args: [Address, bigint];\n}\n\n/**\n * Prepares the transaction data needed to approve a deposit token for the vault\n *\n * This function prepares an ERC20 approval transaction that allows the vault's\n * BoringVault contract to spend the user's deposit tokens.\n *\n * @example\n * ```typescript\n * const approveData = await prepareApproveDepositToken({\n * depositToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * boringVaultAddress: '0x1234...',\n * approvalAmount: \"1000.0\", // Approve 1000 USDC\n * chainId: 1,\n * });\n * ```\n *\n * @param {PrepareApproveDepositTokenTxParams} params - Parameters for the approval operation\n * @returns {Promise<ApproveDepositTokenTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If parameters are invalid\n */\nexport async function prepareApproveDepositTokenTxData({\n yieldType,\n depositToken,\n approvalAmount,\n chainId,\n}: PrepareApproveDepositTokenTxParams): Promise<ApproveDepositTokenTxData> {\n const normalizedChainId = toChainId(chainId);\n\n try {\n const config = await findVaultByConfig({\n assetAddress: depositToken,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n if (!config) {\n throw new APIError(\n `No vault found for token address ${depositToken} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n const boringVaultAddress = config.vault.boringVaultAddress;\n if (!boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n\n // Get asset decimals for amount calculation\n const assets = await getAssetsFromCache({ address: depositToken });\n if (assets.length === 0) {\n throw new APIError(\n `Asset metadata not found for token ${depositToken} on chain ${normalizedChainId}`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n\n const decimals = assets[0].decimals;\n const amount = approvalAmount\n ? parseUnits(approvalAmount, decimals)\n : DEFAULT_APPROVAL_AMOUNT;\n return {\n abi: erc20Abi,\n address: depositToken,\n functionName: \"approve\",\n args: [boringVaultAddress, amount],\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare approval transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareApproveDepositToken\",\n cause: error,\n }\n );\n }\n}\n\nexport type { ApproveDepositTokenTxData, PrepareApproveDepositTokenTxParams };\n","export const CommunityCodeDepositorAbi = [\n {\n inputs: [\n {\n internalType: \"contract TellerWithMultiAssetSupport\",\n name: \"_teller\",\n type: \"address\",\n },\n {\n internalType: \"contract INativeWrapper\",\n name: \"_nativeWrapper\",\n type: \"address\",\n },\n {\n internalType: \"contract Authority\",\n name: \"_rolesAuthority\",\n type: \"address\",\n },\n { internalType: \"bool\", name: \"_isNativeDepositSupported\", type: \"bool\" },\n { internalType: \"address\", name: \"_owner\", type: \"address\" },\n ],\n stateMutability: \"nonpayable\",\n type: \"constructor\",\n },\n { inputs: [], name: \"IncorrectNativeDepositAmount\", type: \"error\" },\n { inputs: [], name: \"NativeDepositNotSupported\", type: \"error\" },\n {\n inputs: [],\n name: \"NativeWrapperAccountantDecimalsMismatch\",\n type: \"error\",\n },\n { inputs: [], name: \"PermitFailedAndAllowanceTooLow\", type: \"error\" },\n { inputs: [], name: \"ZeroAddress\", type: \"error\" },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: \"address\", name: \"user\", type: \"address\" },\n {\n indexed: true,\n internalType: \"contract Authority\",\n name: \"newAuthority\",\n type: \"address\",\n },\n ],\n name: \"AuthorityUpdated\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"address\",\n name: \"depositor\",\n type: \"address\",\n },\n {\n indexed: true,\n internalType: \"contract ERC20\",\n name: \"depositAsset\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"uint256\",\n name: \"depositAmount\",\n type: \"uint256\",\n },\n {\n indexed: false,\n internalType: \"uint256\",\n name: \"minimumMint\",\n type: \"uint256\",\n },\n { indexed: false, internalType: \"address\", name: \"to\", type: \"address\" },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"depositHash\",\n type: \"bytes32\",\n },\n {\n indexed: true,\n internalType: \"bytes\",\n name: \"distributorCode\",\n type: \"bytes\",\n },\n ],\n name: \"DepositWithDistributorCode\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: \"address\", name: \"user\", type: \"address\" },\n {\n indexed: true,\n internalType: \"address\",\n name: \"newOwner\",\n type: \"address\",\n },\n ],\n name: \"OwnershipTransferred\",\n type: \"event\",\n },\n {\n inputs: [],\n name: \"authority\",\n outputs: [\n { internalType: \"contract Authority\", name: \"\", type: \"address\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"boringVault\",\n outputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"contract ERC20\", name: \"depositAsset\", type: \"address\" },\n { internalType: \"uint256\", name: \"depositAmount\", type: \"uint256\" },\n { internalType: \"uint256\", name: \"minimumMint\", type: \"uint256\" },\n { internalType: \"address\", name: \"to\", type: \"address\" },\n { internalType: \"bytes\", name: \"distributorCode\", type: \"bytes\" },\n ],\n name: \"deposit\",\n outputs: [{ internalType: \"uint256\", name: \"shares\", type: \"uint256\" }],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"uint256\", name: \"depositAmount\", type: \"uint256\" },\n { internalType: \"uint256\", name: \"minimumMint\", type: \"uint256\" },\n { internalType: \"address\", name: \"to\", type: \"address\" },\n { internalType: \"bytes\", name: \"distributorCode\", type: \"bytes\" },\n ],\n name: \"depositNative\",\n outputs: [{ internalType: \"uint256\", name: \"shares\", type: \"uint256\" }],\n stateMutability: \"payable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"depositNonce\",\n outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"contract ERC20\", name: \"depositAsset\", type: \"address\" },\n { internalType: \"uint256\", name: \"depositAmount\", type: \"uint256\" },\n { internalType: \"uint256\", name: \"minimumMint\", type: \"uint256\" },\n { internalType: \"address\", name: \"to\", type: \"address\" },\n { internalType: \"bytes\", name: \"distributorCode\", type: \"bytes\" },\n { internalType: \"uint256\", name: \"deadline\", type: \"uint256\" },\n { internalType: \"uint8\", name: \"v\", type: \"uint8\" },\n { internalType: \"bytes32\", name: \"r\", type: \"bytes32\" },\n { internalType: \"bytes32\", name: \"s\", type: \"bytes32\" },\n ],\n name: \"depositWithPermit\",\n outputs: [{ internalType: \"uint256\", name: \"shares\", type: \"uint256\" }],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"isNativeDepositSupported\",\n outputs: [{ internalType: \"bool\", name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"nativeWrapper\",\n outputs: [\n { internalType: \"contract INativeWrapper\", name: \"\", type: \"address\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"owner\",\n outputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract Authority\",\n name: \"newAuthority\",\n type: \"address\",\n },\n ],\n name: \"setAuthority\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"teller\",\n outputs: [\n {\n internalType: \"contract TellerWithMultiAssetSupport\",\n name: \"\",\n type: \"address\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"address\", name: \"newOwner\", type: \"address\" }],\n name: \"transferOwnership\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n] as const;\n","import { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport { WAD } from \"../../utils/bigint\";\n\n/**\n * Calculates the minimum amount of tokens to mint based on deposit amount, rate, and slippage\n * @param depositAmount The amount being deposited (in base units)\n * @param rate The current exchange rate between deposit and mint tokens\n * @param vaultTokenDecimals The number of precision decimals of the vault token\n * @param slippage The maximum acceptable slippage as a decimal (e.g., 0.01 for 1%)\n * @returns The minimum amount of tokens that should be minted accounting for slippage in vault token precision decimals\n */\nconst calculateMinimumMint = (\n depositAmount: bigint, // In deposit token decimals\n rate: bigint, // In deposit token decimals\n vaultTokenDecimals: number, // The number of precision decimals of the vault token\n slippage?: number // In bps (e.g., 50 for 0.5%) = 50 / 10000 = 0.005 = 0.5%\n): bigint => {\n const slippageValue = slippage ?? DEFAULT_SLIPPAGE_BPS;\n // Convert bps to WAD format (multiply by WAD/10000)\n const slippageAsBigInt = (BigInt(slippageValue) * WAD.bigint) / BigInt(10000);\n\n // Calculate ideal mint amount without slippage\n const minimumMint = (depositAmount * WAD.bigint) / rate;\n\n // Calculate the amount to subtract for slippage tolerance\n const slippageAmount = (minimumMint * slippageAsBigInt) / WAD.bigint;\n\n // Return mint amount minus slippage buffer\n if (vaultTokenDecimals > 18) {\n return (\n (minimumMint - slippageAmount) *\n BigInt(10) ** (BigInt(vaultTokenDecimals) - BigInt(18))\n );\n }\n return (\n (minimumMint - slippageAmount) /\n BigInt(10) ** (BigInt(18) - BigInt(vaultTokenDecimals))\n );\n};\n\nexport { calculateMinimumMint };\n","/**\n * @file Deposit functionality for Nucleus vaults\n * @module vaults/deposit\n */\n\nimport { type Address, type Hex, parseUnits, stringToHex } from \"viem\";\nimport { CommunityCodeDepositorAbi } from \"../../abi/community-code-depositor-abi\";\nimport { getRateInQuoteWithAssetDecimals } from \"../../api/accountant\";\nimport {\n fetchSupportedAssets,\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport type {\n AmplifyVault,\n SupportedAsset,\n YieldType,\n} from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { calculateMinimumMint } from \"./utils\";\n\n/**\n * Result object containing transaction data for a deposit operation\n * @interface DepositTxData\n * @property {typeof CommunityCodeDepositorAbi} abi - ABI for the CommunityCodeDepositor contract\n * @property {Address} address - Address of the CommunityCodeDepositor contract\n * @property {'deposit'} functionName - Name of the function to call\n * @property {readonly [depositAsset: Address, depositAmount: bigint, minimumMint: bigint, to: Address, distributorCode: Hex]} args - Arguments for the deposit function:\n * [depositAsset, depositAmount, minimumMint, recipientAddress, distributorCode]\n * @property {number} chainId - ID of the chain where the transaction should be executed\n */\ninterface DepositTxData {\n abi: typeof CommunityCodeDepositorAbi;\n address: Address;\n functionName: \"deposit\";\n args: readonly [\n depositAsset: Address,\n depositAmount: bigint,\n minimumMint: bigint,\n to: Address,\n distributorCode: Hex\n ];\n chainId: number;\n}\n/**\n * Parameters for prepareDepositTransactionData()\n * Accepts yieldType, recipientAddress, depositToken, and chainId for automatic vault resolution\n * @interface PrepareDepositTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (e.g., \"PRIME\", \"TBILL\", \"LENDING\")\n * @property {Address} recipientAddress - Ethereum address of the user. Must be the same as the address used to sign the deposit transaction.\n * @property {Address} depositToken - Token contract address to deposit. Must be supported by the vault.\n * @property {string} depositAmount - Amount of assets to deposit as a decimal string (e.g., \"1.5\")\n * @property {number | string} chainId - ID of the chain where the deposit will occur\n * @property {number} [slippage] - Optional (default is 50 (0.5%)): Maximum acceptable slippage in basis points (e.g., 100 for 1%).\n * @property {string} [partnerCode] - Optional (default is empty string): Partner code to credit deposit fees to the partner used for the deposit\n */\ninterface PrepareDepositTxDataParams {\n yieldType: YieldType;\n recipientAddress: Address;\n depositToken: Address;\n depositAmount: string;\n chainId: ChainId;\n slippage?: number;\n partnerCode?: string;\n}\n\n/**\n * Prepares the transaction data needed to deposit assets into a vault\n *\n * This function calculates the minimum amount of vault tokens to be minted based on\n * the current exchange rate and the specified slippage tolerance. It automatically\n * resolves the vault from yieldType, depositToken, and chainId parameters.\n *\n * ```typescript\n * const depositData = await prepareDepositTransactionData({\n * yieldType: 'PRIME',\n * recipientAddress: '0x1234...',\n * depositToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * depositAmount: \"1.0\",\n * chainId: 1,\n * slippage: 100, // 1% slippage (100 bps)\n * partnerCode: 'my-partner-code',\n * });\n * ```\n *\n * @param {PrepareDepositTransactionDataParams} params - Parameters for the deposit operation\n * @returns {Promise<DepositTransactionData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If vault cannot be resolved, asset not found, or contracts not configured\n */\nexport async function prepareDepositTxData(\n params: PrepareDepositTxDataParams\n): Promise<DepositTxData> {\n const {\n yieldType,\n depositToken,\n depositAmount,\n chainId,\n slippage = DEFAULT_SLIPPAGE_BPS,\n recipientAddress,\n partnerCode,\n } = params;\n\n try {\n const normalizedChainId = toChainId(chainId);\n\n // Implement vault resolution using findVaultByConfig\n let vault: AmplifyVault | null;\n try {\n vault = await findVaultByConfig({\n assetAddress: depositToken,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositToken} with yield type ${yieldType} on chain ${normalizedChainId}: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositTransactionData\",\n cause: error,\n }\n );\n }\n\n // Check if vault was found\n if (!vault) {\n throw new APIError(\n `No vault found for token address ${depositToken} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n {\n endpoint: \"prepareDepositTransactionData\",\n }\n );\n }\n\n // Fetch the asset metadata for the deposit token\n let asset: SupportedAsset | null = null;\n const assets = await getAssetsFromCache({ address: depositToken });\n if (assets.length > 0) {\n // Find the asset for the correct chain\n asset =\n assets.find((a) => a.chains.includes(normalizedChainId)) ||\n assets[0] ||\n null;\n }\n\n if (!asset) {\n throw new APIError(\n `Asset metadata not found for token ${depositToken} on chain ${normalizedChainId}`,\n {\n endpoint: \"prepareDepositTransactionData\",\n }\n );\n }\n\n // Verify transaction data includes correct vault contract addresses\n const communityCodeDepositorAddress = vault.vault\n .communityCodeDepositorAddress as Address;\n const accountantAddress = vault.vault.accountantAddress as Address;\n const depositAssetAddress = asset.address as Address;\n\n // Get exchange rate from accountant (returns tuple from multicall)\n const [depositAssetDecimalsResult, rateInQuoteResult] =\n await getRateInQuoteWithAssetDecimals({\n assetAddress: depositAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n\n // Check decimals call result\n if (depositAssetDecimalsResult.status === \"failure\") {\n throw new APIError(\n `Failed to get asset decimals: ${\n depositAssetDecimalsResult.error?.message || \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositTransactionData\",\n cause: depositAssetDecimalsResult.error,\n }\n );\n }\n\n // Check rate call result\n if (rateInQuoteResult.status === \"failure\") {\n throw new APIError(\n `Failed to get exchange rate: ${\n rateInQuoteResult.error?.message || \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositTransactionData\",\n cause: rateInQuoteResult.error,\n }\n );\n }\n\n // Use decimals from API instead of on-chain call\n const depositAmountAsBigInt = parseUnits(\n depositAmount,\n depositAssetDecimalsResult.result\n );\n\n // Get vault shares asset decimals for minimum mint calculation\n const vaultSharesAssets = await fetchSupportedAssets({\n address: vault.vault.boringVaultAddress,\n });\n\n if (vaultSharesAssets.length === 0) {\n throw new APIError(\n `Vault shares token not found in supported assets: ${vault.vault.boringVaultAddress}`,\n { endpoint: \"prepareDepositTransactionData\" }\n );\n }\n\n const minimumMint = calculateMinimumMint(\n depositAmountAsBigInt,\n rateInQuoteResult.result,\n depositAssetDecimalsResult.result,\n slippage\n );\n\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `CommunityCodeDepositor contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositTransactionData\" }\n );\n }\n\n return {\n abi: CommunityCodeDepositorAbi,\n address: communityCodeDepositorAddress,\n functionName: \"deposit\",\n args: [\n depositAssetAddress,\n depositAmountAsBigInt,\n minimumMint,\n recipientAddress,\n stringToHex(partnerCode || \"\"),\n ],\n chainId: normalizedChainId,\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors with context\n throw new APIError(\n `Failed to prepare deposit transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareDepositTransactionData\",\n cause: error,\n }\n );\n }\n}\n\nexport type { DepositTxData, PrepareDepositTxDataParams };\n","/**\n * @file Deposit with permit functionality for Nucleus vaults\n * @module vaults/deposit/deposit-with-permit\n */\n\nimport {\n type Address,\n type Hex,\n hexToSignature,\n parseUnits,\n stringToHex,\n} from \"viem\";\nimport { CommunityCodeDepositorAbi } from \"../../abi/community-code-depositor-abi\";\nimport { erc2612Abi } from \"../../abi/erc2612-abi\";\nimport { getRateInQuoteWithAssetDecimals } from \"../../api/accountant\";\nimport {\n fetchSupportedAssets,\n findVaultByConfig,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport { getClient } from \"../../lib/viem/client\";\nimport type {\n AmplifyVault,\n SupportedAsset,\n YieldType,\n} from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { calculateMinimumMint } from \"./utils\";\n\n/**\n * EIP-712 domain separator conforming to the EIP-712 TypedData JSON schema\n * Compatible with standard EIP-712 signing libraries (Privy, wagmi, ethers)\n *\n * This interface matches the domain type from SignTypedDataParams as defined in\n * the EIP-712 specification and implemented by signing libraries.\n *\n * @see {@link https://eips.ethereum.org/EIPS/eip-712#specification-of-the-eth_signtypeddata-json-rpc EIP-712 Specification}\n *\n * @property name - Human-readable name of the signing domain\n * @property version - Version of the signing domain\n * @property chainId - Ethereum chain ID as a number (not bigint)\n * @property verifyingContract - Address of the contract that will verify the signature\n * @property salt - Optional salt for disambiguation\n */\nexport interface EIP712Domain {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n salt?: ArrayBuffer;\n}\n\n/**\n * T008: EIP-2612 Permit type definition\n * Standard structure for permit typed data per EIP-2612 specification\n */\nexport const PERMIT_TYPES = {\n Permit: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n ],\n};\n\n/**\n * T009: Complete EIP-712 typed data for permit signature\n * Returned by prepareDepositPermitSignature() ready for wallet signing\n *\n * @property domain - EIP-712 domain separator with numeric chainId\n * @property types - EIP-2612 Permit type structure (mutable for compatibility)\n * @property message - Permit message fields\n * @property primaryType - Always \"Permit\" for EIP-2612\n */\nexport interface PermitSignatureData {\n domain: EIP712Domain;\n types: {\n Permit: Array<{ name: string; type: string }>;\n };\n message: {\n owner: Address;\n spender: Address;\n value: bigint;\n nonce: bigint;\n deadline: bigint;\n };\n primaryType: \"Permit\";\n}\n\n/**\n * T009: Parsed permit signature components\n * Returned by parsePermitSignature() after converting hex signature\n *\n * @property v - Recovery ID (27 or 28)\n * @property r - First 32 bytes of signature\n * @property s - Second 32 bytes of signature\n */\nexport interface ParsedPermitSignature {\n v: number;\n r: Hex;\n s: Hex;\n}\n\n/**\n * T009: Parameters for prepareDepositPermitSignature\n * Input parameters for generating permit typed data\n *\n * @property yieldType - Vault yield strategy\n * @property depositToken - Token contract address to deposit\n * @property depositAmount - Deposit amount as decimal string\n * @property recipientAddress - User address (permit owner)\n * @property chainId - Blockchain network ID\n * @property deadline - Optional permit expiration (defaults to 1 hour)\n * @property nonce - Optional pre-fetched nonce (skips RPC call if provided)\n * @property decimals - Optional pre-fetched token decimals (skips RPC call)\n * @property tokenName - Optional pre-fetched token name (skips RPC call)\n * @property tokenVersion - Optional pre-fetched token version (skips RPC call)\n */\nexport interface PrepareDepositPermitSignatureParams {\n yieldType: YieldType;\n depositToken: Address;\n depositAmount: string;\n recipientAddress: Address;\n chainId: number;\n deadline?: bigint;\n /** Pre-fetched nonce from getTokenPermitInfoWithAllowance */\n nonce?: bigint;\n /** Pre-fetched token decimals */\n decimals?: number;\n /** Pre-fetched token name for EIP-712 domain */\n tokenName?: string;\n /** Pre-fetched token version for EIP-712 domain (defaults to \"1\") */\n tokenVersion?: string;\n}\n\n/**\n * T009: Encoded transaction data for permit deposit\n * Returned by updated prepareDepositWithPermitTransactionData()\n *\n * @property abi - Contract ABI\n * @property functionName - Function name to call\n * @property {readonly [depositAsset: Address, depositAmount: bigint, minimumMint: bigint, to: Address, distributorCode: Hex, deadline: bigint, v: number, r: Hex, s: Hex]} args - Function arguments\n * @property address - Teller contract address\n * @property chainId - Chain ID for transaction\n */\n\nexport interface DepositWithPermitData {\n abi: typeof CommunityCodeDepositorAbi;\n functionName: \"depositWithPermit\";\n args: readonly [\n depositAsset: Address,\n depositAmount: bigint,\n minimumMint: bigint,\n to: Address,\n distributorCode: Hex,\n deadline: bigint,\n v: number,\n r: Hex,\n s: Hex\n ];\n}\n\nexport interface UnencodedDepositWithPermitData {\n data: DepositWithPermitData;\n address: Address;\n chainId: number;\n}\n\n/**\n * T018-T030: Prepare complete EIP-712 typed data for permit signature\n *\n * Reads token metadata (name, version, nonce) from the blockchain and\n * constructs the complete EIP-712 structure for wallet signing.\n *\n * @param params - Permit signature parameters\n * @returns Complete EIP-712 typed data ready for signing\n * @throws {APIError} If token doesn't support EIP-2612, vault not found, or chain unsupported\n *\n * @example\n * ```typescript\n * const permitData = await prepareDepositPermitSignature({\n * yieldType: 'PRIME',\n * depositToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * depositAmount: '1000.0',\n * recipientAddress: recipientAddress,\n * chainId: 1,\n * deadline: BigInt(Math.floor(Date.now() / 1000) + 3600),\n * });\n *\n * // Sign with wallet\n * const signature = await signTypedData(permitData);\n * ```\n */\nexport async function prepareDepositPermitSignature(\n params: PrepareDepositPermitSignatureParams\n): Promise<PermitSignatureData> {\n const {\n yieldType,\n depositToken,\n depositAmount,\n recipientAddress,\n chainId,\n deadline,\n // Optional pre-fetched data to skip RPC calls\n nonce: prefetchedNonce,\n decimals: prefetchedDecimals,\n tokenName: prefetchedTokenName,\n tokenVersion: prefetchedTokenVersion,\n } = params;\n\n try {\n const normalizedChainId = toChainId(chainId);\n\n // T019: Implement vault resolution using findVaultByConfig\n let vault: AmplifyVault | null;\n try {\n vault = await findVaultByConfig({\n assetAddress: depositToken,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositToken} with yield type ${yieldType} on chain ${normalizedChainId}: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n cause: error,\n }\n );\n }\n\n // T028: Check if vault was found\n if (!vault) {\n throw new APIError(\n `No vault found for token address ${depositToken} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n }\n );\n }\n\n // T029: Validate chainId is supported\n const communityCodeDepositorAddress =\n vault.vault.communityCodeDepositorAddress;\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `CommunityCodeDepositor contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositPermitSignature\" }\n );\n }\n\n // Use pre-fetched data if available, otherwise fetch from chain\n let resolvedTokenName: string;\n let resolvedTokenVersion: string;\n let resolvedNonce: bigint;\n\n // Check if all required permit data is pre-fetched\n const hasAllPrefetchedData =\n prefetchedTokenName !== undefined &&\n prefetchedTokenVersion !== undefined &&\n prefetchedNonce !== undefined;\n\n if (hasAllPrefetchedData) {\n // Use pre-fetched data - no RPC call needed\n resolvedTokenName = prefetchedTokenName;\n resolvedTokenVersion = prefetchedTokenVersion;\n resolvedNonce = prefetchedNonce;\n } else {\n // T020: Create PublicClient from chainId\n const client = await getClient(normalizedChainId);\n\n // T021: Read token metadata (name, version, nonces) via multicall\n try {\n // Batch all three reads into a single RPC call\n const [nameResult, versionResult, nonceResult] = await client.multicall(\n {\n contracts: [\n {\n address: depositToken,\n abi: erc2612Abi,\n functionName: \"name\",\n },\n {\n address: depositToken,\n abi: erc2612Abi,\n functionName: \"version\",\n },\n {\n address: depositToken,\n abi: erc2612Abi,\n functionName: \"nonces\",\n args: [recipientAddress],\n },\n ],\n }\n );\n\n // Extract name (use prefetched if available)\n if (prefetchedTokenName !== undefined) {\n resolvedTokenName = prefetchedTokenName;\n } else if (nameResult.status === \"success\") {\n resolvedTokenName = nameResult.result as string;\n } else {\n throw new APIError(`Failed to read token name from ${depositToken}`, {\n endpoint: \"prepareDepositPermitSignature\",\n cause: nameResult.error,\n });\n }\n\n // T022: Extract version with fallback to \"1\" (use prefetched if available)\n if (prefetchedTokenVersion !== undefined) {\n resolvedTokenVersion = prefetchedTokenVersion;\n } else if (versionResult.status === \"success\") {\n resolvedTokenVersion = versionResult.result as string;\n } else {\n // Gracefully default to \"1\" when version() is not implemented\n resolvedTokenVersion = \"1\";\n }\n\n // T027: Extract nonce (use prefetched if available)\n if (prefetchedNonce !== undefined) {\n resolvedNonce = prefetchedNonce;\n } else if (nonceResult.status === \"success\") {\n resolvedNonce = nonceResult.result as bigint;\n } else {\n throw new APIError(\n `Token ${depositToken} does not support EIP-2612 permit. Missing required function: nonces()`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n cause: nonceResult.error,\n }\n );\n }\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n throw new APIError(\n `Failed to read token metadata: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n cause: error,\n }\n );\n }\n }\n\n // T023: Calculate deadline (default: current time + 3600 seconds)\n const permitDeadline =\n deadline ?? BigInt(Math.floor(Date.now() / 1000) + 3600);\n\n // Convert depositAmount to bigint\n // Use pre-fetched decimals if available, otherwise fetch from API\n let resolvedDecimals: number;\n if (prefetchedDecimals !== undefined) {\n resolvedDecimals = prefetchedDecimals;\n } else {\n const assets = await fetchSupportedAssets({ address: depositToken });\n if (assets.length === 0) {\n throw new APIError(\n `Asset metadata not found for token ${depositToken}`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n }\n );\n }\n resolvedDecimals = assets[0].decimals;\n }\n const value = parseUnits(depositAmount, resolvedDecimals);\n\n // T024: Build EIP-712 domain\n const domain: EIP712Domain = {\n name: resolvedTokenName,\n version: resolvedTokenVersion,\n chainId: normalizedChainId,\n verifyingContract: depositToken,\n };\n\n // T025: Build permit message\n const message = {\n owner: recipientAddress,\n spender: communityCodeDepositorAddress,\n value,\n nonce: resolvedNonce,\n deadline: permitDeadline,\n };\n\n // T026: Return PermitSignatureData\n return {\n domain,\n message,\n primaryType: \"Permit\",\n types: PERMIT_TYPES,\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare permit signature: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareDepositPermitSignature\",\n cause: error,\n }\n );\n }\n}\n\n/**\n * T036-T040: Parse raw hex signature into v, r, s components\n *\n * Handles both v-based and yParity-based signature formats.\n * Converts yParity to v by adding 27 if needed.\n *\n * @param signature - Raw hex signature from wallet\n * @returns Parsed signature components (v, r, s)\n * @throws {APIError} If signature format is invalid\n *\n * @example\n * ```typescript\n * const signature = await signTypedData(permitData);\n * const { v, r, s } = parsePermitSignature(signature);\n * // Use v, r, s in smart contract call\n * ```\n */\nexport function parsePermitSignature(signature: Hex): ParsedPermitSignature {\n try {\n // T037: Use viem's hexToSignature for robust parsing\n const parsed = hexToSignature(signature);\n\n // T038: Calculate v from yParity if present, otherwise use v\n // Modern wallets may return yParity (0 or 1) instead of v (27 or 28)\n let v: number;\n if (parsed.v !== undefined) {\n // v-based signature (legacy format)\n v = Number(parsed.v);\n } else if (parsed.yParity !== undefined) {\n // yParity-based signature (modern format) - convert to v\n v = parsed.yParity + 27;\n } else {\n // Default to 27 if neither present\n v = 27;\n }\n\n // T039: Return ParsedPermitSignature object\n return {\n v,\n r: parsed.r,\n s: parsed.s,\n };\n } catch (error) {\n // T040: Throw APIError with clear message when parsing fails\n throw new APIError(\n `Invalid permit signature format. Expected hex string but received: ${signature}. ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"parsePermitSignature\",\n cause: error,\n }\n );\n }\n}\n\n/**\n * T048: Updated parameters for prepareDepositWithPermitTransactionData()\n * Now accepts raw signature and deadline for complete transaction encoding\n *\n * @interface PrepareDepositWithPermitTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (e.g., \"PRIME\", \"TBILL\")\n * @property {Address} recipientAddress - Ethereum address of the user (recipient of vault shares)\n * @property {Address} depositToken - Token contract address to deposit (matches vault's baseTokenAddress)\n * @property {string} depositAmount - Amount of assets to deposit as a decimal string (e.g., \"100.25\")\n * @property {number | ChainId} chainId - ID of the chain where the deposit will occur\n * @property {Hex} signature - Raw hex signature from wallet signing\n * @property {bigint} deadline - Deadline timestamp (must match permit signature deadline)\n * @property {number} [slippage] - Optional (default is 50 (0.5%)): Maximum acceptable slippage in basis points (e.g., 100 for 1%).\n * @property {string} [partnerCode] - Optional (default is empty string): Partner code to credit deposit fees to the partner used for the deposit\n *\n * @example\n * ```typescript\n * const permitData = await prepareDepositPermitSignature({ ... });\n * const signature = await signTypedData(permitData);\n *\n * const params: PrepareDepositWithPermitTransactionDataParams = {\n * yieldType: \"PRIME\",\n * recipientAddress: \"0x1234567890123456789012345678901234567890\",\n * depositToken: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * depositAmount: \"100.25\",\n * chainId: 1,\n * signature,\n * deadline: permitData.message.deadline,\n * slippage: 100, // 1%\n * partnerCode: \"my-partner-code\",\n * };\n * ```\n */\nexport interface PrepareDepositWithPermitTxDataParams {\n yieldType: YieldType;\n recipientAddress: Address;\n depositToken: Address;\n depositAmount: string;\n chainId: number | ChainId;\n signature: Hex;\n deadline: bigint;\n slippage?: number;\n partnerCode?: string;\n}\n\n/**\n * T048-T057: Prepare complete deposit transaction with permit signature\n *\n * Accepts raw signature and deadline, parses signature internally,\n * resolves vault, calculates minimum mint with slippage, and\n * encodes the complete depositWithPermit function call.\n *\n * @param {PrepareDepositWithPermitTransactionDataParams} params - Deposit parameters including signature and deadline\n * @returns {Promise<UnencodedDepositWithPermitData>} Encoded transaction data ready for submission\n * @throws {APIError} If vault not found, invalid signature, or parameter validation fails\n *\n * // Submit transaction\n * await sendTransaction({\n * to: txData.address,\n * data: txData.data,\n * });\n * ```\n */\nexport async function prepareDepositWithPermitTxData(\n params: PrepareDepositWithPermitTxDataParams\n): Promise<UnencodedDepositWithPermitData> {\n const {\n yieldType,\n depositToken,\n depositAmount,\n chainId,\n signature,\n deadline,\n slippage = DEFAULT_SLIPPAGE_BPS,\n recipientAddress,\n partnerCode,\n } = params;\n\n try {\n // T049: Parse signature internally using parsePermitSignature\n const { v, r, s } = parsePermitSignature(signature);\n\n // T050: Validate slippage parameter is within acceptable range (0-10000 bps)\n if (slippage < 0 || slippage > 10000) {\n throw new APIError(\n `Invalid slippage value: ${slippage}. Slippage must be between 0 and 10000 basis points.`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n }\n );\n }\n\n const normalizedChainId = toChainId(chainId);\n\n // T008: Implement vault resolution using findVaultByConfig\n let vault: AmplifyVault | null;\n try {\n vault = await findVaultByConfig({\n assetAddress: depositToken,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositToken} with yield type ${yieldType} on chain ${normalizedChainId}: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n cause: error,\n }\n );\n }\n\n // Check if vault was found\n if (!vault) {\n throw new APIError(\n `No vault found for token address ${depositToken} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n }\n );\n }\n\n // T009: Fetch deposit token metadata using fetchSupportedAssets\n let asset: SupportedAsset | null = null;\n const assets = await fetchSupportedAssets({ address: depositToken });\n if (assets.length > 0) {\n // Find the asset for the correct chain\n asset =\n assets.find((a) => a.chains.includes(normalizedChainId)) ||\n assets[0] ||\n null;\n }\n\n if (!asset) {\n throw new APIError(\n `Asset metadata not found for token ${depositToken} on chain ${normalizedChainId}`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n }\n );\n }\n\n // T035: Implement chainId validation against SupportedAsset.chains\n // T036: Throw APIError with descriptive message when chainId not in supportedChains\n if (!asset.chains || !asset.chains.includes(normalizedChainId)) {\n throw new APIError(\n `Token ${\n asset.symbol || depositToken\n } not supported on chain ${normalizedChainId}`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n }\n );\n }\n\n // Verify transaction data includes correct vault contract addresses\n const communityCodeDepositorAddress =\n vault.vault.communityCodeDepositorAddress;\n const accountantAddress = vault.vault.accountantAddress;\n const depositAssetAddress = asset.address;\n\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `CommunityCodeDepositor contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositWithPermitTxData\" }\n );\n }\n\n // T010: Call getRateInQuoteWithAssetDecimals for exchange rate\n const [depositAssetDecimalsResult, rateInQuoteResult] =\n await getRateInQuoteWithAssetDecimals({\n assetAddress: depositAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n\n // Check decimals call result\n if (depositAssetDecimalsResult.status === \"failure\") {\n throw new APIError(\n `Failed to get asset decimals: ${\n depositAssetDecimalsResult.error?.message || \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n cause: depositAssetDecimalsResult.error,\n }\n );\n }\n\n // Check rate call result\n if (rateInQuoteResult.status === \"failure\") {\n throw new APIError(\n `Failed to get exchange rate: ${\n rateInQuoteResult.error?.message || \"Unknown error\"\n }`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n cause: rateInQuoteResult.error,\n }\n );\n }\n\n // T012: Convert depositAmount from decimal string to bigint\n const depositAmountAsBigInt = parseUnits(depositAmount, asset.decimals);\n\n // Get vault shares asset decimals for minimum mint calculation\n const vaultSharesAssets = await fetchSupportedAssets({\n address: vault.vault.boringVaultAddress,\n });\n\n if (vaultSharesAssets.length === 0) {\n throw new APIError(\n `Vault shares token not found in supported assets: ${vault.vault.boringVaultAddress}`,\n { endpoint: \"prepareDepositWithPermitTxData\" }\n );\n }\n\n // T051: Calculate minimumMint using calculateMinimumMint utility\n const minimumMint = calculateMinimumMint(\n depositAmountAsBigInt,\n rateInQuoteResult.result,\n vaultSharesAssets[0].decimals,\n slippage\n );\n\n return {\n data: {\n abi: CommunityCodeDepositorAbi,\n functionName: \"depositWithPermit\",\n args: [\n depositAssetAddress,\n depositAmountAsBigInt,\n minimumMint,\n recipientAddress,\n stringToHex(partnerCode || \"\"),\n deadline,\n v,\n r,\n s,\n ],\n },\n address: communityCodeDepositorAddress,\n chainId: normalizedChainId,\n };\n } catch (error) {\n // T057: Implement error handling\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors with context\n throw new APIError(\n `Failed to prepare deposit with permit transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareDepositWithPermitTxData\",\n cause: error,\n }\n );\n }\n}\n","/**\n * @file Unified deposit module with wrapper functions\n * @module vaults/deposit\n *\n * Provides high-level wrapper functions for deposit authorization and execution:\n * - `prepareDepositAuthorization`: Determines optimal authorization method (permit/approval)\n * - `prepareDeposit`: Unified deposit preparation with automatic routing\n */\n\nimport { type Address, type Hex, parseUnits } from \"viem\";\nimport { findVaultByConfig } from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport { isDepositSpendApproved } from \"../../display/approvals\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport {\n type ApproveDepositTokenTxData,\n prepareApproveDepositTokenTxData,\n} from \"./approve-deposit\";\nimport { type DepositTxData, prepareDepositTxData } from \"./deposit\";\nimport {\n type PermitSignatureData,\n type UnencodedDepositWithPermitData,\n prepareDepositPermitSignature,\n prepareDepositWithPermitTxData,\n} from \"./deposit-with-permit\";\n\n// ============================================================================\n// ENUMS\n// ============================================================================\n\n/**\n * Authorization methods for deposit operations\n *\n * Extensible const object for current and future authorization mechanisms:\n * - PERMIT: EIP-2612 off-chain signature (gas efficient, single transaction)\n * - APPROVAL: Traditional ERC20 approval (two transactions)\n * - ALREADY_APPROVED: Existing allowance is sufficient (no action needed)\n *\n * @example\n * ```typescript\n * import { DepositAuthMethod } from \"@paxoslabs/amplify-sdk\";\n *\n * if (result.method === DepositAuthMethod.PERMIT) {\n * // Handle permit flow\n * }\n * ```\n */\nexport const DepositAuthMethod = {\n PERMIT: \"permit\",\n APPROVAL: \"approval\",\n ALREADY_APPROVED: \"already_approved\",\n} as const;\n\nexport type DepositAuthMethod =\n (typeof DepositAuthMethod)[keyof typeof DepositAuthMethod];\n\n// ============================================================================\n// TYPE DEFINITIONS - Authorization\n// ============================================================================\n\n/**\n * Permit authorization result\n * Returned when token supports EIP-2612 permit\n */\nexport interface PermitAuthorizationResult {\n method: typeof DepositAuthMethod.PERMIT;\n /** EIP-712 typed data ready for wallet signing */\n permitData: PermitSignatureData;\n}\n\n/**\n * Approval authorization result\n * Returned when an ERC20 approval transaction is needed\n */\nexport interface ApprovalAuthorizationResult {\n method: typeof DepositAuthMethod.APPROVAL;\n /** Transaction data for ERC20 approve() call */\n txData: ApproveDepositTokenTxData;\n /** Current allowance (human-readable) */\n currentAllowance: string;\n /** Current allowance as BigInt string */\n currentAllowanceAsBigInt: string;\n}\n\n/**\n * Already approved authorization result\n * Returned when existing allowance is sufficient for the deposit\n */\nexport interface AlreadyApprovedAuthorizationResult {\n method: typeof DepositAuthMethod.ALREADY_APPROVED;\n /** Current allowance (human-readable) */\n allowance: string;\n /** Current allowance as BigInt string */\n allowanceAsBigInt: string;\n}\n\n/**\n * Discriminated union of all authorization result types\n *\n * Use type narrowing with `result.method` to access specific fields:\n *\n * @example\n * ```typescript\n * const result = await prepareDepositAuthorization({...});\n *\n * switch (result.method) {\n * case DepositAuthMethod.PERMIT:\n * // TypeScript knows result.permitData exists\n * const signature = await signTypedData(result.permitData);\n * break;\n * case DepositAuthMethod.APPROVAL:\n * // TypeScript knows result.txData exists\n * await writeContract(result.txData);\n * break;\n * case DepositAuthMethod.ALREADY_APPROVED:\n * // TypeScript knows result.allowance exists\n * console.log(`Already approved: ${result.allowance}`);\n * break;\n * }\n * ```\n */\nexport type DepositAuthorizationResult =\n | PermitAuthorizationResult\n | ApprovalAuthorizationResult\n | AlreadyApprovedAuthorizationResult;\n\n/**\n * Parameters for prepareDepositAuthorization\n */\nexport interface PrepareDepositAuthorizationParams {\n /** Yield strategy type (e.g., \"PRIME\", \"TBILL\", \"LENDING\") */\n yieldType: YieldType;\n /** Token contract address to deposit */\n depositToken: Address;\n /** Amount of assets to deposit as decimal string (e.g., \"100.25\") */\n depositAmount: string;\n /** User's wallet address (permit owner / approval sender) */\n recipientAddress: Address;\n /** Blockchain network ID */\n chainId: ChainId;\n /** Optional deadline for permit signature (defaults to 1 hour from now) */\n deadline?: bigint;\n /** Force specific authorization method (bypasses automatic detection) */\n forceMethod?: \"permit\" | \"approval\";\n}\n\n// ============================================================================\n// TYPE DEFINITIONS - Deposit\n// ============================================================================\n\n/**\n * Parameters for prepareDeposit\n * Unified deposit function accepting optional permit signature\n */\nexport interface PrepareDepositParams {\n /** Yield strategy type (e.g., \"PRIME\", \"TBILL\", \"LENDING\") */\n yieldType: YieldType;\n /** Token contract address to deposit */\n depositToken: Address;\n /** Amount of assets to deposit as decimal string (e.g., \"100.25\") */\n depositAmount: string;\n /** Recipient address for vault shares */\n recipientAddress: Address;\n /** Blockchain network ID */\n chainId: ChainId;\n /** Optional slippage in basis points (default: 50 = 0.5%) */\n slippage?: number;\n /** Optional partner code for fee attribution */\n partnerCode?: string;\n /** Optional permit signature (hex string from wallet signing) */\n signature?: Hex;\n /** Optional permit deadline (must match signature deadline) */\n deadline?: bigint;\n /** Force deposit method (bypasses automatic routing) */\n forceMethod?: \"permit\" | \"approval\";\n}\n\n/**\n * Standard deposit result (approval flow)\n */\nexport interface StandardDepositResult {\n method: typeof DepositAuthMethod.APPROVAL;\n txData: DepositTxData;\n}\n\n/**\n * Permit deposit result\n */\nexport interface PermitDepositResult {\n method: typeof DepositAuthMethod.PERMIT;\n txData: UnencodedDepositWithPermitData;\n}\n\n/**\n * Unified deposit result\n * Returns either standard deposit or permit deposit transaction data\n */\nexport type PrepareDepositResult = StandardDepositResult | PermitDepositResult;\n\n// ============================================================================\n// FUNCTIONS\n// ============================================================================\n\n/**\n * Prepares authorization for a deposit operation\n *\n * Intelligently determines the best authorization method:\n * 1. Check if token supports EIP-2612 permit → return permit signature data\n * 2. Check existing allowance → if sufficient, return \"already approved\"\n * 3. Otherwise → return approval transaction data\n *\n * Supports force override via `forceMethod` parameter.\n *\n * @param params - Authorization parameters\n * @returns Discriminated union of authorization results\n * @throws {APIError} If vault not found, chain not supported, or token invalid\n *\n * @example\n * ```typescript\n * import { prepareDepositAuthorization, DepositAuthMethod } from \"@paxoslabs/amplify-sdk\";\n *\n * const authResult = await prepareDepositAuthorization({\n * yieldType: \"PRIME\",\n * depositToken: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * depositAmount: \"1000.0\",\n * recipientAddress: \"0x1234...\",\n * chainId: 1,\n * });\n *\n * if (authResult.method === DepositAuthMethod.PERMIT) {\n * const signature = await signTypedData(authResult.permitData);\n * // Use signature in prepareDeposit\n * } else if (authResult.method === DepositAuthMethod.APPROVAL) {\n * await writeContract(authResult.txData);\n * // Wait for confirmation, then call prepareDeposit\n * } else {\n * // Already approved, proceed directly to deposit\n * console.log(`Approved amount: ${authResult.allowance}`);\n * }\n * ```\n */\nexport async function prepareDepositAuthorization(\n params: PrepareDepositAuthorizationParams\n): Promise<DepositAuthorizationResult> {\n const {\n yieldType,\n depositToken,\n depositAmount,\n recipientAddress,\n chainId,\n deadline,\n forceMethod,\n } = params;\n\n try {\n const normalizedChainId = toChainId(chainId);\n\n // Validate vault exists for this configuration\n const vault = await findVaultByConfig({\n assetAddress: depositToken,\n yieldType,\n chainId: normalizedChainId,\n });\n\n if (!vault) {\n throw new APIError(\n `No vault found for token ${depositToken} with yield type '${yieldType}' on chain ${normalizedChainId}`,\n { endpoint: \"prepareDepositAuthorization\" }\n );\n }\n\n // Get token info (allowance, permit support, decimals, etc.) in a single multicall\n // This is used for all routing decisions and passed to downstream functions\n const tokenInfo = await isDepositSpendApproved({\n yieldType,\n chainId: normalizedChainId,\n depositAssetAddress: depositToken,\n recipientAddress,\n });\n\n // Handle force method overrides\n if (forceMethod === \"permit\") {\n const permitData = await prepareDepositPermitSignature({\n yieldType,\n depositToken,\n depositAmount,\n recipientAddress,\n chainId: normalizedChainId,\n deadline,\n // Pass pre-fetched data to avoid redundant RPC calls\n nonce: tokenInfo.nonce ?? undefined,\n decimals: tokenInfo.decimals,\n tokenName: tokenInfo.tokenName,\n tokenVersion: tokenInfo.tokenVersion,\n });\n\n return {\n method: DepositAuthMethod.PERMIT,\n permitData,\n };\n }\n\n if (forceMethod === \"approval\") {\n const txData = await prepareApproveDepositTokenTxData({\n yieldType,\n depositToken,\n approvalAmount: depositAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: DepositAuthMethod.APPROVAL,\n txData,\n currentAllowance: tokenInfo.allowance,\n currentAllowanceAsBigInt: tokenInfo.allowanceAsBigInt,\n };\n }\n\n // Automatic detection: Use dynamic on-chain permit support detection\n if (tokenInfo.supportsPermit) {\n const permitData = await prepareDepositPermitSignature({\n yieldType,\n depositToken,\n depositAmount,\n recipientAddress,\n chainId: normalizedChainId,\n deadline,\n // Pass pre-fetched data to avoid redundant RPC calls\n nonce: tokenInfo.nonce ?? undefined,\n decimals: tokenInfo.decimals,\n tokenName: tokenInfo.tokenName,\n tokenVersion: tokenInfo.tokenVersion,\n });\n\n return {\n method: DepositAuthMethod.PERMIT,\n permitData,\n };\n }\n\n // No permit support: Check existing allowance\n // Use decimals from tokenInfo (already fetched via multicall)\n const depositAmountBigInt = parseUnits(depositAmount, tokenInfo.decimals);\n const currentAllowanceBigInt = BigInt(tokenInfo.allowanceAsBigInt);\n\n // Check if existing allowance is sufficient\n if (\n tokenInfo.isApproved &&\n currentAllowanceBigInt >= depositAmountBigInt\n ) {\n return {\n method: DepositAuthMethod.ALREADY_APPROVED,\n allowance: tokenInfo.allowance,\n allowanceAsBigInt: tokenInfo.allowanceAsBigInt,\n };\n }\n\n // Insufficient allowance: prepare approval transaction\n const txData = await prepareApproveDepositTokenTxData({\n yieldType,\n depositToken,\n approvalAmount: depositAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: DepositAuthMethod.APPROVAL,\n txData,\n currentAllowance: tokenInfo.allowance,\n currentAllowanceAsBigInt: tokenInfo.allowanceAsBigInt,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to prepare deposit authorization: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareDepositAuthorization\",\n cause: error,\n }\n );\n }\n}\n\n/**\n * Unified deposit preparation function\n *\n * Intelligently routes to permit deposit or standard deposit based on:\n * 1. Presence of signature/deadline parameters → permit deposit\n * 2. Force method override → specified method\n * 3. Otherwise → standard deposit\n *\n * @param params - Deposit parameters with optional permit signature\n * @returns Discriminated union of deposit transaction data\n * @throws {APIError} If vault not found, invalid signature, or validation fails\n *\n * @example\n * ```typescript\n * import { prepareDeposit, DepositAuthMethod } from \"@paxoslabs/amplify-sdk\";\n *\n * // Scenario 1: Permit deposit (with signature from prepareDepositAuthorization)\n * const permitDeposit = await prepareDeposit({\n * yieldType: \"PRIME\",\n * depositToken: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n * depositAmount: \"1000.0\",\n * recipientAddress: \"0x1234...\",\n * chainId: 1,\n * signature: \"0xabc...\",\n * deadline: 1234567890n,\n * });\n * // permitDeposit.method === DepositAuthMethod.PERMIT\n *\n * // Scenario 2: Standard deposit (after approval)\n * const standardDeposit = await prepareDeposit({\n * yieldType: \"PRIME\",\n * depositToken: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n * depositAmount: \"1000.0\",\n * recipientAddress: \"0x1234...\",\n * chainId: 1,\n * });\n * // standardDeposit.method === DepositAuthMethod.APPROVAL\n *\n * // Submit transaction\n * await writeContract(standardDeposit.txData);\n * ```\n */\nexport async function prepareDeposit(\n params: PrepareDepositParams\n): Promise<PrepareDepositResult> {\n const {\n yieldType,\n depositToken,\n depositAmount,\n recipientAddress,\n chainId,\n slippage,\n partnerCode,\n signature,\n deadline,\n forceMethod,\n } = params;\n\n try {\n // Validate force method constraints\n if (forceMethod === \"permit\" && (!signature || deadline === undefined)) {\n throw new APIError(\n \"Permit deposit requires both signature and deadline parameters when forceMethod is 'permit'\",\n { endpoint: \"prepareDeposit\" }\n );\n }\n\n // Determine deposit method\n const usePermit =\n forceMethod === \"permit\" ||\n (forceMethod !== \"approval\" &&\n signature !== undefined &&\n deadline !== undefined);\n\n if (usePermit) {\n // Permit deposit path\n if (!signature || deadline === undefined) {\n throw new APIError(\n \"Permit deposit requires both signature and deadline parameters\",\n { endpoint: \"prepareDeposit\" }\n );\n }\n\n const txData = await prepareDepositWithPermitTxData({\n yieldType,\n depositToken,\n depositAmount,\n recipientAddress,\n chainId,\n signature,\n deadline,\n slippage,\n partnerCode,\n });\n\n return {\n method: DepositAuthMethod.PERMIT,\n txData,\n };\n }\n\n // Standard deposit path\n const txData = await prepareDepositTxData({\n yieldType,\n depositToken,\n depositAmount,\n recipientAddress,\n chainId,\n slippage,\n partnerCode,\n });\n\n return {\n method: DepositAuthMethod.APPROVAL,\n txData,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to prepare deposit: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareDeposit\",\n cause: error,\n }\n );\n }\n}\n\n// ============================================================================\n// RE-EXPORTS\n// ============================================================================\n\n// Re-export existing functions for backwards compatibility\nexport { prepareApproveDepositTokenTxData } from \"./approve-deposit\";\nexport type {\n ApproveDepositTokenTxData,\n PrepareApproveDepositTokenTxParams,\n} from \"./approve-deposit\";\n\nexport { prepareDepositTxData } from \"./deposit\";\nexport type { DepositTxData, PrepareDepositTxDataParams } from \"./deposit\";\n\nexport {\n PERMIT_TYPES,\n parsePermitSignature,\n prepareDepositPermitSignature,\n prepareDepositWithPermitTxData,\n} from \"./deposit-with-permit\";\nexport type {\n EIP712Domain,\n ParsedPermitSignature,\n PermitSignatureData,\n PrepareDepositPermitSignatureParams,\n PrepareDepositWithPermitTxDataParams,\n UnencodedDepositWithPermitData,\n} from \"./deposit-with-permit\";\n","import { type Address, parseUnits } from \"viem\";\nimport { BoringVaultAbi } from \"../../abi/boring-vault-abi\";\nimport {\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport {\n ATOMIC_QUEUE_CONTRACT_ADDRESS,\n DEFAULT_APPROVAL_AMOUNT,\n} from \"../../constants\";\nimport { APIError, type YieldType } from \"../../types/amplify-sdk-api\";\n/**\n * Parameters required for preparing an approval transaction (NEW AmplifyVault schema)\n * @interface PrepareApproveWithdrawTokenTxParams\n * @property {YieldType} yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @property {Address} wantAssetAddress - Address of the want token\n * @property {string} [withdrawAmount] - Optional amount to approve (defaults to maximum approval)\n * @property {ChainId} chainId - ID of the chain where the approval will occur\n */\ninterface PrepareApproveWithdrawTokenTxParams {\n yieldType: YieldType;\n wantAssetAddress: Address;\n withdrawAmount?: string;\n chainId: ChainId;\n}\n\n/**\n * Result object containing transaction data for a vault shares approval operation\n * @interface ApproveWithdrawTokenTxData\n * @property {typeof BoringVaultAbi} abi - ABI for the BoringVault contract\n * @property {Address} address - Address of the BoringVault (shares token)\n * @property {'approve'} functionName - Name of the function to call\n * @property {[Address, bigint]} args - Arguments for the approve function:\n * [spender (AtomicQueue address), amount]\n */\ninterface ApproveWithdrawTokenTxData {\n abi: typeof BoringVaultAbi;\n address: Address;\n functionName: \"approve\";\n args: [Address, bigint];\n}\n\n/**\n * Prepares the transaction data needed to approve vault shares for the AtomicQueue contract\n *\n * This function prepares an ERC20 approval transaction that allows the AtomicQueue\n * contract to spend the user's vault shares. It uses the new AmplifyVault schema\n * with asset decimals from the API (no on-chain calls).\n *\n * @example\n * ```typescript\n * const vaults = await fetchVaults({ chainId: 1 });\n * const approveData = await prepareApproveWithdrawToken({\n * yieldType: 'PRIME',\n * wantAssetAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * withdrawAmount: \"10.0\", // Approve 10 vault shares\n * chainId: 1,\n * });\n * ```\n *\n * @param {PrepareApproveWithdrawTokenTxParams} params - Parameters for the approval operation\n * @param {YieldType} params.yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @param {Address} params.wantAssetAddress - Address of the want token\n * @param {string} [params.withdrawAmount] - Optional amount to approve as a decimal string (defaults to maximum approval)\n * @param {number | string} params.chainId - ID of the chain where the approval will occur\n *\n * @returns {Promise<ApproveWithdrawTokenTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not on the correct chain or contracts not configured\n */\nexport async function prepareApproveWithdrawTxData({\n yieldType,\n wantAssetAddress,\n withdrawAmount,\n chainId,\n}: PrepareApproveWithdrawTokenTxParams): Promise<ApproveWithdrawTokenTxData> {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n assetAddress: wantAssetAddress,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n\n // Validation: Ensure vault is on the correct chain\n if (!config || config.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${config?.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareApproveWithdrawToken\" }\n );\n }\n\n // Validation: Ensure boringVault address is configured\n if (!config.vault.boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareApproveWithdrawToken\" }\n );\n }\n\n const boringVaultAddress = config.vault.boringVaultAddress;\n\n // Get vault shares asset decimals for parsing withdraw amount\n const vaultSharesAssets = await getAssetsFromCache({\n address: boringVaultAddress,\n });\n\n if (vaultSharesAssets.length === 0) {\n throw new APIError(\n `Vault shares token not found in supported assets: ${boringVaultAddress}`,\n { endpoint: \"prepareApproveWithdrawToken\" }\n );\n }\n\n // Use decimals from API instead of on-chain call\n const withdrawAmountAsBigInt = withdrawAmount\n ? parseUnits(withdrawAmount, vaultSharesAssets[0].decimals)\n : DEFAULT_APPROVAL_AMOUNT;\n\n return {\n abi: BoringVaultAbi,\n address: boringVaultAddress,\n functionName: \"approve\",\n args: [ATOMIC_QUEUE_CONTRACT_ADDRESS, withdrawAmountAsBigInt],\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare approval transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareApproveWithdrawToken\",\n cause: error,\n }\n );\n }\n}\n\nexport type { ApproveWithdrawTokenTxData, PrepareApproveWithdrawTokenTxParams };\n","import { WithdrawError } from \"../../types/amplify-sdk-api\";\nimport { isValidAddress } from \"../../utils/address\";\nimport { calculateDeadline } from \"../../utils/time\";\nimport type { UserRequest } from \"./withdraw\";\n\n/**\n * Prepares a withdrawal request with the specified parameters\n * @param redeemAmount The amount of tokens to be redeemed\n * @param atomicPrice The current atomic price for the withdrawal\n * @param deadline Optional timestamp for when the request expires\n * @returns UserRequest object with withdrawal parameters\n */\nconst prepareUserRequest = (\n offerAmount: bigint,\n atomicPrice: bigint,\n deadline: number\n): UserRequest => {\n const deadlineTimeStamp = calculateDeadline(deadline);\n return {\n deadline: deadlineTimeStamp,\n atomicPrice: atomicPrice,\n offerAmount: offerAmount,\n inSolve: false,\n };\n};\n\n/**\n * Calculates the final redeem amount accounting for exchange rate and slippage\n * @param amount The initial amount to be redeemed\n * @param exchangeRate The current exchange rate between tokens\n * @param slippage The slippage tolerance as a decimal (e.g., 0.01 for 1%)\n * @returns The final redeem amount after applying exchange rate and slippage\n */\n// ! Deprecated - marked for removal\n// const calculateWantAssetReceiveAmount = (\n// amount: bigint,\n// amountDecimals: number,\n// exchangeRate: bigint,\n// exchangeRateDecimals: number,\n// slippage: number\n// ): bigint => {\n// if (exchangeRate === BigInt(0)) {\n// return BigInt(0);\n// }\n// if (amountDecimals === exchangeRateDecimals) {\n// // all good\n// }\n\n// if (amountDecimals > exchangeRateDecimals) {\n// // normalize to larger decimals\n// }\n// // Convert amount to the target token using exchange rate\n// // Multiply by WAD (10^18) for precision and divide by exchange rate\n// const baseAmount = (amount * WAD.bigint) / exchangeRate;\n\n// // Convert slippage percentage to WAD format for calculation\n// const slippageAsBigInt = BigInt((slippage * WAD.number).toString());\n\n// // Calculate the amount to be subtracted due to slippage\n// const slippageAmount = (baseAmount * slippageAsBigInt) / WAD.bigint;\n\n// // Return the final amount after subtracting slippage\n// return baseAmount - slippageAmount;\n// };\n\n/**\n *\n * @param rateInQuote in want asset decimals\n * @param wantAssetDecimals in want asset decimals\n * @param slippage in bps (e.g., 20 for 0.2%) 20 in 4 decimals = 20 / 10000 = 0.002 = 0.2%\n * @returns atomic price in want asset decimals\n */\nconst calculateAtomicPrice = (\n rateInQuote: bigint, // e.g., 1200000 (1.2 USDC) or 120000000 (1.2 WBTC)\n wantAssetDecimals: number, // 6 for USDC, 8 for WBTC - the \"want\" asset decimals\n slippage: number // In bps (e.g., 20 for 0.2%)\n): bigint => {\n // Step 1: Create precision multiplier for want asset\n const wantPrecision = BigInt(10 ** wantAssetDecimals);\n\n // Step 2: Convert bps to decimal for calculation (bps / 10000)\n const slippageAsBigInt = (BigInt(slippage) * wantPrecision) / BigInt(10000);\n\n // Step 3: Apply formula: atomicPrice = rateInQuote * (1 - slippage)\n return (rateInQuote * (wantPrecision - slippageAsBigInt)) / wantPrecision;\n};\n\nexport { calculateAtomicPrice, prepareUserRequest };\n\n/**\n * Validates withdrawal transaction parameters\n *\n * Performs comprehensive validation of all user-supplied parameters:\n * - yieldType is non-empty string\n * - recipientAddress is valid Ethereum address (not zero address)\n * - wantToken is valid Ethereum address (not zero address)\n * - shareAmount is convertible to positive number\n * - chainId is positive integer\n * - slippage (if provided) is valid basis point value\n *\n * @param yieldType Yield strategy type to validate\n * @param recipientAddress Wallet address to receive withdrawn assets\n * @param wantToken Token address to withdraw\n * @param shareAmount Amount of shares to redeem (decimal string)\n * @param chainId Blockchain network ID\n * @param slippage Optional slippage in basis points\n * @throws WithdrawError if any parameter is invalid\n *\n * @example\n * ```typescript\n * validateWithdrawParams(\n * \"PRIME\",\n * \"0x1234...\",\n * \"0xA0b86991...\",\n * \"1.5\",\n * 1,\n * 100\n * );\n * ```\n */\nexport function validateWithdrawParams(\n yieldType: string,\n recipientAddress: string,\n wantToken: string,\n shareAmount: string,\n chainId: number,\n slippage?: number\n): void {\n // Validate yieldType\n if (!yieldType || typeof yieldType !== \"string\") {\n throw new WithdrawError(\"Invalid yield type\", {\n code: \"INVALID_YIELD_TYPE\",\n });\n }\n\n // Validate recipientAddress\n if (!isValidAddress(recipientAddress)) {\n throw new WithdrawError(\"Invalid recipient address\", {\n code: \"INVALID_RECIPIENT_ADDRESS\",\n });\n }\n\n if (recipientAddress === \"0x0000000000000000000000000000000000000000\") {\n throw new WithdrawError(\"Cannot withdraw to zero address\", {\n code: \"ZERO_ADDRESS\",\n });\n }\n\n // Validate wantToken\n if (!isValidAddress(wantToken)) {\n throw new WithdrawError(\"Invalid token address\", {\n code: \"INVALID_TOKEN_ADDRESS\",\n });\n }\n\n if (wantToken === \"0x0000000000000000000000000000000000000000\") {\n throw new WithdrawError(\"Invalid token address (zero address)\", {\n code: \"INVALID_TOKEN_ADDRESS\",\n });\n }\n\n // Validate shareAmount\n if (!shareAmount || typeof shareAmount !== \"string\") {\n throw new WithdrawError(\"Share amount must be a string\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n const shareAmountNum = Number.parseFloat(shareAmount);\n if (Number.isNaN(shareAmountNum) || shareAmountNum <= 0) {\n throw new WithdrawError(\"Share amount must be greater than zero\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n // Validate chainId\n if (\n typeof chainId !== \"number\" ||\n !Number.isInteger(chainId) ||\n chainId <= 0\n ) {\n throw new WithdrawError(\"Invalid chain ID\", { code: \"INVALID_CHAIN_ID\" });\n }\n\n // Validate slippage if provided\n if (slippage !== undefined) {\n if (typeof slippage !== \"number\" || !Number.isInteger(slippage)) {\n throw new WithdrawError(\"Slippage must be an integer\", {\n code: \"INVALID_SLIPPAGE\",\n });\n }\n\n if (slippage < 0 || slippage > 10000) {\n throw new WithdrawError(\n \"Slippage must be between 0 and 10000 basis points\",\n {\n code: \"INVALID_SLIPPAGE\",\n }\n );\n }\n }\n}\n\n/**\n * Calculates the minimum acceptable asset amount after applying slippage protection\n *\n * Uses the formula: minimumAssets = shareAmount * (10000 - slippage) / 10000\n *\n * This ensures the transaction will revert if the actual output falls below\n * the minimum acceptable amount due to price movements.\n *\n * @param shareAmount Amount of shares to redeem (as bigint in smallest units)\n * @param slippage Acceptable slippage in basis points (100 = 1%, defaults to 100)\n * @returns The minimum acceptable asset amount\n *\n * @example\n * ```typescript\n * const shareAmount = 1000n;\n * const slippage = 100; // 1%\n * const minimumAssets = calculateMinimumAssets(shareAmount, slippage);\n * // Result: 990n (allows 1% slippage)\n * ```\n */\nexport function calculateMinimumAssets(\n shareAmount: bigint,\n slippage: number = 100\n): bigint {\n const basisPoints = BigInt(10000);\n const slippageAmount = BigInt(slippage);\n return (shareAmount * (basisPoints - slippageAmount)) / basisPoints;\n}\n\n/**\n * Converts share amount from decimal string to BigInt\n *\n * Handles conversion of user-supplied decimal amount to blockchain-compatible BigInt.\n * Assumes 18 decimal places (standard for most ERC20 tokens).\n *\n * @param amount Decimal string amount (e.g., \"1.5\", \"100\", \"0.001\")\n * @param decimals Number of decimal places for the token (default: 18)\n * @returns BigInt representation in smallest units\n * @throws WithdrawError if amount cannot be parsed or results in zero\n *\n * @example\n * ```typescript\n * const shareAmountBigInt = parseShareAmount(\"1.5\");\n * // Result: 1500000000000000000n\n *\n * const usdcAmount = parseShareAmount(\"100\", 6);\n * // Result: 100000000n\n * ```\n */\nexport function parseShareAmount(\n amount: string,\n decimals: number = 18\n): bigint {\n if (!amount || typeof amount !== \"string\") {\n throw new WithdrawError(\"Share amount must be a valid string\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n const numAmount = Number.parseFloat(amount);\n if (Number.isNaN(numAmount) || numAmount < 0) {\n throw new WithdrawError(\"Share amount must be a valid positive number\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n const bigIntAmount = BigInt(Math.floor(numAmount * 10 ** decimals));\n\n if (bigIntAmount === BigInt(0) && numAmount > 0) {\n throw new WithdrawError(\n \"Share amount is too small for the specified decimals\",\n {\n code: \"INVALID_SHARE_AMOUNT\",\n }\n );\n }\n\n if (bigIntAmount < BigInt(0)) {\n throw new WithdrawError(\"Share amount must be greater than zero\", {\n code: \"INVALID_SHARE_AMOUNT\",\n });\n }\n\n return bigIntAmount;\n}\n\n/**\n * Finds a vault by configuration criteria from a vault array (test helper)\n *\n * @param vaults - Array of AmplifyVault objects to search\n * @param yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @param wantToken - Token address\n * @param chainId - Blockchain network ID\n * @returns Matching vault or undefined\n */\nexport function findVaultByConfig(\n vaults: Array<{\n yieldType: string;\n chainId: number;\n vault: {\n baseTokenAddress: string;\n };\n }>,\n yieldType: string,\n wantToken: string,\n chainId: number\n) {\n const normalizedToken = wantToken.toLowerCase();\n return vaults.find((vault) => {\n const vaultToken = (vault.vault.baseTokenAddress || \"\").toLowerCase();\n return (\n vault.yieldType === yieldType &&\n vault.chainId === chainId &&\n vaultToken === normalizedToken\n );\n });\n}\n","import { type Address, parseUnits } from \"viem\";\nimport { TellerAbi } from \"../../abi/teller-abi\";\nimport { getRateInQuoteAndSharesAndWantAssetDecimals } from \"../../api/accountant\";\nimport {\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport { DEFAULT_SLIPPAGE_BPS, type YieldType } from \"../../constants/config\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { calculateAtomicPrice } from \"./utils\";\n\ninterface BulkWithdrawTxData {\n abi: typeof TellerAbi;\n address: Address;\n functionName: \"bulkWithdraw\";\n args: [\n withdrawAsset: Address,\n shareAmount: bigint,\n minimumAssets: bigint,\n to: Address\n ];\n chainId: number;\n}\n\ninterface PrepareBulkWithdrawTxDataParams {\n yieldType: YieldType;\n shareAmount: string;\n wantAssetAddress: Address;\n chainId: ChainId;\n slippage?: number;\n recipientAddress: Address;\n}\n\n/**\n * Prepares the transaction data needed to withdraw assets from a vault\n *\n * This function calculates the appropriate exchange rate with slippage protection\n * and prepares a user request for the AtomicQueue contract. It uses the new\n * AmplifyVault schema with asset decimals from the API (no on-chain calls).\n *\n * @example\n * ```typescript\n * const vaults = await fetchVaults({ chainId: 1 });\n * const wantAssets = await fetchSupportedAssets({ symbol: 'WETH' });\n * const withdrawData = await prepareBulkWithdrawTransactionData({\n * vault: vaults[0],\n * wantAsset: wantAssets[0],\n * chainId: 1,\n * recipientAddress: '0x1234...',\n * offerAmount: \"1.0\", // 1 vault share\n * deadline: Math.floor(Date.now() / 1000) + 3600, // 1 hour from now\n * slippage: 100, // 1% slippage (100 bps)\n * });\n * ```\n *\n * @param {PrepareBulkWithdrawTxDataParams} params - Parameters for the withdraw operation\n * @param {AmplifyVault} params.vault - Vault configuration from fetchVaults()\n * @param {SupportedAsset} params.wantAsset - Asset metadata from fetchSupportedAssets()\n * @param {ChainId} params.chainId - ID of the chain where the withdrawal will occur\n * @param {Address} params.recipientAddress - Ethereum address of the user making the withdrawal\n * @param {string} params.offerAmount - Amount of vault shares to withdraw as a decimal string\n * @param {number} [params.deadline] - Unix timestamp when the request expires\n * @param {number} [params.slippage] - Maximum acceptable slippage in basis points\n *\n * @returns {Promise<BulkWithdrawTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not on the correct chain, asset not supported, or contracts not configured\n */\nexport async function prepareBulkWithdrawTxData(\n params: PrepareBulkWithdrawTxDataParams\n): Promise<BulkWithdrawTxData> {\n const {\n yieldType,\n wantAssetAddress,\n shareAmount,\n chainId,\n slippage = DEFAULT_SLIPPAGE_BPS,\n recipientAddress,\n } = params;\n try {\n const normalizedChainId = toChainId(chainId);\n\n const vault = await findVaultByConfig({\n assetAddress: wantAssetAddress,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n\n // Validation: Ensure vault is on the correct chain\n if (vault && vault.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${vault.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareBulkWithdrawTransactionData\" }\n );\n }\n\n // Validation: Ensure required contract addresses are present\n if (!vault || !vault.vault.boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${vault?.vault.boringVaultAddress}`,\n { endpoint: \"prepareBulkWithdrawTransactionData\" }\n );\n }\n const boringVaultAddress = vault.vault.boringVaultAddress;\n const accountantAddress = vault.vault.accountantAddress;\n\n // Get vault shares asset decimals for parsing offer amount\n const wantAsset = await getAssetsFromCache({\n address: wantAssetAddress,\n });\n\n if (wantAsset.length === 0) {\n throw new APIError(\n `Vault shares token not found in supported assets: ${boringVaultAddress}`,\n { endpoint: \"prepareBulkWithdrawTransactionData\" }\n );\n }\n\n // Get exchange rate from accountant\n const [\n wantAssetDecimalsResult,\n sharesAssetDecimalsResult,\n rateInQuoteResult,\n ] = await getRateInQuoteAndSharesAndWantAssetDecimals({\n sharesAssetAddress: boringVaultAddress,\n wantAssetAddress: wantAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n\n // Validate rate results\n if (\n rateInQuoteResult.status === \"failure\" ||\n wantAssetDecimalsResult.status === \"failure\" ||\n sharesAssetDecimalsResult.status === \"failure\"\n ) {\n throw new APIError(\n `Failed to get exchange rate: ${\n rateInQuoteResult?.error?.message ||\n wantAssetDecimalsResult?.error?.message ||\n sharesAssetDecimalsResult?.error?.message\n }`,\n {\n endpoint: \"prepareBulkWithdrawTransactionData\",\n cause:\n rateInQuoteResult?.error ||\n wantAssetDecimalsResult?.error ||\n sharesAssetDecimalsResult?.error,\n }\n );\n }\n\n // Parse offer amount using vault shares decimals from API\n const offerAmountAsBigInt = parseUnits(\n shareAmount,\n sharesAssetDecimalsResult.result\n );\n\n // Calculate atomic price using want asset decimals from API\n const atomicPrice = calculateAtomicPrice(\n rateInQuoteResult.result, // rateInQuote bigint\n wantAssetDecimalsResult.result, // Want asset decimals from API\n slippage\n );\n\n const minimumAssets =\n (atomicPrice * offerAmountAsBigInt) /\n BigInt(10 ** sharesAssetDecimalsResult.result);\n\n return {\n abi: TellerAbi,\n address: vault.vault.tellerAddress as Address,\n functionName: \"bulkWithdraw\",\n args: [\n wantAssetAddress,\n offerAmountAsBigInt,\n minimumAssets,\n recipientAddress,\n ],\n chainId: normalizedChainId,\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare withdrawal transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareBulkWithdrawTransactionData\",\n cause: error,\n }\n );\n }\n}\n\nexport type { BulkWithdrawTxData, PrepareBulkWithdrawTxDataParams };\n","export const AtomicQueueAbi = [\n {\n type: \"function\",\n name: \"getUserAtomicRequest\",\n inputs: [\n { name: \"user\", type: \"address\", internalType: \"address\" },\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"want\", type: \"address\", internalType: \"contract ERC20\" },\n ],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n internalType: \"struct AtomicQueue.AtomicRequest\",\n components: [\n { name: \"deadline\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"atomicPrice\", type: \"uint88\", internalType: \"uint88\" },\n { name: \"offerAmount\", type: \"uint96\", internalType: \"uint96\" },\n { name: \"inSolve\", type: \"bool\", internalType: \"bool\" },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAtomicRequestValid\",\n inputs: [\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"user\", type: \"address\", internalType: \"address\" },\n {\n name: \"userRequest\",\n type: \"tuple\",\n internalType: \"struct AtomicQueue.AtomicRequest\",\n components: [\n { name: \"deadline\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"atomicPrice\", type: \"uint88\", internalType: \"uint88\" },\n { name: \"offerAmount\", type: \"uint96\", internalType: \"uint96\" },\n { name: \"inSolve\", type: \"bool\", internalType: \"bool\" },\n ],\n },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"solve\",\n inputs: [\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"want\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"users\", type: \"address[]\", internalType: \"address[]\" },\n { name: \"runData\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"solver\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"updateAtomicRequest\",\n inputs: [\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"want\", type: \"address\", internalType: \"contract ERC20\" },\n {\n name: \"userRequest\",\n type: \"tuple\",\n internalType: \"struct AtomicQueue.AtomicRequest\",\n components: [\n { name: \"deadline\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"atomicPrice\", type: \"uint88\", internalType: \"uint88\" },\n { name: \"offerAmount\", type: \"uint96\", internalType: \"uint96\" },\n { name: \"inSolve\", type: \"bool\", internalType: \"bool\" },\n ],\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"userAtomicRequest\",\n inputs: [\n { name: \"\", type: \"address\", internalType: \"address\" },\n { name: \"\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"\", type: \"address\", internalType: \"contract ERC20\" },\n ],\n outputs: [\n { name: \"deadline\", type: \"uint64\", internalType: \"uint64\" },\n { name: \"atomicPrice\", type: \"uint88\", internalType: \"uint88\" },\n { name: \"offerAmount\", type: \"uint96\", internalType: \"uint96\" },\n { name: \"inSolve\", type: \"bool\", internalType: \"bool\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"viewSolveMetaData\",\n inputs: [\n { name: \"offer\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"want\", type: \"address\", internalType: \"contract ERC20\" },\n { name: \"users\", type: \"address[]\", internalType: \"address[]\" },\n ],\n outputs: [\n {\n name: \"metaData\",\n type: \"tuple[]\",\n internalType: \"struct AtomicQueue.SolveMetaData[]\",\n components: [\n { name: \"user\", type: \"address\", internalType: \"address\" },\n { name: \"flags\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"assetsToOffer\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"assetsForWant\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n { name: \"totalAssetsForWant\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"totalAssetsToOffer\", type: \"uint256\", internalType: \"uint256\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"event\",\n name: \"AtomicRequestFulfilled\",\n inputs: [\n {\n name: \"user\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"offerToken\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"wantToken\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"offerAmountSpent\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"wantAmountReceived\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"timestamp\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n ],\n anonymous: false,\n },\n {\n type: \"event\",\n name: \"AtomicRequestUpdated\",\n inputs: [\n {\n name: \"user\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"offerToken\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"wantToken\",\n type: \"address\",\n indexed: false,\n internalType: \"address\",\n },\n {\n name: \"amount\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"deadline\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"minPrice\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n {\n name: \"timestamp\",\n type: \"uint256\",\n indexed: false,\n internalType: \"uint256\",\n },\n ],\n anonymous: false,\n },\n {\n type: \"error\",\n name: \"AtomicQueue__RequestDeadlineExceeded\",\n inputs: [{ name: \"user\", type: \"address\", internalType: \"address\" }],\n },\n {\n type: \"error\",\n name: \"AtomicQueue__UserNotInSolve\",\n inputs: [{ name: \"user\", type: \"address\", internalType: \"address\" }],\n },\n {\n type: \"error\",\n name: \"AtomicQueue__UserRepeated\",\n inputs: [{ name: \"user\", type: \"address\", internalType: \"address\" }],\n },\n {\n type: \"error\",\n name: \"AtomicQueue__ZeroOfferAmount\",\n inputs: [{ name: \"user\", type: \"address\", internalType: \"address\" }],\n },\n] as const;\n","/**\n * @file Withdraw functionality for Paxos Labs vaults\n * @module vaults/withdraw\n */\n\nimport { type Address, parseUnits } from \"viem\";\nimport { AtomicQueueAbi } from \"../../abi/atomic-queue-abi\";\nimport { getRateInQuoteAndSharesAndWantAssetDecimals } from \"../../api/accountant\";\nimport { findVaultByConfig } from \"../../api/amplify-sdk-client\";\nimport { type ChainId, toChainId } from \"../../api/vault-config\";\nimport {\n ATOMIC_QUEUE_CONTRACT_ADDRESS,\n DEFAULT_DEADLINE,\n} from \"../../constants\";\nimport { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { calculateAtomicPrice, prepareUserRequest } from \"./utils\";\n\n/**\n * Arguments for an atomic request to the AtomicQueue contract\n * @typedef {Object} AtomicRequestArgs\n * @property {Address} offer - Address of the token being offered (shares token address)\n * @property {Address} want - Address of the token being requested (want token address)\n * @property {UserRequest} userRequest - User request details\n */\nexport type AtomicRequestArgs = {\n offer: Address; // sharesTokenAddress\n want: Address; // wantTokenAddress\n userRequest: UserRequest; // userRequest\n};\n\n/**\n * Options for an atomic request\n * @typedef {Object} AtomicRequestOptions\n * @property {Address} atomicQueueContractAddress - Address of the AtomicQueue contract\n * @property {number} chainId - ID of the destination chain\n */\nexport type AtomicRequestOptions = {\n atomicQueueContractAddress: Address; // atomicQueueContractAddress\n chainId: ChainId; // destinationChainId\n};\n\n/**\n * User request details for an atomic swap\n * @typedef {Object} UserRequest\n * @property {number} deadline - Unix timestamp when the request expires\n * @property {bigint} atomicPrice - Rate in quote with fee applied\n * @property {bigint} offerAmount - Amount of shares token to redeem\n * @property {boolean} inSolve - Whether the request is in solve mode (always false for new requests)\n */\nexport type UserRequest = {\n deadline: bigint; // deadline\n atomicPrice: bigint; // rateInQuoteWithFee\n offerAmount: bigint; // redeemAmount\n inSolve: boolean; // false\n};\n\n/**\n * Parameters for preparing a withdrawal transaction from a vault (NEW AmplifyVault schema)\n * @interface PrepareWithdrawTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @property {Address} wantAssetAddress - Address of the want token\n * @property {ChainId} chainId - ID of the chain where the withdrawal will occur\n * @property {string} offerAmount - Amount of vault shares to withdraw as a decimal string\n * @property {number} [deadline] - Unix timestamp when the request expires (optional)\n * @property {number} [slippage] - Maximum acceptable slippage in basis points (optional, default: 100 for 1%)\n *\n * **Slippage Protection**:\n * The slippage parameter protects users from unfavorable price movements during the withdrawal.\n * It defines the maximum acceptable loss as a percentage of the initial share amount.\n *\n * - Default: 100 basis points (1% slippage tolerance)\n * - Range: 0-10000 basis points (0-100%)\n * - Formula: minimumAssets = shareAmount * (10000 - slippage) / 10000\n *\n * @example\n * ```typescript\n * // 1% slippage (default) - allows price to move 1% unfavorably\n * { slippage: 100 }\n *\n * // 0.5% slippage - conservative, tighter protection\n * { slippage: 50 }\n *\n * // 5% slippage - aggressive, more lenient\n * { slippage: 500 }\n *\n * // No slippage tolerance - transaction reverts if price changes at all\n * { slippage: 0 }\n * ```\n */\ninterface PrepareWithdrawTxDataParams {\n yieldType: YieldType;\n wantAssetAddress: Address;\n chainId: ChainId;\n offerAmount: string;\n deadline?: number;\n slippage?: number;\n}\n\n/**\n * Result object containing transaction data for a withdrawal operation\n * @interface WithdrawTxData\n * @property {typeof AtomicQueueAbi} abi - ABI for the AtomicQueue contract\n * @property {Address} address - Address of the AtomicQueue contract\n * @property {'updateAtomicRequest'} functionName - Name of the function to call\n * @property {[Address, Address, UserRequest]} args - Arguments for the updateAtomicRequest function:\n * [offer (vault shares address), want (want asset address), userRequest]\n * @property {number} chainId - ID of the chain where the transaction should be executed\n */\ninterface WithdrawTxData {\n abi: typeof AtomicQueueAbi;\n address: Address;\n functionName: \"updateAtomicRequest\";\n args: [offer: Address, want: Address, userRequest: UserRequest];\n chainId: number;\n}\n\n/**\n * Prepares the transaction data needed to withdraw assets from a vault\n *\n * This function calculates the appropriate exchange rate with slippage protection\n * and prepares a user request for the AtomicQueue contract. It uses the new\n * AmplifyVault schema with asset decimals from the API (no on-chain calls).\n *\n * @example\n * ```typescript\n * const withdrawData = await prepareWithdrawTransactionData({\n * yieldType: 'PRIME',\n * wantAssetAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * chainId: 1,\n * offerAmount: \"1.0\", // 1 vault share\n * deadline: Math.floor(Date.now() / 1000) + 3600, // Optional: Defaults to 3 days from now\n * slippage: 100, // Optional: Defaults to 0.5% slippage (50 bps)\n * });\n * ```\n *\n * @param {PrepareWithdrawTxDataParams} params - Parameters for the withdraw operation\n * @param {YieldType} params.yieldType - Yield strategy type (PRIME, TBILL, or LENDING)\n * @param {Address} params.wantAssetAddress - Address of the want token\n * @param {ChainId} params.chainId - ID of the chain where the withdrawal will occur\n * @param {Address} params.recipientAddress - Ethereum address of the user making the withdrawal\n * @param {string} params.offerAmount - Amount of vault shares to withdraw as a decimal string\n * @param {number} [params.deadline] - Unix timestamp when the request expires\n * @param {number} [params.slippage] - Maximum acceptable slippage in basis points\n *\n * @returns {Promise<WithdrawTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not on the correct chain, asset not supported, or contracts not configured\n */\nconst prepareWithdrawTxData = async ({\n yieldType,\n wantAssetAddress,\n chainId,\n offerAmount,\n deadline = DEFAULT_DEADLINE,\n slippage = DEFAULT_SLIPPAGE_BPS,\n}: PrepareWithdrawTxDataParams): Promise<WithdrawTxData> => {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n assetAddress: wantAssetAddress,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n\n // Validation: Ensure vault is on the correct chain\n if (config && config.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${config.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareWithdrawTransactionData\" }\n );\n }\n\n // Validation: Ensure required contract addresses are present\n if (!config || !config.vault.boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config?.id}`,\n { endpoint: \"prepareWithdrawTransactionData\" }\n );\n }\n\n if (!config.vault.accountantAddress) {\n throw new APIError(\n `Accountant contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareWithdrawTransactionData\" }\n );\n }\n\n const boringVaultAddress = config.vault.boringVaultAddress;\n const accountantAddress = config.vault.accountantAddress;\n\n // Get exchange rate from accountant\n const [\n wantAssetDecimalsResult,\n sharesAssetDecimalsResult,\n rateInQuoteResult,\n ] = await getRateInQuoteAndSharesAndWantAssetDecimals({\n sharesAssetAddress: boringVaultAddress,\n wantAssetAddress: wantAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n\n // Validate rate results\n if (\n rateInQuoteResult?.status === \"failure\" ||\n wantAssetDecimalsResult?.status === \"failure\" ||\n sharesAssetDecimalsResult?.status === \"failure\"\n ) {\n throw new APIError(\n `Failed to get exchange rate: ${\n rateInQuoteResult?.error?.message ||\n wantAssetDecimalsResult?.error?.message ||\n sharesAssetDecimalsResult?.error?.message\n }`,\n {\n endpoint: \"prepareWithdrawTransactionData\",\n cause:\n rateInQuoteResult?.error ||\n wantAssetDecimalsResult?.error ||\n sharesAssetDecimalsResult?.error,\n }\n );\n }\n\n // Calculate atomic price using want asset decimals from API\n const atomicPrice = calculateAtomicPrice(\n rateInQuoteResult.result, // rateInQuote bigint\n wantAssetDecimalsResult.result, // Want asset decimals from API\n slippage\n );\n\n // Parse offer amount using vault shares decimals from API\n const formattedOfferAmount = parseUnits(\n offerAmount,\n sharesAssetDecimalsResult.result\n );\n\n const userRequest = prepareUserRequest(\n formattedOfferAmount,\n atomicPrice,\n deadline\n );\n\n return {\n abi: AtomicQueueAbi,\n address: ATOMIC_QUEUE_CONTRACT_ADDRESS,\n functionName: \"updateAtomicRequest\",\n args: [boringVaultAddress, wantAssetAddress, userRequest],\n chainId: normalizedChainId,\n };\n } catch (error) {\n // Re-throw APIError as-is\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to prepare withdrawal transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareWithdrawTransactionData\",\n cause: error,\n }\n );\n }\n};\n\nexport { prepareWithdrawTxData };\n\nexport type { PrepareWithdrawTxDataParams, WithdrawTxData };\n"]}