@zyfai/sdk 1.8.3 → 1.9.2

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
@@ -61,7 +61,6 @@ __export(index_exports, {
61
61
  ZyfaiSDK: () => ZyfaiSDK,
62
62
  buildV1ChainSessions: () => buildV1ChainSessions,
63
63
  createBankrProvider: () => createBankrProvider,
64
- createSafeOwnerProvider: () => createSafeOwnerProvider,
65
64
  decodeUserOperationCalls: () => decodeUserOperationCalls,
66
65
  getChainConfig: () => getChainConfig,
67
66
  getDataApiBaseUrl: () => getDataApiBaseUrl,
@@ -1679,6 +1678,36 @@ var getAccountType = async (address, publicClient) => {
1679
1678
  return "Unknown";
1680
1679
  }
1681
1680
  };
1681
+ var signNestedSafeDeployTypedData = async (owner, parentSafe, typedData) => {
1682
+ if (!owner.account) {
1683
+ throw new Error("Wallet not connected. Please connect your wallet first.");
1684
+ }
1685
+ return owner.signTypedData({
1686
+ account: parentSafe,
1687
+ domain: typedData.domain,
1688
+ types: typedData.types,
1689
+ primaryType: typedData.primaryType,
1690
+ message: typedData.message
1691
+ });
1692
+ };
1693
+ var TYPED_DATA_DEPLOY_TIMEOUT_MS = 18e4;
1694
+ var completeSafeDeploy = async (config, strategyBody, body, requestConfig) => {
1695
+ const deployResponse = await config.httpClient.post(
1696
+ `${ENDPOINTS.SAFE_DEPLOY}?chainId=${config.chainId}`,
1697
+ { ...body, ...strategyBody },
1698
+ requestConfig
1699
+ );
1700
+ if (!deployResponse.success) {
1701
+ throw new Error(
1702
+ `Safe deployment failed: ${JSON.stringify(deployResponse)}`
1703
+ );
1704
+ }
1705
+ return {
1706
+ safeAddress: deployResponse.safeAddress || "0x",
1707
+ txHash: deployResponse.txHash,
1708
+ isDeployed: true
1709
+ };
1710
+ };
1682
1711
  var deploySafeAccount = async (config) => {
1683
1712
  try {
1684
1713
  const {
@@ -1701,16 +1730,38 @@ var deploySafeAccount = async (config) => {
1701
1730
  strategyBody
1702
1731
  );
1703
1732
  console.log("prepareResponse", prepareResponse);
1704
- if (prepareResponse.success && !prepareResponse.userOpHashToSign) {
1733
+ if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1705
1734
  return {
1706
1735
  safeAddress: prepareResponse.safeAddress || "0x",
1707
1736
  txHash: "0x0",
1708
1737
  isDeployed: true
1709
1738
  };
1710
1739
  }
1740
+ if (prepareResponse.signingMode === "typed-data") {
1741
+ if (!prepareResponse.typedData) {
1742
+ throw new Error(
1743
+ "Backend returned signingMode typed-data without typedData. Response: " + JSON.stringify(prepareResponse)
1744
+ );
1745
+ }
1746
+ const parentSafe = (0, import_viem6.getAddress)(safeOwnerAddress);
1747
+ console.info(
1748
+ `[ZyfaiSDK] safe-deploy typed-data chainId=${chainId} owner=${parentSafe}`
1749
+ );
1750
+ const typedDataSignature = await signNestedSafeDeployTypedData(
1751
+ owner,
1752
+ parentSafe,
1753
+ prepareResponse.typedData
1754
+ );
1755
+ return completeSafeDeploy(
1756
+ config,
1757
+ strategyBody,
1758
+ { typedDataSignature },
1759
+ { timeout: TYPED_DATA_DEPLOY_TIMEOUT_MS }
1760
+ );
1761
+ }
1711
1762
  if (!prepareResponse.userOpHashToSign) {
1712
1763
  throw new Error(
1713
- "Backend did not return userOpHashToSign. Response: " + JSON.stringify(prepareResponse)
1764
+ "Backend did not return userOpHashToSign or typed-data to sign. Response: " + JSON.stringify(prepareResponse)
1714
1765
  );
1715
1766
  }
1716
1767
  const userOpHashToSign = prepareResponse.userOpHashToSign;
@@ -1738,20 +1789,9 @@ var deploySafeAccount = async (config) => {
1738
1789
  isContractSignature: true
1739
1790
  }
1740
1791
  ]) : userOpSignature;
1741
- const deployResponse = await httpClient.post(
1742
- `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1743
- { userOpSignature: signatureToSubmit, ...strategyBody }
1744
- );
1745
- if (!deployResponse.success) {
1746
- throw new Error(
1747
- `Safe deployment failed: ${JSON.stringify(deployResponse)}`
1748
- );
1749
- }
1750
- return {
1751
- safeAddress: deployResponse.safeAddress || "0x",
1752
- txHash: deployResponse.txHash,
1753
- isDeployed: true
1754
- };
1792
+ return completeSafeDeploy(config, strategyBody, {
1793
+ userOpSignature: signatureToSubmit
1794
+ });
1755
1795
  } catch (error) {
1756
1796
  throw new Error(
1757
1797
  `Failed to deploy Safe account: ${error.message}`
@@ -2573,7 +2613,7 @@ var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
2573
2613
  };
2574
2614
 
2575
2615
  // src/core/ZyfaiSDK.ts
2576
- var import_siwe = require("siwe");
2616
+ var import_siwe = require("viem/siwe");
2577
2617
  var DepositCreditTimeoutError = class extends Error {
2578
2618
  constructor(depositId) {
2579
2619
  super(`Timed out waiting for deposit ${depositId} to be credited`);
@@ -2645,6 +2685,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2645
2685
  this.currentChainId = null;
2646
2686
  /** EOA of the active user session (bearer or SIWE). Cleared on disconnect. */
2647
2687
  this.sessionEoa = null;
2688
+ /** Serialize concurrent connectAccount calls (e.g. React StrictMode double mount). */
2689
+ this.connectAccountInFlight = null;
2690
+ /** One SIWE prompt at a time. Register must not send a second personal_sign. */
2691
+ this.authenticateUserInFlight = null;
2648
2692
  const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
2649
2693
  const {
2650
2694
  apiKey,
@@ -2769,16 +2813,33 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2769
2813
  *
2770
2814
  * @returns Promise that resolves when authentication is complete
2771
2815
  */
2772
- async authenticateUser() {
2816
+ authenticateUser() {
2817
+ if (this.authenticatedUserId !== null || this.httpClient.hasAuthToken()) {
2818
+ return Promise.resolve();
2819
+ }
2820
+ if (!this.authenticateUserInFlight) {
2821
+ this.authenticateUserInFlight = this.performAuthenticateUser().finally(
2822
+ () => {
2823
+ this.authenticateUserInFlight = null;
2824
+ }
2825
+ );
2826
+ }
2827
+ return this.authenticateUserInFlight;
2828
+ }
2829
+ async performAuthenticateUser() {
2773
2830
  try {
2774
- if (this.authenticatedUserId !== null) {
2775
- return;
2776
- }
2777
- if (this.httpClient.hasAuthToken()) {
2831
+ if (this.authenticatedUserId !== null || this.httpClient.hasAuthToken()) {
2778
2832
  return;
2779
2833
  }
2780
2834
  const walletClient = this.getWalletClient();
2781
- const userAddress = (0, import_viem8.getAddress)(walletClient.account.address);
2835
+ const rawAccount = walletClient.account;
2836
+ const connected = typeof rawAccount === "string" ? rawAccount : rawAccount?.address;
2837
+ if (!connected) {
2838
+ throw new Error(
2839
+ "Wallet account address is missing. Call connectAccount() after the wallet is connected."
2840
+ );
2841
+ }
2842
+ const userAddress = (0, import_viem8.getAddress)(connected);
2782
2843
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
2783
2844
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
2784
2845
  let uri;
@@ -2792,7 +2853,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2792
2853
  uri = this.executionApiUrl;
2793
2854
  domain = new URL(this.executionApiUrl).host;
2794
2855
  }
2795
- const messageObj = new import_siwe.SiweMessage({
2856
+ const issuedAt = /* @__PURE__ */ new Date();
2857
+ const messageFields = {
2796
2858
  address: userAddress,
2797
2859
  chainId,
2798
2860
  domain,
@@ -2800,11 +2862,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2800
2862
  statement: "Sign in with Ethereum",
2801
2863
  uri,
2802
2864
  version: "1",
2803
- issuedAt: (/* @__PURE__ */ new Date()).toISOString()
2804
- });
2805
- const messageString = messageObj.prepareMessage();
2865
+ issuedAt
2866
+ };
2867
+ const messageString = (0, import_siwe.createSiweMessage)(messageFields);
2868
+ const messageObj = {
2869
+ ...messageFields,
2870
+ issuedAt: issuedAt.toISOString()
2871
+ };
2806
2872
  const signature = await walletClient.signMessage({
2807
- account: walletClient.account,
2873
+ account: userAddress,
2808
2874
  message: messageString
2809
2875
  });
2810
2876
  const loginResponse = await this.httpClient.post(
@@ -2892,6 +2958,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2892
2958
  [internalAsset]: assetSettings
2893
2959
  }
2894
2960
  };
2961
+ if (request.smartWallet !== void 0)
2962
+ payload.smartWallet = request.smartWallet;
2963
+ if (request.executorProxy !== void 0)
2964
+ payload.executorProxy = request.executorProxy;
2965
+ if (request.chains !== void 0) payload.chains = request.chains;
2895
2966
  if (request.omniAccount !== void 0)
2896
2967
  payload.omniAccount = request.omniAccount;
2897
2968
  if (request.agentName !== void 0)
@@ -3197,82 +3268,167 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3197
3268
  * const provider = await connector.getProvider();
3198
3269
  * await sdk.connectAccount(provider);
3199
3270
  */
3200
- async connectAccount(account, chainId = 8453) {
3201
- if (!isSupportedChain(chainId)) {
3202
- throw new Error(`Unsupported chain ID: ${chainId}`);
3203
- }
3204
- this.authenticatedUserId = null;
3205
- this.isPredeployed = false;
3206
- this.predeployedResolved = false;
3207
- this.connectedSmartWallet = null;
3208
- this.currentChainId = null;
3209
- this.sessionEoa = null;
3210
- this.sessionChannel = void 0;
3211
- this.httpClient.clearAuthToken();
3212
- if (this.currentProvider?.removeAllListeners) {
3213
- try {
3214
- this.currentProvider.removeAllListeners("accountsChanged");
3215
- } catch (error) {
3216
- }
3217
- }
3218
- const chainConfig = getChainConfig(chainId, this.rpcUrls);
3219
- let connectedAddress;
3271
+ async resolveConnectAddress(account) {
3220
3272
  if (typeof account === "string") {
3221
3273
  let privateKey = account;
3222
3274
  if (!privateKey.startsWith("0x")) {
3223
3275
  privateKey = `0x${privateKey}`;
3224
3276
  }
3225
- this.signer = (0, import_accounts2.privateKeyToAccount)(privateKey);
3226
- this.currentChainId = chainId;
3227
- this.walletClient = (0, import_viem8.createWalletClient)({
3228
- account: this.signer,
3229
- chain: chainConfig.chain,
3230
- transport: (0, import_viem8.http)(chainConfig.rpcUrl)
3277
+ return (0, import_accounts2.privateKeyToAccount)(privateKey).address;
3278
+ }
3279
+ const provider = account;
3280
+ if (!provider) {
3281
+ throw new Error(
3282
+ "Invalid account parameter. Expected private key string or wallet provider."
3283
+ );
3284
+ }
3285
+ if (provider.account && provider.transport) {
3286
+ const accountField = provider.account;
3287
+ const resolvedAddress = typeof accountField === "string" ? accountField : accountField.address;
3288
+ if (!resolvedAddress) {
3289
+ throw new Error("Wallet client is missing account address");
3290
+ }
3291
+ return (0, import_viem8.getAddress)(resolvedAddress);
3292
+ }
3293
+ if (provider.request) {
3294
+ const eip1193 = typeof provider.request === "function" ? provider : typeof provider.provider?.request === "function" ? provider.provider : null;
3295
+ if (!eip1193) {
3296
+ throw new Error(
3297
+ "Wallet provider has no EIP-1193 request method. Pass the connector getProvider() result."
3298
+ );
3299
+ }
3300
+ const accounts = await eip1193.request({
3301
+ method: "eth_accounts"
3231
3302
  });
3232
- connectedAddress = this.signer.address;
3233
- this.currentProvider = null;
3234
- } else {
3235
- const provider = account;
3236
- if (!provider) {
3303
+ const fallbackAccounts = accounts?.length > 0 ? accounts : await eip1193.request({
3304
+ method: "eth_requestAccounts"
3305
+ });
3306
+ const raw = fallbackAccounts?.[0];
3307
+ const accountAddress = typeof raw === "string" ? raw : typeof raw?.address === "string" ? raw.address : void 0;
3308
+ if (!accountAddress) {
3237
3309
  throw new Error(
3238
- "Invalid account parameter. Expected private key string or wallet provider."
3310
+ "Wallet returned an account without an address. Reconnect via WalletConnect."
3239
3311
  );
3240
3312
  }
3241
- if (provider.request) {
3242
- const accounts = await provider.request({
3243
- method: "eth_requestAccounts"
3244
- });
3245
- if (!accounts || accounts.length === 0) {
3246
- throw new Error("No accounts found in wallet provider");
3313
+ return (0, import_viem8.getAddress)(accountAddress);
3314
+ }
3315
+ throw new Error(
3316
+ "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3317
+ );
3318
+ }
3319
+ async connectAccount(account, chainId = 8453) {
3320
+ if (!isSupportedChain(chainId)) {
3321
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3322
+ }
3323
+ const resolvedAddress = await this.resolveConnectAddress(account);
3324
+ if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && (0, import_viem8.isAddressEqual)(resolvedAddress, this.sessionEoa)) {
3325
+ this.currentChainId = chainId;
3326
+ return resolvedAddress;
3327
+ }
3328
+ if (this.connectAccountInFlight) {
3329
+ return this.connectAccountInFlight;
3330
+ }
3331
+ const connect = (async () => {
3332
+ this.authenticatedUserId = null;
3333
+ this.isPredeployed = false;
3334
+ this.predeployedResolved = false;
3335
+ this.connectedSmartWallet = null;
3336
+ this.currentChainId = null;
3337
+ this.sessionEoa = null;
3338
+ this.sessionChannel = void 0;
3339
+ this.httpClient.clearAuthToken();
3340
+ if (this.currentProvider?.removeAllListeners) {
3341
+ try {
3342
+ this.currentProvider.removeAllListeners("accountsChanged");
3343
+ } catch (error) {
3247
3344
  }
3248
- this.walletClient = (0, import_viem8.createWalletClient)({
3249
- account: accounts[0],
3250
- chain: chainConfig.chain,
3251
- transport: (0, import_viem8.custom)(provider)
3252
- });
3253
- connectedAddress = accounts[0];
3254
- this.currentProvider = provider;
3255
- this.currentChainId = chainId;
3256
- if (provider.on) {
3257
- provider.on("accountsChanged", this.handleAccountsChanged.bind(this));
3345
+ }
3346
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3347
+ let connectedAddress;
3348
+ if (typeof account === "string") {
3349
+ let privateKey = account;
3350
+ if (!privateKey.startsWith("0x")) {
3351
+ privateKey = `0x${privateKey}`;
3258
3352
  }
3259
- } else if (provider.account && provider.transport) {
3353
+ this.signer = (0, import_accounts2.privateKeyToAccount)(privateKey);
3354
+ this.currentChainId = chainId;
3260
3355
  this.walletClient = (0, import_viem8.createWalletClient)({
3261
- account: provider.account,
3356
+ account: this.signer,
3262
3357
  chain: chainConfig.chain,
3263
- transport: provider.transport
3358
+ transport: (0, import_viem8.http)(chainConfig.rpcUrl)
3264
3359
  });
3265
- connectedAddress = provider.account.address;
3360
+ connectedAddress = this.signer.address;
3266
3361
  this.currentProvider = null;
3267
- this.currentChainId = chainId;
3268
3362
  } else {
3269
- throw new Error(
3270
- "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3271
- );
3363
+ const provider = account;
3364
+ if (!provider) {
3365
+ throw new Error(
3366
+ "Invalid account parameter. Expected private key string or wallet provider."
3367
+ );
3368
+ }
3369
+ if (provider.account && provider.transport) {
3370
+ const accountField = provider.account;
3371
+ const resolvedAddress2 = typeof accountField === "string" ? accountField : accountField.address;
3372
+ if (!resolvedAddress2) {
3373
+ throw new Error("Wallet client is missing account address");
3374
+ }
3375
+ const hasSignMessage = typeof provider.signMessage === "function" && typeof provider.request === "function";
3376
+ this.walletClient = hasSignMessage ? provider : (0, import_viem8.createWalletClient)({
3377
+ account: provider.account,
3378
+ chain: chainConfig.chain,
3379
+ transport: provider.transport
3380
+ });
3381
+ connectedAddress = (0, import_viem8.getAddress)(resolvedAddress2);
3382
+ this.currentProvider = null;
3383
+ this.currentChainId = chainId;
3384
+ } else if (provider.request) {
3385
+ const eip1193 = typeof provider.request === "function" ? provider : typeof provider.provider?.request === "function" ? provider.provider : null;
3386
+ if (!eip1193) {
3387
+ throw new Error(
3388
+ "Wallet provider has no EIP-1193 request method. Pass the connector getProvider() result."
3389
+ );
3390
+ }
3391
+ const accounts = await eip1193.request({
3392
+ method: "eth_requestAccounts"
3393
+ });
3394
+ if (!accounts || accounts.length === 0) {
3395
+ throw new Error("No accounts found in wallet provider");
3396
+ }
3397
+ const raw = accounts[0];
3398
+ const accountAddress = typeof raw === "string" ? raw : typeof raw?.address === "string" ? raw.address : void 0;
3399
+ if (!accountAddress) {
3400
+ throw new Error(
3401
+ "Wallet returned an account without an address. Reconnect via WalletConnect."
3402
+ );
3403
+ }
3404
+ connectedAddress = (0, import_viem8.getAddress)(accountAddress);
3405
+ this.walletClient = (0, import_viem8.createWalletClient)({
3406
+ account: connectedAddress,
3407
+ chain: chainConfig.chain,
3408
+ transport: (0, import_viem8.custom)(eip1193)
3409
+ });
3410
+ this.currentProvider = eip1193;
3411
+ this.currentChainId = chainId;
3412
+ if (provider.on) {
3413
+ provider.on("accountsChanged", this.handleAccountsChanged.bind(this));
3414
+ }
3415
+ } else {
3416
+ throw new Error(
3417
+ "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3418
+ );
3419
+ }
3420
+ }
3421
+ await this.authenticateUser();
3422
+ return connectedAddress;
3423
+ })();
3424
+ this.connectAccountInFlight = connect;
3425
+ try {
3426
+ return await connect;
3427
+ } finally {
3428
+ if (this.connectAccountInFlight === connect) {
3429
+ this.connectAccountInFlight = null;
3272
3430
  }
3273
3431
  }
3274
- await this.authenticateUser();
3275
- return connectedAddress;
3276
3432
  }
3277
3433
  /**
3278
3434
  * Clear the connected wallet, SIWE session, and cached smart-wallet state.
@@ -3338,6 +3494,51 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3338
3494
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3339
3495
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
3340
3496
  }
3497
+ /**
3498
+ * Nested Safe owners use intent sessions: finish any pending safe-deploy typed-data
3499
+ * (install or emissary enable), then register with chainId only.
3500
+ * @private
3501
+ */
3502
+ async registerNestedIntentSessionKey(userAddress, chainId, strategy) {
3503
+ if (!this.authenticatedUserId) {
3504
+ throw new Error(
3505
+ "User ID not available. Please ensure authentication completed successfully."
3506
+ );
3507
+ }
3508
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3509
+ await deploySafeAccount({
3510
+ owner: this.getWalletClient(chainId),
3511
+ safeOwnerAddress: userAddress,
3512
+ chain: chainConfig.chain,
3513
+ publicClient: chainConfig.publicClient,
3514
+ chainId,
3515
+ httpClient: this.httpClient,
3516
+ strategy
3517
+ });
3518
+ const activation = await this.httpClient.post(
3519
+ ENDPOINTS.SESSION_KEYS_ADD,
3520
+ { chainId }
3521
+ );
3522
+ this.hasActiveSessionKey = true;
3523
+ return {
3524
+ success: true,
3525
+ userId: this.authenticatedUserId,
3526
+ message: "Intent session key registered",
3527
+ alreadyActive: false,
3528
+ sessionActivation: activation
3529
+ };
3530
+ }
3531
+ async registerNestedChildProfile(childAddress, chainId, strategy) {
3532
+ await this.updateUserProfile({
3533
+ smartWallet: childAddress,
3534
+ executorProxy: true,
3535
+ chains: [chainId],
3536
+ strategy,
3537
+ protocols: [],
3538
+ autoSelectProtocols: false,
3539
+ asset: "USDC"
3540
+ });
3541
+ }
3341
3542
  /**
3342
3543
  * SIWE login sets predeployed. Agent sessions (`forUser`) do not, so read it
3343
3544
  * from the user record before allowing a transfer to an undeployed pool Safe.
@@ -3361,13 +3562,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3361
3562
  chainId
3362
3563
  );
3363
3564
  const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3364
- if (!childAddress) {
3365
- throw new Error("Child smart wallet address is not available");
3366
- }
3367
- const childDeployed = await isSafeDeployed(
3368
- childAddress,
3369
- chainConfig.publicClient
3370
- );
3565
+ const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3371
3566
  if (!childDeployed) {
3372
3567
  await this.deploySafe(userAddress, chainId, strategy, true);
3373
3568
  return;
@@ -3420,6 +3615,25 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3420
3615
  }
3421
3616
  if (!deriveIfMissing) return null;
3422
3617
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3618
+ const ownerType = await getAccountType(
3619
+ userAddress,
3620
+ chainConfig.publicClient
3621
+ );
3622
+ if (ownerType === "Safe") {
3623
+ if (this.isConnectedUser(userAddress) && this.connectedSmartWallet) {
3624
+ return this.connectedSmartWallet;
3625
+ }
3626
+ try {
3627
+ if (this.httpClient.hasAuthToken()) {
3628
+ const me = await this.httpClient.get(
3629
+ ENDPOINTS.USER_ME
3630
+ );
3631
+ if (me?.smartWallet) return (0, import_viem8.getAddress)(me.smartWallet);
3632
+ }
3633
+ } catch {
3634
+ }
3635
+ return null;
3636
+ }
3423
3637
  return getDeterministicSafeAddress({
3424
3638
  safeOwnerAddress: userAddress,
3425
3639
  chain: chainConfig.chain,
@@ -3449,8 +3663,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3449
3663
  throw new Error(`Unsupported chain ID: ${chainId}`);
3450
3664
  }
3451
3665
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3666
+ const ownerType = await getAccountType(
3667
+ userAddress,
3668
+ chainConfig.publicClient
3669
+ );
3452
3670
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3453
3671
  if (!safeAddress) {
3672
+ if (ownerType === "Safe") {
3673
+ throw new Error("NESTED_CHILD_UNREGISTERED");
3674
+ }
3454
3675
  throw new Error("Smart wallet address is not available");
3455
3676
  }
3456
3677
  const isDeployed = await isSafeDeployed(
@@ -3535,15 +3756,19 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3535
3756
  }
3536
3757
  const walletClient = this.getWalletClient(chainId);
3537
3758
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3538
- const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3539
- if (!safeAddress) {
3540
- throw new Error("Smart wallet address is not available");
3541
- }
3542
- const alreadyDeployed = await isSafeDeployed(
3543
- safeAddress,
3759
+ const ownerAccountType = await getAccountType(
3760
+ userAddress,
3544
3761
  chainConfig.publicClient
3545
3762
  );
3546
- if (alreadyDeployed) {
3763
+ const nestedSafeOwner = ownerAccountType === "Safe";
3764
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3765
+ if (!safeAddress && !nestedSafeOwner) {
3766
+ throw new Error(
3767
+ ownerAccountType === "EOA" ? "For nested deploy, connect WalletConnect as the parent Safe contract address, not the owner EOA." : "Smart wallet address is not available"
3768
+ );
3769
+ }
3770
+ const alreadyDeployed = safeAddress ? await isSafeDeployed(safeAddress, chainConfig.publicClient) : false;
3771
+ if (alreadyDeployed && safeAddress) {
3547
3772
  let enableTxHash = "0x0";
3548
3773
  if (!this.isPredeployed) {
3549
3774
  const enabled = await deploySafeAccount({
@@ -3553,7 +3778,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3553
3778
  publicClient: chainConfig.publicClient,
3554
3779
  chainId,
3555
3780
  httpClient: this.httpClient,
3556
- strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy"
3781
+ strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy",
3782
+ childSafeAddress: safeAddress
3557
3783
  });
3558
3784
  enableTxHash = enabled.txHash || "0x0";
3559
3785
  }
@@ -3586,7 +3812,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3586
3812
  publicClient: chainConfig.publicClient,
3587
3813
  chainId,
3588
3814
  httpClient: this.httpClient,
3589
- strategy: internalStrategy
3815
+ strategy: internalStrategy,
3816
+ childSafeAddress: safeAddress ?? void 0
3590
3817
  });
3591
3818
  this.hasActiveSessionKey = false;
3592
3819
  try {
@@ -3597,8 +3824,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3597
3824
  initError.message
3598
3825
  );
3599
3826
  }
3827
+ if (nestedSafeOwner) {
3828
+ await this.registerNestedChildProfile(
3829
+ deploymentResult.safeAddress,
3830
+ chainId,
3831
+ strategy
3832
+ );
3833
+ }
3600
3834
  await this.updateUserProtocols(strategy);
3601
- if (!this.isPredeployed) {
3835
+ if (!this.isPredeployed && !nestedSafeOwner) {
3602
3836
  await deploySafeAccount({
3603
3837
  owner: walletClient,
3604
3838
  safeOwnerAddress: userAddress,
@@ -3606,7 +3840,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3606
3840
  publicClient: chainConfig.publicClient,
3607
3841
  chainId,
3608
3842
  httpClient: this.httpClient,
3609
- strategy: internalStrategy
3843
+ strategy: internalStrategy,
3844
+ childSafeAddress: deploymentResult.safeAddress
3610
3845
  });
3611
3846
  }
3612
3847
  let sessionKeyCreated = false;
@@ -3709,14 +3944,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3709
3944
  chainConfig.publicClient
3710
3945
  );
3711
3946
  if (accountType === "Safe") {
3712
- await this.assertOwnerSafeOnSessionChains(
3947
+ return this.registerNestedIntentSessionKey(
3713
3948
  userAddress,
3714
- sessions
3949
+ chainId,
3950
+ void 0
3715
3951
  );
3716
3952
  }
3717
3953
  const signingParams = {
3718
3954
  permitGenericPolicy,
3719
- ignoreSecurityAttestations: accountType === "Safe"
3955
+ ignoreSecurityAttestations: false
3720
3956
  };
3721
3957
  const signatureResult = await this.signSessionKey(
3722
3958
  userAddress,
@@ -3746,38 +3982,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3746
3982
  }
3747
3983
  }
3748
3984
  /**
3749
- * Internal method to sign session key
3985
+ * Internal method to sign session key for an EOA owner.
3986
+ * Nested Safe owners register through {@link registerNestedIntentSessionKey}.
3750
3987
  * @private
3751
3988
  */
3752
- /**
3753
- * A nested Safe owner signs one MultiChainSession covering every chain in the
3754
- * session configuration, and the child validates that signature against the
3755
- * owner through ERC-1271 on each of them. A chain where the owner has no code
3756
- * would accept the signature nowhere, so refuse rather than sign it.
3757
- *
3758
- * The session list is not filtered here: the execution API rebuilds the digest
3759
- * from its own configuration, so dropping a chain client-side would change the
3760
- * hash and the signature would be rejected everywhere.
3761
- * @private
3762
- */
3763
- async assertOwnerSafeOnSessionChains(ownerAddress, sessions) {
3764
- const chainIds = [
3765
- ...new Set(sessions.map((session) => Number(session.chainId)))
3766
- ].filter(isSupportedChain);
3767
- const missing = [];
3768
- await Promise.all(
3769
- chainIds.map(async (id) => {
3770
- const { publicClient } = getChainConfig(id, this.rpcUrls);
3771
- const code = await publicClient.getCode({ address: ownerAddress });
3772
- if (!code || code === "0x") missing.push(id);
3773
- })
3774
- );
3775
- if (missing.length > 0) {
3776
- throw new Error(
3777
- `Owner Safe ${ownerAddress} has no code on chain(s) ${missing.sort((a, b) => a - b).join(", ")} covered by the session configuration. Deploy the Safe there, or restrict the user's chains, before signing the session.`
3778
- );
3779
- }
3780
- }
3781
3989
  async signSessionKey(userAddress, chainId, sessions, signingParams) {
3782
3990
  try {
3783
3991
  if (!userAddress) {
@@ -8307,371 +8515,6 @@ function createBankrProvider(config) {
8307
8515
  };
8308
8516
  return provider;
8309
8517
  }
8310
-
8311
- // src/providers/safe-owner.ts
8312
- var import_viem11 = require("viem");
8313
- var EIP1271_MAGIC_VALUE = "0x1626ba7e";
8314
- var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
8315
- var SAFE_ABI2 = (0, import_viem11.parseAbi)([
8316
- "function getThreshold() view returns (uint256)",
8317
- "function getOwners() view returns (address[])",
8318
- "function nonce() view returns (uint256)",
8319
- "function getMessageHash(bytes message) view returns (bytes32)",
8320
- "function getTransactionHash(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce) view returns (bytes32)",
8321
- "function execTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures) payable returns (bool)",
8322
- "function isValidSignature(bytes32 _dataHash, bytes _signature) view returns (bytes4)"
8323
- ]);
8324
- async function createSafeOwnerProvider(config) {
8325
- if (!(0, import_viem11.isAddress)(config.safeAddress)) {
8326
- throw new Error("safeAddress must be an Ethereum address");
8327
- }
8328
- const safeAddress = (0, import_viem11.getAddress)(config.safeAddress);
8329
- const publicClient = (0, import_viem11.createPublicClient)({
8330
- chain: config.chain,
8331
- transport: (0, import_viem11.http)()
8332
- });
8333
- const ownerWallet = await resolveOwnerWallet(config.owner, config.chain);
8334
- const code = await publicClient.getCode({ address: safeAddress });
8335
- if (!code || code === "0x") {
8336
- throw new Error(
8337
- `Safe ${safeAddress} has no code on chain ${config.chain.id}`
8338
- );
8339
- }
8340
- const [threshold, owners] = await Promise.all([
8341
- publicClient.readContract({
8342
- address: safeAddress,
8343
- abi: SAFE_ABI2,
8344
- functionName: "getThreshold"
8345
- }),
8346
- publicClient.readContract({
8347
- address: safeAddress,
8348
- abi: SAFE_ABI2,
8349
- functionName: "getOwners"
8350
- })
8351
- ]);
8352
- if (threshold !== 1n) {
8353
- throw new Error(
8354
- `Safe ${safeAddress} threshold is ${threshold.toString()}. createSafeOwnerProvider can execute only a threshold-1 Safe. For a multisig such as 2-of-4, connect the Safe with WalletConnect or the Safe App and pass that provider to connectAccount. sendDeposit waits while the other owners confirm.`
8355
- );
8356
- }
8357
- const ownerAddress = ownerWallet.address;
8358
- if (!owners.some((owner) => (0, import_viem11.getAddress)(owner) === ownerAddress)) {
8359
- throw new Error(`${ownerAddress} is not an owner of Safe ${safeAddress}`);
8360
- }
8361
- const signSafeDigest = async (dataHash) => {
8362
- const encoded = (0, import_viem11.encodeAbiParameters)([{ type: "bytes32" }], [dataHash]);
8363
- const messageHash = await publicClient.readContract({
8364
- address: safeAddress,
8365
- abi: SAFE_ABI2,
8366
- functionName: "getMessageHash",
8367
- args: [encoded]
8368
- });
8369
- return ownerWallet.signHash(messageHash);
8370
- };
8371
- const probeHash = (0, import_viem11.hashMessage)("zyfai safe owner");
8372
- const probeSignature = await signSafeDigest(probeHash);
8373
- const magic = await publicClient.readContract({
8374
- address: safeAddress,
8375
- abi: SAFE_ABI2,
8376
- functionName: "isValidSignature",
8377
- args: [probeHash, probeSignature]
8378
- });
8379
- if (magic.toLowerCase() !== EIP1271_MAGIC_VALUE) {
8380
- throw new Error(
8381
- `Safe ${safeAddress} rejected the owner signature (isValidSignature returned ${magic})`
8382
- );
8383
- }
8384
- const executeFromSafe = async (tx) => {
8385
- const nonce = await publicClient.readContract({
8386
- address: safeAddress,
8387
- abi: SAFE_ABI2,
8388
- functionName: "nonce"
8389
- });
8390
- const safeTxHash = await publicClient.readContract({
8391
- address: safeAddress,
8392
- abi: SAFE_ABI2,
8393
- functionName: "getTransactionHash",
8394
- args: [
8395
- tx.to,
8396
- tx.value,
8397
- tx.data,
8398
- 0,
8399
- 0n,
8400
- 0n,
8401
- 0n,
8402
- ZERO_ADDRESS,
8403
- ZERO_ADDRESS,
8404
- nonce
8405
- ]
8406
- });
8407
- const signature = await ownerWallet.signHash(safeTxHash);
8408
- const data = (0, import_viem11.encodeFunctionData)({
8409
- abi: SAFE_ABI2,
8410
- functionName: "execTransaction",
8411
- args: [
8412
- tx.to,
8413
- tx.value,
8414
- tx.data,
8415
- 0,
8416
- 0n,
8417
- 0n,
8418
- 0n,
8419
- ZERO_ADDRESS,
8420
- ZERO_ADDRESS,
8421
- signature
8422
- ]
8423
- });
8424
- const hash = await ownerWallet.sendTransaction({
8425
- to: safeAddress,
8426
- data,
8427
- value: 0n
8428
- });
8429
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
8430
- if (receipt.status !== "success") {
8431
- throw new Error(`Safe transaction reverted: ${hash}`);
8432
- }
8433
- return hash;
8434
- };
8435
- return {
8436
- async request({ method, params }) {
8437
- if (method === "eth_requestAccounts" || method === "eth_accounts") {
8438
- return [safeAddress];
8439
- }
8440
- if (method === "personal_sign" || method === "eth_sign") {
8441
- return signSafeDigest(personalSignDigest(params));
8442
- }
8443
- if (method === "eth_signTypedData_v4" || method === "eth_signTypedData") {
8444
- return signSafeDigest(typedDataDigest(params));
8445
- }
8446
- if (method === "eth_sendTransaction" || method === "wallet_sendTransaction") {
8447
- return executeFromSafe(readSafeTransaction(params));
8448
- }
8449
- return publicClient.request({
8450
- method,
8451
- params: params ?? []
8452
- });
8453
- }
8454
- };
8455
- }
8456
- async function resolveOwnerWallet(owner, chain) {
8457
- if (isHashSigner(owner)) {
8458
- const address = (0, import_viem11.getAddress)(owner.address);
8459
- const wallet = (0, import_viem11.createWalletClient)({
8460
- account: owner,
8461
- chain,
8462
- transport: (0, import_viem11.http)()
8463
- });
8464
- return {
8465
- address,
8466
- signHash: (hash) => owner.sign({ hash }),
8467
- signTypedData: (params) => signAccountTypedData(owner, params),
8468
- sendTransaction: (tx) => wallet.sendTransaction({
8469
- account: owner,
8470
- chain,
8471
- to: tx.to,
8472
- data: tx.data,
8473
- value: tx.value
8474
- })
8475
- };
8476
- }
8477
- if (isWalletClient(owner)) {
8478
- const address = await walletClientAddress(owner);
8479
- return {
8480
- address,
8481
- signHash: (hash) => signOwnerHash(looseRequest(owner.request), owner.account, address, hash),
8482
- signTypedData: (params) => {
8483
- const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8484
- return owner.signTypedData({
8485
- account: owner.account ?? address,
8486
- domain,
8487
- types,
8488
- primaryType,
8489
- message
8490
- });
8491
- },
8492
- sendTransaction: (tx) => owner.sendTransaction({
8493
- account: owner.account ?? address,
8494
- chain: owner.chain ?? chain,
8495
- to: tx.to,
8496
- data: tx.data,
8497
- value: tx.value
8498
- })
8499
- };
8500
- }
8501
- if (isEip1193(owner)) {
8502
- const address = await eip1193Address(owner);
8503
- return {
8504
- address,
8505
- signHash: (hash) => signOwnerHash(looseRequest(owner.request), void 0, address, hash),
8506
- signTypedData: async (params) => {
8507
- const { requestPayload } = parseTypedDataPayload(params);
8508
- const signature = await owner.request({
8509
- method: "eth_signTypedData_v4",
8510
- params: [address, JSON.stringify(requestPayload)]
8511
- });
8512
- if (typeof signature !== "string" || !signature.startsWith("0x")) {
8513
- throw new Error("Owner wallet did not return a typed-data signature");
8514
- }
8515
- return signature;
8516
- },
8517
- sendTransaction: async (tx) => {
8518
- const hash = await owner.request({
8519
- method: "eth_sendTransaction",
8520
- params: [
8521
- {
8522
- from: address,
8523
- to: tx.to,
8524
- data: tx.data,
8525
- value: tx.value === 0n ? "0x0" : `0x${tx.value.toString(16)}`
8526
- }
8527
- ]
8528
- });
8529
- if (typeof hash !== "string" || !hash.startsWith("0x")) {
8530
- throw new Error("Owner wallet did not return a transaction hash");
8531
- }
8532
- return hash;
8533
- }
8534
- };
8535
- }
8536
- throw new Error(
8537
- "owner must be a viem wallet client, an account that can sign hashes, or an EIP-1193 provider"
8538
- );
8539
- }
8540
- function isWalletClient(owner) {
8541
- return typeof owner === "object" && owner !== null && "transport" in owner && "sendTransaction" in owner && typeof owner.sendTransaction === "function";
8542
- }
8543
- function isHashSigner(owner) {
8544
- return typeof owner === "object" && owner !== null && "address" in owner && "sign" in owner && typeof owner.sign === "function" && !("transport" in owner);
8545
- }
8546
- function isEip1193(owner) {
8547
- return typeof owner === "object" && owner !== null && "request" in owner && typeof owner.request === "function" && !("transport" in owner) && !isHashSigner(owner);
8548
- }
8549
- function looseRequest(request) {
8550
- return request;
8551
- }
8552
- async function walletClientAddress(owner) {
8553
- if (owner.account?.address && (0, import_viem11.isAddress)(owner.account.address)) {
8554
- return (0, import_viem11.getAddress)(owner.account.address);
8555
- }
8556
- return requestAccount(looseRequest(owner.request));
8557
- }
8558
- async function eip1193Address(owner) {
8559
- return requestAccount(looseRequest(owner.request));
8560
- }
8561
- async function requestAccount(request) {
8562
- const accounts = await request({ method: "eth_requestAccounts" });
8563
- const first = Array.isArray(accounts) ? accounts[0] : void 0;
8564
- if (typeof first !== "string" || !(0, import_viem11.isAddress)(first)) {
8565
- throw new Error("Owner wallet did not return an account");
8566
- }
8567
- return (0, import_viem11.getAddress)(first);
8568
- }
8569
- async function signOwnerHash(request, account, address, hash) {
8570
- if (account?.sign) {
8571
- return account.sign({ hash });
8572
- }
8573
- const signature = await request({
8574
- method: "personal_sign",
8575
- params: [hash, address]
8576
- });
8577
- if (typeof signature !== "string" || !signature.startsWith("0x")) {
8578
- throw new Error("Owner wallet did not return a signature");
8579
- }
8580
- return asSafeEthSign(signature);
8581
- }
8582
- function asSafeEthSign(signature) {
8583
- const sig = (0, import_viem11.hexToSignature)(signature);
8584
- const current = sig.v === void 0 ? sig.yParity === 1 ? 28 : 27 : Number(sig.v);
8585
- const v = current >= 27 ? current + 4 : current + 31;
8586
- return (0, import_viem11.signatureToHex)({ r: sig.r, s: sig.s, v: BigInt(v) });
8587
- }
8588
- function personalSignDigest(params) {
8589
- const [first, second] = params ?? [];
8590
- const message = typeof first === "string" && (0, import_viem11.isAddress)(first) ? second : first;
8591
- const hex = typeof message === "string" && message.startsWith("0x") ? message : (0, import_viem11.stringToHex)(String(message ?? ""));
8592
- return (0, import_viem11.hashMessage)({ raw: hex });
8593
- }
8594
- function parseTypedDataPayload(params) {
8595
- const [first, second] = params ?? [];
8596
- const payload = typeof first === "string" && (0, import_viem11.isAddress)(first) ? second : first;
8597
- const parsed = typeof payload === "string" ? JSON.parse(payload) : payload;
8598
- const types = { ...parsed.types };
8599
- delete types.EIP712Domain;
8600
- const domain = { ...parsed.domain ?? {} };
8601
- if (typeof domain.chainId === "string") {
8602
- domain.chainId = BigInt(domain.chainId);
8603
- }
8604
- const message = coerceEip712Value(
8605
- parsed.primaryType,
8606
- parsed.message,
8607
- types
8608
- );
8609
- return {
8610
- domain,
8611
- types,
8612
- primaryType: parsed.primaryType,
8613
- message,
8614
- requestPayload: parsed
8615
- };
8616
- }
8617
- function typedDataDigest(params) {
8618
- const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8619
- return (0, import_viem11.hashTypedData)({ domain, types, primaryType, message });
8620
- }
8621
- async function signAccountTypedData(account, params) {
8622
- const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8623
- if (!account.signTypedData) {
8624
- throw new Error("Owner account cannot sign typed data");
8625
- }
8626
- return account.signTypedData({
8627
- domain,
8628
- types,
8629
- primaryType,
8630
- message
8631
- });
8632
- }
8633
- function coerceEip712Value(type, value, types) {
8634
- if (value == null) return value;
8635
- const array = type.match(/^(.*)\[(\d*)\]$/);
8636
- if (array) {
8637
- if (!Array.isArray(value)) return value;
8638
- return value.map((item) => coerceEip712Value(array[1], item, types));
8639
- }
8640
- const struct = types[type];
8641
- if (struct) {
8642
- if (typeof value !== "object" || Array.isArray(value)) return value;
8643
- const record = value;
8644
- const next = {};
8645
- for (const field of struct) {
8646
- next[field.name] = coerceEip712Value(
8647
- field.type,
8648
- record[field.name],
8649
- types
8650
- );
8651
- }
8652
- return next;
8653
- }
8654
- if (/^u?int\d*$/.test(type)) {
8655
- if (typeof value === "bigint") return value;
8656
- if (typeof value === "string" || typeof value === "number") {
8657
- return BigInt(value);
8658
- }
8659
- }
8660
- return value;
8661
- }
8662
- function readSafeTransaction(params) {
8663
- const tx = Array.isArray(params) ? params[0] : void 0;
8664
- if (!tx?.to || !(0, import_viem11.isAddress)(tx.to)) {
8665
- throw new Error("Safe transaction is missing a destination");
8666
- }
8667
- const data = typeof tx.data === "string" && tx.data.startsWith("0x") ? tx.data : "0x";
8668
- let value = 0n;
8669
- if (typeof tx.value === "bigint") value = tx.value;
8670
- else if (typeof tx.value === "number" || typeof tx.value === "string") {
8671
- value = BigInt(tx.value);
8672
- }
8673
- return { to: (0, import_viem11.getAddress)(tx.to), data, value };
8674
- }
8675
8518
  // Annotate the CommonJS export names for ESM import in node:
8676
8519
  0 && (module.exports = {
8677
8520
  ALLOWED_HISTORY_DAYS,
@@ -8705,7 +8548,6 @@ function readSafeTransaction(params) {
8705
8548
  ZyfaiSDK,
8706
8549
  buildV1ChainSessions,
8707
8550
  createBankrProvider,
8708
- createSafeOwnerProvider,
8709
8551
  decodeUserOperationCalls,
8710
8552
  getChainConfig,
8711
8553
  getDataApiBaseUrl,