@paxoslabs/amplify-sdk 0.4.1 → 0.4.2

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 (37) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +8 -0
  3. package/dist/{chunk-QKU5APOV.js → chunk-2YPKHXFJ.js} +120 -120
  4. package/dist/{chunk-QKU5APOV.js.map → chunk-2YPKHXFJ.js.map} +1 -1
  5. package/dist/{chunk-ZPIVBZLP.js → chunk-BQG3XKTU.js} +404 -371
  6. package/dist/chunk-BQG3XKTU.js.map +1 -0
  7. package/dist/{chunk-5FVJVJXC.mjs → chunk-GMMBJB4B.mjs} +7 -7
  8. package/dist/chunk-GMMBJB4B.mjs.map +1 -0
  9. package/dist/{chunk-VDNXXONH.js → chunk-OZJNKGW6.js} +59 -59
  10. package/dist/chunk-OZJNKGW6.js.map +1 -0
  11. package/dist/{chunk-SQ3YW6UK.mjs → chunk-RW7PZETN.mjs} +405 -371
  12. package/dist/chunk-RW7PZETN.mjs.map +1 -0
  13. package/dist/{chunk-PLWWBYSM.mjs → chunk-TPU2HZAX.mjs} +4 -4
  14. package/dist/{chunk-PLWWBYSM.mjs.map → chunk-TPU2HZAX.mjs.map} +1 -1
  15. package/dist/{chunk-Y55F4I3A.mjs → chunk-VZED4E3L.mjs} +5 -27
  16. package/dist/chunk-VZED4E3L.mjs.map +1 -0
  17. package/dist/{chunk-YTCO5BHT.js → chunk-WZXCJAKM.js} +12 -35
  18. package/dist/chunk-WZXCJAKM.js.map +1 -0
  19. package/dist/core.js +16 -16
  20. package/dist/core.mjs +4 -4
  21. package/dist/display.js +9 -9
  22. package/dist/display.mjs +3 -3
  23. package/dist/index.d.mts +28 -28
  24. package/dist/index.d.ts +28 -28
  25. package/dist/index.js +50 -58
  26. package/dist/index.mjs +4 -4
  27. package/dist/utils.js +7 -7
  28. package/dist/utils.mjs +2 -2
  29. package/dist/vaults.js +24 -24
  30. package/dist/vaults.mjs +3 -3
  31. package/package.json +1 -1
  32. package/dist/chunk-5FVJVJXC.mjs.map +0 -1
  33. package/dist/chunk-SQ3YW6UK.mjs.map +0 -1
  34. package/dist/chunk-VDNXXONH.js.map +0 -1
  35. package/dist/chunk-Y55F4I3A.mjs.map +0 -1
  36. package/dist/chunk-YTCO5BHT.js.map +0 -1
  37. package/dist/chunk-ZPIVBZLP.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/approvals.ts","../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/utils/wallet.ts","../src/vaults/deposit/index.ts","../src/vaults/withdraw/approve-withdraw.ts","../src/vaults/withdraw/cancel-withdraw.ts","../src/vaults/withdraw/standard-withdraw.ts","../src/vaults/withdraw/index.ts"],"names":["toChainId","findVaultByConfig","APIError","getTokenPermitInfoWithAllowance","formatUnits","getErc20AllowanceWithDecimals","getAssetsFromCache","parseUnits","DEFAULT_APPROVAL_AMOUNT","erc20Abi","DEFAULT_SLIPPAGE_BPS","WAD","getRateInQuoteWithAssetDecimals","stringToHex","getClient","erc2612Abi","getErc20Decimals","hexToSignature","txData","tokenInfo","BoringVaultAbi","WithdrawQueueAbi"],"mappings":";;;;;;;;AAUO,IAAM,yBAAyB,OAAO;AAAA,EAC3C,SAAA;AAAA,EACA,OAAA;AAAA,EACA,mBAAA;AAAA,EACA;AACF,CAAA,KAKM;AACJ,EAAA,IAAI;AACF,IAAA,MAAM,iBAAA,GAAoBA,2BAAU,OAAO,CAAA;AAC3C,IAAA,MAAM,MAAA,GAAS,MAAMC,kCAAA,CAAkB;AAAA,MACrC,SAAA;AAAA,MACA,OAAA,EAAS,iBAAA;AAAA,MACT,YAAA,EAAc;AAAA,KACf,CAAA;AAED,IAAA,IAAI,CAAC,MAAA,EAAQ;AACX,MAAA,MAAM,IAAIC,yBAAA;AAAA,QACR,CAAA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AAAA,MACL,QAAQ,kBAAA,CAAmB,QAAA;AAAA,MAC3B;AAAA,KACF;AAAA,EACF,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,iBAAiBL,yBAAA,EAAU;AAC7B,MAAA,MAAM,KAAA;AAAA,IACR;AAEA,IAAA,MAAM,IAAIA,yBAAA;AAAA,MACR,+CACE,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":"chunk-QKU5APOV.js","sourcesContent":["import type { Address } from \"viem\";\nimport { formatUnits } from \"viem\";\nimport {\n getErc20AllowanceWithDecimals,\n getTokenPermitInfoWithAllowance,\n} from \"../api/erc20\";\nimport { findVaultByConfig } from \"../client/amplify-sdk-client\";\nimport { APIError, type YieldType } from \"../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"./chain-utils\";\n\nexport const isDepositSpendApproved = async ({\n yieldType,\n chainId,\n depositAssetAddress,\n recipientAddress,\n}: {\n yieldType: YieldType;\n chainId: ChainId;\n depositAssetAddress: Address;\n recipientAddress: Address;\n}) => {\n try {\n const normalizedChainId = toChainId(chainId);\n const config = await findVaultByConfig({\n yieldType,\n chainId: normalizedChainId,\n assetAddress: depositAssetAddress,\n });\n\n if (!config) {\n throw new APIError(\n `Vault not found for ${yieldType} on chain ${normalizedChainId}`,\n {\n endpoint: \"isDepositSpendApproved\",\n }\n );\n }\n\n const communityCodeDepositorAddress =\n config.vault.communityCodeDepositorAddress;\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `Community code depositor contract address not configured for vault ${config.id}`,\n {\n endpoint: \"isDepositSpendApproved\",\n }\n );\n }\n\n const {\n decimals,\n allowance,\n supportsPermit,\n nonce,\n domainSeparator,\n tokenName,\n tokenVersion,\n } = await getTokenPermitInfoWithAllowance({\n chainId: normalizedChainId,\n tokenAddress: depositAssetAddress,\n owner: recipientAddress,\n spender: communityCodeDepositorAddress,\n });\n\n return {\n isApproved: allowance > 0n,\n allowance: formatUnits(allowance, decimals),\n allowanceAsBigInt: allowance.toString(),\n decimals,\n supportsPermit,\n nonce,\n domainSeparator,\n tokenName,\n tokenVersion,\n error: null,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to check deposit approval: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"isDepositSpendApproved\",\n cause: error,\n }\n );\n }\n};\n\nexport const isWithdrawalSpendApproved = async ({\n yieldType,\n chainId,\n wantAssetAddress,\n recipientAddress,\n}: {\n yieldType: YieldType;\n chainId: ChainId;\n wantAssetAddress: Address;\n recipientAddress: Address;\n}) => {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n yieldType,\n chainId: normalizedChainId,\n assetAddress: wantAssetAddress,\n });\n\n if (!config) {\n throw new APIError(\n `Vault not found for ${yieldType} on chain ${normalizedChainId}`,\n {\n endpoint: \"isWithdrawalSpendApproved\",\n }\n );\n }\n\n const boringVaultAddress = config.vault.boringVaultAddress;\n\n if (!boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config.id}`,\n {\n endpoint: \"isWithdrawalSpendApproved\",\n }\n );\n }\n\n const withdrawQueueAddress = config.vault.withdrawQueueAddress;\n\n if (!withdrawQueueAddress) {\n throw new APIError(\n `WithdrawQueue contract address not configured for vault ${config.id}`,\n {\n endpoint: \"isWithdrawalSpendApproved\",\n }\n );\n }\n\n const [allowance, decimals] = await getErc20AllowanceWithDecimals({\n chainId: normalizedChainId,\n tokenAddress: boringVaultAddress,\n recipientAddress: recipientAddress,\n spenderAddress: withdrawQueueAddress,\n });\n\n if (allowance.status === \"failure\" || decimals.status === \"failure\") {\n return {\n isApproved: false,\n allowance: \"0\",\n allowanceAsBigInt: \"0\",\n decimals: \"0\",\n error: allowance.error || decimals.error,\n };\n }\n\n return {\n isApproved: allowance.result > 0n,\n allowance: formatUnits(allowance.result, decimals.result),\n allowanceAsBigInt: allowance.result.toString(),\n decimals: decimals.result,\n error: null,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to check withdrawal approval: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { endpoint: \"isWithdrawalSpendApproved\", cause: error }\n );\n }\n};\n","/**\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 \"../../client/amplify-sdk-client\";\nimport { DEFAULT_APPROVAL_AMOUNT } from \"../../constants\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\n\n/**\n * Parameters required for preparing an approval transaction\n * @interface PrepareApproveDepositTokenTxParams\n * @property {YieldType} yieldType - Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\")\n * @property {Address} depositAsset - Token contract address to approve\n * @property {string} [approvalAmount] - Optional amount to approve (defaults to maximum approval)\n * @property {ChainId} chainId - ID of the chain where the approval will occur\n */\ninterface PrepareApproveDepositTokenTxParams {\n yieldType: YieldType;\n depositAsset: 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 (CommunityCodeDepositor 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 * CommunityCodeDepositor contract to spend the user's deposit tokens.\n *\n * @example\n * ```typescript\n * const approveData = await prepareApproveDepositTokenTxData({\n * yieldType: \"CORE\",\n * depositAsset: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\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 or vault not found\n */\nexport async function prepareApproveDepositTokenTxData({\n yieldType,\n depositAsset,\n approvalAmount,\n chainId,\n}: PrepareApproveDepositTokenTxParams): Promise<ApproveDepositTokenTxData> {\n const normalizedChainId = toChainId(chainId);\n\n try {\n const config = await findVaultByConfig({\n assetAddress: depositAsset,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n if (!config) {\n throw new APIError(\n `No vault found for token address ${depositAsset} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n const communityCodeDepositorAddress =\n config.vault.communityCodeDepositorAddress;\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `Community Code Depositor 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: depositAsset });\n if (assets.length === 0) {\n throw new APIError(\n `Asset metadata not found for token ${depositAsset} on chain ${normalizedChainId}`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n\n const verifiedAsset = assets.find(\n (asset) =>\n asset.address.toLowerCase() === depositAsset.toLowerCase() &&\n asset.chains.includes(normalizedChainId)\n );\n\n // verify asset is verified on the desired chain.\n if (!verifiedAsset) {\n throw new APIError(\n `Asset ${depositAsset} not verified on chain ${normalizedChainId}`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n const decimals = verifiedAsset.decimals;\n\n const amount = approvalAmount\n ? parseUnits(approvalAmount, decimals)\n : DEFAULT_APPROVAL_AMOUNT;\n return {\n abi: erc20Abi,\n address: depositAsset,\n functionName: \"approve\",\n args: [communityCodeDepositorAddress, 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 findVaultByConfig,\n getAssetsFromCache,\n} from \"../../client/amplify-sdk-client\";\nimport { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport type {\n YieldType\n} from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\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, to, 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, to, depositAsset, and chainId for automatic vault resolution\n * @interface PrepareDepositTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\")\n * @property {Address} to - Ethereum address of the recipient. Must be the same as the address used to sign the deposit transaction.\n * @property {Address} depositAsset - 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} [distributorCode] - Optional (default is empty string): Distributor code for fee attribution\n */\ninterface PrepareDepositTxDataParams {\n yieldType: YieldType;\n to: Address;\n depositAsset: Address;\n depositAmount: string;\n chainId: ChainId;\n slippage?: number;\n distributorCode?: 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 prepareDepositTxData({\n * yieldType: 'CORE',\n * to: '0x1234...',\n * depositAsset: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * depositAmount: \"1.0\",\n * chainId: 1,\n * slippage: 100, // 1% slippage (100 bps)\n * distributorCode: 'my-distributor-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 depositAsset,\n depositAmount,\n chainId,\n slippage = DEFAULT_SLIPPAGE_BPS,\n to,\n distributorCode,\n } = params;\n\n try {\n const normalizedChainId = toChainId(chainId);\n\n const vault = await findVaultByConfig({\n assetAddress: depositAsset,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n\n\n // Check if vault was found\n if (!vault) {\n throw new APIError(\n `No vault found for token address ${depositAsset} 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 asset\n // let asset: SupportedAsset | null = null;\n const assets = await getAssetsFromCache({ address: depositAsset });\n\n // Find the asset for the correct chain\n const asset = assets.find((a) => a.chains.includes(normalizedChainId)) || assets.find((a) => a.address.toLowerCase() === depositAsset.toLowerCase());\n\n\n if (!asset) {\n throw new APIError(\n `Asset metadata not found for token ${depositAsset} on chain ${normalizedChainId}`,\n {\n endpoint: \"prepareDepositTransactionData\",\n }\n );\n }\n\n // Verify transaction data includes correct vault contract addresses\n const communityCodeDepositorAddress =\n vault.vault.communityCodeDepositorAddress;\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `Community Code Depositor contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositTransactionData\" }\n );\n }\n\n const accountantAddress = vault.vault.accountantAddress;\n\n if (!accountantAddress) {\n throw new APIError(\n `Accountant contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositTransactionData\" }\n );\n }\n const depositAssetAddress = asset.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: ${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: ${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 // Calculate minimumMint using calculateMinimumMint utility (asset is vault base token)\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 to,\n stringToHex(distributorCode || \"\"),\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: ${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 { getErc20Decimals } from \"../../api/erc20\";\nimport {\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../client/amplify-sdk-client\";\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 { type ChainId, toChainId } from \"../../utils/chain-utils\";\nimport { calculateMinimumMint } from \"./utils\";\n\n/**\n * Strict EIP-712 domain separator conforming to the EIP-712 TypedData JSON schema\n * Compatible with viem's TypedDataDomain and standard EIP-712 signing libraries\n *\n * This interface matches viem/abitype's TypedDataDomain for seamless integration\n * with viem's signTypedData() and wagmi's signTypedDataAsync().\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 (hex string)\n */\nexport interface EIP712Domain {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: Address;\n salt?: Hex;\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} as const;\n\n/**\n * EIP-712 domain type definition for raw JSON-RPC calls\n * Required by eth_signTypedData_v4 but auto-added by viem/wagmi\n */\nconst EIP712_DOMAIN_TYPE = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\n/**\n * Converts PermitSignatureData to the format required by eth_signTypedData_v4\n *\n * Use this when calling eth_signTypedData_v4 directly via a provider (e.g., Privy\n * embedded wallets). For viem/wagmi, use the PermitSignatureData directly.\n *\n * Key differences from viem/wagmi format:\n * - Includes EIP712Domain in the types object (viem auto-adds this)\n * - Converts bigint values to strings for JSON serialization\n *\n * @param permitData - Permit data from prepareDepositPermitSignature()\n * @returns JSON string ready for eth_signTypedData_v4 params\n *\n * @example\n * ```typescript\n * // With Privy embedded wallet\n * const permitData = await prepareDepositPermitSignature({...});\n * const provider = await wallet.getEthereumProvider();\n * const signature = await provider.request({\n * method: 'eth_signTypedData_v4',\n * params: [wallet.address, toEthSignTypedDataV4(permitData)],\n * });\n * ```\n */\nexport function toEthSignTypedDataV4(permitData: PermitSignatureData): string {\n return JSON.stringify({\n domain: permitData.domain,\n types: {\n EIP712Domain: EIP712_DOMAIN_TYPE,\n ...permitData.types,\n },\n primaryType: permitData.primaryType,\n message: {\n owner: permitData.message.owner,\n spender: permitData.message.spender,\n value: permitData.message.value.toString(),\n nonce: permitData.message.nonce.toString(),\n deadline: permitData.message.deadline.toString(),\n },\n });\n}\n\n/**\n * T009: Complete EIP-712 typed data for permit signature\n * Returned by prepareDepositPermitSignature() ready for wallet signing\n *\n * Compatible with viem's signTypedData(), wagmi's signTypedDataAsync(),\n * and Privy's signTypedData(). Pass this object directly to the signing function.\n *\n * @property domain - EIP-712 domain separator with numeric chainId\n * @property types - EIP-2612 Permit type structure\n * @property message - Permit message fields with uint256 values as decimal strings\n * @property primaryType - Always \"Permit\" for EIP-2612\n *\n * @remarks\n * The message uses decimal string representations for uint256 values to ensure:\n * 1. JSON serialization compatibility (required for Privy embedded wallets)\n * 2. Compatibility with viem, wagmi, and Privy signing functions\n * 3. Compliance with EIP-712 JSON schema specification\n *\n * @example\n * ```typescript\n * // With wagmi\n * const signature = await signTypedDataAsync(permitData);\n *\n * // With viem\n * const signature = await walletClient.signTypedData(permitData);\n *\n * // With Privy\n * const signature = await wallet.signTypedData(permitData);\n * ```\n */\nexport type PermitSignatureData = Awaited<\n ReturnType<typeof prepareDepositPermitSignature>\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 depositAsset - Token contract address to deposit\n * @property depositAmount - Deposit amount as decimal string\n * @property to - 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 depositAsset: Address;\n depositAmount: string;\n to: 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 type UnencodedDepositWithPermitData = Awaited<\n ReturnType<typeof prepareDepositWithPermitTxData>\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: 'CORE',\n * depositAsset: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * depositAmount: '1000.0',\n * to: userAddress,\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) {\n const {\n yieldType,\n depositAsset,\n depositAmount,\n to,\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: depositAsset,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositAsset} 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 ${depositAsset} 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: depositAsset,\n abi: erc2612Abi,\n functionName: \"name\",\n },\n {\n address: depositAsset,\n abi: erc2612Abi,\n functionName: \"version\",\n },\n {\n address: depositAsset,\n abi: erc2612Abi,\n functionName: \"nonces\",\n args: [to],\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 ${depositAsset}`, {\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 ${depositAsset} 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 on-chain\n let resolvedDecimals: number;\n if (prefetchedDecimals !== undefined) {\n resolvedDecimals = prefetchedDecimals;\n } else {\n resolvedDecimals = await getErc20Decimals({\n tokenAddress: depositAsset,\n chainId: normalizedChainId,\n });\n }\n const value = parseUnits(depositAmount, resolvedDecimals);\n\n // T024: Build EIP-712 domain with required fields for permit signing\n const domain = {\n name: resolvedTokenName,\n version: resolvedTokenVersion,\n chainId: normalizedChainId,\n verifyingContract: depositAsset,\n } satisfies EIP712Domain;\n\n // T025: Build permit message with uint256 values as decimal strings\n // String representation ensures JSON serialization compatibility for\n // Privy embedded wallets while remaining compatible with viem/wagmi\n const message = {\n owner: to,\n spender: communityCodeDepositorAddress,\n value: value,\n nonce: resolvedNonce,\n deadline: permitDeadline,\n };\n\n // T026: Return PermitSignatureData\n return {\n account: to,\n domain,\n types: PERMIT_TYPES,\n primaryType: \"Permit\" as const,\n message,\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 prepareDepositWithPermitTxData()\n * Now accepts raw signature and deadline for complete transaction encoding\n *\n * @example\n * ```typescript\n * const permitData = await prepareDepositPermitSignature({ ... });\n * const signature = await signTypedData(permitData);\n *\n * const params: PrepareDepositWithPermitTxDataParams = {\n * yieldType: \"CORE\",\n * to: \"0x1234567890123456789012345678901234567890\",\n * depositAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * depositAmount: \"100.25\",\n * chainId: 1,\n * signature,\n * deadline: permitData.message.deadline,\n * slippage: 100, // 1%\n * distributorCode: \"my-distributor-code\",\n * };\n * ```\n */\nexport interface PrepareDepositWithPermitTxDataParams {\n yieldType: YieldType;\n to: Address;\n depositAsset: Address;\n depositAmount: string;\n chainId: number | ChainId;\n signature: Hex;\n deadline: bigint;\n slippage?: number;\n distributorCode?: 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 params - Deposit parameters including signature and deadline\n * @returns Encoded transaction data ready for submission\n * @throws {APIError} If vault not found, invalid signature, or parameter validation fails\n *\n * @example\n * ```typescript\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) {\n const {\n yieldType,\n depositAsset,\n depositAmount,\n chainId,\n signature,\n deadline,\n slippage = DEFAULT_SLIPPAGE_BPS,\n to,\n distributorCode,\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: depositAsset,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositAsset} 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 ${depositAsset} 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 asset metadata using getAssetsFromCache\n // Use cache-based lookup which properly filters by address\n let asset: SupportedAsset | null = null;\n const assets = await getAssetsFromCache({ address: depositAsset });\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 ${depositAsset} 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 || depositAsset\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 // Use the deposit asset address that was passed in (matches vault.baseTokenAddress)\n const depositAssetAddress = depositAsset;\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 rateAndDecimalResults = await getRateInQuoteWithAssetDecimals({\n assetAddress: depositAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n const [depositAssetDecimalsResult, rateInQuoteResult] = rateAndDecimalResults;\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 // Use on-chain decimals from multicall (not cache placeholder)\n const onChainDecimals =\n depositAssetDecimalsResult.result as number;\n const depositAmountAsBigInt = parseUnits(\n depositAmount,\n onChainDecimals\n );\n\n // T051: Calculate minimumMint using calculateMinimumMint utility (asset is vault base token)\n const minimumMint = calculateMinimumMint(\n depositAmountAsBigInt,\n rateInQuoteResult.result,\n onChainDecimals,\n slippage\n );\n\n return {\n data: {\n abi: CommunityCodeDepositorAbi,\n functionName: \"depositWithPermit\",\n args: [\n depositAssetAddress,\n depositAmountAsBigInt,\n minimumMint,\n to,\n stringToHex(distributorCode || \"\"),\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 * Wallet detection utilities\n *\n * Provides helpers to determine wallet type (EOA vs smart contract wallet)\n * by inspecting on-chain bytecode.\n *\n * @module utils/wallet\n */\n\nimport type { Address } from \"viem\";\nimport { getClient } from \"../lib/viem/client\";\nimport type { ChainId } from \"./chain-utils\";\n\n/**\n * Checks whether an address is a smart contract wallet\n *\n * Uses viem's `getCode` to retrieve bytecode at the address:\n * - No bytecode (undefined / \"0x\") → EOA (externally owned account)\n * - Bytecode present → smart contract wallet (or EIP-7702 delegated EOA)\n *\n * Smart contract wallets can batch approve + execute atomically,\n * so pre-approval checks can be skipped for them.\n *\n * @param address - The wallet address to check\n * @param chainId - The chain to query\n * @returns true if the address has deployed bytecode (smart contract wallet)\n */\nexport async function isSmartContractWallet(\n address: Address,\n chainId: ChainId,\n): Promise<boolean> {\n const client = await getClient(chainId);\n const code = await client.getCode({ address });\n return !!code && code !== \"0x\";\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 \"../../client/amplify-sdk-client\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { isDepositSpendApproved } from \"../../utils/approvals\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\nimport { isSmartContractWallet } from \"../../utils/wallet\";\nimport {\n type ApproveDepositTokenTxData,\n prepareApproveDepositTokenTxData,\n} from \"./approve-deposit\";\nimport { type DepositTxData, prepareDepositTxData } from \"./deposit\";\nimport {\n type PermitSignatureData,\n prepareDepositPermitSignature,\n prepareDepositWithPermitTxData,\n type UnencodedDepositWithPermitData,\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}\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 guards or type narrowing with `result.method` to access specific fields:\n *\n * @example Using type guards (recommended)\n * ```typescript\n * import {\n * prepareDepositAuthorization,\n * isPermitAuth,\n * isApprovalAuth,\n * isAlreadyApprovedAuth,\n * } from \"@paxoslabs/amplify-sdk\";\n *\n * const result = await prepareDepositAuthorization({...});\n *\n * if (isPermitAuth(result)) {\n * // TypeScript knows result.permitData exists\n * const signature = await signTypedData(result.permitData);\n * } else if (isApprovalAuth(result)) {\n * // TypeScript knows result.txData exists\n * await writeContract(result.txData);\n * } else if (isAlreadyApprovedAuth(result)) {\n * // TypeScript knows result.allowance exists\n * console.log(`Already approved: ${result.allowance}`);\n * }\n * ```\n *\n * @example Using switch statement\n * ```typescript\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// TYPE GUARDS\n// ============================================================================\n\n/**\n * Type guard for permit authorization result\n *\n * @param result - Authorization result to check\n * @returns true if result is a permit authorization\n *\n * @example\n * ```typescript\n * if (isPermitAuth(result)) {\n * // TypeScript knows result.permitData exists\n * const signature = await signTypedData(result.permitData);\n * }\n * ```\n */\nexport function isPermitAuth(\n result: DepositAuthorizationResult\n): result is PermitAuthorizationResult {\n return result.method === DepositAuthMethod.PERMIT;\n}\n\n/**\n * Type guard for approval authorization result\n *\n * @param result - Authorization result to check\n * @returns true if result requires an ERC20 approval transaction\n *\n * @example\n * ```typescript\n * if (isApprovalAuth(result)) {\n * // TypeScript knows result.txData exists\n * await writeContract(result.txData);\n * }\n * ```\n */\nexport function isApprovalAuth(\n result: DepositAuthorizationResult\n): result is ApprovalAuthorizationResult {\n return result.method === DepositAuthMethod.APPROVAL;\n}\n\n/**\n * Type guard for already-approved authorization result\n *\n * @param result - Authorization result to check\n * @returns true if existing allowance is sufficient (no action needed)\n *\n * @example\n * ```typescript\n * if (isAlreadyApprovedAuth(result)) {\n * // TypeScript knows result.allowance exists\n * console.log(`Sufficient allowance: ${result.allowance}`);\n * }\n * ```\n */\nexport function isAlreadyApprovedAuth(\n result: DepositAuthorizationResult\n): result is AlreadyApprovedAuthorizationResult {\n return result.method === DepositAuthMethod.ALREADY_APPROVED;\n}\n\n/**\n * Parameters for prepareDepositAuthorization\n */\nexport interface PrepareDepositAuthorizationParams {\n /** Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\") */\n yieldType: YieldType;\n /** Token contract address to deposit */\n depositAsset: 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 to: 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., \"CORE\", \"TREASURY\", \"FRONTIER\") */\n yieldType: YieldType;\n /** Token contract address to deposit */\n depositAsset: Address;\n /** Amount of assets to deposit as decimal string (e.g., \"100.25\") */\n depositAmount: string;\n /** Recipient address for vault shares */\n to: Address;\n /** Blockchain network ID */\n chainId: ChainId;\n /** Optional slippage in basis points (default: 50 = 0.5%) */\n slippage?: number;\n /** Optional distributor code for fee attribution */\n distributorCode?: 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: \"CORE\",\n * depositAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * depositAmount: \"1000.0\",\n * to: \"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) {\n const {\n yieldType,\n depositAsset,\n depositAmount,\n to,\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: depositAsset,\n yieldType,\n chainId: normalizedChainId,\n });\n\n if (!vault) {\n throw new APIError(\n `No vault found for token ${depositAsset} with yield type '${yieldType}' on chain ${normalizedChainId}`,\n { endpoint: \"prepareDepositAuthorization\" },\n );\n }\n\n // Force override: always return approval tx data.\n if (forceMethod === \"approval\") {\n const txData = await prepareApproveDepositTokenTxData({\n yieldType,\n depositAsset,\n approvalAmount: depositAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: DepositAuthMethod.APPROVAL,\n txData,\n };\n }\n\n // Force override: always return permit signature data.\n if (forceMethod === \"permit\") {\n const tokenInfo = await isDepositSpendApproved({\n yieldType,\n chainId: normalizedChainId,\n depositAssetAddress: depositAsset,\n recipientAddress: to,\n });\n\n const permitData = await prepareDepositPermitSignature({\n yieldType,\n depositAsset,\n depositAmount,\n to,\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 // Smart contract wallets (e.g. Safe, EIP-4337, EIP-7702) are routed\n // to APPROVAL in auto mode so callers can batch approve + deposit\n // atomically.\n const smartWallet = await isSmartContractWallet(\n to,\n normalizedChainId,\n );\n\n if (smartWallet) {\n const txData = await prepareApproveDepositTokenTxData({\n yieldType,\n depositAsset,\n approvalAmount: depositAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: DepositAuthMethod.APPROVAL,\n txData,\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: depositAsset,\n recipientAddress: to,\n });\n\n // Automatic detection: Use dynamic on-chain permit support detection\n if (tokenInfo.supportsPermit) {\n const permitData = await prepareDepositPermitSignature({\n yieldType,\n depositAsset,\n depositAmount,\n to,\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 (tokenInfo.isApproved && currentAllowanceBigInt >= depositAmountBigInt) {\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 depositAsset,\n approvalAmount: depositAmount,\n chainId: normalizedChainId,\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 authorization: ${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: \"CORE\",\n * depositAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n * depositAmount: \"1000.0\",\n * to: \"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: \"CORE\",\n * depositAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n * depositAmount: \"1000.0\",\n * to: \"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 depositAsset,\n depositAmount,\n to,\n chainId,\n slippage,\n distributorCode,\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 depositAsset,\n depositAmount,\n to,\n chainId,\n signature,\n deadline,\n slippage,\n distributorCode,\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 depositAsset,\n depositAmount,\n to,\n chainId,\n slippage,\n distributorCode,\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: ${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\nexport type {\n ApproveDepositTokenTxData,\n PrepareApproveDepositTokenTxParams\n} from \"./approve-deposit\";\n// Re-export existing functions for backwards compatibility\nexport { prepareApproveDepositTokenTxData } from \"./approve-deposit\";\nexport { prepareDepositTxData } from \"./deposit\";\nexport type { DepositTxData, PrepareDepositTxDataParams } from \"./deposit\";\nexport {\n parsePermitSignature, PERMIT_TYPES, prepareDepositPermitSignature,\n prepareDepositWithPermitTxData,\n toEthSignTypedDataV4\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 { getErc20Decimals } from \"../../api/erc20\";\nimport { findVaultByConfig } from \"../../client/amplify-sdk-client\";\nimport { DEFAULT_APPROVAL_AMOUNT } from \"../../constants\";\nimport { APIError, type YieldType } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\n\n/**\n * Parameters required for preparing an approval transaction (NEW AmplifyVault schema)\n * @interface PrepareApproveWithdrawOrderTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (CORE, TREASURY, or FRONTIER)\n * @property {Address} wantAssetAddress - Address of the want token\n * @property {string} withdrawAmount - Amount to approve as a decimal string (defaults to maximum approval)\n * @property {ChainId} chainId - ID of the chain where the approval will occur\n */\ninterface PrepareApproveWithdrawOrderTxDataParams {\n yieldType: YieldType;\n wantAssetAddress: Address;\n withdrawAmount?: string;\n chainId: ChainId;\n /** Pre-fetched vault share decimals (avoids redundant RPC call) */\n shareDecimals?: number;\n}\n\n/**\n * Result object containing transaction data for a vault shares approval operation (vault shares token)\n * @interface ApproveWithdrawOrderTxData\n * @property {typeof BoringVaultAbi} abi - ABI for the BoringVault contract (vault shares token)\n * @property {Address} address - Address of the BoringVault (vault shares token)\n * @property {'approve'} functionName - Name of the function to call\n * @property {[Address, bigint]} args - Arguments for the approve function:\n * [spender (WithdrawQueue address), amount]\n */\ninterface ApproveWithdrawOrderTxData {\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 WithdrawQueue contract\n *\n * This function prepares an ERC20 approval transaction that allows the WithdrawQueue\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 prepareApproveWithdrawOrderTxData({\n * yieldType: 'CORE',\n * wantAssetAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * withdrawAmount: \"10.0\", // Approve 10 USDC\n * chainId: 1,\n * });\n * ```\n *\n * @param {PrepareApproveWithdrawOrderTxDataParams} params - Parameters for the approval operation\n * @param {YieldType} params.yieldType - Yield strategy type (CORE, TREASURY, or FRONTIER)\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<ApproveWithdrawOrderTxData>} 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 prepareApproveWithdrawOrderTxData({\n yieldType,\n wantAssetAddress,\n withdrawAmount,\n chainId,\n shareDecimals,\n}: PrepareApproveWithdrawOrderTxDataParams): Promise<ApproveWithdrawOrderTxData> {\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: \"prepareApproveWithdrawOrderTxData\" }\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: \"prepareApproveWithdrawOrderTxData\" }\n );\n }\n if (!config.vault.withdrawQueueAddress) {\n throw new APIError(\n `WithdrawQueue contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareApproveWithdrawOrderTxData\" }\n );\n }\n\n const boringVaultAddress = config.vault.boringVaultAddress;\n const withdrawQueueAddress = config.vault.withdrawQueueAddress;\n\n // Resolve vault share decimals:\n // Use pre-fetched value if provided, otherwise read from chain\n const decimals =\n shareDecimals ??\n (await getErc20Decimals({\n tokenAddress: boringVaultAddress,\n chainId: normalizedChainId,\n }));\n\n const withdrawAmountAsBigInt = withdrawAmount\n ? parseUnits(withdrawAmount, decimals)\n : DEFAULT_APPROVAL_AMOUNT;\n\n return {\n abi: BoringVaultAbi,\n address: boringVaultAddress,\n functionName: \"approve\",\n args: [withdrawQueueAddress, 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: \"prepareApproveWithdrawOrderTxData\",\n cause: error,\n }\n );\n }\n}\n\nexport type {\n ApproveWithdrawOrderTxData,\n PrepareApproveWithdrawOrderTxDataParams,\n};\n","/**\n * @file Cancel withdrawal order functionality for WithdrawQueue contract\n * @module vaults/withdraw/cancel-withdraw\n */\n\nimport type { Address } from \"viem\";\nimport { WithdrawQueueAbi } from \"../../abi/withdraw-queue-abi\";\nimport { findVaultByConfig } from \"../../client/amplify-sdk-client\";\nimport { APIError, type YieldType } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\n\n/**\n * Parameters for preparing a cancel withdrawal order transaction\n *\n * @interface PrepareCancelWithdrawOrderTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (CORE, TREASURY, or FRONTIER)\n * @property {Address} wantAsset - Address of the want token (used to find the correct vault/queue)\n * @property {ChainId} chainId - ID of the chain where the order exists\n * @property {bigint} orderIndex - Index of the order to cancel (provided by user)\n */\ninterface PrepareCancelWithdrawOrderTxDataParams {\n yieldType: YieldType;\n wantAsset: Address;\n chainId: ChainId;\n orderIndex: bigint;\n}\n\n/**\n * Transaction data for canceling a withdrawal order on the WithdrawQueue contract\n *\n * Ready-to-use transaction data that can be passed directly to viem's writeContract\n * or wagmi's useWriteContract hook.\n *\n * @interface CancelWithdrawOrderTxData\n */\ninterface CancelWithdrawOrderTxData {\n abi: typeof WithdrawQueueAbi;\n address: Address;\n functionName: \"cancelOrder\";\n args: [orderIndex: bigint];\n chainId: number;\n}\n\n/**\n * Prepares transaction data to cancel a withdrawal order on the WithdrawQueue contract\n *\n * This function prepares the transaction to cancel an existing order in the queue.\n * Only the order owner can cancel their order.\n *\n * @param {PrepareCancelWithdrawOrderTxDataParams} params - Parameters for the cancel operation\n * @returns {Promise<CancelWithdrawOrderTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not found, chain mismatch, or contracts not configured\n *\n * @example\n * ```typescript\n * import { prepareCancelWithdrawOrderTxData } from \"@paxoslabs/amplify-sdk\";\n *\n * const txData = await prepareCancelWithdrawOrderTxData({\n * yieldType: \"CORE\",\n * wantAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * chainId: 1,\n * orderIndex: 42n, // The order index to cancel\n * });\n *\n * // Execute with viem\n * const hash = await walletClient.writeContract(txData);\n *\n * // Or with wagmi\n * const { writeContract } = useWriteContract();\n * await writeContract(txData);\n * ```\n */\nconst prepareCancelWithdrawOrderTxData = async ({\n yieldType,\n wantAsset,\n chainId,\n orderIndex,\n}: PrepareCancelWithdrawOrderTxDataParams): Promise<CancelWithdrawOrderTxData> => {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n assetAddress: wantAsset,\n yieldType,\n chainId: normalizedChainId,\n });\n\n // Validation: Ensure vault exists\n if (!config) {\n throw new APIError(\n `No vault found for asset ${wantAsset} with yield type '${yieldType}' on chain ${normalizedChainId}`,\n { endpoint: \"prepareCancelWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure vault is on the correct chain\n if (config.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${config.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareCancelWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure withdrawQueueAddress is configured\n if (!config.vault.withdrawQueueAddress) {\n throw new APIError(\n `WithdrawQueue contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareCancelWithdrawOrderTxData\" }\n );\n }\n\n return {\n abi: WithdrawQueueAbi,\n address: config.vault.withdrawQueueAddress,\n functionName: \"cancelOrder\",\n args: [orderIndex],\n chainId: normalizedChainId,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to prepare cancel order transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareCancelWithdrawOrderTxData\",\n cause: error,\n }\n );\n }\n};\n\nexport { prepareCancelWithdrawOrderTxData };\nexport type {\n CancelWithdrawOrderTxData,\n PrepareCancelWithdrawOrderTxDataParams,\n};\n","/**\n * @file Standard withdrawal functionality for WithdrawQueue contract\n * @module vaults/withdraw/standard-withdraw\n */\n\nimport { type Address, parseUnits } from \"viem\";\nimport { WithdrawQueueAbi } from \"../../abi/withdraw-queue-abi\";\nimport { getErc20Decimals } from \"../../api/erc20\";\nimport { findVaultByConfig } from \"../../client/amplify-sdk-client\";\nimport { APIError, type YieldType } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\n\n/**\n * Approval method enum for WithdrawQueue signature params\n * Maps to contract's ApprovalMethod enum\n */\nconst ApprovalMethod = {\n /** Standard ERC20 approve (user has pre-approved via approve()) */\n EIP20_APPROVE: 0,\n /** EIP-2612 permit signature */\n EIP2612_APPROVE: 1,\n} as const;\n\n/**\n * Empty signature params for submitOrder when no permit/signature is used\n *\n * The contract expects this struct even when using pre-approved allowance.\n * ApprovalMethod enum: 0 = NONE, 1 = PERMIT, 2 = ALLOWANCE\n */\nconst EMPTY_SIGNATURE_PARAMS = {\n approvalMethod: ApprovalMethod.EIP20_APPROVE,\n approvalV: 0,\n approvalR:\n \"0x0000000000000000000000000000000000000000000000000000000000000000\" as `0x${string}`,\n approvalS:\n \"0x0000000000000000000000000000000000000000000000000000000000000000\" as `0x${string}`,\n submitWithSignature: false,\n deadline: 0n,\n eip2612Signature: \"0x\" as `0x${string}`,\n} as const;\n\n/**\n * Parameters for preparing a submit order transaction\n *\n * @interface PrepareWithdrawOrderTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (CORE, TREASURY, or FRONTIER)\n * @property {Address} wantAsset - Address of the token to receive upon withdrawal\n * @property {Address} userAddress - User's wallet address (used for intendedDepositor, receiver, refundReceiver)\n * @property {ChainId} chainId - ID of the chain where the withdrawal will occur\n * @property {string} amountOffer - Amount of vault shares to withdraw as a decimal string\n */\ninterface PrepareWithdrawOrderTxDataParams {\n yieldType: YieldType;\n wantAsset: Address;\n userAddress: Address;\n chainId: ChainId;\n amountOffer: string;\n}\n\n/**\n * Transaction data for submitting a withdrawal order to the WithdrawQueue contract\n *\n * Ready-to-use transaction data that can be passed directly to viem's writeContract\n * or wagmi's useWriteContract hook.\n *\n * @interface WithdrawOrderTxData\n */\ninterface WithdrawOrderTxData {\n abi: typeof WithdrawQueueAbi;\n address: Address;\n functionName: \"submitOrder\";\n args: [\n {\n amountOffer: bigint;\n wantAsset: Address;\n intendedDepositor: Address;\n receiver: Address;\n refundReceiver: Address;\n signatureParams: typeof EMPTY_SIGNATURE_PARAMS;\n },\n ];\n chainId: number;\n}\n\n/**\n * Prepares transaction data to submit a withdrawal order to the WithdrawQueue contract\n *\n * This function prepares a user request for the new WithdrawQueue contract.\n * Unlike the old AtomicQueue, this does not require exchange rate queries or slippage parameters.\n * It intentionally does not perform allowance pre-checks; callers should use\n * `prepareWithdrawalAuthorization` when they need approval routing.\n *\n * @param {PrepareWithdrawOrderTxDataParams} params - Parameters for the withdraw operation\n * @returns {Promise<WithdrawOrderTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not found, chain mismatch, or contracts not configured\n *\n * @example\n * ```typescript\n * import { prepareWithdrawOrderTxData } from \"@paxoslabs/amplify-sdk\";\n *\n * const txData = await prepareWithdrawOrderTxData({\n * yieldType: \"CORE\",\n * wantAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * userAddress: \"0x1234...\",\n * chainId: 1,\n * amountOffer: \"1.0\", // 1 vault share\n * });\n *\n * // Execute with viem\n * const hash = await walletClient.writeContract(txData);\n *\n * // Or with wagmi\n * const { writeContract } = useWriteContract();\n * await writeContract(txData);\n * ```\n */\nconst prepareWithdrawOrderTxData = async ({\n yieldType,\n wantAsset,\n userAddress,\n chainId,\n amountOffer,\n}: PrepareWithdrawOrderTxDataParams): Promise<WithdrawOrderTxData> => {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n assetAddress: wantAsset,\n yieldType,\n chainId: normalizedChainId,\n });\n\n\n // Validation: Ensure vault exists\n if (!config) {\n throw new APIError(\n `No vault found for asset ${wantAsset} with yield type '${yieldType}' on chain ${normalizedChainId}`,\n { endpoint: \"prepareWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure vault is on the correct chain\n if (config.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${config.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure withdrawQueueAddress is configured\n if (!config.vault.withdrawQueueAddress) {\n throw new APIError(\n `WithdrawQueue contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure boringVaultAddress is configured (needed for share decimals)\n if (!config.vault.boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareWithdrawOrderTxData\" }\n );\n }\n\n // Get vault share decimals from the BoringVault contract\n const sharesDecimals = await getErc20Decimals({\n tokenAddress: config.vault.boringVaultAddress,\n chainId: normalizedChainId,\n });\n\n // Parse offer amount using vault share decimals\n const formattedAmountOffer = parseUnits(amountOffer, sharesDecimals);\n\n return {\n abi: WithdrawQueueAbi,\n address: config.vault.withdrawQueueAddress,\n functionName: \"submitOrder\",\n args: [\n {\n amountOffer: formattedAmountOffer,\n wantAsset,\n intendedDepositor: userAddress,\n receiver: userAddress,\n refundReceiver: userAddress,\n signatureParams: EMPTY_SIGNATURE_PARAMS,\n },\n ],\n chainId: normalizedChainId,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to prepare withdraw order transaction: ${error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareWithdrawOrderTxData\",\n cause: error,\n }\n );\n }\n};\n\nexport { prepareWithdrawOrderTxData };\nexport type { PrepareWithdrawOrderTxDataParams, WithdrawOrderTxData };\n","/**\n * @file Unified withdrawal module with wrapper functions\n * @module vaults/withdraw\n *\n * Provides high-level wrapper functions for withdrawal authorization:\n * - `prepareWithdrawal`: Unified withdrawal preparation wrapper\n * - `prepareWithdrawalAuthorization`: Determines if approval is needed\n */\n\nimport { type Address, parseUnits } from \"viem\";\nimport { findVaultByConfig } from \"../../client/amplify-sdk-client\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { isWithdrawalSpendApproved } from \"../../utils/approvals\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\nimport { isSmartContractWallet } from \"../../utils/wallet\";\nimport {\n type ApproveWithdrawOrderTxData,\n prepareApproveWithdrawOrderTxData,\n} from \"./approve-withdraw\";\nimport {\n type WithdrawOrderTxData,\n prepareWithdrawOrderTxData,\n} from \"./standard-withdraw\";\n\n// ============================================================================\n// ENUMS\n// ============================================================================\n\n/**\n * Authorization methods for withdrawal operations\n *\n * Withdrawals do not support EIP-2612 permit — only two paths:\n * - APPROVAL: ERC20 approval of vault shares to WithdrawQueue\n * - ALREADY_APPROVED: Existing allowance is sufficient\n *\n * @example\n * ```typescript\n * import { WithdrawAuthMethod } from \"@paxoslabs/amplify-sdk\";\n *\n * if (result.method === WithdrawAuthMethod.ALREADY_APPROVED) {\n * // Proceed directly to withdrawal\n * }\n * ```\n */\nexport const WithdrawAuthMethod = {\n APPROVAL: \"approval\",\n ALREADY_APPROVED: \"already_approved\",\n} as const;\n\nexport type WithdrawAuthMethod =\n (typeof WithdrawAuthMethod)[keyof typeof WithdrawAuthMethod];\n\n// ============================================================================\n// TYPE DEFINITIONS - Authorization\n// ============================================================================\n\n/**\n * Approval authorization result\n * Returned when an ERC20 approval transaction is needed\n */\nexport interface WithdrawApprovalAuthorizationResult {\n method: typeof WithdrawAuthMethod.APPROVAL;\n /** Transaction data for ERC20 approve() call on vault shares */\n txData: ApproveWithdrawOrderTxData;\n}\n\n/**\n * Already approved authorization result\n * Returned when existing allowance is sufficient for the withdrawal\n */\nexport interface WithdrawAlreadyApprovedAuthorizationResult {\n method: typeof WithdrawAuthMethod.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 withdrawal authorization result types\n *\n * Use type guards or type narrowing with `result.method`:\n *\n * @example Using type guards (recommended)\n * ```typescript\n * import {\n * prepareWithdrawalAuthorization,\n * isWithdrawApprovalAuth,\n * isWithdrawAlreadyApprovedAuth,\n * } from \"@paxoslabs/amplify-sdk\";\n *\n * const result = await prepareWithdrawalAuthorization({...});\n *\n * if (isWithdrawApprovalAuth(result)) {\n * await writeContract(result.txData);\n * } else if (isWithdrawAlreadyApprovedAuth(result)) {\n * console.log(`Already approved: ${result.allowance}`);\n * }\n * ```\n */\nexport type WithdrawAuthorizationResult =\n | WithdrawApprovalAuthorizationResult\n | WithdrawAlreadyApprovedAuthorizationResult;\n\n// ============================================================================\n// TYPE GUARDS\n// ============================================================================\n\n/**\n * Type guard for approval authorization result\n *\n * @param result - Authorization result to check\n * @returns true if result requires an ERC20 approval transaction\n */\nexport function isWithdrawApprovalAuth(\n result: WithdrawAuthorizationResult\n): result is WithdrawApprovalAuthorizationResult {\n return result.method === WithdrawAuthMethod.APPROVAL;\n}\n\n/**\n * Type guard for already-approved authorization result\n *\n * @param result - Authorization result to check\n * @returns true if existing allowance is sufficient\n */\nexport function isWithdrawAlreadyApprovedAuth(\n result: WithdrawAuthorizationResult\n): result is WithdrawAlreadyApprovedAuthorizationResult {\n return result.method === WithdrawAuthMethod.ALREADY_APPROVED;\n}\n\n// ============================================================================\n// PARAMETERS\n// ============================================================================\n\n/**\n * Parameters for prepareWithdrawalAuthorization\n */\nexport interface PrepareWithdrawalAuthorizationParams {\n /** Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\") */\n yieldType: YieldType;\n /** Token address the user wants to receive upon withdrawal */\n wantAsset: Address;\n /** Amount of vault shares to withdraw as decimal string */\n withdrawAmount: string;\n /** User's wallet address (owner of vault shares) */\n userAddress: Address;\n /** Blockchain network ID */\n chainId: ChainId;\n /**\n * Force specific authorization routing behavior:\n * - \"approval\": Always return approval tx data\n * - \"allowance_check\": Always check allowance (skip smart-wallet heuristic)\n */\n forceMethod?: \"approval\" | \"allowance_check\";\n}\n\n/**\n * Parameters for prepareWithdrawal\n * Unified withdrawal wrapper that maps to standard withdraw tx preparation.\n */\nexport interface PrepareWithdrawalParams {\n /** Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\") */\n yieldType: YieldType;\n /** Token address the user wants to receive upon withdrawal */\n wantAsset: Address;\n /** Amount of vault shares to withdraw as decimal string */\n withdrawAmount: string;\n /** User's wallet address (owner of vault shares) */\n userAddress: Address;\n /** Blockchain network ID */\n chainId: ChainId;\n}\n\n/**\n * Unified withdrawal result\n * Currently routes to standard WithdrawQueue order preparation.\n */\nexport type PrepareWithdrawalResult = WithdrawOrderTxData;\n\n// ============================================================================\n// FUNCTIONS\n// ============================================================================\n\n/**\n * Unified withdrawal preparation wrapper\n *\n * Provides a stable high-level API for withdrawal execution while reusing\n * the low-level WithdrawQueue transaction builder under the hood.\n *\n * @param params - Withdrawal parameters\n * @returns Transaction data for submitOrder on WithdrawQueue\n * @throws {APIError} If preparation fails\n */\nexport async function prepareWithdrawal(\n params: PrepareWithdrawalParams,\n): Promise<PrepareWithdrawalResult> {\n const { yieldType, wantAsset, withdrawAmount, userAddress, chainId } =\n params;\n\n try {\n return await prepareWithdrawOrderTxData({\n yieldType,\n wantAsset,\n userAddress,\n chainId,\n amountOffer: withdrawAmount,\n });\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to prepare withdrawal: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareWithdrawal\",\n cause: error,\n },\n );\n }\n}\n\n/**\n * Prepares authorization for a withdrawal operation\n *\n * Determines if the user needs to approve vault shares for the\n * WithdrawQueue contract:\n * 1. Optional force override (`forceMethod`)\n * 2. Auto smart-wallet heuristic (returns approval for smart wallets)\n * 3. Check existing allowance → if sufficient, return \"already approved\"\n * 4. Otherwise → return approval transaction data\n *\n * @param params - Authorization parameters\n * @returns Discriminated union of authorization results\n * @throws {APIError} If vault not found or approval check fails\n *\n * @example\n * ```typescript\n * import {\n * prepareWithdrawalAuthorization,\n * WithdrawAuthMethod,\n * } from \"@paxoslabs/amplify-sdk\";\n *\n * const authResult = await prepareWithdrawalAuthorization({\n * yieldType: \"CORE\",\n * wantAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n * withdrawAmount: \"1.0\",\n * userAddress: \"0x1234...\",\n * chainId: 1,\n * });\n *\n * if (authResult.method === WithdrawAuthMethod.APPROVAL) {\n * await writeContract(authResult.txData);\n * // Wait for confirmation, then submit withdraw order\n * } else {\n * // Already approved, proceed to withdrawal\n * }\n * ```\n */\nexport async function prepareWithdrawalAuthorization(\n params: PrepareWithdrawalAuthorizationParams\n): Promise<WithdrawAuthorizationResult> {\n const {\n yieldType,\n wantAsset,\n withdrawAmount,\n userAddress,\n chainId,\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: wantAsset,\n yieldType,\n chainId: normalizedChainId,\n });\n\n if (!vault) {\n throw new APIError(\n `No vault found for asset ${wantAsset} with yield type '${yieldType}' on chain ${normalizedChainId}`,\n { endpoint: \"prepareWithdrawalAuthorization\" },\n );\n }\n\n // Force override: always return approval tx data.\n if (forceMethod === \"approval\") {\n const txData = await prepareApproveWithdrawOrderTxData({\n yieldType,\n wantAssetAddress: wantAsset,\n withdrawAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: WithdrawAuthMethod.APPROVAL,\n txData,\n };\n }\n\n // Smart contract wallets (e.g. Safe, EIP-4337, EIP-7702) can batch\n // approve + withdraw atomically. In auto mode, skip allowance checks\n // and return approval tx data directly.\n if (forceMethod !== \"allowance_check\") {\n const smartWallet = await isSmartContractWallet(\n userAddress,\n normalizedChainId,\n );\n\n if (smartWallet) {\n const txData = await prepareApproveWithdrawOrderTxData({\n yieldType,\n wantAssetAddress: wantAsset,\n withdrawAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: WithdrawAuthMethod.APPROVAL,\n txData,\n };\n }\n }\n\n // Check current withdrawal approval status\n const approvalInfo = await isWithdrawalSpendApproved({\n yieldType,\n chainId: normalizedChainId,\n wantAssetAddress: wantAsset,\n recipientAddress: userAddress,\n });\n\n // Handle multicall failure\n if (approvalInfo.error) {\n throw new APIError(\n `Failed to check withdrawal approval: ${approvalInfo.error}`,\n { endpoint: \"prepareWithdrawalAuthorization\" },\n );\n }\n\n // Parse withdraw amount to compare against allowance\n const decimals =\n typeof approvalInfo.decimals === \"string\"\n ? Number(approvalInfo.decimals)\n : approvalInfo.decimals;\n const withdrawAmountBigInt = parseUnits(withdrawAmount, decimals);\n const currentAllowanceBigInt = BigInt(\n approvalInfo.allowanceAsBigInt,\n );\n\n // Check if existing allowance is sufficient\n if (\n approvalInfo.isApproved &&\n currentAllowanceBigInt >= withdrawAmountBigInt\n ) {\n return {\n method: WithdrawAuthMethod.ALREADY_APPROVED,\n allowance: approvalInfo.allowance,\n allowanceAsBigInt: approvalInfo.allowanceAsBigInt,\n };\n }\n\n // Insufficient allowance: prepare approval transaction\n // Pass share decimals to avoid redundant RPC call\n const txData = await prepareApproveWithdrawOrderTxData({\n yieldType,\n wantAssetAddress: wantAsset,\n withdrawAmount,\n chainId: normalizedChainId,\n shareDecimals: decimals,\n });\n\n return {\n method: WithdrawAuthMethod.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 withdrawal authorization: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareWithdrawalAuthorization\",\n cause: error,\n },\n );\n }\n}\n\n// ============================================================================\n// RE-EXPORTS\n// ============================================================================\n\nexport type {\n ApproveWithdrawOrderTxData,\n PrepareApproveWithdrawOrderTxDataParams,\n} from \"./approve-withdraw\";\nexport { prepareApproveWithdrawOrderTxData } from \"./approve-withdraw\";\nexport type {\n CancelWithdrawOrderTxData,\n PrepareCancelWithdrawOrderTxDataParams,\n} from \"./cancel-withdraw\";\nexport { prepareCancelWithdrawOrderTxData } from \"./cancel-withdraw\";\nexport type {\n PrepareWithdrawOrderTxDataParams,\n WithdrawOrderTxData,\n} from \"./standard-withdraw\";\nexport { prepareWithdrawOrderTxData } from \"./standard-withdraw\";\n"]}
