@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.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.");
@@ -1679,12 +1688,13 @@ var deploySafeAccount = async (config) => {
1679
1688
  }
1680
1689
  console.log("strategy", strategy);
1681
1690
  const strategyBody = strategy ? { strategy } : {};
1682
- const prepareResponse = await httpClient.post(
1683
- `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1691
+ const prepareResponse = await postSafeDeployPrepare(
1692
+ httpClient,
1693
+ chainId,
1684
1694
  strategyBody
1685
1695
  );
1686
1696
  console.log("prepareResponse", prepareResponse);
1687
- if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1697
+ if (isSafeDeployPermissionsReady(prepareResponse)) {
1688
1698
  return {
1689
1699
  safeAddress: prepareResponse.safeAddress || "0x",
1690
1700
  txHash: "0x0",
@@ -1883,7 +1893,9 @@ async function signNestedOwnerSessionKey(config, sessions, allPublicClients, sig
1883
1893
 
1884
1894
  // src/utils/nested-safe-deposit.ts
1885
1895
  import {
1886
- getAddress as getAddress3
1896
+ getAddress as getAddress3,
1897
+ decodeEventLog,
1898
+ parseAbiItem
1887
1899
  } from "viem";
1888
1900
  var NESTED_SAFE_DEPOSIT_TIMEOUT_MS = 20 * 60 * 1e3;
1889
1901
  var NESTED_SAFE_DEPOSIT_POLL_MS = 1e4;
@@ -1925,35 +1937,6 @@ function sameAddress(left, right) {
1925
1937
  return false;
1926
1938
  }
1927
1939
  }
1928
- function transferMatches(transaction, params) {
1929
- if (!sameAddress(transaction.to, params.tokenAddress)) return false;
1930
- if (transaction.isSuccessful === false) return false;
1931
- const decoded = transaction.dataDecoded;
1932
- if (decoded?.method?.toLowerCase() !== "transfer") return false;
1933
- const parameters = decoded.parameters;
1934
- if (!parameters) return false;
1935
- const destination = parameters.find(
1936
- (p) => (p.name === "to" || p.name === "dst" || p.name === "_to") && p.type === "address"
1937
- );
1938
- if (!sameAddress(destination?.value, params.childSafe)) return false;
1939
- if (params.amount === void 0) return true;
1940
- const valueParam = parameters.find(
1941
- (p) => (p.name === "value" || p.name === "amount" || p.name === "_value" || p.name === "wad") && p.type.startsWith("uint")
1942
- );
1943
- if (!valueParam) return false;
1944
- try {
1945
- return BigInt(valueParam.value) === params.amount;
1946
- } catch {
1947
- return false;
1948
- }
1949
- }
1950
- function isWithinWindow(transaction, since) {
1951
- if (!since) return true;
1952
- const stamp = transaction.executionDate ?? transaction.submissionDate;
1953
- if (!stamp) return false;
1954
- const at = Date.parse(stamp);
1955
- return Number.isFinite(at) && at >= since.getTime();
1956
- }
1957
1940
  async function findSafeTransferByHash(params) {
1958
1941
  const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1959
1942
  const url = `https://api.safe.global/tx-service/${networkName}/api/v2/multisig-transactions/${params.safeTxHash}/`;
@@ -1972,54 +1955,101 @@ async function findSafeTransferByHash(params) {
1972
1955
  isExecuted: transaction.isExecuted === true && !!transaction.transactionHash
1973
1956
  };
1974
1957
  }
