@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.mjs CHANGED
@@ -1632,6 +1632,36 @@ var getAccountType = async (address, publicClient) => {
1632
1632
  return "Unknown";
1633
1633
  }
1634
1634
  };
1635
+ var signNestedSafeDeployTypedData = async (owner, parentSafe, typedData) => {
1636
+ if (!owner.account) {
1637
+ throw new Error("Wallet not connected. Please connect your wallet first.");
1638
+ }
1639
+ return owner.signTypedData({
1640
+ account: parentSafe,
1641
+ domain: typedData.domain,
1642
+ types: typedData.types,
1643
+ primaryType: typedData.primaryType,
1644
+ message: typedData.message
1645
+ });
1646
+ };
1647
+ var TYPED_DATA_DEPLOY_TIMEOUT_MS = 18e4;
1648
+ var completeSafeDeploy = async (config, strategyBody, body, requestConfig) => {
1649
+ const deployResponse = await config.httpClient.post(
1650
+ `${ENDPOINTS.SAFE_DEPLOY}?chainId=${config.chainId}`,
1651
+ { ...body, ...strategyBody },
1652
+ requestConfig
1653
+ );
1654
+ if (!deployResponse.success) {
1655
+ throw new Error(
1656
+ `Safe deployment failed: ${JSON.stringify(deployResponse)}`
1657
+ );
1658
+ }
1659
+ return {
1660
+ safeAddress: deployResponse.safeAddress || "0x",
1661
+ txHash: deployResponse.txHash,
1662
+ isDeployed: true
1663
+ };
1664
+ };
1635
1665
  var deploySafeAccount = async (config) => {
1636
1666
  try {
1637
1667
  const {
@@ -1654,16 +1684,38 @@ var deploySafeAccount = async (config) => {
1654
1684
  strategyBody
1655
1685
  );
1656
1686
  console.log("prepareResponse", prepareResponse);
1657
- if (prepareResponse.success && !prepareResponse.userOpHashToSign) {
1687
+ if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1658
1688
  return {
1659
1689
  safeAddress: prepareResponse.safeAddress || "0x",
1660
1690
  txHash: "0x0",
1661
1691
  isDeployed: true
1662
1692
  };
1663
1693
  }
1694
+ if (prepareResponse.signingMode === "typed-data") {
1695
+ if (!prepareResponse.typedData) {
1696
+ throw new Error(
1697
+ "Backend returned signingMode typed-data without typedData. Response: " + JSON.stringify(prepareResponse)
1698
+ );
1699
+ }
1700
+ const parentSafe = getAddress2(safeOwnerAddress);
1701
+ console.info(
1702
+ `[ZyfaiSDK] safe-deploy typed-data chainId=${chainId} owner=${parentSafe}`
1703
+ );
1704
+ const typedDataSignature = await signNestedSafeDeployTypedData(
1705
+ owner,
1706
+ parentSafe,
1707
+ prepareResponse.typedData
1708
+ );
1709
+ return completeSafeDeploy(
1710
+ config,
1711
+ strategyBody,
1712
+ { typedDataSignature },
1713
+ { timeout: TYPED_DATA_DEPLOY_TIMEOUT_MS }
1714
+ );
1715
+ }
1664
1716
  if (!prepareResponse.userOpHashToSign) {
1665
1717
  throw new Error(
1666
- "Backend did not return userOpHashToSign. Response: " + JSON.stringify(prepareResponse)
1718
+ "Backend did not return userOpHashToSign or typed-data to sign. Response: " + JSON.stringify(prepareResponse)
1667
1719
  );
1668
1720
  }
1669
1721
  const userOpHashToSign = prepareResponse.userOpHashToSign;
@@ -1691,20 +1743,9 @@ var deploySafeAccount = async (config) => {
1691
1743
  isContractSignature: true
1692
1744
  }
1693
1745
  ]) : userOpSignature;
1694
- const deployResponse = await httpClient.post(
1695
- `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1696
- { userOpSignature: signatureToSubmit, ...strategyBody }
1697
- );
1698
- if (!deployResponse.success) {
1699
- throw new Error(
1700
- `Safe deployment failed: ${JSON.stringify(deployResponse)}`
1701
- );
1702
- }
1703
- return {
1704
- safeAddress: deployResponse.safeAddress || "0x",
1705
- txHash: deployResponse.txHash,
1706
- isDeployed: true
1707
- };
1746
+ return completeSafeDeploy(config, strategyBody, {
1747
+ userOpSignature: signatureToSubmit
1748
+ });
1708
1749
  } catch (error) {
1709
1750
  throw new Error(
1710
1751
  `Failed to deploy Safe account: ${error.message}`
@@ -2528,7 +2569,7 @@ var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
2528
2569
  };
2529
2570
 
2530
2571
  // src/core/ZyfaiSDK.ts
2531
- import { SiweMessage } from "siwe";
2572
+ import { createSiweMessage } from "viem/siwe";
2532
2573
  var DepositCreditTimeoutError = class extends Error {
2533
2574
  constructor(depositId) {
2534
2575
  super(`Timed out waiting for deposit ${depositId} to be credited`);
@@ -2600,6 +2641,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2600
2641
  this.currentChainId = null;
2601
2642
  /** EOA of the active user session (bearer or SIWE). Cleared on disconnect. */
2602
2643
  this.sessionEoa = null;
2644
+ /** Serialize concurrent connectAccount calls (e.g. React StrictMode double mount). */
2645
+ this.connectAccountInFlight = null;
2646
+ /** One SIWE prompt at a time. Register must not send a second personal_sign. */
2647
+ this.authenticateUserInFlight = null;
2603
2648
  const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
2604
2649
  const {
2605
2650
  apiKey,
@@ -2724,16 +2769,33 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2724
2769
  *
2725
2770
  * @returns Promise that resolves when authentication is complete
2726
2771
  */
2727
- async authenticateUser() {
2772
+ authenticateUser() {
2773
+ if (this.authenticatedUserId !== null || this.httpClient.hasAuthToken()) {
2774
+ return Promise.resolve();
2775
+ }
2776
+ if (!this.authenticateUserInFlight) {
2777
+ this.authenticateUserInFlight = this.performAuthenticateUser().finally(
2778
+ () => {
2779
+ this.authenticateUserInFlight = null;
2780
+ }
2781
+ );
2782
+ }
2783
+ return this.authenticateUserInFlight;
2784
+ }
2785
+ async performAuthenticateUser() {
2728
2786
  try {
2729
- if (this.authenticatedUserId !== null) {
2730
- return;
2731
- }
2732
- if (this.httpClient.hasAuthToken()) {
2787
+ if (this.authenticatedUserId !== null || this.httpClient.hasAuthToken()) {
2733
2788
  return;
2734
2789
  }
2735
2790
  const walletClient = this.getWalletClient();
2736
- const userAddress = getAddress4(walletClient.account.address);
2791
+ const rawAccount = walletClient.account;
2792
+ const connected = typeof rawAccount === "string" ? rawAccount : rawAccount?.address;
2793
+ if (!connected) {
2794
+ throw new Error(
2795
+ "Wallet account address is missing. Call connectAccount() after the wallet is connected."
2796
+ );
2797
+ }
2798
+ const userAddress = getAddress4(connected);
2737
2799
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
2738
2800
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
2739
2801
  let uri;
@@ -2747,7 +2809,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2747
2809
  uri = this.executionApiUrl;
2748
2810
  domain = new URL(this.executionApiUrl).host;
2749
2811
  }
2750
- const messageObj = new SiweMessage({
2812
+ const issuedAt = /* @__PURE__ */ new Date();
2813
+ const messageFields = {
2751
2814
  address: userAddress,
2752
2815
  chainId,
2753
2816
  domain,
@@ -2755,11 +2818,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2755
2818
  statement: "Sign in with Ethereum",
2756
2819
  uri,
2757
2820
  version: "1",
2758
- issuedAt: (/* @__PURE__ */ new Date()).toISOString()
2759
- });
2760
- const messageString = messageObj.prepareMessage();
2821
+ issuedAt
2822
+ };
2823
+ const messageString = createSiweMessage(messageFields);
2824
+ const messageObj = {
2825
+ ...messageFields,
2826
+ issuedAt: issuedAt.toISOString()
2827
+ };
2761
2828
  const signature = await walletClient.signMessage({
2762
- account: walletClient.account,
2829
+ account: userAddress,
2763
2830
  message: messageString
2764
2831
  });
2765
2832
  const loginResponse = await this.httpClient.post(
@@ -2847,6 +2914,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2847
2914
  [internalAsset]: assetSettings
2848
2915
  }
2849
2916
  };
2917
+ if (request.smartWallet !== void 0)
2918
+ payload.smartWallet = request.smartWallet;
2919
+ if (request.executorProxy !== void 0)
2920
+ payload.executorProxy = request.executorProxy;
2921
+ if (request.chains !== void 0) payload.chains = request.chains;
2850
2922
  if (request.omniAccount !== void 0)
2851
2923
  payload.omniAccount = request.omniAccount;
2852
2924
  if (request.agentName !== void 0)
@@ -3152,82 +3224,167 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3152
3224
  * const provider = await connector.getProvider();
3153
3225
  * await sdk.connectAccount(provider);
3154
3226
  */
3155
- async connectAccount(account, chainId = 8453) {
3156
- if (!isSupportedChain(chainId)) {
3157
- throw new Error(`Unsupported chain ID: ${chainId}`);
3158
- }
3159
- this.authenticatedUserId = null;
3160
- this.isPredeployed = false;
3161
- this.predeployedResolved = false;
3162
- this.connectedSmartWallet = null;
3163
- this.currentChainId = null;
3164
- this.sessionEoa = null;
3165
- this.sessionChannel = void 0;
3166
- this.httpClient.clearAuthToken();
3167
- if (this.currentProvider?.removeAllListeners) {
3168
- try {
3169
- this.currentProvider.removeAllListeners("accountsChanged");
3170
- } catch (error) {
3171
- }
3172
- }
3173
- const chainConfig = getChainConfig(chainId, this.rpcUrls);
3174
- let connectedAddress;
3227
+ async resolveConnectAddress(account) {
3175
3228
  if (typeof account === "string") {
3176
3229
  let privateKey = account;
3177
3230
  if (!privateKey.startsWith("0x")) {
3178
3231
  privateKey = `0x${privateKey}`;
3179
3232
  }
3180
- this.signer = privateKeyToAccount(privateKey);
3181
- this.currentChainId = chainId;
3182
- this.walletClient = createWalletClient({
3183
- account: this.signer,
3184
- chain: chainConfig.chain,
3185
- transport: http2(chainConfig.rpcUrl)
3233
+ return privateKeyToAccount(privateKey).address;
3234
+ }
3235
+ const provider = account;
3236
+ if (!provider) {
3237
+ throw new Error(
3238
+ "Invalid account parameter. Expected private key string or wallet provider."
3239
+ );
3240
+ }
3241
+ if (provider.account && provider.transport) {
3242
+ const accountField = provider.account;
3243
+ const resolvedAddress = typeof accountField === "string" ? accountField : accountField.address;
3244
+ if (!resolvedAddress) {
3245
+ throw new Error("Wallet client is missing account address");
3246
+ }
3247
+ return getAddress4(resolvedAddress);
3248
+ }
3249
+ if (provider.request) {
3250
+ const eip1193 = typeof provider.request === "function" ? provider : typeof provider.provider?.request === "function" ? provider.provider : null;
3251
+ if (!eip1193) {
3252
+ throw new Error(
3253
+ "Wallet provider has no EIP-1193 request method. Pass the connector getProvider() result."
3254
+ );
3255
+ }
3256
+ const accounts = await eip1193.request({
3257
+ method: "eth_accounts"
3186
3258
  });
3187
- connectedAddress = this.signer.address;
3188
- this.currentProvider = null;
3189
- } else {
3190
- const provider = account;
3191
- if (!provider) {
3259
+ const fallbackAccounts = accounts?.length > 0 ? accounts : await eip1193.request({
3260
+ method: "eth_requestAccounts"
3261
+ });
3262
+ const raw = fallbackAccounts?.[0];
3263
+ const accountAddress = typeof raw === "string" ? raw : typeof raw?.address === "string" ? raw.address : void 0;
3264
+ if (!accountAddress) {
3192
3265
  throw new Error(
3193
- "Invalid account parameter. Expected private key string or wallet provider."
3266
+ "Wallet returned an account without an address. Reconnect via WalletConnect."
3194
3267
  );
3195
3268
  }
3196
- if (provider.request) {
3197
- const accounts = await provider.request({
3198
- method: "eth_requestAccounts"
3199
- });
3200
- if (!accounts || accounts.length === 0) {
3201
- throw new Error("No accounts found in wallet provider");
3269
+ return getAddress4(accountAddress);
3270
+ }
3271
+ throw new Error(
3272
+ "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3273
+ );
3274
+ }
3275
+ async connectAccount(account, chainId = 8453) {
3276
+ if (!isSupportedChain(chainId)) {
3277
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3278
+ }
3279
+ const resolvedAddress = await this.resolveConnectAddress(account);
3280
+ if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && isAddressEqual2(resolvedAddress, this.sessionEoa)) {
3281
+ this.currentChainId = chainId;
3282
+ return resolvedAddress;
3283
+ }
3284
+ if (this.connectAccountInFlight) {
3285
+ return this.connectAccountInFlight;
3286
+ }
3287
+ const connect = (async () => {
3288
+ this.authenticatedUserId = null;
3289
+ this.isPredeployed = false;
3290
+ this.predeployedResolved = false;
3291
+ this.connectedSmartWallet = null;
3292
+ this.currentChainId = null;
3293
+ this.sessionEoa = null;
3294
+ this.sessionChannel = void 0;
3295
+ this.httpClient.clearAuthToken();
3296
+ if (this.currentProvider?.removeAllListeners) {
3297
+ try {
3298
+ this.currentProvider.removeAllListeners("accountsChanged");
3299
+ } catch (error) {
3202
3300
  }
3203
- this.walletClient = createWalletClient({
3204
- account: accounts[0],
3205
- chain: chainConfig.chain,
3206
- transport: custom(provider)
3207
- });
3208
- connectedAddress = accounts[0];
3209
- this.currentProvider = provider;
3210
- this.currentChainId = chainId;
3211
- if (provider.on) {
3212
- provider.on("accountsChanged", this.handleAccountsChanged.bind(this));
3301
+ }
3302
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3303
+ let connectedAddress;
3304
+ if (typeof account === "string") {
3305
+ let privateKey = account;
3306
+ if (!privateKey.startsWith("0x")) {
3307
+ privateKey = `0x${privateKey}`;
3213
3308
  }
3214
- } else if (provider.account && provider.transport) {
3309
+ this.signer = privateKeyToAccount(privateKey);
3310
+ this.currentChainId = chainId;
3215
3311
  this.walletClient = createWalletClient({
3216
- account: provider.account,
3312
+ account: this.signer,
3217
3313
  chain: chainConfig.chain,
3218
- transport: provider.transport
3314
+ transport: http2(chainConfig.rpcUrl)
3219
3315
  });
3220
- connectedAddress = provider.account.address;
3316
+ connectedAddress = this.signer.address;
3221
3317
  this.currentProvider = null;
3222
- this.currentChainId = chainId;
3223
3318
  } else {
3224
- throw new Error(
3225
- "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3226
- );
3319
+ const provider = account;
3320
+ if (!provider) {
3321
+ throw new Error(
3322
+ "Invalid account parameter. Expected private key string or wallet provider."
3323
+ );
3324
+ }
3325
+ if (provider.account && provider.transport) {
3326
+ const accountField = provider.account;
3327
+ const resolvedAddress2 = typeof accountField === "string" ? accountField : accountField.address;
3328
+ if (!resolvedAddress2) {
3329
+ throw new Error("Wallet client is missing account address");
3330
+ }
3331
+ const hasSignMessage = typeof provider.signMessage === "function" && typeof provider.request === "function";
3332
+ this.walletClient = hasSignMessage ? provider : createWalletClient({
3333
+ account: provider.account,
3334
+ chain: chainConfig.chain,
3335
+ transport: provider.transport
3336
+ });
3337
+ connectedAddress = getAddress4(resolvedAddress2);
3338
+ this.currentProvider = null;
3339
+ this.currentChainId = chainId;
3340
+ } else if (provider.request) {
3341
+ const eip1193 = typeof provider.request === "function" ? provider : typeof provider.provider?.request === "function" ? provider.provider : null;
3342
+ if (!eip1193) {
3343
+ throw new Error(
3344
+ "Wallet provider has no EIP-1193 request method. Pass the connector getProvider() result."
3345
+ );
3346
+ }
3347
+ const accounts = await eip1193.request({
3348
+ method: "eth_requestAccounts"
3349
+ });
3350
+ if (!accounts || accounts.length === 0) {
3351
+ throw new Error("No accounts found in wallet provider");
3352
+ }
3353
+ const raw = accounts[0];
3354
+ const accountAddress = typeof raw === "string" ? raw : typeof raw?.address === "string" ? raw.address : void 0;
3355
+ if (!accountAddress) {
3356
+ throw new Error(
3357
+ "Wallet returned an account without an address. Reconnect via WalletConnect."
3358
+ );
3359
+ }
3360
+ connectedAddress = getAddress4(accountAddress);
3361
+ this.walletClient = createWalletClient({
3362
+ account: connectedAddress,
3363
+ chain: chainConfig.chain,
3364
+ transport: custom(eip1193)
3365
+ });
3366
+ this.currentProvider = eip1193;
3367
+ this.currentChainId = chainId;
3368
+ if (provider.on) {
3369
+ provider.on("accountsChanged", this.handleAccountsChanged.bind(this));
3370
+ }
3371
+ } else {
3372
+ throw new Error(
3373
+ "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3374
+ );
3375
+ }
3376
+ }
3377
+ await this.authenticateUser();
3378
+ return connectedAddress;
3379
+ })();
3380
+ this.connectAccountInFlight = connect;
3381
+ try {
3382
+ return await connect;
3383
+ } finally {
3384
+ if (this.connectAccountInFlight === connect) {
3385
+ this.connectAccountInFlight = null;
3227
3386
  }
3228
3387
  }
3229
- await this.authenticateUser();
3230
- return connectedAddress;
3231
3388
  }
3232
3389
  /**
3233
3390
  * Clear the connected wallet, SIWE session, and cached smart-wallet state.
@@ -3293,6 +3450,51 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3293
3450
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3294
3451
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
3295
3452
  }
3453
+ /**
3454
+ * Nested Safe owners use intent sessions: finish any pending safe-deploy typed-data
3455
+ * (install or emissary enable), then register with chainId only.
3456
+ * @private
3457
+ */
3458
+ async registerNestedIntentSessionKey(userAddress, chainId, strategy) {
3459
+ if (!this.authenticatedUserId) {
3460
+ throw new Error(
3461
+ "User ID not available. Please ensure authentication completed successfully."
3462
+ );
3463
+ }
3464
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3465
+ await deploySafeAccount({
3466
+ owner: this.getWalletClient(chainId),
3467
+ safeOwnerAddress: userAddress,
3468
+ chain: chainConfig.chain,
3469
+ publicClient: chainConfig.publicClient,
3470
+ chainId,
3471
+ httpClient: this.httpClient,
3472
+ strategy
3473
+ });
3474
+ const activation = await this.httpClient.post(
3475
+ ENDPOINTS.SESSION_KEYS_ADD,
3476
+ { chainId }
3477
+ );
3478
+ this.hasActiveSessionKey = true;
3479
+ return {
3480
+ success: true,
3481
+ userId: this.authenticatedUserId,
3482
+ message: "Intent session key registered",
3483
+ alreadyActive: false,
3484
+ sessionActivation: activation
3485
+ };
3486
+ }
3487
+ async registerNestedChildProfile(childAddress, chainId, strategy) {
3488
+ await this.updateUserProfile({
3489
+ smartWallet: childAddress,
3490
+ executorProxy: true,
3491
+ chains: [chainId],
3492
+ strategy,
3493
+ protocols: [],
3494
+ autoSelectProtocols: false,
3495
+ asset: "USDC"
3496
+ });
3497
+ }
3296
3498
  /**
3297
3499
  * SIWE login sets predeployed. Agent sessions (`forUser`) do not, so read it
3298
3500
  * from the user record before allowing a transfer to an undeployed pool Safe.
@@ -3316,13 +3518,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3316
3518
  chainId
3317
3519
  );
3318
3520
  const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3319
- if (!childAddress) {
3320
- throw new Error("Child smart wallet address is not available");
3321
- }
3322
- const childDeployed = await isSafeDeployed(
3323
- childAddress,
3324
- chainConfig.publicClient
3325
- );
3521
+ const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3326
3522
  if (!childDeployed) {
3327
3523
  await this.deploySafe(userAddress, chainId, strategy, true);
3328
3524
  return;
@@ -3375,6 +3571,25 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3375
3571
  }
3376
3572
  if (!deriveIfMissing) return null;
3377
3573
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3574
+ const ownerType = await getAccountType(
3575
+ userAddress,
3576
+ chainConfig.publicClient
3577
+ );
3578
+ if (ownerType === "Safe") {
3579
+ if (this.isConnectedUser(userAddress) && this.connectedSmartWallet) {
3580
+ return this.connectedSmartWallet;
3581
+ }
3582
+ try {
3583
+ if (this.httpClient.hasAuthToken()) {
3584
+ const me = await this.httpClient.get(
3585
+ ENDPOINTS.USER_ME
3586
+ );
3587
+ if (me?.smartWallet) return getAddress4(me.smartWallet);
3588
+ }
3589
+ } catch {
3590
+ }
3591
+ return null;
3592
+ }
3378
3593
  return getDeterministicSafeAddress({
3379
3594
  safeOwnerAddress: userAddress,
3380
3595
  chain: chainConfig.chain,
@@ -3404,8 +3619,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3404
3619
  throw new Error(`Unsupported chain ID: ${chainId}`);
3405
3620
  }
3406
3621
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3622
+ const ownerType = await getAccountType(
3623
+ userAddress,
3624
+ chainConfig.publicClient
3625
+ );
3407
3626
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3408
3627
  if (!safeAddress) {
3628
+ if (ownerType === "Safe") {
3629
+ throw new Error("NESTED_CHILD_UNREGISTERED");
3630
+ }
3409
3631
  throw new Error("Smart wallet address is not available");
3410
3632
  }
3411
3633
  const isDeployed = await isSafeDeployed(
@@ -3490,15 +3712,19 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3490
3712
  }
3491
3713
  const walletClient = this.getWalletClient(chainId);
3492
3714
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3493
- const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3494
- if (!safeAddress) {
3495
- throw new Error("Smart wallet address is not available");
3496
- }
3497
- const alreadyDeployed = await isSafeDeployed(
3498
- safeAddress,
3715
+ const ownerAccountType = await getAccountType(
3716
+ userAddress,
3499
3717
  chainConfig.publicClient
3500
3718
  );
3501
- if (alreadyDeployed) {
3719
+ const nestedSafeOwner = ownerAccountType === "Safe";
3720
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3721
+ if (!safeAddress && !nestedSafeOwner) {
3722
+ throw new Error(
3723
+ ownerAccountType === "EOA" ? "For nested deploy, connect WalletConnect as the parent Safe contract address, not the owner EOA." : "Smart wallet address is not available"
3724
+ );
3725
+ }
3726
+ const alreadyDeployed = safeAddress ? await isSafeDeployed(safeAddress, chainConfig.publicClient) : false;
3727
+ if (alreadyDeployed && safeAddress) {
3502
3728
  let enableTxHash = "0x0";
3503
3729
  if (!this.isPredeployed) {
3504
3730
  const enabled = await deploySafeAccount({
@@ -3508,7 +3734,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3508
3734
  publicClient: chainConfig.publicClient,
3509
3735
  chainId,
3510
3736
  httpClient: this.httpClient,
3511
- strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy"
3737
+ strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy",
3738
+ childSafeAddress: safeAddress
3512
3739
  });
3513
3740
  enableTxHash = enabled.txHash || "0x0";
3514
3741
  }
@@ -3541,7 +3768,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3541
3768
  publicClient: chainConfig.publicClient,
3542
3769
  chainId,
3543
3770
  httpClient: this.httpClient,
3544
- strategy: internalStrategy
3771
+ strategy: internalStrategy,
3772
+ childSafeAddress: safeAddress ?? void 0
3545
3773
  });
3546
3774
  this.hasActiveSessionKey = false;
3547
3775
  try {
@@ -3552,8 +3780,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3552
3780
  initError.message
3553
3781
  );
3554
3782
  }
3783
+ if (nestedSafeOwner) {
3784
+ await this.registerNestedChildProfile(
3785
+ deploymentResult.safeAddress,
3786
+ chainId,
3787
+ strategy
3788
+ );
3789
+ }
3555
3790
  await this.updateUserProtocols(strategy);
3556
- if (!this.isPredeployed) {
3791
+ if (!this.isPredeployed && !nestedSafeOwner) {
3557
3792
  await deploySafeAccount({
3558
3793
  owner: walletClient,
3559
3794
  safeOwnerAddress: userAddress,
@@ -3561,7 +3796,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3561
3796
  publicClient: chainConfig.publicClient,
3562
3797
  chainId,
3563
3798
  httpClient: this.httpClient,
3564
- strategy: internalStrategy
3799
+ strategy: internalStrategy,
3800
+ childSafeAddress: deploymentResult.safeAddress
3565
3801
  });
3566
3802
  }
3567
3803
  let sessionKeyCreated = false;
@@ -3664,14 +3900,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3664
3900
  chainConfig.publicClient
3665
3901
  );
3666
3902
  if (accountType === "Safe") {
3667
- await this.assertOwnerSafeOnSessionChains(
3903
+ return this.registerNestedIntentSessionKey(
3668
3904
  userAddress,
3669
- sessions
3905
+ chainId,
3906
+ void 0
3670
3907
  );
3671
3908
  }
3672
3909
  const signingParams = {
3673
3910
  permitGenericPolicy,
3674
- ignoreSecurityAttestations: accountType === "Safe"
3911
+ ignoreSecurityAttestations: false
3675
3912
  };
3676
3913
  const signatureResult = await this.signSessionKey(
3677
3914
  userAddress,
@@ -3701,38 +3938,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3701
3938
  }
3702
3939
  }
3703
3940
  /**
3704
- * Internal method to sign session key
3941
+ * Internal method to sign session key for an EOA owner.
3942
+ * Nested Safe owners register through {@link registerNestedIntentSessionKey}.
3705
3943
  * @private
3706
3944
  */
3707
- /**
3708
- * A nested Safe owner signs one MultiChainSession covering every chain in the
3709
- * session configuration, and the child validates that signature against the
3710
- * owner through ERC-1271 on each of them. A chain where the owner has no code
3711
- * would accept the signature nowhere, so refuse rather than sign it.
3712
- *
3713
- * The session list is not filtered here: the execution API rebuilds the digest
3714
- * from its own configuration, so dropping a chain client-side would change the
3715
- * hash and the signature would be rejected everywhere.
3716
- * @private
3717
- */
3718
- async assertOwnerSafeOnSessionChains(ownerAddress, sessions) {
3719
- const chainIds = [
3720
- ...new Set(sessions.map((session) => Number(session.chainId)))
3721
- ].filter(isSupportedChain);
3722
- const missing = [];
3723
- await Promise.all(
3724
- chainIds.map(async (id) => {
3725
- const { publicClient } = getChainConfig(id, this.rpcUrls);
3726
- const code = await publicClient.getCode({ address: ownerAddress });
3727
- if (!code || code === "0x") missing.push(id);
3728
- })
3729
- );
3730
- if (missing.length > 0) {
3731
- throw new Error(
3732
- `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.`
3733
- );
3734
- }
3735
- }
3736
3945
  async signSessionKey(userAddress, chainId, sessions, signingParams) {
3737
3946
  try {
3738
3947
  if (!userAddress) {
@@ -8274,385 +8483,6 @@ function createBankrProvider(config) {
8274
8483
  };
8275
8484
  return provider;
8276
8485
  }
8277
-
8278
- // src/providers/safe-owner.ts
8279
- import {
8280
- createPublicClient as createPublicClient2,
8281
- createWalletClient as createWalletClient2,
8282
- encodeAbiParameters as encodeAbiParameters2,
8283
- encodeFunctionData as encodeFunctionData3,
8284
- getAddress as getAddress5,
8285
- hashMessage as hashMessage2,
8286
- hashTypedData as hashTypedData2,
8287
- hexToSignature,
8288
- http as http3,
8289
- isAddress as isAddress3,
8290
- parseAbi as parseAbi3,
8291
- signatureToHex,
8292
- stringToHex
8293
- } from "viem";
8294
- var EIP1271_MAGIC_VALUE = "0x1626ba7e";
8295
- var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
8296
- var SAFE_ABI2 = parseAbi3([
8297
- "function getThreshold() view returns (uint256)",
8298
- "function getOwners() view returns (address[])",
8299
- "function nonce() view returns (uint256)",
8300
- "function getMessageHash(bytes message) view returns (bytes32)",
8301
- "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)",
8302
- "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)",
8303
- "function isValidSignature(bytes32 _dataHash, bytes _signature) view returns (bytes4)"
8304
- ]);
8305
- async function createSafeOwnerProvider(config) {
8306
- if (!isAddress3(config.safeAddress)) {
8307
- throw new Error("safeAddress must be an Ethereum address");
8308
- }
8309
- const safeAddress = getAddress5(config.safeAddress);
8310
- const publicClient = createPublicClient2({
8311
- chain: config.chain,
8312
- transport: http3()
8313
- });
8314
- const ownerWallet = await resolveOwnerWallet(config.owner, config.chain);
8315
- const code = await publicClient.getCode({ address: safeAddress });
8316
- if (!code || code === "0x") {
8317
- throw new Error(
8318
- `Safe ${safeAddress} has no code on chain ${config.chain.id}`
8319
- );
8320
- }
8321
- const [threshold, owners] = await Promise.all([
8322
- publicClient.readContract({
8323
- address: safeAddress,
8324
- abi: SAFE_ABI2,
8325
- functionName: "getThreshold"
8326
- }),
8327
- publicClient.readContract({
8328
- address: safeAddress,
8329
- abi: SAFE_ABI2,
8330
- functionName: "getOwners"
8331
- })
8332
- ]);
8333
- if (threshold !== 1n) {
8334
- throw new Error(
8335
- `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.`
8336
- );
8337
- }
8338
- const ownerAddress = ownerWallet.address;
8339
- if (!owners.some((owner) => getAddress5(owner) === ownerAddress)) {
8340
- throw new Error(`${ownerAddress} is not an owner of Safe ${safeAddress}`);
8341
- }
8342
- const signSafeDigest = async (dataHash) => {
8343
- const encoded = encodeAbiParameters2([{ type: "bytes32" }], [dataHash]);
8344
- const messageHash = await publicClient.readContract({
8345
- address: safeAddress,
8346
- abi: SAFE_ABI2,
8347
- functionName: "getMessageHash",
8348
- args: [encoded]
8349
- });
8350
- return ownerWallet.signHash(messageHash);
8351
- };
8352
- const probeHash = hashMessage2("zyfai safe owner");
8353
- const probeSignature = await signSafeDigest(probeHash);
8354
- const magic = await publicClient.readContract({
8355
- address: safeAddress,
8356
- abi: SAFE_ABI2,
8357
- functionName: "isValidSignature",
8358
- args: [probeHash, probeSignature]
8359
- });
8360
- if (magic.toLowerCase() !== EIP1271_MAGIC_VALUE) {
8361
- throw new Error(
8362
- `Safe ${safeAddress} rejected the owner signature (isValidSignature returned ${magic})`
8363
- );
8364
- }
8365
- const executeFromSafe = async (tx) => {
8366
- const nonce = await publicClient.readContract({
8367
- address: safeAddress,
8368
- abi: SAFE_ABI2,
8369
- functionName: "nonce"
8370
- });
8371
- const safeTxHash = await publicClient.readContract({
8372
- address: safeAddress,
8373
- abi: SAFE_ABI2,
8374
- functionName: "getTransactionHash",
8375
- args: [
8376
- tx.to,
8377
- tx.value,
8378
- tx.data,
8379
- 0,
8380
- 0n,
8381
- 0n,
8382
- 0n,
8383
- ZERO_ADDRESS,
8384
- ZERO_ADDRESS,
8385
- nonce
8386
- ]
8387
- });
8388
- const signature = await ownerWallet.signHash(safeTxHash);
8389
- const data = encodeFunctionData3({
8390
- abi: SAFE_ABI2,
8391
- functionName: "execTransaction",
8392
- args: [
8393
- tx.to,
8394
- tx.value,
8395
- tx.data,
8396
- 0,
8397
- 0n,
8398
- 0n,
8399
- 0n,
8400
- ZERO_ADDRESS,
8401
- ZERO_ADDRESS,
8402
- signature
8403
- ]
8404
- });
8405
- const hash = await ownerWallet.sendTransaction({
8406
- to: safeAddress,
8407
- data,
8408
- value: 0n
8409
- });
8410
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
8411
- if (receipt.status !== "success") {
8412
- throw new Error(`Safe transaction reverted: ${hash}`);
8413
- }
8414
- return hash;
8415
- };
8416
- return {
8417
- async request({ method, params }) {
8418
- if (method === "eth_requestAccounts" || method === "eth_accounts") {
8419
- return [safeAddress];
8420
- }
8421
- if (method === "personal_sign" || method === "eth_sign") {
8422
- return signSafeDigest(personalSignDigest(params));
8423
- }
8424
- if (method === "eth_signTypedData_v4" || method === "eth_signTypedData") {
8425
- return signSafeDigest(typedDataDigest(params));
8426
- }
8427
- if (method === "eth_sendTransaction" || method === "wallet_sendTransaction") {
8428
- return executeFromSafe(readSafeTransaction(params));
8429
- }
8430
- return publicClient.request({
8431
- method,
8432
- params: params ?? []
8433
- });
8434
- }
8435
- };
8436
- }
8437
- async function resolveOwnerWallet(owner, chain) {
8438
- if (isHashSigner(owner)) {
8439
- const address = getAddress5(owner.address);
8440
- const wallet = createWalletClient2({
8441
- account: owner,
8442
- chain,
8443
- transport: http3()
8444
- });
8445
- return {
8446
- address,
8447
- signHash: (hash) => owner.sign({ hash }),
8448
- signTypedData: (params) => signAccountTypedData(owner, params),
8449
- sendTransaction: (tx) => wallet.sendTransaction({
8450
- account: owner,
8451
- chain,
8452
- to: tx.to,
8453
- data: tx.data,
8454
- value: tx.value
8455
- })
8456
- };
8457
- }
8458
- if (isWalletClient(owner)) {
8459
- const address = await walletClientAddress(owner);
8460
- return {
8461
- address,
8462
- signHash: (hash) => signOwnerHash(looseRequest(owner.request), owner.account, address, hash),
8463
- signTypedData: (params) => {
8464
- const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8465
- return owner.signTypedData({
8466
- account: owner.account ?? address,
8467
- domain,
8468
- types,
8469
- primaryType,
8470
- message
8471
- });
8472
- },
8473
- sendTransaction: (tx) => owner.sendTransaction({
8474
- account: owner.account ?? address,
8475
- chain: owner.chain ?? chain,
8476
- to: tx.to,
8477
- data: tx.data,
8478
- value: tx.value
8479
- })
8480
- };
8481
- }
8482
- if (isEip1193(owner)) {
8483
- const address = await eip1193Address(owner);
8484
- return {
8485
- address,
8486
- signHash: (hash) => signOwnerHash(looseRequest(owner.request), void 0, address, hash),
8487
- signTypedData: async (params) => {
8488
- const { requestPayload } = parseTypedDataPayload(params);
8489
- const signature = await owner.request({
8490
- method: "eth_signTypedData_v4",
8491
- params: [address, JSON.stringify(requestPayload)]
8492
- });
8493
- if (typeof signature !== "string" || !signature.startsWith("0x")) {
8494
- throw new Error("Owner wallet did not return a typed-data signature");
8495
- }
8496
- return signature;
8497
- },
8498
- sendTransaction: async (tx) => {
8499
- const hash = await owner.request({
8500
- method: "eth_sendTransaction",
8501
- params: [
8502
- {
8503
- from: address,
8504
- to: tx.to,
8505
- data: tx.data,
8506
- value: tx.value === 0n ? "0x0" : `0x${tx.value.toString(16)}`
8507
- }
8508
- ]
8509
- });
8510
- if (typeof hash !== "string" || !hash.startsWith("0x")) {
8511
- throw new Error("Owner wallet did not return a transaction hash");
8512
- }
8513
- return hash;
8514
- }
8515
- };
8516
- }
8517
- throw new Error(
8518
- "owner must be a viem wallet client, an account that can sign hashes, or an EIP-1193 provider"
8519
- );
8520
- }
8521
- function isWalletClient(owner) {
8522
- return typeof owner === "object" && owner !== null && "transport" in owner && "sendTransaction" in owner && typeof owner.sendTransaction === "function";
8523
- }
8524
- function isHashSigner(owner) {
8525
- return typeof owner === "object" && owner !== null && "address" in owner && "sign" in owner && typeof owner.sign === "function" && !("transport" in owner);
8526
- }
8527
- function isEip1193(owner) {
8528
- return typeof owner === "object" && owner !== null && "request" in owner && typeof owner.request === "function" && !("transport" in owner) && !isHashSigner(owner);
8529
- }
8530
- function looseRequest(request) {
8531
- return request;
8532
- }
8533
- async function walletClientAddress(owner) {
8534
- if (owner.account?.address && isAddress3(owner.account.address)) {
8535
- return getAddress5(owner.account.address);
8536
- }
8537
- return requestAccount(looseRequest(owner.request));
8538
- }
8539
- async function eip1193Address(owner) {
8540
- return requestAccount(looseRequest(owner.request));
8541
- }
8542
- async function requestAccount(request) {
8543
- const accounts = await request({ method: "eth_requestAccounts" });
8544
- const first = Array.isArray(accounts) ? accounts[0] : void 0;
8545
- if (typeof first !== "string" || !isAddress3(first)) {
8546
- throw new Error("Owner wallet did not return an account");
8547
- }
8548
- return getAddress5(first);
8549
- }
8550
- async function signOwnerHash(request, account, address, hash) {
8551
- if (account?.sign) {
8552
- return account.sign({ hash });
8553
- }
8554
- const signature = await request({
8555
- method: "personal_sign",
8556
- params: [hash, address]
8557
- });
8558
- if (typeof signature !== "string" || !signature.startsWith("0x")) {
8559
- throw new Error("Owner wallet did not return a signature");
8560
- }
8561
- return asSafeEthSign(signature);
8562
- }
8563
- function asSafeEthSign(signature) {
8564
- const sig = hexToSignature(signature);
8565
- const current = sig.v === void 0 ? sig.yParity === 1 ? 28 : 27 : Number(sig.v);
8566
- const v = current >= 27 ? current + 4 : current + 31;
8567
- return signatureToHex({ r: sig.r, s: sig.s, v: BigInt(v) });
8568
- }
8569
- function personalSignDigest(params) {
8570
- const [first, second] = params ?? [];
8571
- const message = typeof first === "string" && isAddress3(first) ? second : first;
8572
- const hex = typeof message === "string" && message.startsWith("0x") ? message : stringToHex(String(message ?? ""));
8573
- return hashMessage2({ raw: hex });
8574
- }
8575
- function parseTypedDataPayload(params) {
8576
- const [first, second] = params ?? [];
8577
- const payload = typeof first === "string" && isAddress3(first) ? second : first;
8578
- const parsed = typeof payload === "string" ? JSON.parse(payload) : payload;
8579
- const types = { ...parsed.types };
8580
- delete types.EIP712Domain;
8581
- const domain = { ...parsed.domain ?? {} };
8582
- if (typeof domain.chainId === "string") {
8583
- domain.chainId = BigInt(domain.chainId);
8584
- }
8585
- const message = coerceEip712Value(
8586
- parsed.primaryType,
8587
- parsed.message,
8588
- types
8589
- );
8590
- return {
8591
- domain,
8592
- types,
8593
- primaryType: parsed.primaryType,
8594
- message,
8595
- requestPayload: parsed
8596
- };
8597
- }
8598
- function typedDataDigest(params) {
8599
- const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8600
- return hashTypedData2({ domain, types, primaryType, message });
8601
- }
8602
- async function signAccountTypedData(account, params) {
8603
- const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8604
- if (!account.signTypedData) {
8605
- throw new Error("Owner account cannot sign typed data");
8606
- }
8607
- return account.signTypedData({
8608
- domain,
8609
- types,
8610
- primaryType,
8611
- message
8612
- });
8613
- }
8614
- function coerceEip712Value(type, value, types) {
8615
- if (value == null) return value;
8616
- const array = type.match(/^(.*)\[(\d*)\]$/);
8617
- if (array) {
8618
- if (!Array.isArray(value)) return value;
8619
- return value.map((item) => coerceEip712Value(array[1], item, types));
8620
- }
8621
- const struct = types[type];
8622
- if (struct) {
8623
- if (typeof value !== "object" || Array.isArray(value)) return value;
8624
- const record = value;
8625
- const next = {};
8626
- for (const field of struct) {
8627
- next[field.name] = coerceEip712Value(
8628
- field.type,
8629
- record[field.name],
8630
- types
8631
- );
8632
- }
8633
- return next;
8634
- }
8635
- if (/^u?int\d*$/.test(type)) {
8636
- if (typeof value === "bigint") return value;
8637
- if (typeof value === "string" || typeof value === "number") {
8638
- return BigInt(value);
8639
- }
8640
- }
8641
- return value;
8642
- }
8643
- function readSafeTransaction(params) {
8644
- const tx = Array.isArray(params) ? params[0] : void 0;
8645
- if (!tx?.to || !isAddress3(tx.to)) {
8646
- throw new Error("Safe transaction is missing a destination");
8647
- }
8648
- const data = typeof tx.data === "string" && tx.data.startsWith("0x") ? tx.data : "0x";
8649
- let value = 0n;
8650
- if (typeof tx.value === "bigint") value = tx.value;
8651
- else if (typeof tx.value === "number" || typeof tx.value === "string") {
8652
- value = BigInt(tx.value);
8653
- }
8654
- return { to: getAddress5(tx.to), data, value };
8655
- }
8656
8486
  export {
8657
8487
  ALLOWED_HISTORY_DAYS,
8658
8488
  API_ENDPOINT,
@@ -8685,7 +8515,6 @@ export {
8685
8515
  ZyfaiSDK,
8686
8516
  buildV1ChainSessions,
8687
8517
  createBankrProvider,
8688
- createSafeOwnerProvider,
8689
8518
  decodeUserOperationCalls,
8690
8519
  getChainConfig,
8691
8520
  getDataApiBaseUrl,