@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.mjs CHANGED
@@ -51,10 +51,15 @@ var ENDPOINTS = {
51
51
  USER_AGENT_DEPOSIT_INTENT_CONSUME: (actionId) => `/users/me/agent-deposit-intents/${encodeURIComponent(actionId)}/consume`,
52
52
  USER_AGENT_DEPOSIT_INTENT_COMPLETE: (actionId) => `/users/me/agent-deposit-intents/${encodeURIComponent(actionId)}/complete`,
53
53
  AGENT_DEPOSIT_INTENT_RESOLVE: "/agent-deposit-intents/resolve",
54
- USER_WITHDRAW: "/users/withdraw",
55
- PARTIAL_WITHDRAW: "/users/partial-withdraw",
54
+ USER_WITHDRAW: "/users/withdraw/v2",
55
+ PARTIAL_WITHDRAW: "/users/partial-withdraw/v2",
56
56
  LOG_DEPOSIT: "/users/log_deposit/v2",
57
- DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}`,
57
+ FUNDING_ORDERS: "/users/me/funding-orders",
58
+ FUNDING_ORDER: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}`,
59
+ FUNDING_ORDER_QUOTE: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/quote`,
60
+ FUNDING_ORDER_EXECUTION: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/execution`,
61
+ DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}/v2`,
62
+ WITHDRAW_STATUS: (withdrawalId) => `/users/withdrawals/${withdrawalId}`,
58
63
  // Safe Deployment (single endpoint)
59
64
  SAFE_DEPLOY: "/users/safe-deploy",
60
65
  // Multichain deploy for predeployed (pool) wallets — deploys + rotates the
@@ -381,6 +386,11 @@ function sleep(ms) {
381
386
  return new Promise((resolve) => setTimeout(resolve, ms));
382
387
  }
383
388
 
389
+ // src/utils/withdraw-lifecycle-polling.ts
390
+ function isWithdrawSettlementTerminal(status) {
391
+ return status === "completed" || status === "async_cooldown" || status === "async_claiming";
392
+ }
393
+
384
394
  // src/utils/token-price.ts
385
395
  var PRICE_SCALE = 8;
386
396
  var parseTokenUsdPrice = (response) => {
@@ -479,6 +489,15 @@ var ERC20_ABI = [
479
489
  outputs: [{ name: "", type: "uint256" }]
480
490
  }
481
491
  ];
492
+ var WETH_DEPOSIT_ABI = [
493
+ {
494
+ name: "deposit",
495
+ type: "function",
496
+ stateMutability: "payable",
497
+ inputs: [],
498
+ outputs: []
499
+ }
500
+ ];
482
501
  var ERC20_TRANSFER_LEGACY_ABI = [
483
502
  {
484
503
  name: "transfer",
@@ -643,12 +662,39 @@ var DEPOSIT_CREDIT_TIMEOUT_MS = {
643
662
  };
644
663
  var getDepositCreditIntervalMs = (chainId) => DEPOSIT_CREDIT_INTERVAL_MS[chainId];
645
664
  var getDepositCreditTimeoutMs = (chainId) => DEPOSIT_CREDIT_TIMEOUT_MS[chainId];
665
+ var USER_OP_LIFECYCLE_INTERVAL_MS = {
666
+ 1: 4e3,
667
+ 8453: 1e3,
668
+ 42161: 1e3
669
+ };
670
+ var USER_OP_LIFECYCLE_TIMEOUT_MS = {
671
+ 1: 18e4,
672
+ 8453: 9e4,
673
+ 42161: 9e4
674
+ };
675
+ var ASYNC_WITHDRAW_COOLDOWN_POLL_INTERVAL_MS = 6e4;
676
+ var ASYNC_WITHDRAW_CLAIM_GRACE_MS = 6 * 60 * 60 * 1e3;
677
+ var getUserOpLifecycleIntervalMs = (chainId) => USER_OP_LIFECYCLE_INTERVAL_MS[chainId];
678
+ var getUserOpLifecycleTimeoutMs = (chainId) => USER_OP_LIFECYCLE_TIMEOUT_MS[chainId];
679
+ function nextWithdrawCompleteDeadline(startedAt, previousDeadline, estimatedClaimAt, options) {
680
+ if (options.explicitTimeoutMs != null) {
681
+ return startedAt + options.explicitTimeoutMs;
682
+ }
683
+ let deadline = previousDeadline ?? startedAt + options.fallbackMs;
684
+ if (estimatedClaimAt) {
685
+ const claimAt = Date.parse(estimatedClaimAt);
686
+ if (!Number.isNaN(claimAt)) {
687
+ deadline = Math.max(deadline, claimAt + options.graceMs);
688
+ }
689
+ }
690
+ return deadline;
691
+ }
646
692
  var AGENT_DEPOSIT_INTENT_INTERVAL_MS = 1500;
647
693
  var AGENT_DEPOSIT_INTENT_TIMEOUT_MS = 30 * 60 * 1e3;
648
694
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
649
- const base2 = 10n ** BigInt(decimals);
650
- const whole = raw / base2;
651
- const fraction = raw % base2;
695
+ const base3 = 10n ** BigInt(decimals);
696
+ const whole = raw / base3;
697
+ const fraction = raw % base3;
652
698
  if (fraction === 0n) {
653
699
  return `${whole.toString()} ${symbol}`;
654
700
  }
@@ -707,8 +753,10 @@ import {
707
753
  custom,
708
754
  http as http2,
709
755
  getAddress as getAddress2,
710
- encodeFunctionData
756
+ encodeFunctionData,
757
+ defineChain
711
758
  } from "viem";
759
+ import { execute } from "@relayprotocol/relay-sdk";
712
760
 
713
761
  // src/config/chains.ts
714
762
  import { createPublicClient, http } from "viem";
@@ -903,6 +951,233 @@ var getSupportedChainIds = () => {
903
951
  return Object.keys(CHAINS).map(Number);
904
952
  };
905
953
 
954
+ // src/deposits/deposit-route.ts
955
+ var NATIVE_CURRENCY = "0x0000000000000000000000000000000000000000";
956
+ var RELAY_DESTINATION_ASSETS = [
957
+ "USDC",
958
+ "WETH",
959
+ "CBBTC",
960
+ "WBTC",
961
+ "EURC",
962
+ "USDT",
963
+ "PYUSD",
964
+ "NVDAC",
965
+ "GOOGLC",
966
+ "AAPLC",
967
+ "METAC"
968
+ ];
969
+ var lookupCollateral = (asset) => Object.keys(ASSET_CONFIGS).find(
970
+ (key) => key.toLowerCase() === asset.toLowerCase()
971
+ ) ?? null;
972
+ var toRelayDestinationAsset = (asset) => asset.trim().toUpperCase();
973
+ var isNativeSpendToken = (token) => {
974
+ const value = token.trim().toLowerCase();
975
+ return value === "eth" || value === "native" || value === NATIVE_CURRENCY;
976
+ };
977
+ var isSameCollateralToken = (spend, collateral, chainId) => {
978
+ if (spend.toLowerCase() === collateral.toLowerCase()) return true;
979
+ const address = ASSET_CONFIGS[collateral]?.addresses?.[chainId];
980
+ return !!address && spend.toLowerCase() === address.toLowerCase();
981
+ };
982
+ var originCurrencyForSpend = (spend, chainId) => {
983
+ if (isNativeSpendToken(spend)) return NATIVE_CURRENCY;
984
+ if (/^0x[0-9a-fA-F]{40}$/.test(spend)) return spend;
985
+ const collateral = lookupCollateral(spend);
986
+ if (!collateral) {
987
+ throw new Error(
988
+ `spendToken must be a collateral symbol or a token contract address. Received "${spend}".`
989
+ );
990
+ }
991
+ const address = ASSET_CONFIGS[collateral]?.addresses?.[chainId];
992
+ if (!address) {
993
+ throw new Error(`${collateral} is not available on chain ${chainId}.`);
994
+ }
995
+ return address;
996
+ };
997
+ var resolveDepositRoute = (input) => {
998
+ const asset = input.asset?.trim();
999
+ if (!asset) throw new Error("Asset is required");
1000
+ const spendChainId = input.spendChainId ?? input.chainId;
1001
+ const collateral = lookupCollateral(asset);
1002
+ const spend = input.spendToken?.trim();
1003
+ const holdsDestinationCollateral = !spend || spendChainId === input.chainId && !!collateral && isSameCollateralToken(spend, collateral, input.chainId);
1004
+ if (holdsDestinationCollateral) {
1005
+ if (!collateral) {
1006
+ throw new Error(
1007
+ `${asset} cannot be transferred directly. Pass spendToken to swap another token into it.`
1008
+ );
1009
+ }
1010
+ const chains = getAssetChainIds(collateral);
1011
+ if (!chains.includes(input.chainId)) {
1012
+ throw new Error(
1013
+ `${collateral} is not available on chain ${input.chainId}. Supported chains: ${chains.join(", ")}.`
1014
+ );
1015
+ }
1016
+ return { kind: "direct", asset: collateral };
1017
+ }
1018
+ if (collateral === "WETH" && spendChainId === input.chainId && spend && isNativeSpendToken(spend)) {
1019
+ return { kind: "wrap", asset: "WETH" };
1020
+ }
1021
+ const destinationAsset = toRelayDestinationAsset(asset);
1022
+ if (!RELAY_DESTINATION_ASSETS.includes(
1023
+ destinationAsset
1024
+ )) {
1025
+ throw new Error(
1026
+ `${asset} is not a collateral Relay can deliver. Supported: ${RELAY_DESTINATION_ASSETS.join(", ")}.`
1027
+ );
1028
+ }
1029
+ return {
1030
+ kind: "swap",
1031
+ originChainId: spendChainId,
1032
+ originCurrency: originCurrencyForSpend(spend, spendChainId),
1033
+ destinationAsset
1034
+ };
1035
+ };
1036
+
1037
+ // src/deposits/funding-order-route.ts
1038
+ var sameText = (left, right) => typeof left === "string" && left.trim().toLowerCase() === right.trim().toLowerCase();
1039
+ var assertStoredFundingOrderRoute = (order, requested) => {
1040
+ const mismatches = [];
1041
+ if (order.originChainId !== requested.originChainId) {
1042
+ mismatches.push(
1043
+ `originChainId caller ${requested.originChainId}, stored ${order.originChainId}`
1044
+ );
1045
+ }
1046
+ if (!sameText(order.originCurrency, requested.originCurrency)) {
1047
+ mismatches.push(
1048
+ `originCurrency caller ${requested.originCurrency}, stored ${order.originCurrency}`
1049
+ );
1050
+ }
1051
+ if (order.destinationChainId !== requested.destinationChainId) {
1052
+ mismatches.push(
1053
+ `destinationChainId caller ${requested.destinationChainId}, stored ${order.destinationChainId}`
1054
+ );
1055
+ }
1056
+ if (!sameText(order.destinationAsset, requested.destinationAsset)) {
1057
+ mismatches.push(
1058
+ `destinationAsset caller ${requested.destinationAsset}, stored ${order.destinationAsset}`
1059
+ );
1060
+ }
1061
+ if (mismatches.length === 0) return;
1062
+ throw new Error(
1063
+ `Funding order ${order.id} does not match this swap: ${mismatches.join("; ")}`
1064
+ );
1065
+ };
1066
+
1067
+ // src/deposits/collateral-minimum.ts
1068
+ var positiveUnits = (value) => {
1069
+ if (!value || value === "0") return null;
1070
+ return value;
1071
+ };
1072
+ var resolveCollateralMinimum = (storedMinimum, quote) => positiveUnits(storedMinimum) ?? positiveUnits(quote.details?.currencyOut?.minimumAmount) ?? positiveUnits(quote.details?.currencyOut?.amount) ?? "0";
1073
+
1074
+ // src/deposits/relay-slippage.ts
1075
+ var DEFAULT_RELAY_SLIPPAGE_BPS = 200;
1076
+ var MAX_RELAY_SLIPPAGE_BPS = 500;
1077
+ var RELAY_SLIPPAGE_PRESETS_BPS = [50, 200, 500];
1078
+ var resolveRelaySlippageBps = (clientBps) => {
1079
+ if (clientBps == null || !Number.isFinite(clientBps)) {
1080
+ return DEFAULT_RELAY_SLIPPAGE_BPS;
1081
+ }
1082
+ return Math.min(
1083
+ Math.max(1, Math.trunc(clientBps)),
1084
+ MAX_RELAY_SLIPPAGE_BPS
1085
+ );
1086
+ };
1087
+
1088
+ // src/deposits/relay-client.ts
1089
+ import {
1090
+ MAINNET_RELAY_API,
1091
+ convertViemChainToRelayChain,
1092
+ createClient,
1093
+ getClient
1094
+ } from "@relayprotocol/relay-sdk";
1095
+ import { arbitrum as arbitrum2, base as base2, mainnet as mainnet2 } from "viem/chains";
1096
+ var RELAY_FUNDING_CHAIN_IDS = [mainnet2.id, base2.id, arbitrum2.id];
1097
+ var clientHasFundingChains = () => {
1098
+ const client = getClient();
1099
+ if (!client?.baseApiUrl) return false;
1100
+ return RELAY_FUNDING_CHAIN_IDS.every(
1101
+ (chainId) => client.chains.some((chain) => chain.id === chainId)
1102
+ );
1103
+ };
1104
+ var ensureRelaySdkClient = () => {
1105
+ if (clientHasFundingChains()) return;
1106
+ createClient({
1107
+ baseApiUrl: MAINNET_RELAY_API,
1108
+ source: "zyf.ai",
1109
+ chains: [mainnet2, base2, arbitrum2].map(convertViemChainToRelayChain)
1110
+ });
1111
+ };
1112
+
1113
+ // src/deposits/relay-fill.ts
1114
+ var TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
1115
+ var collectTxHashes = (execution) => {
1116
+ const out = [];
1117
+ for (const step of execution.steps ?? []) {
1118
+ for (const item of step.items ?? []) {
1119
+ for (const row of item.txHashes ?? []) {
1120
+ if (row.txHash) out.push(row);
1121
+ }
1122
+ for (const row of item.internalTxHashes ?? []) {
1123
+ if (row.txHash) out.push(row);
1124
+ }
1125
+ }
1126
+ }
1127
+ return out;
1128
+ };
1129
+ var collectRelaySourceTxHashes = (execution, originChainId) => {
1130
+ const hashes = /* @__PURE__ */ new Set();
1131
+ for (const row of collectTxHashes(execution)) {
1132
+ if (row.chainId === originChainId) hashes.add(row.txHash);
1133
+ }
1134
+ return [...hashes];
1135
+ };
1136
+ var collectRelayDestinationTxHashes = (execution, destinationChainId) => {
1137
+ const hashes = /* @__PURE__ */ new Set();
1138
+ for (const row of collectTxHashes(execution)) {
1139
+ if (row.chainId === destinationChainId && row.txHash) {
1140
+ hashes.add(row.txHash);
1141
+ }
1142
+ }
1143
+ return [...hashes];
1144
+ };
1145
+ var transferAmountTo = (logs, token, recipient) => {
1146
+ const tokenAddr = token.toLowerCase();
1147
+ const recipientAddr = recipient.toLowerCase();
1148
+ let total = 0n;
1149
+ for (const log of logs) {
1150
+ if (log.address.toLowerCase() !== tokenAddr) continue;
1151
+ if (log.topics[0]?.toLowerCase() !== TRANSFER_TOPIC) continue;
1152
+ const toTopic = log.topics[2];
1153
+ if (!toTopic) continue;
1154
+ const to = `0x${toTopic.slice(-40)}`.toLowerCase();
1155
+ if (to !== recipientAddr) continue;
1156
+ try {
1157
+ const value = BigInt(log.data);
1158
+ if (value > 0n) total += value;
1159
+ } catch {
1160
+ }
1161
+ }
1162
+ return total;
1163
+ };
1164
+ var receiptTransfersTokenTo = (logs, token, recipient) => transferAmountTo(logs, token, recipient) > 0n;
1165
+ var selectRelayCreditTxHash = (params) => {
1166
+ const seen = /* @__PURE__ */ new Set();
1167
+ for (const hash of params.candidates) {
1168
+ if (!hash) continue;
1169
+ const key = hash.toLowerCase();
1170
+ if (seen.has(key)) continue;
1171
+ seen.add(key);
1172
+ const receipt = params.receipts.get(key);
1173
+ if (!receipt || receipt.status !== "success") continue;
1174
+ if (receiptTransfersTokenTo(receipt.logs, params.token, params.recipient)) {
1175
+ return hash;
1176
+ }
1177
+ }
1178
+ return null;
1179
+ };
1180
+
906
1181
  // src/config/managed-assets.ts
907
1182
  var MANAGED_ASSET_ORDER = [
908
1183
  "USDC",
@@ -1703,12 +1978,41 @@ var DepositCreditTimeoutError = class extends Error {
1703
1978
  this.name = "DepositCreditTimeoutError";
1704
1979
  }
1705
1980
  };
1981
+ var DepositPositionTimeoutError = class extends Error {
1982
+ constructor(depositId) {
1983
+ super(`Timed out waiting for deposit ${depositId} to reach a position`);
1984
+ this.name = "DepositPositionTimeoutError";
1985
+ }
1986
+ };
1987
+ var WithdrawSettlementTimeoutError = class extends Error {
1988
+ constructor(withdrawalId) {
1989
+ super(
1990
+ `Timed out waiting for withdraw lifecycle ${withdrawalId} to settle`
1991
+ );
1992
+ this.name = "WithdrawSettlementTimeoutError";
1993
+ }
1994
+ };
1995
+ var WithdrawCompleteTimeoutError = class extends Error {
1996
+ constructor(withdrawalId) {
1997
+ super(
1998
+ `Timed out waiting for withdraw lifecycle ${withdrawalId} to complete`
1999
+ );
2000
+ this.name = "WithdrawCompleteTimeoutError";
2001
+ }
2002
+ };
1706
2003
  var AgentDepositIntentTimeoutError = class extends Error {
1707
2004
  constructor(actionId) {
1708
2005
  super(`Timed out waiting for agent deposit intent ${actionId} to complete`);
1709
2006
  this.name = "AgentDepositIntentTimeoutError";
1710
2007
  }
1711
2008
  };
2009
+ var thrownMessage = (error) => {
2010
+ if (error instanceof Error) return error.message;
2011
+ if (error && typeof error === "object" && "message" in error && typeof error.message === "string") {
2012
+ return error.message;
2013
+ }
2014
+ return String(error);
2015
+ };
1712
2016
  var _ZyfaiSDK = class _ZyfaiSDK {
1713
2017
  /**
1714
2018
  * Create an SDK instance bound to a partner API key.
@@ -2895,14 +3199,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2895
3199
  effectiveChains,
2896
3200
  withPools,
2897
3201
  strategy,
2898
- mandateChainId
3202
+ mandateChainId,
3203
+ existingChains
2899
3204
  );
2900
3205
  }
2901
3206
  /**
2902
3207
  * Persist protocol discovery for one asset (user PATCH or agent deposit-setup).
2903
3208
  * @internal
2904
3209
  */
2905
- async persistDiscoveredAssetProfile(asset, effectiveChains, withPools, strategy, agentDepositChainId) {
3210
+ async persistDiscoveredAssetProfile(asset, effectiveChains, withPools, strategy, agentDepositChainId, existingChains = []) {
2906
3211
  const internalAsset = convertAssetInternally(asset);
2907
3212
  const assetSettings = {
2908
3213
  chains: effectiveChains,
@@ -2911,9 +3216,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2911
3216
  if (strategy !== void 0) {
2912
3217
  assetSettings.rebalanceStrategy = toInternalStrategy(strategy);
2913
3218
  }
3219
+ const configureProfile = () => this.updateUserProfile({
3220
+ asset,
3221
+ protocols: withPools,
3222
+ chains: effectiveChains,
3223
+ ...strategy !== void 0 && { strategy }
3224
+ });
2914
3225
  if (this.sessionChannel === "agent") {
2915
3226
  const chainId = agentDepositChainId ?? effectiveChains[effectiveChains.length - 1] ?? effectiveChains[0];
2916
- await this.httpClient.post(
3227
+ if (existingChains.includes(chainId)) {
3228
+ return await configureProfile();
3229
+ }
3230
+ const setupResult = await this.httpClient.post(
2917
3231
  ENDPOINTS.AGENT_DEPOSIT_SETUP,
2918
3232
  {
2919
3233
  asset,
@@ -2924,14 +3238,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2924
3238
  }
2925
3239
  }
2926
3240
  );
3241
+ if (!setupResult.applied) {
3242
+ throw new Error(
3243
+ `Agent deposit setup did not apply for ${asset} on chain ${chainId}.`
3244
+ );
3245
+ }
2927
3246
  return await this.getUserDetails(asset);
2928
3247
  }
2929
- return await this.updateUserProfile({
2930
- asset,
2931
- protocols: withPools,
2932
- chains: effectiveChains,
2933
- ...strategy !== void 0 && { strategy }
2934
- });
3248
+ return await configureProfile();
2935
3249
  }
2936
3250
  /**
2937
3251
  * Switch one asset to a strategy and select the protocols that go with it.
@@ -3166,14 +3480,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3166
3480
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
3167
3481
  }
3168
3482
  /**
3169
- * Transfer funds from the connected EOA to the user's Safe and register the deposit.
3483
+ * Transfer a collateral token the wallet already holds into the Safe.
3170
3484
  *
3171
3485
  * @remarks
3172
- * Execution API + on-chain ERC-20 `transfer`. Confirms the transaction, then calls
3173
- * {@link ZyfaiSDK.logDeposit}. Pair with {@link ZyfaiSDK.waitForDepositCredit} for
3174
- * investable balance. Custom-wallet flows: {@link ZyfaiSDK.buildDepositTransfer},
3175
- * {@link ZyfaiSDK.logDeposit}, {@link ZyfaiSDK.getDepositStatus}.
3486
+ * Use this when the connected wallet holds the strategy collateral on the
3487
+ * deposit chain. {@link ZyfaiSDK.sendDeposit} calls this automatically in
3488
+ * that case. A different token uses {@link ZyfaiSDK.sendSwapDeposit}.
3176
3489
  *
3490
+ * Confirms the ERC-20 `transfer`, then calls {@link ZyfaiSDK.logDeposit}.
3177
3491
  * Requires {@link ZyfaiSDK.connectAccount}. Pass the **EOA** as `userAddress`.
3178
3492
  *
3179
3493
  * @group Deposits and withdrawals
@@ -3181,20 +3495,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3181
3495
  * @param userAddress - Owner EOA (not the Safe)
3182
3496
  * @param chainId - Chain for the transfer
3183
3497
  * @param amount - Amount in least units (string integer)
3184
- * @param asset - Asset symbol (`USDC`, `WETH`, `EURC`, `NVDAc`)
3498
+ * @param asset - Collateral symbol (`USDC`, `WETH`, `EURC`, `NVDAc`)
3185
3499
  * @param strategy - Optional first-deposit {@link Strategy}
3186
- * @returns Transfer receipt and deposit registration (not yet credited until polled)
3500
+ * @returns Transfer receipt and deposit registration
3187
3501
  *
3188
- * @throws If validation fails, minimum portfolio is not met, Safe is unavailable, or transfer/register fails
3502
+ * @throws If validation fails, the minimum portfolio is not met, the Safe is unavailable, or transfer/register fails
3503
+ *
3504
+ * @see {@link ZyfaiSDK.sendDeposit}
3189
3505
  *
3190
3506
  * @example
3191
3507
  * ```typescript
