@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.mjs CHANGED
@@ -1632,6 +1632,15 @@ var getAccountType = async (address, publicClient) => {
1632
1632
  return "Unknown";
1633
1633
  }
1634
1634
  };
1635
+ function isSafeDeployPermissionsReady(prepare) {
1636
+ return prepare.success && !prepare.userOpHashToSign && prepare.signingMode !== "typed-data";
1637
+ }
1638
+ async function postSafeDeployPrepare(httpClient, chainId, strategyBody = {}) {
1639
+ return await httpClient.post(
1640
+ `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1641
+ strategyBody
1642
+ );
1643
+ }
1635
1644
  var signNestedSafeDeployTypedData = async (owner, parentSafe, typedData) => {
1636
1645
  if (!owner.account) {
1637
1646
  throw new Error("Wallet not connected. Please connect your wallet first.");
@@ -1644,10 +1653,12 @@ var signNestedSafeDeployTypedData = async (owner, parentSafe, typedData) => {
1644
1653
  message: typedData.message
1645
1654
  });
1646
1655
  };
1647
- var completeSafeDeploy = async (config, strategyBody, body) => {
1656
+ var TYPED_DATA_DEPLOY_TIMEOUT_MS = 18e4;
1657
+ var completeSafeDeploy = async (config, strategyBody, body, requestConfig) => {
1648
1658
  const deployResponse = await config.httpClient.post(
1649
1659
  `${ENDPOINTS.SAFE_DEPLOY}?chainId=${config.chainId}`,
1650
- { ...body, ...strategyBody }
1660
+ { ...body, ...strategyBody },
1661
+ requestConfig
1651
1662
  );
1652
1663
  if (!deployResponse.success) {
1653
1664
  throw new Error(
@@ -1677,12 +1688,13 @@ var deploySafeAccount = async (config) => {
1677
1688
  }
1678
1689
  console.log("strategy", strategy);
1679
1690
  const strategyBody = strategy ? { strategy } : {};
1680
- const prepareResponse = await httpClient.post(
1681
- `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1691
+ const prepareResponse = await postSafeDeployPrepare(
1692
+ httpClient,
1693
+ chainId,
1682
1694
  strategyBody
1683
1695
  );
1684
1696
  console.log("prepareResponse", prepareResponse);
1685
- if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1697
+ if (isSafeDeployPermissionsReady(prepareResponse)) {
1686
1698
  return {
1687
1699
  safeAddress: prepareResponse.safeAddress || "0x",
1688
1700
  txHash: "0x0",
@@ -1704,9 +1716,12 @@ var deploySafeAccount = async (config) => {
1704
1716
  parentSafe,
1705
1717
  prepareResponse.typedData
1706
1718
  );
1707
- return completeSafeDeploy(config, strategyBody, {
1708
- typedDataSignature
1709
- });
1719
+ return completeSafeDeploy(
1720
+ config,
1721
+ strategyBody,
1722
+ { typedDataSignature },
1723
+ { timeout: TYPED_DATA_DEPLOY_TIMEOUT_MS }
1724
+ );
1710
1725
  }
1711
1726
  if (!prepareResponse.userOpHashToSign) {
1712
1727
  throw new Error(
@@ -1878,7 +1893,9 @@ async function signNestedOwnerSessionKey(config, sessions, allPublicClients, sig
1878
1893
 
1879
1894
  // src/utils/nested-safe-deposit.ts
1880
1895
  import {
1881
- getAddress as getAddress3
1896
+ getAddress as getAddress3,
1897
+ decodeEventLog,
1898
+ parseAbiItem
1882
1899
  } from "viem";
1883
1900
  var NESTED_SAFE_DEPOSIT_TIMEOUT_MS = 20 * 60 * 1e3;
1884
1901
  var NESTED_SAFE_DEPOSIT_POLL_MS = 1e4;
@@ -1920,35 +1937,6 @@ function sameAddress(left, right) {
1920
1937
  return false;
1921
1938
  }
1922
1939
  }
1923
- function transferMatches(transaction, params) {
1924
- if (!sameAddress(transaction.to, params.tokenAddress)) return false;
1925
- if (transaction.isSuccessful === false) return false;
1926
- const decoded = transaction.dataDecoded;
1927
- if (decoded?.method?.toLowerCase() !== "transfer") return false;
1928
- const parameters = decoded.parameters;
1929
- if (!parameters) return false;
1930
- const destination = parameters.find(
1931
- (p) => (p.name === "to" || p.name === "dst" || p.name === "_to") && p.type === "address"
1932
- );
1933
- if (!sameAddress(destination?.value, params.childSafe)) return false;
1934
- if (params.amount === void 0) return true;
1935
- const valueParam = parameters.find(
1936
- (p) => (p.name === "value" || p.name === "amount" || p.name === "_value" || p.name === "wad") && p.type.startsWith("uint")
1937
- );
1938
- if (!valueParam) return false;
1939
- try {
1940
- return BigInt(valueParam.value) === params.amount;
1941
- } catch {
1942
- return false;
1943
- }
1944
- }
1945
- function isWithinWindow(transaction, since) {
1946
- if (!since) return true;
1947
- const stamp = transaction.executionDate ?? transaction.submissionDate;
1948
- if (!stamp) return false;
1949
- const at = Date.parse(stamp);
1950
- return Number.isFinite(at) && at >= since.getTime();
1951
- }
1952
1940
  async function findSafeTransferByHash(params) {
1953
1941
  const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1954
1942
  const url = `https://api.safe.global/tx-service/${networkName}/api/v2/multisig-transactions/${params.safeTxHash}/`;
@@ -1967,54 +1955,100 @@ async function findSafeTransferByHash(params) {
1967
1955
  isExecuted: transaction.isExecuted === true && !!transaction.transactionHash
1968
1956
  };
1969
1957
  }
1970
- async function findSafeTransferProposal(params) {
1971
- const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1972
- const url = `https://api.safe.global/tx-service/${networkName}/api/v2/safes/${getAddress3(
1973
- params.parentSafe
1974
- )}/multisig-transactions/?ordering=-nonce`;
1975
- const response = await fetch(url);
1976
- if (!response.ok) return null;
1977
- const body = await response.json();
1978
- const match = (body.results ?? []).find(
1979
- (transaction) => !!transaction.safeTxHash && isWithinWindow(transaction, params.since) && transferMatches(transaction, {
1980
- childSafe: params.childSafe,
1981
- tokenAddress: params.tokenAddress,
1982
- amount: params.amount
1983
- })
1984
- );
1985
- if (!match) return null;
1986
- return {
1987
- safeTxHash: match.safeTxHash,
1988
- transactionHash: match.transactionHash ?? null,
1989
- isExecuted: match.isExecuted === true && !!match.transactionHash
1990
- };
1991
- }
1992
- async function waitForSafeTransferExecution(params) {
1993
- safeTxServiceNetworkNameOrThrow(params.chainId);
1958
+ var TRANSFER_EVENT = parseAbiItem("event Transfer(address indexed from, address indexed to, uint256 value)");
1959
+ async function waitForExactSafeDepositExecution(params) {
1960
+ const started = Date.now();
1994
1961
  const timeoutMs = params.timeoutMs ?? NESTED_SAFE_DEPOSIT_TIMEOUT_MS;
1995
1962
  const pollMs = params.pollMs ?? NESTED_SAFE_DEPOSIT_POLL_MS;
1996
- const started = Date.now();
1997
- do {
1998
- const proposal = params.safeTxHash ? await findSafeTransferByHash({
1999
- chainId: params.chainId,
2000
- safeTxHash: params.safeTxHash
2001
- }) : await findSafeTransferProposal({
2002
- parentSafe: params.parentSafe,
2003
- childSafe: params.childSafe,
2004
- chainId: params.chainId,
2005
- tokenAddress: params.tokenAddress,
2006
- amount: params.amount,
2007
- since: params.since
2008
- });
2009
- if (proposal?.isExecuted && proposal.transactionHash) {
2010
- return proposal.transactionHash;
1963
+ let hash = params.proposalHash;
1964
+ try {
1965
+ do {
1966
+ const receipt = await params.publicClient.getTransactionReceipt({ hash }).catch(() => void 0);
1967
+ if (receipt) {
1968
+ if (receipt.status !== "success") throw new Error("Safe transfer reverted");
1969
+ const matches = receipt.logs.some((log) => {
1970
+ if (!sameAddress(log.address, params.tokenAddress)) return false;
1971
+ try {
1972
+ const decoded = decodeEventLog({ abi: [TRANSFER_EVENT], data: log.data, topics: log.topics });
1973
+ return sameAddress(decoded.args.from, params.parentSafe) && sameAddress(decoded.args.to, params.childSafe) && decoded.args.value === params.amount;
1974
+ } catch {
1975
+ return false;
1976
+ }
1977
+ });
1978
+ if (!matches) throw new Error("Executed transaction does not contain the expected parent-to-child transfer");
1979
+ return hash;
1980
+ }
1981
+ if (safeTxServiceNetworkName(params.chainId) && hash === params.proposalHash) {
1982
+ const proposal = await findSafeTransferByHash({ chainId: params.chainId, safeTxHash: params.proposalHash });
1983
+ if (proposal?.isExecuted && proposal.transactionHash) {
1984
+ hash = proposal.transactionHash;
1985
+ continue;
1986
+ }
1987
+ }
1988
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
1989
+ } while (Date.now() - started < timeoutMs);
1990
+ throw new Error("Timed out waiting for Safe transfer execution");
1991
+ } catch (error) {
1992
+ throw new Error(`Safe deposit proposal ${params.proposalHash}: ${error.message}. Resume this exact proposal with resumeNestedSafeDeposit; do not send another transfer.`);
1993
+ }
1994
+ }
1995
+
1996
+ // src/utils/nested-safe-onboarding.ts
1997
+ function positiveAmount(value) {
1998
+ if (!value) return false;
1999
+ const trimmed = value.trim();
2000
+ if (!trimmed || trimmed === "0" || trimmed === "0x" || trimmed === "0x0") {
2001
+ return false;
2002
+ }
2003
+ try {
2004
+ if (trimmed.startsWith("0x") || trimmed.startsWith("0X")) {
2005
+ return BigInt(trimmed) > 0n;
2011
2006
  }
2012
- await new Promise((resolve) => setTimeout(resolve, pollMs));
2013
- } while (Date.now() - started < timeoutMs);
2014
- throw new Error(
2015
- `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.`
2007
+ if (/^\d+$/.test(trimmed)) return BigInt(trimmed) > 0n;
2008
+ const numeric = Number(trimmed);
2009
+ return Number.isFinite(numeric) && numeric > 0;
2010
+ } catch {
2011
+ return false;
2012
+ }
2013
+ }
2014
+ function portfolioHasWithdrawableBalance(portfolio) {
2015
+ if (!portfolio) return false;
2016
+ if (portfolio.hasBalance) return true;
2017
+ const buckets = [
2018
+ ...Object.values(portfolio.portfolioByAssetType ?? {}),
2019
+ ...Object.values(portfolio.portfolioByChain ?? {}).flatMap(
2020
+ (byAsset) => Object.values(byAsset)
2021
+ )
2022
+ ];
2023
+ if (buckets.some(
2024
+ (entry) => positiveAmount(entry.balance) || positiveAmount(entry.balanceWithFee)
2025
+ )) {
2026
+ return true;
2027
+ }
2028
+ if ((portfolio.positions ?? []).some(
2029
+ (slot) => positiveAmount(slot.underlyingAmountWithFee) || positiveAmount(slot.underlyingAmount) || positiveAmount(slot.amount)
2030
+ )) {
2031
+ return true;
2032
+ }
2033
+ return (portfolio.staleBalances ?? []).some(
2034
+ (stale) => positiveAmount(stale.balance)
2016
2035
  );
2017
2036
  }
2037
+ function deriveNestedSafeOnboardingStep(flags) {
2038
+ if (!flags.isNestedOwner) return "deploy";
2039
+ if (!flags.childRegistered || !flags.childDeployed) return "deploy";
2040
+ if (!flags.sessionActive) return "register";
2041
+ if (!flags.hasPortfolioBalance) return "deposit";
2042
+ if (flags.hasPortfolioBalance) return "withdraw";
2043
+ return "ready";
2044
+ }
2045
+ function buildNestedSafeOnboardingStatus(flags, child) {
2046
+ return {
2047
+ ...flags,
2048
+ child,
2049
+ suggestedStep: deriveNestedSafeOnboardingStep(flags)
2050
+ };
2051
+ }
2018
2052
 
2019
2053
  // src/utils/strategy.ts
2020
2054
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
@@ -3272,15 +3306,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3272
3306
  throw new Error(`Unsupported chain ID: ${chainId}`);
3273
3307
  }
3274
3308
  const resolvedAddress = await this.resolveConnectAddress(account);
3275
- if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && isAddressEqual2(resolvedAddress, this.sessionEoa)) {
3309
+ if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && isAddressEqual2(resolvedAddress, this.sessionEoa) && this.currentChainId === chainId && (account === this.currentProvider || account === this.walletClient)) {
3276
3310
  this.currentChainId = chainId;
3277
3311
  return resolvedAddress;
3278
3312
  }
3279
3313
  if (this.connectAccountInFlight) {
3280
- return this.connectAccountInFlight;
3314
+ throw new Error("Wallet connection already in progress; retry after it completes");
3281
3315
  }
3282
3316
  const connect = (async () => {
3283
3317
  this.authenticatedUserId = null;
3318
+ this.hasActiveSessionKey = false;
3319
+ this.signer = null;
3284
3320
  this.isPredeployed = false;
3285
3321
  this.predeployedResolved = false;
3286
3322
  this.connectedSmartWallet = null;
@@ -3330,6 +3366,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3330
3366
  transport: provider.transport
3331
3367
  });
3332
3368
  connectedAddress = getAddress4(resolvedAddress2);
3369
+ if (provider.chain?.id !== void 0 && provider.chain.id !== chainId) {
3370
+ throw new Error(`Wallet client chain ${provider.chain.id} does not match requested chain ${chainId}`);
3371
+ }
3333
3372
  this.currentProvider = null;
3334
3373
  this.currentChainId = chainId;
3335
3374
  } else if (provider.request) {
@@ -3353,6 +3392,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3353
3392
  );
3354
3393
  }
3355
3394
  connectedAddress = getAddress4(accountAddress);
3395
+ if (!isAddressEqual2(connectedAddress, resolvedAddress)) {
3396
+ throw new Error("Wallet account changed during connection; reconnect");
3397
+ }
3398
+ const providerChain = await eip1193.request({ method: "eth_chainId" });
3399
+ if (Number(providerChain) !== chainId) {
3400
+ throw new Error(`Wallet is on chain ${providerChain}; switch to chain ${chainId} before connecting`);
3401
+ }
3356
3402
  this.walletClient = createWalletClient({
3357
3403
  account: connectedAddress,
3358
3404
  chain: chainConfig.chain,
@@ -3441,6 +3487,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3441
3487
  * True when userAddress is the signer, wallet client, or agent session EOA.
3442
3488
  * @private
3443
3489
  */
3490
+ assertConnectedUser(userAddress) {
3491
+ if (!this.isConnectedUser(userAddress) || this.sessionEoa && !isAddressEqual2(getAddress4(userAddress), this.sessionEoa)) {
3492
+ throw new Error("userAddress does not match the authenticated wallet");
3493
+ }
3494
+ }
3444
3495
  isConnectedUser(userAddress) {
3445
3496
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3446
3497
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
@@ -3450,6 +3501,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3450
3501
  * (install or emissary enable), then register with chainId only.
3451
3502
  * @private
3452
3503
  */
3504
+ /**
3505
+ * Read-only probe for nested owners: on-chain session permissions on `chainId`.
3506
+ * Mirrors the early-return branch in {@link deploySafeAccount} without signing.
3507
+ * @private
3508
+ */
3509
+ async isNestedChainSessionPermissionsReady(chainId) {
3510
+ const prepare = await postSafeDeployPrepare(this.httpClient, chainId);
3511
+ return isSafeDeployPermissionsReady(prepare);
3512
+ }
3453
3513
  async registerNestedIntentSessionKey(userAddress, chainId, strategy) {
3454
3514
  if (!this.authenticatedUserId) {
3455
3515
  throw new Error(
@@ -3466,10 +3526,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3466
3526
  httpClient: this.httpClient,
3467
3527
  strategy
3468
3528
  });
3529
+ if (this.hasActiveSessionKey) {
3530
+ return {
3531
+ success: true,
3532
+ userId: this.authenticatedUserId,
3533
+ message: "Intent session permissions ready on requested chain",
3534
+ alreadyActive: true
3535
+ };
3536
+ }
3469
3537
  const activation = await this.httpClient.post(
3470
3538
  ENDPOINTS.SESSION_KEYS_ADD,
3471
3539
  { chainId }
3472
3540
  );
3541
+ if (!activation?.isActive || !activation?.isEnabled) {
3542
+ throw new Error("Intent session is not active and enabled on the requested chain");
3543
+ }
3473
3544
  this.hasActiveSessionKey = true;
3474
3545
  return {
3475
3546
  success: true,
@@ -3515,7 +3586,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3515
3586
  const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3516
3587
  const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3517
3588
  if (!childDeployed) {
3518
- await this.deploySafe(userAddress, chainId, strategy, true);
3589
+ const deployment = await this.deploySafe(userAddress, chainId, strategy, false);
3590
+ if (!deployment.success) throw new Error("Nested Safe deployment failed");
3591
+ await this.createSessionKey(userAddress, chainId);
3519
3592
  return;
3520
3593
  }
3521
3594
  console.info(
@@ -3640,6 +3713,84 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3640
3713
  isOwner
3641
3714
  };
3642
3715
  }
3716
+ /**
3717
+ * Nested-parent onboarding snapshot for a connected parent Safe address.
3718
+ *
3719
+ * @group Deposits and withdrawals
3720
+ *
3721
+ * @remarks Combines child resolution ({@link ZyfaiSDK.getSmartWalletAddress}),
3722
+ * session state (account registration plus per-chain safe-deploy readiness),
3723
+ * and portfolio balances
3724
+ * ({@link ZyfaiSDK.getPortfolio}). Wallet connect remains integrator-side.
3725
+ *
3726
+ * @param userAddress - Parent Safe address from {@link ZyfaiSDK.connectAccount}
3727
+ * @param chainId - Target chain (deployment and session are per chain)
3728
+ */
3729
+ async getNestedSafeOnboardingStatus(userAddress, chainId) {
3730
+ if (!userAddress) {
3731
+ throw new Error("User address is required");
3732
+ }
3733
+ if (!isSupportedChain(chainId)) {
3734
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3735
+ }
3736
+ await this.authenticateUser();
3737
+ this.assertConnectedUser(userAddress);
3738
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3739
+ const isNestedOwner = await getAccountType(userAddress, chainConfig.publicClient) === "Safe";
3740
+ let child = null;
3741
+ let childRegistered = false;
3742
+ let childDeployed = false;
3743
+ try {
3744
+ child = await this.getSmartWalletAddress(userAddress, chainId);
3745
+ childRegistered = true;
3746
+ childDeployed = child.isDeployed;
3747
+ } catch (error) {
3748
+ const message = error.message;
3749
+ if (message !== "NESTED_CHILD_UNREGISTERED") {
3750
+ throw error;
3751
+ }
3752
+ }
3753
+ let accountSessionRegistered = false;
3754
+ try {
3755
+ const details = await this.getUserDetails("USDC");
3756
+ accountSessionRegistered = Boolean(details.hasActiveSessionKey);
3757
+ } catch {
3758
+ }
3759
+ let chainSessionReady = false;
3760
+ if (isNestedOwner && childDeployed) {
3761
+ try {
3762
+ chainSessionReady = await this.isNestedChainSessionPermissionsReady(chainId);
3763
+ } catch {
3764
+ }
3765
+ }
3766
+ const sessionActive = chainSessionReady && accountSessionRegistered;
3767
+ let hasPortfolioBalance = false;
3768
+ if (childRegistered) {
3769
+ try {
3770
+ const portfolio = await this.getPortfolio(userAddress);
3771
+ hasPortfolioBalance = portfolioHasWithdrawableBalance(
3772
+ portfolio.portfolio
3773
+ );
3774
+ } catch {
3775
+ }
3776
+ }
3777
+ const status = buildNestedSafeOnboardingStatus(
3778
+ {
3779
+ isNestedOwner,
3780
+ childRegistered,
3781
+ childDeployed,
3782
+ sessionActive: sessionActive && childDeployed && childRegistered,
3783
+ hasPortfolioBalance
3784
+ },
3785
+ child
3786
+ );
3787
+ return {
3788
+ success: true,
3789
+ userAddress,
3790
+ chainId,
3791
+ status
3792
+ };
3793
+ }
3643
3794
  /**
3644
3795
  * Deploy Safe Smart Wallet for a user
3645
3796
  *
@@ -3677,6 +3828,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3677
3828
  throw new Error(`Unsupported chain ID: ${chainId}`);
3678
3829
  }
3679
3830
  await this.authenticateUser();
3831
+ this.assertConnectedUser(userAddress);
3680
3832
  this.warnPredeployedOnboardingMethod("deploySafe");
3681
3833
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
3682
3834
  const predeployedAddress = await this.getSafeAddressFor(
@@ -3849,6 +4001,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3849
4001
  async createSessionKey(userAddress, chainId) {
3850
4002
  try {
3851
4003
  await this.authenticateUser();
4004
+ this.assertConnectedUser(userAddress);
3852
4005
  this.warnPredeployedOnboardingMethod("createSessionKey");
3853
4006
  if (!this.authenticatedUserId) {
3854
4007
  throw new Error(
@@ -3863,6 +4016,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3863
4016
  alreadyActive: true
3864
4017
  };
3865
4018
  }
4019
+ const nestedChain = getChainConfig(chainId, this.rpcUrls);
4020
+ if (await getAccountType(userAddress, nestedChain.publicClient) === "Safe") {
4021
+ await assertParentSafeDeployedOnChain(userAddress, nestedChain.publicClient, chainId);
4022
+ return this.registerNestedIntentSessionKey(userAddress, chainId);
4023
+ }
3866
4024
  if (this.hasActiveSessionKey) {
3867
4025
  return {
3868
4026
  success: true,
@@ -3894,12 +4052,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3894
4052
  userAddress,
3895
4053
  chainConfig.publicClient
3896
4054
  );
3897
- if (accountType === "Safe") {
3898
- return this.registerNestedIntentSessionKey(
3899
- userAddress,
3900
- chainId,
3901
- void 0
3902
- );
4055
+ if (accountType !== "EOA") {
4056
+ throw new Error("Unable to establish EOA session account type");
3903
4057
  }
3904
4058
  const signingParams = {
3905
4059
  permitGenericPolicy,
@@ -4397,10 +4551,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4397
4551
  * await sdk.waitForDepositPosition(sent.registration.id, 8453);
4398
4552
  * ```
4399
4553
  */
4400
- async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
4401
- return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true);
4554
+ async sendDirectDeposit(userAddress, chainId, amount, asset, strategy, onSafeProposal) {
4555
+ return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true, onSafeProposal);
4402
4556
  }
4403
- async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit) {
4557
+ async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit, onSafeProposal) {
4404
4558
  try {
4405
4559
  if (!userAddress) {
4406
4560
  throw new Error("User address is required");
@@ -4452,11 +4606,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4452
4606
  } else {
4453
4607
  await this.authenticateUser();
4454
4608
  }
4455
- await this.hydrateSessionWallet();
4456
- const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4457
- if (!safeAddress) {
4458
- throw new Error("Smart wallet address is not available");
4609
+ this.assertConnectedUser(userAddress);
4610
+ if (!this.signer && walletClient.chain?.id !== chainId) {
4611
+ throw new Error("Switch the connected wallet to the deposit chain and reconnect");
4459
4612
  }
4613
+ await this.hydrateSessionWallet();
4614
+ let safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4460
4615
  const amountBigInt = BigInt(amount);
4461
4616
  const ownerType = await getAccountType(
4462
4617
  userAddress,
@@ -4467,6 +4622,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4467
4622
  `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.`
4468
4623
  );
4469
4624
  }
4625
+ let nestedOnboarded = false;
4626
+ if (!safeAddress && ownerType === "Safe" && !this.isPredeployed) {
4627
+ await this.ensureNestedOwnerReadyForDeposit(userAddress, chainId, strategy);
4628
+ safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4629
+ nestedOnboarded = true;
4630
+ }
4631
+ if (!safeAddress) {
4632
+ throw new Error("Smart wallet address is not available");
4633
+ }
4470
4634
  const [isDeployed, currentSafeBalance] = await Promise.all([
4471
4635
  isSafeDeployed(safeAddress, chainConfig.publicClient),
4472
4636
  minRequired !== void 0 ? chainConfig.publicClient.readContract({
@@ -4478,7 +4642,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4478
4642
  this.prepareFirstDeposit(strategy)
4479
4643
  ]).then(([deployed, balance]) => [deployed, balance]);
4480
4644
  if (!isDeployed) {
4481
- if (ownerType === "Safe" && !this.isPredeployed) {
4645
+ if (ownerType === "Safe" && !this.isPredeployed && !nestedOnboarded) {
4482
4646
  await assertParentSafeDeployedOnChain(
4483
4647
  userAddress,
4484
4648
  chainConfig.publicClient,
@@ -4512,7 +4676,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4512
4676
  );
4513
4677
  }
4514
4678
  }
4515
- if (ownerType === "Safe" && isDeployed) {
4679
+ if (ownerType === "Safe" && isDeployed && !nestedOnboarded) {
4516
4680
  await assertParentSafeDeployedOnChain(
4517
4681
  userAddress,
4518
4682
  chainConfig.publicClient,
@@ -4535,35 +4699,35 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4535
4699
  if (sponsored) return sponsored;
4536
4700
  }
4537
4701
  if (ownerType === "Safe") {
4538
- const since = new Date(Date.now() - NESTED_SAFE_RESUME_WINDOW_MS);
4539
- const inFlight = await findSafeTransferProposal({
4540
- parentSafe: userAddress,
4541
- childSafe: safeAddress,
4542
- chainId,
4543
- tokenAddress: token,
4544
- amount: amountBigInt,
4545
- since
4702
+ const proposed = await walletClient.writeContract({
4703
+ address: token,
4704
+ abi: erc20TransferWriteAbi(assetSymbol),
4705
+ functionName: "transfer",
4706
+ args: [safeAddress, amountBigInt],
4707
+ chain: chainConfig.chain,
4708
+ account: walletClient.account
4546
4709
  });
4547
- let safeTxHash = inFlight?.safeTxHash;
4548
- if (!inFlight) {
4549
- const proposed = await walletClient.writeContract({
4550
- address: token,
4551
- abi: erc20TransferWriteAbi(assetSymbol),
4552
- functionName: "transfer",
4553
- args: [safeAddress, amountBigInt],
4554
- chain: chainConfig.chain,
4555
- account: walletClient.account
4556
- });
4557
- safeTxHash = (await findSafeTransferByHash({ chainId, safeTxHash: proposed }))?.safeTxHash;
4710
+ const reference = {
4711
+ userAddress: getAddress4(userAddress),
4712
+ chainId,
4713
+ amount,
4714
+ asset: assetSymbol,
4715
+ childSafe: safeAddress,
4716
+ proposalHash: proposed
4717
+ };
4718
+ try {
4719
+ await onSafeProposal?.(reference);
4720
+ } catch (error) {
4721
+ throw new Error(`Safe proposal ${proposed} was submitted; persist its reference and resumeNestedSafeDeposit instead of sending again: ${thrownMessage(error)}`);
4558
4722
  }
4559
- const executedHash = inFlight?.isExecuted && inFlight.transactionHash ? inFlight.transactionHash : await waitForSafeTransferExecution({
4560
- parentSafe: userAddress,
4723
+ const executedHash = await waitForExactSafeDepositExecution({
4724
+ parentSafe: reference.userAddress,
4561
4725
  childSafe: safeAddress,
4562
4726
  chainId,
4563
4727
  tokenAddress: token,
4564
4728
  amount: amountBigInt,
4565
- safeTxHash,
4566
- since
4729
+ proposalHash: proposed,
4730
+ publicClient: chainConfig.publicClient
4567
4731
  });
4568
4732
  const registration2 = await this.registerDeposit(
4569
4733
  chainId,
@@ -4738,6 +4902,39 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4738
4902
  strategy
4739
4903
  );
4740
4904
  }
4905
+ /**
4906
+ * Resume one specific parent Safe deposit without proposing another transfer.
4907
+ * Persist the reference supplied by sendDeposit's onSafeProposal callback.
4908
+ *
4909
+ * @group Deposits and withdrawals
4910
+ */
4911
+ async resumeNestedSafeDeposit(reference) {
4912
+ const { userAddress, chainId, childSafe, proposalHash, asset, amount } = reference;
4913
+ if (!isSupportedChain(chainId)) throw new Error("Unsupported deposit chain");
4914
+ if (!/^0x[0-9a-fA-F]{64}$/.test(proposalHash)) throw new Error("Invalid proposal hash");
4915
+ await this.authenticateUser();
4916
+ if (!this.isConnectedUser(userAddress) || this.sessionEoa && !isAddressEqual2(this.sessionEoa, userAddress)) {
4917
+ throw new Error("Deposit reference does not match the authenticated parent");
4918
+ }
4919
+ await this.hydrateSessionWallet();
4920
+ const resolved = await this.getSafeAddressFor(userAddress, chainId);
4921
+ if (!resolved || !isAddressEqual2(resolved, childSafe)) throw new Error("Deposit reference does not match the registered child");
4922
+ const symbol = resolveAssetSymbol(asset);
4923
+ if (!getAssetChainIds(symbol).includes(chainId) || BigInt(amount) <= 0n) throw new Error("Invalid deposit asset or amount");
4924
+ const config = getChainConfig(chainId, this.rpcUrls);
4925
+ const token = getDefaultTokenAddress(chainId, symbol);
4926
+ const txHash = await waitForExactSafeDepositExecution({
4927
+ parentSafe: userAddress,
4928
+ childSafe,
4929
+ chainId,
4930
+ tokenAddress: token,
4931
+ amount: BigInt(amount),
4932
+ proposalHash,
4933
+ publicClient: config.publicClient
4934
+ });
4935
+ const registration = await this.registerDeposit(chainId, txHash, amount, token);
4936
+ return { success: true, txHash, smartWallet: childSafe, amount, route: "direct", registration };
4937
+ }
4741
4938
  /**
4742
4939
  * Resolve a deposit without signing.
4743
4940
  *
@@ -4998,7 +5195,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4998
5195
  params.chainId,
4999
5196
  params.amount,
5000
5197
  route.asset,
5001
- params.strategy
5198
+ params.strategy,
5199
+ params.onSafeProposal
5002
5200
  );
5003
5201
  }
5004
5202
  if (route.kind === "wrap") {
@@ -5616,7 +5814,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5616
5814
  );
5617
5815
  } catch (logError) {
5618
5816
  throw new Error(
5619
- `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
5817
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}", "${tokenAddress}") to retry.`
5620
5818
  );
5621
5819
  }
5622
5820
  return registration.deposit;
@@ -5983,6 +6181,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5983
6181
  );
5984
6182
  }
5985
6183
  await this.authenticateUser();
6184
+ this.assertConnectedUser(userAddress);
5986
6185
  await this.assertAsyncRedemptionSlotFree(
5987
6186
  userAddress,
5988
6187
  chainId,
@@ -8508,9 +8707,11 @@ export {
8508
8707
  WS_ENDPOINT,
8509
8708
  WS_URLS,
8510
8709
  ZyfaiSDK,
8710
+ buildNestedSafeOnboardingStatus,
8511
8711
  buildV1ChainSessions,
8512
8712
  createBankrProvider,
8513
8713
  decodeUserOperationCalls,
8714
+ deriveNestedSafeOnboardingStep,
8514
8715
  getChainConfig,
8515
8716
  getDataApiBaseUrl,
8516
8717
  getDefaultTokenAddress,
@@ -8523,6 +8724,7 @@ export {
8523
8724
  isSupportedChain,
8524
8725
  parseUserOperationJson,
8525
8726
  parseV1ChainSessions,
8727
+ portfolioHasWithdrawableBalance,
8526
8728
  resolveDepositRoute,
8527
8729
  resolveRelaySlippageBps,
8528
8730
  serializeV1ChainSessions