@zyfai/sdk 1.5.0 → 1.8.0

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
@@ -842,7 +842,7 @@ import {
842
842
  createWalletClient,
843
843
  custom,
844
844
  http as http2,
845
- getAddress as getAddress2,
845
+ getAddress as getAddress4,
846
846
  isAddressEqual as isAddressEqual2,
847
847
  encodeFunctionData as encodeFunctionData2,
848
848
  defineChain
@@ -1347,7 +1347,7 @@ import {
1347
1347
  } from "@rhinestone/module-sdk";
1348
1348
  import { toSafeSmartAccount } from "permissionless/accounts";
1349
1349
  import {
1350
- getAddress,
1350
+ getAddress as getAddress2,
1351
1351
  fromHex,
1352
1352
  toHex
1353
1353
  } from "viem";
@@ -1373,6 +1373,145 @@ var POOL_MODULE_ADDRESSES = [
1373
1373
  OWNABLE_VALIDATOR
1374
1374
  ];
1375
1375
 
1376
+ // src/utils/safe-signature.ts
1377
+ import { SMART_SESSIONS_ADDRESS } from "@rhinestone/module-sdk";
1378
+ import {
1379
+ concat,
1380
+ getAddress
1381
+ } from "viem";
1382
+ var EMPTY_DATA = "0x";
1383
+ var SIGNATURE_LENGTH_BYTES = 65;
1384
+ function safeSigStaticPart(sig, dynamicOffset) {
1385
+ if (sig.isContractSignature) {
1386
+ return `${sig.signer.slice(2).padStart(64, "0")}${dynamicOffset ?? ""}00`;
1387
+ }
1388
+ return sig.data.slice(2);
1389
+ }
1390
+ function safeSigDynamicPart(sig) {
1391
+ if (!sig.isContractSignature) return "";
1392
+ const dynamicPartLength = (sig.data.slice(2).length / 2).toString(16).padStart(64, "0");
1393
+ return `${dynamicPartLength}${sig.data.slice(2)}`;
1394
+ }
1395
+ function buildSafeSignatureBytes(signatures) {
1396
+ const sorted = [...signatures].sort(
1397
+ (left, right) => left.signer.toLowerCase().localeCompare(right.signer.toLowerCase())
1398
+ );
1399
+ let signatureBytes = EMPTY_DATA.slice(2);
1400
+ let dynamicBytes = "";
1401
+ for (const signature of sorted) {
1402
+ if (signature.isContractSignature) {
1403
+ const dynamicPartPosition = (sorted.length * SIGNATURE_LENGTH_BYTES + dynamicBytes.length / 2).toString(16).padStart(64, "0");
1404
+ signatureBytes += safeSigStaticPart(signature, dynamicPartPosition);
1405
+ dynamicBytes += safeSigDynamicPart(signature);
1406
+ } else {
1407
+ signatureBytes += signature.data.slice(2);
1408
+ }
1409
+ }
1410
+ return `0x${signatureBytes}${dynamicBytes}`;
1411
+ }
1412
+ function wrapNestedSafeOwnerSignature(parentSafe, rawSignature, validator) {
1413
+ const normalizedParent = getAddress(parentSafe);
1414
+ const normalizedValidator = getAddress(validator);
1415
+ const inner = rawSignature.toLowerCase().startsWith(normalizedValidator.toLowerCase()) ? `0x${rawSignature.slice(42)}` : rawSignature;
1416
+ const safeSignature = {
1417
+ signer: normalizedParent,
1418
+ data: inner,
1419
+ isContractSignature: true
1420
+ };
1421
+ return concat([
1422
+ normalizedValidator,
1423
+ buildSafeSignatureBytes([safeSignature])
1424
+ ]);
1425
+ }
1426
+ function buildMultiChainSessionTypedData(params) {
1427
+ const smartSession = params.smartSessionAddress ?? SMART_SESSIONS_ADDRESS;
1428
+ return {
1429
+ domain: {
1430
+ name: "SmartSession",
1431
+ version: "1"
1432
+ },
1433
+ types: {
1434
+ PolicyData: [
1435
+ { name: "policy", type: "address" },
1436
+ { name: "initData", type: "bytes" }
1437
+ ],
1438
+ ActionData: [
1439
+ { name: "actionTargetSelector", type: "bytes4" },
1440
+ { name: "actionTarget", type: "address" },
1441
+ { name: "actionPolicies", type: "PolicyData[]" }
1442
+ ],
1443
+ ERC7739Context: [
1444
+ { name: "appDomainSeparator", type: "bytes32" },
1445
+ { name: "contentName", type: "string[]" }
1446
+ ],
1447
+ ERC7739Data: [
1448
+ { name: "allowedERC7739Content", type: "ERC7739Context[]" },
1449
+ { name: "erc1271Policies", type: "PolicyData[]" }
1450
+ ],
1451
+ SignedPermissions: [
1452
+ { name: "permitGenericPolicy", type: "bool" },
1453
+ { name: "permitAdminAccess", type: "bool" },
1454
+ { name: "ignoreSecurityAttestations", type: "bool" },
1455
+ { name: "permitERC4337Paymaster", type: "bool" },
1456
+ { name: "userOpPolicies", type: "PolicyData[]" },
1457
+ { name: "erc7739Policies", type: "ERC7739Data" },
1458
+ { name: "actions", type: "ActionData[]" }
1459
+ ],
1460
+ SignedSession: [
1461
+ { name: "account", type: "address" },
1462
+ { name: "permissions", type: "SignedPermissions" },
1463
+ { name: "sessionValidator", type: "address" },
1464
+ { name: "sessionValidatorInitData", type: "bytes" },
1465
+ { name: "salt", type: "bytes32" },
1466
+ { name: "smartSession", type: "address" },
1467
+ { name: "nonce", type: "uint256" }
1468
+ ],
1469
+ ChainSession: [
1470
+ { name: "chainId", type: "uint64" },
1471
+ { name: "session", type: "SignedSession" }
1472
+ ],
1473
+ MultiChainSession: [
1474
+ { name: "sessionsAndChainIds", type: "ChainSession[]" }
1475
+ ]
1476
+ },
1477
+ primaryType: "MultiChainSession",
1478
+ message: {
1479
+ sessionsAndChainIds: params.sessions.map((session, index) => ({
1480
+ chainId: BigInt(session.chainId),
1481
+ session: {
1482
+ account: params.childSafeAddress,
1483
+ permissions: {
1484
+ permitGenericPolicy: params.permitGenericPolicy,
1485
+ permitAdminAccess: false,
1486
+ ignoreSecurityAttestations: true,
1487
+ permitERC4337Paymaster: session.permitERC4337Paymaster,
1488
+ userOpPolicies: session.userOpPolicies,
1489
+ erc7739Policies: session.erc7739Policies,
1490
+ actions: session.actions
1491
+ },
1492
+ sessionValidator: session.sessionValidator,
1493
+ sessionValidatorInitData: session.sessionValidatorInitData,
1494
+ salt: session.salt,
1495
+ smartSession,
1496
+ nonce: params.sessionNonces[index]
1497
+ }
1498
+ }))
1499
+ }
1500
+ };
1501
+ }
1502
+ async function signMultiChainSessionTypedData(walletClient, typedData) {
1503
+ if (!walletClient.account) {
1504
+ throw new Error("Wallet not connected. Please connect your wallet first.");
1505
+ }
1506
+ return walletClient.signTypedData({
1507
+ account: walletClient.account,
1508
+ domain: typedData.domain,
1509
+ types: typedData.types,
1510
+ primaryType: typedData.primaryType,
1511
+ message: typedData.message
1512
+ });
1513
+ }
1514
+
1376
1515
  // src/utils/safe-account.ts
1377
1516
  var SAFE_7579_ADDRESS2 = "0x7579EE8307284F293B1927136486880611F20002";
1378
1517
  var ERC7579_LAUNCHPAD_ADDRESS2 = "0x7579011aB74c46090561ea277Ba79D510c6C00ff";
@@ -1382,7 +1521,7 @@ var getSafeAccount = async (config) => {
1382
1521
  if (!safeOwnerAddress) {
1383
1522
  throw new Error("Safe owner address is required");
1384
1523
  }
1385
- const formattedOwnerAddress = getAddress(safeOwnerAddress);
1524
+ const formattedOwnerAddress = getAddress2(safeOwnerAddress);
1386
1525
  const ownableValidator = getOwnableValidator({
1387
1526
  owners: [formattedOwnerAddress],
1388
1527
  threshold: 1
@@ -1434,12 +1573,12 @@ var isSafeDeployed = async (address, publicClient) => {
1434
1573
  }
1435
1574
  };
1436
1575
  var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) => {
1437
- const normalizedUser = getAddress(userAddress);
1438
- const normalizedSafe = getAddress(safeAddress);
1576
+ const normalizedUser = getAddress2(userAddress);
1577
+ const normalizedSafe = getAddress2(safeAddress);
1439
1578
  const validatorAddresses = Array.from(
1440
1579
  /* @__PURE__ */ new Set([
1441
- getAddress(OWNABLE_VALIDATOR),
1442
- getAddress(OWNABLE_VALIDATOR_ADDRESS)
1580
+ getAddress2(OWNABLE_VALIDATOR),
1581
+ getAddress2(OWNABLE_VALIDATOR_ADDRESS)
1443
1582
  ])
1444
1583
  );
1445
1584
  for (const validatorAddress of validatorAddresses) {
@@ -1450,7 +1589,7 @@ var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) =>
1450
1589
  functionName: "getOwners",
1451
1590
  args: [normalizedSafe]
1452
1591
  });
1453
- if (owners.some((owner) => getAddress(owner) === normalizedUser)) {
1592
+ if (owners.some((owner) => getAddress2(owner) === normalizedUser)) {
1454
1593
  return true;
1455
1594
  }
1456
1595
  } catch {
@@ -1537,10 +1676,22 @@ var deploySafeAccount = async (config) => {
1537
1676
  }
1538
1677
  };
1539
1678
  var signSessionKey = async (config, sessions, allPublicClients, signingParams) => {
1540
- const { owner, publicClient } = config;
1679
+ const { owner, publicClient, safeOwnerAddress } = config;
1541
1680
  if (!owner || !owner.account) {
1542
1681
  throw new Error("Wallet not connected. Please connect your wallet first.");
1543
1682
  }
1683
+ const ownerAccountType = await getAccountType(
1684
+ safeOwnerAddress,
1685
+ publicClient
1686
+ );
1687
+ if (ownerAccountType === "Safe") {
1688
+ return signNestedOwnerSessionKey(
1689
+ config,
1690
+ sessions,
1691
+ allPublicClients,
1692
+ signingParams
1693
+ );
1694
+ }
1544
1695
  const safeAccount = await getSafeAccount(config);
1545
1696
  const account = getAccount({
1546
1697
  address: safeAccount.address,
@@ -1579,6 +1730,194 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
1579
1730
  sessionNonces
1580
1731
  };
1581
1732
  };
1733
+ async function signNestedOwnerSessionKey(config, sessions, allPublicClients, signingParams) {
1734
+ const { owner, publicClient, safeOwnerAddress } = config;
1735
+ const derivedChild = (await getSafeAccount(config)).address;
1736
+ const childSafeAddress = getAddress2(
1737
+ config.childSafeAddress ?? derivedChild
1738
+ );
1739
+ const account = getAccount({
1740
+ address: childSafeAddress,
1741
+ type: "safe"
1742
+ });
1743
+ const clients = allPublicClients || [publicClient];
1744
+ const sessionNonces = await Promise.all(
1745
+ sessions.map((session) => {
1746
+ const sessionChainId = Number(session.chainId);
1747
+ const client = clients.find((c) => c.chain?.id === sessionChainId) || publicClient;
1748
+ return getSessionNonce({
1749
+ client,
1750
+ account,
1751
+ permissionId: getPermissionId({
1752
+ session
1753
+ })
1754
+ });
1755
+ })
1756
+ );
1757
+ const permitGenericPolicy = signingParams?.permitGenericPolicy ?? true;
1758
+ const typedData = buildMultiChainSessionTypedData({
1759
+ childSafeAddress,
1760
+ sessions,
1761
+ sessionNonces,
1762
+ permitGenericPolicy
1763
+ });
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
+ }
1770
+ const rawSignature = await signMultiChainSessionTypedData(owner, typedData);
1771
+ const signature = wrapNestedSafeOwnerSignature(
1772
+ safeOwnerAddress,
1773
+ rawSignature,
1774
+ sessionValidator
1775
+ );
1776
+ return {
1777
+ signature,
1778
+ sessionNonces
1779
+ };
1780
+ }
1781
+
1782
+ // src/utils/nested-safe-deposit.ts
1783
+ import {
1784
+ getAddress as getAddress3
1785
+ } from "viem";
1786
+ var NESTED_SAFE_DEPOSIT_TIMEOUT_MS = 20 * 60 * 1e3;
1787
+ var NESTED_SAFE_DEPOSIT_POLL_MS = 1e4;
1788
+ var NESTED_SAFE_RESUME_WINDOW_MS = 24 * 60 * 60 * 1e3;
1789
+ var SAFE_TX_SERVICE_NETWORK = {
1790
+ 1: "eth",
1791
+ 42161: "arb1",
1792
+ 8453: "base",
1793
+ 10: "oeth",
1794
+ 59144: "linea",
1795
+ 146: "sonic",
1796
+ 9745: "plasma"
1797
+ };
1798
+ function safeTxServiceNetworkName(chainId) {
1799
+ return SAFE_TX_SERVICE_NETWORK[chainId];
1800
+ }
1801
+ function safeTxServiceNetworkNameOrThrow(chainId) {
1802
+ const networkName = safeTxServiceNetworkName(chainId);
1803
+ if (!networkName) {
1804
+ throw new Error(
1805
+ `Chain ${chainId} has no Safe Transaction Service. A nested Safe deposit cannot be tracked there.`
1806
+ );
1807
+ }
1808
+ return networkName;
1809
+ }
1810
+ async function assertParentSafeDeployedOnChain(parentSafe, publicClient, chainId) {
1811
+ const code = await publicClient.getCode({ address: getAddress3(parentSafe) });
1812
+ if (!code || code === "0x") {
1813
+ throw new Error(
1814
+ `Parent Safe ${parentSafe} has no code on chain ${chainId}. Choose a chain where the Safe is deployed.`
1815
+ );
1816
+ }
1817
+ }
1818
+ function sameAddress(left, right) {
1819
+ if (!left || !right) return false;
1820
+ try {
1821
+ return getAddress3(left) === getAddress3(right);
1822
+ } catch {
1823
+ return false;
1824
+ }
1825
+ }
1826
+ function transferMatches(transaction, params) {
1827
+ if (!sameAddress(transaction.to, params.tokenAddress)) return false;
1828
+ if (transaction.isSuccessful === false) return false;
1829
+ const decoded = transaction.dataDecoded;
1830
+ if (decoded?.method?.toLowerCase() !== "transfer") return false;
1831
+ const parameters = decoded.parameters;
1832
+ if (!parameters) return false;
1833
+ const destination = parameters.find(
1834
+ (p) => (p.name === "to" || p.name === "dst" || p.name === "_to") && p.type === "address"
1835
+ );
1836
+ if (!sameAddress(destination?.value, params.childSafe)) return false;
1837
+ if (params.amount === void 0) return true;
1838
+ const valueParam = parameters.find(
1839
+ (p) => (p.name === "value" || p.name === "amount" || p.name === "_value" || p.name === "wad") && p.type.startsWith("uint")
1840
+ );
1841
+ if (!valueParam) return false;
1842
+ try {
1843
+ return BigInt(valueParam.value) === params.amount;
1844
+ } catch {
1845
+ return false;
1846
+ }
1847
+ }
1848
+ function isWithinWindow(transaction, since) {
1849
+ if (!since) return true;
1850
+ const stamp = transaction.executionDate ?? transaction.submissionDate;
1851
+ if (!stamp) return false;
1852
+ const at = Date.parse(stamp);
1853
+ return Number.isFinite(at) && at >= since.getTime();
1854
+ }
1855
+ async function findSafeTransferByHash(params) {
1856
+ const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1857
+ const url = `https://api.safe.global/tx-service/${networkName}/api/v2/multisig-transactions/${params.safeTxHash}/`;
1858
+ const response = await fetch(url);
1859
+ if (!response.ok) return null;
1860
+ const transaction = await response.json();
1861
+ if (!transaction.safeTxHash) return null;
1862
+ if (transaction.isSuccessful === false) {
1863
+ throw new Error(
1864
+ `Safe transaction ${params.safeTxHash} on chain ${params.chainId} reverted on-chain. No deposit was registered.`
1865
+ );
1866
+ }
1867
+ return {
1868
+ safeTxHash: transaction.safeTxHash,
1869
+ transactionHash: transaction.transactionHash ?? null,
1870
+ isExecuted: transaction.isExecuted === true && !!transaction.transactionHash
1871
+ };
1872
+ }
1873
+ async function findSafeTransferProposal(params) {
1874
+ const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1875
+ const url = `https://api.safe.global/tx-service/${networkName}/api/v2/safes/${getAddress3(
1876
+ params.parentSafe
1877
+ )}/multisig-transactions/?ordering=-nonce`;
1878
+ const response = await fetch(url);
1879
+ if (!response.ok) return null;
1880
+ const body = await response.json();
1881
+ const match = (body.results ?? []).find(
1882
+ (transaction) => !!transaction.safeTxHash && isWithinWindow(transaction, params.since) && transferMatches(transaction, {
1883
+ childSafe: params.childSafe,
1884
+ tokenAddress: params.tokenAddress,
1885
+ amount: params.amount
1886
+ })
1887
+ );
1888
+ if (!match) return null;
1889
+ return {
1890
+ safeTxHash: match.safeTxHash,
1891
+ transactionHash: match.transactionHash ?? null,
1892
+ isExecuted: match.isExecuted === true && !!match.transactionHash
1893
+ };
1894
+ }
1895
+ async function waitForSafeTransferExecution(params) {
1896
+ safeTxServiceNetworkNameOrThrow(params.chainId);
1897
+ const timeoutMs = params.timeoutMs ?? NESTED_SAFE_DEPOSIT_TIMEOUT_MS;
1898
+ const pollMs = params.pollMs ?? NESTED_SAFE_DEPOSIT_POLL_MS;
1899
+ const started = Date.now();
1900
+ do {
1901
+ const proposal = params.safeTxHash ? await findSafeTransferByHash({
1902
+ chainId: params.chainId,
1903
+ safeTxHash: params.safeTxHash
1904
+ }) : await findSafeTransferProposal({
1905
+ parentSafe: params.parentSafe,
1906
+ childSafe: params.childSafe,
1907
+ chainId: params.chainId,
1908
+ tokenAddress: params.tokenAddress,
1909
+ amount: params.amount,
1910
+ since: params.since
1911
+ });
1912
+ if (proposal?.isExecuted && proposal.transactionHash) {
1913
+ return proposal.transactionHash;
1914
+ }
1915
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
1916
+ } while (Date.now() - started < timeoutMs);
1917
+ throw new Error(
1918
+ `Timed out waiting for Safe transfer from parent ${params.parentSafe} to child ${params.childSafe} on chain ${params.chainId} for token ${params.tokenAddress} amount ${params.amount.toString()}${params.safeTxHash ? ` (safeTxHash ${params.safeTxHash})` : ""}. Call sendDeposit again once co-signers have executed the proposal; it resumes that transfer instead of proposing another.`
1919
+ );
1920
+ }
1582
1921
 
1583
1922
  // src/utils/strategy.ts
1584
1923
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
@@ -2246,7 +2585,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2246
2585
  }
