@zyfai/sdk 0.9.0 → 0.11.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.
package/dist/index.js CHANGED
@@ -34,6 +34,7 @@ __export(index_exports, {
34
34
  API_ENDPOINT: () => API_ENDPOINT,
35
35
  DATA_API_BASE_URLS: () => DATA_API_BASE_URLS,
36
36
  DATA_API_ENDPOINT: () => DATA_API_ENDPOINT,
37
+ DEFAULT_RELAY_SLIPPAGE_BPS: () => DEFAULT_RELAY_SLIPPAGE_BPS,
37
38
  DEFAULT_TOKEN_ADDRESSES: () => DEFAULT_TOKEN_ADDRESSES,
38
39
  ERC7579_LAUNCHPAD_ADDRESS: () => ERC7579_LAUNCHPAD_ADDRESS,
39
40
  EXECUTION_API_BASE_URLS: () => EXECUTION_API_BASE_URLS,
@@ -42,9 +43,11 @@ __export(index_exports, {
42
43
  LOCAL_DATA_API_BASE_URL: () => LOCAL_DATA_API_BASE_URL,
43
44
  LOCAL_EXECUTION_API_BASE_URL: () => LOCAL_EXECUTION_API_BASE_URL,
44
45
  LOCAL_WS_URL: () => LOCAL_WS_URL,
46
+ MAX_RELAY_SLIPPAGE_BPS: () => MAX_RELAY_SLIPPAGE_BPS,
45
47
  OWNABLE_VALIDATOR: () => OWNABLE_VALIDATOR,
46
48
  POOL_MODULE_ADDRESSES: () => POOL_MODULE_ADDRESSES,
47
49
  PROXY_EXECUTOR: () => PROXY_EXECUTOR,
50
+ RELAY_SLIPPAGE_PRESETS_BPS: () => RELAY_SLIPPAGE_PRESETS_BPS,
48
51
  SAFE_7579_ADDRESS: () => SAFE_7579_ADDRESS,
49
52
  SMART_SESSIONS_FALLBACK: () => SMART_SESSIONS_FALLBACK,
50
53
  SMART_SESSIONS_VALIDATOR: () => SMART_SESSIONS_VALIDATOR,
@@ -63,7 +66,9 @@ __export(index_exports, {
63
66
  getManagedAssets: () => getManagedAssets,
64
67
  getSupportedChainIds: () => getSupportedChainIds,
65
68
  getWsUrl: () => getWsUrl,
66
- isSupportedChain: () => isSupportedChain
69
+ isSupportedChain: () => isSupportedChain,
70
+ resolveDepositRoute: () => resolveDepositRoute,
71
+ resolveRelaySlippageBps: () => resolveRelaySlippageBps
67
72
  });
68
73
  module.exports = __toCommonJS(index_exports);
69
74
 
@@ -120,10 +125,15 @@ var ENDPOINTS = {
120
125
  USER_AGENT_DEPOSIT_INTENT_CONSUME: (actionId) => `/users/me/agent-deposit-intents/${encodeURIComponent(actionId)}/consume`,
121
126
  USER_AGENT_DEPOSIT_INTENT_COMPLETE: (actionId) => `/users/me/agent-deposit-intents/${encodeURIComponent(actionId)}/complete`,
122
127
  AGENT_DEPOSIT_INTENT_RESOLVE: "/agent-deposit-intents/resolve",
123
- USER_WITHDRAW: "/users/withdraw",
124
- PARTIAL_WITHDRAW: "/users/partial-withdraw",
128
+ USER_WITHDRAW: "/users/withdraw/v2",
129
+ PARTIAL_WITHDRAW: "/users/partial-withdraw/v2",
125
130
  LOG_DEPOSIT: "/users/log_deposit/v2",
126
- DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}`,
131
+ FUNDING_ORDERS: "/users/me/funding-orders",
132
+ FUNDING_ORDER: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}`,
133
+ FUNDING_ORDER_QUOTE: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/quote`,
134
+ FUNDING_ORDER_EXECUTION: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/execution`,
135
+ DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}/v2`,
136
+ WITHDRAW_STATUS: (withdrawalId) => `/users/withdrawals/${withdrawalId}`,
127
137
  // Safe Deployment (single endpoint)
128
138
  SAFE_DEPLOY: "/users/safe-deploy",
129
139
  // Multichain deploy for predeployed (pool) wallets — deploys + rotates the
@@ -450,6 +460,11 @@ function sleep(ms) {
450
460
  return new Promise((resolve) => setTimeout(resolve, ms));
451
461
  }
452
462
 
463
+ // src/utils/withdraw-lifecycle-polling.ts
464
+ function isWithdrawSettlementTerminal(status) {
465
+ return status === "completed" || status === "async_cooldown" || status === "async_claiming";
466
+ }
467
+
453
468
  // src/utils/token-price.ts
454
469
  var PRICE_SCALE = 8;
455
470
  var parseTokenUsdPrice = (response) => {
@@ -548,6 +563,15 @@ var ERC20_ABI = [
548
563
  outputs: [{ name: "", type: "uint256" }]
549
564
  }
550
565
  ];
566
+ var WETH_DEPOSIT_ABI = [
567
+ {
568
+ name: "deposit",
569
+ type: "function",
570
+ stateMutability: "payable",
571
+ inputs: [],
572
+ outputs: []
573
+ }
574
+ ];
551
575
  var ERC20_TRANSFER_LEGACY_ABI = [
552
576
  {
553
577
  name: "transfer",
@@ -712,12 +736,39 @@ var DEPOSIT_CREDIT_TIMEOUT_MS = {
712
736
  };
713
737
  var getDepositCreditIntervalMs = (chainId) => DEPOSIT_CREDIT_INTERVAL_MS[chainId];
714
738
  var getDepositCreditTimeoutMs = (chainId) => DEPOSIT_CREDIT_TIMEOUT_MS[chainId];
739
+ var USER_OP_LIFECYCLE_INTERVAL_MS = {
740
+ 1: 4e3,
741
+ 8453: 1e3,
742
+ 42161: 1e3
743
+ };
744
+ var USER_OP_LIFECYCLE_TIMEOUT_MS = {
745
+ 1: 18e4,
746
+ 8453: 9e4,
747
+ 42161: 9e4
748
+ };
749
+ var ASYNC_WITHDRAW_COOLDOWN_POLL_INTERVAL_MS = 6e4;
750
+ var ASYNC_WITHDRAW_CLAIM_GRACE_MS = 6 * 60 * 60 * 1e3;
751
+ var getUserOpLifecycleIntervalMs = (chainId) => USER_OP_LIFECYCLE_INTERVAL_MS[chainId];
752
+ var getUserOpLifecycleTimeoutMs = (chainId) => USER_OP_LIFECYCLE_TIMEOUT_MS[chainId];
753
+ function nextWithdrawCompleteDeadline(startedAt, previousDeadline, estimatedClaimAt, options) {
754
+ if (options.explicitTimeoutMs != null) {
755
+ return startedAt + options.explicitTimeoutMs;
756
+ }
757
+ let deadline = previousDeadline ?? startedAt + options.fallbackMs;
758
+ if (estimatedClaimAt) {
759
+ const claimAt = Date.parse(estimatedClaimAt);
760
+ if (!Number.isNaN(claimAt)) {
761
+ deadline = Math.max(deadline, claimAt + options.graceMs);
762
+ }
763
+ }
764
+ return deadline;
765
+ }
715
766
  var AGENT_DEPOSIT_INTENT_INTERVAL_MS = 1500;
716
767
  var AGENT_DEPOSIT_INTENT_TIMEOUT_MS = 30 * 60 * 1e3;
717
768
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
718
- const base2 = 10n ** BigInt(decimals);
719
- const whole = raw / base2;
720
- const fraction = raw % base2;
769
+ const base3 = 10n ** BigInt(decimals);
770
+ const whole = raw / base3;
771
+ const fraction = raw % base3;
721
772
  if (fraction === 0n) {
722
773
  return `${whole.toString()} ${symbol}`;
723
774
  }
@@ -772,6 +823,7 @@ function isMainnetMinPortfolioExempt(chainId, ...addresses) {
772
823
  // src/core/ZyfaiSDK.ts
773
824
  var import_accounts2 = require("viem/accounts");
774
825
  var import_viem4 = require("viem");
826
+ var import_relay_sdk2 = require("@relayprotocol/relay-sdk");
775
827
 
776
828
  // src/config/chains.ts
777
829
  var import_viem2 = require("viem");
@@ -966,6 +1018,228 @@ var getSupportedChainIds = () => {
966
1018
  return Object.keys(CHAINS).map(Number);
967
1019
  };
968
1020
 
1021
+ // src/deposits/deposit-route.ts
1022
+ var NATIVE_CURRENCY = "0x0000000000000000000000000000000000000000";
1023
+ var RELAY_DESTINATION_ASSETS = [
1024
+ "USDC",
1025
+ "WETH",
1026
+ "CBBTC",
1027
+ "WBTC",
1028
+ "EURC",
1029
+ "USDT",
1030
+ "PYUSD",
1031
+ "NVDAC",
1032
+ "GOOGLC",
1033
+ "AAPLC",
1034
+ "METAC"
1035
+ ];
1036
+ var lookupCollateral = (asset) => Object.keys(ASSET_CONFIGS).find(
1037
+ (key) => key.toLowerCase() === asset.toLowerCase()
1038
+ ) ?? null;
1039
+ var toRelayDestinationAsset = (asset) => asset.trim().toUpperCase();
1040
+ var isNativeSpendToken = (token) => {
1041
+ const value = token.trim().toLowerCase();
1042
+ return value === "eth" || value === "native" || value === NATIVE_CURRENCY;
1043
+ };
1044
+ var isSameCollateralToken = (spend, collateral, chainId) => {
1045
+ if (spend.toLowerCase() === collateral.toLowerCase()) return true;
1046
+ const address = ASSET_CONFIGS[collateral]?.addresses?.[chainId];
1047
+ return !!address && spend.toLowerCase() === address.toLowerCase();
1048
+ };
1049
+ var originCurrencyForSpend = (spend, chainId) => {
1050
+ if (isNativeSpendToken(spend)) return NATIVE_CURRENCY;
1051
+ if (/^0x[0-9a-fA-F]{40}$/.test(spend)) return spend;
1052
+ const collateral = lookupCollateral(spend);
1053
+ if (!collateral) {
1054
+ throw new Error(
1055
+ `spendToken must be a collateral symbol or a token contract address. Received "${spend}".`
1056
+ );
1057
+ }
1058
+ const address = ASSET_CONFIGS[collateral]?.addresses?.[chainId];
1059
+ if (!address) {
1060
+ throw new Error(`${collateral} is not available on chain ${chainId}.`);
1061
+ }
1062
+ return address;
1063
+ };
1064
+ var resolveDepositRoute = (input) => {
1065
+ const asset = input.asset?.trim();
1066
+ if (!asset) throw new Error("Asset is required");
1067
+ const spendChainId = input.spendChainId ?? input.chainId;
1068
+ const collateral = lookupCollateral(asset);
1069
+ const spend = input.spendToken?.trim();
1070
+ const holdsDestinationCollateral = !spend || spendChainId === input.chainId && !!collateral && isSameCollateralToken(spend, collateral, input.chainId);
1071
+ if (holdsDestinationCollateral) {
1072
+ if (!collateral) {
1073
+ throw new Error(
1074
+ `${asset} cannot be transferred directly. Pass spendToken to swap another token into it.`
1075
+ );
1076
+ }
1077
+ const chains = getAssetChainIds(collateral);
1078
+ if (!chains.includes(input.chainId)) {
1079
+ throw new Error(
1080
+ `${collateral} is not available on chain ${input.chainId}. Supported chains: ${chains.join(", ")}.`
1081
+ );
1082
+ }
1083
+ return { kind: "direct", asset: collateral };
1084
+ }
1085
+ if (collateral === "WETH" && spendChainId === input.chainId && spend && isNativeSpendToken(spend)) {
1086
+ return { kind: "wrap", asset: "WETH" };
1087
+ }
1088
+ const destinationAsset = toRelayDestinationAsset(asset);
1089
+ if (!RELAY_DESTINATION_ASSETS.includes(
1090
+ destinationAsset
1091
+ )) {
1092
+ throw new Error(
1093
+ `${asset} is not a collateral Relay can deliver. Supported: ${RELAY_DESTINATION_ASSETS.join(", ")}.`
1094
+ );
1095
+ }
1096
+ return {
1097
+ kind: "swap",
1098
+ originChainId: spendChainId,
1099
+ originCurrency: originCurrencyForSpend(spend, spendChainId),
1100
+ destinationAsset
1101
+ };
1102
+ };
1103
+
1104
+ // src/deposits/funding-order-route.ts
1105
+ var sameText = (left, right) => typeof left === "string" && left.trim().toLowerCase() === right.trim().toLowerCase();
1106
+ var assertStoredFundingOrderRoute = (order, requested) => {
1107
+ const mismatches = [];
1108
+ if (order.originChainId !== requested.originChainId) {
1109
+ mismatches.push(
1110
+ `originChainId caller ${requested.originChainId}, stored ${order.originChainId}`
1111
+ );
1112
+ }
1113
+ if (!sameText(order.originCurrency, requested.originCurrency)) {
1114
+ mismatches.push(
1115
+ `originCurrency caller ${requested.originCurrency}, stored ${order.originCurrency}`
1116
+ );
1117
+ }
1118
+ if (order.destinationChainId !== requested.destinationChainId) {
1119
+ mismatches.push(
1120
+ `destinationChainId caller ${requested.destinationChainId}, stored ${order.destinationChainId}`
1121
+ );
1122
+ }
1123
+ if (!sameText(order.destinationAsset, requested.destinationAsset)) {
1124
+ mismatches.push(
1125
+ `destinationAsset caller ${requested.destinationAsset}, stored ${order.destinationAsset}`
1126
+ );
1127
+ }
1128
+ if (mismatches.length === 0) return;
1129
+ throw new Error(
1130
+ `Funding order ${order.id} does not match this swap: ${mismatches.join("; ")}`
1131
+ );
1132
+ };
1133
+
1134
+ // src/deposits/collateral-minimum.ts
1135
+ var positiveUnits = (value) => {
1136
+ if (!value || value === "0") return null;
1137
+ return value;
1138
+ };
1139
+ var resolveCollateralMinimum = (storedMinimum, quote) => positiveUnits(storedMinimum) ?? positiveUnits(quote.details?.currencyOut?.minimumAmount) ?? positiveUnits(quote.details?.currencyOut?.amount) ?? "0";
1140
+
1141
+ // src/deposits/relay-slippage.ts
1142
+ var DEFAULT_RELAY_SLIPPAGE_BPS = 200;
1143
+ var MAX_RELAY_SLIPPAGE_BPS = 500;
1144
+ var RELAY_SLIPPAGE_PRESETS_BPS = [50, 200, 500];
1145
+ var resolveRelaySlippageBps = (clientBps) => {
1146
+ if (clientBps == null || !Number.isFinite(clientBps)) {
1147
+ return DEFAULT_RELAY_SLIPPAGE_BPS;
1148
+ }
1149
+ return Math.min(
1150
+ Math.max(1, Math.trunc(clientBps)),
1151
+ MAX_RELAY_SLIPPAGE_BPS
1152
+ );
1153
+ };
1154
+
1155
+ // src/deposits/relay-client.ts
1156
+ var import_relay_sdk = require("@relayprotocol/relay-sdk");
1157
+ var import_chains3 = require("viem/chains");
1158
+ var RELAY_FUNDING_CHAIN_IDS = [import_chains3.mainnet.id, import_chains3.base.id, import_chains3.arbitrum.id];
1159
+ var clientHasFundingChains = () => {
1160
+ const client = (0, import_relay_sdk.getClient)();
1161
+ if (!client?.baseApiUrl) return false;
1162
+ return RELAY_FUNDING_CHAIN_IDS.every(
1163
+ (chainId) => client.chains.some((chain) => chain.id === chainId)
1164
+ );
1165
+ };
1166
+ var ensureRelaySdkClient = () => {
1167
+ if (clientHasFundingChains()) return;
1168
+ (0, import_relay_sdk.createClient)({
1169
+ baseApiUrl: import_relay_sdk.MAINNET_RELAY_API,
1170
+ source: "zyf.ai",
1171
+ chains: [import_chains3.mainnet, import_chains3.base, import_chains3.arbitrum].map(import_relay_sdk.convertViemChainToRelayChain)
1172
+ });
1173
+ };
1174
+
1175
+ // src/deposits/relay-fill.ts
1176
+ var TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
1177
+ var collectTxHashes = (execution) => {
1178
+ const out = [];
1179
+ for (const step of execution.steps ?? []) {
1180
+ for (const item of step.items ?? []) {
1181
+ for (const row of item.txHashes ?? []) {
1182
+ if (row.txHash) out.push(row);
1183
+ }
1184
+ for (const row of item.internalTxHashes ?? []) {
1185
+ if (row.txHash) out.push(row);
1186
+ }
1187
+ }
1188
+ }
1189
+ return out;
1190
+ };
1191
+ var collectRelaySourceTxHashes = (execution, originChainId) => {
1192
+ const hashes = /* @__PURE__ */ new Set();
1193
+ for (const row of collectTxHashes(execution)) {
1194
+ if (row.chainId === originChainId) hashes.add(row.txHash);
1195
+ }
1196
+ return [...hashes];
1197
+ };
1198
+ var collectRelayDestinationTxHashes = (execution, destinationChainId) => {
1199
+ const hashes = /* @__PURE__ */ new Set();
1200
+ for (const row of collectTxHashes(execution)) {
1201
+ if (row.chainId === destinationChainId && row.txHash) {
1202
+ hashes.add(row.txHash);
1203
+ }
1204
+ }
1205
+ return [...hashes];
1206
+ };
1207
+ var transferAmountTo = (logs, token, recipient) => {
1208
+ const tokenAddr = token.toLowerCase();
1209
+ const recipientAddr = recipient.toLowerCase();
1210
+ let total = 0n;
1211
+ for (const log of logs) {
1212
+ if (log.address.toLowerCase() !== tokenAddr) continue;
1213
+ if (log.topics[0]?.toLowerCase() !== TRANSFER_TOPIC) continue;
1214
+ const toTopic = log.topics[2];
1215
+ if (!toTopic) continue;
1216
+ const to = `0x${toTopic.slice(-40)}`.toLowerCase();
1217
+ if (to !== recipientAddr) continue;
1218
+ try {
1219
+ const value = BigInt(log.data);
1220
+ if (value > 0n) total += value;
1221
+ } catch {
1222
+ }
1223
+ }
1224
+ return total;
1225
+ };
1226
+ var receiptTransfersTokenTo = (logs, token, recipient) => transferAmountTo(logs, token, recipient) > 0n;
1227
+ var selectRelayCreditTxHash = (params) => {
1228
+ const seen = /* @__PURE__ */ new Set();
1229
+ for (const hash of params.candidates) {
1230
+ if (!hash) continue;
1231
+ const key = hash.toLowerCase();
1232
+ if (seen.has(key)) continue;
1233
+ seen.add(key);
1234
+ const receipt = params.receipts.get(key);
1235
+ if (!receipt || receipt.status !== "success") continue;
1236
+ if (receiptTransfersTokenTo(receipt.logs, params.token, params.recipient)) {
1237
+ return hash;
1238
+ }
1239
+ }
1240
+ return null;
1241
+ };
1242
+
969
1243
  // src/config/managed-assets.ts
970
1244
  var MANAGED_ASSET_ORDER = [
971
1245
  "USDC",
@@ -1752,12 +2026,41 @@ var DepositCreditTimeoutError = class extends Error {
1752
2026
  this.name = "DepositCreditTimeoutError";
1753
2027
  }
1754
2028
  };
2029
+ var DepositPositionTimeoutError = class extends Error {
2030
+ constructor(depositId) {
2031
+ super(`Timed out waiting for deposit ${depositId} to reach a position`);
2032
+ this.name = "DepositPositionTimeoutError";
2033
+ }
2034
+ };
2035
+ var WithdrawSettlementTimeoutError = class extends Error {
2036
+ constructor(withdrawalId) {
2037
+ super(
2038
+ `Timed out waiting for withdraw lifecycle ${withdrawalId} to settle`
2039
+ );
2040
+ this.name = "WithdrawSettlementTimeoutError";
2041
+ }
2042
+ };
2043
+ var WithdrawCompleteTimeoutError = class extends Error {
2044
+ constructor(withdrawalId) {
2045
+ super(
2046
+ `Timed out waiting for withdraw lifecycle ${withdrawalId} to complete`
2047
+ );
2048
+ this.name = "WithdrawCompleteTimeoutError";
2049
+ }
2050
+ };
1755
2051
  var AgentDepositIntentTimeoutError = class extends Error {
1756
2052
  constructor(actionId) {
1757
2053
  super(`Timed out waiting for agent deposit intent ${actionId} to complete`);
1758
2054
  this.name = "AgentDepositIntentTimeoutError";
1759
2055
  }
1760
2056
  };
2057
+ var thrownMessage = (error) => {
2058
+ if (error instanceof Error) return error.message;
2059
+ if (error && typeof error === "object" && "message" in error && typeof error.message === "string") {
2060
+ return error.message;
2061
+ }
2062
+ return String(error);
2063
+ };
1761
2064
  var _ZyfaiSDK = class _ZyfaiSDK {
1762
2065
  /**
1763
2066
  * Create an SDK instance bound to a partner API key.
@@ -2944,14 +3247,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2944
3247
  effectiveChains,
2945
3248
  withPools,
2946
3249
  strategy,
2947
- mandateChainId
3250
+ mandateChainId,
3251
+ existingChains
2948
3252
  );
2949
3253
  }
2950
3254
  /**
2951
3255
  * Persist protocol discovery for one asset (user PATCH or agent deposit-setup).
2952
3256
  * @internal
2953
3257
  */
2954
- async persistDiscoveredAssetProfile(asset, effectiveChains, withPools, strategy, agentDepositChainId) {
3258
+ async persistDiscoveredAssetProfile(asset, effectiveChains, withPools, strategy, agentDepositChainId, existingChains = []) {
2955
3259
  const internalAsset = convertAssetInternally(asset);
2956
3260
  const assetSettings = {
2957
3261
  chains: effectiveChains,
@@ -2960,9 +3264,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2960
3264
  if (strategy !== void 0) {
2961
3265
  assetSettings.rebalanceStrategy = toInternalStrategy(strategy);
2962
3266
  }
3267
+ const configureProfile = () => this.updateUserProfile({
3268
+ asset,
3269
+ protocols: withPools,
3270
+ chains: effectiveChains,
3271
+ ...strategy !== void 0 && { strategy }
3272
+ });
2963
3273
  if (this.sessionChannel === "agent") {
2964
3274
  const chainId = agentDepositChainId ?? effectiveChains[effectiveChains.length - 1] ?? effectiveChains[0];
2965
- await this.httpClient.post(
3275
+ if (existingChains.includes(chainId)) {
3276
+ return await configureProfile();
3277
+ }
3278
+ const setupResult = await this.httpClient.post(
2966
3279
  ENDPOINTS.AGENT_DEPOSIT_SETUP,
2967
3280
  {
2968
3281
  asset,
@@ -2973,14 +3286,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2973
3286
  }
2974
3287
  }
2975
3288
  );
3289
+ if (!setupResult.applied) {
3290
+ throw new Error(
3291
+ `Agent deposit setup did not apply for ${asset} on chain ${chainId}.`
3292
+ );
3293
+ }
2976
3294
  return await this.getUserDetails(asset);
2977
3295
  }
2978
- return await this.updateUserProfile({
2979
- asset,
2980
- protocols: withPools,
2981
- chains: effectiveChains,
2982
- ...strategy !== void 0 && { strategy }
2983
- });
3296
+ return await configureProfile();
2984
3297
  }
2985
3298
  /**
2986
3299
  * Switch one asset to a strategy and select the protocols that go with it.
@@ -3215,14 +3528,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3215
3528
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
3216
3529
  }
3217
3530
  /**
3218
- * Transfer funds from the connected EOA to the user's Safe and register the deposit.
3531
+ * Transfer a collateral token the wallet already holds into the Safe.
3219
3532
  *
3220
3533
  * @remarks
3221
- * Execution API + on-chain ERC-20 `transfer`. Confirms the transaction, then calls
3222
- * {@link ZyfaiSDK.logDeposit}. Pair with {@link ZyfaiSDK.waitForDepositCredit} for
3223
- * investable balance. Custom-wallet flows: {@link ZyfaiSDK.buildDepositTransfer},
3224
- * {@link ZyfaiSDK.logDeposit}, {@link ZyfaiSDK.getDepositStatus}.
3534
+ * Use this when the connected wallet holds the strategy collateral on the
3535
+ * deposit chain. {@link ZyfaiSDK.sendDeposit} calls this automatically in
3536
+ * that case. A different token uses {@link ZyfaiSDK.sendSwapDeposit}.
3225
3537
  *
3538
+ * Confirms the ERC-20 `transfer`, then calls {@link ZyfaiSDK.logDeposit}.
3226
3539
  * Requires {@link ZyfaiSDK.connectAccount}. Pass the **EOA** as `userAddress`.
3227
3540
  *
3228
3541
  * @group Deposits and withdrawals
@@ -3230,20 +3543,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3230
3543
  * @param userAddress - Owner EOA (not the Safe)
3231
3544
  * @param chainId - Chain for the transfer
3232
3545
  * @param amount - Amount in least units (string integer)
3233
- * @param asset - Asset symbol (`USDC`, `WETH`, `EURC`, `NVDAc`)
3546
+ * @param asset - Collateral symbol (`USDC`, `WETH`, `EURC`, `NVDAc`)
3234
3547
  * @param strategy - Optional first-deposit {@link Strategy}
3235
- * @returns Transfer receipt and deposit registration (not yet credited until polled)
3548
+ * @returns Transfer receipt and deposit registration
3549
+ *
3550
+ * @throws If validation fails, the minimum portfolio is not met, the Safe is unavailable, or transfer/register fails
3236
3551
  *
3237
- * @throws If validation fails, minimum portfolio is not met, Safe is unavailable, or transfer/register fails
3552
+ * @see {@link ZyfaiSDK.sendDeposit}
3238
3553
  *
3239
3554
  * @example
3240
3555
  * ```typescript
3241
3556
  * await sdk.connectAccount(provider);
3242
- * const sent = await sdk.sendDeposit(eoa, 8453, "10000000", "USDC", "conservative");
3243
- * await sdk.waitForDepositCredit(sent.registration.id, 8453);
3557
+ * const sent = await sdk.sendDirectDeposit(eoa, 8453, "10000000", "USDC", "conservative");
3558
+ * await sdk.waitForDepositPosition(sent.registration.id, 8453);
3244
3559
  * ```
3245
3560
  */
3246
- async sendDeposit(userAddress, chainId, amount, asset, strategy) {
3561
+ async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
3247
3562
  try {
3248
3563
  if (!userAddress) {
3249
3564
  throw new Error("User address is required");
@@ -3360,12 +3675,489 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3360
3675
  txHash,
3361
3676
  smartWallet: safeAddress,
3362
3677
  amount: amountBigInt.toString(),
3678
+ route: "direct",
3363
3679
  registration
3364
3680
  };
3365
3681
  } catch (error) {
3366
3682
  throw new Error(`Deposit failed: ${error.message}`);
3367
3683
  }
3368
3684
  }
3685
+ async sendDeposit(userAddressOrParams, chainId, amount, asset, strategy) {
3686
+ if (typeof userAddressOrParams !== "string") {
3687
+ return this.sendRoutedDeposit(userAddressOrParams);
3688
+ }
3689
+ if (chainId === void 0 || amount === void 0 || asset === void 0) {
3690
+ throw new Error(
3691
+ "Deposit failed: chainId, amount, and asset are required"
3692
+ );
3693
+ }
3694
+ return this.sendDirectDeposit(
3695
+ userAddressOrParams,
3696
+ chainId,
3697
+ amount,
3698
+ asset,
3699
+ strategy
3700
+ );
3701
+ }
3702
+ /**
3703
+ * Resolve a deposit without signing.
3704
+ *
3705
+ * @remarks
3706
+ * A collateral the wallet already holds on `chainId` returns `route: "direct"`.
3707
+ * Same-chain native ETH into WETH returns `route: "wrap"`. Any other spend
3708
+ * token returns a Relay review quote (`route: "swap"`). Nothing is signed.
3709
+ * Optional `slippageBps` (default 200, max 500) is stored on that funding
3710
+ * order and reused when the quote is refreshed for signing.
3711
+ *
3712
+ * @group Deposits and withdrawals
3713
+ *
3714
+ * @param params - Destination collateral and optional spend token
3715
+ * @returns The route, and a review quote when a swap is required
3716
+ *
3717
+ * @throws If the spend token or destination collateral is not supported
3718
+ */
3719
+ async quoteDeposit(params) {
3720
+ if (!params.userAddress) throw new Error("User address is required");
3721
+ if (!isSupportedChain(params.chainId)) {
3722
+ throw new Error(`Unsupported chain ID: ${params.chainId}`);
3723
+ }
3724
+ if (!params.amount || BigInt(params.amount) <= 0n) {
3725
+ throw new Error("Valid amount is required");
3726
+ }
3727
+ const route = resolveDepositRoute(params);
3728
+ if (route.kind === "direct" || route.kind === "wrap") {
3729
+ return {
3730
+ route: route.kind,
3731
+ asset: route.asset,
3732
+ chainId: params.chainId,
3733
+ amount: params.amount
3734
+ };
3735
+ }
3736
+ const quote = await this.quoteSwapDeposit({
3737
+ userAddress: params.userAddress,
3738
+ originChainId: route.originChainId,
3739
+ originCurrency: route.originCurrency,
3740
+ originAmount: params.amount,
3741
+ destinationChainId: params.chainId,
3742
+ destinationAsset: route.destinationAsset,
3743
+ strategy: params.strategy,
3744
+ slippageBps: params.slippageBps
3745
+ });
3746
+ return { route: "swap", ...quote };
3747
+ }
3748
+ /**
3749
+ * Quote a Relay swap that delivers a collateral token to the Safe.
3750
+ *
3751
+ * @remarks
3752
+ * Creates a funding order on the execution API. The connected wallet does
3753
+ * not sign. Pass `orderId` to {@link ZyfaiSDK.sendSwapDeposit} to sign the
3754
+ * refreshed quote, or call {@link ZyfaiSDK.sendDeposit} to quote and sign
3755
+ * in one step.
3756
+ *
3757
+ * Same-chain native ETH into WETH is rejected here. Use {@link ZyfaiSDK.sendDeposit}
3758
+ * with `spendToken: "ETH"`, which wraps in the wallet.
3759
+ *
3760
+ * Optional `slippageBps` defaults to 200 (max 500) and is fixed when this
3761
+ * funding order is created. Sign-time refresh reuses the stored value.
3762
+ *
3763
+ * @group Deposits and withdrawals
3764
+ *
3765
+ * @param params - Origin token, destination collateral, and funding wallet
3766
+ * @returns Review quote. Not yet signed.
3767
+ *
3768
+ * @throws If the server rejects the pair, the amount, or the quote
3769
+ */
3770
+ async quoteSwapDeposit(params) {
3771
+ this.assertSwapDepositParams(params);
3772
+ await this.authenticateUser();
3773
+ const created = await this.httpClient.post(
3774
+ ENDPOINTS.FUNDING_ORDERS,
3775
+ {
3776
+ originChainId: params.originChainId,
3777
+ destinationChainId: params.destinationChainId,
3778
+ originCurrency: params.originCurrency,
3779
+ originAmount: params.originAmount,
3780
+ destinationAsset: params.destinationAsset.toUpperCase(),
3781
+ fundingWallet: params.userAddress,
3782
+ ...params.slippageBps != null ? { slippageBps: resolveRelaySlippageBps(params.slippageBps) } : {}
3783
+ }
3784
+ );
3785
+ return {
3786
+ orderId: created.orderId,
3787
+ status: created.status,
3788
+ spend: created.spend,
3789
+ expectedOutput: created.expectedOutput,
3790
+ minimumOutput: created.minimumOutput,
3791
+ destinationChainId: created.destinationChainId,
3792
+ destinationCurrency: created.destinationCurrency,
3793
+ destinationAsset: params.destinationAsset.toUpperCase(),
3794
+ fees: created.fees ?? [],
3795
+ investEligible: created.investEligible,
3796
+ expiresAt: created.expiresAt ?? null,
3797
+ timeEstimate: created.timeEstimate ?? null
3798
+ };
3799
+ }
3800
+ /**
3801
+ * Read a Relay funding order, including a linked deposit once credit starts.
3802
+ *
3803
+ * @group Deposits and withdrawals
3804
+ *
3805
+ * @param orderId - Id from {@link ZyfaiSDK.quoteSwapDeposit}
3806
+ * @returns Stored order
3807
+ *
3808
+ * @throws If `orderId` is missing
3809
+ */
3810
+ async getSwapDeposit(orderId) {
3811
+ if (!orderId) throw new Error("Funding order id is required");
3812
+ await this.authenticateUser();
3813
+ return this.httpClient.get(ENDPOINTS.FUNDING_ORDER(orderId));
3814
+ }
3815
+ /**
3816
+ * Swap or bridge a token into a Zyfai collateral, then register the deposit.
3817
+ *
3818
+ * @remarks
3819
+ * The execution API quotes Relay with the Safe as recipient. This method
3820
+ * refreshes that quote, signs the steps with the connected wallet, waits
3821
+ * for the collateral transfer into the Safe, and calls {@link ZyfaiSDK.logDeposit}.
3822
+ * Credit still requires that verified transfer. A refund or failed fill does
3823
+ * not register a deposit.
3824
+ *
3825
+ * Requires {@link ZyfaiSDK.connectAccount}. Origin chains other than
3826
+ * Ethereum, Base, and Arbitrum need an EIP-1193 wallet that can sign there.
3827
+ *
3828
+ * Optional `slippageBps` defaults to 200 (max 500) and is fixed when the
3829
+ * funding order is created. A later call that passes `orderId` ignores
3830
+ * `slippageBps` and signs the stored order.
3831
+ *
3832
+ * @group Deposits and withdrawals
3833
+ *
3834
+ * @param params - Origin token and destination collateral
3835
+ * @returns Destination transfer and deposit registration
3836
+ *
3837
+ * @throws If the quote, signature, fill, or registration fails, or if
3838
+ * `orderId` names a funding order whose origin or destination differs from
3839
+ * this call
3840
+ *
3841
+ * @see {@link ZyfaiSDK.sendDeposit}
3842
+ *
3843
+ * @example
3844
+ * ```typescript
3845
+ * await sdk.connectAccount(provider);
3846
+ * const sent = await sdk.sendSwapDeposit({
3847
+ * userAddress: eoa,
3848
+ * originChainId: 42161,
3849
+ * originCurrency: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
3850
+ * originAmount: "10000000",
3851
+ * destinationChainId: 8453,
3852
+ * destinationAsset: "WETH",
3853
+ * });
3854
+ * ```
3855
+ */
3856
+ async sendSwapDeposit(params) {
3857
+ try {
3858
+ this.assertSwapDepositParams(params);
3859
+ await this.authenticateUser();
3860
+ await this.prepareFirstDeposit(params.strategy);
3861
+ let orderId;
3862
+ let destinationCurrency;
3863
+ let storedMinimum;
3864
+ if (params.orderId) {
3865
+ const existing = await this.getSwapDeposit(params.orderId);
3866
+ assertStoredFundingOrderRoute(existing, params);
3867
+ orderId = existing.id;
3868
+ destinationCurrency = existing.destinationCurrency;
3869
+ storedMinimum = existing.minimumOutput;
3870
+ } else {
3871
+ const created = await this.quoteSwapDeposit(params);
3872
+ orderId = created.orderId;
3873
+ destinationCurrency = created.destinationCurrency;
3874
+ storedMinimum = created.minimumOutput;
3875
+ }
3876
+ const signQuote = await this.httpClient.post(ENDPOINTS.FUNDING_ORDER_QUOTE(orderId));
3877
+ if (!signQuote.quote) {
3878
+ throw new Error("Relay funding quote is missing from the server response");
3879
+ }
3880
+ const minimumOutput = resolveCollateralMinimum(
3881
+ storedMinimum,
3882
+ signQuote.quote
3883
+ );
3884
+ await this.assertCollateralMinimum(
3885
+ params.userAddress,
3886
+ params.destinationChainId,
3887
+ params.destinationAsset,
3888
+ BigInt(minimumOutput)
3889
+ );
3890
+ ensureRelaySdkClient();
3891
+ const walletClient = await this.walletClientForOrigin(params.originChainId);
3892
+ const { data: execution } = await (0, import_relay_sdk2.execute)({
3893
+ quote: signQuote.quote,
3894
+ wallet: walletClient
3895
+ });
3896
+ const sourceTxHashes = collectRelaySourceTxHashes(
3897
+ execution,
3898
+ params.originChainId
3899
+ );
3900
+ const destinationFromExecution = collectRelayDestinationTxHashes(
3901
+ execution,
3902
+ params.destinationChainId
3903
+ );
3904
+ await this.httpClient.post(ENDPOINTS.FUNDING_ORDER_EXECUTION(orderId), {
3905
+ sourceTxHashes: sourceTxHashes.length ? sourceTxHashes : void 0,
3906
+ stepStatus: "submitted"
3907
+ });
3908
+ await this.hydrateSessionWallet();
3909
+ const safeAddress = await this.getSafeAddressFor(
3910
+ params.userAddress,
3911
+ params.destinationChainId
3912
+ );
3913
+ if (!safeAddress) {
3914
+ throw new Error("Smart wallet address is not available");
3915
+ }
3916
+ const filled = await this.waitForRelayCreditTx({
3917
+ orderId,
3918
+ destinationChainId: params.destinationChainId,
3919
+ destinationToken: destinationCurrency,
3920
+ recipientSafe: safeAddress,
3921
+ initialCandidates: destinationFromExecution
3922
+ });
3923
+ const creditAmount = filled.amount.toString();
3924
+ const registration = await this.registerDeposit(
3925
+ params.destinationChainId,
3926
+ filled.hash,
3927
+ creditAmount,
3928
+ destinationCurrency
3929
+ );
3930
+ return {
3931
+ success: true,
3932
+ txHash: filled.hash,
3933
+ smartWallet: safeAddress,
3934
+ amount: creditAmount,
3935
+ route: "swap",
3936
+ orderId,
3937
+ registration
3938
+ };
3939
+ } catch (error) {
3940
+ const message = thrownMessage(error);
3941
+ throw new Error(
3942
+ message.startsWith("Deposit failed:") ? message : `Deposit failed: ${message}`
3943
+ );
3944
+ }
3945
+ }
3946
+ async sendRoutedDeposit(params) {
3947
+ try {
3948
+ if (!params.userAddress) throw new Error("User address is required");
3949
+ if (!isSupportedChain(params.chainId)) {
3950
+ throw new Error(`Unsupported chain ID: ${params.chainId}`);
3951
+ }
3952
+ if (!params.amount || BigInt(params.amount) <= 0n) {
3953
+ throw new Error("Valid amount is required");
3954
+ }
3955
+ const route = resolveDepositRoute(params);
3956
+ if (route.kind === "direct") {
3957
+ return this.sendDirectDeposit(
3958
+ params.userAddress,
3959
+ params.chainId,
3960
+ params.amount,
3961
+ route.asset,
3962
+ params.strategy
3963
+ );
3964
+ }
3965
+ if (route.kind === "wrap") {
3966
+ await this.assertCollateralMinimum(
3967
+ params.userAddress,
3968
+ params.chainId,
3969
+ "WETH",
3970
+ BigInt(params.amount)
3971
+ );
3972
+ await this.wrapNativeEth(params.chainId, params.amount);
3973
+ const sent = await this.sendDirectDeposit(
3974
+ params.userAddress,
3975
+ params.chainId,
3976
+ params.amount,
3977
+ "WETH",
3978
+ params.strategy
3979
+ );
3980
+ return { ...sent, route: "wrap" };
3981
+ }
3982
+ return this.sendSwapDeposit({
3983
+ userAddress: params.userAddress,
3984
+ originChainId: route.originChainId,
3985
+ originCurrency: route.originCurrency,
3986
+ originAmount: params.amount,
3987
+ destinationChainId: params.chainId,
3988
+ destinationAsset: route.destinationAsset,
3989
+ strategy: params.strategy,
3990
+ slippageBps: params.slippageBps
3991
+ });
3992
+ } catch (error) {
3993
+ const message = thrownMessage(error);
3994
+ throw new Error(
3995
+ message.startsWith("Deposit failed:") ? message : `Deposit failed: ${message}`
3996
+ );
3997
+ }
3998
+ }
3999
+ /** Portfolio floor used by a direct deposit, applied before a wrap or swap spends. */
4000
+ async assertCollateralMinimum(userAddress, chainId, asset, amount) {
4001
+ const symbol = Object.keys(ASSET_CONFIGS).find(
4002
+ (key) => key.toLowerCase() === asset.toLowerCase()
4003
+ );
4004
+ if (!symbol || !getAssetChainIds(symbol).includes(chainId)) return;
4005
+ await this.hydrateSessionWallet();
4006
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4007
+ if (!safeAddress) {
4008
+ throw new Error("Smart wallet address is not available");
4009
+ }
4010
+ await this.enforceMinimumPortfolioBalance(
4011
+ chainId,
4012
+ symbol,
4013
+ amount,
4014
+ safeAddress,
4015
+ userAddress
4016
+ );
4017
+ }
4018
+ assertSwapDepositParams(params) {
4019
+ if (!params.userAddress) throw new Error("User address is required");
4020
+ if (!params.originAmount || BigInt(params.originAmount) <= 0n) {
4021
+ throw new Error("Valid origin amount is required");
4022
+ }
4023
+ if (!Number.isInteger(params.originChainId) || params.originChainId <= 0) {
4024
+ throw new Error("Valid origin chain is required");
4025
+ }
4026
+ if (!isSupportedChain(params.destinationChainId)) {
4027
+ throw new Error(`Unsupported chain ID: ${params.destinationChainId}`);
4028
+ }
4029
+ if (!params.originCurrency) throw new Error("Origin token is required");
4030
+ if (!params.destinationAsset) throw new Error("Destination asset is required");
4031
+ if (params.slippageBps != null) {
4032
+ if (!Number.isInteger(params.slippageBps) || params.slippageBps < 1 || params.slippageBps > MAX_RELAY_SLIPPAGE_BPS) {
4033
+ throw new Error(
4034
+ `slippageBps must be an integer from 1 to ${MAX_RELAY_SLIPPAGE_BPS}. Received ${params.slippageBps}.`
4035
+ );
4036
+ }
4037
+ }
4038
+ if (params.destinationAsset.toUpperCase() === "WETH" && params.originChainId === params.destinationChainId && isNativeSpendToken(params.originCurrency)) {
4039
+ throw new Error(
4040
+ 'Same-chain ETH to WETH is a wrap, not a Relay swap. Call sendDeposit with spendToken "ETH".'
4041
+ );
4042
+ }
4043
+ }
4044
+ async walletClientForOrigin(originChainId) {
4045
+ if (this.signer) {
4046
+ if (!isSupportedChain(originChainId)) {
4047
+ throw new Error(
4048
+ `Cannot sign a swap from chain ${originChainId} with a private key. Connect an EIP-1193 wallet, or spend from Ethereum, Base, or Arbitrum.`
4049
+ );
4050
+ }
4051
+ return this.getWalletClient(originChainId);
4052
+ }
4053
+ if (!this.walletClient?.account) {
4054
+ throw new Error("No account connected. Call connectAccount() first");
4055
+ }
4056
+ if (!this.currentProvider?.request) {
4057
+ if (this.walletClient.chain?.id === originChainId) return this.walletClient;
4058
+ throw new Error(
4059
+ `Wallet is on chain ${this.walletClient.chain?.id ?? "unknown"}. Switch it to chain ${originChainId} before this swap.`
4060
+ );
4061
+ }
4062
+ await this.currentProvider.request({
4063
+ method: "wallet_switchEthereumChain",
4064
+ params: [{ chainId: `0x${originChainId.toString(16)}` }]
4065
+ });
4066
+ const chain = isSupportedChain(originChainId) ? getChainConfig(originChainId, this.rpcUrls).chain : (0, import_viem4.defineChain)({
4067
+ id: originChainId,
4068
+ name: `Chain ${originChainId}`,
4069
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
4070
+ rpcUrls: { default: { http: ["http://127.0.0.1"] } }
4071
+ });
4072
+ this.walletClient = (0, import_viem4.createWalletClient)({
4073
+ account: this.walletClient.account,
4074
+ chain,
4075
+ transport: (0, import_viem4.custom)(this.currentProvider)
4076
+ });
4077
+ if (isSupportedChain(originChainId)) {
4078
+ this.currentChainId = originChainId;
4079
+ }
4080
+ return this.walletClient;
4081
+ }
4082
+ async wrapNativeEth(chainId, amount) {
4083
+ const token = getDefaultTokenAddress(chainId, "WETH");
4084
+ const walletClient = this.getWalletClient(chainId);
4085
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
4086
+ const hash = await walletClient.writeContract({
4087
+ address: token,
4088
+ abi: WETH_DEPOSIT_ABI,
4089
+ functionName: "deposit",
4090
+ value: BigInt(amount),
4091
+ chain: chainConfig.chain,
4092
+ account: walletClient.account
4093
+ });
4094
+ const receipt = await chainConfig.publicClient.waitForTransactionReceipt({
4095
+ hash
4096
+ });
4097
+ if (receipt.status !== "success") {
4098
+ throw new Error("ETH wrap failed");
4099
+ }
4100
+ }
4101
+ async waitForRelayCreditTx(params) {
4102
+ const chainConfig = getChainConfig(params.destinationChainId, this.rpcUrls);
4103
+ const receipts = /* @__PURE__ */ new Map();
4104
+ const maxAttempts = 120;
4105
+ const intervalMs = 5e3;
4106
+ const loadReceipt = async (hash) => {
4107
+ const key = hash.toLowerCase();
4108
+ if (receipts.has(key)) return;
4109
+ try {
4110
+ const receipt = await chainConfig.publicClient.getTransactionReceipt({
4111
+ hash
4112
+ });
4113
+ receipts.set(key, {
4114
+ status: receipt.status,
4115
+ logs: receipt.logs.map((log) => ({
4116
+ address: log.address,
4117
+ topics: log.topics,
4118
+ data: log.data
4119
+ }))
4120
+ });
4121
+ } catch {
4122
+ }
4123
+ };
4124
+ const pick = async (candidates) => {
4125
+ for (const hash2 of candidates) {
4126
+ if (hash2) await loadReceipt(hash2);
4127
+ }
4128
+ const hash = selectRelayCreditTxHash({
4129
+ candidates,
4130
+ receipts,
4131
+ token: params.destinationToken,
4132
+ recipient: params.recipientSafe
4133
+ });
4134
+ if (!hash) return null;
4135
+ const receipt = receipts.get(hash.toLowerCase());
4136
+ return {
4137
+ hash,
4138
+ amount: receipt ? transferAmountTo(
4139
+ receipt.logs,
4140
+ params.destinationToken,
4141
+ params.recipientSafe
4142
+ ) : 0n
4143
+ };
4144
+ };
4145
+ const immediate = await pick(params.initialCandidates);
4146
+ if (immediate) return immediate;
4147
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
4148
+ const order = await this.getSwapDeposit(params.orderId);
4149
+ if (order.status === "refunded" || order.status === "failed") {
4150
+ throw new Error(`Relay funding ${order.status}`);
4151
+ }
4152
+ const match = await pick([
4153
+ ...params.initialCandidates,
4154
+ ...order.destinationTxHashes ?? []
4155
+ ]);
4156
+ if (match) return match;
4157
+ await sleep(intervalMs);
4158
+ }
4159
+ throw new Error("Relay funding is still converting");
4160
+ }
3369
4161
  /**
3370
4162
  * @deprecated Compatibility convenience method. Prefer {@link ZyfaiSDK.sendDeposit} followed by
3371
4163
  * {@link ZyfaiSDK.waitForDepositCredit} when the caller owns the completion UX.
@@ -3531,7 +4323,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3531
4323
  }
3532
4324
  await this.authenticateUser();
3533
4325
  const usdcDetails = await this.getUserDetails("USDC");
3534
- if ((usdcDetails.chains?.length ?? 0) > 0) {
4326
+ const usdcChainsConfigured = (usdcDetails.chains?.length ?? 0) > 0;
4327
+ const usdcProtocolsConfigured = (usdcDetails.protocols?.length ?? 0) > 0;
4328
+ if (usdcChainsConfigured && usdcProtocolsConfigured) {
3535
4329
  return { applied: false };
3536
4330
  }
3537
4331
  await this.updateUserProtocols(strategy, { strict: true });
@@ -3541,6 +4335,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3541
4335
  "First-deposit setup did not persist USDC chain configuration."
3542
4336
  );
3543
4337
  }
4338
+ if ((usdcAfterSetup.protocols?.length ?? 0) === 0) {
4339
+ throw new Error(
4340
+ "First-deposit setup did not persist USDC protocol configuration."
4341
+ );
4342
+ }
3544
4343
  return { applied: true };
3545
4344
  }
3546
4345
  /**
@@ -3557,7 +4356,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3557
4356
  }
3558
4357
  await this.authenticateUser();
3559
4358
  const details = await this.getUserDetails(asset);
3560
- if (details.chains?.includes(chainId)) {
4359
+ const chainConfigured = details.chains?.includes(chainId) ?? false;
4360
+ const protocolsConfigured = (details.protocols?.length ?? 0) > 0;
4361
+ if (chainConfigured && protocolsConfigured) {
3561
4362
  return { applied: false };
3562
4363
  }
3563
4364
  const allProtocols = await this.httpClient.get(
@@ -3575,8 +4376,20 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3575
4376
  `First-deposit setup did not persist ${asset} chain ${chainId} configuration.`
3576
4377
  );
3577
4378
  }
4379
+ if ((afterSetup.protocols?.length ?? 0) === 0) {
4380
+ throw new Error(
4381
+ `First-deposit setup did not persist ${asset} protocol configuration.`
4382
+ );
4383
+ }
3578
4384
  return { applied: true };
3579
4385
  }
4386
+ /**
4387
+ * Persist the deposit asset on one chain before a signing page runs the transfer or swap.
4388
+ * Does not build calldata and does not check the portfolio minimum.
4389
+ */
4390
+ async ensureDepositAssetOnChain(params) {
4391
+ return this.ensureDepositProfileForPrepare(params);
4392
+ }
3580
4393
  /**
3581
4394
  * Prepare a deposit: persist first-deposit profile when needed and return
3582
4395
  * ERC-20 transfer calldata for the user to sign (does not broadcast).
@@ -3772,7 +4585,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3772
4585
  const started = Date.now();
3773
4586
  while (Date.now() - started < timeoutMs) {
3774
4587
  const status = await this.getDepositStatus(depositId);
3775
- if (status.status === "credited" && status.balanceCredited) {
4588
+ if (status.balanceCredited && status.status !== "recovered_to_eoa") {
3776
4589
  return status;
3777
4590
  }
3778
4591
  if (status.status === "recovered_to_eoa") {
@@ -3787,6 +4600,134 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3787
4600
  }
3788
4601
  throw new DepositCreditTimeoutError(depositId);
3789
4602
  }
4603
+ /**
4604
+ * Poll deposit status until funds are allocated to a protocol position, skipped, or failed.
4605
+ * Crosschain deposits resolve once the bridge tx is recorded (`crosschain: true`, `executionTxHash` set);
4606
+ * the destination-chain allocation is not tracked on this lifecycle.
4607
+ */
4608
+ async waitForDepositPosition(depositId, chainId, options) {
4609
+ if (!depositId) {
4610
+ throw new Error("Deposit ID is required");
4611
+ }
4612
+ if (!isSupportedChain(chainId)) {
4613
+ throw new Error(`Unsupported chain ID: ${chainId}`);
4614
+ }
4615
+ const intervalMs = options?.intervalMs ?? getUserOpLifecycleIntervalMs(chainId);
4616
+ const timeoutMs = options?.timeoutMs ?? getUserOpLifecycleTimeoutMs(chainId);
4617
+ const started = Date.now();
4618
+ while (Date.now() - started < timeoutMs) {
4619
+ const status = await this.getDepositStatus(depositId);
4620
+ if (status.positionOutcome === "failed") {
4621
+ throw new Error(
4622
+ `Deposit ${depositId} position allocation failed (status=${status.status})`
4623
+ );
4624
+ }
4625
+ if (status.status === "positioned") {
4626
+ return status;
4627
+ }
4628
+ if (status.positionOutcome === "skipped") {
4629
+ return status;
4630
+ }
4631
+ if (status.crosschain && status.executionTxHash) {
4632
+ return status;
4633
+ }
4634
+ if (status.status === "recovered_to_eoa") {
4635
+ throw new Error(
4636
+ `Deposit ${depositId} recovered to EOA; position was not opened`
4637
+ );
4638
+ }
4639
+ await sleep(intervalMs);
4640
+ }
4641
+ throw new DepositPositionTimeoutError(depositId);
4642
+ }
4643
+ async getWithdrawStatus(withdrawalId) {
4644
+ if (!withdrawalId) {
4645
+ throw new Error("Withdrawal lifecycle ID is required");
4646
+ }
4647
+ await this.authenticateUser();
4648
+ return this.httpClient.get(
4649
+ ENDPOINTS.WITHDRAW_STATUS(withdrawalId)
4650
+ );
4651
+ }
4652
+ /**
4653
+ * Short poll: completes when sync slice settles, async enters cooldown, or claim is already in flight (resume/retry).
4654
+ */
4655
+ async waitForWithdrawSettlement(withdrawalId, chainId, options) {
4656
+ if (!withdrawalId) {
4657
+ throw new Error("Withdrawal lifecycle ID is required");
4658
+ }
4659
+ if (!isSupportedChain(chainId)) {
4660
+ throw new Error(`Unsupported chain ID: ${chainId}`);
4661
+ }
4662
+ const intervalMs = options?.intervalMs ?? getUserOpLifecycleIntervalMs(chainId);
4663
+ const timeoutMs = options?.timeoutMs ?? getUserOpLifecycleTimeoutMs(chainId);
4664
+ const started = Date.now();
4665
+ while (Date.now() - started < timeoutMs) {
4666
+ const status = await this.getWithdrawStatus(withdrawalId);
4667
+ if (isWithdrawSettlementTerminal(status.status)) {
4668
+ return status;
4669
+ }
4670
+ if (status.status === "failed") {
4671
+ throw new Error(
4672
+ `Withdraw ${withdrawalId} failed: ${status.lastError ?? "unknown"}`
4673
+ );
4674
+ }
4675
+ await sleep(intervalMs);
4676
+ }
4677
+ throw new WithdrawSettlementTimeoutError(withdrawalId);
4678
+ }
4679
+ /**
4680
+ * Long poll through async cooldown and claim until lifecycle is completed.
4681
+ */
4682
+ async waitForWithdrawComplete(withdrawalId, chainId, options) {
4683
+ if (!withdrawalId) {
4684
+ throw new Error("Withdrawal lifecycle ID is required");
4685
+ }
4686
+ if (!isSupportedChain(chainId)) {
4687
+ throw new Error(`Unsupported chain ID: ${chainId}`);
4688
+ }
4689
+ const fastIntervalMs = options?.intervalMs ?? getUserOpLifecycleIntervalMs(chainId);
4690
+ const cooldownIntervalMs = options?.cooldownIntervalMs ?? ASYNC_WITHDRAW_COOLDOWN_POLL_INTERVAL_MS;
4691
+ const started = Date.now();
4692
+ const fallbackMs = getUserOpLifecycleTimeoutMs(chainId) + ASYNC_WITHDRAW_CLAIM_GRACE_MS;
4693
+ let deadlineMs = nextWithdrawCompleteDeadline(
4694
+ started,
4695
+ void 0,
4696
+ void 0,
4697
+ {
4698
+ explicitTimeoutMs: options?.timeoutMs,
4699
+ graceMs: ASYNC_WITHDRAW_CLAIM_GRACE_MS,
4700
+ fallbackMs
4701
+ }
4702
+ );
4703
+ while (true) {
4704
+ const status = await this.getWithdrawStatus(withdrawalId);
4705
+ if (status.status === "completed") {
4706
+ return status;
4707
+ }
4708
+ if (status.status === "failed") {
4709
+ throw new Error(
4710
+ `Withdraw ${withdrawalId} failed: ${status.lastError ?? "unknown"}`
4711
+ );
4712
+ }
4713
+ deadlineMs = nextWithdrawCompleteDeadline(
4714
+ started,
4715
+ deadlineMs,
4716
+ status.estimatedClaimAt,
4717
+ {
4718
+ explicitTimeoutMs: options?.timeoutMs,
4719
+ graceMs: ASYNC_WITHDRAW_CLAIM_GRACE_MS,
4720
+ fallbackMs
4721
+ }
4722
+ );
4723
+ if (Date.now() >= deadlineMs) {
4724
+ break;
4725
+ }
4726
+ const intervalMs = status.status === "async_cooldown" ? cooldownIntervalMs : fastIntervalMs;
4727
+ await sleep(intervalMs);
4728
+ }
4729
+ throw new WithdrawCompleteTimeoutError(withdrawalId);
4730
+ }
3790
4731
  /**
3791
4732
  * Withdraw funds from Safe smart wallet
3792
4733
  * Initiates a withdrawal request to the Zyfai API
@@ -3882,17 +4823,28 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3882
4823
  response = await this.httpClient.get(ENDPOINTS.USER_WITHDRAW, {
3883
4824
  params: { chainId, tokenSymbol }
3884
4825
  });
3885
- console.log(JSON.stringify(response, null, 2));
3886
4826
  }
3887
4827
  const success = response?.success ?? true;
3888
4828
  const message = response?.message || "Withdrawal request sent";
3889
4829
  const txHash = response?.txHash || response?.transactionHash;
4830
+ const lifecycleId = response?.id;
4831
+ const lifecycle = lifecycleId && response?.statusUrl ? {
4832
+ id: lifecycleId,
4833
+ status: "accepted",
4834
+ chainId,
4835
+ tokenSymbol: tokenSymbol ?? null,
4836
+ syncSettled: false,
4837
+ asyncLegs: [],
4838
+ failedAsyncIds: [],
4839
+ statusUrl: response.statusUrl
4840
+ } : void 0;
3890
4841
  return {
3891
4842
  success,
3892
4843
  message,
3893
4844
  txHash,
3894
4845
  type: amount ? "partial" : "full",
3895
- amount: amount || "all"
4846
+ amount: amount || "all",
4847
+ lifecycle
3896
4848
  };
3897
4849
  } catch (error) {
3898
4850
  throw new Error(`Withdrawal failed: ${error.message}`);
@@ -6060,6 +7012,7 @@ function createBankrProvider(config) {
6060
7012
  API_ENDPOINT,
6061
7013
  DATA_API_BASE_URLS,
6062
7014
  DATA_API_ENDPOINT,
7015
+ DEFAULT_RELAY_SLIPPAGE_BPS,
6063
7016
  DEFAULT_TOKEN_ADDRESSES,
6064
7017
  ERC7579_LAUNCHPAD_ADDRESS,
6065
7018
  EXECUTION_API_BASE_URLS,
@@ -6068,9 +7021,11 @@ function createBankrProvider(config) {
6068
7021
  LOCAL_DATA_API_BASE_URL,
6069
7022
  LOCAL_EXECUTION_API_BASE_URL,
6070
7023
  LOCAL_WS_URL,
7024
+ MAX_RELAY_SLIPPAGE_BPS,
6071
7025
  OWNABLE_VALIDATOR,
6072
7026
  POOL_MODULE_ADDRESSES,
6073
7027
  PROXY_EXECUTOR,
7028
+ RELAY_SLIPPAGE_PRESETS_BPS,
6074
7029
  SAFE_7579_ADDRESS,
6075
7030
  SMART_SESSIONS_FALLBACK,
6076
7031
  SMART_SESSIONS_VALIDATOR,
@@ -6089,5 +7044,7 @@ function createBankrProvider(config) {
6089
7044
  getManagedAssets,
6090
7045
  getSupportedChainIds,
6091
7046
  getWsUrl,
6092
- isSupportedChain
7047
+ isSupportedChain,
7048
+ resolveDepositRoute,
7049
+ resolveRelaySlippageBps
6093
7050
  });