@zyfai/sdk 1.9.1 → 1.10.0

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.");
@@ -1690,10 +1702,12 @@ var signNestedSafeDeployTypedData = async (owner, parentSafe, typedData) => {
1690
1702
  message: typedData.message
1691
1703
  });
1692
1704
  };
1693
- var completeSafeDeploy = async (config, strategyBody, body) => {
1705
+ var TYPED_DATA_DEPLOY_TIMEOUT_MS = 18e4;
1706
+ var completeSafeDeploy = async (config, strategyBody, body, requestConfig) => {
1694
1707
  const deployResponse = await config.httpClient.post(
1695
1708
  `${ENDPOINTS.SAFE_DEPLOY}?chainId=${config.chainId}`,
1696
- { ...body, ...strategyBody }
1709
+ { ...body, ...strategyBody },
1710
+ requestConfig
1697
1711
  );
1698
1712
  if (!deployResponse.success) {
1699
1713
  throw new Error(
@@ -1723,12 +1737,13 @@ var deploySafeAccount = async (config) => {
1723
1737
  }
1724
1738
  console.log("strategy", strategy);
1725
1739
  const strategyBody = strategy ? { strategy } : {};
1726
- const prepareResponse = await httpClient.post(
1727
- `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1740
+ const prepareResponse = await postSafeDeployPrepare(
1741
+ httpClient,
1742
+ chainId,
1728
1743
  strategyBody
1729
1744
  );
1730
1745
  console.log("prepareResponse", prepareResponse);
1731
- if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1746
+ if (isSafeDeployPermissionsReady(prepareResponse)) {
1732
1747
  return {
1733
1748
  safeAddress: prepareResponse.safeAddress || "0x",
1734
1749
  txHash: "0x0",
@@ -1750,9 +1765,12 @@ var deploySafeAccount = async (config) => {
1750
1765
  parentSafe,
1751
1766
  prepareResponse.typedData
1752
1767
  );
1753
- return completeSafeDeploy(config, strategyBody, {
1754
- typedDataSignature
1755
- });
1768
+ return completeSafeDeploy(
1769
+ config,
1770
+ strategyBody,
1771
+ { typedDataSignature },
1772
+ { timeout: TYPED_DATA_DEPLOY_TIMEOUT_MS }
1773
+ );
1756
1774
  }
1757
1775
  if (!prepareResponse.userOpHashToSign) {
1758
1776
  throw new Error(
@@ -1964,35 +1982,6 @@ function sameAddress(left, right) {
1964
1982
  return false;
1965
1983
  }
1966
1984
  }
1967
- function transferMatches(transaction, params) {
1968
- if (!sameAddress(transaction.to, params.tokenAddress)) return false;
1969
- if (transaction.isSuccessful === false) return false;
1970
- const decoded = transaction.dataDecoded;
1971
- if (decoded?.method?.toLowerCase() !== "transfer") return false;
1972
- const parameters = decoded.parameters;
1973
- if (!parameters) return false;
1974
- const destination = parameters.find(
1975
- (p) => (p.name === "to" || p.name === "dst" || p.name === "_to") && p.type === "address"
1976
- );
1977
- if (!sameAddress(destination?.value, params.childSafe)) return false;
1978
- if (params.amount === void 0) return true;
1979
- const valueParam = parameters.find(
1980
- (p) => (p.name === "value" || p.name === "amount" || p.name === "_value" || p.name === "wad") && p.type.startsWith("uint")
1981
- );
1982
- if (!valueParam) return false;
1983
- try {
1984
- return BigInt(valueParam.value) === params.amount;
1985
- } catch {
1986
- return false;
1987
- }
1988
- }
1989
- function isWithinWindow(transaction, since) {
1990
- if (!since) return true;
1991
- const stamp = transaction.executionDate ?? transaction.submissionDate;
1992
- if (!stamp) return false;
1993
- const at = Date.parse(stamp);
1994
- return Number.isFinite(at) && at >= since.getTime();
1995
- }
1996
1985
  async function findSafeTransferByHash(params) {
1997
1986
  const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1998
1987
  const url = `https://api.safe.global/tx-service/${networkName}/api/v2/multisig-transactions/${params.safeTxHash}/`;
@@ -2011,54 +2000,100 @@ async function findSafeTransferByHash(params) {
2011
2000
  isExecuted: transaction.isExecuted === true && !!transaction.transactionHash
2012
2001
  };
2013
2002
  }
2014
- async function findSafeTransferProposal(params) {
2015
- const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
2016
- const url = `https://api.safe.global/tx-service/${networkName}/api/v2/safes/${(0, import_viem7.getAddress)(
2017
- params.parentSafe
2018
- )}/multisig-transactions/?ordering=-nonce`;
2019
- const response = await fetch(url);
2020
- if (!response.ok) return null;
2021
- const body = await response.json();
2022
- const match = (body.results ?? []).find(
2023
- (transaction) => !!transaction.safeTxHash && isWithinWindow(transaction, params.since) && transferMatches(transaction, {
2024
- childSafe: params.childSafe,
2025
- tokenAddress: params.tokenAddress,
2026
- amount: params.amount
2027
- })
2028
- );
2029
- if (!match) return null;
2030
- return {
2031
- safeTxHash: match.safeTxHash,
2032
- transactionHash: match.transactionHash ?? null,
2033
- isExecuted: match.isExecuted === true && !!match.transactionHash
2034
- };
2035
- }
2036
- async function waitForSafeTransferExecution(params) {
2037
- 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();
2038
2006
  const timeoutMs = params.timeoutMs ?? NESTED_SAFE_DEPOSIT_TIMEOUT_MS;
2039
2007
  const pollMs = params.pollMs ?? NESTED_SAFE_DEPOSIT_POLL_MS;
2040
- const started = Date.now();
2041
- do {
2042
- const proposal = params.safeTxHash ? await findSafeTransferByHash({
2043
- chainId: params.chainId,
2044
- safeTxHash: params.safeTxHash
2045
- }) : await findSafeTransferProposal({
2046
- parentSafe: params.parentSafe,
2047
- childSafe: params.childSafe,
2048
- chainId: params.chainId,
2049
- tokenAddress: params.tokenAddress,
2050
- amount: params.amount,
2051
- since: params.since
2052
- });
2053
- if (proposal?.isExecuted && proposal.transactionHash) {
2054
- 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;
2055
2051
  }
2056
- await new Promise((resolve) => setTimeout(resolve, pollMs));
2057
- } while (Date.now() - started < timeoutMs);
2058
- throw new Error(
2059
- `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)
2060
2080
  );
2061
2081
  }
2082
+ function deriveNestedSafeOnboardingStep(flags) {
2083
+ if (!flags.isNestedOwner) return "deploy";
2084
+ if (!flags.childRegistered || !flags.childDeployed) return "deploy";
2085
+ if (!flags.sessionActive) return "register";
2086
+ if (!flags.hasPortfolioBalance) return "deposit";
2087
+ if (flags.hasPortfolioBalance) return "withdraw";
2088
+ return "ready";
2089
+ }
2090
+ function buildNestedSafeOnboardingStatus(flags, child) {
2091
+ return {
2092
+ ...flags,
2093
+ child,
2094
+ suggestedStep: deriveNestedSafeOnboardingStep(flags)
2095
+ };
2096
+ }
2062
2097
 
2063
2098
  // src/utils/strategy.ts
2064
2099
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
@@ -3316,15 +3351,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3316
3351
  throw new Error(`Unsupported chain ID: ${chainId}`);
3317
3352
  }
3318
3353
  const resolvedAddress = await this.resolveConnectAddress(account);
3319
- if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && (0, import_viem8.isAddressEqual)(resolvedAddress, this.sessionEoa)) {
3354
+ 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)) {
3320
3355
  this.currentChainId = chainId;
3321
3356
  return resolvedAddress;
3322
3357
  }
3323
3358
  if (this.connectAccountInFlight) {
3324
- return this.connectAccountInFlight;
3359
+ throw new Error("Wallet connection already in progress; retry after it completes");
3325
3360
  }
3326
3361
  const connect = (async () => {
3327
3362
  this.authenticatedUserId = null;
3363
+ this.hasActiveSessionKey = false;
3364
+ this.signer = null;
3328
3365
  this.isPredeployed = false;
3329
3366
  this.predeployedResolved = false;
3330
3367
  this.connectedSmartWallet = null;
@@ -3374,6 +3411,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3374
3411
  transport: provider.transport
3375
3412
  });
3376
3413
  connectedAddress = (0, import_viem8.getAddress)(resolvedAddress2);
3414
+ if (provider.chain?.id !== void 0 && provider.chain.id !== chainId) {
3415
+ throw new Error(`Wallet client chain ${provider.chain.id} does not match requested chain ${chainId}`);
3416
+ }
3377
3417
  this.currentProvider = null;
3378
3418
  this.currentChainId = chainId;
3379
3419
  } else if (provider.request) {
@@ -3397,6 +3437,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3397
3437
  );
3398
3438
  }
3399
3439
  connectedAddress = (0, import_viem8.getAddress)(accountAddress);
3440
+ if (!(0, import_viem8.isAddressEqual)(connectedAddress, resolvedAddress)) {
3441
+ throw new Error("Wallet account changed during connection; reconnect");
3442
+ }
3443
+ const providerChain = await eip1193.request({ method: "eth_chainId" });
3444
+ if (Number(providerChain) !== chainId) {
3445
+ throw new Error(`Wallet is on chain ${providerChain}; switch to chain ${chainId} before connecting`);
3446
+ }
3400
3447
  this.walletClient = (0, import_viem8.createWalletClient)({
3401
3448
  account: connectedAddress,
3402
3449
  chain: chainConfig.chain,
@@ -3485,6 +3532,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3485
3532
  * True when userAddress is the signer, wallet client, or agent session EOA.
3486
3533
  * @private
3487
3534
  */
3535
+ assertConnectedUser(userAddress) {
3536
+ if (!this.isConnectedUser(userAddress) || this.sessionEoa && !(0, import_viem8.isAddressEqual)((0, import_viem8.getAddress)(userAddress), this.sessionEoa)) {
3537
+ throw new Error("userAddress does not match the authenticated wallet");
3538
+ }
3539
+ }
3488
3540
  isConnectedUser(userAddress) {
3489
3541
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3490
3542
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
@@ -3494,6 +3546,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3494
3546
  * (install or emissary enable), then register with chainId only.
3495
3547
  * @private
3496
3548
  */
3549
+ /**
3550
+ * Read-only probe for nested owners: on-chain session permissions on `chainId`.
3551
+ * Mirrors the early-return branch in {@link deploySafeAccount} without signing.
3552
+ * @private
3553
+ */
3554
+ async isNestedChainSessionPermissionsReady(chainId) {
3555
+ const prepare = await postSafeDeployPrepare(this.httpClient, chainId);
3556
+ return isSafeDeployPermissionsReady(prepare);
3557
+ }
3497
3558
  async registerNestedIntentSessionKey(userAddress, chainId, strategy) {
3498
3559
  if (!this.authenticatedUserId) {
3499
3560
  throw new Error(
@@ -3510,10 +3571,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3510
3571
  httpClient: this.httpClient,
3511
3572
  strategy
3512
3573
  });
3574
+ if (this.hasActiveSessionKey) {
3575
+ return {
3576
+ success: true,
3577
+ userId: this.authenticatedUserId,
3578
+ message: "Intent session permissions ready on requested chain",
3579
+ alreadyActive: true
3580
+ };
3581
+ }
3513
3582
  const activation = await this.httpClient.post(
3514
3583
  ENDPOINTS.SESSION_KEYS_ADD,
3515
3584
  { chainId }
3516
3585
  );
3586
+ if (!activation?.isActive || !activation?.isEnabled) {
3587
+ throw new Error("Intent session is not active and enabled on the requested chain");
3588
+ }
3517
3589
  this.hasActiveSessionKey = true;
3518
3590
  return {
3519
3591
  success: true,
@@ -3559,7 +3631,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3559
3631
  const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3560
3632
  const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3561
3633
  if (!childDeployed) {
3562
- await this.deploySafe(userAddress, chainId, strategy, true);
3634
+ const deployment = await this.deploySafe(userAddress, chainId, strategy, false);
3635
+ if (!deployment.success) throw new Error("Nested Safe deployment failed");
3636
+ await this.createSessionKey(userAddress, chainId);
3563
3637
  return;
3564
3638
  }
3565
3639
  console.info(
@@ -3684,6 +3758,84 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3684
3758
  isOwner
3685
3759
  };
3686
3760
  }
3761
+ /**
3762
+ * Nested-parent onboarding snapshot for a connected parent Safe address.
3763
+ *
3764
+ * @group Deposits and withdrawals
3765
+ *
3766
+ * @remarks Combines child resolution ({@link ZyfaiSDK.getSmartWalletAddress}),
3767
+ * session state (account registration plus per-chain safe-deploy readiness),
3768
+ * and portfolio balances
3769
+ * ({@link ZyfaiSDK.getPortfolio}). Wallet connect remains integrator-side.
3770
+ *
3771
+ * @param userAddress - Parent Safe address from {@link ZyfaiSDK.connectAccount}
3772
+ * @param chainId - Target chain (deployment and session are per chain)
3773
+ */
3774
+ async getNestedSafeOnboardingStatus(userAddress, chainId) {
3775
+ if (!userAddress) {
3776
+ throw new Error("User address is required");
3777
+ }
3778
+ if (!isSupportedChain(chainId)) {
3779
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3780
+ }
3781
+ await this.authenticateUser();
3782
+ this.assertConnectedUser(userAddress);
3783
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3784
+ const isNestedOwner = await getAccountType(userAddress, chainConfig.publicClient) === "Safe";
3785
+ let child = null;
3786
+ let childRegistered = false;
3787
+ let childDeployed = false;
3788
+ try {
3789
+ child = await this.getSmartWalletAddress(userAddress, chainId);
3790
+ childRegistered = true;
3791
+ childDeployed = child.isDeployed;
3792
+ } catch (error) {
3793
+ const message = error.message;
3794
+ if (message !== "NESTED_CHILD_UNREGISTERED") {
3795
+ throw error;
3796
+ }
3797
+ }
3798
+ let accountSessionRegistered = false;
3799
+ try {
3800
+ const details = await this.getUserDetails("USDC");
3801
+ accountSessionRegistered = Boolean(details.hasActiveSessionKey);
3802
+ } catch {
3803
+ }
3804
+ let chainSessionReady = false;
3805
+ if (isNestedOwner && childDeployed) {
3806
+ try {
3807
+ chainSessionReady = await this.isNestedChainSessionPermissionsReady(chainId);
3808
+ } catch {
3809
+ }
3810
+ }
3811
+ const sessionActive = chainSessionReady && accountSessionRegistered;
3812
+ let hasPortfolioBalance = false;
3813
+ if (childRegistered) {
3814
+ try {
3815
+ const portfolio = await this.getPortfolio(userAddress);
3816
+ hasPortfolioBalance = portfolioHasWithdrawableBalance(
3817
+ portfolio.portfolio
3818
+ );
3819
+ } catch {
3820
+ }
3821
+ }
3822
+ const status = buildNestedSafeOnboardingStatus(
3823
+ {
3824
+ isNestedOwner,
3825
+ childRegistered,
3826
+ childDeployed,
3827
+ sessionActive: sessionActive && childDeployed && childRegistered,
3828
+ hasPortfolioBalance
3829
+ },
3830
+ child
3831
+ );
3832
+ return {
3833
+ success: true,
3834
+ userAddress,
3835
+ chainId,
3836
+ status
3837
+ };
3838
+ }
3687
3839
  /**
3688
3840
  * Deploy Safe Smart Wallet for a user
3689
3841
  *
@@ -3721,6 +3873,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3721
3873
  throw new Error(`Unsupported chain ID: ${chainId}`);
3722
3874
  }
3723
3875
  await this.authenticateUser();
3876
+ this.assertConnectedUser(userAddress);
3724
3877
  this.warnPredeployedOnboardingMethod("deploySafe");
3725
3878
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
3726
3879
  const predeployedAddress = await this.getSafeAddressFor(
@@ -3893,6 +4046,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3893
4046
  async createSessionKey(userAddress, chainId) {
3894
4047
  try {
3895
4048
  await this.authenticateUser();
4049
+ this.assertConnectedUser(userAddress);
3896
4050
  this.warnPredeployedOnboardingMethod("createSessionKey");
3897
4051
  if (!this.authenticatedUserId) {
3898
4052
  throw new Error(
@@ -3907,6 +4061,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3907
4061
  alreadyActive: true
3908
4062
  };
3909
4063
  }
4064
+ const nestedChain = getChainConfig(chainId, this.rpcUrls);
4065
+ if (await getAccountType(userAddress, nestedChain.publicClient) === "Safe") {
4066
+ await assertParentSafeDeployedOnChain(userAddress, nestedChain.publicClient, chainId);
4067
+ return this.registerNestedIntentSessionKey(userAddress, chainId);
4068
+ }
3910
4069
  if (this.hasActiveSessionKey) {
3911
4070
  return {
3912
4071
  success: true,
@@ -3938,12 +4097,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3938
4097
  userAddress,
3939
4098
  chainConfig.publicClient
3940
4099
  );
3941
- if (accountType === "Safe") {
3942
- return this.registerNestedIntentSessionKey(
3943
- userAddress,
3944
- chainId,
3945
- void 0
3946
- );
4100
+ if (accountType !== "EOA") {
4101
+ throw new Error("Unable to establish EOA session account type");
3947
4102
  }
3948
4103
  const signingParams = {
3949
4104
  permitGenericPolicy,
@@ -4441,10 +4596,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4441
4596
  * await sdk.waitForDepositPosition(sent.registration.id, 8453);
4442
4597
  * ```
4443
4598
  */
4444
- async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
4445
- return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true);
4599
+ async sendDirectDeposit(userAddress, chainId, amount, asset, strategy, onSafeProposal) {
4600
+ return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true, onSafeProposal);
4446
4601
  }
4447
- async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit) {
4602
+ async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit, onSafeProposal) {
4448
4603
  try {
4449
4604
  if (!userAddress) {
4450
4605
  throw new Error("User address is required");
@@ -4496,11 +4651,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4496
4651
  } else {
4497
4652
  await this.authenticateUser();
4498
4653
  }
4499
- await this.hydrateSessionWallet();
4500
- const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4501
- if (!safeAddress) {
4502
- throw new Error("Smart wallet address is not available");
4654
+ this.assertConnectedUser(userAddress);
4655
+ if (!this.signer && walletClient.chain?.id !== chainId) {
4656
+ throw new Error("Switch the connected wallet to the deposit chain and reconnect");
4503
4657
  }
4658
+ await this.hydrateSessionWallet();
4659
+ let safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4504
4660
  const amountBigInt = BigInt(amount);
4505
4661
  const ownerType = await getAccountType(
4506
4662
  userAddress,
@@ -4511,6 +4667,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4511
4667
  `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.`
4512
4668
  );
4513
4669
  }
4670
+ let nestedOnboarded = false;
4671
+ if (!safeAddress && ownerType === "Safe" && !this.isPredeployed) {
4672
+ await this.ensureNestedOwnerReadyForDeposit(userAddress, chainId, strategy);
4673
+ safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4674
+ nestedOnboarded = true;
4675
+ }
4676
+ if (!safeAddress) {
4677
+ throw new Error("Smart wallet address is not available");
4678
+ }
4514
4679
  const [isDeployed, currentSafeBalance] = await Promise.all([
4515
4680
  isSafeDeployed(safeAddress, chainConfig.publicClient),
4516
4681
  minRequired !== void 0 ? chainConfig.publicClient.readContract({
@@ -4522,7 +4687,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4522
4687
  this.prepareFirstDeposit(strategy)
4523
4688
  ]).then(([deployed, balance]) => [deployed, balance]);
4524
4689
  if (!isDeployed) {
4525
- if (ownerType === "Safe" && !this.isPredeployed) {
4690
+ if (ownerType === "Safe" && !this.isPredeployed && !nestedOnboarded) {
4526
4691
  await assertParentSafeDeployedOnChain(
4527
4692
  userAddress,
4528
4693
  chainConfig.publicClient,
@@ -4556,7 +4721,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4556
4721
  );
4557
4722
  }
4558
4723
  }
4559
- if (ownerType === "Safe" && isDeployed) {
4724
+ if (ownerType === "Safe" && isDeployed && !nestedOnboarded) {
4560
4725
  await assertParentSafeDeployedOnChain(
4561
4726
  userAddress,
4562
4727
  chainConfig.publicClient,
@@ -4579,35 +4744,35 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4579
4744
  if (sponsored) return sponsored;
4580
4745
  }
4581
4746
  if (ownerType === "Safe") {
4582
- const since = new Date(Date.now() - NESTED_SAFE_RESUME_WINDOW_MS);
4583
- const inFlight = await findSafeTransferProposal({
4584
- parentSafe: userAddress,
4585
- childSafe: safeAddress,
4586
- chainId,
4587
- tokenAddress: token,
4588
- amount: amountBigInt,
4589
- since
4747
+ const proposed = await walletClient.writeContract({
4748
+ address: token,
4749
+ abi: erc20TransferWriteAbi(assetSymbol),
4750
+ functionName: "transfer",
4751
+ args: [safeAddress, amountBigInt],
4752
+ chain: chainConfig.chain,
4753
+ account: walletClient.account
4590
4754
  });
4591
- let safeTxHash = inFlight?.safeTxHash;
4592
- if (!inFlight) {
4593
- const proposed = await walletClient.writeContract({
4594
- address: token,
4595
- abi: erc20TransferWriteAbi(assetSymbol),
4596
- functionName: "transfer",
4597
- args: [safeAddress, amountBigInt],
4598
- chain: chainConfig.chain,
4599
- account: walletClient.account
4600
- });
4601
- safeTxHash = (await findSafeTransferByHash({ chainId, safeTxHash: proposed }))?.safeTxHash;
4755
+ const reference = {
4756
+ userAddress: (0, import_viem8.getAddress)(userAddress),
4757
+ chainId,
4758
+ amount,
4759
+ asset: assetSymbol,
4760
+ childSafe: safeAddress,
4761
+ proposalHash: proposed
4762
+ };
4763
+ try {
4764
+ await onSafeProposal?.(reference);
4765
+ } catch (error) {
4766
+ throw new Error(`Safe proposal ${proposed} was submitted; persist its reference and resumeNestedSafeDeposit instead of sending again: ${thrownMessage(error)}`);
4602
4767
  }
4603
- const executedHash = inFlight?.isExecuted && inFlight.transactionHash ? inFlight.transactionHash : await waitForSafeTransferExecution({
4604
- parentSafe: userAddress,
4768
+ const executedHash = await waitForExactSafeDepositExecution({
4769
+ parentSafe: reference.userAddress,
4605
4770
  childSafe: safeAddress,
4606
4771
  chainId,
4607
4772
  tokenAddress: token,
4608
4773
  amount: amountBigInt,
4609
- safeTxHash,
4610
- since
4774
+ proposalHash: proposed,
4775
+ publicClient: chainConfig.publicClient
4611
4776
  });
4612
4777
  const registration2 = await this.registerDeposit(
4613
4778
  chainId,
@@ -4782,6 +4947,39 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4782
4947
  strategy
4783
4948
  );
4784
4949
  }
4950
+ /**
4951
+ * Resume one specific parent Safe deposit without proposing another transfer.
4952
+ * Persist the reference supplied by sendDeposit's onSafeProposal callback.
4953
+ *
4954
+ * @group Deposits and withdrawals
4955
+ */
4956
+ async resumeNestedSafeDeposit(reference) {
4957
+ const { userAddress, chainId, childSafe, proposalHash, asset, amount } = reference;
4958
+ if (!isSupportedChain(chainId)) throw new Error("Unsupported deposit chain");
4959
+ if (!/^0x[0-9a-fA-F]{64}$/.test(proposalHash)) throw new Error("Invalid proposal hash");
4960
+ await this.authenticateUser();
4961
+ if (!this.isConnectedUser(userAddress) || this.sessionEoa && !(0, import_viem8.isAddressEqual)(this.sessionEoa, userAddress)) {
4962
+ throw new Error("Deposit reference does not match the authenticated parent");
4963
+ }
4964
+ await this.hydrateSessionWallet();
4965
+ const resolved = await this.getSafeAddressFor(userAddress, chainId);
4966
+ if (!resolved || !(0, import_viem8.isAddressEqual)(resolved, childSafe)) throw new Error("Deposit reference does not match the registered child");
4967
+ const symbol = resolveAssetSymbol(asset);
4968
+ if (!getAssetChainIds(symbol).includes(chainId) || BigInt(amount) <= 0n) throw new Error("Invalid deposit asset or amount");
4969
+ const config = getChainConfig(chainId, this.rpcUrls);
4970
+ const token = getDefaultTokenAddress(chainId, symbol);
4971
+ const txHash = await waitForExactSafeDepositExecution({
4972
+ parentSafe: userAddress,
4973
+ childSafe,
4974
+ chainId,
4975
+ tokenAddress: token,
4976
+ amount: BigInt(amount),
4977
+ proposalHash,
4978
+ publicClient: config.publicClient
4979
+ });
4980
+ const registration = await this.registerDeposit(chainId, txHash, amount, token);
4981
+ return { success: true, txHash, smartWallet: childSafe, amount, route: "direct", registration };
4982
+ }
4785
4983
  /**
4786
4984
  * Resolve a deposit without signing.
4787
4985
  *
@@ -5042,7 +5240,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5042
5240
  params.chainId,
5043
5241
  params.amount,
5044
5242
  route.asset,
5045
- params.strategy
5243
+ params.strategy,
5244
+ params.onSafeProposal
5046
5245
  );
5047
5246
  }
5048
5247
  if (route.kind === "wrap") {
@@ -5660,7 +5859,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5660
5859
  );
5661
5860
  } catch (logError) {
5662
5861
  throw new Error(
5663
- `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
5862
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}", "${tokenAddress}") to retry.`
5664
5863
  );
5665
5864
  }
5666
5865
  return registration.deposit;
@@ -6027,6 +6226,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
6027
6226
  );
6028
6227
  }
6029
6228
  await this.authenticateUser();
6229
+ this.assertConnectedUser(userAddress);
6030
6230
  await this.assertAsyncRedemptionSlotFree(
6031
6231
  userAddress,
6032
6232
  chainId,
@@ -8541,9 +8741,11 @@ function createBankrProvider(config) {
8541
8741
  WS_ENDPOINT,
8542
8742
  WS_URLS,
8543
8743
  ZyfaiSDK,
8744
+ buildNestedSafeOnboardingStatus,
8544
8745
  buildV1ChainSessions,
8545
8746
  createBankrProvider,
8546
8747
  decodeUserOperationCalls,
8748
+ deriveNestedSafeOnboardingStep,
8547
8749
  getChainConfig,
8548
8750
  getDataApiBaseUrl,
8549
8751
  getDefaultTokenAddress,
@@ -8556,6 +8758,7 @@ function createBankrProvider(config) {
8556
8758
  isSupportedChain,
8557
8759
  parseUserOperationJson,
8558
8760
  parseV1ChainSessions,
8761
+ portfolioHasWithdrawableBalance,
8559
8762
  resolveDepositRoute,
8560
8763
  resolveRelaySlippageBps,
8561
8764
  serializeV1ChainSessions