2247
2586
  this.httpClient.setAuthToken(session.accessToken);
2248
2587
  this.authenticatedUserId = session.userId ?? "bearer-session";
2249
- this.sessionEoa = session.eoa ? getAddress2(session.eoa) : null;
2588
+ this.sessionEoa = session.eoa ? getAddress4(session.eoa) : null;
2250
2589
  this.sessionChannel = session.channel;
2251
2590
  this.isPredeployed = false;
2252
2591
  this.predeployedResolved = false;
@@ -2295,19 +2634,28 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2295
2634
  this.isPredeployed = loginResponse.predeployed || false;
2296
2635
  this.predeployedResolved = true;
2297
2636
  this.connectedSmartWallet = loginResponse.smartWallet || null;
2298
- this.sessionEoa = getAddress2(params.message.address);
2637
+ this.sessionEoa = getAddress4(params.message.address);
2299
2638
  this.sessionChannel = void 0;
2300
2639
  return loginResponse;
2301
2640
  }
2302
- /**
2303
- * Warn that a legacy method is deprecated in favor of sendDeposit.
2304
- * Predeployed wallets no longer require deploySafe / createSessionKey.
2305
- */
2641
+ /** Warn that a deprecated compatibility method was called. */
2306
2642
  warnDeprecatedOnboardingMethod(methodName) {
2307
2643
  console.warn(
2308
2644
  `[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer sendDeposit() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
2309
2645
  );
2310
2646
  }
2647
+ /**
2648
+ * Warn only a pool wallet, which sendDeposit onboards on its own. A contract
2649
+ * owner is never predeployed and reaches these methods through sendDeposit,
2650
+ * so warning unconditionally tells that caller to use what it just called.
2651
+ * Call after authentication, once `isPredeployed` is resolved.
2652
+ */
2653
+ warnPredeployedOnboardingMethod(methodName) {
2654
+ if (!this.isPredeployed) return;
2655
+ console.warn(
2656
+ `[ZyfaiSDK] ${methodName}() is not needed for a predeployed wallet \u2014 sendDeposit() deploys the Safe and enables the agent session on first deposit.`
2657
+ );
2658
+ }
2311
2659
  /**
2312
2660
  * Authenticate user with SIWE (Sign-In with Ethereum) & JWT token
2313
2661
  * This is required for accessing user-specific endpoints like session-keys/config
@@ -2324,7 +2672,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2324
2672
  return;
2325
2673
  }
2326
2674
  const walletClient = this.getWalletClient();
2327
- const userAddress = getAddress2(walletClient.account.address);
2675
+ const userAddress = getAddress4(walletClient.account.address);
2328
2676
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
2329
2677
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
2330
2678
  let uri;
@@ -2889,6 +3237,46 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2889
3237
  * from the user record before allowing a transfer to an undeployed pool Safe.
2890
3238
  * @private
2891
3239
  */
3240
+ /**
3241
+ * Deploy the child Zyfai Safe and session for a nested (contract) owner.
3242
+ * @private
3243
+ */
3244
+ async ensureNestedOwnerReadyForDeposit(userAddress, chainId, strategy) {
3245
+ if (this.isPredeployed) return;
3246
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3247
+ const ownerType = await getAccountType(
3248
+ userAddress,
3249
+ chainConfig.publicClient
3250
+ );
3251
+ if (ownerType !== "Safe") return;
3252
+ await assertParentSafeDeployedOnChain(
3253
+ userAddress,
3254
+ chainConfig.publicClient,
3255
+ chainId
3256
+ );
3257
+ 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
+ );
3265
+ if (!childDeployed) {
3266
+ await this.deploySafe(userAddress, chainId, strategy, true);
3267
+ return;
3268
+ }
3269
+ 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
+ }
3278
+ }
3279
+ }
2892
3280
  async hydrateSessionWallet() {
2893
3281
  if (this.predeployedResolved || !this.sessionEoa) return;
2894
3282
  const me = await this.httpClient.get(ENDPOINTS.USER_ME);
@@ -2973,9 +3361,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2973
3361
  /**
2974
3362
  * Deploy Safe Smart Wallet for a user
2975
3363
  *
2976
- * @deprecated Prefer {@link ZyfaiSDK.sendDeposit}. Predeployed Safes and session keys are
2977
- * managed automatically on first deposit. This method remains available for
2978
- * legacy flows.
3364
+ * Not needed for a predeployed (pool) wallet: {@link ZyfaiSDK.sendDeposit} deploys the Safe and
3365
+ * enables the agent session on first deposit. Required for an owner that is not predeployed —
3366
+ * a contract owner such as a nested Safe, or a legacy self-deployed wallet — where `sendDeposit`
3367
+ * calls this method internally.
2979
3368
  *
2980
3369
  * @see {@link ZyfaiSDK.sendDeposit}
2981
3370
  *
@@ -2989,16 +3378,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2989
3378
  *
2990
3379
  * @example
2991
3380
  * ```typescript
2992
- * // Preferred: sendDeposit handles predeployed wallet onboarding
3381
+ * // Preferred: sendDeposit handles onboarding for every owner type
2993
3382
  * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
2994
3383
  * await sdk.waitForDepositCredit(sent.registration.id, 8453);
2995
3384
  *
2996
- * // Legacy: deploy with default conservative strategy
3385
+ * // Explicit: deploy with default conservative strategy
2997
3386
  * await sdk.deploySafe(userAddress, 8453);
2998
3387
  * ```
2999
3388
  */
3000
3389
  async deploySafe(userAddress, chainId, strategy, createSessionKey) {
3001
- this.warnDeprecatedOnboardingMethod("deploySafe");
3002
3390
  try {
3003
3391
  if (!userAddress) {
3004
3392
  throw new Error("User address is required");
@@ -3007,6 +3395,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3007
3395
  throw new Error(`Unsupported chain ID: ${chainId}`);
3008
3396
  }
3009
3397
  await this.authenticateUser();
3398
+ this.warnPredeployedOnboardingMethod("deploySafe");
3010
3399
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
3011
3400
  const predeployedAddress = await this.getSafeAddressFor(
3012
3401
  userAddress,
@@ -3108,18 +3497,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3108
3497
  };
3109
3498
  } catch (error) {
3110
3499
  console.error("Safe deployment failed:", error);
3111
- throw new Error(
3112
- `Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
3113
- );
3500
+ throw new Error(`Safe deployment failed: ${error.message}`);
3114
3501
  }
