@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.mjs CHANGED
@@ -1632,6 +1632,34 @@ 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 completeSafeDeploy = async (config, strategyBody, body) => {
1648
+ const deployResponse = await config.httpClient.post(
1649
+ `${ENDPOINTS.SAFE_DEPLOY}?chainId=${config.chainId}`,
1650
+ { ...body, ...strategyBody }
1651
+ );
1652
+ if (!deployResponse.success) {
1653
+ throw new Error(
1654
+ `Safe deployment failed: ${JSON.stringify(deployResponse)}`
1655
+ );
1656
+ }
1657
+ return {
1658
+ safeAddress: deployResponse.safeAddress || "0x",
1659
+ txHash: deployResponse.txHash,
1660
+ isDeployed: true
1661
+ };
1662
+ };
1635
1663
  var deploySafeAccount = async (config) => {
1636
1664
  try {
1637
1665
  const {
@@ -1654,16 +1682,35 @@ var deploySafeAccount = async (config) => {
1654
1682
  strategyBody
1655
1683
  );
1656
1684
  console.log("prepareResponse", prepareResponse);
1657
- if (prepareResponse.success && !prepareResponse.userOpHashToSign) {
1685
+ if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1658
1686
  return {
1659
1687
  safeAddress: prepareResponse.safeAddress || "0x",
1660
1688
  txHash: "0x0",
1661
1689
  isDeployed: true
1662
1690
  };
1663
1691
  }
1692
+ if (prepareResponse.signingMode === "typed-data") {
1693
+ if (!prepareResponse.typedData) {
1694
+ throw new Error(
1695
+ "Backend returned signingMode typed-data without typedData. Response: " + JSON.stringify(prepareResponse)
1696
+ );
1697
+ }
1698
+ const parentSafe = getAddress2(safeOwnerAddress);
1699
+ console.info(
1700
+ `[ZyfaiSDK] safe-deploy typed-data chainId=${chainId} owner=${parentSafe}`
1701
+ );
1702
+ const typedDataSignature = await signNestedSafeDeployTypedData(
1703
+ owner,
1704
+ parentSafe,
1705
+ prepareResponse.typedData
1706
+ );
1707
+ return completeSafeDeploy(config, strategyBody, {
1708
+ typedDataSignature
1709
+ });
1710
+ }
1664
1711
  if (!prepareResponse.userOpHashToSign) {
1665
1712
  throw new Error(
1666
- "Backend did not return userOpHashToSign. Response: " + JSON.stringify(prepareResponse)
1713
+ "Backend did not return userOpHashToSign or typed-data to sign. Response: " + JSON.stringify(prepareResponse)
1667
1714
  );
1668
1715
  }
1669
1716
  const userOpHashToSign = prepareResponse.userOpHashToSign;
@@ -1691,20 +1738,9 @@ var deploySafeAccount = async (config) => {
1691
1738
  isContractSignature: true
1692
1739
  }
1693
1740
  ]) : 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
- };
1741
+ return completeSafeDeploy(config, strategyBody, {
1742
+ userOpSignature: signatureToSubmit
1743
+ });
1708
1744
  } catch (error) {
1709
1745
  throw new Error(
1710
1746
  `Failed to deploy Safe account: ${error.message}`
@@ -2528,7 +2564,7 @@ var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
2528
2564
  };
2529
2565
 
2530
2566
  // src/core/ZyfaiSDK.ts
2531
- import { SiweMessage } from "siwe";
2567
+ import { createSiweMessage } from "viem/siwe";
2532
2568
  var DepositCreditTimeoutError = class extends Error {
2533
2569
  constructor(depositId) {
2534
2570
  super(`Timed out waiting for deposit ${depositId} to be credited`);
@@ -2600,6 +2636,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2600
2636
  this.currentChainId = null;
2601
2637
  /** EOA of the active user session (bearer or SIWE). Cleared on disconnect. */
2602
2638
  this.sessionEoa = null;
2639
+ /** Serialize concurrent connectAccount calls (e.g. React StrictMode double mount). */
2640
+ this.connectAccountInFlight = null;
2641
+ /** One SIWE prompt at a time. Register must not send a second personal_sign. */
2642
+ this.authenticateUserInFlight = null;
2603
2643
  const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
2604
2644
  const {
2605
2645
  apiKey,
@@ -2724,16 +2764,33 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2724
2764
  *
2725
2765
  * @returns Promise that resolves when authentication is complete
2726
2766
  */
2727
- async authenticateUser() {
2767
+ authenticateUser() {
2768
+ if (this.authenticatedUserId !== null || this.httpClient.hasAuthToken()) {
2769
+ return Promise.resolve();
2770
+ }
2771
+ if (!this.authenticateUserInFlight) {
2772
+ this.authenticateUserInFlight = this.performAuthenticateUser().finally(
2773
+ () => {
2774
+ this.authenticateUserInFlight = null;
2775
+ }
2776
+ );
2777
+ }
2778
+ return this.authenticateUserInFlight;
2779
+ }
2780
+ async performAuthenticateUser() {
2728
2781
  try {
2729
- if (this.authenticatedUserId !== null) {
2730
- return;
2731
- }
2732
- if (this.httpClient.hasAuthToken()) {
2782
+ if (this.authenticatedUserId !== null || this.httpClient.hasAuthToken()) {
2733
2783
  return;
2734
2784
  }
2735
2785
  const walletClient = this.getWalletClient();
2736
- const userAddress = getAddress4(walletClient.account.address);
2786
+ const rawAccount = walletClient.account;
2787
+ const connected = typeof rawAccount === "string" ? rawAccount : rawAccount?.address;
2788
+ if (!connected) {
2789
+ throw new Error(
2790
+ "Wallet account address is missing. Call connectAccount() after the wallet is connected."
2791
+ );
2792
+ }
2793
+ const userAddress = getAddress4(connected);
2737
2794
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
2738
2795
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
2739
2796
  let uri;
@@ -2747,7 +2804,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2747
2804
  uri = this.executionApiUrl;
2748
2805
  domain = new URL(this.executionApiUrl).host;
2749
2806
  }
2750
- const messageObj = new SiweMessage({
2807
+ const issuedAt = /* @__PURE__ */ new Date();
2808
+ const messageFields = {
2751
2809
  address: userAddress,
2752
2810
  chainId,
2753
2811
  domain,
@@ -2755,11 +2813,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2755
2813
  statement: "Sign in with Ethereum",
2756
2814
  uri,
2757
2815
  version: "1",
2758
- issuedAt: (/* @__PURE__ */ new Date()).toISOString()
2759
- });
2760
- const messageString = messageObj.prepareMessage();
2816
+ issuedAt
2817
+ };
2818
+ const messageString = createSiweMessage(messageFields);
2819
+ const messageObj = {
2820
+ ...messageFields,
2821
+ issuedAt: issuedAt.toISOString()
2822
+ };
2761
2823
  const signature = await walletClient.signMessage({
2762
- account: walletClient.account,
2824
+ account: userAddress,
2763
2825
  message: messageString
2764
2826
  });
2765
2827
  const loginResponse = await this.httpClient.post(
@@ -2847,6 +2909,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2847
2909
  [internalAsset]: assetSettings
2848
2910
  }
2849
2911
  };
2912
+ if (request.smartWallet !== void 0)
2913
+ payload.smartWallet = request.smartWallet;
2914
+ if (request.executorProxy !== void 0)
2915
+ payload.executorProxy = request.executorProxy;
2916
+ if (request.chains !== void 0) payload.chains = request.chains;
2850
2917
  if (request.omniAccount !== void 0)
2851
2918
  payload.omniAccount = request.omniAccount;
2852
2919
  if (request.agentName !== void 0)
@@ -3152,82 +3219,167 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3152
3219
  * const provider = await connector.getProvider();
3153
3220
  * await sdk.connectAccount(provider);
3154
3221
  */
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;
3222
+ async resolveConnectAddress(account) {
3175
3223
  if (typeof account === "string") {
3176
3224
  let privateKey = account;
3177
3225
  if (!privateKey.startsWith("0x")) {
3178
3226
  privateKey = `0x${privateKey}`;
3179
3227
  }
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)
3228
+ return privateKeyToAccount(privateKey).address;
3229
+ }
3230
+ const provider = account;
3231
+ if (!provider) {
3232
+ throw new Error(
3233
+ "Invalid account parameter. Expected private key string or wallet provider."
3234
+ );
3235
+ }
3236
+ if (provider.account && provider.transport) {
3237
+ const accountField = provider.account;
3238
+ const resolvedAddress = typeof accountField === "string" ? accountField : accountField.address;
3239
+ if (!resolvedAddress) {
3240
+ throw new Error("Wallet client is missing account address");
3241
+ }
3242
+ return getAddress4(resolvedAddress);
3243
+ }
3244
+ if (provider.request) {
3245
+ const eip1193 = typeof provider.request === "function" ? provider : typeof provider.provider?.request === "function" ? provider.provider : null;
3246
+ if (!eip1193) {
3247
+ throw new Error(
3248
+ "Wallet provider has no EIP-1193 request method. Pass the connector getProvider() result."
3249
+ );
3250
+ }
3251
+ const accounts = await eip1193.request({
3252
+ method: "eth_accounts"
3186
3253
  });
3187
- connectedAddress = this.signer.address;
3188
- this.currentProvider = null;
3189
- } else {
3190
- const provider = account;
3191
- if (!provider) {
3254
+ const fallbackAccounts = accounts?.length > 0 ? accounts : await eip1193.request({
3255
+ method: "eth_requestAccounts"
3256
+ });
3257
+ const raw = fallbackAccounts?.[0];
3258
+ const accountAddress = typeof raw === "string" ? raw : typeof raw?.address === "string" ? raw.address : void 0;
3259
+ if (!accountAddress) {
3192
3260
  throw new Error(
3193
- "Invalid account parameter. Expected private key string or wallet provider."
3261
+ "Wallet returned an account without an address. Reconnect via WalletConnect."
3194
3262
  );
3195
3263
  }
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");
3264
+ return getAddress4(accountAddress);
3265
+ }
3266
+ throw new Error(
3267
+ "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3268
+ );
3269
+ }
3270
+ async connectAccount(account, chainId = 8453) {
3271
+ if (!isSupportedChain(chainId)) {
3272
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3273
+ }
3274
+ const resolvedAddress = await this.resolveConnectAddress(account);
3275
+ if (this.sessionEoa && this.httpClient.hasAuthToken() && this.authenticatedUserId !== null && isAddressEqual2(resolvedAddress, this.sessionEoa)) {
3276
+ this.currentChainId = chainId;
3277
+ return resolvedAddress;
3278
+ }
3279
+ if (this.connectAccountInFlight) {
3280
+ return this.connectAccountInFlight;
3281
+ }
3282
+ const connect = (async () => {
3283
+ this.authenticatedUserId = null;
3284
+ this.isPredeployed = false;
3285
+ this.predeployedResolved = false;
3286
+ this.connectedSmartWallet = null;
3287
+ this.currentChainId = null;
3288
+ this.sessionEoa = null;
3289
+ this.sessionChannel = void 0;
3290
+ this.httpClient.clearAuthToken();
3291
+ if (this.currentProvider?.removeAllListeners) {
3292
+ try {
3293
+ this.currentProvider.removeAllListeners("accountsChanged");
3294
+ } catch (error) {
3202
3295
  }
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));
3296
+ }
3297
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3298
+ let connectedAddress;
3299
+ if (typeof account === "string") {
3300
+ let privateKey = account;
3301
+ if (!privateKey.startsWith("0x")) {
3302
+ privateKey = `0x${privateKey}`;
3213
3303
  }
3214
- } else if (provider.account && provider.transport) {
3304
+ this.signer = privateKeyToAccount(privateKey);
3305
+ this.currentChainId = chainId;
3215
3306
  this.walletClient = createWalletClient({
3216
- account: provider.account,
3307
+ account: this.signer,
3217
3308
  chain: chainConfig.chain,
3218
- transport: provider.transport
3309
+ transport: http2(chainConfig.rpcUrl)
3219
3310
  });
3220
- connectedAddress = provider.account.address;
3311
+ connectedAddress = this.signer.address;
3221
3312
  this.currentProvider = null;
3222
- this.currentChainId = chainId;
3223
3313
  } else {
3224
- throw new Error(
3225
- "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3226
- );
3314
+ const provider = account;
3315
+ if (!provider) {
3316
+ throw new Error(
3317
+ "Invalid account parameter. Expected private key string or wallet provider."
3318
+ );
3319
+ }
3320
+ if (provider.account && provider.transport) {
3321
+ const accountField = provider.account;
3322
+ const resolvedAddress2 = typeof accountField === "string" ? accountField : accountField.address;
3323
+ if (!resolvedAddress2) {
3324
+ throw new Error("Wallet client is missing account address");
3325
+ }
3326
+ const hasSignMessage = typeof provider.signMessage === "function" && typeof provider.request === "function";
3327
+ this.walletClient = hasSignMessage ? provider : createWalletClient({
3328
+ account: provider.account,
3329
+ chain: chainConfig.chain,
3330
+ transport: provider.transport
3331
+ });
3332
+ connectedAddress = getAddress4(resolvedAddress2);
3333
+ this.currentProvider = null;
3334
+ this.currentChainId = chainId;
3335
+ } else if (provider.request) {
3336
+ const eip1193 = typeof provider.request === "function" ? provider : typeof provider.provider?.request === "function" ? provider.provider : null;
3337
+ if (!eip1193) {
3338
+ throw new Error(
3339
+ "Wallet provider has no EIP-1193 request method. Pass the connector getProvider() result."
3340
+ );
3341
+ }
3342
+ const accounts = await eip1193.request({
3343
+ method: "eth_requestAccounts"
3344
+ });
3345
+ if (!accounts || accounts.length === 0) {
3346
+ throw new Error("No accounts found in wallet provider");
3347
+ }
3348
+ const raw = accounts[0];
3349
+ const accountAddress = typeof raw === "string" ? raw : typeof raw?.address === "string" ? raw.address : void 0;
3350
+ if (!accountAddress) {
3351
+ throw new Error(
3352
+ "Wallet returned an account without an address. Reconnect via WalletConnect."
3353
+ );
3354
+ }
3355
+ connectedAddress = getAddress4(accountAddress);
3356
+ this.walletClient = createWalletClient({
3357
+ account: connectedAddress,
3358
+ chain: chainConfig.chain,
3359
+ transport: custom(eip1193)
3360
+ });
3361
+ this.currentProvider = eip1193;
3362
+ this.currentChainId = chainId;
3363
+ if (provider.on) {
3364
+ provider.on("accountsChanged", this.handleAccountsChanged.bind(this));
3365
+ }
3366
+ } else {
3367
+ throw new Error(
3368
+ "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3369
+ );
3370
+ }
3371
+ }
3372
+ await this.authenticateUser();
3373
+ return connectedAddress;
3374
+ })();
3375
+ this.connectAccountInFlight = connect;
3376
+ try {
3377
+ return await connect;
3378
+ } finally {
3379
+ if (this.connectAccountInFlight === connect) {
3380
+ this.connectAccountInFlight = null;
3227
3381
  }
3228
3382
  }
3229
- await this.authenticateUser();
3230
- return connectedAddress;
3231
3383
  }
3232
3384
  /**
3233
3385
  * Clear the connected wallet, SIWE session, and cached smart-wallet state.
@@ -3293,6 +3445,51 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3293
3445
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3294
3446
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
3295
3447
  }
3448
+ /**
3449
+ * Nested Safe owners use intent sessions: finish any pending safe-deploy typed-data
3450
+ * (install or emissary enable), then register with chainId only.
3451
+ * @private
3452
+ */
3453
+ async registerNestedIntentSessionKey(userAddress, chainId, strategy) {
3454
+ if (!this.authenticatedUserId) {
3455
+ throw new Error(
3456
+ "User ID not available. Please ensure authentication completed successfully."
3457
+ );
3458
+ }
3459
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3460
+ await deploySafeAccount({
3461
+ owner: this.getWalletClient(chainId),
3462
+ safeOwnerAddress: userAddress,
3463
+ chain: chainConfig.chain,
3464
+ publicClient: chainConfig.publicClient,
3465
+ chainId,
3466
+ httpClient: this.httpClient,
3467
+ strategy
3468
+ });
3469
+ const activation = await this.httpClient.post(
3470
+ ENDPOINTS.SESSION_KEYS_ADD,
3471
+ { chainId }
3472
+ );
3473
+ this.hasActiveSessionKey = true;
3474
+ return {
3475
+ success: true,
3476
+ userId: this.authenticatedUserId,
3477
+ message: "Intent session key registered",
3478
+ alreadyActive: false,
3479
+ sessionActivation: activation
3480
+ };
3481
+ }
3482
+ async registerNestedChildProfile(childAddress, chainId, strategy) {
3483
+ await this.updateUserProfile({
3484
+ smartWallet: childAddress,
3485
+ executorProxy: true,
3486
+ chains: [chainId],
3487
+ strategy,
3488
+ protocols: [],
3489
+ autoSelectProtocols: false,
3490
+ asset: "USDC"
3491
+ });
3492
+ }
3296
3493
  /**
3297
3494
  * SIWE login sets predeployed. Agent sessions (`forUser`) do not, so read it
3298
3495
  * from the user record before allowing a transfer to an undeployed pool Safe.
@@ -3316,13 +3513,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3316
3513
  chainId
3317
3514
  );
3318
3515
  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
- );
3516
+ const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3326
3517
  if (!childDeployed) {
3327
3518
  await this.deploySafe(userAddress, chainId, strategy, true);
3328
3519
  return;
@@ -3375,6 +3566,25 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3375
3566
  }
3376
3567
  if (!deriveIfMissing) return null;
3377
3568
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3569
+ const ownerType = await getAccountType(
3570
+ userAddress,
3571
+ chainConfig.publicClient
3572
+ );
3573
+ if (ownerType === "Safe") {
3574
+ if (this.isConnectedUser(userAddress) && this.connectedSmartWallet) {
3575
+ return this.connectedSmartWallet;
3576
+ }
3577
+ try {
3578
+ if (this.httpClient.hasAuthToken()) {
3579
+ const me = await this.httpClient.get(
3580
+ ENDPOINTS.USER_ME
3581
+ );
3582
+ if (me?.smartWallet) return getAddress4(me.smartWallet);
3583
+ }
3584
+ } catch {
3585
+ }
3586
+ return null;
3587
+ }
3378
3588
  return getDeterministicSafeAddress({
3379
3589
  safeOwnerAddress: userAddress,
3380
3590
  chain: chainConfig.chain,
@@ -3404,8 +3614,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3404
3614
  throw new Error(`Unsupported chain ID: ${chainId}`);
3405
3615
  }
3406
3616
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3617
+ const ownerType = await getAccountType(
3618
+ userAddress,
3619
+ chainConfig.publicClient
3620
+ );
3407
3621
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3408
3622
  if (!safeAddress) {
3623
+ if (ownerType === "Safe") {
3624
+ throw new Error("NESTED_CHILD_UNREGISTERED");
3625
+ }
3409
3626
  throw new Error("Smart wallet address is not available");
3410
3627
  }
3411
3628
  const isDeployed = await isSafeDeployed(
@@ -3490,15 +3707,19 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3490
3707
  }
3491
3708
  const walletClient = this.getWalletClient(chainId);
3492
3709
  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,
3710
+ const ownerAccountType = await getAccountType(
3711
+ userAddress,
3499
3712
  chainConfig.publicClient
3500
3713
  );
3501
- if (alreadyDeployed) {
3714
+ const nestedSafeOwner = ownerAccountType === "Safe";
3715
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3716
+ if (!safeAddress && !nestedSafeOwner) {
3717
+ throw new Error(
3718
+ ownerAccountType === "EOA" ? "For nested deploy, connect WalletConnect as the parent Safe contract address, not the owner EOA." : "Smart wallet address is not available"
3719
+ );
3720
+ }
3721
+ const alreadyDeployed = safeAddress ? await isSafeDeployed(safeAddress, chainConfig.publicClient) : false;
3722
+ if (alreadyDeployed && safeAddress) {
3502
3723
  let enableTxHash = "0x0";
3503
3724
  if (!this.isPredeployed) {
3504
3725
  const enabled = await deploySafeAccount({
@@ -3508,7 +3729,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3508
3729
  publicClient: chainConfig.publicClient,
3509
3730
  chainId,
3510
3731
  httpClient: this.httpClient,
3511
- strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy"
3732
+ strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy",
3733
+ childSafeAddress: safeAddress
3512
3734
  });
3513
3735
  enableTxHash = enabled.txHash || "0x0";
3514
3736
  }
@@ -3541,7 +3763,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3541
3763
  publicClient: chainConfig.publicClient,
3542
3764
  chainId,
3543
3765
  httpClient: this.httpClient,
3544
- strategy: internalStrategy
3766
+ strategy: internalStrategy,
3767
+ childSafeAddress: safeAddress ?? void 0
3545
3768
  });
3546
3769
  this.hasActiveSessionKey = false;
3547
3770
  try {
@@ -3552,8 +3775,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3552
3775
  initError.message
3553
3776
  );
3554
3777
  }
3778
+ if (nestedSafeOwner) {
3779
+ await this.registerNestedChildProfile(
3780
+ deploymentResult.safeAddress,
3781
+ chainId,
3782
+ strategy
3783
+ );
3784
+ }
3555
3785
  await this.updateUserProtocols(strategy);
3556
- if (!this.isPredeployed) {
3786
+ if (!this.isPredeployed && !nestedSafeOwner) {
3557
3787
  await deploySafeAccount({
3558
3788
  owner: walletClient,
3559
3789
  safeOwnerAddress: userAddress,
@@ -3561,7 +3791,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3561
3791
  publicClient: chainConfig.publicClient,
3562
3792
  chainId,
3563
3793
  httpClient: this.httpClient,
3564
- strategy: internalStrategy
3794
+ strategy: internalStrategy,
3795
+ childSafeAddress: deploymentResult.safeAddress
3565
3796
  });
3566
3797
  }
3567
3798
  let sessionKeyCreated = false;
@@ -3664,14 +3895,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3664
3895
  chainConfig.publicClient
3665
3896
  );
3666
3897
  if (accountType === "Safe") {
3667
- await this.assertOwnerSafeOnSessionChains(
3898
+ return this.registerNestedIntentSessionKey(
3668
3899
  userAddress,
3669
- sessions
3900
+ chainId,
3901
+ void 0
3670
3902
  );
3671
3903
  }
3672
3904
  const signingParams = {
3673
3905
  permitGenericPolicy,
3674
- ignoreSecurityAttestations: accountType === "Safe"
3906
+ ignoreSecurityAttestations: false
3675
3907
  };
3676
3908
  const signatureResult = await this.signSessionKey(
3677
3909
  userAddress,
@@ -3701,38 +3933,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3701
3933
  }
3702
3934
  }
3703
3935
  /**
3704
- * Internal method to sign session key
3936
+ * Internal method to sign session key for an EOA owner.
3937
+ * Nested Safe owners register through {@link registerNestedIntentSessionKey}.
3705
3938
  * @private
3706
3939
  */
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
3940
  async signSessionKey(userAddress, chainId, sessions, signingParams) {
3737
3941
  try {
3738
3942
  if (!userAddress) {
@@ -8274,385 +8478,6 @@ function createBankrProvider(config) {
8274
8478
  };
8275
8479
  return provider;
8276
8480
  }
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
8481
  export {
8657
8482
  ALLOWED_HISTORY_DAYS,
8658
8483
  API_ENDPOINT,
@@ -8685,7 +8510,6 @@ export {
8685
8510
  ZyfaiSDK,
8686
8511
  buildV1ChainSessions,
8687
8512
  createBankrProvider,
8688
- createSafeOwnerProvider,
8689
8513
  decodeUserOperationCalls,
8690
8514
  getChainConfig,
8691
8515
  getDataApiBaseUrl,