1975
- async function findSafeTransferProposal(params) {
1976
- const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1977
- const url = `https://api.safe.global/tx-service/${networkName}/api/v2/safes/${getAddress3(
1978
- params.parentSafe
1979
- )}/multisig-transactions/?ordering=-nonce`;
1980
- const response = await fetch(url);
1981
- if (!response.ok) return null;
1982
- const body = await response.json();
1983
- const match = (body.results ?? []).find(
1984
- (transaction) => !!transaction.safeTxHash && isWithinWindow(transaction, params.since) && transferMatches(transaction, {
1985
- childSafe: params.childSafe,
1986
- tokenAddress: params.tokenAddress,
1987
- amount: params.amount
1988
- })
1989
- );
1990
- if (!match) return null;
1991
- return {
1992
- safeTxHash: match.safeTxHash,
1993
- transactionHash: match.transactionHash ?? null,
1994
- isExecuted: match.isExecuted === true && !!match.transactionHash
1995
- };
1996
- }
1997
- async function waitForSafeTransferExecution(params) {
1998
- 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();
1999
1961
  const timeoutMs = params.timeoutMs ?? NESTED_SAFE_DEPOSIT_TIMEOUT_MS;
2000
1962
  const pollMs = params.pollMs ?? NESTED_SAFE_DEPOSIT_POLL_MS;
2001
- const started = Date.now();
2002
- do {
2003
- const proposal = params.safeTxHash ? await findSafeTransferByHash({
2004
- chainId: params.chainId,
2005
- safeTxHash: params.safeTxHash
2006
- }) : await findSafeTransferProposal({
2007
- parentSafe: params.parentSafe,
2008
- childSafe: params.childSafe,
2009
- chainId: params.chainId,
2010
- tokenAddress: params.tokenAddress,
2011
- amount: params.amount,
2012
- since: params.since
2013
- });
2014
- if (proposal?.isExecuted && proposal.transactionHash) {
2015
- 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;
2016
2006
  }
2017
- await new Promise((resolve) => setTimeout(resolve, pollMs));
2018
- } while (Date.now() - started < timeoutMs);
2019
- throw new Error(
2020
- `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)
2021
2035
  );
2022
2036
  }
2037
+ function deriveNestedSafeOnboardingStep(flags) {
2038
+ if (!flags.isNestedOwner) return "deploy";
2039
+ if (!flags.childRegistered || !flags.childDeployed || !flags.sessionActive) {
2040
+ return "deploy";
2041
+ }
2042
+ if (!flags.hasPortfolioBalance) return "deposit";
2043
+ if (flags.hasPortfolioBalance) return "withdraw";
2044
+ return "ready";
2045
+ }
2046
+ function buildNestedSafeOnboardingStatus(flags, child) {
2047
+ return {
2048
+ ...flags,
2049
+ child,
2050
+ suggestedStep: deriveNestedSafeOnboardingStep(flags)
2051
+ };
2052
+ }
2023
2053
 
2024
2054
  // src/utils/strategy.ts
2025
2055
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
@@ -3277,15 +3307,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3277
3307
  throw new Error(`Unsupported chain ID: ${chainId}`);
3278
3308
  }
3279
3309
  const resolvedAddress = await this.resolveConnectAddress(account);
3280
- if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && isAddressEqual2(resolvedAddress, this.sessionEoa)) {
3310
+ if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && isAddressEqual2(resolvedAddress, this.sessionEoa) && this.currentChainId === chainId && (account === this.currentProvider || account === this.walletClient)) {
3281
3311
  this.currentChainId = chainId;
3282
3312
  return resolvedAddress;
3283
3313
  }
3284
3314
  if (this.connectAccountInFlight) {
3285
- return this.connectAccountInFlight;
3315
+ throw new Error("Wallet connection already in progress; retry after it completes");
3286
3316
  }
3287
3317
  const connect = (async () => {
3288
3318
  this.authenticatedUserId = null;
3319
+ this.hasActiveSessionKey = false;
3320
+ this.signer = null;
3289
3321
  this.isPredeployed = false;
3290
3322
  this.predeployedResolved = false;
3291
3323
  this.connectedSmartWallet = null;
@@ -3335,6 +3367,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3335
3367
  transport: provider.transport
3336
3368
  });
3337
3369
  connectedAddress = getAddress4(resolvedAddress2);
3370
+ if (provider.chain?.id !== void 0 && provider.chain.id !== chainId) {
3371
+ throw new Error(`Wallet client chain ${provider.chain.id} does not match requested chain ${chainId}`);
3372
+ }
3338
3373
  this.currentProvider = null;
3339
3374
  this.currentChainId = chainId;
3340
3375
  } else if (provider.request) {
@@ -3358,6 +3393,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3358
3393
  );
3359
3394
  }
3360
3395
  connectedAddress = getAddress4(accountAddress);
3396
+ if (!isAddressEqual2(connectedAddress, resolvedAddress)) {
3397
+ throw new Error("Wallet account changed during connection; reconnect");
3398
+ }
3399
+ const providerChain = await eip1193.request({ method: "eth_chainId" });
3400
+ if (Number(providerChain) !== chainId) {
3401
+ throw new Error(`Wallet is on chain ${providerChain}; switch to chain ${chainId} before connecting`);
3402
+ }
3361
3403
  this.walletClient = createWalletClient({
3362
3404
  account: connectedAddress,
3363
3405
  chain: chainConfig.chain,
@@ -3446,6 +3488,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3446
3488
  * True when userAddress is the signer, wallet client, or agent session EOA.
3447
3489
  * @private
3448
3490
  */
3491
+ assertConnectedUser(userAddress) {
3492
+ if (!this.isConnectedUser(userAddress) || this.sessionEoa && !isAddressEqual2(getAddress4(userAddress), this.sessionEoa)) {
3493
+ throw new Error("userAddress does not match the authenticated wallet");
3494
+ }
3495
+ }
3449
3496
  isConnectedUser(userAddress) {
3450
3497
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3451
3498
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
@@ -3455,6 +3502,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3455
3502
  * (install or emissary enable), then register with chainId only.
3456
3503
  * @private
3457
3504
  */
3505
+ /**
3506
+ * Read-only probe for nested owners: on-chain session permissions on `chainId`.
3507
+ * Mirrors the early-return branch in {@link deploySafeAccount} without signing.
3508
+ * @private
3509
+ */
3510
+ async isNestedChainSessionPermissionsReady(chainId) {
3511
+ const prepare = await postSafeDeployPrepare(this.httpClient, chainId);
3512
+ return isSafeDeployPermissionsReady(prepare);
3513
+ }
3458
3514
  async registerNestedIntentSessionKey(userAddress, chainId, strategy) {
3459
3515
  if (!this.authenticatedUserId) {
3460
3516
  throw new Error(
@@ -3471,10 +3527,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3471
3527
  httpClient: this.httpClient,
3472
3528
  strategy
3473
3529
  });
3530
+ if (this.hasActiveSessionKey) {
3531
+ return {
3532
+ success: true,
3533
+ userId: this.authenticatedUserId,
3534
+ message: "Intent session permissions ready on requested chain",
3535
+ alreadyActive: true
3536
+ };
3537
+ }
3474
3538
  const activation = await this.httpClient.post(
3475
3539
  ENDPOINTS.SESSION_KEYS_ADD,
3476
3540
  { chainId }
3477
3541
  );
3542
+ if (!activation?.isActive || !activation?.isEnabled) {
3543
+ throw new Error("Intent session is not active and enabled on the requested chain");
3544
+ }
3478
3545
  this.hasActiveSessionKey = true;
3479
3546
  return {
3480
3547
  success: true,
@@ -3520,7 +3587,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3520
3587
  const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3521
3588
  const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3522
3589
  if (!childDeployed) {
3523
- await this.deploySafe(userAddress, chainId, strategy, true);
3590
+ const deployment = await this.deploySafe(userAddress, chainId, strategy, false);
3591
+ if (!deployment.success) throw new Error("Nested Safe deployment failed");
3592
+ await this.createSessionKey(userAddress, chainId);
3524
3593
  return;
3525
3594
  }
3526
3595
  console.info(
@@ -3645,6 +3714,84 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3645
3714
  isOwner
3646
3715
  };
3647
3716
  }
3717
+ /**
3718
+ * Nested-parent onboarding snapshot for a connected parent Safe address.
3719
+ *
3720
+ * @group Deposits and withdrawals
3721
+ *
3722
+ * @remarks Combines child resolution ({@link ZyfaiSDK.getSmartWalletAddress}),
3723
+ * session state (account registration plus per-chain safe-deploy readiness),
3724
+ * and portfolio balances
3725
+ * ({@link ZyfaiSDK.getPortfolio}). Wallet connect remains integrator-side.
3726
+ *
3727
+ * @param userAddress - Parent Safe address from {@link ZyfaiSDK.connectAccount}
3728
+ * @param chainId - Target chain (deployment and session are per chain)
3729
+ */
3730
+ async getNestedSafeOnboardingStatus(userAddress, chainId) {
3731
+ if (!userAddress) {
3732
+ throw new Error("User address is required");
3733
+ }
3734
+ if (!isSupportedChain(chainId)) {
3735
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3736
+ }
3737
+ await this.authenticateUser();
3738
+ this.assertConnectedUser(userAddress);
3739
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3740
+ const isNestedOwner = await getAccountType(userAddress, chainConfig.publicClient) === "Safe";
3741
+ let child = null;
3742
+ let childRegistered = false;
3743
+ let childDeployed = false;
3744
+ try {
3745
+ child = await this.getSmartWalletAddress(userAddress, chainId);
3746
+ childRegistered = true;
3747
+ childDeployed = child.isDeployed;
3748
+ } catch (error) {
3749
+ const message = error.message;
3750
+ if (message !== "NESTED_CHILD_UNREGISTERED") {
3751
+ throw error;
3752
+ }
3753
+ }
3754
+ let accountSessionRegistered = false;
3755
+ try {
3756
+ const details = await this.getUserDetails("USDC");
3757
+ accountSessionRegistered = Boolean(details.hasActiveSessionKey);
3758
+ } catch {
3759
+ }
3760
+ let chainSessionReady = false;
3761
+ if (isNestedOwner && childDeployed) {
3762
+ try {
3763
+ chainSessionReady = await this.isNestedChainSessionPermissionsReady(chainId);
3764
+ } catch {
3765
+ }
3766
+ }
3767
+ const sessionActive = chainSessionReady && accountSessionRegistered;
3768
+ let hasPortfolioBalance = false;
3769
+ if (childRegistered) {
3770
+ try {
3771
+ const portfolio = await this.getPortfolio(userAddress);
3772
+ hasPortfolioBalance = portfolioHasWithdrawableBalance(
3773
+ portfolio.portfolio
3774
+ );
3775
+ } catch {
3776
+ }
3777
+ }
3778
+ const status = buildNestedSafeOnboardingStatus(
3779
+ {
3780
+ isNestedOwner,
3781
+ childRegistered,
3782
+ childDeployed,
3783
+ sessionActive: sessionActive && childDeployed && childRegistered,
3784
+ hasPortfolioBalance
3785
+ },
3786
+ child
3787
+ );
3788
+ return {
3789
+ success: true,
3790
+ userAddress,
3791
+ chainId,
3792
+ status
3793
+ };
3794
+ }
3648
3795
  /**
3649
3796
  * Deploy Safe Smart Wallet for a user
3650
3797
  *
@@ -3660,7 +3807,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3660
3807
  * @param userAddress - User's EOA address (the connected EOA, not the smart wallet address)
3661
3808
  * @param chainId - Target chain ID
3662
3809
  * @param strategy - Optional strategy selection: "conservative" (default), "aggressive" or "yieldmaxxing"
3663
- * @param createSessionKey - If true, automatically creates a session key after deployment (default: false)
3810
+ * @param createSessionKey - For EOA owners, if true, creates a session key after deployment (default: false). Nested Safe owners always register the session after deploy.
3664
3811
  * @returns Deployment response with Safe address and transaction hash
3665
3812
  *
3666
3813
  * @example
@@ -3682,6 +3829,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3682
3829
  throw new Error(`Unsupported chain ID: ${chainId}`);
3683
3830
  }
3684
3831
  await this.authenticateUser();
3832
+ this.assertConnectedUser(userAddress);
3685
3833
  this.warnPredeployedOnboardingMethod("deploySafe");
3686
3834
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
3687
3835
  const predeployedAddress = await this.getSafeAddressFor(
@@ -3717,6 +3865,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3717
3865
  chainConfig.publicClient
3718
3866
  );
3719
3867
  const nestedSafeOwner = ownerAccountType === "Safe";
3868
+ const registerSession = nestedSafeOwner || Boolean(createSessionKey);
3720
3869
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3721
3870
  if (!safeAddress && !nestedSafeOwner) {
3722
3871
  throw new Error(
@@ -3741,7 +3890,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3741
3890
  }
3742
3891
  await this.updateUserProtocols(strategy);
3743
3892
  let sessionKeyCreated2 = false;
3744
- if (createSessionKey) {
3893
+ if (registerSession) {
3745
3894
  try {
3746
3895
  await this.createSessionKey(userAddress, chainId);
3747
3896
  sessionKeyCreated2 = true;
@@ -3801,7 +3950,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3801
3950
  });
3802
3951
  }
3803
3952
  let sessionKeyCreated = false;
3804
- if (createSessionKey) {
3953
+ if (registerSession) {
3805
3954
  try {
3806
3955
  await this.createSessionKey(userAddress, chainId);
3807
3956
  sessionKeyCreated = true;
@@ -3854,6 +4003,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3854
4003
  async createSessionKey(userAddress, chainId) {
3855
4004
  try {
3856
4005
  await this.authenticateUser();
4006
+ this.assertConnectedUser(userAddress);
3857
4007
  this.warnPredeployedOnboardingMethod("createSessionKey");
3858
4008
  if (!this.authenticatedUserId) {
3859
4009
  throw new Error(
@@ -3868,6 +4018,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3868
4018
  alreadyActive: true
3869
4019
  };
3870
4020
  }
4021
+ const nestedChain = getChainConfig(chainId, this.rpcUrls);
4022
+ if (await getAccountType(userAddress, nestedChain.publicClient) === "Safe") {
4023
+ await assertParentSafeDeployedOnChain(userAddress, nestedChain.publicClient, chainId);
4024
+ return this.registerNestedIntentSessionKey(userAddress, chainId);
4025
+ }
3871
4026
  if (this.hasActiveSessionKey) {
3872
4027
  return {
3873
4028
  success: true,
@@ -3899,12 +4054,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3899
4054
  userAddress,
3900
4055
  chainConfig.publicClient
3901
4056
  );
3902
- if (accountType === "Safe") {
3903
- return this.registerNestedIntentSessionKey(
3904
- userAddress,
3905
- chainId,
3906
- void 0
3907
- );
4057
+ if (accountType !== "EOA") {
4058
+ throw new Error("Unable to establish EOA session account type");
3908
4059
  }
3909
4060
  const signingParams = {
3910
4061
  permitGenericPolicy,
@@ -4402,10 +4553,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4402
4553
  * await sdk.waitForDepositPosition(sent.registration.id, 8453);
4403
4554
  * ```
4404
4555
  */
4405
- async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
4406
- return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true);
4556
+ async sendDirectDeposit(userAddress, chainId, amount, asset, strategy, onSafeProposal) {
4557
+ return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true, onSafeProposal);
4407
4558
  }