3115
3502
  }
3116
3503
  /**
3117
3504
  * Create session key with auto-fetched configuration from Zyfai API
3118
3505
  * This is the simplified method that automatically fetches session configuration
3119
3506
  *
3120
- * @deprecated Prefer {@link ZyfaiSDK.sendDeposit}. Predeployed wallets already have the
3121
- * agent session enabled; session activation is handled after first deposit.
3122
- * This method remains available for legacy flows.
3507
+ * Not needed for a predeployed (pool) wallet: its agent session is already enabled on-chain and
3508
+ * {@link ZyfaiSDK.sendDeposit} records it after the first deposit. Required for an owner that is
3509
+ * not predeployed — a contract owner such as a nested Safe, or a legacy self-deployed wallet —
3510
+ * where `sendDeposit` calls this method internally.
3123
3511
  *
3124
3512
  * @see {@link ZyfaiSDK.sendDeposit}
3125
3513
  *
@@ -3131,18 +3519,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3131
3519
  *
3132
3520
  * @example
3133
3521
  * ```typescript
3134
- * // Preferred: sendDeposit handles session onboarding for predeployed wallets
3522
+ * // Preferred: sendDeposit handles session onboarding for every owner type
3135
3523
  * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
3136
3524
  * await sdk.waitForDepositCredit(sent.registration.id, 8453);
3137
3525
  *
3138
- * // Legacy:
3526
+ * // Explicit:
3139
3527
  * const result = await sdk.createSessionKey(userAddress, 8453);
3140
3528
  * ```
3141
3529
  */
