@zyfai/sdk 1.9.2 → 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.");
@@ -1725,12 +1737,13 @@ var deploySafeAccount = async (config) => {
1725
1737
  }
1726
1738
  console.log("strategy", strategy);
1727
1739
  const strategyBody = strategy ? { strategy } : {};
1728
- const prepareResponse = await httpClient.post(
1729
- `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1740
+ const prepareResponse = await postSafeDeployPrepare(
1741
+ httpClient,
1742
+ chainId,
1730
1743
  strategyBody
1731
1744
  );
1732
1745
  console.log("prepareResponse", prepareResponse);
1733
- if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1746
+ if (isSafeDeployPermissionsReady(prepareResponse)) {
1734
1747
  return {
1735
1748
  safeAddress: prepareResponse.safeAddress || "0x",
1736
1749
  txHash: "0x0",
@@ -1969,35 +1982,6 @@ function sameAddress(left, right) {
1969
1982
  return false;
1970
1983
  }
1971
1984
  }
1972
- function transferMatches(transaction, params) {
1973
- if (!sameAddress(transaction.to, params.tokenAddress)) return false;
1974
- if (transaction.isSuccessful === false) return false;
1975
- const decoded = transaction.dataDecoded;
1976
- if (decoded?.method?.toLowerCase() !== "transfer") return false;
1977
- const parameters = decoded.parameters;
1978
- if (!parameters) return false;
1979
- const destination = parameters.find(
1980
- (p) => (p.name === "to" || p.name === "dst" || p.name === "_to") && p.type === "address"
1981
- );
1982
- if (!sameAddress(destination?.value, params.childSafe)) return false;
1983
- if (params.amount === void 0) return true;
1984
- const valueParam = parameters.find(
1985
- (p) => (p.name === "value" || p.name === "amount" || p.name === "_value" || p.name === "wad") && p.type.startsWith("uint")
1986
- );
1987
- if (!valueParam) return false;
1988
- try {
1989
- return BigInt(valueParam.value) === params.amount;
1990
- } catch {
1991
- return false;
1992
- }
1993
- }
1994
- function isWithinWindow(transaction, since) {
1995
- if (!since) return true;
1996
- const stamp = transaction.executionDate ?? transaction.submissionDate;
1997
- if (!stamp) return false;
1998
- const at = Date.parse(stamp);
1999
- return Number.isFinite(at) && at >= since.getTime();
2000
- }
2001
1985
  async function findSafeTransferByHash(params) {
2002
1986
  const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
2003
1987
  const url = `https://api.safe.global/tx-service/${networkName}/api/v2/multisig-transactions/${params.safeTxHash}/`;
@@ -2016,54 +2000,100 @@ async function findSafeTransferByHash(params) {
2016
2000
  isExecuted: transaction.isExecuted === true && !!transaction.transactionHash
2017
2001
  };
2018
2002
  }
