@zyfai/sdk 1.8.0 → 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
@@ -1362,6 +1362,10 @@ var INTENT_EXECUTOR = "0x00000000005aD9ce1f5035FD62CA96CEf16AdAAF";
1362
1362
  var PROXY_EXECUTOR = "0xF659d30D4EB88B06A909F20839D8959Bd77d8790";
1363
1363
  var INTENT_SMART_SESSIONS = "0xad568b3f825a8d5ffc06dd3253526b64d810ae89";
1364
1364
  var OWNABLE_VALIDATOR = "0x000000000013fdB5234E4E3162a810F54d9f7E98";
1365
+ var OWNABLE_VALIDATOR_DEPLOYMENTS = [
1366
+ "0x2483DA3A338895199E5e538530213157e931Bf06",
1367
+ OWNABLE_VALIDATOR
1368
+ ];
1365
1369
  var SAFE_7579_ADDRESS = "0x7579EE8307284F293B1927136486880611F20002";
1366
1370
  var ERC7579_LAUNCHPAD_ADDRESS = "0x7579011aB74c46090561ea277Ba79D510c6C00ff";
1367
1371
  var POOL_MODULE_ADDRESSES = [
@@ -1377,7 +1381,8 @@ var POOL_MODULE_ADDRESSES = [
1377
1381
  import { SMART_SESSIONS_ADDRESS } from "@rhinestone/module-sdk";
1378
1382
  import {
1379
1383
  concat,
1380
- getAddress
1384
+ getAddress,
1385
+ hashTypedData
1381
1386
  } from "viem";
1382
1387
  var EMPTY_DATA = "0x";
1383
1388
  var SIGNATURE_LENGTH_BYTES = 65;
@@ -1503,12 +1508,9 @@ async function signMultiChainSessionTypedData(walletClient, typedData) {
1503
1508
  if (!walletClient.account) {
1504
1509
  throw new Error("Wallet not connected. Please connect your wallet first.");
1505
1510
  }
1506
- return walletClient.signTypedData({
1511
+ return walletClient.signMessage({
1507
1512
  account: walletClient.account,
1508
- domain: typedData.domain,
1509
- types: typedData.types,
1510
- primaryType: typedData.primaryType,
1511
- message: typedData.message
1513
+ message: { raw: hashTypedData(typedData) }
1512
1514
  });
1513
1515
  }
1514
1516
 
@@ -1597,13 +1599,12 @@ var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) =>
1597
1599
  }
1598
1600
  return false;
1599
1601
  };
1602
+ var isEip7702Delegation = (code) => !!code && code.toLowerCase().startsWith("0xef0100");
1603
+ var hasPersistentContractCode = (code) => !!code && code !== "0x" && !isEip7702Delegation(code);
1600
1604
  var getAccountType = async (address, publicClient) => {
1601
1605
  try {
1602
1606
  const code = await publicClient.getCode({ address });
1603
- if (!code || code === "0x" || code.length === 2) {
1604
- return "EOA";
1605
- }
1606
- if (code.startsWith("0xef01")) {
1607
+ if (!code || code === "0x" || code.length === 2 || isEip7702Delegation(code)) {
1607
1608
  return "EOA";
1608
1609
  }
1609
1610
  try {
@@ -1631,23 +1632,85 @@ var getAccountType = async (address, publicClient) => {
1631
1632
  return "Unknown";
1632
1633
  }
1633
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
+ };
1634
1663
  var deploySafeAccount = async (config) => {
1635
1664
  try {
1636
- const { owner, httpClient, chainId, strategy = "safe_strategy" } = config;
1665
+ const {
1666
+ owner,
1667
+ httpClient,
1668
+ chainId,
1669
+ publicClient,
1670
+ safeOwnerAddress,
1671
+ strategy
1672
+ } = config;
1637
1673
  if (!owner || !owner.account) {
1638
1674
  throw new Error(
1639
1675
  "Wallet not connected. Please connect your wallet first."
1640
1676
  );
1641
1677
  }
1642
1678
  console.log("strategy", strategy);
1679
+ const strategyBody = strategy ? { strategy } : {};
1643
1680
  const prepareResponse = await httpClient.post(
1644
1681
  `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1645
- { strategy }
1682
+ strategyBody
1646
1683
  );
1647
1684
  console.log("prepareResponse", prepareResponse);
1685
+ if (prepareResponse.success && !prepareResponse.userOpHashToSign && prepareResponse.signingMode !== "typed-data") {
1686
+ return {
1687
+ safeAddress: prepareResponse.safeAddress || "0x",
1688
+ txHash: "0x0",
1689
+ isDeployed: true
1690
+ };
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
+ }
1648
1711
  if (!prepareResponse.userOpHashToSign) {
1649
1712
  throw new Error(
1650
- "Backend did not return userOpHashToSign. Response: " + JSON.stringify(prepareResponse)
1713
+ "Backend did not return userOpHashToSign or typed-data to sign. Response: " + JSON.stringify(prepareResponse)
1651
1714
  );
1652
1715
  }
1653
1716
  const userOpHashToSign = prepareResponse.userOpHashToSign;
@@ -1655,20 +1718,29 @@ var deploySafeAccount = async (config) => {
1655
1718
  account: owner.account,
1656
1719
  message: { raw: userOpHashToSign }
1657
1720
  });
1658
- const deployResponse = await httpClient.post(
1659
- `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1660
- { userOpSignature, strategy }
1661
- );
1662
- if (!deployResponse.success) {
1663
- throw new Error(
1664
- `Safe deployment failed: ${JSON.stringify(deployResponse)}`
1721
+ const ownerAddress = getAddress2(safeOwnerAddress);
1722
+ const ownerCode = await publicClient.getCode({ address: ownerAddress }).catch((error) => {
1723
+ console.warn(
1724
+ `[ZyfaiSDK] Could not read code at owner ${ownerAddress}: ${error.message}. Submitting the owner signature unwrapped; a contract owner will be rejected with AA24.`
1665
1725
  );
1666
- }
1667
- return {
1668
- safeAddress: deployResponse.safeAddress || "0x",
1669
- txHash: deployResponse.txHash,
1670
- isDeployed: true
1671
- };
1726
+ return void 0;
1727
+ });
1728
+ const delegatedEoa = isEip7702Delegation(ownerCode);
1729
+ const wrapContractSignature = hasPersistentContractCode(ownerCode);
1730
+ const ownerKind = delegatedEoa ? "eip7702" : wrapContractSignature ? "contract" : "eoa";
1731
+ console.info(
1732
+ `[ZyfaiSDK] safe-deploy signature chainId=${chainId} owner=${ownerAddress} ownerKind=${ownerKind} wrapped=${wrapContractSignature}`
1733
+ );
1734
+ const signatureToSubmit = wrapContractSignature ? buildSafeSignatureBytes([
1735
+ {
1736
+ signer: ownerAddress,
1737
+ data: userOpSignature,
1738
+ isContractSignature: true
1739
+ }
1740
+ ]) : userOpSignature;
1741
+ return completeSafeDeploy(config, strategyBody, {
1742
+ userOpSignature: signatureToSubmit
1743
+ });
1672
1744
  } catch (error) {
1673
1745
  throw new Error(
1674
1746
  `Failed to deploy Safe account: ${error.message}`
@@ -1730,6 +1802,33 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
1730
1802
  sessionNonces
1731
1803
  };
1732
1804
  };
1805
+ var IS_MODULE_INSTALLED_ABI = [
1806
+ {
1807
+ type: "function",
1808
+ name: "isModuleInstalled",
1809
+ stateMutability: "view",
1810
+ inputs: [
1811
+ { name: "moduleTypeId", type: "uint256" },
1812
+ { name: "module", type: "address" },
1813
+ { name: "additionalContext", type: "bytes" }
1814
+ ],
1815
+ outputs: [{ type: "bool" }]
1816
+ }
1817
+ ];
1818
+ async function resolveOwnerValidator(publicClient, childSafeAddress) {
1819
+ for (const candidate of OWNABLE_VALIDATOR_DEPLOYMENTS) {
1820
+ const installed = await publicClient.readContract({
1821
+ address: childSafeAddress,
1822
+ abi: IS_MODULE_INSTALLED_ABI,
1823
+ functionName: "isModuleInstalled",
1824
+ args: [1n, candidate, "0x"]
1825
+ }).catch(() => false);
1826
+ if (installed) return candidate;
1827
+ }
1828
+ throw new Error(
1829
+ `No known OwnableValidator is installed on Safe ${childSafeAddress}. A nested Safe owner signature cannot be routed to a validator.`
1830
+ );
1831
+ }
1733
1832
  async function signNestedOwnerSessionKey(config, sessions, allPublicClients, signingParams) {
1734
1833
  const { owner, publicClient, safeOwnerAddress } = config;
1735
1834
  const derivedChild = (await getSafeAccount(config)).address;
@@ -1761,17 +1860,15 @@ async function signNestedOwnerSessionKey(config, sessions, allPublicClients, sig
1761
1860
  sessionNonces,
1762
1861
  permitGenericPolicy
1763
1862
  });
1764
- const sessionValidator = sessions[0]?.sessionValidator;
1765
- if (!sessionValidator) {
1766
- throw new Error(
1767
- "Session configuration has no sessionValidator. The nested Safe signature cannot be routed to a validator."
1768
- );
1769
- }
1863
+ const ownerValidator = await resolveOwnerValidator(
1864
+ publicClient,
1865
+ childSafeAddress
1866
+ );
1770
1867
  const rawSignature = await signMultiChainSessionTypedData(owner, typedData);
1771
1868
  const signature = wrapNestedSafeOwnerSignature(
1772
1869
  safeOwnerAddress,
1773
1870
  rawSignature,
1774
- sessionValidator
1871
+ ownerValidator
1775
1872
  );
1776
1873
  return {
1777
1874
  signature,
@@ -2467,7 +2564,7 @@ var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
2467
2564
  };
2468
2565
 
2469
2566
  // src/core/ZyfaiSDK.ts
2470
- import { SiweMessage } from "siwe";
2567
+ import { createSiweMessage } from "viem/siwe";
2471
2568
  var DepositCreditTimeoutError = class extends Error {
2472
2569
  constructor(depositId) {
2473
2570
  super(`Timed out waiting for deposit ${depositId} to be credited`);
@@ -2539,6 +2636,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2539
2636
  this.currentChainId = null;
2540
2637
  /** EOA of the active user session (bearer or SIWE). Cleared on disconnect. */
2541
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;
2542
2643
  const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
2543
2644
  const {
2544
2645
  apiKey,
@@ -2663,16 +2764,33 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2663
2764
  *
2664
2765
  * @returns Promise that resolves when authentication is complete
2665
2766
  */
2666
- 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() {
2667
2781
  try {
2668
- if (this.authenticatedUserId !== null) {
2669
- return;
2670
- }
2671
- if (this.httpClient.hasAuthToken()) {
2782
+ if (this.authenticatedUserId !== null || this.httpClient.hasAuthToken()) {
2672
2783
  return;
2673
2784
  }
2674
2785
  const walletClient = this.getWalletClient();
2675
- 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);
2676
2794
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
2677
2795
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
2678
2796
  let uri;
@@ -2686,7 +2804,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2686
2804
  uri = this.executionApiUrl;
2687
2805
  domain = new URL(this.executionApiUrl).host;
2688
2806
  }
2689
- const messageObj = new SiweMessage({
2807
+ const issuedAt = /* @__PURE__ */ new Date();
2808
+ const messageFields = {
2690
2809
  address: userAddress,
2691
2810
  chainId,
2692
2811
  domain,
@@ -2694,11 +2813,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2694
2813
  statement: "Sign in with Ethereum",
2695
2814
  uri,
2696
2815
  version: "1",
2697
- issuedAt: (/* @__PURE__ */ new Date()).toISOString()
2698
- });
2699
- const messageString = messageObj.prepareMessage();
2816
+ issuedAt
2817
+ };
2818
+ const messageString = createSiweMessage(messageFields);
2819
+ const messageObj = {
2820
+ ...messageFields,
2821
+ issuedAt: issuedAt.toISOString()
2822
+ };
2700
2823
  const signature = await walletClient.signMessage({
2701
- account: walletClient.account,
2824
+ account: userAddress,
2702
2825
  message: messageString
2703
2826
  });
2704
2827
  const loginResponse = await this.httpClient.post(
@@ -2786,6 +2909,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2786
2909
  [internalAsset]: assetSettings
2787
2910
  }
2788
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;
2789
2917
  if (request.omniAccount !== void 0)
2790
2918
  payload.omniAccount = request.omniAccount;
2791
2919
  if (request.agentName !== void 0)
@@ -3091,82 +3219,167 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3091
3219
  * const provider = await connector.getProvider();
3092
3220
  * await sdk.connectAccount(provider);
3093
3221
  */
3094
- async connectAccount(account, chainId = 8453) {
3095
- if (!isSupportedChain(chainId)) {
3096
- throw new Error(`Unsupported chain ID: ${chainId}`);
3097
- }
3098
- this.authenticatedUserId = null;
3099
- this.isPredeployed = false;
3100
- this.predeployedResolved = false;
3101
- this.connectedSmartWallet = null;
3102
- this.currentChainId = null;
3103
- this.sessionEoa = null;
3104
- this.sessionChannel = void 0;
3105
- this.httpClient.clearAuthToken();
3106
- if (this.currentProvider?.removeAllListeners) {
3107
- try {
3108
- this.currentProvider.removeAllListeners("accountsChanged");
3109
- } catch (error) {
3110
- }
3111
- }
3112
- const chainConfig = getChainConfig(chainId, this.rpcUrls);
3113
- let connectedAddress;
3222
+ async resolveConnectAddress(account) {
3114
3223
  if (typeof account === "string") {
3115
3224
  let privateKey = account;
3116
3225
  if (!privateKey.startsWith("0x")) {
3117
3226
  privateKey = `0x${privateKey}`;
3118
3227
  }
3119
- this.signer = privateKeyToAccount(privateKey);
3120
- this.currentChainId = chainId;
3121
- this.walletClient = createWalletClient({
3122
- account: this.signer,
3123
- chain: chainConfig.chain,
3124
- 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"
3125
3253
  });
3126
- connectedAddress = this.signer.address;
3127
- this.currentProvider = null;
3128
- } else {
3129
- const provider = account;
3130
- 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) {
3131
3260
  throw new Error(
3132
- "Invalid account parameter. Expected private key string or wallet provider."
3261
+ "Wallet returned an account without an address. Reconnect via WalletConnect."
3133
3262
  );
3134
3263
  }
3135
- if (provider.request) {
3136
- const accounts = await provider.request({
3137
- method: "eth_requestAccounts"
3138
- });
3139
- if (!accounts || accounts.length === 0) {
3140
- 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) {
3141
3295
  }
3142
- this.walletClient = createWalletClient({
3143
- account: accounts[0],
3144
- chain: chainConfig.chain,
3145
- transport: custom(provider)
3146
- });
3147
- connectedAddress = accounts[0];
3148
- this.currentProvider = provider;
3149
- this.currentChainId = chainId;
3150
- if (provider.on) {
3151
- 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}`;
3152
3303
  }
3153
- } else if (provider.account && provider.transport) {
3304
+ this.signer = privateKeyToAccount(privateKey);
3305
+ this.currentChainId = chainId;
3154
3306
  this.walletClient = createWalletClient({
3155
- account: provider.account,
3307
+ account: this.signer,
3156
3308
  chain: chainConfig.chain,
3157
- transport: provider.transport
3309
+ transport: http2(chainConfig.rpcUrl)
3158
3310
  });
3159
- connectedAddress = provider.account.address;
3311
+ connectedAddress = this.signer.address;
3160
3312
  this.currentProvider = null;
3161
- this.currentChainId = chainId;
3162
3313
  } else {
3163
- throw new Error(
3164
- "Invalid wallet provider. Expected EIP-1193 provider or viem WalletClient."
3165
- );
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;
3166
3381
  }
3167
3382
  }
3168
- await this.authenticateUser();
3169
- return connectedAddress;
3170
3383
  }
3171
3384
  /**
3172
3385
  * Clear the connected wallet, SIWE session, and cached smart-wallet state.
@@ -3232,6 +3445,51 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3232
3445
  const connected = this.signer?.address ?? this.walletClient?.account?.address ?? this.sessionEoa;
3233
3446
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
3234
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
+ }
3235
3493
  /**
3236
3494
  * SIWE login sets predeployed. Agent sessions (`forUser`) do not, so read it
3237
3495
  * from the user record before allowing a transfer to an undeployed pool Safe.
@@ -3255,26 +3513,24 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3255
3513
  chainId
3256
3514
  );
3257
3515
  const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3258
- if (!childAddress) {
3259
- throw new Error("Child smart wallet address is not available");
3260
- }
3261
- const childDeployed = await isSafeDeployed(
3262
- childAddress,
3263
- chainConfig.publicClient
3264
- );
3516
+ const childDeployed = childAddress ? await isSafeDeployed(childAddress, chainConfig.publicClient) : false;
3265
3517
  if (!childDeployed) {
3266
3518
  await this.deploySafe(userAddress, chainId, strategy, true);
3267
3519
  return;
3268
3520
  }
3521
+ console.info(
3522
+ `[ZyfaiSDK] nested deposit signing pending enable only chainId=${chainId} owner=${userAddress} sessionActive=${this.hasActiveSessionKey}`
3523
+ );
3524
+ await deploySafeAccount({
3525
+ owner: this.getWalletClient(chainId),
3526
+ safeOwnerAddress: userAddress,
3527
+ chain: chainConfig.chain,
3528
+ publicClient: chainConfig.publicClient,
3529
+ chainId,
3530
+ httpClient: this.httpClient
3531
+ });
3269
3532
  if (!this.hasActiveSessionKey) {
3270
- try {
3271
- await this.createSessionKey(userAddress, chainId);
3272
- } catch (sessionError) {
3273
- console.warn(
3274
- "Failed to create session key for nested owner:",
3275
- sessionError.message
3276
- );
3277
- }
3533
+ await this.createSessionKey(userAddress, chainId);
3278
3534
  }
3279
3535
  }
3280
3536
  async hydrateSessionWallet() {
@@ -3310,6 +3566,25 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3310
3566
  }
3311
3567
  if (!deriveIfMissing) return null;
3312
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
+ }
3313
3588
  return getDeterministicSafeAddress({
3314
3589
  safeOwnerAddress: userAddress,
3315
3590
  chain: chainConfig.chain,
@@ -3339,8 +3614,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3339
3614
  throw new Error(`Unsupported chain ID: ${chainId}`);
3340
3615
  }
3341
3616
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3617
+ const ownerType = await getAccountType(
3618
+ userAddress,
3619
+ chainConfig.publicClient
3620
+ );
3342
3621
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3343
3622
  if (!safeAddress) {
3623
+ if (ownerType === "Safe") {
3624
+ throw new Error("NESTED_CHILD_UNREGISTERED");
3625
+ }
3344
3626
  throw new Error("Smart wallet address is not available");
3345
3627
  }
3346
3628
  const isDeployed = await isSafeDeployed(
@@ -3425,16 +3707,33 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3425
3707
  }
3426
3708
  const walletClient = this.getWalletClient(chainId);
3427
3709
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3428
- const safeAddress = await getDeterministicSafeAddress({
3429
- safeOwnerAddress: userAddress,
3430
- chain: chainConfig.chain,
3431
- publicClient: chainConfig.publicClient
3432
- });
3433
- const alreadyDeployed = await isSafeDeployed(
3434
- safeAddress,
3710
+ const ownerAccountType = await getAccountType(
3711
+ userAddress,
3435
3712
  chainConfig.publicClient
3436
3713
  );
3437
- 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) {
3723
+ let enableTxHash = "0x0";
3724
+ if (!this.isPredeployed) {
3725
+ const enabled = await deploySafeAccount({
3726
+ owner: walletClient,
3727
+ safeOwnerAddress: userAddress,
3728
+ chain: chainConfig.chain,
3729
+ publicClient: chainConfig.publicClient,
3730
+ chainId,
3731
+ httpClient: this.httpClient,
3732
+ strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy",
3733
+ childSafeAddress: safeAddress
3734
+ });
3735
+ enableTxHash = enabled.txHash || "0x0";
3736
+ }
3438
3737
  await this.updateUserProtocols(strategy);
3439
3738
  let sessionKeyCreated2 = false;
3440
3739
  if (createSessionKey) {
@@ -3451,7 +3750,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3451
3750
  return {
3452
3751
  success: true,
3453
3752
  safeAddress,
3454
- txHash: "0x0",
3753
+ txHash: enableTxHash,
3455
3754
  status: "deployed",
3456
3755
  sessionKeyCreated: sessionKeyCreated2
3457
3756
  };
@@ -3464,7 +3763,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3464
3763
  publicClient: chainConfig.publicClient,
3465
3764
  chainId,
3466
3765
  httpClient: this.httpClient,
3467
- strategy: internalStrategy
3766
+ strategy: internalStrategy,
3767
+ childSafeAddress: safeAddress ?? void 0
3468
3768
  });
3469
3769
  this.hasActiveSessionKey = false;
3470
3770
  try {
@@ -3475,7 +3775,26 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3475
3775
  initError.message
3476
3776
  );
3477
3777
  }
3778
+ if (nestedSafeOwner) {
3779
+ await this.registerNestedChildProfile(
3780
+ deploymentResult.safeAddress,
3781
+ chainId,
3782
+ strategy
3783
+ );
3784
+ }
3478
3785
  await this.updateUserProtocols(strategy);
3786
+ if (!this.isPredeployed && !nestedSafeOwner) {
3787
+ await deploySafeAccount({
3788
+ owner: walletClient,
3789
+ safeOwnerAddress: userAddress,
3790
+ chain: chainConfig.chain,
3791
+ publicClient: chainConfig.publicClient,
3792
+ chainId,
3793
+ httpClient: this.httpClient,
3794
+ strategy: internalStrategy,
3795
+ childSafeAddress: deploymentResult.safeAddress
3796
+ });
3797
+ }
3479
3798
  let sessionKeyCreated = false;
3480
3799
  if (createSessionKey) {
3481
3800
  try {
@@ -3576,14 +3895,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3576
3895
  chainConfig.publicClient
3577
3896
  );
3578
3897
  if (accountType === "Safe") {
3579
- await this.assertOwnerSafeOnSessionChains(
3898
+ return this.registerNestedIntentSessionKey(
3580
3899
  userAddress,
3581
- sessions
3900
+ chainId,
3901
+ void 0
3582
3902
  );
3583
3903
  }
3584
3904
  const signingParams = {
3585
3905
  permitGenericPolicy,
3586
- ignoreSecurityAttestations: accountType === "Safe"
3906
+ ignoreSecurityAttestations: false
3587
3907
  };
3588
3908
  const signatureResult = await this.signSessionKey(
3589
3909
  userAddress,
@@ -3613,38 +3933,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3613
3933
  }
3614
3934
  }
3615
3935
  /**
3616
- * Internal method to sign session key
3617
- * @private
3618
- */
3619
- /**
3620
- * A nested Safe owner signs one MultiChainSession covering every chain in the
3621
- * session configuration, and the child validates that signature against the
3622
- * owner through ERC-1271 on each of them. A chain where the owner has no code
3623
- * would accept the signature nowhere, so refuse rather than sign it.
3624
- *
3625
- * The session list is not filtered here: the execution API rebuilds the digest
3626
- * from its own configuration, so dropping a chain client-side would change the
3627
- * hash and the signature would be rejected everywhere.
3936
+ * Internal method to sign session key for an EOA owner.
3937
+ * Nested Safe owners register through {@link registerNestedIntentSessionKey}.
3628
3938
  * @private
3629
3939
  */
3630
- async assertOwnerSafeOnSessionChains(ownerAddress, sessions) {
3631
- const chainIds = [
3632
- ...new Set(sessions.map((session) => Number(session.chainId)))
3633
- ].filter(isSupportedChain);
3634
- const missing = [];
3635
- await Promise.all(
3636
- chainIds.map(async (id) => {
3637
- const { publicClient } = getChainConfig(id, this.rpcUrls);
3638
- const code = await publicClient.getCode({ address: ownerAddress });
3639
- if (!code || code === "0x") missing.push(id);
3640
- })
3641
- );
3642
- if (missing.length > 0) {
3643
- throw new Error(
3644
- `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.`
3645
- );
3646
- }
3647
- }
3648
3940
  async signSessionKey(userAddress, chainId, sessions, signingParams) {
3649
3941
  try {
3650
3942
  if (!userAddress) {
@@ -8186,385 +8478,6 @@ function createBankrProvider(config) {
8186
8478
  };
8187
8479
  return provider;
8188
8480
  }
8189
-
8190
- // src/providers/safe-owner.ts
8191
- import {
8192
- createPublicClient as createPublicClient2,
8193
- createWalletClient as createWalletClient2,
8194
- encodeAbiParameters as encodeAbiParameters2,
8195
- encodeFunctionData as encodeFunctionData3,
8196
- getAddress as getAddress5,
8197
- hashMessage as hashMessage2,
8198
- hashTypedData,
8199
- hexToSignature,
8200
- http as http3,
8201
- isAddress as isAddress3,
8202
- parseAbi as parseAbi3,
8203
- signatureToHex,
8204
- stringToHex
8205
- } from "viem";
8206
- var EIP1271_MAGIC_VALUE = "0x1626ba7e";
8207
- var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
8208
- var SAFE_ABI2 = parseAbi3([
8209
- "function getThreshold() view returns (uint256)",
8210
- "function getOwners() view returns (address[])",
8211
- "function nonce() view returns (uint256)",
8212
- "function getMessageHash(bytes message) view returns (bytes32)",
8213
- "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)",
8214
- "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)",
8215
- "function isValidSignature(bytes32 _dataHash, bytes _signature) view returns (bytes4)"
8216
- ]);
8217
- async function createSafeOwnerProvider(config) {
8218
- if (!isAddress3(config.safeAddress)) {
8219
- throw new Error("safeAddress must be an Ethereum address");
8220
- }
8221
- const safeAddress = getAddress5(config.safeAddress);
8222
- const publicClient = createPublicClient2({
8223
- chain: config.chain,
8224
- transport: http3()
8225
- });
8226
- const ownerWallet = await resolveOwnerWallet(config.owner, config.chain);
8227
- const code = await publicClient.getCode({ address: safeAddress });
8228
- if (!code || code === "0x") {
8229
- throw new Error(
8230
- `Safe ${safeAddress} has no code on chain ${config.chain.id}`
8231
- );
8232
- }
8233
- const [threshold, owners] = await Promise.all([
8234
- publicClient.readContract({
8235
- address: safeAddress,
8236
- abi: SAFE_ABI2,
8237
- functionName: "getThreshold"
8238
- }),
8239
- publicClient.readContract({
8240
- address: safeAddress,
8241
- abi: SAFE_ABI2,
8242
- functionName: "getOwners"
8243
- })
8244
- ]);
8245
- if (threshold !== 1n) {
8246
- throw new Error(
8247
- `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.`
8248
- );
8249
- }
8250
- const ownerAddress = ownerWallet.address;
8251
- if (!owners.some((owner) => getAddress5(owner) === ownerAddress)) {
8252
- throw new Error(`${ownerAddress} is not an owner of Safe ${safeAddress}`);
8253
- }
8254
- const signSafeDigest = async (dataHash) => {
8255
- const encoded = encodeAbiParameters2([{ type: "bytes32" }], [dataHash]);
8256
- const messageHash = await publicClient.readContract({
8257
- address: safeAddress,
8258
- abi: SAFE_ABI2,
8259
- functionName: "getMessageHash",
8260
- args: [encoded]
8261
- });
8262
- return ownerWallet.signHash(messageHash);
8263
- };
8264
- const probeHash = hashMessage2("zyfai safe owner");
8265
- const probeSignature = await signSafeDigest(probeHash);
8266
- const magic = await publicClient.readContract({
8267
- address: safeAddress,
8268
- abi: SAFE_ABI2,
8269
- functionName: "isValidSignature",
8270
- args: [probeHash, probeSignature]
8271
- });
8272
- if (magic.toLowerCase() !== EIP1271_MAGIC_VALUE) {
8273
- throw new Error(
8274
- `Safe ${safeAddress} rejected the owner signature (isValidSignature returned ${magic})`
8275
- );
8276
- }
8277
- const executeFromSafe = async (tx) => {
8278
- const nonce = await publicClient.readContract({
8279
- address: safeAddress,
8280
- abi: SAFE_ABI2,
8281
- functionName: "nonce"
8282
- });
8283
- const safeTxHash = await publicClient.readContract({
8284
- address: safeAddress,
8285
- abi: SAFE_ABI2,
8286
- functionName: "getTransactionHash",
8287
- args: [
8288
- tx.to,
8289
- tx.value,
8290
- tx.data,
8291
- 0,
8292
- 0n,
8293
- 0n,
8294
- 0n,
8295
- ZERO_ADDRESS,
8296
- ZERO_ADDRESS,
8297
- nonce
8298
- ]
8299
- });
8300
- const signature = await ownerWallet.signHash(safeTxHash);
8301
- const data = encodeFunctionData3({
8302
- abi: SAFE_ABI2,
8303
- functionName: "execTransaction",
8304
- args: [
8305
- tx.to,
8306
- tx.value,
8307
- tx.data,
8308
- 0,
8309
- 0n,
8310
- 0n,
8311
- 0n,
8312
- ZERO_ADDRESS,
8313
- ZERO_ADDRESS,
8314
- signature
8315
- ]
8316
- });
8317
- const hash = await ownerWallet.sendTransaction({
8318
- to: safeAddress,
8319
- data,
8320
- value: 0n
8321
- });
8322
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
8323
- if (receipt.status !== "success") {
8324
- throw new Error(`Safe transaction reverted: ${hash}`);
8325
- }
8326
- return hash;
8327
- };
8328
- return {
8329
- async request({ method, params }) {
8330
- if (method === "eth_requestAccounts" || method === "eth_accounts") {
8331
- return [safeAddress];
8332
- }
8333
- if (method === "personal_sign" || method === "eth_sign") {
8334
- return signSafeDigest(personalSignDigest(params));
8335
- }
8336
- if (method === "eth_signTypedData_v4" || method === "eth_signTypedData") {
8337
- return signSafeDigest(typedDataDigest(params));
8338
- }
8339
- if (method === "eth_sendTransaction" || method === "wallet_sendTransaction") {
8340
- return executeFromSafe(readSafeTransaction(params));
8341
- }
8342
- return publicClient.request({
8343
- method,
8344
- params: params ?? []
8345
- });
8346
- }
8347
- };
8348
- }
8349
- async function resolveOwnerWallet(owner, chain) {
8350
- if (isHashSigner(owner)) {
8351
- const address = getAddress5(owner.address);
8352
- const wallet = createWalletClient2({
8353
- account: owner,
8354
- chain,
8355
- transport: http3()
8356
- });
8357
- return {
8358
- address,
8359
- signHash: (hash) => owner.sign({ hash }),
8360
- signTypedData: (params) => signAccountTypedData(owner, params),
8361
- sendTransaction: (tx) => wallet.sendTransaction({
8362
- account: owner,
8363
- chain,
8364
- to: tx.to,
8365
- data: tx.data,
8366
- value: tx.value
8367
- })
8368
- };
8369
- }
8370
- if (isWalletClient(owner)) {
8371
- const address = await walletClientAddress(owner);
8372
- return {
8373
- address,
8374
- signHash: (hash) => signOwnerHash(looseRequest(owner.request), owner.account, address, hash),
8375
- signTypedData: (params) => {
8376
- const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8377
- return owner.signTypedData({
8378
- account: owner.account ?? address,
8379
- domain,
8380
- types,
8381
- primaryType,
8382
- message
8383
- });
8384
- },
8385
- sendTransaction: (tx) => owner.sendTransaction({
8386
- account: owner.account ?? address,
8387
- chain: owner.chain ?? chain,
8388
- to: tx.to,
8389
- data: tx.data,
8390
- value: tx.value
8391
- })
8392
- };
8393
- }
8394
- if (isEip1193(owner)) {
8395
- const address = await eip1193Address(owner);
8396
- return {
8397
- address,
8398
- signHash: (hash) => signOwnerHash(looseRequest(owner.request), void 0, address, hash),
8399
- signTypedData: async (params) => {
8400
- const { requestPayload } = parseTypedDataPayload(params);
8401
- const signature = await owner.request({
8402
- method: "eth_signTypedData_v4",
8403
- params: [address, JSON.stringify(requestPayload)]
8404
- });
8405
- if (typeof signature !== "string" || !signature.startsWith("0x")) {
8406
- throw new Error("Owner wallet did not return a typed-data signature");
8407
- }
8408
- return signature;
8409
- },
8410
- sendTransaction: async (tx) => {
8411
- const hash = await owner.request({
8412
- method: "eth_sendTransaction",
8413
- params: [
8414
- {
8415
- from: address,
8416
- to: tx.to,
8417
- data: tx.data,
8418
- value: tx.value === 0n ? "0x0" : `0x${tx.value.toString(16)}`
8419
- }
8420
- ]
8421
- });
8422
- if (typeof hash !== "string" || !hash.startsWith("0x")) {
8423
- throw new Error("Owner wallet did not return a transaction hash");
8424
- }
8425
- return hash;
8426
- }
8427
- };
8428
- }
8429
- throw new Error(
8430
- "owner must be a viem wallet client, an account that can sign hashes, or an EIP-1193 provider"
8431
- );
8432
- }
8433
- function isWalletClient(owner) {
8434
- return typeof owner === "object" && owner !== null && "transport" in owner && "sendTransaction" in owner && typeof owner.sendTransaction === "function";
8435
- }
8436
- function isHashSigner(owner) {
8437
- return typeof owner === "object" && owner !== null && "address" in owner && "sign" in owner && typeof owner.sign === "function" && !("transport" in owner);
8438
- }
8439
- function isEip1193(owner) {
8440
- return typeof owner === "object" && owner !== null && "request" in owner && typeof owner.request === "function" && !("transport" in owner) && !isHashSigner(owner);
8441
- }
8442
- function looseRequest(request) {
8443
- return request;
8444
- }
8445
- async function walletClientAddress(owner) {
8446
- if (owner.account?.address && isAddress3(owner.account.address)) {
8447
- return getAddress5(owner.account.address);
8448
- }
8449
- return requestAccount(looseRequest(owner.request));
8450
- }
8451
- async function eip1193Address(owner) {
8452
- return requestAccount(looseRequest(owner.request));
8453
- }
8454
- async function requestAccount(request) {
8455
- const accounts = await request({ method: "eth_requestAccounts" });
8456
- const first = Array.isArray(accounts) ? accounts[0] : void 0;
8457
- if (typeof first !== "string" || !isAddress3(first)) {
8458
- throw new Error("Owner wallet did not return an account");
8459
- }
8460
- return getAddress5(first);
8461
- }
8462
- async function signOwnerHash(request, account, address, hash) {
8463
- if (account?.sign) {
8464
- return account.sign({ hash });
8465
- }
8466
- const signature = await request({
8467
- method: "personal_sign",
8468
- params: [hash, address]
8469
- });
8470
- if (typeof signature !== "string" || !signature.startsWith("0x")) {
8471
- throw new Error("Owner wallet did not return a signature");
8472
- }
8473
- return asSafeEthSign(signature);
8474
- }
8475
- function asSafeEthSign(signature) {
8476
- const sig = hexToSignature(signature);
8477
- const current = sig.v === void 0 ? sig.yParity === 1 ? 28 : 27 : Number(sig.v);
8478
- const v = current >= 27 ? current + 4 : current + 31;
8479
- return signatureToHex({ r: sig.r, s: sig.s, v: BigInt(v) });
8480
- }
8481
- function personalSignDigest(params) {
8482
- const [first, second] = params ?? [];
8483
- const message = typeof first === "string" && isAddress3(first) ? second : first;
8484
- const hex = typeof message === "string" && message.startsWith("0x") ? message : stringToHex(String(message ?? ""));
8485
- return hashMessage2({ raw: hex });
8486
- }
8487
- function parseTypedDataPayload(params) {
8488
- const [first, second] = params ?? [];
8489
- const payload = typeof first === "string" && isAddress3(first) ? second : first;
8490
- const parsed = typeof payload === "string" ? JSON.parse(payload) : payload;
8491
- const types = { ...parsed.types };
8492
- delete types.EIP712Domain;
8493
- const domain = { ...parsed.domain ?? {} };
8494
- if (typeof domain.chainId === "string") {
8495
- domain.chainId = BigInt(domain.chainId);
8496
- }
8497
- const message = coerceEip712Value(
8498
- parsed.primaryType,
8499
- parsed.message,
8500
- types
8501
- );
8502
- return {
8503
- domain,
8504
- types,
8505
- primaryType: parsed.primaryType,
8506
- message,
8507
- requestPayload: parsed
8508
- };
8509
- }
8510
- function typedDataDigest(params) {
8511
- const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8512
- return hashTypedData({ domain, types, primaryType, message });
8513
- }
8514
- async function signAccountTypedData(account, params) {
8515
- const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8516
- if (!account.signTypedData) {
8517
- throw new Error("Owner account cannot sign typed data");
8518
- }
8519
- return account.signTypedData({
8520
- domain,
8521
- types,
8522
- primaryType,
8523
- message
8524
- });
8525
- }
8526
- function coerceEip712Value(type, value, types) {
8527
- if (value == null) return value;
8528
- const array = type.match(/^(.*)\[(\d*)\]$/);
8529
- if (array) {
8530
- if (!Array.isArray(value)) return value;
8531
- return value.map((item) => coerceEip712Value(array[1], item, types));
8532
- }
8533
- const struct = types[type];
8534
- if (struct) {
8535
- if (typeof value !== "object" || Array.isArray(value)) return value;
8536
- const record = value;
8537
- const next = {};
8538
- for (const field of struct) {
8539
- next[field.name] = coerceEip712Value(
8540
- field.type,
8541
- record[field.name],
8542
- types
8543
- );
8544
- }
8545
- return next;
8546
- }
8547
- if (/^u?int\d*$/.test(type)) {
8548
- if (typeof value === "bigint") return value;
8549
- if (typeof value === "string" || typeof value === "number") {
8550
- return BigInt(value);
8551
- }
8552
- }
8553
- return value;
8554
- }
8555
- function readSafeTransaction(params) {
8556
- const tx = Array.isArray(params) ? params[0] : void 0;
8557
- if (!tx?.to || !isAddress3(tx.to)) {
8558
- throw new Error("Safe transaction is missing a destination");
8559
- }
8560
- const data = typeof tx.data === "string" && tx.data.startsWith("0x") ? tx.data : "0x";
8561
- let value = 0n;
8562
- if (typeof tx.value === "bigint") value = tx.value;
8563
- else if (typeof tx.value === "number" || typeof tx.value === "string") {
8564
- value = BigInt(tx.value);
8565
- }
8566
- return { to: getAddress5(tx.to), data, value };
8567
- }
8568
8481
  export {
8569
8482
  ALLOWED_HISTORY_DAYS,
8570
8483
  API_ENDPOINT,
@@ -8597,7 +8510,6 @@ export {
8597
8510
  ZyfaiSDK,
8598
8511
  buildV1ChainSessions,
8599
8512
  createBankrProvider,
8600
- createSafeOwnerProvider,
8601
8513
  decodeUserOperationCalls,
8602
8514
  getChainConfig,
8603
8515
  getDataApiBaseUrl,