3142
3530
  async createSessionKey(userAddress, chainId) {
3143
- this.warnDeprecatedOnboardingMethod("createSessionKey");
3144
3531
  try {
3145
3532
  await this.authenticateUser();
3533
+ this.warnPredeployedOnboardingMethod("createSessionKey");
3146
3534
  if (!this.authenticatedUserId) {
3147
3535
  throw new Error(
3148
3536
  "User ID not available. Please ensure authentication completed successfully."
@@ -3187,6 +3575,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3187
3575
  userAddress,
3188
3576
  chainConfig.publicClient
3189
3577
  );
3578
+ if (accountType === "Safe") {
3579
+ await this.assertOwnerSafeOnSessionChains(
3580
+ userAddress,
3581
+ sessions
3582
+ );
3583
+ }
3190
3584
  const signingParams = {
3191
3585
  permitGenericPolicy,
3192
3586
  ignoreSecurityAttestations: accountType === "Safe"
@@ -3214,7 +3608,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3214
3608
  };
3215
3609
  } catch (error) {
3216
3610
  throw new Error(
3217
- `Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
3611
+ `Failed to create session key: ${error.message}`
3218
3612
  );
3219
3613
  }
3220
3614
  }
@@ -3222,6 +3616,35 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3222
3616
  * Internal method to sign session key
3223
3617
  * @private
3224
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.
3628
+ * @private
3629
+ */
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
+ }
3225
3648
  async signSessionKey(userAddress, chainId, sessions, signingParams) {
3226
3649
  try {
3227
3650
  if (!userAddress) {
@@ -3235,14 +3658,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3235
3658
  }
3236
3659
  const walletClient = this.getWalletClient();
3237
3660
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3238
- const accountType = await getAccountType(
3661
+ await this.hydrateSessionWallet();
3662
+ const childSafeAddress = await this.getSafeAddressFor(
3239
3663
  userAddress,
3240
- chainConfig.publicClient
3664
+ chainId
3241
3665
  );
3242
- if (accountType !== "EOA") {
3243
- throw new Error(
3244
- `Invalid account type for ${userAddress}. Must be an EOA.`
3245
- );
3666
+ if (!childSafeAddress) {
3667
+ throw new Error("Child smart wallet address is not available");
3246
3668
  }
3247
3669
  const sessionChainIds = [
3248
3670
  ...new Set(sessions.map((s) => Number(s.chainId)))
@@ -3252,6 +3674,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3252
3674
  {
3253
3675
  owner: walletClient,
3254
3676
  safeOwnerAddress: userAddress,
3677
+ childSafeAddress,
3255
3678
  chain: chainConfig.chain,
3256
3679
  publicClient: chainConfig.publicClient
3257
3680
  },
@@ -3743,6 +4166,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3743
4166
  throw new Error("Smart wallet address is not available");
3744
4167
  }
3745
4168
  const amountBigInt = BigInt(amount);
4169
+ const ownerType = await getAccountType(
4170
+ userAddress,
4171
+ chainConfig.publicClient
4172
+ );
4173
+ if (ownerType !== "EOA" && ownerType !== "Safe") {
4174
+ throw new Error(
4175
+ `Could not resolve the account type of ${userAddress} on chain ${chainId}: it is neither an EOA nor a Safe, or the RPC read failed. No deposit was sent.`
4176
+ );
4177
+ }
3746
4178
  const [isDeployed, currentSafeBalance] = await Promise.all([
3747
4179
  isSafeDeployed(safeAddress, chainConfig.publicClient),
3748
4180
  minRequired !== void 0 ? chainConfig.publicClient.readContract({
@@ -3754,7 +4186,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3754
4186
  this.prepareFirstDeposit(strategy)
3755
4187
  ]).then(([deployed, balance]) => [deployed, balance]);
3756
4188
  if (!isDeployed) {
3757
- if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
4189
+ if (ownerType === "Safe" && !this.isPredeployed) {
4190
+ await assertParentSafeDeployedOnChain(
4191
+ userAddress,
4192
+ chainConfig.publicClient,
4193
+ chainId
4194
+ );
4195
+ await this.ensureNestedOwnerReadyForDeposit(
4196
+ userAddress,
4197
+ chainId,
4198
+ strategy
4199
+ );
4200
+ } else if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
3758
4201
  throw new Error(
3759
4202
  `Safe not available for ${userAddress} on chain ${chainId}.`
3760
4203
  );
@@ -3777,16 +4220,74 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3777
4220
  );
3778
4221
  }
3779
4222
  }
4223
+ if (ownerType === "Safe" && isDeployed) {
4224
+ await assertParentSafeDeployedOnChain(
4225
+ userAddress,
4226
+ chainConfig.publicClient,
4227
+ chainId
4228
+ );
4229
+ await this.ensureNestedOwnerReadyForDeposit(
4230
+ userAddress,
4231
+ chainId,
4232
+ strategy
4233
+ );
4234
+ }
3780
4235
  if (allowPermit && this.isPredeployed && this.isConnectedUser(userAddress)) {
3781
4236
  const sponsored = await this.sendFirstPermitDeposit({
3782
- owner: getAddress2(userAddress),
4237
+ owner: getAddress4(userAddress),
3783
4238
  safe: safeAddress,
3784
4239
  chainId,
3785
- token: getAddress2(token),
4240
+ token: getAddress4(token),
3786
4241
  amount: amountBigInt
3787
4242
  });
3788
4243
  if (sponsored) return sponsored;
3789
4244
  }
4245
+ if (ownerType === "Safe") {
4246
+ const since = new Date(Date.now() - NESTED_SAFE_RESUME_WINDOW_MS);
4247
+ const inFlight = await findSafeTransferProposal({
4248
+ parentSafe: userAddress,
4249
+ childSafe: safeAddress,
4250
+ chainId,
4251
+ tokenAddress: token,
4252
+ amount: amountBigInt,
4253
+ since
4254
+ });
4255
+ let safeTxHash = inFlight?.safeTxHash;
4256
+ if (!inFlight) {
4257
+ const proposed = await walletClient.writeContract({
4258
+ address: token,
4259
+ abi: erc20TransferWriteAbi(assetSymbol),
4260
+ functionName: "transfer",
4261
+ args: [safeAddress, amountBigInt],
4262
+ chain: chainConfig.chain,
4263
+ account: walletClient.account
4264
+ });
4265
+ safeTxHash = (await findSafeTransferByHash({ chainId, safeTxHash: proposed }))?.safeTxHash;
4266
+ }
4267
+ const executedHash = inFlight?.isExecuted && inFlight.transactionHash ? inFlight.transactionHash : await waitForSafeTransferExecution({
4268
+ parentSafe: userAddress,
4269
+ childSafe: safeAddress,
4270
+ chainId,
4271
+ tokenAddress: token,
4272
+ amount: amountBigInt,
4273
+ safeTxHash,
4274
+ since
4275
+ });
4276
+ const registration2 = await this.registerDeposit(
4277
+ chainId,
4278
+ executedHash,
4279
+ amount,
4280
+ token
4281
+ );
4282
+ return {
4283
+ success: true,
4284
+ txHash: executedHash,
4285
+ smartWallet: safeAddress,
4286
+ amount: amountBigInt.toString(),
4287
+ route: "direct",
4288
+ registration: registration2
4289
+ };
4290
+ }
3790
4291
  const txHash = await walletClient.writeContract({
3791
4292
  address: token,
3792
4293
  abi: erc20TransferWriteAbi(assetSymbol),
@@ -3839,7 +4340,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3839
4340
  * ```
3840
4341
  */
3841
4342
  async getFirstPermitDepositStatus(userAddress) {
3842
- if (!this.sessionEoa || !isAddressEqual2(getAddress2(userAddress), this.sessionEoa)) {
4343
+ if (!this.sessionEoa || !isAddressEqual2(getAddress4(userAddress), this.sessionEoa)) {
3843
4344
  throw new Error("userAddress does not match authenticated session EOA");
3844
4345
  }
3845
4346
  return (await this.getFirstPermitDepositAvailability()).intent;
@@ -4524,7 +5025,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4524
5025
  if (!userAddress) {
4525
5026
  throw new Error("A user address is required");
4526
5027
  }
4527
- const owner = getAddress2(userAddress);
5028
+ const owner = getAddress4(userAddress);
4528
5029
  const chainId = 8453;
4529
5030
  await this.hydrateSessionWallet();
4530
5031
  const safe = await this.getSafeAddressFor(owner, chainId);
@@ -4546,7 +5047,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4546
5047
  ]).catch(() => {
4547
5048
  throw new Error(`Safe ${safe} is not deployed on Base`);
4548
5049
  });
4549
- if (threshold !== 1n || !owners.some((o) => getAddress2(o) === owner)) {
5050
+ if (threshold !== 1n || !owners.some((o) => getAddress4(o) === owner)) {
4550
5051
  throw new Error(
4551
5052
  `${owner} cannot execute Safe ${safe} alone (not an owner, or threshold above 1)`
4552
5053
  );
@@ -4635,7 +5136,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4635
5136
  if (!userAddress) {
4636
5137
  throw new Error("A user address is required");
4637
5138
  }
4638
- if (this.sessionEoa && getAddress2(userAddress) !== this.sessionEoa) {
5139
+ if (this.sessionEoa && getAddress4(userAddress) !== this.sessionEoa) {
4639
5140
  throw new Error("userAddress does not match authenticated session EOA");
4640
5141
  }
4641
5142
  }
@@ -4781,7 +5282,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4781
5282
  */
4782
5283
  async prepareDeposit(params) {
4783
5284
  const { userAddress, chainId, amount, asset } = params;
4784
- if (this.sessionEoa && getAddress2(userAddress) !== this.sessionEoa) {
5285
+ if (this.sessionEoa && getAddress4(userAddress) !== this.sessionEoa) {
4785
5286
  throw new Error("userAddress does not match authenticated session EOA");
4786
5287
  }
4787
5288
  const setup = await this.ensureDepositProfileForPrepare({
@@ -7378,7 +7879,7 @@ function hashV1SessionEnable(chainSessions) {
7378
7879
 
7379
7880
  // src/utils/userop-verification.ts
7380
7881
  import {
7381
- concat,
7882
+ concat as concat2,
7382
7883
  decodeAbiParameters,
7383
7884
  decodeFunctionData,
7384
7885
  encodeAbiParameters,
@@ -7448,8 +7949,8 @@ function parseUserOperationJson(json) {
7448
7949
  }
7449
7950
  var uint128 = (value) => numberToHex(value, { size: 16 });
7450
7951
  function hashUserOperationV07(userOp, chainId, entryPoint = ENTRY_POINT_V07_ADDRESS) {
7451
- const initCode = userOp.factory ? concat([userOp.factory, userOp.factoryData ?? "0x"]) : "0x";
7452
- const paymasterAndData = userOp.paymaster ? concat([
7952
+ const initCode = userOp.factory ? concat2([userOp.factory, userOp.factoryData ?? "0x"]) : "0x";
7953
+ const paymasterAndData = userOp.paymaster ? concat2([
7453
7954
  userOp.paymaster,
7454
7955
  uint128(userOp.paymasterVerificationGasLimit ?? 0n),
7455
7956
  uint128(userOp.paymasterPostOpGasLimit ?? 0n),
@@ -7471,9 +7972,9 @@ function hashUserOperationV07(userOp, chainId, entryPoint = ENTRY_POINT_V07_ADDR
7471
7972
  userOp.nonce,
7472
7973
  keccak256(initCode),
7473
7974
  keccak256(userOp.callData),
7474
- concat([uint128(userOp.verificationGasLimit), uint128(userOp.callGasLimit)]),
7975
+ concat2([uint128(userOp.verificationGasLimit), uint128(userOp.callGasLimit)]),
7475
7976
  userOp.preVerificationGas,
7476
- concat([uint128(userOp.maxPriorityFeePerGas), uint128(userOp.maxFeePerGas)]),
7977
+ concat2([uint128(userOp.maxPriorityFeePerGas), uint128(userOp.maxFeePerGas)]),
7477
7978
  keccak256(paymasterAndData)
7478
7979
  ]
7479
7980
  );
@@ -7685,6 +8186,385 @@ function createBankrProvider(config) {
7685
8186
  };
7686
8187
  return provider;
7687
8188
  }
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
+ }
7688
8568
  export {
7689
8569
  ALLOWED_HISTORY_DAYS,
7690
8570
  API_ENDPOINT,
@@ -7717,6 +8597,7 @@ export {
7717
8597
  ZyfaiSDK,
7718
8598
  buildV1ChainSessions,
7719
8599
  createBankrProvider,
8600
+ createSafeOwnerProvider,
7720
8601
  decodeUserOperationCalls,
7721
8602
  getChainConfig,
7722
8603
  getDataApiBaseUrl,