2019
- async function findSafeTransferProposal(params) {
2020
- const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
2021
- const url = `https://api.safe.global/tx-service/${networkName}/api/v2/safes/${(0, import_viem7.getAddress)(
2022
- params.parentSafe
2023
- )}/multisig-transactions/?ordering=-nonce`;
2024
- const response = await fetch(url);
2025
- if (!response.ok) return null;
2026
- const body = await response.json();
2027
- const match = (body.results ?? []).find(
2028
- (transaction) => !!transaction.safeTxHash && isWithinWindow(transaction, params.since) && transferMatches(transaction, {
2029
- childSafe: params.childSafe,
2030
- tokenAddress: params.tokenAddress,
2031
- amount: params.amount
2032
- })
2033
- );
2034
- if (!match) return null;
2035
- return {
2036
- safeTxHash: match.safeTxHash,
2037
- transactionHash: match.transactionHash ?? null,
2038
- isExecuted: match.isExecuted === true && !!match.transactionHash
2039
- };
2040
- }
2041
- async function waitForSafeTransferExecution(params) {
2042
- safeTxServiceNetworkNameOrThrow(params.chainId);
2003
+ var TRANSFER_EVENT = (0, import_viem7.parseAbiItem)("event Transfer(address indexed from, address indexed to, uint256 value)");
2004
+ async function waitForExactSafeDepositExecution(params) {
2005
+ const started = Date.now();
2043
2006
  const timeoutMs = params.timeoutMs ?? NESTED_SAFE_DEPOSIT_TIMEOUT_MS;
2044
2007
  const pollMs = params.pollMs ?? NESTED_SAFE_DEPOSIT_POLL_MS;
2045
- const started = Date.now();
2046
- do {
2047
- const proposal = params.safeTxHash ? await findSafeTransferByHash({
2048
- chainId: params.chainId,
2049
- safeTxHash: params.safeTxHash
2050
- }) : await findSafeTransferProposal({
2051
- parentSafe: params.parentSafe,
2052
- childSafe: params.childSafe,
2053
- chainId: params.chainId,
2054
- tokenAddress: params.tokenAddress,
2055
- amount: params.amount,
2056
- since: params.since
2057
- });
2058
- if (proposal?.isExecuted && proposal.transactionHash) {
2059
- return proposal.transactionHash;
2008
+ let hash = params.proposalHash;
2009
+ try {
2010
+ do {
2011
+ const receipt = await params.publicClient.getTransactionReceipt({ hash }).catch(() => void 0);
2012
+ if (receipt) {
2013
+ if (receipt.status !== "success") throw new Error("Safe transfer reverted");
2014
+ const matches = receipt.logs.some((log) => {
2015
+ if (!sameAddress(log.address, params.tokenAddress)) return false;
2016
+ try {
2017
+ const decoded = (0, import_viem7.decodeEventLog)({ abi: [TRANSFER_EVENT], data: log.data, topics: log.topics });
2018
+ return sameAddress(decoded.args.from, params.parentSafe) && sameAddress(decoded.args.to, params.childSafe) && decoded.args.value === params.amount;
2019
+ } catch {
2020
+ return false;
2021
+ }
2022
+ });
2023
+ if (!matches) throw new Error("Executed transaction does not contain the expected parent-to-child transfer");
2024
+ return hash;
2025
+ }
2026
+ if (safeTxServiceNetworkName(params.chainId) && hash === params.proposalHash) {
2027
+ const proposal = await findSafeTransferByHash({ chainId: params.chainId, safeTxHash: params.proposalHash });
2028
+ if (proposal?.isExecuted && proposal.transactionHash) {
2029
+ hash = proposal.transactionHash;
2030
+ continue;
2031
+ }
2032
+ }
2033
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
2034
+ } while (Date.now() - started < timeoutMs);
2035
+ throw new Error("Timed out waiting for Safe transfer execution");
2036
+ } catch (error) {
2037
+ throw new Error(`Safe deposit proposal ${params.proposalHash}: ${error.message}. Resume this exact proposal with resumeNestedSafeDeposit; do not send another transfer.`);
2038
+ }
2039
+ }
2040
+
2041
+ // src/utils/nested-safe-onboarding.ts
2042
+ function positiveAmount(value) {
2043
+ if (!value) return false;
2044
+ const trimmed = value.trim();
2045
+ if (!trimmed || trimmed === "0" || trimmed === "0x" || trimmed === "0x0") {
2046
+ return false;
2047
+ }
2048
+ try {
2049
+ if (trimmed.startsWith("0x") || trimmed.startsWith("0X")) {
2050
+ return BigInt(trimmed) > 0n;
2060
2051
  }
2061
- await new Promise((resolve) => setTimeout(resolve, pollMs));
2062
- } while (Date.now() - started < timeoutMs);
2063
- throw new Error(
2064
- `Timed out waiting for Safe transfer from parent ${params.parentSafe} to child ${params.childSafe} on chain ${params.chainId} for token ${params.tokenAddress} amount ${params.amount.toString()}${params.safeTxHash ? ` (safeTxHash ${params.safeTxHash})` : ""}. Call sendDeposit again once co-signers have executed the proposal; it resumes that transfer instead of proposing another.`
2052
+ if (/^\d+$/.test(trimmed)) return BigInt(trimmed) > 0n;
2053
+ const numeric = Number(trimmed);
2054
+ return Number.isFinite(numeric) && numeric > 0;
2055
+ } catch {
2056
+ return false;
2057
+ }
2058
+ }
2059
+ function portfolioHasWithdrawableBalance(portfolio) {
2060
+ if (!portfolio) return false;
2061
+ if (portfolio.hasBalance) return true;
2062
+ const buckets = [
2063
+ ...Object.values(portfolio.portfolioByAssetType ?? {}),
2064
+ ...Object.values(portfolio.portfolioByChain ?? {}).flatMap(
2065
+ (byAsset) => Object.values(byAsset)
2066
+ )
2067
+ ];
2068
+ if (buckets.some(
2069
+ (entry) => positiveAmount(entry.balance) || positiveAmount(entry.balanceWithFee)
2070
+ )) {
2071
+ return true;
2072
+ }
2073
+ if ((portfolio.positions ?? []).some(
2074
+ (slot) => positiveAmount(slot.underlyingAmountWithFee) || positiveAmount(slot.underlyingAmount) || positiveAmount(slot.amount)
2075
+ )) {
2076
+ return true;
2077
+ }
2078
+ return (portfolio.staleBalances ?? []).some(
2079
+ (stale) => positiveAmount(stale.balance)
2065
2080
  );
2066
2081
  }
2082
+ function deriveNestedSafeOnboardingStep(flags) {
2083
+ if (!flags.isNestedOwner) return "deploy";
2084
+ if (!flags.childRegistered || !flags.childDeployed) 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
+ }
2067
2097
 
2068
2098
  // src/utils/strategy.ts
2069
2099
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
@@ -3321,15 +3351,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3321
3351
  throw new Error(`Unsupported chain ID: ${chainId}`);
3322
3352
  }
3323
3353
  const resolvedAddress = await this.resolveConnectAddress(account);
3324
- 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)) {
3325
3355
  this.currentChainId = chainId;
3326
3356
  return resolvedAddress;
3327
3357
  }