3192
3508
  * await sdk.connectAccount(provider);
3193
- * const sent = await sdk.sendDeposit(eoa, 8453, "10000000", "USDC", "conservative");
3194
- * await sdk.waitForDepositCredit(sent.registration.id, 8453);
3509
+ * const sent = await sdk.sendDirectDeposit(eoa, 8453, "10000000", "USDC", "conservative");
3510
+ * await sdk.waitForDepositPosition(sent.registration.id, 8453);
3195
3511
  * ```
3196
3512
  */
3197
- async sendDeposit(userAddress, chainId, amount, asset, strategy) {
3513
+ async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
3198
3514
  try {
3199
3515
  if (!userAddress) {
3200
3516
  throw new Error("User address is required");
@@ -3311,12 +3627,489 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3311
3627
  txHash,
3312
3628
  smartWallet: safeAddress,
3313
3629
  amount: amountBigInt.toString(),
3630
+ route: "direct",
3314
3631
  registration
3315
3632
  };
3316
3633
  } catch (error) {
3317
3634
  throw new Error(`Deposit failed: ${error.message}`);
3318
3635
  }
3319
3636
  }
3637
+ async sendDeposit(userAddressOrParams, chainId, amount, asset, strategy) {
3638
+ if (typeof userAddressOrParams !== "string") {
3639
+ return this.sendRoutedDeposit(userAddressOrParams);
3640
+ }
3641
+ if (chainId === void 0 || amount === void 0 || asset === void 0) {
3642
+ throw new Error(
3643
+ "Deposit failed: chainId, amount, and asset are required"
3644
+ );
3645
+ }
3646
+ return this.sendDirectDeposit(
3647
+ userAddressOrParams,
3648
+ chainId,
3649
+ amount,
3650
+ asset,
3651
+ strategy
3652
+ );
3653
+ }
3654
+ /**
3655
+ * Resolve a deposit without signing.
3656
+ *
3657
+ * @remarks
3658
+ * A collateral the wallet already holds on `chainId` returns `route: "direct"`.
3659
+ * Same-chain native ETH into WETH returns `route: "wrap"`. Any other spend
3660
+ * token returns a Relay review quote (`route: "swap"`). Nothing is signed.
3661
+ * Optional `slippageBps` (default 200, max 500) is stored on that funding
3662
+ * order and reused when the quote is refreshed for signing.
3663
+ *
3664
+ * @group Deposits and withdrawals
3665
+ *
3666
+ * @param params - Destination collateral and optional spend token
3667
+ * @returns The route, and a review quote when a swap is required
3668
+ *
3669
+ * @throws If the spend token or destination collateral is not supported
3670
+ */
3671
+ async quoteDeposit(params) {
3672
+ if (!params.userAddress) throw new Error("User address is required");
3673
+ if (!isSupportedChain(params.chainId)) {
3674
+ throw new Error(`Unsupported chain ID: ${params.chainId}`);
3675
+ }
3676
+ if (!params.amount || BigInt(params.amount) <= 0n) {
3677
+ throw new Error("Valid amount is required");
3678
+ }
3679
+ const route = resolveDepositRoute(params);
3680
+ if (route.kind === "direct" || route.kind === "wrap") {
3681
+ return {
3682
+ route: route.kind,
3683
+ asset: route.asset,
3684
+ chainId: params.chainId,
3685
+ amount: params.amount
3686
+ };
3687
+ }
3688
+ const quote = await this.quoteSwapDeposit({
3689
+ userAddress: params.userAddress,
3690
+ originChainId: route.originChainId,
3691
+ originCurrency: route.originCurrency,
3692
+ originAmount: params.amount,
3693
+ destinationChainId: params.chainId,
3694
+ destinationAsset: route.destinationAsset,
3695
+ strategy: params.strategy,
3696
+ slippageBps: params.slippageBps
3697
+ });
3698
+ return { route: "swap", ...quote };
3699
+ }
3700
+ /**
3701
+ * Quote a Relay swap that delivers a collateral token to the Safe.
3702
+ *
3703
+ * @remarks
3704
+ * Creates a funding order on the execution API. The connected wallet does
3705
+ * not sign. Pass `orderId` to {@link ZyfaiSDK.sendSwapDeposit} to sign the
3706
+ * refreshed quote, or call {@link ZyfaiSDK.sendDeposit} to quote and sign
3707
+ * in one step.
3708
+ *
3709
+ * Same-chain native ETH into WETH is rejected here. Use {@link ZyfaiSDK.sendDeposit}
3710
+ * with `spendToken: "ETH"`, which wraps in the wallet.
3711
+ *
3712
+ * Optional `slippageBps` defaults to 200 (max 500) and is fixed when this
3713
+ * funding order is created. Sign-time refresh reuses the stored value.
3714
+ *
3715
+ * @group Deposits and withdrawals
3716
+ *
3717
+ * @param params - Origin token, destination collateral, and funding wallet
3718
+ * @returns Review quote. Not yet signed.
3719
+ *
3720
+ * @throws If the server rejects the pair, the amount, or the quote
3721
+ */
3722
+ async quoteSwapDeposit(params) {
3723
+ this.assertSwapDepositParams(params);
3724
+ await this.authenticateUser();
3725
+ const created = await this.httpClient.post(
3726
+ ENDPOINTS.FUNDING_ORDERS,
3727
+ {
3728
+ originChainId: params.originChainId,
3729
+ destinationChainId: params.destinationChainId,
3730
+ originCurrency: params.originCurrency,
3731
+ originAmount: params.originAmount,
3732
+ destinationAsset: params.destinationAsset.toUpperCase(),
3733
+ fundingWallet: params.userAddress,
3734
+ ...params.slippageBps != null ? { slippageBps: resolveRelaySlippageBps(params.slippageBps) } : {}
3735
+ }
3736
+ );
3737
+ return {
3738
+ orderId: created.orderId,
3739
+ status: created.status,
3740
+ spend: created.spend,
3741
+ expectedOutput: created.expectedOutput,
3742
+ minimumOutput: created.minimumOutput,
3743
+ destinationChainId: created.destinationChainId,
3744
+ destinationCurrency: created.destinationCurrency,
3745
+ destinationAsset: params.destinationAsset.toUpperCase(),
3746
+ fees: created.fees ?? [],
3747
+ investEligible: created.investEligible,
3748
+ expiresAt: created.expiresAt ?? null,
3749
+ timeEstimate: created.timeEstimate ?? null
3750
+ };
3751
+ }
3752
+ /**
3753
+ * Read a Relay funding order, including a linked deposit once credit starts.
3754
+ *
3755
+ * @group Deposits and withdrawals
3756
+ *
3757
+ * @param orderId - Id from {@link ZyfaiSDK.quoteSwapDeposit}
3758
+ * @returns Stored order
3759
+ *
3760
+ * @throws If `orderId` is missing
3761
+ */
3762
+ async getSwapDeposit(orderId) {
3763
+ if (!orderId) throw new Error("Funding order id is required");
3764
+ await this.authenticateUser();
3765
+ return this.httpClient.get(ENDPOINTS.FUNDING_ORDER(orderId));
3766
+ }
3767
+ /**
3768
+ * Swap or bridge a token into a Zyfai collateral, then register the deposit.
3769
+ *
3770
+ * @remarks
3771
+ * The execution API quotes Relay with the Safe as recipient. This method
3772
+ * refreshes that quote, signs the steps with the connected wallet, waits
3773
+ * for the collateral transfer into the Safe, and calls {@link ZyfaiSDK.logDeposit}.
3774
+ * Credit still requires that verified transfer. A refund or failed fill does
3775
+ * not register a deposit.
3776
+ *
3777
+ * Requires {@link ZyfaiSDK.connectAccount}. Origin chains other than
3778
+ * Ethereum, Base, and Arbitrum need an EIP-1193 wallet that can sign there.
3779
+ *
3780
+ * Optional `slippageBps` defaults to 200 (max 500) and is fixed when the
3781
+ * funding order is created. A later call that passes `orderId` ignores
3782
+ * `slippageBps` and signs the stored order.
3783
+ *
3784
+ * @group Deposits and withdrawals
3785
+ *
3786
+ * @param params - Origin token and destination collateral
3787
+ * @returns Destination transfer and deposit registration
3788
+ *
3789
+ * @throws If the quote, signature, fill, or registration fails, or if
3790
+ * `orderId` names a funding order whose origin or destination differs from
3791
+ * this call
3792
+ *
3793
+ * @see {@link ZyfaiSDK.sendDeposit}
3794
+ *
3795
+ * @example
3796
+ * ```typescript
3797
+ * await sdk.connectAccount(provider);
3798
+ * const sent = await sdk.sendSwapDeposit({
3799
+ * userAddress: eoa,
3800
+ * originChainId: 42161,
3801
+ * originCurrency: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
3802
+ * originAmount: "10000000",
3803
+ * destinationChainId: 8453,
3804
+ * destinationAsset: "WETH",
3805
+ * });
3806
+ * ```
3807
+ */
3808
+ async sendSwapDeposit(params) {
3809
+ try {
3810
+ this.assertSwapDepositParams(params);
3811
+ await this.authenticateUser();
3812
+ await this.prepareFirstDeposit(params.strategy);
3813
+ let orderId;
3814
+ let destinationCurrency;
3815
+ let storedMinimum;
3816
+ if (params.orderId) {
3817
+ const existing = await this.getSwapDeposit(params.orderId);
3818
+ assertStoredFundingOrderRoute(existing, params);
3819
+ orderId = existing.id;
3820
+ destinationCurrency = existing.destinationCurrency;
3821
+ storedMinimum = existing.minimumOutput;
3822
+ } else {
3823
+ const created = await this.quoteSwapDeposit(params);
3824
+ orderId = created.orderId;
3825
+ destinationCurrency = created.destinationCurrency;
3826
+ storedMinimum = created.minimumOutput;
3827
+ }
3828
+ const signQuote = await this.httpClient.post(ENDPOINTS.FUNDING_ORDER_QUOTE(orderId));
3829
+ if (!signQuote.quote) {
3830
+ throw new Error("Relay funding quote is missing from the server response");
3831
+ }
3832
+ const minimumOutput = resolveCollateralMinimum(
3833
+ storedMinimum,
3834
+ signQuote.quote
3835
+ );
3836
+ await this.assertCollateralMinimum(
3837
+ params.userAddress,
3838
+ params.destinationChainId,
3839
+ params.destinationAsset,
3840
+ BigInt(minimumOutput)
3841
+ );
3842
+ ensureRelaySdkClient();
3843
+ const walletClient = await this.walletClientForOrigin(params.originChainId);
3844
+ const { data: execution } = await execute({
3845
+ quote: signQuote.quote,
3846
+ wallet: walletClient
3847
+ });
3848
+ const sourceTxHashes = collectRelaySourceTxHashes(
3849
+ execution,
3850
+ params.originChainId
3851
+ );
3852
+ const destinationFromExecution = collectRelayDestinationTxHashes(
3853
+ execution,
3854
+ params.destinationChainId
3855
+ );
3856
+ await this.httpClient.post(ENDPOINTS.FUNDING_ORDER_EXECUTION(orderId), {
3857
+ sourceTxHashes: sourceTxHashes.length ? sourceTxHashes : void 0,
3858
+ stepStatus: "submitted"
3859
+ });
3860
+ await this.hydrateSessionWallet();
3861
+ const safeAddress = await this.getSafeAddressFor(
3862
+ params.userAddress,
3863
+ params.destinationChainId
3864
+ );
3865
+ if (!safeAddress) {
3866
+ throw new Error("Smart wallet address is not available");
3867
+ }
3868
+ const filled = await this.waitForRelayCreditTx({
3869
+ orderId,
3870
+ destinationChainId: params.destinationChainId,
3871
+ destinationToken: destinationCurrency,
3872
+ recipientSafe: safeAddress,
3873
+ initialCandidates: destinationFromExecution
3874
+ });
3875
+ const creditAmount = filled.amount.toString();
3876
+ const registration = await this.registerDeposit(
3877
+ params.destinationChainId,
3878
+ filled.hash,
3879
+ creditAmount,
3880
+ destinationCurrency
3881
+ );
3882
+ return {
3883
+ success: true,
3884
+ txHash: filled.hash,
3885
+ smartWallet: safeAddress,
3886
+ amount: creditAmount,
3887
+ route: "swap",
3888
+ orderId,
3889
+ registration
3890
+ };
3891
+ } catch (error) {
3892
+ const message = thrownMessage(error);
3893
+ throw new Error(
3894
+ message.startsWith("Deposit failed:") ? message : `Deposit failed: ${message}`
3895
+ );
3896
+ }
3897
+ }
3898
+ async sendRoutedDeposit(params) {
3899
+ try {
3900
+ if (!params.userAddress) throw new Error("User address is required");
3901
+ if (!isSupportedChain(params.chainId)) {
3902
+ throw new Error(`Unsupported chain ID: ${params.chainId}`);
3903
+ }
3904
+ if (!params.amount || BigInt(params.amount) <= 0n) {
3905
+ throw new Error("Valid amount is required");
3906
+ }
3907
+ const route = resolveDepositRoute(params);
3908
+ if (route.kind === "direct") {
3909
+ return this.sendDirectDeposit(
3910
+ params.userAddress,
3911
+ params.chainId,
3912
+ params.amount,
3913
+ route.asset,
3914
+ params.strategy
3915
+ );
3916
+ }
3917
+ if (route.kind === "wrap") {
3918
+ await this.assertCollateralMinimum(
3919
+ params.userAddress,
3920
+ params.chainId,
3921
+ "WETH",
3922
+ BigInt(params.amount)
3923
+ );
3924
+ await this.wrapNativeEth(params.chainId, params.amount);
3925
+ const sent = await this.sendDirectDeposit(
3926
+ params.userAddress,
3927
+ params.chainId,
3928
+ params.amount,
3929
+ "WETH",
3930
+ params.strategy
3931
+ );
3932
+ return { ...sent, route: "wrap" };
3933
+ }
3934
+ return this.sendSwapDeposit({
3935
+ userAddress: params.userAddress,
3936
+ originChainId: route.originChainId,
3937
+ originCurrency: route.originCurrency,
3938
+ originAmount: params.amount,
3939
+ destinationChainId: params.chainId,
3940
+ destinationAsset: route.destinationAsset,
3941
+ strategy: params.strategy,
3942
+ slippageBps: params.slippageBps
3943
+ });
3944
+ } catch (error) {
3945
+ const message = thrownMessage(error);
3946
+ throw new Error(
3947
+ message.startsWith("Deposit failed:") ? message : `Deposit failed: ${message}`
3948
+ );
3949
+ }
3950
+ }
3951
+ /** Portfolio floor used by a direct deposit, applied before a wrap or swap spends. */
3952
+ async assertCollateralMinimum(userAddress, chainId, asset, amount) {
3953
+ const symbol = Object.keys(ASSET_CONFIGS).find(
3954
+ (key) => key.toLowerCase() === asset.toLowerCase()
3955
+ );
3956
+ if (!symbol || !getAssetChainIds(symbol).includes(chainId)) return;
3957
+ await this.hydrateSessionWallet();
3958
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3959
+ if (!safeAddress) {
3960
+ throw new Error("Smart wallet address is not available");
3961
+ }
3962
+ await this.enforceMinimumPortfolioBalance(
3963
+ chainId,
3964
+ symbol,
3965
+ amount,
3966
+ safeAddress,
3967
+ userAddress
3968
+ );
3969
+ }
3970
+ assertSwapDepositParams(params) {
3971
+ if (!params.userAddress) throw new Error("User address is required");
3972
+ if (!params.originAmount || BigInt(params.originAmount) <= 0n) {
3973
+ throw new Error("Valid origin amount is required");
3974
+ }
3975
+ if (!Number.isInteger(params.originChainId) || params.originChainId <= 0) {
3976
+ throw new Error("Valid origin chain is required");
3977
+ }
3978
+ if (!isSupportedChain(params.destinationChainId)) {
3979
+ throw new Error(`Unsupported chain ID: ${params.destinationChainId}`);
3980
+ }
3981
+ if (!params.originCurrency) throw new Error("Origin token is required");
3982
+ if (!params.destinationAsset) throw new Error("Destination asset is required");
3983
+ if (params.slippageBps != null) {
3984
+ if (!Number.isInteger(params.slippageBps) || params.slippageBps < 1 || params.slippageBps > MAX_RELAY_SLIPPAGE_BPS) {
3985
+ throw new Error(
3986
+ `slippageBps must be an integer from 1 to ${MAX_RELAY_SLIPPAGE_BPS}. Received ${params.slippageBps}.`
3987
+ );
3988
+ }
3989
+ }
3990
+ if (params.destinationAsset.toUpperCase() === "WETH" && params.originChainId === params.destinationChainId && isNativeSpendToken(params.originCurrency)) {
3991
+ throw new Error(
3992
+ 'Same-chain ETH to WETH is a wrap, not a Relay swap. Call sendDeposit with spendToken "ETH".'
3993
+ );
3994
+ }
3995
+ }
3996
+ async walletClientForOrigin(originChainId) {
3997
+ if (this.signer) {
3998
+ if (!isSupportedChain(originChainId)) {
3999
+ throw new Error(
4000
+ `Cannot sign a swap from chain ${originChainId} with a private key. Connect an EIP-1193 wallet, or spend from Ethereum, Base, or Arbitrum.`
4001
+ );
4002
+ }
4003
+ return this.getWalletClient(originChainId);
4004
+ }
4005
+ if (!this.walletClient?.account) {
4006
+ throw new Error("No account connected. Call connectAccount() first");
4007
+ }
4008
+ if (!this.currentProvider?.request) {
4009
+ if (this.walletClient.chain?.id === originChainId) return this.walletClient;
4010
+ throw new Error(
4011
+ `Wallet is on chain ${this.walletClient.chain?.id ?? "unknown"}. Switch it to chain ${originChainId} before this swap.`
4012
+ );
4013
+ }
4014
+ await this.currentProvider.request({
4015
+ method: "wallet_switchEthereumChain",
4016
+ params: [{ chainId: `0x${originChainId.toString(16)}` }]
4017
+ });
4018
+ const chain = isSupportedChain(originChainId) ? getChainConfig(originChainId, this.rpcUrls).chain : defineChain({
4019
+ id: originChainId,
4020
+ name: `Chain ${originChainId}`,
4021
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
4022
+ rpcUrls: { default: { http: ["http://127.0.0.1"] } }
4023
+ });
4024
+ this.walletClient = createWalletClient({
4025
+ account: this.walletClient.account,
4026
+ chain,
4027
+ transport: custom(this.currentProvider)
4028
+ });
4029
+ if (isSupportedChain(originChainId)) {
4030
+ this.currentChainId = originChainId;
4031
+ }
4032
+ return this.walletClient;
4033
+ }
4034
+ async wrapNativeEth(chainId, amount) {
4035
+ const token = getDefaultTokenAddress(chainId, "WETH");
4036
+ const walletClient = this.getWalletClient(chainId);
4037
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
4038
+ const hash = await walletClient.writeContract({
4039
+ address: token,
4040
+ abi: WETH_DEPOSIT_ABI,
4041
+ functionName: "deposit",
4042
+ value: BigInt(amount),
4043
+ chain: chainConfig.chain,
4044
+ account: walletClient.account
4045
+ });
4046
+ const receipt = await chainConfig.publicClient.waitForTransactionReceipt({
4047
+ hash
4048
+ });
4049
+ if (receipt.status !== "success") {
4050
+ throw new Error("ETH wrap failed");
4051
+ }
4052
+ }
4053
+ async waitForRelayCreditTx(params) {
4054
+ const chainConfig = getChainConfig(params.destinationChainId, this.rpcUrls);
4055
+ const receipts = /* @__PURE__ */ new Map();
4056
+ const maxAttempts = 120;
4057
+ const intervalMs = 5e3;
4058
+ const loadReceipt = async (hash) => {
4059
+ const key = hash.toLowerCase();
4060
+ if (receipts.has(key)) return;
4061
+ try {
4062
+ const receipt = await chainConfig.publicClient.getTransactionReceipt({
4063
+ hash
4064
+ });
4065
+ receipts.set(key, {
4066
+ status: receipt.status,
4067
+ logs: receipt.logs.map((log) => ({
4068
+ address: log.address,
4069
+ topics: log.topics,
4070
+ data: log.data
4071
+ }))
4072
+ });
4073
+ } catch {
4074
+ }
4075
+ };
4076
+ const pick = async (candidates) => {
4077
+ for (const hash2 of candidates) {
4078
+ if (hash2) await loadReceipt(hash2);
4079
+ }
4080
+ const hash = selectRelayCreditTxHash({
4081
+ candidates,
4082
+ receipts,
4083
+ token: params.destinationToken,
4084
+ recipient: params.recipientSafe
4085
+ });
4086
+ if (!hash) return null;
4087
+ const receipt = receipts.get(hash.toLowerCase());
4088
+ return {
4089
+ hash,
4090
+ amount: receipt ? transferAmountTo(
4091
+ receipt.logs,
4092
+ params.destinationToken,
4093
+ params.recipientSafe
4094
+ ) : 0n
4095
+ };
4096
+ };
4097
+ const immediate = await pick(params.initialCandidates);
4098
+ if (immediate) return immediate;
4099
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
4100
+ const order = await this.getSwapDeposit(params.orderId);
4101
+ if (order.status === "refunded" || order.status === "failed") {
4102
+ throw new Error(`Relay funding ${order.status}`);
4103
+ }
4104
+ const match = await pick([
4105
+ ...params.initialCandidates,
4106
+ ...order.destinationTxHashes ?? []
4107
+ ]);
4108
+ if (match) return match;
4109
+ await sleep(intervalMs);
4110
+ }
4111
+ throw new Error("Relay funding is still converting");
4112
+ }
3320
4113
  /**
3321
4114
  * @deprecated Compatibility convenience method. Prefer {@link ZyfaiSDK.sendDeposit} followed by
3322
4115
  * {@link ZyfaiSDK.waitForDepositCredit} when the caller owns the completion UX.
@@ -3482,7 +4275,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3482
4275
  }
3483
4276
  await this.authenticateUser();
3484
4277
  const usdcDetails = await this.getUserDetails("USDC");
3485
- if ((usdcDetails.chains?.length ?? 0) > 0) {
4278
+ const usdcChainsConfigured = (usdcDetails.chains?.length ?? 0) > 0;
4279
+ const usdcProtocolsConfigured = (usdcDetails.protocols?.length ?? 0) > 0;
4280
+ if (usdcChainsConfigured && usdcProtocolsConfigured) {
3486
4281
  return { applied: false };
3487
4282
  }
3488
4283
  await this.updateUserProtocols(strategy, { strict: true });
@@ -3492,6 +4287,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3492
4287
  "First-deposit setup did not persist USDC chain configuration."
3493
4288
  );
3494
4289
  }
4290
+ if ((usdcAfterSetup.protocols?.length ?? 0) === 0) {
4291
+ throw new Error(
4292
+ "First-deposit setup did not persist USDC protocol configuration."
4293
+ );
4294
+ }
3495
4295
  return { applied: true };
3496
4296
  }
3497
4297
  /**
@@ -3508,7 +4308,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3508
4308
  }
3509
4309
  await this.authenticateUser();
3510
4310
  const details = await this.getUserDetails(asset);
3511
- if (details.chains?.includes(chainId)) {
4311
+ const chainConfigured = details.chains?.includes(chainId) ?? false;
4312
+ const protocolsConfigured = (details.protocols?.length ?? 0) > 0;
4313
+ if (chainConfigured && protocolsConfigured) {
3512
4314
  return { applied: false };
3513
4315
  }
3514
4316
  const allProtocols = await this.httpClient.get(
@@ -3526,8 +4328,20 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3526
4328
  `First-deposit setup did not persist ${asset} chain ${chainId} configuration.`
3527
4329
  );
3528
4330
  }
4331
+ if ((afterSetup.protocols?.length ?? 0) === 0) {
4332
+ throw new Error(
4333
+ `First-deposit setup did not persist ${asset} protocol configuration.`
4334
+ );
4335
+ }
3529
4336
  return { applied: true };
3530
4337
  }
4338
+ /**
4339
+ * Persist the deposit asset on one chain before a signing page runs the transfer or swap.
4340
+ * Does not build calldata and does not check the portfolio minimum.
4341
+ */
4342
+ async ensureDepositAssetOnChain(params) {
4343
+ return this.ensureDepositProfileForPrepare(params);
4344
+ }
3531
4345
  /**
3532
4346
  * Prepare a deposit: persist first-deposit profile when needed and return
3533
4347
  * ERC-20 transfer calldata for the user to sign (does not broadcast).
@@ -3723,7 +4537,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3723
4537
  const started = Date.now();
3724
4538
  while (Date.now() - started < timeoutMs) {
3725
4539
  const status = await this.getDepositStatus(depositId);
3726
- if (status.status === "credited" && status.balanceCredited) {
4540
+ if (status.balanceCredited && status.status !== "recovered_to_eoa") {
3727
4541
  return status;
3728
4542
  }
3729
4543
  if (status.status === "recovered_to_eoa") {
@@ -3738,6 +4552,134 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3738
4552
  }
3739
4553
  throw new DepositCreditTimeoutError(depositId);
3740
4554
  }
4555
+ /**
4556
+ * Poll deposit status until funds are allocated to a protocol position, skipped, or failed.
4557
+ * Crosschain deposits resolve once the bridge tx is recorded (`crosschain: true`, `executionTxHash` set);
4558
+ * the destination-chain allocation is not tracked on this lifecycle.
4559
+ */
4560
+ async waitForDepositPosition(depositId, chainId, options) {
4561
+ if (!depositId) {
4562
+ throw new Error("Deposit ID is required");
4563
+ }
4564
+ if (!isSupportedChain(chainId)) {
4565
+ throw new Error(`Unsupported chain ID: ${chainId}`);
4566
+ }
4567
+ const intervalMs = options?.intervalMs ?? getUserOpLifecycleIntervalMs(chainId);
4568
+ const timeoutMs = options?.timeoutMs ?? getUserOpLifecycleTimeoutMs(chainId);
4569
+ const started = Date.now();
4570
+ while (Date.now() - started < timeoutMs) {
4571
+ const status = await this.getDepositStatus(depositId);
4572
+ if (status.positionOutcome === "failed") {
4573
+ throw new Error(
4574
+ `Deposit ${depositId} position allocation failed (status=${status.status})`
4575
+ );
4576
+ }
4577
+ if (status.status === "positioned") {
4578
+ return status;
4579
+ }
4580
+ if (status.positionOutcome === "skipped") {
4581
+ return status;
4582
+ }
4583
+ if (status.crosschain && status.executionTxHash) {
4584
+ return status;
4585
+ }
4586
+ if (status.status === "recovered_to_eoa") {
4587
+ throw new Error(
4588
+ `Deposit ${depositId} recovered to EOA; position was not opened`
4589
+ );
4590
+ }
4591
+ await sleep(intervalMs);
4592
+ }
4593
+ throw new DepositPositionTimeoutError(depositId);
4594
+ }
4595
+ async getWithdrawStatus(withdrawalId) {
4596
+ if (!withdrawalId) {
4597
+ throw new Error("Withdrawal lifecycle ID is required");
4598
+ }
4599
+ await this.authenticateUser();
4600
+ return this.httpClient.get(
4601
+ ENDPOINTS.WITHDRAW_STATUS(withdrawalId)
4602
+ );
4603
+ }
4604
+ /**
4605
+ * Short poll: completes when sync slice settles, async enters cooldown, or claim is already in flight (resume/retry).
4606
+ */
4607
+ async waitForWithdrawSettlement(withdrawalId, chainId, options) {
4608
+ if (!withdrawalId) {
4609
+ throw new Error("Withdrawal lifecycle ID is required");
4610
+ }
4611
+ if (!isSupportedChain(chainId)) {
4612
+ throw new Error(`Unsupported chain ID: ${chainId}`);
4613
+ }
4614
+ const intervalMs = options?.intervalMs ?? getUserOpLifecycleIntervalMs(chainId);
4615
+ const timeoutMs = options?.timeoutMs ?? getUserOpLifecycleTimeoutMs(chainId);
4616
+ const started = Date.now();
4617
+ while (Date.now() - started < timeoutMs) {
4618
+ const status = await this.getWithdrawStatus(withdrawalId);
4619
+ if (isWithdrawSettlementTerminal(status.status)) {
4620
+ return status;
4621
+ }
4622
+ if (status.status === "failed") {
4623
+ throw new Error(
4624
+ `Withdraw ${withdrawalId} failed: ${status.lastError ?? "unknown"}`
4625
+ );
4626
+ }
4627
+ await sleep(intervalMs);
4628
+ }
4629
+ throw new WithdrawSettlementTimeoutError(withdrawalId);
4630
+ }
4631
+ /**
4632
+ * Long poll through async cooldown and claim until lifecycle is completed.
4633
+ */
4634
+ async waitForWithdrawComplete(withdrawalId, chainId, options) {
4635
+ if (!withdrawalId) {
4636
+ throw new Error("Withdrawal lifecycle ID is required");
4637
+ }
4638
+ if (!isSupportedChain(chainId)) {
4639
+ throw new Error(`Unsupported chain ID: ${chainId}`);
4640
+ }
4641
+ const fastIntervalMs = options?.intervalMs ?? getUserOpLifecycleIntervalMs(chainId);
4642
+ const cooldownIntervalMs = options?.cooldownIntervalMs ?? ASYNC_WITHDRAW_COOLDOWN_POLL_INTERVAL_MS;
4643
+ const started = Date.now();
4644
+ const fallbackMs = getUserOpLifecycleTimeoutMs(chainId) + ASYNC_WITHDRAW_CLAIM_GRACE_MS;
4645
+ let deadlineMs = nextWithdrawCompleteDeadline(
4646
+ started,
4647
+ void 0,
4648
+ void 0,
4649
+ {
4650
+ explicitTimeoutMs: options?.timeoutMs,
4651
+ graceMs: ASYNC_WITHDRAW_CLAIM_GRACE_MS,
4652
+ fallbackMs
4653
+ }
4654
+ );
4655
+ while (true) {
4656
+ const status = await this.getWithdrawStatus(withdrawalId);
4657
+ if (status.status === "completed") {
4658
+ return status;
4659
+ }
4660
+ if (status.status === "failed") {
4661
+ throw new Error(
4662
+ `Withdraw ${withdrawalId} failed: ${status.lastError ?? "unknown"}`
4663
+ );
4664
+ }
4665
+ deadlineMs = nextWithdrawCompleteDeadline(
4666
+ started,
4667
+ deadlineMs,
4668
+ status.estimatedClaimAt,
4669
+ {
4670
+ explicitTimeoutMs: options?.timeoutMs,
4671
+ graceMs: ASYNC_WITHDRAW_CLAIM_GRACE_MS,
4672
+ fallbackMs
4673
+ }
4674
+ );
4675
+ if (Date.now() >= deadlineMs) {
4676
+ break;
4677
+ }
4678
+ const intervalMs = status.status === "async_cooldown" ? cooldownIntervalMs : fastIntervalMs;
4679
+ await sleep(intervalMs);
4680
+ }
4681
+ throw new WithdrawCompleteTimeoutError(withdrawalId);
4682
+ }
3741
4683
  /**
3742
4684
  * Withdraw funds from Safe smart wallet
3743
4685
  * Initiates a withdrawal request to the Zyfai API
@@ -3833,17 +4775,28 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3833
4775
  response = await this.httpClient.get(ENDPOINTS.USER_WITHDRAW, {
3834
4776
  params: { chainId, tokenSymbol }
3835
4777
  });
3836
- console.log(JSON.stringify(response, null, 2));
3837
4778
  }
3838
4779
  const success = response?.success ?? true;
3839
4780
  const message = response?.message || "Withdrawal request sent";
3840
4781
  const txHash = response?.txHash || response?.transactionHash;
4782
+ const lifecycleId = response?.id;
4783
+ const lifecycle = lifecycleId && response?.statusUrl ? {
4784
+ id: lifecycleId,
4785
+ status: "accepted",
4786
+ chainId,
4787
+ tokenSymbol: tokenSymbol ?? null,
4788
+ syncSettled: false,
4789
+ asyncLegs: [],
4790
+ failedAsyncIds: [],
4791
+ statusUrl: response.statusUrl
4792
+ } : void 0;
3841
4793
  return {
3842
4794
  success,
3843
4795
  message,
3844
4796
  txHash,
3845
4797
  type: amount ? "partial" : "full",
3846
- amount: amount || "all"
4798
+ amount: amount || "all",
4799
+ lifecycle
3847
4800
  };
3848
4801
  } catch (error) {
3849
4802
  throw new Error(`Withdrawal failed: ${error.message}`);
@@ -6010,6 +6963,7 @@ export {
6010
6963
  API_ENDPOINT,
6011
6964
  DATA_API_BASE_URLS,
6012
6965
  DATA_API_ENDPOINT,
6966
+ DEFAULT_RELAY_SLIPPAGE_BPS,
6013
6967
  DEFAULT_TOKEN_ADDRESSES,
6014
6968
  ERC7579_LAUNCHPAD_ADDRESS,
6015
6969
  EXECUTION_API_BASE_URLS,
@@ -6018,9 +6972,11 @@ export {
6018
6972
  LOCAL_DATA_API_BASE_URL,
6019
6973
  LOCAL_EXECUTION_API_BASE_URL,
6020
6974
  LOCAL_WS_URL,
6975
+ MAX_RELAY_SLIPPAGE_BPS,
6021
6976
  OWNABLE_VALIDATOR,
6022
6977
  POOL_MODULE_ADDRESSES,
6023
6978
  PROXY_EXECUTOR,
6979
+ RELAY_SLIPPAGE_PRESETS_BPS,
6024
6980
  SAFE_7579_ADDRESS,
6025
6981
  SMART_SESSIONS_FALLBACK,
6026
6982
  SMART_SESSIONS_VALIDATOR,
@@ -6039,5 +6995,7 @@ export {
6039
6995
  getManagedAssets,
6040
6996
  getSupportedChainIds,
6041
6997
  getWsUrl,
6042
- isSupportedChain
6998
+ isSupportedChain,
6999
+ resolveDepositRoute,
7000
+ resolveRelaySlippageBps
6043
7001
  };