@zyfai/sdk 1.8.3 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,34 @@ 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 completeSafeDeploy = async (config, strategyBody, body) => {
1694
+ const deployResponse = await config.httpClient.post(
1695
+ `${ENDPOINTS.SAFE_DEPLOY}?chainId=${config.chainId}`,
1696
+ { ...body, ...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
+ };
1708
+ };
1682
1709
  var deploySafeAccount = async (config) => {
1683
1710
  try {
1684
1711
  const {
@@ -1701,16 +1728,35 @@ var deploySafeAccount = async (config) => {
1701
1728
  strategyBody
1702
1729
  );
1703
1730
  console.log("prepareResponse", prepareResponse);
1704
- if (prepareResponse.success && !prepareResponse.userOpHashToSign) {
1731
+ if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1705
1732
  return {
1706
1733
  safeAddress: prepareResponse.safeAddress || "0x",
1707
1734
  txHash: "0x0",
1708
1735
  isDeployed: true
1709
1736
  };
1710
1737
  }
1738
+ if (prepareResponse.signingMode === "typed-data") {
1739
+ if (!prepareResponse.typedData) {
1740
+ throw new Error(
1741
+ "Backend returned signingMode typed-data without typedData. Response: " + JSON.stringify(prepareResponse)
1742
+ );
1743
+ }
1744
+ const parentSafe = (0, import_viem6.getAddress)(safeOwnerAddress);
1745
+ console.info(
1746
+ `[ZyfaiSDK] safe-deploy typed-data chainId=${chainId} owner=${parentSafe}`
1747
+ );
1748
+ const typedDataSignature = await signNestedSafeDeployTypedData(
1749
+ owner,
1750
+ parentSafe,
1751
+ prepareResponse.typedData
1752
+ );
1753
+ return completeSafeDeploy(config, strategyBody, {
1754
+ typedDataSignature
1755
+ });
1756
+ }
1711
1757
  if (!prepareResponse.userOpHashToSign) {
1712
1758
  throw new Error(
1713
- "Backend did not return userOpHashToSign. Response: " + JSON.stringify(prepareResponse)
1759
+ "Backend did not return userOpHashToSign or typed-data to sign. Response: " + JSON.stringify(prepareResponse)
1714
1760
  );
1715
1761
  }
1716
1762
  const userOpHashToSign = prepareResponse.userOpHashToSign;
@@ -1738,20 +1784,9 @@ var deploySafeAccount = async (config) => {
1738
1784
  isContractSignature: true
1739
1785
  }
1740
1786
  ]) : 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
- };
1787
+ return completeSafeDeploy(config, strategyBody, {
1788
+ userOpSignature: signatureToSubmit
1789
+ });
1755
1790
  } catch (error) {
1756
1791
  throw new Error(
1757
1792
  `Failed to deploy Safe account: ${error.message}`
@@ -2573,7 +2608,7 @@ var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
2573
2608
  };
2574
2609
 
2575
2610
  // src/core/ZyfaiSDK.ts
2576
- var import_siwe = require("siwe");
2611
+ var import_siwe = require("viem/siwe");
2577
2612
  var DepositCreditTimeoutError = class extends Error {
2578
2613
  constructor(depositId) {
2579
2614
  super(`Timed out waiting for deposit ${depositId} to be credited`);
@@ -2645,6 +2680,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2645
2680
  this.currentChainId = null;
2646
2681
  /** EOA of the active user session (bearer or SIWE). Cleared on disconnect. */
2647
2682
  this.sessionEoa = null;
2683
+ /** Serialize concurrent connectAccount calls (e.g. React StrictMode double mount). */
2684
+ this.connectAccountInFlight = null;
2685
+ /** One SIWE prompt at a time. Register must not send a second personal_sign. */
2686
+ this.authenticateUserInFlight = null;
2648
2687
  const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
2649
2688
  const {
2650
2689
  apiKey,
@@ -2769,16 +2808,33 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2769
2808
  *
2770
2809
  * @returns Promise that resolves when authentication is complete
2771
2810
  */
2772
- async authenticateUser() {
2811
+ authenticateUser() {
2812
+ if (this.authenticatedUserId !== null || this.httpClient.hasAuthToken()) {
2813
+ return Promise.resolve();
2814
+ }
2815
+ if (!this.authenticateUserInFlight) {
2816
+ this.authenticateUserInFlight = this.performAuthenticateUser().finally(
2817
+ () => {
2818
+ this.authenticateUserInFlight = null;
2819
+ }
2820
+ );
2821
+ }
2822
+ return this.authenticateUserInFlight;
2823
+ }
2824
+ async performAuthenticateUser() {
2773
2825
  try {
2774
- if (this.authenticatedUserId !== null) {
2775
- return;
2776
- }
2777
- if (this.httpClient.hasAuthToken()) {
2826
+ if (this.authenticatedUserId !== null || this.httpClient.hasAuthToken()) {
2778
2827
  return;
2779
2828
  }
2780
2829
  const walletClient = this.getWalletClient();
2781
- const userAddress = (0, import_viem8.getAddress)(walletClient.account.address);
2830
+ const rawAccount = walletClient.account;
2831
+ const connected = typeof rawAccount === "string" ? rawAccount : rawAccount?.address;
2832
+ if (!connected) {
2833
+ throw new Error(
2834
+ "Wallet account address is missing. Call connectAccount() after the wallet is connected."
2835
+ );
2836
+ }
2837
+ const userAddress = (0, import_viem8.getAddress)(connected);
2782
2838
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
2783
2839
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
2784
2840
  let uri;
@@ -2792,7 +2848,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2792
2848
  uri = this.executionApiUrl;
2793
2849
  domain = new URL(this.executionApiUrl).host;
2794
2850
  }
2795
- const messageObj = new import_siwe.SiweMessage({
2851
+ const issuedAt = /* @__PURE__ */ new Date();
2852
+ const messageFields = {
2796
2853
  address: userAddress,
2797
2854
  chainId,
2798
2855
  domain,
@@ -2800,11 +2857,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2800
2857
  statement: "Sign in with Ethereum",
2801
2858
  uri,
2802
2859
  version: "1",
2803
- issuedAt: (/* @__PURE__ */ new Date()).toISOString()
2804
- });
2805
- const messageString = messageObj.prepareMessage();
2860
+ issuedAt
2861
+ };
2862
+ const messageString = (0, import_siwe.createSiweMessage)(messageFields);
2863
+ const messageObj = {
2864
+ ...messageFields,
2865
+ issuedAt: issuedAt.toISOString()
2866
+ };
2806
2867
  const signature = await walletClient.signMessage({
2807
- account: walletClient.account,
2868
+ account: userAddress,
2808
2869
  message: messageString
2809
2870
  });
2810
2871
  const loginResponse = await this.httpClient.post(
@@ -2892,6 +2953,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2892
2953
  [internalAsset]: assetSettings
2893
2954
  }
2894
2955
  };
2956
+ if (request.smartWallet !== void 0)
2957
+ payload.smartWallet = request.smartWallet;
2958
+ if (request.executorProxy !== void 0)
2959
+ payload.executorProxy = request.executorProxy;
2960
+ if (request.chains !== void 0) payload.chains = request.chains;
2895
2961
  if (request.omniAccount !== void 0)
2896
2962
  payload.omniAccount = request.omniAccount;
2897
2963
  if (request.agentName !== void 0)
@@ -3197,82 +3263,167 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3197
3263
  * const provider = await connector.getProvider();
3198
3264
  * await sdk.connectAccount(provider);
3199
3265
  */
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;
3266
+ async resolveConnectAddress(account) {
3220
3267
  if (typeof account === "string") {
3221
3268
  let privateKey = account;
3222
3269
  if (!privateKey.startsWith("0x")) {
3223
3270
  privateKey = `0x${privateKey}`;
3224
3271
  }
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)
3272
+ return (0, import_accounts2.privateKeyToAccount)(privateKey).address;
3273
+ }
3274
+ const provider = account;
3275
+ if (!provider) {
3276
+ throw new Error(
3277
+ "Invalid account parameter. Expected private key string or wallet provider."
3278
+ );
3279
+ }
3280
+ if (provider.account && provider.transport) {
3281
+ const accountField = provider.account;
3282
+ const resolvedAddress = typeof accountField === "string" ? accountField : accountField.address;
3283
+ if (!resolvedAddress) {
3284
+ throw new Error("Wallet client is missing account address");
3285
+ }
3286
+ return (0, import_viem8.getAddress)(resolvedAddress);
3287
+ }
3288
+ if (provider.request) {
3289
+ const eip1193 = typeof provider.request === "function" ? provider : typeof provider.provider?.request === "function" ? provider.provider : null;
3290
+ if (!eip1193) {
3291
+ throw new Error(
3292
+ "Wallet provider has no EIP-1193 request method. Pass the connector getProvider() result."
3293
+ );
3294
+ }
3295
+ const accounts = await eip1193.request({
3296
+ method: "eth_accounts"
3231
3297
  });
3232
- connectedAddress = this.signer.address;
3233
- this.currentProvider = null;
3234
- } else {
3235
- const provider = account;
3236
- if (!provider) {
3298
+ const fallbackAccounts = accounts?.length > 0 ? accounts : await eip1193.request({
3299
+ method: "eth_requestAccounts"
3300
+ });
3301
+ const raw = fallbackAccounts?.[0];
3302
+ const accountAddress = typeof raw === "string" ? raw : typeof raw?.address === "string" ? raw.address : void 0;
3303
+ if (!accountAddress) {
3237
3304
  throw new Error(
3238
- "Invalid account parameter. Expected private key string or wallet provider."
3305
+ "Wallet returned an account without an address. Reconnect via WalletConnect."
3239
3306
  );
3240
3307
  }
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");
3308
+ return (0, import_viem8.getAddress)(accountAddress);
3309
+ }
3310
+ throw new Error(
3311
+ "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3312
+ );
3313
+ }
3314
+ async connectAccount(account, chainId = 8453) {
3315
+ if (!isSupportedChain(chainId)) {
3316
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3317
+ }
3318
+ const resolvedAddress = await this.resolveConnectAddress(account);
3319
+ if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && (0, import_viem8.isAddressEqual)(resolvedAddress, this.sessionEoa)) {
3320
+ this.currentChainId = chainId;
3321
+ return resolvedAddress;
3322
+ }
3323
+ if (this.connectAccountInFlight) {
3324
+ return this.connectAccountInFlight;
3325
+ }
3326
+ const connect = (async () => {
3327
+ this.authenticatedUserId = null;
3328
+ this.isPredeployed = false;
3329
+ this.predeployedResolved = false;
3330
+ this.connectedSmartWallet = null;
3331
+ this.currentChainId = null;
3332
+ this.sessionEoa = null;
3333
+ this.sessionChannel = void 0;
3334
+ this.httpClient.clearAuthToken();
3335
+ if (this.currentProvider?.removeAllListeners) {
3336
+ try {
3337
+ this.currentProvider.removeAllListeners("accountsChanged");
3338
+ } catch (error) {
3247
3339
  }
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));
3340
+ }
3341
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3342
+ let connectedAddress;
3343
+ if (typeof account === "string") {
3344
+ let privateKey = account;
3345
+ if (!privateKey.startsWith("0x")) {
3346
+ privateKey = `0x${privateKey}`;
3258
3347
  }
3259
- } else if (provider.account && provider.transport) {
3348
+ this.signer = (0, import_accounts2.privateKeyToAccount)(privateKey);
3349
+ this.currentChainId = chainId;
3260
3350
  this.walletClient = (0, import_viem8.createWalletClient)({
3261
- account: provider.account,
3351
+ account: this.signer,
3262
3352
  chain: chainConfig.chain,
3263
- transport: provider.transport
3353
+ transport: (0, import_viem8.http)(chainConfig.rpcUrl)
3264
3354
  });
3265
- connectedAddress = provider.account.address;
3355
+ connectedAddress = this.signer.address;
3266
3356
  this.currentProvider = null;
3267
- this.currentChainId = chainId;
3268
3357
  } else {
3269
- throw new Error(
3270
- "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3271
- );
3358
+ const provider = account;
3359
+ if (!provider) {
3360
+ throw new Error(
3361
+ "Invalid account parameter. Expected private key string or wallet provider."
3362
+ );
3363
+ }
3364
+ if (provider.account && provider.transport) {
3365
+ const accountField = provider.account;
3366
+ const resolvedAddress2 = typeof accountField === "string" ? accountField : accountField.address;
3367
+ if (!resolvedAddress2) {
3368
+ throw new Error("Wallet client is missing account address");
3369
+ }
3370
+ const hasSignMessage = typeof provider.signMessage === "function" && typeof provider.request === "function";
3371
+ this.walletClient = hasSignMessage ? provider : (0, import_viem8.createWalletClient)({
3372
+ account: provider.account,
3373
+ chain: chainConfig.chain,
3374
+ transport: provider.transport
3375
+ });
3376
+ connectedAddress = (0, import_viem8.getAddress)(resolvedAddress2);
3377
+ this.currentProvider = null;
3378
+ this.currentChainId = chainId;
3379
+ } else if (provider.request) {
3380
+ const eip1193 = typeof provider.request === "function" ? provider : typeof provider.provider?.request === "function" ? provider.provider : null;
3381
+ if (!eip1193) {
3382
+ throw new Error(
3383
+ "Wallet provider has no EIP-1193 request method. Pass the connector getProvider() result."
3384
+ );
3385
+ }
3386
+ const accounts = await eip1193.request({
3387
+ method: "eth_requestAccounts"
3388
+ });
3389
+ if (!accounts || accounts.length === 0) {
3390
+ throw new Error("No accounts found in wallet provider");
3391
+ }
3392
+ const raw = accounts[0];
3393
+ const accountAddress = typeof raw === "string" ? raw : typeof raw?.address === "string" ? raw.address : void 0;
3394
+ if (!accountAddress) {
3395
+ throw new Error(
3396
+ "Wallet returned an account without an address. Reconnect via WalletConnect."
3397
+ );
3398
+ }
3399
+ connectedAddress = (0, import_viem8.getAddress)(accountAddress);
3400
+ this.walletClient = (0, import_viem8.createWalletClient)({
3401
+ account: connectedAddress,
3402
+ chain: chainConfig.chain,
3403
+ transport: (0, import_viem8.custom)(eip1193)
3404
+ });
3405
+ this.currentProvider = eip1193;
3406
+ this.currentChainId = chainId;
3407
+ if (provider.on) {
3408
+ provider.on("accountsChanged", this.handleAccountsChanged.bind(this));
3409
+ }
3410
+ } else {
3411
+ throw new Error(
3412
+ "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3413
+ );
3414
+ }
3415
+ }
3416
+ await this.authenticateUser();
3417
+ return connectedAddress;
3418
+ })();
3419
+ this.connectAccountInFlight = connect;
3420
+ try {
3421
+ return await connect;
3422
+ } finally {
3423
+ if (this.connectAccountInFlight === connect) {
3424
+ this.connectAccountInFlight = null;
3272
3425
  }
3273
3426
  }
3274
- await this.authenticateUser();
3275
- return connectedAddress;
3276
3427
  }
3277
3428
  /**
3278
3429
  * Clear the connected wallet, SIWE session, and cached smart-wallet state.
@@ -3338,6 +3489,51 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3338
3489
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3339
3490
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
3340
3491
  }
3492
+ /**
3493
+ * Nested Safe owners use intent sessions: finish any pending safe-deploy typed-data
3494
+ * (install or emissary enable), then register with chainId only.
3495
+ * @private
3496
+ */
3497
+ async registerNestedIntentSessionKey(userAddress, chainId, strategy) {
3498
+ if (!this.authenticatedUserId) {
3499
+ throw new Error(
3500
+ "User ID not available. Please ensure authentication completed successfully."
3501
+ );
3502
+ }
3503
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3504
+ await deploySafeAccount({
3505
+ owner: this.getWalletClient(chainId),
3506
+ safeOwnerAddress: userAddress,
3507
+ chain: chainConfig.chain,
3508
+ publicClient: chainConfig.publicClient,
3509
+ chainId,
3510
+ httpClient: this.httpClient,
3511
+ strategy
3512
+ });
3513
+ const activation = await this.httpClient.post(
3514
+ ENDPOINTS.SESSION_KEYS_ADD,
3515
+ { chainId }
3516
+ );
3517
+ this.hasActiveSessionKey = true;
3518
+ return {
3519
+ success: true,
3520
+ userId: this.authenticatedUserId,
3521
+ message: "Intent session key registered",
3522
+ alreadyActive: false,
3523
+ sessionActivation: activation
3524
+ };
3525
+ }
3526
+ async registerNestedChildProfile(childAddress, chainId, strategy) {
3527
+ await this.updateUserProfile({
3528
+ smartWallet: childAddress,
3529
+ executorProxy: true,
3530
+ chains: [chainId],
3531
+ strategy,
3532
+ protocols: [],
3533
+ autoSelectProtocols: false,
3534
+ asset: "USDC"
3535
+ });
3536
+ }
3341
3537
  /**
3342
3538
  * SIWE login sets predeployed. Agent sessions (`forUser`) do not, so read it
3343
3539
  * from the user record before allowing a transfer to an undeployed pool Safe.
@@ -3361,13 +3557,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3361
3557
  chainId
3362
3558
  );
3363
3559
  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
- );
3560
+ const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3371
3561
  if (!childDeployed) {
3372
3562
  await this.deploySafe(userAddress, chainId, strategy, true);
3373
3563
  return;
@@ -3420,6 +3610,25 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3420
3610
  }
3421
3611
  if (!deriveIfMissing) return null;
3422
3612
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3613
+ const ownerType = await getAccountType(
3614
+ userAddress,
3615
+ chainConfig.publicClient
3616
+ );
3617
+ if (ownerType === "Safe") {
3618
+ if (this.isConnectedUser(userAddress) && this.connectedSmartWallet) {
3619
+ return this.connectedSmartWallet;
3620
+ }
3621
+ try {
3622
+ if (this.httpClient.hasAuthToken()) {
3623
+ const me = await this.httpClient.get(
3624
+ ENDPOINTS.USER_ME
3625
+ );
3626
+ if (me?.smartWallet) return (0, import_viem8.getAddress)(me.smartWallet);
3627
+ }
3628
+ } catch {
3629
+ }
3630
+ return null;
3631
+ }
3423
3632
  return getDeterministicSafeAddress({
3424
3633
  safeOwnerAddress: userAddress,
3425
3634
  chain: chainConfig.chain,
@@ -3449,8 +3658,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3449
3658
  throw new Error(`Unsupported chain ID: ${chainId}`);
3450
3659
  }
3451
3660
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3661
+ const ownerType = await getAccountType(
3662
+ userAddress,
3663
+ chainConfig.publicClient
3664
+ );
3452
3665
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3453
3666
  if (!safeAddress) {
3667
+ if (ownerType === "Safe") {
3668
+ throw new Error("NESTED_CHILD_UNREGISTERED");
3669
+ }
3454
3670
  throw new Error("Smart wallet address is not available");
3455
3671
  }
3456
3672
  const isDeployed = await isSafeDeployed(
@@ -3535,15 +3751,19 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3535
3751
  }
3536
3752
  const walletClient = this.getWalletClient(chainId);
3537
3753
  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,
3754
+ const ownerAccountType = await getAccountType(
3755
+ userAddress,
3544
3756
  chainConfig.publicClient
3545
3757
  );
3546
- if (alreadyDeployed) {
3758
+ const nestedSafeOwner = ownerAccountType === "Safe";
3759
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3760
+ if (!safeAddress && !nestedSafeOwner) {
3761
+ throw new Error(
3762
+ ownerAccountType === "EOA" ? "For nested deploy, connect WalletConnect as the parent Safe contract address, not the owner EOA." : "Smart wallet address is not available"
3763
+ );
3764
+ }
3765
+ const alreadyDeployed = safeAddress ? await isSafeDeployed(safeAddress, chainConfig.publicClient) : false;
3766
+ if (alreadyDeployed && safeAddress) {
3547
3767
  let enableTxHash = "0x0";
3548
3768
  if (!this.isPredeployed) {
3549
3769
  const enabled = await deploySafeAccount({
@@ -3553,7 +3773,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3553
3773
  publicClient: chainConfig.publicClient,
3554
3774
  chainId,
3555
3775
  httpClient: this.httpClient,
3556
- strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy"
3776
+ strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy",
3777
+ childSafeAddress: safeAddress
3557
3778
  });
3558
3779
  enableTxHash = enabled.txHash || "0x0";
3559
3780
  }
@@ -3586,7 +3807,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3586
3807
  publicClient: chainConfig.publicClient,
3587
3808
  chainId,
3588
3809
  httpClient: this.httpClient,
3589
- strategy: internalStrategy
3810
+ strategy: internalStrategy,
3811
+ childSafeAddress: safeAddress ?? void 0
3590
3812
  });
3591
3813
  this.hasActiveSessionKey = false;
3592
3814
  try {
@@ -3597,8 +3819,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3597
3819
  initError.message
3598
3820
  );
3599
3821
  }
3822
+ if (nestedSafeOwner) {
3823
+ await this.registerNestedChildProfile(
3824
+ deploymentResult.safeAddress,
3825
+ chainId,
3826
+ strategy
3827
+ );
3828
+ }
3600
3829
  await this.updateUserProtocols(strategy);
3601
- if (!this.isPredeployed) {
3830
+ if (!this.isPredeployed && !nestedSafeOwner) {
3602
3831
  await deploySafeAccount({
3603
3832
  owner: walletClient,
3604
3833
  safeOwnerAddress: userAddress,
@@ -3606,7 +3835,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3606
3835
  publicClient: chainConfig.publicClient,
3607
3836
  chainId,
3608
3837
  httpClient: this.httpClient,
3609
- strategy: internalStrategy
3838
+ strategy: internalStrategy,
3839
+ childSafeAddress: deploymentResult.safeAddress
3610
3840
  });
3611
3841
  }
3612
3842
  let sessionKeyCreated = false;
@@ -3709,14 +3939,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3709
3939
  chainConfig.publicClient
3710
3940
  );
3711
3941
  if (accountType === "Safe") {
3712
- await this.assertOwnerSafeOnSessionChains(
3942
+ return this.registerNestedIntentSessionKey(
3713
3943
  userAddress,
3714
- sessions
3944
+ chainId,
3945
+ void 0
3715
3946
  );
3716
3947
  }
3717
3948
  const signingParams = {
3718
3949
  permitGenericPolicy,
3719
- ignoreSecurityAttestations: accountType === "Safe"
3950
+ ignoreSecurityAttestations: false
3720
3951
  };
3721
3952
  const signatureResult = await this.signSessionKey(
3722
3953
  userAddress,
@@ -3746,38 +3977,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3746
3977
  }
3747
3978
  }
3748
3979
  /**
3749
- * Internal method to sign session key
3980
+ * Internal method to sign session key for an EOA owner.
3981
+ * Nested Safe owners register through {@link registerNestedIntentSessionKey}.
3750
3982
  * @private
3751
3983
  */
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
3984
  async signSessionKey(userAddress, chainId, sessions, signingParams) {
3782
3985
  try {
3783
3986
  if (!userAddress) {
@@ -8307,371 +8510,6 @@ function createBankrProvider(config) {
8307
8510
  };
8308
8511
  return provider;
8309
8512
  }
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
8513
  // Annotate the CommonJS export names for ESM import in node:
8676
8514
  0 && (module.exports = {
8677
8515
  ALLOWED_HISTORY_DAYS,
@@ -8705,7 +8543,6 @@ function readSafeTransaction(params) {
8705
8543
  ZyfaiSDK,
8706
8544
  buildV1ChainSessions,
8707
8545
  createBankrProvider,
8708
- createSafeOwnerProvider,
8709
8546
  decodeUserOperationCalls,
8710
8547
  getChainConfig,
8711
8548
  getDataApiBaseUrl,