3328
3358
  if (this.connectAccountInFlight) {
3329
- return this.connectAccountInFlight;
3359
+ throw new Error("Wallet connection already in progress; retry after it completes");
3330
3360
  }
3331
3361
  const connect = (async () => {
3332
3362
  this.authenticatedUserId = null;
3363
+ this.hasActiveSessionKey = false;
3364
+ this.signer = null;
3333
3365
  this.isPredeployed = false;
3334
3366
  this.predeployedResolved = false;
3335
3367
  this.connectedSmartWallet = null;
@@ -3379,6 +3411,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3379
3411
  transport: provider.transport
3380
3412
  });
3381
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
+ }
3382
3417
  this.currentProvider = null;
3383
3418
  this.currentChainId = chainId;
3384
3419
  } else if (provider.request) {
@@ -3402,6 +3437,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3402
3437
  );
3403
3438
  }
3404
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
+ }
3405
3447
  this.walletClient = (0, import_viem8.createWalletClient)({
3406
3448
  account: connectedAddress,
3407
3449
  chain: chainConfig.chain,
@@ -3490,6 +3532,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3490
3532
  * True when userAddress is the signer, wallet client, or agent session EOA.
3491
3533
  * @private
3492
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
+ }
3493
3540
  isConnectedUser(userAddress) {
3494
3541
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3495
3542
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
@@ -3499,6 +3546,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3499
3546
  * (install or emissary enable), then register with chainId only.
3500
3547
  * @private
3501
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
+ }
3502
3558
  async registerNestedIntentSessionKey(userAddress, chainId, strategy) {
3503
3559
  if (!this.authenticatedUserId) {
3504
3560
  throw new Error(
@@ -3515,10 +3571,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3515
3571
  httpClient: this.httpClient,
3516
3572
  strategy
3517
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
+ }
3518
3582
  const activation = await this.httpClient.post(
3519
3583
  ENDPOINTS.SESSION_KEYS_ADD,
3520
3584
  { chainId }
3521
3585
  );
3586
+ if (!activation?.isActive || !activation?.isEnabled) {
3587
+ throw new Error("Intent session is not active and enabled on the requested chain");
3588
+ }
3522
3589
  this.hasActiveSessionKey = true;
3523
3590
  return {
3524
3591
  success: true,
@@ -3564,7 +3631,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3564
3631
  const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3565
3632
  const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3566
3633
  if (!childDeployed) {
3567
- 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);
3568
3637
  return;
3569
3638
  }
3570
3639
  console.info(
@@ -3689,6 +3758,84 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3689
3758
  isOwner
3690
3759
  };
3691
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
+ }
3692
3839
  /**
3693
3840
  * Deploy Safe Smart Wallet for a user
3694
3841
  *
@@ -3726,6 +3873,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3726
3873
  throw new Error(`Unsupported chain ID: ${chainId}`);
3727
3874
  }
3728
3875
  await this.authenticateUser();
3876
+ this.assertConnectedUser(userAddress);
3729
3877
  this.warnPredeployedOnboardingMethod("deploySafe");
3730
3878
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
3731
3879
  const predeployedAddress = await this.getSafeAddressFor(
@@ -3898,6 +4046,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3898
4046
  async createSessionKey(userAddress, chainId) {
3899
4047
  try {
3900
4048
  await this.authenticateUser();
4049
+ this.assertConnectedUser(userAddress);
3901
4050
  this.warnPredeployedOnboardingMethod("createSessionKey");
3902
4051
  if (!this.authenticatedUserId) {
3903
4052
  throw new Error(
@@ -3912,6 +4061,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3912
4061
  alreadyActive: true
3913
4062
  };
3914
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
+ }
3915
4069
  if (this.hasActiveSessionKey) {
3916
4070
  return {
3917
4071
  success: true,
@@ -3943,12 +4097,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3943
4097
  userAddress,
3944
4098
  chainConfig.publicClient
3945
4099
  );
3946
- if (accountType === "Safe") {
3947
- return this.registerNestedIntentSessionKey(
3948
- userAddress,
3949
- chainId,
3950
- void 0
3951
- );
4100
+ if (accountType !== "EOA") {
4101
+ throw new Error("Unable to establish EOA session account type");
3952
4102
  }
3953
4103
  const signingParams = {
3954
4104
  permitGenericPolicy,
@@ -4446,10 +4596,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4446
4596
  * await sdk.waitForDepositPosition(sent.registration.id, 8453);
4447
4597
  * ```
4448
4598
  */
4449
- async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
4450
- 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);
4451
4601
  }