1
+ {"version":3,"sources":["../src/utils/approvals.ts","../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/utils/wallet.ts","../src/vaults/deposit/index.ts","../src/vaults/withdraw/approve-withdraw.ts","../src/vaults/withdraw/cancel-withdraw.ts","../src/vaults/withdraw/standard-withdraw.ts","../src/vaults/withdraw/index.ts"],"names":["toChainId","findVaultByConfig","APIError","getTokenPermitInfoWithAllowance","formatUnits","getErc20AllowanceWithDecimals","getAssetsFromCache","parseUnits","DEFAULT_APPROVAL_AMOUNT","erc20Abi","DEFAULT_SLIPPAGE_BPS","WAD","getRateInQuoteWithAssetDecimals","stringToHex","getClient","erc2612Abi","getErc20Decimals","hexToSignature","txData","tokenInfo","BoringVaultAbi","WithdrawQueueAbi"],"mappings":";;;;;;;;AAUO,IAAM,yBAAyB,OAAO;AAAA,EAC3C,SAAA;AAAA,EACA,OAAA;AAAA,EACA,mBAAA;AAAA,EACA;AACF,CAAA,KAKM;AACJ,EAAA,IAAI;AACF,IAAA,MAAM,iBAAA,GAAoBA,2BAAU,OAAO,CAAA;AAC3C,IAAA,MAAM,MAAA,GAAS,MAAMC,kCAAA,CAAkB;AAAA,MACrC,SAAA;AAAA,MACA,OAAA,EAAS,iBAAA;AAAA,MACT,YAAA,EAAc;AAAA,KACf,CAAA;AAED,IAAA,IAAI,CAAC,MAAA,EAAQ;AACX,MAAA,MAAM,IAAIC,yBAAA;AAAA,QACR,CAAA,oBAAA,EAAuB,SAAS,CAAA,UAAA,EAAa,iBAAiB,CAAA,CAA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KACF;AAAA,EACF,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,iBAAiBL,yBAAA,EAAU;AAC7B,MAAA,MAAM,KAAA;AAAA,IACR;AAEA,IAAA,MAAM,IAAIA,yBAAA;AAAA,MACR,+CACE,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":"chunk-2YPKHXFJ.js","sourcesContent":["import type { Address } from \"viem\";\nimport { formatUnits } from \"viem\";\nimport {\n getErc20AllowanceWithDecimals,\n getTokenPermitInfoWithAllowance,\n} from \"../api/erc20\";\nimport { findVaultByConfig } from \"../client/amplify-sdk-client\";\nimport { APIError, type YieldType } from \"../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"./chain-utils\";\n\nexport const isDepositSpendApproved = async ({\n yieldType,\n chainId,\n depositAssetAddress,\n recipientAddress,\n}: {\n yieldType: YieldType;\n chainId: ChainId;\n depositAssetAddress: Address;\n recipientAddress: Address;\n}) => {\n try {\n const normalizedChainId = toChainId(chainId);\n const config = await findVaultByConfig({\n yieldType,\n chainId: normalizedChainId,\n assetAddress: depositAssetAddress,\n });\n\n if (!config) {\n throw new APIError(\n `Vault not found for ${yieldType} on chain ${normalizedChainId}`,\n {\n endpoint: \"isDepositSpendApproved\",\n }\n );\n }\n\n const communityCodeDepositorAddress =\n config.vault.communityCodeDepositorAddress;\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `Community code depositor contract address not configured for vault ${config.id}`,\n {\n endpoint: \"isDepositSpendApproved\",\n }\n );\n }\n\n const {\n decimals,\n allowance,\n supportsPermit,\n nonce,\n domainSeparator,\n tokenName,\n tokenVersion,\n } = await getTokenPermitInfoWithAllowance({\n chainId: normalizedChainId,\n tokenAddress: depositAssetAddress,\n owner: recipientAddress,\n spender: communityCodeDepositorAddress,\n });\n\n return {\n isApproved: allowance > 0n,\n allowance: formatUnits(allowance, decimals),\n allowanceAsBigInt: allowance.toString(),\n decimals,\n supportsPermit,\n nonce,\n domainSeparator,\n tokenName,\n tokenVersion,\n error: null,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n // Wrap other errors\n throw new APIError(\n `Failed to check deposit approval: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"isDepositSpendApproved\",\n cause: error,\n }\n );\n }\n};\n\nexport const isWithdrawalSpendApproved = async ({\n yieldType,\n chainId,\n wantAssetAddress,\n recipientAddress,\n}: {\n yieldType: YieldType;\n chainId: ChainId;\n wantAssetAddress: Address;\n recipientAddress: Address;\n}) => {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n yieldType,\n chainId: normalizedChainId,\n assetAddress: wantAssetAddress,\n });\n\n if (!config) {\n throw new APIError(\n `Vault not found for ${yieldType} on chain ${normalizedChainId}`,\n {\n endpoint: \"isWithdrawalSpendApproved\",\n }\n );\n }\n\n const boringVaultAddress = config.vault.boringVaultAddress;\n\n if (!boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config.id}`,\n {\n endpoint: \"isWithdrawalSpendApproved\",\n }\n );\n }\n\n const withdrawQueueAddress = config.vault.withdrawQueueAddress;\n\n if (!withdrawQueueAddress) {\n throw new APIError(\n `WithdrawQueue contract address not configured for vault ${config.id}`,\n {\n endpoint: \"isWithdrawalSpendApproved\",\n }\n );\n }\n\n const [allowance, decimals] = await getErc20AllowanceWithDecimals({\n chainId: normalizedChainId,\n tokenAddress: boringVaultAddress,\n recipientAddress: recipientAddress,\n spenderAddress: withdrawQueueAddress,\n });\n\n if (allowance.status === \"failure\" || decimals.status === \"failure\") {\n return {\n isApproved: false,\n allowance: \"0\",\n allowanceAsBigInt: \"0\",\n decimals: \"0\",\n error: allowance.error || decimals.error,\n };\n }\n\n return {\n isApproved: allowance.result > 0n,\n allowance: formatUnits(allowance.result, decimals.result),\n allowanceAsBigInt: allowance.result.toString(),\n decimals: decimals.result,\n error: null,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to check withdrawal approval: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { endpoint: \"isWithdrawalSpendApproved\", cause: error }\n );\n }\n};\n","/**\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 \"../../client/amplify-sdk-client\";\nimport { DEFAULT_APPROVAL_AMOUNT } from \"../../constants\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\n\n/**\n * Parameters required for preparing an approval transaction\n * @interface PrepareApproveDepositTokenTxParams\n * @property {YieldType} yieldType - Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\")\n * @property {Address} depositAsset - Token contract address to approve\n * @property {string} [approvalAmount] - Optional amount to approve (defaults to maximum approval)\n * @property {ChainId} chainId - ID of the chain where the approval will occur\n */\ninterface PrepareApproveDepositTokenTxParams {\n yieldType: YieldType;\n depositAsset: 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 (CommunityCodeDepositor 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 * CommunityCodeDepositor contract to spend the user's deposit tokens.\n *\n * @example\n * ```typescript\n * const approveData = await prepareApproveDepositTokenTxData({\n * yieldType: \"CORE\",\n * depositAsset: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\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 or vault not found\n */\nexport async function prepareApproveDepositTokenTxData({\n yieldType,\n depositAsset,\n approvalAmount,\n chainId,\n}: PrepareApproveDepositTokenTxParams): Promise<ApproveDepositTokenTxData> {\n const normalizedChainId = toChainId(chainId);\n\n try {\n const config = await findVaultByConfig({\n assetAddress: depositAsset,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n if (!config) {\n throw new APIError(\n `No vault found for token address ${depositAsset} with yield type '${yieldType}' on chain ${normalizedChainId}. This combination may not be supported.`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n const communityCodeDepositorAddress =\n config.vault.communityCodeDepositorAddress;\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `Community Code Depositor 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: depositAsset });\n if (assets.length === 0) {\n throw new APIError(\n `Asset metadata not found for token ${depositAsset} on chain ${normalizedChainId}`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n\n const verifiedAsset = assets.find(\n (asset) =>\n asset.address.toLowerCase() === depositAsset.toLowerCase() &&\n asset.chains.includes(normalizedChainId)\n );\n\n // verify asset is verified on the desired chain.\n if (!verifiedAsset) {\n throw new APIError(\n `Asset ${depositAsset} not verified on chain ${normalizedChainId}`,\n { endpoint: \"prepareApproveDepositToken\" }\n );\n }\n const decimals = verifiedAsset.decimals;\n\n const amount = approvalAmount\n ? parseUnits(approvalAmount, decimals)\n : DEFAULT_APPROVAL_AMOUNT;\n return {\n abi: erc20Abi,\n address: depositAsset,\n functionName: \"approve\",\n args: [communityCodeDepositorAddress, 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 findVaultByConfig,\n getAssetsFromCache,\n} from \"../../client/amplify-sdk-client\";\nimport { DEFAULT_SLIPPAGE_BPS } from \"../../constants/config\";\nimport type {\n YieldType\n} from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\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, to, 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, to, depositAsset, and chainId for automatic vault resolution\n * @interface PrepareDepositTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\")\n * @property {Address} to - Ethereum address of the recipient. Must be the same as the address used to sign the deposit transaction.\n * @property {Address} depositAsset - 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} [distributorCode] - Optional (default is empty string): Distributor code for fee attribution\n */\ninterface PrepareDepositTxDataParams {\n yieldType: YieldType;\n to: Address;\n depositAsset: Address;\n depositAmount: string;\n chainId: ChainId;\n slippage?: number;\n distributorCode?: 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 prepareDepositTxData({\n * yieldType: 'CORE',\n * to: '0x1234...',\n * depositAsset: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * depositAmount: \"1.0\",\n * chainId: 1,\n * slippage: 100, // 1% slippage (100 bps)\n * distributorCode: 'my-distributor-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 depositAsset,\n depositAmount,\n chainId,\n slippage = DEFAULT_SLIPPAGE_BPS,\n to,\n distributorCode,\n } = params;\n\n try {\n const normalizedChainId = toChainId(chainId);\n\n const vault = await findVaultByConfig({\n assetAddress: depositAsset,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n\n\n // Check if vault was found\n if (!vault) {\n throw new APIError(\n `No vault found for token address ${depositAsset} 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 asset\n // let asset: SupportedAsset | null = null;\n const assets = await getAssetsFromCache({ address: depositAsset });\n\n // Find the asset for the correct chain\n const asset = assets.find((a) => a.chains.includes(normalizedChainId)) || assets.find((a) => a.address.toLowerCase() === depositAsset.toLowerCase());\n\n\n if (!asset) {\n throw new APIError(\n `Asset metadata not found for token ${depositAsset} on chain ${normalizedChainId}`,\n {\n endpoint: \"prepareDepositTransactionData\",\n }\n );\n }\n\n // Verify transaction data includes correct vault contract addresses\n const communityCodeDepositorAddress =\n vault.vault.communityCodeDepositorAddress;\n if (!communityCodeDepositorAddress) {\n throw new APIError(\n `Community Code Depositor contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositTransactionData\" }\n );\n }\n\n const accountantAddress = vault.vault.accountantAddress;\n\n if (!accountantAddress) {\n throw new APIError(\n `Accountant contract address not found for vault ${vault.id}`,\n { endpoint: \"prepareDepositTransactionData\" }\n );\n }\n const depositAssetAddress = asset.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: ${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: ${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 // Calculate minimumMint using calculateMinimumMint utility (asset is vault base token)\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 to,\n stringToHex(distributorCode || \"\"),\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: ${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 { getErc20Decimals } from \"../../api/erc20\";\nimport {\n findVaultByConfig,\n getAssetsFromCache,\n} from \"../../client/amplify-sdk-client\";\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 { type ChainId, toChainId } from \"../../utils/chain-utils\";\nimport { calculateMinimumMint } from \"./utils\";\n\n/**\n * Strict EIP-712 domain separator conforming to the EIP-712 TypedData JSON schema\n * Compatible with viem's TypedDataDomain and standard EIP-712 signing libraries\n *\n * This interface matches viem/abitype's TypedDataDomain for seamless integration\n * with viem's signTypedData() and wagmi's signTypedDataAsync().\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 (hex string)\n */\nexport interface EIP712Domain {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: Address;\n salt?: Hex;\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} as const;\n\n/**\n * EIP-712 domain type definition for raw JSON-RPC calls\n * Required by eth_signTypedData_v4 but auto-added by viem/wagmi\n */\nconst EIP712_DOMAIN_TYPE = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\n/**\n * Converts PermitSignatureData to the format required by eth_signTypedData_v4\n *\n * Use this when calling eth_signTypedData_v4 directly via a provider (e.g., Privy\n * embedded wallets). For viem/wagmi, use the PermitSignatureData directly.\n *\n * Key differences from viem/wagmi format:\n * - Includes EIP712Domain in the types object (viem auto-adds this)\n * - Converts bigint values to strings for JSON serialization\n *\n * @param permitData - Permit data from prepareDepositPermitSignature()\n * @returns JSON string ready for eth_signTypedData_v4 params\n *\n * @example\n * ```typescript\n * // With Privy embedded wallet\n * const permitData = await prepareDepositPermitSignature({...});\n * const provider = await wallet.getEthereumProvider();\n * const signature = await provider.request({\n * method: 'eth_signTypedData_v4',\n * params: [wallet.address, toEthSignTypedDataV4(permitData)],\n * });\n * ```\n */\nexport function toEthSignTypedDataV4(permitData: PermitSignatureData): string {\n return JSON.stringify({\n domain: permitData.domain,\n types: {\n EIP712Domain: EIP712_DOMAIN_TYPE,\n ...permitData.types,\n },\n primaryType: permitData.primaryType,\n message: {\n owner: permitData.message.owner,\n spender: permitData.message.spender,\n value: permitData.message.value.toString(),\n nonce: permitData.message.nonce.toString(),\n deadline: permitData.message.deadline.toString(),\n },\n });\n}\n\n/**\n * T009: Complete EIP-712 typed data for permit signature\n * Returned by prepareDepositPermitSignature() ready for wallet signing\n *\n * Compatible with viem's signTypedData(), wagmi's signTypedDataAsync(),\n * and Privy's signTypedData(). Pass this object directly to the signing function.\n *\n * @property domain - EIP-712 domain separator with numeric chainId\n * @property types - EIP-2612 Permit type structure\n * @property message - Permit message fields with uint256 values as decimal strings\n * @property primaryType - Always \"Permit\" for EIP-2612\n *\n * @remarks\n * The message uses decimal string representations for uint256 values to ensure:\n * 1. JSON serialization compatibility (required for Privy embedded wallets)\n * 2. Compatibility with viem, wagmi, and Privy signing functions\n * 3. Compliance with EIP-712 JSON schema specification\n *\n * @example\n * ```typescript\n * // With wagmi\n * const signature = await signTypedDataAsync(permitData);\n *\n * // With viem\n * const signature = await walletClient.signTypedData(permitData);\n *\n * // With Privy\n * const signature = await wallet.signTypedData(permitData);\n * ```\n */\nexport type PermitSignatureData = Awaited<\n ReturnType<typeof prepareDepositPermitSignature>\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 depositAsset - Token contract address to deposit\n * @property depositAmount - Deposit amount as decimal string\n * @property to - 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 depositAsset: Address;\n depositAmount: string;\n to: 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 type UnencodedDepositWithPermitData = Awaited<\n ReturnType<typeof prepareDepositWithPermitTxData>\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: 'CORE',\n * depositAsset: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * depositAmount: '1000.0',\n * to: userAddress,\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) {\n const {\n yieldType,\n depositAsset,\n depositAmount,\n to,\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: depositAsset,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositAsset} 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 ${depositAsset} 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: depositAsset,\n abi: erc2612Abi,\n functionName: \"name\",\n },\n {\n address: depositAsset,\n abi: erc2612Abi,\n functionName: \"version\",\n },\n {\n address: depositAsset,\n abi: erc2612Abi,\n functionName: \"nonces\",\n args: [to],\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 ${depositAsset}`, {\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 ${depositAsset} 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 on-chain\n let resolvedDecimals: number;\n if (prefetchedDecimals !== undefined) {\n resolvedDecimals = prefetchedDecimals;\n } else {\n resolvedDecimals = await getErc20Decimals({\n tokenAddress: depositAsset,\n chainId: normalizedChainId,\n });\n }\n const value = parseUnits(depositAmount, resolvedDecimals);\n\n // T024: Build EIP-712 domain with required fields for permit signing\n const domain = {\n name: resolvedTokenName,\n version: resolvedTokenVersion,\n chainId: normalizedChainId,\n verifyingContract: depositAsset,\n } satisfies EIP712Domain;\n\n // T025: Build permit message with uint256 values as decimal strings\n // String representation ensures JSON serialization compatibility for\n // Privy embedded wallets while remaining compatible with viem/wagmi\n const message = {\n owner: to,\n spender: communityCodeDepositorAddress,\n value: value,\n nonce: resolvedNonce,\n deadline: permitDeadline,\n };\n\n // T026: Return PermitSignatureData\n return {\n account: to,\n domain,\n types: PERMIT_TYPES,\n primaryType: \"Permit\" as const,\n message,\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 prepareDepositWithPermitTxData()\n * Now accepts raw signature and deadline for complete transaction encoding\n *\n * @example\n * ```typescript\n * const permitData = await prepareDepositPermitSignature({ ... });\n * const signature = await signTypedData(permitData);\n *\n * const params: PrepareDepositWithPermitTxDataParams = {\n * yieldType: \"CORE\",\n * to: \"0x1234567890123456789012345678901234567890\",\n * depositAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * depositAmount: \"100.25\",\n * chainId: 1,\n * signature,\n * deadline: permitData.message.deadline,\n * slippage: 100, // 1%\n * distributorCode: \"my-distributor-code\",\n * };\n * ```\n */\nexport interface PrepareDepositWithPermitTxDataParams {\n yieldType: YieldType;\n to: Address;\n depositAsset: Address;\n depositAmount: string;\n chainId: number | ChainId;\n signature: Hex;\n deadline: bigint;\n slippage?: number;\n distributorCode?: 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 params - Deposit parameters including signature and deadline\n * @returns Encoded transaction data ready for submission\n * @throws {APIError} If vault not found, invalid signature, or parameter validation fails\n *\n * @example\n * ```typescript\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) {\n const {\n yieldType,\n depositAsset,\n depositAmount,\n chainId,\n signature,\n deadline,\n slippage = DEFAULT_SLIPPAGE_BPS,\n to,\n distributorCode,\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: depositAsset,\n yieldType: yieldType,\n chainId: normalizedChainId,\n });\n } catch (error) {\n throw new APIError(\n `Failed to resolve vault for token ${depositAsset} 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 ${depositAsset} 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 asset metadata using getAssetsFromCache\n // Use cache-based lookup which properly filters by address\n let asset: SupportedAsset | null = null;\n const assets = await getAssetsFromCache({ address: depositAsset });\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 ${depositAsset} 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 || depositAsset\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 // Use the deposit asset address that was passed in (matches vault.baseTokenAddress)\n const depositAssetAddress = depositAsset;\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 rateAndDecimalResults = await getRateInQuoteWithAssetDecimals({\n assetAddress: depositAssetAddress,\n accountantAddress: accountantAddress,\n chainId: normalizedChainId,\n });\n const [depositAssetDecimalsResult, rateInQuoteResult] = rateAndDecimalResults;\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 // Use on-chain decimals from multicall (not cache placeholder)\n const onChainDecimals =\n depositAssetDecimalsResult.result as number;\n const depositAmountAsBigInt = parseUnits(\n depositAmount,\n onChainDecimals\n );\n\n // T051: Calculate minimumMint using calculateMinimumMint utility (asset is vault base token)\n const minimumMint = calculateMinimumMint(\n depositAmountAsBigInt,\n rateInQuoteResult.result,\n onChainDecimals,\n slippage\n );\n\n return {\n data: {\n abi: CommunityCodeDepositorAbi,\n functionName: \"depositWithPermit\",\n args: [\n depositAssetAddress,\n depositAmountAsBigInt,\n minimumMint,\n to,\n stringToHex(distributorCode || \"\"),\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 * Wallet detection utilities\n *\n * Provides helpers to determine wallet type (EOA vs smart contract wallet)\n * by inspecting on-chain bytecode.\n *\n * @module utils/wallet\n */\n\nimport type { Address } from \"viem\";\nimport { getClient } from \"../lib/viem/client\";\nimport type { ChainId } from \"./chain-utils\";\n\n/**\n * Checks whether an address is a smart contract wallet\n *\n * Uses viem's `getCode` to retrieve bytecode at the address:\n * - No bytecode (undefined / \"0x\") → EOA (externally owned account)\n * - Bytecode present → smart contract wallet (or EIP-7702 delegated EOA)\n *\n * Smart contract wallets can batch approve + execute atomically,\n * so pre-approval checks can be skipped for them.\n *\n * @param address - The wallet address to check\n * @param chainId - The chain to query\n * @returns true if the address has deployed bytecode (smart contract wallet)\n */\nexport async function isSmartContractWallet(\n address: Address,\n chainId: ChainId,\n): Promise<boolean> {\n const client = await getClient(chainId);\n const code = await client.getCode({ address });\n return !!code && code !== \"0x\";\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 \"../../client/amplify-sdk-client\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { isDepositSpendApproved } from \"../../utils/approvals\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\nimport { isSmartContractWallet } from \"../../utils/wallet\";\nimport {\n type ApproveDepositTokenTxData,\n prepareApproveDepositTokenTxData,\n} from \"./approve-deposit\";\nimport { type DepositTxData, prepareDepositTxData } from \"./deposit\";\nimport {\n type PermitSignatureData,\n prepareDepositPermitSignature,\n prepareDepositWithPermitTxData,\n type UnencodedDepositWithPermitData,\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}\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 guards or type narrowing with `result.method` to access specific fields:\n *\n * @example Using type guards (recommended)\n * ```typescript\n * import {\n * prepareDepositAuthorization,\n * isPermitAuth,\n * isApprovalAuth,\n * isAlreadyApprovedAuth,\n * } from \"@paxoslabs/amplify-sdk\";\n *\n * const result = await prepareDepositAuthorization({...});\n *\n * if (isPermitAuth(result)) {\n * // TypeScript knows result.permitData exists\n * const signature = await signTypedData(result.permitData);\n * } else if (isApprovalAuth(result)) {\n * // TypeScript knows result.txData exists\n * await writeContract(result.txData);\n * } else if (isAlreadyApprovedAuth(result)) {\n * // TypeScript knows result.allowance exists\n * console.log(`Already approved: ${result.allowance}`);\n * }\n * ```\n *\n * @example Using switch statement\n * ```typescript\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// TYPE GUARDS\n// ============================================================================\n\n/**\n * Type guard for permit authorization result\n *\n * @param result - Authorization result to check\n * @returns true if result is a permit authorization\n *\n * @example\n * ```typescript\n * if (isPermitAuth(result)) {\n * // TypeScript knows result.permitData exists\n * const signature = await signTypedData(result.permitData);\n * }\n * ```\n */\nexport function isPermitAuth(\n result: DepositAuthorizationResult\n): result is PermitAuthorizationResult {\n return result.method === DepositAuthMethod.PERMIT;\n}\n\n/**\n * Type guard for approval authorization result\n *\n * @param result - Authorization result to check\n * @returns true if result requires an ERC20 approval transaction\n *\n * @example\n * ```typescript\n * if (isApprovalAuth(result)) {\n * // TypeScript knows result.txData exists\n * await writeContract(result.txData);\n * }\n * ```\n */\nexport function isApprovalAuth(\n result: DepositAuthorizationResult\n): result is ApprovalAuthorizationResult {\n return result.method === DepositAuthMethod.APPROVAL;\n}\n\n/**\n * Type guard for already-approved authorization result\n *\n * @param result - Authorization result to check\n * @returns true if existing allowance is sufficient (no action needed)\n *\n * @example\n * ```typescript\n * if (isAlreadyApprovedAuth(result)) {\n * // TypeScript knows result.allowance exists\n * console.log(`Sufficient allowance: ${result.allowance}`);\n * }\n * ```\n */\nexport function isAlreadyApprovedAuth(\n result: DepositAuthorizationResult\n): result is AlreadyApprovedAuthorizationResult {\n return result.method === DepositAuthMethod.ALREADY_APPROVED;\n}\n\n/**\n * Parameters for prepareDepositAuthorization\n */\nexport interface PrepareDepositAuthorizationParams {\n /** Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\") */\n yieldType: YieldType;\n /** Token contract address to deposit */\n depositAsset: 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 to: 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., \"CORE\", \"TREASURY\", \"FRONTIER\") */\n yieldType: YieldType;\n /** Token contract address to deposit */\n depositAsset: Address;\n /** Amount of assets to deposit as decimal string (e.g., \"100.25\") */\n depositAmount: string;\n /** Recipient address for vault shares */\n to: Address;\n /** Blockchain network ID */\n chainId: ChainId;\n /** Optional slippage in basis points (default: 50 = 0.5%) */\n slippage?: number;\n /** Optional distributor code for fee attribution */\n distributorCode?: 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: \"CORE\",\n * depositAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * depositAmount: \"1000.0\",\n * to: \"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) {\n const {\n yieldType,\n depositAsset,\n depositAmount,\n to,\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: depositAsset,\n yieldType,\n chainId: normalizedChainId,\n });\n\n if (!vault) {\n throw new APIError(\n `No vault found for token ${depositAsset} with yield type '${yieldType}' on chain ${normalizedChainId}`,\n { endpoint: \"prepareDepositAuthorization\" },\n );\n }\n\n // Force override: always return approval tx data.\n if (forceMethod === \"approval\") {\n const txData = await prepareApproveDepositTokenTxData({\n yieldType,\n depositAsset,\n approvalAmount: depositAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: DepositAuthMethod.APPROVAL,\n txData,\n };\n }\n\n // Force override: always return permit signature data.\n if (forceMethod === \"permit\") {\n const tokenInfo = await isDepositSpendApproved({\n yieldType,\n chainId: normalizedChainId,\n depositAssetAddress: depositAsset,\n recipientAddress: to,\n });\n\n const permitData = await prepareDepositPermitSignature({\n yieldType,\n depositAsset,\n depositAmount,\n to,\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 // Smart contract wallets (e.g. Safe, EIP-4337, EIP-7702) are routed\n // to APPROVAL in auto mode so callers can batch approve + deposit\n // atomically.\n const smartWallet = await isSmartContractWallet(\n to,\n normalizedChainId,\n );\n\n if (smartWallet) {\n const txData = await prepareApproveDepositTokenTxData({\n yieldType,\n depositAsset,\n approvalAmount: depositAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: DepositAuthMethod.APPROVAL,\n txData,\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: depositAsset,\n recipientAddress: to,\n });\n\n // Automatic detection: Use dynamic on-chain permit support detection\n if (tokenInfo.supportsPermit) {\n const permitData = await prepareDepositPermitSignature({\n yieldType,\n depositAsset,\n depositAmount,\n to,\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 (tokenInfo.isApproved && currentAllowanceBigInt >= depositAmountBigInt) {\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 depositAsset,\n approvalAmount: depositAmount,\n chainId: normalizedChainId,\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 authorization: ${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: \"CORE\",\n * depositAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n * depositAmount: \"1000.0\",\n * to: \"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: \"CORE\",\n * depositAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n * depositAmount: \"1000.0\",\n * to: \"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 depositAsset,\n depositAmount,\n to,\n chainId,\n slippage,\n distributorCode,\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 depositAsset,\n depositAmount,\n to,\n chainId,\n signature,\n deadline,\n slippage,\n distributorCode,\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 depositAsset,\n depositAmount,\n to,\n chainId,\n slippage,\n distributorCode,\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: ${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\nexport type {\n ApproveDepositTokenTxData,\n PrepareApproveDepositTokenTxParams\n} from \"./approve-deposit\";\n// Re-export existing functions for backwards compatibility\nexport { prepareApproveDepositTokenTxData } from \"./approve-deposit\";\nexport { prepareDepositTxData } from \"./deposit\";\nexport type { DepositTxData, PrepareDepositTxDataParams } from \"./deposit\";\nexport {\n parsePermitSignature, PERMIT_TYPES, prepareDepositPermitSignature,\n prepareDepositWithPermitTxData,\n toEthSignTypedDataV4\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 { getErc20Decimals } from \"../../api/erc20\";\nimport { findVaultByConfig } from \"../../client/amplify-sdk-client\";\nimport { DEFAULT_APPROVAL_AMOUNT } from \"../../constants\";\nimport { APIError, type YieldType } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\n\n/**\n * Parameters required for preparing an approval transaction (NEW AmplifyVault schema)\n * @interface PrepareApproveWithdrawOrderTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (CORE, TREASURY, or FRONTIER)\n * @property {Address} wantAssetAddress - Address of the want token\n * @property {string} withdrawAmount - Amount to approve as a decimal string (defaults to maximum approval)\n * @property {ChainId} chainId - ID of the chain where the approval will occur\n */\ninterface PrepareApproveWithdrawOrderTxDataParams {\n yieldType: YieldType;\n wantAssetAddress: Address;\n withdrawAmount?: string;\n chainId: ChainId;\n /** Pre-fetched vault share decimals (avoids redundant RPC call) */\n shareDecimals?: number;\n}\n\n/**\n * Result object containing transaction data for a vault shares approval operation (vault shares token)\n * @interface ApproveWithdrawOrderTxData\n * @property {typeof BoringVaultAbi} abi - ABI for the BoringVault contract (vault shares token)\n * @property {Address} address - Address of the BoringVault (vault shares token)\n * @property {'approve'} functionName - Name of the function to call\n * @property {[Address, bigint]} args - Arguments for the approve function:\n * [spender (WithdrawQueue address), amount]\n */\ninterface ApproveWithdrawOrderTxData {\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 WithdrawQueue contract\n *\n * This function prepares an ERC20 approval transaction that allows the WithdrawQueue\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 prepareApproveWithdrawOrderTxData({\n * yieldType: 'CORE',\n * wantAssetAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC\n * withdrawAmount: \"10.0\", // Approve 10 USDC\n * chainId: 1,\n * });\n * ```\n *\n * @param {PrepareApproveWithdrawOrderTxDataParams} params - Parameters for the approval operation\n * @param {YieldType} params.yieldType - Yield strategy type (CORE, TREASURY, or FRONTIER)\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<ApproveWithdrawOrderTxData>} 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 prepareApproveWithdrawOrderTxData({\n yieldType,\n wantAssetAddress,\n withdrawAmount,\n chainId,\n shareDecimals,\n}: PrepareApproveWithdrawOrderTxDataParams): Promise<ApproveWithdrawOrderTxData> {\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: \"prepareApproveWithdrawOrderTxData\" }\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: \"prepareApproveWithdrawOrderTxData\" }\n );\n }\n if (!config.vault.withdrawQueueAddress) {\n throw new APIError(\n `WithdrawQueue contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareApproveWithdrawOrderTxData\" }\n );\n }\n\n const boringVaultAddress = config.vault.boringVaultAddress;\n const withdrawQueueAddress = config.vault.withdrawQueueAddress;\n\n // Resolve vault share decimals:\n // Use pre-fetched value if provided, otherwise read from chain\n const decimals =\n shareDecimals ??\n (await getErc20Decimals({\n tokenAddress: boringVaultAddress,\n chainId: normalizedChainId,\n }));\n\n const withdrawAmountAsBigInt = withdrawAmount\n ? parseUnits(withdrawAmount, decimals)\n : DEFAULT_APPROVAL_AMOUNT;\n\n return {\n abi: BoringVaultAbi,\n address: boringVaultAddress,\n functionName: \"approve\",\n args: [withdrawQueueAddress, 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: \"prepareApproveWithdrawOrderTxData\",\n cause: error,\n }\n );\n }\n}\n\nexport type {\n ApproveWithdrawOrderTxData,\n PrepareApproveWithdrawOrderTxDataParams,\n};\n","/**\n * @file Cancel withdrawal order functionality for WithdrawQueue contract\n * @module vaults/withdraw/cancel-withdraw\n */\n\nimport type { Address } from \"viem\";\nimport { WithdrawQueueAbi } from \"../../abi/withdraw-queue-abi\";\nimport { findVaultByConfig } from \"../../client/amplify-sdk-client\";\nimport { APIError, type YieldType } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\n\n/**\n * Parameters for preparing a cancel withdrawal order transaction\n *\n * @interface PrepareCancelWithdrawOrderTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (CORE, TREASURY, or FRONTIER)\n * @property {Address} wantAsset - Address of the want token (used to find the correct vault/queue)\n * @property {ChainId} chainId - ID of the chain where the order exists\n * @property {bigint} orderIndex - Index of the order to cancel (provided by user)\n */\ninterface PrepareCancelWithdrawOrderTxDataParams {\n yieldType: YieldType;\n wantAsset: Address;\n chainId: ChainId;\n orderIndex: bigint;\n}\n\n/**\n * Transaction data for canceling a withdrawal order on the WithdrawQueue contract\n *\n * Ready-to-use transaction data that can be passed directly to viem's writeContract\n * or wagmi's useWriteContract hook.\n *\n * @interface CancelWithdrawOrderTxData\n */\ninterface CancelWithdrawOrderTxData {\n abi: typeof WithdrawQueueAbi;\n address: Address;\n functionName: \"cancelOrder\";\n args: [orderIndex: bigint];\n chainId: number;\n}\n\n/**\n * Prepares transaction data to cancel a withdrawal order on the WithdrawQueue contract\n *\n * This function prepares the transaction to cancel an existing order in the queue.\n * Only the order owner can cancel their order.\n *\n * @param {PrepareCancelWithdrawOrderTxDataParams} params - Parameters for the cancel operation\n * @returns {Promise<CancelWithdrawOrderTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not found, chain mismatch, or contracts not configured\n *\n * @example\n * ```typescript\n * import { prepareCancelWithdrawOrderTxData } from \"@paxoslabs/amplify-sdk\";\n *\n * const txData = await prepareCancelWithdrawOrderTxData({\n * yieldType: \"CORE\",\n * wantAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * chainId: 1,\n * orderIndex: 42n, // The order index to cancel\n * });\n *\n * // Execute with viem\n * const hash = await walletClient.writeContract(txData);\n *\n * // Or with wagmi\n * const { writeContract } = useWriteContract();\n * await writeContract(txData);\n * ```\n */\nconst prepareCancelWithdrawOrderTxData = async ({\n yieldType,\n wantAsset,\n chainId,\n orderIndex,\n}: PrepareCancelWithdrawOrderTxDataParams): Promise<CancelWithdrawOrderTxData> => {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n assetAddress: wantAsset,\n yieldType,\n chainId: normalizedChainId,\n });\n\n // Validation: Ensure vault exists\n if (!config) {\n throw new APIError(\n `No vault found for asset ${wantAsset} with yield type '${yieldType}' on chain ${normalizedChainId}`,\n { endpoint: \"prepareCancelWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure vault is on the correct chain\n if (config.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${config.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareCancelWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure withdrawQueueAddress is configured\n if (!config.vault.withdrawQueueAddress) {\n throw new APIError(\n `WithdrawQueue contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareCancelWithdrawOrderTxData\" }\n );\n }\n\n return {\n abi: WithdrawQueueAbi,\n address: config.vault.withdrawQueueAddress,\n functionName: \"cancelOrder\",\n args: [orderIndex],\n chainId: normalizedChainId,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to prepare cancel order transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareCancelWithdrawOrderTxData\",\n cause: error,\n }\n );\n }\n};\n\nexport { prepareCancelWithdrawOrderTxData };\nexport type {\n CancelWithdrawOrderTxData,\n PrepareCancelWithdrawOrderTxDataParams,\n};\n","/**\n * @file Standard withdrawal functionality for WithdrawQueue contract\n * @module vaults/withdraw/standard-withdraw\n */\n\nimport { type Address, parseUnits } from \"viem\";\nimport { WithdrawQueueAbi } from \"../../abi/withdraw-queue-abi\";\nimport { getErc20Decimals } from \"../../api/erc20\";\nimport { findVaultByConfig } from \"../../client/amplify-sdk-client\";\nimport { APIError, type YieldType } from \"../../types/amplify-sdk-api\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\n\n/**\n * Approval method enum for WithdrawQueue signature params\n * Maps to contract's ApprovalMethod enum\n */\nconst ApprovalMethod = {\n /** Standard ERC20 approve (user has pre-approved via approve()) */\n EIP20_APPROVE: 0,\n /** EIP-2612 permit signature */\n EIP2612_APPROVE: 1,\n} as const;\n\n/**\n * Empty signature params for submitOrder when no permit/signature is used\n *\n * The contract expects this struct even when using pre-approved allowance.\n * ApprovalMethod enum: 0 = NONE, 1 = PERMIT, 2 = ALLOWANCE\n */\nconst EMPTY_SIGNATURE_PARAMS = {\n approvalMethod: ApprovalMethod.EIP20_APPROVE,\n approvalV: 0,\n approvalR:\n \"0x0000000000000000000000000000000000000000000000000000000000000000\" as `0x${string}`,\n approvalS:\n \"0x0000000000000000000000000000000000000000000000000000000000000000\" as `0x${string}`,\n submitWithSignature: false,\n deadline: 0n,\n eip2612Signature: \"0x\" as `0x${string}`,\n} as const;\n\n/**\n * Parameters for preparing a submit order transaction\n *\n * @interface PrepareWithdrawOrderTxDataParams\n * @property {YieldType} yieldType - Yield strategy type (CORE, TREASURY, or FRONTIER)\n * @property {Address} wantAsset - Address of the token to receive upon withdrawal\n * @property {Address} userAddress - User's wallet address (used for intendedDepositor, receiver, refundReceiver)\n * @property {ChainId} chainId - ID of the chain where the withdrawal will occur\n * @property {string} amountOffer - Amount of vault shares to withdraw as a decimal string\n */\ninterface PrepareWithdrawOrderTxDataParams {\n yieldType: YieldType;\n wantAsset: Address;\n userAddress: Address;\n chainId: ChainId;\n amountOffer: string;\n}\n\n/**\n * Transaction data for submitting a withdrawal order to the WithdrawQueue contract\n *\n * Ready-to-use transaction data that can be passed directly to viem's writeContract\n * or wagmi's useWriteContract hook.\n *\n * @interface WithdrawOrderTxData\n */\ninterface WithdrawOrderTxData {\n abi: typeof WithdrawQueueAbi;\n address: Address;\n functionName: \"submitOrder\";\n args: [\n {\n amountOffer: bigint;\n wantAsset: Address;\n intendedDepositor: Address;\n receiver: Address;\n refundReceiver: Address;\n signatureParams: typeof EMPTY_SIGNATURE_PARAMS;\n },\n ];\n chainId: number;\n}\n\n/**\n * Prepares transaction data to submit a withdrawal order to the WithdrawQueue contract\n *\n * This function prepares a user request for the new WithdrawQueue contract.\n * Unlike the old AtomicQueue, this does not require exchange rate queries or slippage parameters.\n * It intentionally does not perform allowance pre-checks; callers should use\n * `prepareWithdrawalAuthorization` when they need approval routing.\n *\n * @param {PrepareWithdrawOrderTxDataParams} params - Parameters for the withdraw operation\n * @returns {Promise<WithdrawOrderTxData>} Promise resolving to the prepared transaction data\n * @throws {APIError} If the vault is not found, chain mismatch, or contracts not configured\n *\n * @example\n * ```typescript\n * import { prepareWithdrawOrderTxData } from \"@paxoslabs/amplify-sdk\";\n *\n * const txData = await prepareWithdrawOrderTxData({\n * yieldType: \"CORE\",\n * wantAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", // USDC\n * userAddress: \"0x1234...\",\n * chainId: 1,\n * amountOffer: \"1.0\", // 1 vault share\n * });\n *\n * // Execute with viem\n * const hash = await walletClient.writeContract(txData);\n *\n * // Or with wagmi\n * const { writeContract } = useWriteContract();\n * await writeContract(txData);\n * ```\n */\nconst prepareWithdrawOrderTxData = async ({\n yieldType,\n wantAsset,\n userAddress,\n chainId,\n amountOffer,\n}: PrepareWithdrawOrderTxDataParams): Promise<WithdrawOrderTxData> => {\n try {\n const normalizedChainId = toChainId(chainId);\n\n const config = await findVaultByConfig({\n assetAddress: wantAsset,\n yieldType,\n chainId: normalizedChainId,\n });\n\n\n // Validation: Ensure vault exists\n if (!config) {\n throw new APIError(\n `No vault found for asset ${wantAsset} with yield type '${yieldType}' on chain ${normalizedChainId}`,\n { endpoint: \"prepareWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure vault is on the correct chain\n if (config.chainId !== normalizedChainId) {\n throw new APIError(\n `Vault chain mismatch: vault is on chain ${config.chainId}, requested chain ${normalizedChainId}`,\n { endpoint: \"prepareWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure withdrawQueueAddress is configured\n if (!config.vault.withdrawQueueAddress) {\n throw new APIError(\n `WithdrawQueue contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareWithdrawOrderTxData\" }\n );\n }\n\n // Validation: Ensure boringVaultAddress is configured (needed for share decimals)\n if (!config.vault.boringVaultAddress) {\n throw new APIError(\n `BoringVault contract address not configured for vault ${config.id}`,\n { endpoint: \"prepareWithdrawOrderTxData\" }\n );\n }\n\n // Get vault share decimals from the BoringVault contract\n const sharesDecimals = await getErc20Decimals({\n tokenAddress: config.vault.boringVaultAddress,\n chainId: normalizedChainId,\n });\n\n // Parse offer amount using vault share decimals\n const formattedAmountOffer = parseUnits(amountOffer, sharesDecimals);\n\n return {\n abi: WithdrawQueueAbi,\n address: config.vault.withdrawQueueAddress,\n functionName: \"submitOrder\",\n args: [\n {\n amountOffer: formattedAmountOffer,\n wantAsset,\n intendedDepositor: userAddress,\n receiver: userAddress,\n refundReceiver: userAddress,\n signatureParams: EMPTY_SIGNATURE_PARAMS,\n },\n ],\n chainId: normalizedChainId,\n };\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to prepare withdraw order transaction: ${error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareWithdrawOrderTxData\",\n cause: error,\n }\n );\n }\n};\n\nexport { prepareWithdrawOrderTxData };\nexport type { PrepareWithdrawOrderTxDataParams, WithdrawOrderTxData };\n","/**\n * @file Unified withdrawal module with wrapper functions\n * @module vaults/withdraw\n *\n * Provides high-level wrapper functions for withdrawal authorization:\n * - `prepareWithdrawal`: Unified withdrawal preparation wrapper\n * - `prepareWithdrawalAuthorization`: Determines if approval is needed\n */\n\nimport { type Address, parseUnits } from \"viem\";\nimport { findVaultByConfig } from \"../../client/amplify-sdk-client\";\nimport type { YieldType } from \"../../types/amplify-sdk-api\";\nimport { APIError } from \"../../types/amplify-sdk-api\";\nimport { isWithdrawalSpendApproved } from \"../../utils/approvals\";\nimport { type ChainId, toChainId } from \"../../utils/chain-utils\";\nimport { isSmartContractWallet } from \"../../utils/wallet\";\nimport {\n type ApproveWithdrawOrderTxData,\n prepareApproveWithdrawOrderTxData,\n} from \"./approve-withdraw\";\nimport {\n type WithdrawOrderTxData,\n prepareWithdrawOrderTxData,\n} from \"./standard-withdraw\";\n\n// ============================================================================\n// ENUMS\n// ============================================================================\n\n/**\n * Authorization methods for withdrawal operations\n *\n * Withdrawals do not support EIP-2612 permit — only two paths:\n * - APPROVAL: ERC20 approval of vault shares to WithdrawQueue\n * - ALREADY_APPROVED: Existing allowance is sufficient\n *\n * @example\n * ```typescript\n * import { WithdrawAuthMethod } from \"@paxoslabs/amplify-sdk\";\n *\n * if (result.method === WithdrawAuthMethod.ALREADY_APPROVED) {\n * // Proceed directly to withdrawal\n * }\n * ```\n */\nexport const WithdrawAuthMethod = {\n APPROVAL: \"approval\",\n ALREADY_APPROVED: \"already_approved\",\n} as const;\n\nexport type WithdrawAuthMethod =\n (typeof WithdrawAuthMethod)[keyof typeof WithdrawAuthMethod];\n\n// ============================================================================\n// TYPE DEFINITIONS - Authorization\n// ============================================================================\n\n/**\n * Approval authorization result\n * Returned when an ERC20 approval transaction is needed\n */\nexport interface WithdrawApprovalAuthorizationResult {\n method: typeof WithdrawAuthMethod.APPROVAL;\n /** Transaction data for ERC20 approve() call on vault shares */\n txData: ApproveWithdrawOrderTxData;\n}\n\n/**\n * Already approved authorization result\n * Returned when existing allowance is sufficient for the withdrawal\n */\nexport interface WithdrawAlreadyApprovedAuthorizationResult {\n method: typeof WithdrawAuthMethod.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 withdrawal authorization result types\n *\n * Use type guards or type narrowing with `result.method`:\n *\n * @example Using type guards (recommended)\n * ```typescript\n * import {\n * prepareWithdrawalAuthorization,\n * isWithdrawApprovalAuth,\n * isWithdrawAlreadyApprovedAuth,\n * } from \"@paxoslabs/amplify-sdk\";\n *\n * const result = await prepareWithdrawalAuthorization({...});\n *\n * if (isWithdrawApprovalAuth(result)) {\n * await writeContract(result.txData);\n * } else if (isWithdrawAlreadyApprovedAuth(result)) {\n * console.log(`Already approved: ${result.allowance}`);\n * }\n * ```\n */\nexport type WithdrawAuthorizationResult =\n | WithdrawApprovalAuthorizationResult\n | WithdrawAlreadyApprovedAuthorizationResult;\n\n// ============================================================================\n// TYPE GUARDS\n// ============================================================================\n\n/**\n * Type guard for approval authorization result\n *\n * @param result - Authorization result to check\n * @returns true if result requires an ERC20 approval transaction\n */\nexport function isWithdrawApprovalAuth(\n result: WithdrawAuthorizationResult\n): result is WithdrawApprovalAuthorizationResult {\n return result.method === WithdrawAuthMethod.APPROVAL;\n}\n\n/**\n * Type guard for already-approved authorization result\n *\n * @param result - Authorization result to check\n * @returns true if existing allowance is sufficient\n */\nexport function isWithdrawAlreadyApprovedAuth(\n result: WithdrawAuthorizationResult\n): result is WithdrawAlreadyApprovedAuthorizationResult {\n return result.method === WithdrawAuthMethod.ALREADY_APPROVED;\n}\n\n// ============================================================================\n// PARAMETERS\n// ============================================================================\n\n/**\n * Parameters for prepareWithdrawalAuthorization\n */\nexport interface PrepareWithdrawalAuthorizationParams {\n /** Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\") */\n yieldType: YieldType;\n /** Token address the user wants to receive upon withdrawal */\n wantAsset: Address;\n /** Amount of vault shares to withdraw as decimal string */\n withdrawAmount: string;\n /** User's wallet address (owner of vault shares) */\n userAddress: Address;\n /** Blockchain network ID */\n chainId: ChainId;\n /**\n * Force specific authorization routing behavior:\n * - \"approval\": Always return approval tx data\n * - \"allowance_check\": Always check allowance (skip smart-wallet heuristic)\n */\n forceMethod?: \"approval\" | \"allowance_check\";\n}\n\n/**\n * Parameters for prepareWithdrawal\n * Unified withdrawal wrapper that maps to standard withdraw tx preparation.\n */\nexport interface PrepareWithdrawalParams {\n /** Yield strategy type (e.g., \"CORE\", \"TREASURY\", \"FRONTIER\") */\n yieldType: YieldType;\n /** Token address the user wants to receive upon withdrawal */\n wantAsset: Address;\n /** Amount of vault shares to withdraw as decimal string */\n withdrawAmount: string;\n /** User's wallet address (owner of vault shares) */\n userAddress: Address;\n /** Blockchain network ID */\n chainId: ChainId;\n}\n\n/**\n * Unified withdrawal result\n * Currently routes to standard WithdrawQueue order preparation.\n */\nexport type PrepareWithdrawalResult = WithdrawOrderTxData;\n\n// ============================================================================\n// FUNCTIONS\n// ============================================================================\n\n/**\n * Unified withdrawal preparation wrapper\n *\n * Provides a stable high-level API for withdrawal execution while reusing\n * the low-level WithdrawQueue transaction builder under the hood.\n *\n * @param params - Withdrawal parameters\n * @returns Transaction data for submitOrder on WithdrawQueue\n * @throws {APIError} If preparation fails\n */\nexport async function prepareWithdrawal(\n params: PrepareWithdrawalParams,\n): Promise<PrepareWithdrawalResult> {\n const { yieldType, wantAsset, withdrawAmount, userAddress, chainId } =\n params;\n\n try {\n return await prepareWithdrawOrderTxData({\n yieldType,\n wantAsset,\n userAddress,\n chainId,\n amountOffer: withdrawAmount,\n });\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n throw new APIError(\n `Failed to prepare withdrawal: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareWithdrawal\",\n cause: error,\n },\n );\n }\n}\n\n/**\n * Prepares authorization for a withdrawal operation\n *\n * Determines if the user needs to approve vault shares for the\n * WithdrawQueue contract:\n * 1. Optional force override (`forceMethod`)\n * 2. Auto smart-wallet heuristic (returns approval for smart wallets)\n * 3. Check existing allowance → if sufficient, return \"already approved\"\n * 4. Otherwise → return approval transaction data\n *\n * @param params - Authorization parameters\n * @returns Discriminated union of authorization results\n * @throws {APIError} If vault not found or approval check fails\n *\n * @example\n * ```typescript\n * import {\n * prepareWithdrawalAuthorization,\n * WithdrawAuthMethod,\n * } from \"@paxoslabs/amplify-sdk\";\n *\n * const authResult = await prepareWithdrawalAuthorization({\n * yieldType: \"CORE\",\n * wantAsset: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n * withdrawAmount: \"1.0\",\n * userAddress: \"0x1234...\",\n * chainId: 1,\n * });\n *\n * if (authResult.method === WithdrawAuthMethod.APPROVAL) {\n * await writeContract(authResult.txData);\n * // Wait for confirmation, then submit withdraw order\n * } else {\n * // Already approved, proceed to withdrawal\n * }\n * ```\n */\nexport async function prepareWithdrawalAuthorization(\n params: PrepareWithdrawalAuthorizationParams\n): Promise<WithdrawAuthorizationResult> {\n const {\n yieldType,\n wantAsset,\n withdrawAmount,\n userAddress,\n chainId,\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: wantAsset,\n yieldType,\n chainId: normalizedChainId,\n });\n\n if (!vault) {\n throw new APIError(\n `No vault found for asset ${wantAsset} with yield type '${yieldType}' on chain ${normalizedChainId}`,\n { endpoint: \"prepareWithdrawalAuthorization\" },\n );\n }\n\n // Force override: always return approval tx data.\n if (forceMethod === \"approval\") {\n const txData = await prepareApproveWithdrawOrderTxData({\n yieldType,\n wantAssetAddress: wantAsset,\n withdrawAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: WithdrawAuthMethod.APPROVAL,\n txData,\n };\n }\n\n // Smart contract wallets (e.g. Safe, EIP-4337, EIP-7702) can batch\n // approve + withdraw atomically. In auto mode, skip allowance checks\n // and return approval tx data directly.\n if (forceMethod !== \"allowance_check\") {\n const smartWallet = await isSmartContractWallet(\n userAddress,\n normalizedChainId,\n );\n\n if (smartWallet) {\n const txData = await prepareApproveWithdrawOrderTxData({\n yieldType,\n wantAssetAddress: wantAsset,\n withdrawAmount,\n chainId: normalizedChainId,\n });\n\n return {\n method: WithdrawAuthMethod.APPROVAL,\n txData,\n };\n }\n }\n\n // Check current withdrawal approval status\n const approvalInfo = await isWithdrawalSpendApproved({\n yieldType,\n chainId: normalizedChainId,\n wantAssetAddress: wantAsset,\n recipientAddress: userAddress,\n });\n\n // Handle multicall failure\n if (approvalInfo.error) {\n throw new APIError(\n `Failed to check withdrawal approval: ${approvalInfo.error}`,\n { endpoint: \"prepareWithdrawalAuthorization\" },\n );\n }\n\n // Parse withdraw amount to compare against allowance\n const decimals =\n typeof approvalInfo.decimals === \"string\"\n ? Number(approvalInfo.decimals)\n : approvalInfo.decimals;\n const withdrawAmountBigInt = parseUnits(withdrawAmount, decimals);\n const currentAllowanceBigInt = BigInt(\n approvalInfo.allowanceAsBigInt,\n );\n\n // Check if existing allowance is sufficient\n if (\n approvalInfo.isApproved &&\n currentAllowanceBigInt >= withdrawAmountBigInt\n ) {\n return {\n method: WithdrawAuthMethod.ALREADY_APPROVED,\n allowance: approvalInfo.allowance,\n allowanceAsBigInt: approvalInfo.allowanceAsBigInt,\n };\n }\n\n // Insufficient allowance: prepare approval transaction\n // Pass share decimals to avoid redundant RPC call\n const txData = await prepareApproveWithdrawOrderTxData({\n yieldType,\n wantAssetAddress: wantAsset,\n withdrawAmount,\n chainId: normalizedChainId,\n shareDecimals: decimals,\n });\n\n return {\n method: WithdrawAuthMethod.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 withdrawal authorization: ${\n error instanceof Error ? error.message : String(error)\n }`,\n {\n endpoint: \"prepareWithdrawalAuthorization\",\n cause: error,\n },\n );\n }\n}\n\n// ============================================================================\n// RE-EXPORTS\n// ============================================================================\n\nexport type {\n ApproveWithdrawOrderTxData,\n PrepareApproveWithdrawOrderTxDataParams,\n} from \"./approve-withdraw\";\nexport { prepareApproveWithdrawOrderTxData } from \"./approve-withdraw\";\nexport type {\n CancelWithdrawOrderTxData,\n PrepareCancelWithdrawOrderTxDataParams,\n} from \"./cancel-withdraw\";\nexport { prepareCancelWithdrawOrderTxData } from \"./cancel-withdraw\";\nexport type {\n PrepareWithdrawOrderTxDataParams,\n WithdrawOrderTxData,\n} from \"./standard-withdraw\";\nexport { prepareWithdrawOrderTxData } from \"./standard-withdraw\";\n"]}