@zyfai/sdk 1.9.2 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -59,9 +59,11 @@ __export(index_exports, {
59
59
  WS_ENDPOINT: () => WS_ENDPOINT,
60
60
  WS_URLS: () => WS_URLS,
61
61
  ZyfaiSDK: () => ZyfaiSDK,
62
+ buildNestedSafeOnboardingStatus: () => buildNestedSafeOnboardingStatus,
62
63
  buildV1ChainSessions: () => buildV1ChainSessions,
63
64
  createBankrProvider: () => createBankrProvider,
64
65
  decodeUserOperationCalls: () => decodeUserOperationCalls,
66
+ deriveNestedSafeOnboardingStep: () => deriveNestedSafeOnboardingStep,
65
67
  getChainConfig: () => getChainConfig,
66
68
  getDataApiBaseUrl: () => getDataApiBaseUrl,
67
69
  getDefaultTokenAddress: () => getDefaultTokenAddress,
@@ -74,6 +76,7 @@ __export(index_exports, {
74
76
  isSupportedChain: () => isSupportedChain,
75
77
  parseUserOperationJson: () => parseUserOperationJson,
76
78
  parseV1ChainSessions: () => parseV1ChainSessions,
79
+ portfolioHasWithdrawableBalance: () => portfolioHasWithdrawableBalance,
77
80
  resolveDepositRoute: () => resolveDepositRoute,
78
81
  resolveRelaySlippageBps: () => resolveRelaySlippageBps,
79
82
  serializeV1ChainSessions: () => serializeV1ChainSessions
@@ -1678,6 +1681,15 @@ var getAccountType = async (address, publicClient) => {
1678
1681
  return "Unknown";
1679
1682
  }
1680
1683
  };
1684
+ function isSafeDeployPermissionsReady(prepare) {
1685
+ return prepare.success && !prepare.userOpHashToSign && prepare.signingMode !== "typed-data";
1686
+ }
1687
+ async function postSafeDeployPrepare(httpClient, chainId, strategyBody = {}) {
1688
+ return await httpClient.post(
1689
+ `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1690
+ strategyBody
1691
+ );
1692
+ }
1681
1693
  var signNestedSafeDeployTypedData = async (owner, parentSafe, typedData) => {
1682
1694
  if (!owner.account) {
1683
1695
  throw new Error("Wallet not connected. Please connect your wallet first.");
@@ -1725,12 +1737,13 @@ var deploySafeAccount = async (config) => {
1725
1737
  }
1726
1738
  console.log("strategy", strategy);
1727
1739
  const strategyBody = strategy ? { strategy } : {};
1728
- const prepareResponse = await httpClient.post(
1729
- `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1740
+ const prepareResponse = await postSafeDeployPrepare(
1741
+ httpClient,
1742
+ chainId,
1730
1743
  strategyBody
1731
1744
  );
1732
1745
  console.log("prepareResponse", prepareResponse);
1733
- if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1746
+ if (isSafeDeployPermissionsReady(prepareResponse)) {
1734
1747
  return {
1735
1748
  safeAddress: prepareResponse.safeAddress || "0x",
1736
1749
  txHash: "0x0",
@@ -1969,35 +1982,6 @@ function sameAddress(left, right) {
1969
1982
  return false;
1970
1983
  }
1971
1984
  }
1972
- function transferMatches(transaction, params) {
1973
- if (!sameAddress(transaction.to, params.tokenAddress)) return false;
1974
- if (transaction.isSuccessful === false) return false;
1975
- const decoded = transaction.dataDecoded;
1976
- if (decoded?.method?.toLowerCase() !== "transfer") return false;
1977
- const parameters = decoded.parameters;
1978
- if (!parameters) return false;
1979
- const destination = parameters.find(
1980
- (p) => (p.name === "to" || p.name === "dst" || p.name === "_to") && p.type === "address"
1981
- );
1982
- if (!sameAddress(destination?.value, params.childSafe)) return false;
1983
- if (params.amount === void 0) return true;
1984
- const valueParam = parameters.find(
1985
- (p) => (p.name === "value" || p.name === "amount" || p.name === "_value" || p.name === "wad") && p.type.startsWith("uint")
1986
- );
1987
- if (!valueParam) return false;
1988
- try {
1989
- return BigInt(valueParam.value) === params.amount;
1990
- } catch {
1991
- return false;
1992
- }
1993
- }
1994
- function isWithinWindow(transaction, since) {
1995
- if (!since) return true;
1996
- const stamp = transaction.executionDate ?? transaction.submissionDate;
1997
- if (!stamp) return false;
1998
- const at = Date.parse(stamp);
1999
- return Number.isFinite(at) && at >= since.getTime();
2000
- }
2001
1985
  async function findSafeTransferByHash(params) {
2002
1986
  const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
2003
1987
  const url = `https://api.safe.global/tx-service/${networkName}/api/v2/multisig-transactions/${params.safeTxHash}/`;
@@ -2016,54 +2000,101 @@ async function findSafeTransferByHash(params) {
2016
2000
  isExecuted: transaction.isExecuted === true && !!transaction.transactionHash
2017
2001
  };
2018
2002
  }
2019
- async function findSafeTransferProposal(params) {
2020
- const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
2021
- const url = `https://api.safe.global/tx-service/${networkName}/api/v2/safes/${(0, import_viem7.getAddress)(
2022
- params.parentSafe
2023
- )}/multisig-transactions/?ordering=-nonce`;
2024
- const response = await fetch(url);
2025
- if (!response.ok) return null;
2026
- const body = await response.json();
2027
- const match = (body.results ?? []).find(
2028
- (transaction) => !!transaction.safeTxHash && isWithinWindow(transaction, params.since) && transferMatches(transaction, {
2029
- childSafe: params.childSafe,
2030
- tokenAddress: params.tokenAddress,
2031
- amount: params.amount
2032
- })
2033
- );
2034
- if (!match) return null;
2035
- return {
2036
- safeTxHash: match.safeTxHash,
2037
- transactionHash: match.transactionHash ?? null,
2038
- isExecuted: match.isExecuted === true && !!match.transactionHash
2039
- };
2040
- }
2041
- async function waitForSafeTransferExecution(params) {
2042
- safeTxServiceNetworkNameOrThrow(params.chainId);
2003
+ var TRANSFER_EVENT = (0, import_viem7.parseAbiItem)("event Transfer(address indexed from, address indexed to, uint256 value)");
2004
+ async function waitForExactSafeDepositExecution(params) {
2005
+ const started = Date.now();
2043
2006
  const timeoutMs = params.timeoutMs ?? NESTED_SAFE_DEPOSIT_TIMEOUT_MS;
2044
2007
  const pollMs = params.pollMs ?? NESTED_SAFE_DEPOSIT_POLL_MS;
2045
- const started = Date.now();
2046
- do {
2047
- const proposal = params.safeTxHash ? await findSafeTransferByHash({
2048
- chainId: params.chainId,
2049
- safeTxHash: params.safeTxHash
2050
- }) : await findSafeTransferProposal({
2051
- parentSafe: params.parentSafe,
2052
- childSafe: params.childSafe,
2053
- chainId: params.chainId,
2054
- tokenAddress: params.tokenAddress,
2055
- amount: params.amount,
2056
- since: params.since
2057
- });
2058
- if (proposal?.isExecuted && proposal.transactionHash) {
2059
- return proposal.transactionHash;
2008
+ let hash = params.proposalHash;
2009
+ try {
2010
+ do {
2011
+ const receipt = await params.publicClient.getTransactionReceipt({ hash }).catch(() => void 0);
2012
+ if (receipt) {
2013
+ if (receipt.status !== "success") throw new Error("Safe transfer reverted");
2014
+ const matches = receipt.logs.some((log) => {
2015
+ if (!sameAddress(log.address, params.tokenAddress)) return false;
2016
+ try {
2017
+ const decoded = (0, import_viem7.decodeEventLog)({ abi: [TRANSFER_EVENT], data: log.data, topics: log.topics });
2018
+ return sameAddress(decoded.args.from, params.parentSafe) && sameAddress(decoded.args.to, params.childSafe) && decoded.args.value === params.amount;
2019
+ } catch {
2020
+ return false;
2021
+ }
2022
+ });
2023
+ if (!matches) throw new Error("Executed transaction does not contain the expected parent-to-child transfer");
2024
+ return hash;
2025
+ }
2026
+ if (safeTxServiceNetworkName(params.chainId) && hash === params.proposalHash) {
2027
+ const proposal = await findSafeTransferByHash({ chainId: params.chainId, safeTxHash: params.proposalHash });
2028
+ if (proposal?.isExecuted && proposal.transactionHash) {
2029
+ hash = proposal.transactionHash;
2030
+ continue;
2031
+ }
2032
+ }
2033
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
2034
+ } while (Date.now() - started < timeoutMs);
2035
+ throw new Error("Timed out waiting for Safe transfer execution");
2036
+ } catch (error) {
2037
+ throw new Error(`Safe deposit proposal ${params.proposalHash}: ${error.message}. Resume this exact proposal with resumeNestedSafeDeposit; do not send another transfer.`);
2038
+ }
2039
+ }
2040
+
2041
+ // src/utils/nested-safe-onboarding.ts
2042
+ function positiveAmount(value) {
2043
+ if (!value) return false;
2044
+ const trimmed = value.trim();
2045
+ if (!trimmed || trimmed === "0" || trimmed === "0x" || trimmed === "0x0") {
2046
+ return false;
2047
+ }
2048
+ try {
2049
+ if (trimmed.startsWith("0x") || trimmed.startsWith("0X")) {
2050
+ return BigInt(trimmed) > 0n;
2060
2051
  }
2061
- await new Promise((resolve) => setTimeout(resolve, pollMs));
2062
- } while (Date.now() - started < timeoutMs);
2063
- throw new Error(
2064
- `Timed out waiting for Safe transfer from parent ${params.parentSafe} to child ${params.childSafe} on chain ${params.chainId} for token ${params.tokenAddress} amount ${params.amount.toString()}${params.safeTxHash ? ` (safeTxHash ${params.safeTxHash})` : ""}. Call sendDeposit again once co-signers have executed the proposal; it resumes that transfer instead of proposing another.`
2052
+ if (/^\d+$/.test(trimmed)) return BigInt(trimmed) > 0n;
2053
+ const numeric = Number(trimmed);
2054
+ return Number.isFinite(numeric) && numeric > 0;
2055
+ } catch {
2056
+ return false;
2057
+ }
2058
+ }
2059
+ function portfolioHasWithdrawableBalance(portfolio) {
2060
+ if (!portfolio) return false;
2061
+ if (portfolio.hasBalance) return true;
2062
+ const buckets = [
2063
+ ...Object.values(portfolio.portfolioByAssetType ?? {}),
2064
+ ...Object.values(portfolio.portfolioByChain ?? {}).flatMap(
2065
+ (byAsset) => Object.values(byAsset)
2066
+ )
2067
+ ];
2068
+ if (buckets.some(
2069
+ (entry) => positiveAmount(entry.balance) || positiveAmount(entry.balanceWithFee)
2070
+ )) {
2071
+ return true;
2072
+ }
2073
+ if ((portfolio.positions ?? []).some(
2074
+ (slot) => positiveAmount(slot.underlyingAmountWithFee) || positiveAmount(slot.underlyingAmount) || positiveAmount(slot.amount)
2075
+ )) {
2076
+ return true;
2077
+ }
2078
+ return (portfolio.staleBalances ?? []).some(
2079
+ (stale) => positiveAmount(stale.balance)
2065
2080
  );
2066
2081
  }
2082
+ function deriveNestedSafeOnboardingStep(flags) {
2083
+ if (!flags.isNestedOwner) return "deploy";
2084
+ if (!flags.childRegistered || !flags.childDeployed || !flags.sessionActive) {
2085
+ return "deploy";
2086
+ }
2087
+ if (!flags.hasPortfolioBalance) return "deposit";
2088
+ if (flags.hasPortfolioBalance) return "withdraw";
2089
+ return "ready";
2090
+ }
2091
+ function buildNestedSafeOnboardingStatus(flags, child) {
2092
+ return {
2093
+ ...flags,
2094
+ child,
2095
+ suggestedStep: deriveNestedSafeOnboardingStep(flags)
2096
+ };
2097
+ }
2067
2098
 
2068
2099
  // src/utils/strategy.ts
2069
2100
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
@@ -3321,15 +3352,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3321
3352
  throw new Error(`Unsupported chain ID: ${chainId}`);
3322
3353
  }
3323
3354
  const resolvedAddress = await this.resolveConnectAddress(account);
3324
- if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && (0, import_viem8.isAddressEqual)(resolvedAddress, this.sessionEoa)) {
3355
+ if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && (0, import_viem8.isAddressEqual)(resolvedAddress, this.sessionEoa) && this.currentChainId === chainId && (account === this.currentProvider || account === this.walletClient)) {
3325
3356
  this.currentChainId = chainId;
3326
3357
  return resolvedAddress;
3327
3358
  }
3328
3359
  if (this.connectAccountInFlight) {
3329
- return this.connectAccountInFlight;
3360
+ throw new Error("Wallet connection already in progress; retry after it completes");
3330
3361
  }
3331
3362
  const connect = (async () => {
3332
3363
  this.authenticatedUserId = null;
3364
+ this.hasActiveSessionKey = false;
3365
+ this.signer = null;
3333
3366
  this.isPredeployed = false;
3334
3367
  this.predeployedResolved = false;
3335
3368
  this.connectedSmartWallet = null;
@@ -3379,6 +3412,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3379
3412
  transport: provider.transport
3380
3413
  });
3381
3414
  connectedAddress = (0, import_viem8.getAddress)(resolvedAddress2);
3415
+ if (provider.chain?.id !== void 0 && provider.chain.id !== chainId) {
3416
+ throw new Error(`Wallet client chain ${provider.chain.id} does not match requested chain ${chainId}`);
3417
+ }
3382
3418
  this.currentProvider = null;
3383
3419
  this.currentChainId = chainId;
3384
3420
  } else if (provider.request) {
@@ -3402,6 +3438,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3402
3438
  );
3403
3439
  }
3404
3440
  connectedAddress = (0, import_viem8.getAddress)(accountAddress);
3441
+ if (!(0, import_viem8.isAddressEqual)(connectedAddress, resolvedAddress)) {
3442
+ throw new Error("Wallet account changed during connection; reconnect");
3443
+ }
3444
+ const providerChain = await eip1193.request({ method: "eth_chainId" });
3445
+ if (Number(providerChain) !== chainId) {
3446
+ throw new Error(`Wallet is on chain ${providerChain}; switch to chain ${chainId} before connecting`);
3447
+ }
3405
3448
  this.walletClient = (0, import_viem8.createWalletClient)({
3406
3449
  account: connectedAddress,
3407
3450
  chain: chainConfig.chain,
@@ -3490,6 +3533,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3490
3533
  * True when userAddress is the signer, wallet client, or agent session EOA.
3491
3534
  * @private
3492
3535
  */
3536
+ assertConnectedUser(userAddress) {
3537
+ if (!this.isConnectedUser(userAddress) || this.sessionEoa && !(0, import_viem8.isAddressEqual)((0, import_viem8.getAddress)(userAddress), this.sessionEoa)) {
3538
+ throw new Error("userAddress does not match the authenticated wallet");
3539
+ }
3540
+ }
3493
3541
  isConnectedUser(userAddress) {
3494
3542
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3495
3543
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
@@ -3499,6 +3547,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3499
3547
  * (install or emissary enable), then register with chainId only.
3500
3548
  * @private
3501
3549
  */
3550
+ /**
3551
+ * Read-only probe for nested owners: on-chain session permissions on `chainId`.
3552
+ * Mirrors the early-return branch in {@link deploySafeAccount} without signing.
3553
+ * @private
3554
+ */
3555
+ async isNestedChainSessionPermissionsReady(chainId) {
3556
+ const prepare = await postSafeDeployPrepare(this.httpClient, chainId);
3557
+ return isSafeDeployPermissionsReady(prepare);
3558
+ }
3502
3559
  async registerNestedIntentSessionKey(userAddress, chainId, strategy) {
3503
3560
  if (!this.authenticatedUserId) {
3504
3561
  throw new Error(
@@ -3515,10 +3572,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3515
3572
  httpClient: this.httpClient,
3516
3573
  strategy
3517
3574
  });
3575
+ if (this.hasActiveSessionKey) {
3576
+ return {
3577
+ success: true,
3578
+ userId: this.authenticatedUserId,
3579
+ message: "Intent session permissions ready on requested chain",
3580
+ alreadyActive: true
3581
+ };
3582
+ }
3518
3583
  const activation = await this.httpClient.post(
3519
3584
  ENDPOINTS.SESSION_KEYS_ADD,
3520
3585
  { chainId }
3521
3586
  );
3587
+ if (!activation?.isActive || !activation?.isEnabled) {
3588
+ throw new Error("Intent session is not active and enabled on the requested chain");
3589
+ }
3522
3590
  this.hasActiveSessionKey = true;
3523
3591
  return {
3524
3592
  success: true,
@@ -3564,7 +3632,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3564
3632
  const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3565
3633
  const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3566
3634
  if (!childDeployed) {
3567
- await this.deploySafe(userAddress, chainId, strategy, true);
3635
+ const deployment = await this.deploySafe(userAddress, chainId, strategy, false);
3636
+ if (!deployment.success) throw new Error("Nested Safe deployment failed");
3637
+ await this.createSessionKey(userAddress, chainId);
3568
3638
  return;
3569
3639
  }
3570
3640
  console.info(
@@ -3689,6 +3759,84 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3689
3759
  isOwner
3690
3760
  };
3691
3761
  }
3762
+ /**
3763
+ * Nested-parent onboarding snapshot for a connected parent Safe address.
3764
+ *
3765
+ * @group Deposits and withdrawals
3766
+ *
3767
+ * @remarks Combines child resolution ({@link ZyfaiSDK.getSmartWalletAddress}),
3768
+ * session state (account registration plus per-chain safe-deploy readiness),
3769
+ * and portfolio balances
3770
+ * ({@link ZyfaiSDK.getPortfolio}). Wallet connect remains integrator-side.
3771
+ *
3772
+ * @param userAddress - Parent Safe address from {@link ZyfaiSDK.connectAccount}
3773
+ * @param chainId - Target chain (deployment and session are per chain)
3774
+ */
3775
+ async getNestedSafeOnboardingStatus(userAddress, chainId) {
3776
+ if (!userAddress) {
3777
+ throw new Error("User address is required");
3778
+ }
3779
+ if (!isSupportedChain(chainId)) {
3780
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3781
+ }
3782
+ await this.authenticateUser();
3783
+ this.assertConnectedUser(userAddress);
3784
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3785
+ const isNestedOwner = await getAccountType(userAddress, chainConfig.publicClient) === "Safe";
3786
+ let child = null;
3787
+ let childRegistered = false;
3788
+ let childDeployed = false;
3789
+ try {
3790
+ child = await this.getSmartWalletAddress(userAddress, chainId);
3791
+ childRegistered = true;
3792
+ childDeployed = child.isDeployed;
3793
+ } catch (error) {
3794
+ const message = error.message;
3795
+ if (message !== "NESTED_CHILD_UNREGISTERED") {
3796
+ throw error;
3797
+ }
3798
+ }
3799
+ let accountSessionRegistered = false;
3800
+ try {
3801
+ const details = await this.getUserDetails("USDC");
3802
+ accountSessionRegistered = Boolean(details.hasActiveSessionKey);
3803
+ } catch {
3804
+ }
3805
+ let chainSessionReady = false;
3806
+ if (isNestedOwner && childDeployed) {
3807
+ try {
3808
+ chainSessionReady = await this.isNestedChainSessionPermissionsReady(chainId);
3809
+ } catch {
3810
+ }
3811
+ }
3812
+ const sessionActive = chainSessionReady && accountSessionRegistered;
3813
+ let hasPortfolioBalance = false;
3814
+ if (childRegistered) {
3815
+ try {
3816
+ const portfolio = await this.getPortfolio(userAddress);
3817
+ hasPortfolioBalance = portfolioHasWithdrawableBalance(
3818
+ portfolio.portfolio
3819
+ );
3820
+ } catch {
3821
+ }
3822
+ }
3823
+ const status = buildNestedSafeOnboardingStatus(
3824
+ {
3825
+ isNestedOwner,
3826
+ childRegistered,
3827
+ childDeployed,
3828
+ sessionActive: sessionActive && childDeployed && childRegistered,
3829
+ hasPortfolioBalance
3830
+ },
3831
+ child
3832
+ );
3833
+ return {
3834
+ success: true,
3835
+ userAddress,
3836
+ chainId,
3837
+ status
3838
+ };
3839
+ }
3692
3840
  /**
3693
3841
  * Deploy Safe Smart Wallet for a user
3694
3842
  *
@@ -3704,7 +3852,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3704
3852
  * @param userAddress - User's EOA address (the connected EOA, not the smart wallet address)
3705
3853
  * @param chainId - Target chain ID
3706
3854
  * @param strategy - Optional strategy selection: "conservative" (default), "aggressive" or "yieldmaxxing"
3707
- * @param createSessionKey - If true, automatically creates a session key after deployment (default: false)
3855
+ * @param createSessionKey - For EOA owners, if true, creates a session key after deployment (default: false). Nested Safe owners always register the session after deploy.
3708
3856
  * @returns Deployment response with Safe address and transaction hash
3709
3857
  *
3710
3858
  * @example
@@ -3726,6 +3874,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3726
3874
  throw new Error(`Unsupported chain ID: ${chainId}`);
3727
3875
  }
3728
3876
  await this.authenticateUser();
3877
+ this.assertConnectedUser(userAddress);
3729
3878
  this.warnPredeployedOnboardingMethod("deploySafe");
3730
3879
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
3731
3880
  const predeployedAddress = await this.getSafeAddressFor(
@@ -3761,6 +3910,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3761
3910
  chainConfig.publicClient
3762
3911
  );
3763
3912
  const nestedSafeOwner = ownerAccountType === "Safe";
3913
+ const registerSession = nestedSafeOwner || Boolean(createSessionKey);
3764
3914
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3765
3915
  if (!safeAddress && !nestedSafeOwner) {
3766
3916
  throw new Error(
@@ -3785,7 +3935,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3785
3935
  }
3786
3936
  await this.updateUserProtocols(strategy);
3787
3937
  let sessionKeyCreated2 = false;
3788
- if (createSessionKey) {
3938
+ if (registerSession) {
3789
3939
  try {
3790
3940
  await this.createSessionKey(userAddress, chainId);
3791
3941
  sessionKeyCreated2 = true;
@@ -3845,7 +3995,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3845
3995
  });
3846
3996
  }
3847
3997
  let sessionKeyCreated = false;
3848
- if (createSessionKey) {
3998
+ if (registerSession) {
3849
3999
  try {
3850
4000
  await this.createSessionKey(userAddress, chainId);
3851
4001
  sessionKeyCreated = true;
@@ -3898,6 +4048,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3898
4048
  async createSessionKey(userAddress, chainId) {
3899
4049
  try {
3900
4050
  await this.authenticateUser();
4051
+ this.assertConnectedUser(userAddress);
3901
4052
  this.warnPredeployedOnboardingMethod("createSessionKey");
3902
4053
  if (!this.authenticatedUserId) {
3903
4054
  throw new Error(
@@ -3912,6 +4063,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3912
4063
  alreadyActive: true
3913
4064
  };
3914
4065
  }
4066
+ const nestedChain = getChainConfig(chainId, this.rpcUrls);
4067
+ if (await getAccountType(userAddress, nestedChain.publicClient) === "Safe") {
4068
+ await assertParentSafeDeployedOnChain(userAddress, nestedChain.publicClient, chainId);
4069
+ return this.registerNestedIntentSessionKey(userAddress, chainId);
4070
+ }
3915
4071
  if (this.hasActiveSessionKey) {
3916
4072
  return {
3917
4073
  success: true,
@@ -3943,12 +4099,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3943
4099
  userAddress,
3944
4100
  chainConfig.publicClient
3945
4101
  );
3946
- if (accountType === "Safe") {
3947
- return this.registerNestedIntentSessionKey(
3948
- userAddress,
3949
- chainId,
3950
- void 0
3951
- );
4102
+ if (accountType !== "EOA") {
4103
+ throw new Error("Unable to establish EOA session account type");
3952
4104
  }
3953
4105
  const signingParams = {
3954
4106
  permitGenericPolicy,
@@ -4446,10 +4598,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4446
4598
  * await sdk.waitForDepositPosition(sent.registration.id, 8453);
4447
4599
  * ```
4448
4600
  */
4449
- async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
4450
- return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true);
4601
+ async sendDirectDeposit(userAddress, chainId, amount, asset, strategy, onSafeProposal) {
4602
+ return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true, onSafeProposal);
4451
4603
  }
4452
- async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit) {
4604
+ async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit, onSafeProposal) {
4453
4605
  try {
4454
4606
  if (!userAddress) {
4455
4607
  throw new Error("User address is required");
@@ -4501,11 +4653,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4501
4653
  } else {
4502
4654
  await this.authenticateUser();
4503
4655
  }
4504
- await this.hydrateSessionWallet();
4505
- const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4506
- if (!safeAddress) {
4507
- throw new Error("Smart wallet address is not available");
4656
+ this.assertConnectedUser(userAddress);
4657
+ if (!this.signer && walletClient.chain?.id !== chainId) {
4658
+ throw new Error("Switch the connected wallet to the deposit chain and reconnect");
4508
4659
  }
4660
+ await this.hydrateSessionWallet();
4661
+ let safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4509
4662
  const amountBigInt = BigInt(amount);
4510
4663
  const ownerType = await getAccountType(
4511
4664
  userAddress,
@@ -4516,6 +4669,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4516
4669
  `Could not resolve the account type of ${userAddress} on chain ${chainId}: it is neither an EOA nor a Safe, or the RPC read failed. No deposit was sent.`
4517
4670
  );
4518
4671
  }
4672
+ let nestedOnboarded = false;
4673
+ if (!safeAddress && ownerType === "Safe" && !this.isPredeployed) {
4674
+ await this.ensureNestedOwnerReadyForDeposit(userAddress, chainId, strategy);
4675
+ safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4676
+ nestedOnboarded = true;
4677
+ }
4678
+ if (!safeAddress) {
4679
+ throw new Error("Smart wallet address is not available");
4680
+ }
4519
4681
  const [isDeployed, currentSafeBalance] = await Promise.all([
4520
4682
  isSafeDeployed(safeAddress, chainConfig.publicClient),
4521
4683
  minRequired !== void 0 ? chainConfig.publicClient.readContract({
@@ -4527,7 +4689,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4527
4689
  this.prepareFirstDeposit(strategy)
4528
4690
  ]).then(([deployed, balance]) => [deployed, balance]);
4529
4691
  if (!isDeployed) {
4530
- if (ownerType === "Safe" && !this.isPredeployed) {
4692
+ if (ownerType === "Safe" && !this.isPredeployed && !nestedOnboarded) {
4531
4693
  await assertParentSafeDeployedOnChain(
4532
4694
  userAddress,
4533
4695
  chainConfig.publicClient,
@@ -4561,7 +4723,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4561
4723
  );
4562
4724
  }
4563
4725
  }
4564
- if (ownerType === "Safe" && isDeployed) {
4726
+ if (ownerType === "Safe" && isDeployed && !nestedOnboarded) {
4565
4727
  await assertParentSafeDeployedOnChain(
4566
4728
  userAddress,
4567
4729
  chainConfig.publicClient,
@@ -4584,35 +4746,35 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4584
4746
  if (sponsored) return sponsored;
4585
4747
  }
4586
4748
  if (ownerType === "Safe") {
4587
- const since = new Date(Date.now() - NESTED_SAFE_RESUME_WINDOW_MS);
4588
- const inFlight = await findSafeTransferProposal({
4589
- parentSafe: userAddress,
4590
- childSafe: safeAddress,
4591
- chainId,
4592
- tokenAddress: token,
4593
- amount: amountBigInt,
4594
- since
4749
+ const proposed = await walletClient.writeContract({
4750
+ address: token,
4751
+ abi: erc20TransferWriteAbi(assetSymbol),
4752
+ functionName: "transfer",
4753
+ args: [safeAddress, amountBigInt],
4754
+ chain: chainConfig.chain,
4755
+ account: walletClient.account
4595
4756
  });
4596
- let safeTxHash = inFlight?.safeTxHash;
4597
- if (!inFlight) {
4598
- const proposed = await walletClient.writeContract({
4599
- address: token,
4600
- abi: erc20TransferWriteAbi(assetSymbol),
4601
- functionName: "transfer",
4602
- args: [safeAddress, amountBigInt],
4603
- chain: chainConfig.chain,
4604
- account: walletClient.account
4605
- });
4606
- safeTxHash = (await findSafeTransferByHash({ chainId, safeTxHash: proposed }))?.safeTxHash;
4757
+ const reference = {
4758
+ userAddress: (0, import_viem8.getAddress)(userAddress),
4759
+ chainId,
4760
+ amount,
4761
+ asset: assetSymbol,
4762
+ childSafe: safeAddress,
4763
+ proposalHash: proposed
4764
+ };
4765
+ try {
4766
+ await onSafeProposal?.(reference);
4767
+ } catch (error) {
4768
+ throw new Error(`Safe proposal ${proposed} was submitted; persist its reference and resumeNestedSafeDeposit instead of sending again: ${thrownMessage(error)}`);
4607
4769
  }
4608
- const executedHash = inFlight?.isExecuted && inFlight.transactionHash ? inFlight.transactionHash : await waitForSafeTransferExecution({
4609
- parentSafe: userAddress,
4770
+ const executedHash = await waitForExactSafeDepositExecution({
4771
+ parentSafe: reference.userAddress,
4610
4772
  childSafe: safeAddress,
4611
4773
  chainId,
4612
4774
  tokenAddress: token,
4613
4775
  amount: amountBigInt,
4614
- safeTxHash,
4615
- since
4776
+ proposalHash: proposed,
4777
+ publicClient: chainConfig.publicClient
4616
4778
  });
4617
4779
  const registration2 = await this.registerDeposit(
4618
4780
  chainId,
@@ -4787,6 +4949,39 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4787
4949
  strategy
4788
4950
  );
4789
4951
  }
4952
+ /**
4953
+ * Resume one specific parent Safe deposit without proposing another transfer.
4954
+ * Persist the reference supplied by sendDeposit's onSafeProposal callback.
4955
+ *
4956
+ * @group Deposits and withdrawals
4957
+ */
4958
+ async resumeNestedSafeDeposit(reference) {
4959
+ const { userAddress, chainId, childSafe, proposalHash, asset, amount } = reference;
4960
+ if (!isSupportedChain(chainId)) throw new Error("Unsupported deposit chain");
4961
+ if (!/^0x[0-9a-fA-F]{64}$/.test(proposalHash)) throw new Error("Invalid proposal hash");
4962
+ await this.authenticateUser();
4963
+ if (!this.isConnectedUser(userAddress) || this.sessionEoa && !(0, import_viem8.isAddressEqual)(this.sessionEoa, userAddress)) {
4964
+ throw new Error("Deposit reference does not match the authenticated parent");
4965
+ }
4966
+ await this.hydrateSessionWallet();
4967
+ const resolved = await this.getSafeAddressFor(userAddress, chainId);
4968
+ if (!resolved || !(0, import_viem8.isAddressEqual)(resolved, childSafe)) throw new Error("Deposit reference does not match the registered child");
4969
+ const symbol = resolveAssetSymbol(asset);
4970
+ if (!getAssetChainIds(symbol).includes(chainId) || BigInt(amount) <= 0n) throw new Error("Invalid deposit asset or amount");
4971
+ const config = getChainConfig(chainId, this.rpcUrls);
4972
+ const token = getDefaultTokenAddress(chainId, symbol);
4973
+ const txHash = await waitForExactSafeDepositExecution({
4974
+ parentSafe: userAddress,
4975
+ childSafe,
4976
+ chainId,
4977
+ tokenAddress: token,
4978
+ amount: BigInt(amount),
4979
+ proposalHash,
4980
+ publicClient: config.publicClient
4981
+ });
4982
+ const registration = await this.registerDeposit(chainId, txHash, amount, token);
4983
+ return { success: true, txHash, smartWallet: childSafe, amount, route: "direct", registration };
4984
+ }
4790
4985
  /**
4791
4986
  * Resolve a deposit without signing.
4792
4987
  *
@@ -5047,7 +5242,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5047
5242
  params.chainId,
5048
5243
  params.amount,
5049
5244
  route.asset,
5050
- params.strategy
5245
+ params.strategy,
5246
+ params.onSafeProposal
5051
5247
  );
5052
5248
  }
5053
5249
  if (route.kind === "wrap") {
@@ -5665,7 +5861,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5665
5861
  );
5666
5862
  } catch (logError) {
5667
5863
  throw new Error(
5668
- `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
5864
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}", "${tokenAddress}") to retry.`
5669
5865
  );
5670
5866
  }
5671
5867
  return registration.deposit;
@@ -6032,6 +6228,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
6032
6228
  );
6033
6229
  }
6034
6230
  await this.authenticateUser();
6231
+ this.assertConnectedUser(userAddress);
6035
6232
  await this.assertAsyncRedemptionSlotFree(
6036
6233
  userAddress,
6037
6234
  chainId,
@@ -8546,9 +8743,11 @@ function createBankrProvider(config) {
8546
8743
  WS_ENDPOINT,
8547
8744
  WS_URLS,
8548
8745
  ZyfaiSDK,
8746
+ buildNestedSafeOnboardingStatus,
8549
8747
  buildV1ChainSessions,
8550
8748
  createBankrProvider,
8551
8749
  decodeUserOperationCalls,
8750
+ deriveNestedSafeOnboardingStep,
8552
8751
  getChainConfig,
8553
8752
  getDataApiBaseUrl,
8554
8753
  getDefaultTokenAddress,
@@ -8561,6 +8760,7 @@ function createBankrProvider(config) {
8561
8760
  isSupportedChain,
8562
8761
  parseUserOperationJson,
8563
8762
  parseV1ChainSessions,
8763
+ portfolioHasWithdrawableBalance,
8564
8764
  resolveDepositRoute,
8565
8765
  resolveRelaySlippageBps,
8566
8766
  serializeV1ChainSessions