4452
- async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit) {
4602
+ async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit, onSafeProposal) {
4453
4603
  try {
4454
4604
  if (!userAddress) {
4455
4605
  throw new Error("User address is required");
@@ -4501,11 +4651,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4501
4651
  } else {
4502
4652
  await this.authenticateUser();
4503
4653
  }
4504
- await this.hydrateSessionWallet();
4505
- const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4506
- if (!safeAddress) {
4507
- throw new Error("Smart wallet address is not available");
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");
4508
4657
  }
4658
+ await this.hydrateSessionWallet();
4659
+ let safeAddress = await this.getSafeAddressFor(userAddress, chainId);
4509
4660
  const amountBigInt = BigInt(amount);
4510
4661
  const ownerType = await getAccountType(
4511
4662
  userAddress,
@@ -4516,6 +4667,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4516
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.`
4517
4668
  );
4518
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
+ }
4519
4679
  const [isDeployed, currentSafeBalance] = await Promise.all([
4520
4680
  isSafeDeployed(safeAddress, chainConfig.publicClient),
4521
4681
  minRequired !== void 0 ? chainConfig.publicClient.readContract({
@@ -4527,7 +4687,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4527
4687
  this.prepareFirstDeposit(strategy)
4528
4688
  ]).then(([deployed, balance]) => [deployed, balance]);
4529
4689
  if (!isDeployed) {
4530
- if (ownerType === "Safe" && !this.isPredeployed) {
4690
+ if (ownerType === "Safe" && !this.isPredeployed && !nestedOnboarded) {
4531
4691
  await assertParentSafeDeployedOnChain(
4532
4692
  userAddress,
4533
4693
  chainConfig.publicClient,
@@ -4561,7 +4721,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4561
4721
  );
4562
4722
  }
4563
4723
  }
4564
- if (ownerType === "Safe" && isDeployed) {
4724
+ if (ownerType === "Safe" && isDeployed && !nestedOnboarded) {
4565
4725
  await assertParentSafeDeployedOnChain(
4566
4726
  userAddress,
4567
4727
  chainConfig.publicClient,
@@ -4584,35 +4744,35 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4584
4744
  if (sponsored) return sponsored;
4585
4745
  }
4586
4746
  if (ownerType === "Safe") {
4587
- const since = new Date(Date.now() - NESTED_SAFE_RESUME_WINDOW_MS);
4588
- const inFlight = await findSafeTransferProposal({
4589
- parentSafe: userAddress,
4590
- childSafe: safeAddress,
4591
- chainId,
4592
- tokenAddress: token,
4593
- amount: amountBigInt,
4594
- since
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
4595
4754
  });
4596
- let safeTxHash = inFlight?.safeTxHash;
4597
- if (!inFlight) {
4598
- const proposed = await walletClient.writeContract({
4599
- address: token,
4600
- abi: erc20TransferWriteAbi(assetSymbol),
4601
- functionName: "transfer",
4602
- args: [safeAddress, amountBigInt],
4603
- chain: chainConfig.chain,
4604
- account: walletClient.account
4605
- });
4606
- safeTxHash = (await findSafeTransferByHash({ chainId, safeTxHash: proposed }))?.safeTxHash;
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)}`);
4607
4767
  }
4608
- const executedHash = inFlight?.isExecuted && inFlight.transactionHash ? inFlight.transactionHash : await waitForSafeTransferExecution({
4609
- parentSafe: userAddress,
4768
+ const executedHash = await waitForExactSafeDepositExecution({
4769
+ parentSafe: reference.userAddress,
4610
4770
  childSafe: safeAddress,
4611
4771
  chainId,
4612
4772
  tokenAddress: token,
4613
4773
  amount: amountBigInt,
4614
- safeTxHash,
4615
- since
4774
+ proposalHash: proposed,
4775
+ publicClient: chainConfig.publicClient
4616
4776
  });
4617
4777
  const registration2 = await this.registerDeposit(
4618
4778
  chainId,
@@ -4787,6 +4947,39 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4787
4947
  strategy
4788
4948
  );
4789
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
+ }
4790
4983
  /**
4791
4984
  * Resolve a deposit without signing.
4792
4985
  *
@@ -5047,7 +5240,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5047
5240
  params.chainId,
5048
5241
  params.amount,
5049
5242
  route.asset,
5050
- params.strategy
5243
+ params.strategy,
5244
+ params.onSafeProposal
5051
5245
  );
5052
5246
  }
5053
5247
  if (route.kind === "wrap") {
@@ -5665,7 +5859,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5665
5859
  );
5666
5860
  } catch (logError) {
5667
5861
  throw new Error(
5668
- `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
5862
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}", "${tokenAddress}") to retry.`
5669
5863
  );
5670
5864
  }
5671
5865
  return registration.deposit;
@@ -6032,6 +6226,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
6032
6226
  );
6033
6227
  }
6034
6228
  await this.authenticateUser();
6229
+ this.assertConnectedUser(userAddress);
6035
6230
  await this.assertAsyncRedemptionSlotFree(
6036
6231
  userAddress,
6037
6232
  chainId,
@@ -8546,9 +8741,11 @@ function createBankrProvider(config) {
8546
8741
  WS_ENDPOINT,
8547
8742
  WS_URLS,
8548
8743
  ZyfaiSDK,
8744
+ buildNestedSafeOnboardingStatus,
8549
8745
  buildV1ChainSessions,
8550
8746
  createBankrProvider,
8551
8747
  decodeUserOperationCalls,
8748
+ deriveNestedSafeOnboardingStep,
8552
8749
  getChainConfig,
8553
8750
  getDataApiBaseUrl,
8554
8751
  getDefaultTokenAddress,
@@ -8561,6 +8758,7 @@ function createBankrProvider(config) {
8561
8758
  isSupportedChain,
8562
8759
  parseUserOperationJson,
8563
8760
  parseV1ChainSessions,
8761
+ portfolioHasWithdrawableBalance,
8564
8762
  resolveDepositRoute,
8565
8763
  resolveRelaySlippageBps,
8566
8764
  serializeV1ChainSessions