4408
- async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit) {
4559
+ async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit, onSafeProposal) {
4409
4560
  try {
4410
4561
  if (!userAddress) {
4411
4562
  throw new Error("User address is required");
@@ -4457,11 +4608,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4457
4608
  } else {
4458
4609
  await this.authenticateUser();
4459
4610
  }
4460
- await this.hydrateSessionWallet();
4461
- const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4462
- if (!safeAddress) {
4463
- throw new Error("Smart wallet address is not available");
4611
+ this.assertConnectedUser(userAddress);
4612
+ if (!this.signer && walletClient.chain?.id !== chainId) {
4613
+ throw new Error("Switch the connected wallet to the deposit chain and reconnect");
4464
4614
  }
4615
+ await this.hydrateSessionWallet();
4616
+ let safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4465
4617
  const amountBigInt = BigInt(amount);
4466
4618
  const ownerType = await getAccountType(
4467
4619
  userAddress,
@@ -4472,6 +4624,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4472
4624
  `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.`
4473
4625
  );
4474
4626
  }
4627
+ let nestedOnboarded = false;
4628
+ if (!safeAddress && ownerType === "Safe" && !this.isPredeployed) {
4629
+ await this.ensureNestedOwnerReadyForDeposit(userAddress, chainId, strategy);
4630
+ safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4631
+ nestedOnboarded = true;
4632
+ }
4633
+ if (!safeAddress) {
4634
+ throw new Error("Smart wallet address is not available");
4635
+ }
4475
4636
  const [isDeployed, currentSafeBalance] = await Promise.all([
4476
4637
  isSafeDeployed(safeAddress, chainConfig.publicClient),
4477
4638
  minRequired !== void 0 ? chainConfig.publicClient.readContract({
@@ -4483,7 +4644,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4483
4644
  this.prepareFirstDeposit(strategy)
4484
4645
  ]).then(([deployed, balance]) => [deployed, balance]);
4485
4646
  if (!isDeployed) {
4486
- if (ownerType === "Safe" && !this.isPredeployed) {
4647
+ if (ownerType === "Safe" && !this.isPredeployed && !nestedOnboarded) {
4487
4648
  await assertParentSafeDeployedOnChain(
4488
4649
  userAddress,
4489
4650
  chainConfig.publicClient,
@@ -4517,7 +4678,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4517
4678
  );
4518
4679
  }
4519
4680
  }
4520
- if (ownerType === "Safe" && isDeployed) {
4681
+ if (ownerType === "Safe" && isDeployed && !nestedOnboarded) {
4521
4682
  await assertParentSafeDeployedOnChain(
4522
4683
  userAddress,
4523
4684
  chainConfig.publicClient,
@@ -4540,35 +4701,35 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4540
4701
  if (sponsored) return sponsored;
4541
4702
  }
4542
4703
  if (ownerType === "Safe") {
4543
- const since = new Date(Date.now() - NESTED_SAFE_RESUME_WINDOW_MS);
4544
- const inFlight = await findSafeTransferProposal({
4545
- parentSafe: userAddress,
4546
- childSafe: safeAddress,
4547
- chainId,
4548
- tokenAddress: token,
4549
- amount: amountBigInt,
4550
- since
4704
+ const proposed = await walletClient.writeContract({
4705
+ address: token,
4706
+ abi: erc20TransferWriteAbi(assetSymbol),
4707
+ functionName: "transfer",
4708
+ args: [safeAddress, amountBigInt],
4709
+ chain: chainConfig.chain,
4710
+ account: walletClient.account
4551
4711
  });
4552
- let safeTxHash = inFlight?.safeTxHash;
4553
- if (!inFlight) {
4554
- const proposed = await walletClient.writeContract({
4555
- address: token,
4556
- abi: erc20TransferWriteAbi(assetSymbol),
4557
- functionName: "transfer",
4558
- args: [safeAddress, amountBigInt],
4559
- chain: chainConfig.chain,
4560
- account: walletClient.account
4561
- });
4562
- safeTxHash = (await findSafeTransferByHash({ chainId, safeTxHash: proposed }))?.safeTxHash;
4712
+ const reference = {
4713
+ userAddress: getAddress4(userAddress),
4714
+ chainId,
4715
+ amount,
4716
+ asset: assetSymbol,
4717
+ childSafe: safeAddress,
4718
+ proposalHash: proposed
4719
+ };
4720
+ try {
4721
+ await onSafeProposal?.(reference);
4722
+ } catch (error) {
4723
+ throw new Error(`Safe proposal ${proposed} was submitted; persist its reference and resumeNestedSafeDeposit instead of sending again: ${thrownMessage(error)}`);
4563
4724
  }
4564
- const executedHash = inFlight?.isExecuted && inFlight.transactionHash ? inFlight.transactionHash : await waitForSafeTransferExecution({
4565
- parentSafe: userAddress,
4725
+ const executedHash = await waitForExactSafeDepositExecution({
4726
+ parentSafe: reference.userAddress,
4566
4727
  childSafe: safeAddress,
4567
4728
  chainId,
4568
4729
  tokenAddress: token,
4569
4730
  amount: amountBigInt,
4570
- safeTxHash,
4571
- since
4731
+ proposalHash: proposed,
4732
+ publicClient: chainConfig.publicClient
4572
4733
  });
4573
4734
  const registration2 = await this.registerDeposit(
4574
4735
  chainId,
@@ -4743,6 +4904,39 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4743
4904
  strategy
4744
4905
  );
4745
4906
  }
4907
+ /**
4908
+ * Resume one specific parent Safe deposit without proposing another transfer.
4909
+ * Persist the reference supplied by sendDeposit's onSafeProposal callback.
4910
+ *
4911
+ * @group Deposits and withdrawals
4912
+ */
4913
+ async resumeNestedSafeDeposit(reference) {
4914
+ const { userAddress, chainId, childSafe, proposalHash, asset, amount } = reference;
4915
+ if (!isSupportedChain(chainId)) throw new Error("Unsupported deposit chain");
4916
+ if (!/^0x[0-9a-fA-F]{64}$/.test(proposalHash)) throw new Error("Invalid proposal hash");
4917
+ await this.authenticateUser();
4918
+ if (!this.isConnectedUser(userAddress) || this.sessionEoa && !isAddressEqual2(this.sessionEoa, userAddress)) {
4919
+ throw new Error("Deposit reference does not match the authenticated parent");
4920
+ }
4921
+ await this.hydrateSessionWallet();
4922
+ const resolved = await this.getSafeAddressFor(userAddress, chainId);
4923
+ if (!resolved || !isAddressEqual2(resolved, childSafe)) throw new Error("Deposit reference does not match the registered child");
4924
+ const symbol = resolveAssetSymbol(asset);
4925
+ if (!getAssetChainIds(symbol).includes(chainId) || BigInt(amount) <= 0n) throw new Error("Invalid deposit asset or amount");
4926
+ const config = getChainConfig(chainId, this.rpcUrls);
4927
+ const token = getDefaultTokenAddress(chainId, symbol);
4928
+ const txHash = await waitForExactSafeDepositExecution({
4929
+ parentSafe: userAddress,
4930
+ childSafe,
4931
+ chainId,
4932
+ tokenAddress: token,
4933
+ amount: BigInt(amount),
4934
+ proposalHash,
4935
+ publicClient: config.publicClient
4936
+ });
4937
+ const registration = await this.registerDeposit(chainId, txHash, amount, token);
4938
+ return { success: true, txHash, smartWallet: childSafe, amount, route: "direct", registration };
4939
+ }
4746
4940
  /**
4747
4941
  * Resolve a deposit without signing.
4748
4942
  *
@@ -5003,7 +5197,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5003
5197
  params.chainId,
5004
5198
  params.amount,
5005
5199
  route.asset,
5006
- params.strategy
5200
+ params.strategy,
5201
+ params.onSafeProposal
5007
5202
  );
5008
5203
  }
5009
5204
  if (route.kind === "wrap") {
@@ -5621,7 +5816,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5621
5816
  );
5622
5817
  } catch (logError) {
5623
5818
  throw new Error(
5624
- `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
5819
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}", "${tokenAddress}") to retry.`
5625
5820
  );
5626
5821
  }
5627
5822
  return registration.deposit;
@@ -5988,6 +6183,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5988
6183
  );
5989
6184
  }
5990
6185
  await this.authenticateUser();
6186
+ this.assertConnectedUser(userAddress);
5991
6187
  await this.assertAsyncRedemptionSlotFree(
5992
6188
  userAddress,
5993
6189
  chainId,
@@ -8513,9 +8709,11 @@ export {
8513
8709
  WS_ENDPOINT,
8514
8710
  WS_URLS,
8515
8711
  ZyfaiSDK,
8712
+ buildNestedSafeOnboardingStatus,
8516
8713
  buildV1ChainSessions,
8517
8714
  createBankrProvider,
8518
8715
  decodeUserOperationCalls,
8716
+ deriveNestedSafeOnboardingStep,
8519
8717
  getChainConfig,
8520
8718
  getDataApiBaseUrl,
8521
8719
  getDefaultTokenAddress,
@@ -8528,6 +8726,7 @@ export {
8528
8726
  isSupportedChain,
8529
8727
  parseUserOperationJson,
8530
8728
  parseV1ChainSessions,
8729
+ portfolioHasWithdrawableBalance,
8531
8730
  resolveDepositRoute,
8532
8731
  resolveRelaySlippageBps,
8533
8732
  serializeV1ChainSessions